Revert `org-agenda-dim-blocked-tasks' and `org-agenda-inhibit-startup' to their previ...
[org-mode.git] / lisp / org.el
blob2fb5b2f9fe50eec81eefc7815c30fe943d9122c1
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function orgtbl-mode "org-table" (&optional arg))
126 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
127 (declare-function org-beamer-mode "ox-beamer" ())
128 (declare-function org-table-edit-field "org-table" (arg))
129 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :version "24.4"
351 :package-version '(Org . "8.0")
352 :type
353 '(set :greedy t
354 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
355 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
356 (const :tag " crypt: Encryption of subtrees" org-crypt)
357 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
358 (const :tag " docview: Links to doc-view buffers" org-docview)
359 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
360 (const :tag " id: Global IDs for identifying entries" org-id)
361 (const :tag " info: Links to Info nodes" org-info)
362 (const :tag " habit: Track your consistency with habits" org-habit)
363 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
364 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
365 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
366 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
367 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
368 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
369 (const :tag " mouse: Additional mouse support" org-mouse)
371 (const :tag "C vm: Links to VM folders/messages" org-vm)
372 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
373 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
374 (const :tag "C mew: Links to Mew folders/messages" org-mew)
375 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
376 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
377 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
378 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
379 (const :tag "C collector: Collect properties into tables" org-collector)
380 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
381 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
382 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
383 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
384 (const :tag "C eval: Include command output as text" org-eval)
385 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
386 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
387 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
388 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
389 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
391 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
393 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
394 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
395 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
396 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
397 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
398 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
399 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
400 (const :tag "C mtags: Support for muse-like tags" org-mtags)
401 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
402 (const :tag "C registry: A registry for Org-mode links" org-registry)
403 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
404 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
405 (const :tag "C secretary: Team management with org-mode" org-secretary)
406 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
407 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
408 (const :tag "C track: Keep up with Org-mode development" org-track)
409 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
410 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
411 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
413 (defvar org-export-registered-backends) ; From ox.el
414 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
415 (defcustom org-export-backends '(ascii html icalendar latex)
416 "List of export back-ends that should be always available.
418 If a description starts with <C>, the file is not part of Emacs
419 and loading it will require that you have downloaded and properly
420 installed the Org mode distribution.
422 Unlike to `org-modules', libraries in this list will not be
423 loaded along with Org, but only once the export framework is
424 needed.
426 This variable needs to be set before org.el is loaded. If you
427 need to make a change while Emacs is running, use the customize
428 interface or run the following code, where VALUE stands for the
429 new value of the variable, after updating it:
431 \(progn
432 \(setq org-export-registered-backends
433 \(org-remove-if-not
434 \(lambda (backend)
435 \(or (memq backend val)
436 \(catch 'parentp
437 \(mapc
438 \(lambda (b)
439 \(and (org-export-derived-backend-p b (car backend))
440 \(throw 'parentp t)))
441 val)
442 nil)))
443 org-export-registered-backends))
444 \(let ((new-list (mapcar 'car org-export-registered-backends)))
445 \(dolist (backend val)
446 \(cond
447 \((not (load (format \"ox-%s\" backend) t t))
448 \(message \"Problems while trying to load export back-end `%s'\"
449 backend))
450 \((not (memq backend new-list)) (push backend new-list))))
451 \(set-default var new-list)))
453 Adding a back-end to this list will also pull the back-end it
454 depends on, if any."
455 :group 'org
456 :group 'org-export
457 :version "24.4"
458 :package-version '(Org . "8.0")
459 :initialize 'custom-initialize-set
460 :set (lambda (var val)
461 (if (not (featurep 'ox)) (set-default var val)
462 ;; Any back-end not required anymore (not present in VAL and not
463 ;; a parent of any back-end in the new value) is removed from the
464 ;; list of registered back-ends.
465 (setq org-export-registered-backends
466 (org-remove-if-not
467 (lambda (backend)
468 (or (memq backend val)
469 (catch 'parentp
470 (mapc
471 (lambda (b)
472 (and (org-export-derived-backend-p b (car backend))
473 (throw 'parentp t)))
474 val)
475 nil)))
476 org-export-registered-backends))
477 ;; Now build NEW-LIST of both new back-ends and required
478 ;; parents.
479 (let ((new-list (mapcar 'car org-export-registered-backends)))
480 (dolist (backend val)
481 (cond
482 ((not (load (format "ox-%s" backend) t t))
483 (message "Problems while trying to load export back-end `%s'"
484 backend))
485 ((not (memq backend new-list)) (push backend new-list))))
486 ;; Set VAR to that list with fixed dependencies.
487 (set-default var new-list))))
488 :type '(set :greedy t
489 (const :tag " ascii Export buffer to ASCII format" ascii)
490 (const :tag " beamer Export buffer to Beamer presentation" beamer)
491 (const :tag " html Export buffer to HTML format" html)
492 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
493 (const :tag " latex Export buffer to LaTeX format" latex)
494 (const :tag " man Export buffer to MAN format" man)
495 (const :tag " md Export buffer to Markdown format" md)
496 (const :tag " odt Export buffer to ODT format" odt)
497 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
498 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
499 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
502 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
504 (eval-after-load 'ox
505 '(mapc
506 (lambda (backend)
507 (condition-case nil (require (intern (format "ox-%s" backend)))
508 (error (message "Problems while trying to load export back-end `%s'"
509 backend))))
510 org-export-backends))
512 (defcustom org-support-shift-select nil
513 "Non-nil means make shift-cursor commands select text when possible.
515 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
516 start selecting a region, or enlarge regions started in this way.
517 In Org-mode, in special contexts, these same keys are used for
518 other purposes, important enough to compete with shift selection.
519 Org tries to balance these needs by supporting `shift-select-mode'
520 outside these special contexts, under control of this variable.
522 The default of this variable is nil, to avoid confusing behavior. Shifted
523 cursor keys will then execute Org commands in the following contexts:
524 - on a headline, changing TODO state (left/right) and priority (up/down)
525 - on a time stamp, changing the time
526 - in a plain list item, changing the bullet type
527 - in a property definition line, switching between allowed values
528 - in the BEGIN line of a clock table (changing the time block).
529 Outside these contexts, the commands will throw an error.
531 When this variable is t and the cursor is not in a special
532 context, Org-mode will support shift-selection for making and
533 enlarging regions. To make this more effective, the bullet
534 cycling will no longer happen anywhere in an item line, but only
535 if the cursor is exactly on the bullet.
537 If you set this variable to the symbol `always', then the keys
538 will not be special in headlines, property lines, and item lines,
539 to make shift selection work there as well. If this is what you
540 want, you can use the following alternative commands: `C-c C-t'
541 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
542 can be used to switch TODO sets, `C-c -' to cycle item bullet
543 types, and properties can be edited by hand or in column view.
545 However, when the cursor is on a timestamp, shift-cursor commands
546 will still edit the time stamp - this is just too good to give up.
548 XEmacs user should have this variable set to nil, because
549 `shift-select-mode' is in Emacs 23 or later only."
550 :group 'org
551 :type '(choice
552 (const :tag "Never" nil)
553 (const :tag "When outside special context" t)
554 (const :tag "Everywhere except timestamps" always)))
556 (defcustom org-loop-over-headlines-in-active-region nil
557 "Shall some commands act upon headlines in the active region?
559 When set to `t', some commands will be performed in all headlines
560 within the active region.
562 When set to `start-level', some commands will be performed in all
563 headlines within the active region, provided that these headlines
564 are of the same level than the first one.
566 When set to a string, those commands will be performed on the
567 matching headlines within the active region. Such string must be
568 a tags/property/todo match as it is used in the agenda tags view.
570 The list of commands is: `org-schedule', `org-deadline',
571 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
572 `org-archive-to-archive-sibling'. The archiving commands skip
573 already archived entries."
574 :type '(choice (const :tag "Don't loop" nil)
575 (const :tag "All headlines in active region" t)
576 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
577 (string :tag "Tags/Property/Todo matcher"))
578 :version "24.1"
579 :group 'org-todo
580 :group 'org-archive)
582 (defgroup org-startup nil
583 "Options concerning startup of Org-mode."
584 :tag "Org Startup"
585 :group 'org)
587 (defcustom org-startup-folded t
588 "Non-nil means entering Org-mode will switch to OVERVIEW.
589 This can also be configured on a per-file basis by adding one of
590 the following lines anywhere in the buffer:
592 #+STARTUP: fold (or `overview', this is equivalent)
593 #+STARTUP: nofold (or `showall', this is equivalent)
594 #+STARTUP: content
595 #+STARTUP: showeverything
597 By default, this option is ignored when Org opens agenda files
598 for the first time. If you want the agenda to honor the startup
599 option, set `org-agenda-inhibit-startup' to nil."
600 :group 'org-startup
601 :type '(choice
602 (const :tag "nofold: show all" nil)
603 (const :tag "fold: overview" t)
604 (const :tag "content: all headlines" content)
605 (const :tag "show everything, even drawers" showeverything)))
607 (defcustom org-startup-truncated t
608 "Non-nil means entering Org-mode will set `truncate-lines'.
609 This is useful since some lines containing links can be very long and
610 uninteresting. Also tables look terrible when wrapped."
611 :group 'org-startup
612 :type 'boolean)
614 (defcustom org-startup-indented nil
615 "Non-nil means turn on `org-indent-mode' on startup.
616 This can also be configured on a per-file basis by adding one of
617 the following lines anywhere in the buffer:
619 #+STARTUP: indent
620 #+STARTUP: noindent"
621 :group 'org-structure
622 :type '(choice
623 (const :tag "Not" nil)
624 (const :tag "Globally (slow on startup in large files)" t)))
626 (defcustom org-use-sub-superscripts t
627 "Non-nil means interpret \"_\" and \"^\" for display.
628 When this option is turned on, you can use TeX-like syntax for sub- and
629 superscripts. Several characters after \"_\" or \"^\" will be
630 considered as a single item - so grouping with {} is normally not
631 needed. For example, the following things will be parsed as single
632 sub- or superscripts.
634 10^24 or 10^tau several digits will be considered 1 item.
635 10^-12 or 10^-tau a leading sign with digits or a word
636 x^2-y^3 will be read as x^2 - y^3, because items are
637 terminated by almost any nonword/nondigit char.
638 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
640 Still, ambiguity is possible - so when in doubt use {} to enclose
641 the sub/superscript. If you set this variable to the symbol
642 `{}', the braces are *required* in order to trigger
643 interpretations as sub/superscript. This can be helpful in
644 documents that need \"_\" frequently in plain text."
645 :group 'org-startup
646 :version "24.1"
647 :type '(choice
648 (const :tag "Always interpret" t)
649 (const :tag "Only with braces" {})
650 (const :tag "Never interpret" nil)))
652 (defcustom org-startup-with-beamer-mode nil
653 "Non-nil means turn on `org-beamer-mode' on startup.
654 This can also be configured on a per-file basis by adding one of
655 the following lines anywhere in the buffer:
657 #+STARTUP: beamer"
658 :group 'org-startup
659 :version "24.1"
660 :type 'boolean)
662 (defcustom org-startup-align-all-tables nil
663 "Non-nil means align all tables when visiting a file.
664 This is useful when the column width in tables is forced with <N> cookies
665 in table fields. Such tables will look correct only after the first re-align.
666 This can also be configured on a per-file basis by adding one of
667 the following lines anywhere in the buffer:
668 #+STARTUP: align
669 #+STARTUP: noalign"
670 :group 'org-startup
671 :type 'boolean)
673 (defcustom org-startup-with-inline-images nil
674 "Non-nil means show inline images when loading a new Org file.
675 This can also be configured on a per-file basis by adding one of
676 the following lines anywhere in the buffer:
677 #+STARTUP: inlineimages
678 #+STARTUP: noinlineimages"
679 :group 'org-startup
680 :version "24.1"
681 :type 'boolean)
683 (defcustom org-startup-with-latex-preview nil
684 "Non-nil means preview LaTeX fragments when loading a new Org file.
686 This can also be configured on a per-file basis by adding one of
687 the followinglines anywhere in the buffer:
688 #+STARTUP: latexpreview
689 #+STARTUP: nolatexpreview"
690 :group 'org-startup
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type 'boolean)
695 (defcustom org-insert-mode-line-in-empty-file nil
696 "Non-nil means insert the first line setting Org-mode in empty files.
697 When the function `org-mode' is called interactively in an empty file, this
698 normally means that the file name does not automatically trigger Org-mode.
699 To ensure that the file will always be in Org-mode in the future, a
700 line enforcing Org-mode will be inserted into the buffer, if this option
701 has been set."
702 :group 'org-startup
703 :type 'boolean)
705 (defcustom org-replace-disputed-keys nil
706 "Non-nil means use alternative key bindings for some keys.
707 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
708 These keys are also used by other packages like shift-selection-mode'
709 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
710 If you want to use Org-mode together with one of these other modes,
711 or more generally if you would like to move some Org-mode commands to
712 other keys, set this variable and configure the keys with the variable
713 `org-disputed-keys'.
715 This option is only relevant at load-time of Org-mode, and must be set
716 *before* org.el is loaded. Changing it requires a restart of Emacs to
717 become effective."
718 :group 'org-startup
719 :type 'boolean)
721 (defcustom org-use-extra-keys nil
722 "Non-nil means use extra key sequence definitions for certain commands.
723 This happens automatically if you run XEmacs or if `window-system'
724 is nil. This variable lets you do the same manually. You must
725 set it before loading org.
727 Example: on Carbon Emacs 22 running graphically, with an external
728 keyboard on a Powerbook, the default way of setting M-left might
729 not work for either Alt or ESC. Setting this variable will make
730 it work for ESC."
731 :group 'org-startup
732 :type 'boolean)
734 (if (fboundp 'defvaralias)
735 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
737 (defcustom org-disputed-keys
738 '(([(shift up)] . [(meta p)])
739 ([(shift down)] . [(meta n)])
740 ([(shift left)] . [(meta -)])
741 ([(shift right)] . [(meta +)])
742 ([(control shift right)] . [(meta shift +)])
743 ([(control shift left)] . [(meta shift -)]))
744 "Keys for which Org-mode and other modes compete.
745 This is an alist, cars are the default keys, second element specifies
746 the alternative to use when `org-replace-disputed-keys' is t.
748 Keys can be specified in any syntax supported by `define-key'.
749 The value of this option takes effect only at Org-mode's startup,
750 therefore you'll have to restart Emacs to apply it after changing."
751 :group 'org-startup
752 :type 'alist)
754 (defun org-key (key)
755 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
756 Or return the original if not disputed.
757 Also apply the translations defined in `org-xemacs-key-equivalents'."
758 (when org-replace-disputed-keys
759 (let* ((nkey (key-description key))
760 (x (org-find-if (lambda (x)
761 (equal (key-description (car x)) nkey))
762 org-disputed-keys)))
763 (setq key (if x (cdr x) key))))
764 (when (featurep 'xemacs)
765 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
766 key)
768 (defun org-find-if (predicate seq)
769 (catch 'exit
770 (while seq
771 (if (funcall predicate (car seq))
772 (throw 'exit (car seq))
773 (pop seq)))))
775 (defun org-defkey (keymap key def)
776 "Define a key, possibly translated, as returned by `org-key'."
777 (define-key keymap (org-key key) def))
779 (defcustom org-ellipsis nil
780 "The ellipsis to use in the Org-mode outline.
781 When nil, just use the standard three dots. When a string, use that instead,
782 When a face, use the standard 3 dots, but with the specified face.
783 The change affects only Org-mode (which will then use its own display table).
784 Changing this requires executing `M-x org-mode' in a buffer to become
785 effective."
786 :group 'org-startup
787 :type '(choice (const :tag "Default" nil)
788 (face :tag "Face" :value org-warning)
789 (string :tag "String" :value "...#")))
791 (defvar org-display-table nil
792 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
794 (defgroup org-keywords nil
795 "Keywords in Org-mode."
796 :tag "Org Keywords"
797 :group 'org)
799 (defcustom org-deadline-string "DEADLINE:"
800 "String to mark deadline entries.
801 A deadline is this string, followed by a time stamp. Should be a word,
802 terminated by a colon. You can insert a schedule keyword and
803 a timestamp with \\[org-deadline].
804 Changes become only effective after restarting Emacs."
805 :group 'org-keywords
806 :type 'string)
808 (defcustom org-scheduled-string "SCHEDULED:"
809 "String to mark scheduled TODO entries.
810 A schedule is this string, followed by a time stamp. Should be a word,
811 terminated by a colon. You can insert a schedule keyword and
812 a timestamp with \\[org-schedule].
813 Changes become only effective after restarting Emacs."
814 :group 'org-keywords
815 :type 'string)
817 (defcustom org-closed-string "CLOSED:"
818 "String used as the prefix for timestamps logging closing a TODO entry."
819 :group 'org-keywords
820 :type 'string)
822 (defcustom org-clock-string "CLOCK:"
823 "String used as prefix for timestamps clocking work hours on an item."
824 :group 'org-keywords
825 :type 'string)
827 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
828 org-scheduled-string "\\|"
829 org-deadline-string "\\|"
830 org-closed-string "\\|"
831 org-clock-string "\\)")
832 "Matches a line with planning or clock info.")
834 (defcustom org-comment-string "COMMENT"
835 "Entries starting with this keyword will never be exported.
836 An entry can be toggled between COMMENT and normal with
837 \\[org-toggle-comment].
838 Changes become only effective after restarting Emacs."
839 :group 'org-keywords
840 :type 'string)
842 (defcustom org-quote-string "QUOTE"
843 "Entries starting with this keyword will be exported in fixed-width font.
844 Quoting applies only to the text in the entry following the headline, and does
845 not extend beyond the next headline, even if that is lower level.
846 An entry can be toggled between QUOTE and normal with
847 \\[org-toggle-fixed-width-section]."
848 :group 'org-keywords
849 :type 'string)
851 (defconst org-repeat-re
852 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
853 "Regular expression for specifying repeated events.
854 After a match, group 1 contains the repeat expression.")
856 (defgroup org-structure nil
857 "Options concerning the general structure of Org-mode files."
858 :tag "Org Structure"
859 :group 'org)
861 (defgroup org-reveal-location nil
862 "Options about how to make context of a location visible."
863 :tag "Org Reveal Location"
864 :group 'org-structure)
866 (defconst org-context-choice
867 '(choice
868 (const :tag "Always" t)
869 (const :tag "Never" nil)
870 (repeat :greedy t :tag "Individual contexts"
871 (cons
872 (choice :tag "Context"
873 (const agenda)
874 (const org-goto)
875 (const occur-tree)
876 (const tags-tree)
877 (const link-search)
878 (const mark-goto)
879 (const bookmark-jump)
880 (const isearch)
881 (const default))
882 (boolean))))
883 "Contexts for the reveal options.")
885 (defcustom org-show-hierarchy-above '((default . t))
886 "Non-nil means show full hierarchy when revealing a location.
887 Org-mode often shows locations in an org-mode file which might have
888 been invisible before. When this is set, the hierarchy of headings
889 above the exposed location is shown.
890 Turning this off for example for sparse trees makes them very compact.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. Valid contexts are
893 agenda when exposing an entry from the agenda
894 org-goto when using the command `org-goto' on key C-c C-j
895 occur-tree when using the command `org-occur' on key C-c /
896 tags-tree when constructing a sparse tree based on tags matches
897 link-search when exposing search matches associated with a link
898 mark-goto when exposing the jump goal of a mark
899 bookmark-jump when exposing a bookmark location
900 isearch when exiting from an incremental search
901 default default for all contexts not set explicitly"
902 :group 'org-reveal-location
903 :type org-context-choice)
905 (defcustom org-show-following-heading '((default . nil))
906 "Non-nil means show following heading when revealing a location.
907 Org-mode often shows locations in an org-mode file which might have
908 been invisible before. When this is set, the heading following the
909 match is shown.
910 Turning this off for example for sparse trees makes them very compact,
911 but makes it harder to edit the location of the match. In such a case,
912 use the command \\[org-reveal] to show more context.
913 Instead of t, this can also be an alist specifying this option for different
914 contexts. See `org-show-hierarchy-above' for valid contexts."
915 :group 'org-reveal-location
916 :type org-context-choice)
918 (defcustom org-show-siblings '((default . nil) (isearch t))
919 "Non-nil means show all sibling heading when revealing a location.
920 Org-mode often shows locations in an org-mode file which might have
921 been invisible before. When this is set, the sibling of the current entry
922 heading are all made visible. If `org-show-hierarchy-above' is t,
923 the same happens on each level of the hierarchy above the current entry.
925 By default this is on for the isearch context, off for all other contexts.
926 Turning this off for example for sparse trees makes them very compact,
927 but makes it harder to edit the location of the match. In such a case,
928 use the command \\[org-reveal] to show more context.
929 Instead of t, this can also be an alist specifying this option for different
930 contexts. See `org-show-hierarchy-above' for valid contexts."
931 :group 'org-reveal-location
932 :type org-context-choice)
934 (defcustom org-show-entry-below '((default . nil))
935 "Non-nil means show the entry below a headline when revealing a location.
936 Org-mode often shows locations in an org-mode file which might have
937 been invisible before. When this is set, the text below the headline that is
938 exposed is also shown.
940 By default this is off for all contexts.
941 Instead of t, this can also be an alist specifying this option for different
942 contexts. See `org-show-hierarchy-above' for valid contexts."
943 :group 'org-reveal-location
944 :type org-context-choice)
946 (defcustom org-indirect-buffer-display 'other-window
947 "How should indirect tree buffers be displayed?
948 This applies to indirect buffers created with the commands
949 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
950 Valid values are:
951 current-window Display in the current window
952 other-window Just display in another window.
953 dedicated-frame Create one new frame, and re-use it each time.
954 new-frame Make a new frame each time. Note that in this case
955 previously-made indirect buffers are kept, and you need to
956 kill these buffers yourself."
957 :group 'org-structure
958 :group 'org-agenda-windows
959 :type '(choice
960 (const :tag "In current window" current-window)
961 (const :tag "In current frame, other window" other-window)
962 (const :tag "Each time a new frame" new-frame)
963 (const :tag "One dedicated frame" dedicated-frame)))
965 (defcustom org-use-speed-commands nil
966 "Non-nil means activate single letter commands at beginning of a headline.
967 This may also be a function to test for appropriate locations where speed
968 commands should be active."
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Never" nil)
972 (const :tag "At beginning of headline stars" t)
973 (function)))
975 (defcustom org-speed-commands-user nil
976 "Alist of additional speed commands.
977 This list will be checked before `org-speed-commands-default'
978 when the variable `org-use-speed-commands' is non-nil
979 and when the cursor is at the beginning of a headline.
980 The car if each entry is a string with a single letter, which must
981 be assigned to `self-insert-command' in the global map.
982 The cdr is either a command to be called interactively, a function
983 to be called, or a form to be evaluated.
984 An entry that is just a list with a single string will be interpreted
985 as a descriptive headline that will be added when listing the speed
986 commands in the Help buffer using the `?' speed command."
987 :group 'org-structure
988 :type '(repeat :value ("k" . ignore)
989 (choice :value ("k" . ignore)
990 (list :tag "Descriptive Headline" (string :tag "Headline"))
991 (cons :tag "Letter and Command"
992 (string :tag "Command letter")
993 (choice
994 (function)
995 (sexp))))))
997 (defgroup org-cycle nil
998 "Options concerning visibility cycling in Org-mode."
999 :tag "Org Cycle"
1000 :group 'org-structure)
1002 (defcustom org-cycle-skip-children-state-if-no-children t
1003 "Non-nil means skip CHILDREN state in entries that don't have any."
1004 :group 'org-cycle
1005 :type 'boolean)
1007 (defcustom org-cycle-max-level nil
1008 "Maximum level which should still be subject to visibility cycling.
1009 Levels higher than this will, for cycling, be treated as text, not a headline.
1010 When `org-odd-levels-only' is set, a value of N in this variable actually
1011 means 2N-1 stars as the limiting headline.
1012 When nil, cycle all levels.
1013 Note that the limiting level of cycling is also influenced by
1014 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1015 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1016 than its value."
1017 :group 'org-cycle
1018 :type '(choice
1019 (const :tag "No limit" nil)
1020 (integer :tag "Maximum level")))
1022 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1023 "Names of drawers. Drawers are not opened by cycling on the headline above.
1024 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1025 this:
1026 :DRAWERNAME:
1027 .....
1028 :END:
1029 The drawer \"PROPERTIES\" is special for capturing properties through
1030 the property API.
1032 Drawers can be defined on the per-file basis with a line like:
1034 #+DRAWERS: HIDDEN STATE PROPERTIES"
1035 :group 'org-structure
1036 :group 'org-cycle
1037 :type '(repeat (string :tag "Drawer Name")))
1039 (defcustom org-hide-block-startup nil
1040 "Non-nil means entering Org-mode will fold all blocks.
1041 This can also be set in on a per-file basis with
1043 #+STARTUP: hideblocks
1044 #+STARTUP: showblocks"
1045 :group 'org-startup
1046 :group 'org-cycle
1047 :type 'boolean)
1049 (defcustom org-cycle-global-at-bob nil
1050 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1051 This makes it possible to do global cycling without having to use S-TAB or
1052 \\[universal-argument] TAB. For this special case to work, the first line
1053 of the buffer must not be a headline -- it may be empty or some other text.
1054 When used in this way, `org-cycle-hook' is disabled temporarily to make
1055 sure the cursor stays at the beginning of the buffer. When this option is
1056 nil, don't do anything special at the beginning of the buffer."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-level-after-item/entry-creation t
1061 "Non-nil means cycle entry level or item indentation in new empty entries.
1063 When the cursor is at the end of an empty headline, i.e., with only stars
1064 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1065 and then all possible ancestor states, before returning to the original state.
1066 This makes data entry extremely fast: M-RET to create a new headline,
1067 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1069 When the cursor is at the end of an empty plain list item, one TAB will
1070 make it a subitem, two or more tabs will back up to make this an item
1071 higher up in the item hierarchy."
1072 :group 'org-cycle
1073 :type 'boolean)
1075 (defcustom org-cycle-emulate-tab t
1076 "Where should `org-cycle' emulate TAB.
1077 nil Never
1078 white Only in completely white lines
1079 whitestart Only at the beginning of lines, before the first non-white char
1080 t Everywhere except in headlines
1081 exc-hl-bol Everywhere except at the start of a headline
1082 If TAB is used in a place where it does not emulate TAB, the current subtree
1083 visibility is cycled."
1084 :group 'org-cycle
1085 :type '(choice (const :tag "Never" nil)
1086 (const :tag "Only in completely white lines" white)
1087 (const :tag "Before first char in a line" whitestart)
1088 (const :tag "Everywhere except in headlines" t)
1089 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1092 (defcustom org-cycle-separator-lines 2
1093 "Number of empty lines needed to keep an empty line between collapsed trees.
1094 If you leave an empty line between the end of a subtree and the following
1095 headline, this empty line is hidden when the subtree is folded.
1096 Org-mode will leave (exactly) one empty line visible if the number of
1097 empty lines is equal or larger to the number given in this variable.
1098 So the default 2 means at least 2 empty lines after the end of a subtree
1099 are needed to produce free space between a collapsed subtree and the
1100 following headline.
1102 If the number is negative, and the number of empty lines is at least -N,
1103 all empty lines are shown.
1105 Special case: when 0, never leave empty lines in collapsed view."
1106 :group 'org-cycle
1107 :type 'integer)
1108 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1110 (defcustom org-pre-cycle-hook nil
1111 "Hook that is run before visibility cycling is happening.
1112 The function(s) in this hook must accept a single argument which indicates
1113 the new state that will be set right after running this hook. The
1114 argument is a symbol. Before a global state change, it can have the values
1115 `overview', `content', or `all'. Before a local state change, it can have
1116 the values `folded', `children', or `subtree'."
1117 :group 'org-cycle
1118 :type 'hook)
1120 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1121 org-cycle-hide-drawers
1122 org-cycle-hide-inline-tasks
1123 org-cycle-show-empty-lines
1124 org-optimize-window-after-visibility-change)
1125 "Hook that is run after `org-cycle' has changed the buffer visibility.
1126 The function(s) in this hook must accept a single argument which indicates
1127 the new state that was set by the most recent `org-cycle' command. The
1128 argument is a symbol. After a global state change, it can have the values
1129 `overview', `contents', or `all'. After a local state change, it can have
1130 the values `folded', `children', or `subtree'."
1131 :group 'org-cycle
1132 :type 'hook)
1134 (defgroup org-edit-structure nil
1135 "Options concerning structure editing in Org-mode."
1136 :tag "Org Edit Structure"
1137 :group 'org-structure)
1139 (defcustom org-odd-levels-only nil
1140 "Non-nil means skip even levels and only use odd levels for the outline.
1141 This has the effect that two stars are being added/taken away in
1142 promotion/demotion commands. It also influences how levels are
1143 handled by the exporters.
1144 Changing it requires restart of `font-lock-mode' to become effective
1145 for fontification also in regions already fontified.
1146 You may also set this on a per-file basis by adding one of the following
1147 lines to the buffer:
1149 #+STARTUP: odd
1150 #+STARTUP: oddeven"
1151 :group 'org-edit-structure
1152 :group 'org-appearance
1153 :type 'boolean)
1155 (defcustom org-adapt-indentation t
1156 "Non-nil means adapt indentation to outline node level.
1158 When this variable is set, Org assumes that you write outlines by
1159 indenting text in each node to align with the headline (after the stars).
1160 The following issues are influenced by this variable:
1162 - When this is set and the *entire* text in an entry is indented, the
1163 indentation is increased by one space in a demotion command, and
1164 decreased by one in a promotion command. If any line in the entry
1165 body starts with text at column 0, indentation is not changed at all.
1167 - Property drawers and planning information is inserted indented when
1168 this variable s set. When nil, they will not be indented.
1170 - TAB indents a line relative to context. The lines below a headline
1171 will be indented when this variable is set.
1173 Note that this is all about true indentation, by adding and removing
1174 space characters. See also `org-indent.el' which does level-dependent
1175 indentation in a virtual way, i.e. at display time in Emacs."
1176 :group 'org-edit-structure
1177 :type 'boolean)
1179 (defcustom org-special-ctrl-a/e nil
1180 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1182 When t, `C-a' will bring back the cursor to the beginning of the
1183 headline text, i.e. after the stars and after a possible TODO
1184 keyword. In an item, this will be the position after bullet and
1185 check-box, if any. When the cursor is already at that position,
1186 another `C-a' will bring it to the beginning of the line.
1188 `C-e' will jump to the end of the headline, ignoring the presence
1189 of tags in the headline. A second `C-e' will then jump to the
1190 true end of the line, after any tags. This also means that, when
1191 this variable is non-nil, `C-e' also will never jump beyond the
1192 end of the heading of a folded section, i.e. not after the
1193 ellipses.
1195 When set to the symbol `reversed', the first `C-a' or `C-e' works
1196 normally, going to the true line boundary first. Only a directly
1197 following, identical keypress will bring the cursor to the
1198 special positions.
1200 This may also be a cons cell where the behavior for `C-a' and
1201 `C-e' is set separately."
1202 :group 'org-edit-structure
1203 :type '(choice
1204 (const :tag "off" nil)
1205 (const :tag "on: after stars/bullet and before tags first" t)
1206 (const :tag "reversed: true line boundary first" reversed)
1207 (cons :tag "Set C-a and C-e separately"
1208 (choice :tag "Special C-a"
1209 (const :tag "off" nil)
1210 (const :tag "on: after stars/bullet first" t)
1211 (const :tag "reversed: before stars/bullet first" reversed))
1212 (choice :tag "Special C-e"
1213 (const :tag "off" nil)
1214 (const :tag "on: before tags first" t)
1215 (const :tag "reversed: after tags first" reversed)))))
1216 (if (fboundp 'defvaralias)
1217 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1219 (defcustom org-special-ctrl-k nil
1220 "Non-nil means `C-k' will behave specially in headlines.
1221 When nil, `C-k' will call the default `kill-line' command.
1222 When t, the following will happen while the cursor is in the headline:
1224 - When the cursor is at the beginning of a headline, kill the entire
1225 line and possible the folded subtree below the line.
1226 - When in the middle of the headline text, kill the headline up to the tags.
1227 - When after the headline text, kill the tags."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-ctrl-k-protect-subtree nil
1232 "Non-nil means, do not delete a hidden subtree with C-k.
1233 When set to the symbol `error', simply throw an error when C-k is
1234 used to kill (part-of) a headline that has hidden text behind it.
1235 Any other non-nil value will result in a query to the user, if it is
1236 OK to kill that hidden subtree. When nil, kill without remorse."
1237 :group 'org-edit-structure
1238 :version "24.1"
1239 :type '(choice
1240 (const :tag "Do not protect hidden subtrees" nil)
1241 (const :tag "Protect hidden subtrees with a security query" t)
1242 (const :tag "Never kill a hidden subtree with C-k" error)))
1244 (defcustom org-catch-invisible-edits nil
1245 "Check if in invisible region before inserting or deleting a character.
1246 Valid values are:
1248 nil Do not check, so just do invisible edits.
1249 error Throw an error and do nothing.
1250 show Make point visible, and do the requested edit.
1251 show-and-error Make point visible, then throw an error and abort the edit.
1252 smart Make point visible, and do insertion/deletion if it is
1253 adjacent to visible text and the change feels predictable.
1254 Never delete a previously invisible character or add in the
1255 middle or right after an invisible region. Basically, this
1256 allows insertion and backward-delete right before ellipses.
1257 FIXME: maybe in this case we should not even show?"
1258 :group 'org-edit-structure
1259 :version "24.1"
1260 :type '(choice
1261 (const :tag "Do not check" nil)
1262 (const :tag "Throw error when trying to edit" error)
1263 (const :tag "Unhide, but do not do the edit" show-and-error)
1264 (const :tag "Show invisible part and do the edit" show)
1265 (const :tag "Be smart and do the right thing" smart)))
1267 (defcustom org-yank-folded-subtrees t
1268 "Non-nil means when yanking subtrees, fold them.
1269 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1270 it starts with a heading and all other headings in it are either children
1271 or siblings, then fold all the subtrees. However, do this only if no
1272 text after the yank would be swallowed into a folded tree by this action."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-yank-adjusted-subtrees nil
1277 "Non-nil means when yanking subtrees, adjust the level.
1278 With this setting, `org-paste-subtree' is used to insert the subtree, see
1279 this function for details."
1280 :group 'org-edit-structure
1281 :type 'boolean)
1283 (defcustom org-M-RET-may-split-line '((default . t))
1284 "Non-nil means M-RET will split the line at the cursor position.
1285 When nil, it will go to the end of the line before making a
1286 new line.
1287 You may also set this option in a different way for different
1288 contexts. Valid contexts are:
1290 headline when creating a new headline
1291 item when creating a new item
1292 table in a table field
1293 default the value to be used for all contexts not explicitly
1294 customized"
1295 :group 'org-structure
1296 :group 'org-table
1297 :type '(choice
1298 (const :tag "Always" t)
1299 (const :tag "Never" nil)
1300 (repeat :greedy t :tag "Individual contexts"
1301 (cons
1302 (choice :tag "Context"
1303 (const headline)
1304 (const item)
1305 (const table)
1306 (const default))
1307 (boolean)))))
1310 (defcustom org-insert-heading-respect-content nil
1311 "Non-nil means insert new headings after the current subtree.
1312 When nil, the new heading is created directly after the current line.
1313 The commands \\[org-insert-heading-respect-content] and
1314 \\[org-insert-todo-heading-respect-content] turn this variable on
1315 for the duration of the command."
1316 :group 'org-structure
1317 :type 'boolean)
1319 (defcustom org-blank-before-new-entry '((heading . auto)
1320 (plain-list-item . auto))
1321 "Should `org-insert-heading' leave a blank line before new heading/item?
1322 The value is an alist, with `heading' and `plain-list-item' as CAR,
1323 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1324 which case Org will look at the surrounding headings/items and try to
1325 make an intelligent decision whether to insert a blank line or not.
1327 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1328 set, the setting here is ignored and no empty line is inserted, to avoid
1329 breaking the list structure."
1330 :group 'org-edit-structure
1331 :type '(list
1332 (cons (const heading)
1333 (choice (const :tag "Never" nil)
1334 (const :tag "Always" t)
1335 (const :tag "Auto" auto)))
1336 (cons (const plain-list-item)
1337 (choice (const :tag "Never" nil)
1338 (const :tag "Always" t)
1339 (const :tag "Auto" auto)))))
1341 (defcustom org-insert-heading-hook nil
1342 "Hook being run after inserting a new heading."
1343 :group 'org-edit-structure
1344 :type 'hook)
1346 (defcustom org-enable-fixed-width-editor t
1347 "Non-nil means lines starting with \":\" are treated as fixed-width.
1348 This currently only means they are never auto-wrapped.
1349 When nil, such lines will be treated like ordinary lines.
1350 See also the QUOTE keyword."
1351 :group 'org-edit-structure
1352 :type 'boolean)
1354 (defcustom org-goto-auto-isearch t
1355 "Non-nil means typing characters in `org-goto' starts incremental search.
1356 When nil, you can use these keybindings to navigate the buffer:
1358 q Quit the org-goto interface
1359 n Go to the next visible heading
1360 p Go to the previous visible heading
1361 f Go one heading forward on same level
1362 b Go one heading backward on same level
1363 u Go one heading up"
1364 :group 'org-edit-structure
1365 :type 'boolean)
1367 (defgroup org-sparse-trees nil
1368 "Options concerning sparse trees in Org-mode."
1369 :tag "Org Sparse Trees"
1370 :group 'org-structure)
1372 (defcustom org-highlight-sparse-tree-matches t
1373 "Non-nil means highlight all matches that define a sparse tree.
1374 The highlights will automatically disappear the next time the buffer is
1375 changed by an edit command."
1376 :group 'org-sparse-trees
1377 :type 'boolean)
1379 (defcustom org-remove-highlights-with-change t
1380 "Non-nil means any change to the buffer will remove temporary highlights.
1381 Such highlights are created by `org-occur' and `org-clock-display'.
1382 When nil, `C-c C-c needs to be used to get rid of the highlights.
1383 The highlights created by `org-preview-latex-fragment' always need
1384 `C-c C-c' to be removed."
1385 :group 'org-sparse-trees
1386 :group 'org-time
1387 :type 'boolean)
1390 (defcustom org-occur-hook '(org-first-headline-recenter)
1391 "Hook that is run after `org-occur' has constructed a sparse tree.
1392 This can be used to recenter the window to show as much of the structure
1393 as possible."
1394 :group 'org-sparse-trees
1395 :type 'hook)
1397 (defgroup org-imenu-and-speedbar nil
1398 "Options concerning imenu and speedbar in Org-mode."
1399 :tag "Org Imenu and Speedbar"
1400 :group 'org-structure)
1402 (defcustom org-imenu-depth 2
1403 "The maximum level for Imenu access to Org-mode headlines.
1404 This also applied for speedbar access."
1405 :group 'org-imenu-and-speedbar
1406 :type 'integer)
1408 (defgroup org-table nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table"
1411 :group 'org)
1413 (defcustom org-enable-table-editor 'optimized
1414 "Non-nil means lines starting with \"|\" are handled by the table editor.
1415 When nil, such lines will be treated like ordinary lines.
1417 When equal to the symbol `optimized', the table editor will be optimized to
1418 do the following:
1419 - Automatic overwrite mode in front of whitespace in table fields.
1420 This makes the structure of the table stay in tact as long as the edited
1421 field does not exceed the column width.
1422 - Minimize the number of realigns. Normally, the table is aligned each time
1423 TAB or RET are pressed to move to another field. With optimization this
1424 happens only if changes to a field might have changed the column width.
1425 Optimization requires replacing the functions `self-insert-command',
1426 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1427 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1428 very good at guessing when a re-align will be necessary, but you can always
1429 force one with \\[org-ctrl-c-ctrl-c].
1431 If you would like to use the optimized version in Org-mode, but the
1432 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1434 This variable can be used to turn on and off the table editor during a session,
1435 but in order to toggle optimization, a restart is required.
1437 See also the variable `org-table-auto-blank-field'."
1438 :group 'org-table
1439 :type '(choice
1440 (const :tag "off" nil)
1441 (const :tag "on" t)
1442 (const :tag "on, optimized" optimized)))
1444 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1445 (version<= emacs-version "24.1"))
1446 "Non-nil means cluster self-insert commands for undo when possible.
1447 If this is set, then, like in the Emacs command loop, 20 consecutive
1448 characters will be undone together.
1449 This is configurable, because there is some impact on typing performance."
1450 :group 'org-table
1451 :type 'boolean)
1453 (defcustom org-table-tab-recognizes-table.el t
1454 "Non-nil means TAB will automatically notice a table.el table.
1455 When it sees such a table, it moves point into it and - if necessary -
1456 calls `table-recognize-table'."
1457 :group 'org-table-editing
1458 :type 'boolean)
1460 (defgroup org-link nil
1461 "Options concerning links in Org-mode."
1462 :tag "Org Link"
1463 :group 'org)
1465 (defvar org-link-abbrev-alist-local nil
1466 "Buffer-local version of `org-link-abbrev-alist', which see.
1467 The value of this is taken from the #+LINK lines.")
1468 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1470 (defcustom org-link-abbrev-alist nil
1471 "Alist of link abbreviations.
1472 The car of each element is a string, to be replaced at the start of a link.
1473 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1474 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1476 [[linkkey:tag][description]]
1478 The 'linkkey' must be a word word, starting with a letter, followed
1479 by letters, numbers, '-' or '_'.
1481 If REPLACE is a string, the tag will simply be appended to create the link.
1482 If the string contains \"%s\", the tag will be inserted there. If the string
1483 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1484 at that point (see the function `url-hexify-string'). If the string contains
1485 the specifier \"%(my-function)\", then the custom function `my-function' will
1486 be invoked: this function takes the tag as its only argument and must return
1487 a string.
1489 REPLACE may also be a function that will be called with the tag as the
1490 only argument to create the link, which should be returned as a string.
1492 See the manual for examples."
1493 :group 'org-link
1494 :type '(repeat
1495 (cons
1496 (string :tag "Protocol")
1497 (choice
1498 (string :tag "Format")
1499 (function)))))
1501 (defcustom org-descriptive-links t
1502 "Non-nil means Org will display descriptive links.
1503 E.g. [[http://orgmode.org][Org website]] will be displayed as
1504 \"Org Website\", hiding the link itself and just displaying its
1505 description. When set to `nil', Org will display the full links
1506 literally.
1508 You can interactively set the value of this variable by calling
1509 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1510 :group 'org-link
1511 :type 'boolean)
1513 (defcustom org-link-file-path-type 'adaptive
1514 "How the path name in file links should be stored.
1515 Valid values are:
1517 relative Relative to the current directory, i.e. the directory of the file
1518 into which the link is being inserted.
1519 absolute Absolute path, if possible with ~ for home directory.
1520 noabbrev Absolute path, no abbreviation of home directory.
1521 adaptive Use relative path for files in the current directory and sub-
1522 directories of it. For other files, use an absolute path."
1523 :group 'org-link
1524 :type '(choice
1525 (const relative)
1526 (const absolute)
1527 (const noabbrev)
1528 (const adaptive)))
1530 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1531 "Types of links that should be activated in Org-mode files.
1532 This is a list of symbols, each leading to the activation of a certain link
1533 type. In principle, it does not hurt to turn on most link types - there may
1534 be a small gain when turning off unused link types. The types are:
1536 bracket The recommended [[link][description]] or [[link]] links with hiding.
1537 angle Links in angular brackets that may contain whitespace like
1538 <bbdb:Carsten Dominik>.
1539 plain Plain links in normal text, no whitespace, like http://google.com.
1540 radio Text that is matched by a radio target, see manual for details.
1541 tag Tag settings in a headline (link to tag search).
1542 date Time stamps (link to calendar).
1543 footnote Footnote labels.
1545 Changing this variable requires a restart of Emacs to become effective."
1546 :group 'org-link
1547 :type '(set :greedy t
1548 (const :tag "Double bracket links" bracket)
1549 (const :tag "Angular bracket links" angle)
1550 (const :tag "Plain text links" plain)
1551 (const :tag "Radio target matches" radio)
1552 (const :tag "Tags" tag)
1553 (const :tag "Timestamps" date)
1554 (const :tag "Footnotes" footnote)))
1556 (defcustom org-make-link-description-function nil
1557 "Function to use for generating link descriptions from links.
1558 When nil, the link location will be used. This function must take
1559 two parameters: the first one is the link, the second one is the
1560 description generated by `org-insert-link'. The function should
1561 return the description to use."
1562 :group 'org-link
1563 :type 'function)
1565 (defgroup org-link-store nil
1566 "Options concerning storing links in Org-mode."
1567 :tag "Org Store Link"
1568 :group 'org-link)
1570 (defcustom org-url-hexify-p t
1571 "When non-nil, hexify URL when creating a link."
1572 :type 'boolean
1573 :version "24.3"
1574 :group 'org-link-store)
1576 (defcustom org-email-link-description-format "Email %c: %.30s"
1577 "Format of the description part of a link to an email or usenet message.
1578 The following %-escapes will be replaced by corresponding information:
1580 %F full \"From\" field
1581 %f name, taken from \"From\" field, address if no name
1582 %T full \"To\" field
1583 %t first name in \"To\" field, address if no name
1584 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1585 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1586 %s subject
1587 %d date
1588 %m message-id.
1590 You may use normal field width specification between the % and the letter.
1591 This is for example useful to limit the length of the subject.
1593 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1594 :group 'org-link-store
1595 :type 'string)
1597 (defcustom org-from-is-user-regexp
1598 (let (r1 r2)
1599 (when (and user-mail-address (not (string= user-mail-address "")))
1600 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1601 (when (and user-full-name (not (string= user-full-name "")))
1602 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1603 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1604 "Regexp matched against the \"From:\" header of an email or usenet message.
1605 It should match if the message is from the user him/herself."
1606 :group 'org-link-store
1607 :type 'regexp)
1609 (defcustom org-context-in-file-links t
1610 "Non-nil means file links from `org-store-link' contain context.
1611 A search string will be added to the file name with :: as separator and
1612 used to find the context when the link is activated by the command
1613 `org-open-at-point'. When this option is t, the entire active region
1614 will be placed in the search string of the file link. If set to a
1615 positive integer, only the first n lines of context will be stored.
1617 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1618 negates this setting for the duration of the command."
1619 :group 'org-link-store
1620 :type '(choice boolean integer))
1622 (defcustom org-keep-stored-link-after-insertion nil
1623 "Non-nil means keep link in list for entire session.
1625 The command `org-store-link' adds a link pointing to the current
1626 location to an internal list. These links accumulate during a session.
1627 The command `org-insert-link' can be used to insert links into any
1628 Org-mode file (offering completion for all stored links). When this
1629 option is nil, every link which has been inserted once using \\[org-insert-link]
1630 will be removed from the list, to make completing the unused links
1631 more efficient."
1632 :group 'org-link-store
1633 :type 'boolean)
1635 (defgroup org-link-follow nil
1636 "Options concerning following links in Org-mode."
1637 :tag "Org Follow Link"
1638 :group 'org-link)
1640 (defcustom org-link-translation-function nil
1641 "Function to translate links with different syntax to Org syntax.
1642 This can be used to translate links created for example by the Planner
1643 or emacs-wiki packages to Org syntax.
1644 The function must accept two parameters, a TYPE containing the link
1645 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1646 which is everything after the link protocol. It should return a cons
1647 with possibly modified values of type and path.
1648 Org contains a function for this, so if you set this variable to
1649 `org-translate-link-from-planner', you should be able follow many
1650 links created by planner."
1651 :group 'org-link-follow
1652 :type 'function)
1654 (defcustom org-follow-link-hook nil
1655 "Hook that is run after a link has been followed."
1656 :group 'org-link-follow
1657 :type 'hook)
1659 (defcustom org-tab-follows-link nil
1660 "Non-nil means on links TAB will follow the link.
1661 Needs to be set before org.el is loaded.
1662 This really should not be used, it does not make sense, and the
1663 implementation is bad."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-return-follows-link nil
1668 "Non-nil means on links RET will follow the link.
1669 In tables, the special behavior of RET has precedence."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mouse-1-follows-link
1674 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1675 "Non-nil means mouse-1 on a link will follow the link.
1676 A longer mouse click will still set point. Does not work on XEmacs.
1677 Needs to be set before org.el is loaded."
1678 :group 'org-link-follow
1679 :type 'boolean)
1681 (defcustom org-mark-ring-length 4
1682 "Number of different positions to be recorded in the ring.
1683 Changing this requires a restart of Emacs to work correctly."
1684 :group 'org-link-follow
1685 :type 'integer)
1687 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1688 "Non-nil means internal links in Org files must exactly match a headline.
1689 When nil, the link search tries to match a phrase with all words
1690 in the search text."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type '(choice
1694 (const :tag "Use fuzzy text search" nil)
1695 (const :tag "Match only exact headline" t)
1696 (const :tag "Match exact headline or query to create it"
1697 query-to-create)))
1699 (defcustom org-link-frame-setup
1700 '((vm . vm-visit-folder-other-frame)
1701 (vm-imap . vm-visit-imap-folder-other-frame)
1702 (gnus . org-gnus-no-new-news)
1703 (file . find-file-other-window)
1704 (wl . wl-other-frame))
1705 "Setup the frame configuration for following links.
1706 When following a link with Emacs, it may often be useful to display
1707 this link in another window or frame. This variable can be used to
1708 set this up for the different types of links.
1709 For VM, use any of
1710 `vm-visit-folder'
1711 `vm-visit-folder-other-window'
1712 `vm-visit-folder-other-frame'
1713 For Gnus, use any of
1714 `gnus'
1715 `gnus-other-frame'
1716 `org-gnus-no-new-news'
1717 For FILE, use any of
1718 `find-file'
1719 `find-file-other-window'
1720 `find-file-other-frame'
1721 For Wanderlust use any of
1722 `wl'
1723 `wl-other-frame'
1724 For the calendar, use the variable `calendar-setup'.
1725 For BBDB, it is currently only possible to display the matches in
1726 another window."
1727 :group 'org-link-follow
1728 :type '(list
1729 (cons (const vm)
1730 (choice
1731 (const vm-visit-folder)
1732 (const vm-visit-folder-other-window)
1733 (const vm-visit-folder-other-frame)))
1734 (cons (const gnus)
1735 (choice
1736 (const gnus)
1737 (const gnus-other-frame)
1738 (const org-gnus-no-new-news)))
1739 (cons (const file)
1740 (choice
1741 (const find-file)
1742 (const find-file-other-window)
1743 (const find-file-other-frame)))
1744 (cons (const wl)
1745 (choice
1746 (const wl)
1747 (const wl-other-frame)))))
1749 (defcustom org-display-internal-link-with-indirect-buffer nil
1750 "Non-nil means use indirect buffer to display infile links.
1751 Activating internal links (from one location in a file to another location
1752 in the same file) normally just jumps to the location. When the link is
1753 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1754 is displayed in
1755 another window. When this option is set, the other window actually displays
1756 an indirect buffer clone of the current buffer, to avoid any visibility
1757 changes to the current buffer."
1758 :group 'org-link-follow
1759 :type 'boolean)
1761 (defcustom org-open-non-existing-files nil
1762 "Non-nil means `org-open-file' will open non-existing files.
1763 When nil, an error will be generated.
1764 This variable applies only to external applications because they
1765 might choke on non-existing files. If the link is to a file that
1766 will be opened in Emacs, the variable is ignored."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-open-directory-means-index-dot-org nil
1771 "Non-nil means a link to a directory really means to index.org.
1772 When nil, following a directory link will run dired or open a finder/explorer
1773 window on that directory."
1774 :group 'org-link-follow
1775 :type 'boolean)
1777 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1778 "Function and arguments to call for following mailto links.
1779 This is a list with the first element being a Lisp function, and the
1780 remaining elements being arguments to the function. In string arguments,
1781 %a will be replaced by the address, and %s will be replaced by the subject
1782 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1786 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1787 (const :tag "message-mail" (message-mail "%a" "%s"))
1788 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1790 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1791 "Non-nil means ask for confirmation before executing shell links.
1792 Shell links can be dangerous: just think about a link
1794 [[shell:rm -rf ~/*][Google Search]]
1796 This link would show up in your Org-mode document as \"Google Search\",
1797 but really it would remove your entire home directory.
1798 Therefore we advise against setting this variable to nil.
1799 Just change it to `y-or-n-p' if you want to confirm with a
1800 single keystroke rather than having to type \"yes\"."
1801 :group 'org-link-follow
1802 :type '(choice
1803 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1804 (const :tag "with y-or-n (faster)" y-or-n-p)
1805 (const :tag "no confirmation (dangerous)" nil)))
1806 (put 'org-confirm-shell-link-function
1807 'safe-local-variable
1808 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1810 (defcustom org-confirm-shell-link-not-regexp ""
1811 "A regexp to skip confirmation for shell links."
1812 :group 'org-link-follow
1813 :version "24.1"
1814 :type 'regexp)
1816 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1817 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1818 Elisp links can be dangerous: just think about a link
1820 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1822 This link would show up in your Org-mode document as \"Google Search\",
1823 but really it would remove your entire home directory.
1824 Therefore we advise against setting this variable to nil.
1825 Just change it to `y-or-n-p' if you want to confirm with a
1826 single keystroke rather than having to type \"yes\"."
1827 :group 'org-link-follow
1828 :type '(choice
1829 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1830 (const :tag "with y-or-n (faster)" y-or-n-p)
1831 (const :tag "no confirmation (dangerous)" nil)))
1832 (put 'org-confirm-shell-link-function
1833 'safe-local-variable
1834 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1836 (defcustom org-confirm-elisp-link-not-regexp ""
1837 "A regexp to skip confirmation for Elisp links."
1838 :group 'org-link-follow
1839 :version "24.1"
1840 :type 'regexp)
1842 (defconst org-file-apps-defaults-gnu
1843 '((remote . emacs)
1844 (system . mailcap)
1845 (t . mailcap))
1846 "Default file applications on a UNIX or GNU/Linux system.
1847 See `org-file-apps'.")
1849 (defconst org-file-apps-defaults-macosx
1850 '((remote . emacs)
1851 (t . "open %s")
1852 (system . "open %s")
1853 ("ps.gz" . "gv %s")
1854 ("eps.gz" . "gv %s")
1855 ("dvi" . "xdvi %s")
1856 ("fig" . "xfig %s"))
1857 "Default file applications on a MacOS X system.
1858 The system \"open\" is known as a default, but we use X11 applications
1859 for some files for which the OS does not have a good default.
1860 See `org-file-apps'.")
1862 (defconst org-file-apps-defaults-windowsnt
1863 (list
1864 '(remote . emacs)
1865 (cons t
1866 (list (if (featurep 'xemacs)
1867 'mswindows-shell-execute
1868 'w32-shell-execute)
1869 "open" 'file))
1870 (cons 'system
1871 (list (if (featurep 'xemacs)
1872 'mswindows-shell-execute
1873 'w32-shell-execute)
1874 "open" 'file)))
1875 "Default file applications on a Windows NT system.
1876 The system \"open\" is used for most files.
1877 See `org-file-apps'.")
1879 (defcustom org-file-apps
1881 (auto-mode . emacs)
1882 ("\\.mm\\'" . default)
1883 ("\\.x?html?\\'" . default)
1884 ("\\.pdf\\'" . default)
1886 "External applications for opening `file:path' items in a document.
1887 Org-mode uses system defaults for different file types, but
1888 you can use this variable to set the application for a given file
1889 extension. The entries in this list are cons cells where the car identifies
1890 files and the cdr the corresponding command. Possible values for the
1891 file identifier are
1892 \"string\" A string as a file identifier can be interpreted in different
1893 ways, depending on its contents:
1895 - Alphanumeric characters only:
1896 Match links with this file extension.
1897 Example: (\"pdf\" . \"evince %s\")
1898 to open PDFs with evince.
1900 - Regular expression: Match links where the
1901 filename matches the regexp. If you want to
1902 use groups here, use shy groups.
1904 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1905 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1906 to open *.html and *.xhtml with firefox.
1908 - Regular expression which contains (non-shy) groups:
1909 Match links where the whole link, including \"::\", and
1910 anything after that, matches the regexp.
1911 In a custom command string, %1, %2, etc. are replaced with
1912 the parts of the link that were matched by the groups.
1913 For backwards compatibility, if a command string is given
1914 that does not use any of the group matches, this case is
1915 handled identically to the second one (i.e. match against
1916 file name only).
1917 In a custom lisp form, you can access the group matches with
1918 (match-string n link).
1920 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1921 to open [[file:document.pdf::5]] with evince at page 5.
1923 `directory' Matches a directory
1924 `remote' Matches a remote file, accessible through tramp or efs.
1925 Remote files most likely should be visited through Emacs
1926 because external applications cannot handle such paths.
1927 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1928 so all files Emacs knows how to handle. Using this with
1929 command `emacs' will open most files in Emacs. Beware that this
1930 will also open html files inside Emacs, unless you add
1931 (\"html\" . default) to the list as well.
1932 t Default for files not matched by any of the other options.
1933 `system' The system command to open files, like `open' on Windows
1934 and Mac OS X, and mailcap under GNU/Linux. This is the command
1935 that will be selected if you call `C-c C-o' with a double
1936 \\[universal-argument] \\[universal-argument] prefix.
1938 Possible values for the command are:
1939 `emacs' The file will be visited by the current Emacs process.
1940 `default' Use the default application for this file type, which is the
1941 association for t in the list, most likely in the system-specific
1942 part.
1943 This can be used to overrule an unwanted setting in the
1944 system-specific variable.
1945 `system' Use the system command for opening files, like \"open\".
1946 This command is specified by the entry whose car is `system'.
1947 Most likely, the system-specific version of this variable
1948 does define this command, but you can overrule/replace it
1949 here.
1950 string A command to be executed by a shell; %s will be replaced
1951 by the path to the file.
1952 sexp A Lisp form which will be evaluated. The file path will
1953 be available in the Lisp variable `file'.
1954 For more examples, see the system specific constants
1955 `org-file-apps-defaults-macosx'
1956 `org-file-apps-defaults-windowsnt'
1957 `org-file-apps-defaults-gnu'."
1958 :group 'org-link-follow
1959 :type '(repeat
1960 (cons (choice :value ""
1961 (string :tag "Extension")
1962 (const :tag "System command to open files" system)
1963 (const :tag "Default for unrecognized files" t)
1964 (const :tag "Remote file" remote)
1965 (const :tag "Links to a directory" directory)
1966 (const :tag "Any files that have Emacs modes"
1967 auto-mode))
1968 (choice :value ""
1969 (const :tag "Visit with Emacs" emacs)
1970 (const :tag "Use default" default)
1971 (const :tag "Use the system command" system)
1972 (string :tag "Command")
1973 (sexp :tag "Lisp form")))))
1975 (defcustom org-doi-server-url "http://dx.doi.org/"
1976 "The URL of the DOI server."
1977 :type 'string
1978 :version "24.3"
1979 :group 'org-link-follow)
1981 (defgroup org-refile nil
1982 "Options concerning refiling entries in Org-mode."
1983 :tag "Org Refile"
1984 :group 'org)
1986 (defcustom org-directory "~/org"
1987 "Directory with org files.
1988 This is just a default location to look for Org files. There is no need
1989 at all to put your files into this directory. It is only used in the
1990 following situations:
1992 1. When a capture template specifies a target file that is not an
1993 absolute path. The path will then be interpreted relative to
1994 `org-directory'
1995 2. When a capture note is filed away in an interactive way (when exiting the
1996 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1997 with `org-directory' as the default path."
1998 :group 'org-refile
1999 :group 'org-remember
2000 :group 'org-capture
2001 :type 'directory)
2003 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2004 "Default target for storing notes.
2005 Used as a fall back file for org-remember.el and org-capture.el, for
2006 templates that do not specify a target file."
2007 :group 'org-refile
2008 :group 'org-remember
2009 :group 'org-capture
2010 :type '(choice
2011 (const :tag "Default from remember-data-file" nil)
2012 file))
2014 (defcustom org-goto-interface 'outline
2015 "The default interface to be used for `org-goto'.
2016 Allowed values are:
2017 outline The interface shows an outline of the relevant file
2018 and the correct heading is found by moving through
2019 the outline or by searching with incremental search.
2020 outline-path-completion Headlines in the current buffer are offered via
2021 completion. This is the interface also used by
2022 the refile command."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Outline" outline)
2026 (const :tag "Outline-path-completion" outline-path-completion)))
2028 (defcustom org-goto-max-level 5
2029 "Maximum target level when running `org-goto' with refile interface."
2030 :group 'org-refile
2031 :type 'integer)
2033 (defcustom org-reverse-note-order nil
2034 "Non-nil means store new notes at the beginning of a file or entry.
2035 When nil, new notes will be filed to the end of a file or entry.
2036 This can also be a list with cons cells of regular expressions that
2037 are matched against file names, and values."
2038 :group 'org-remember
2039 :group 'org-capture
2040 :group 'org-refile
2041 :type '(choice
2042 (const :tag "Reverse always" t)
2043 (const :tag "Reverse never" nil)
2044 (repeat :tag "By file name regexp"
2045 (cons regexp boolean))))
2047 (defcustom org-log-refile nil
2048 "Information to record when a task is refiled.
2050 Possible values are:
2052 nil Don't add anything
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologrefile
2059 #+STARTUP: logrefile
2060 #+STARTUP: lognoterefile
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords.
2065 When bulk-refiling from the agenda, the value `note' is forbidden and
2066 will temporarily be changed to `time'."
2067 :group 'org-refile
2068 :group 'org-progress
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "No logging" nil)
2072 (const :tag "Record timestamp" time)
2073 (const :tag "Record timestamp with note." note)))
2075 (defcustom org-refile-targets nil
2076 "Targets for refiling entries with \\[org-refile].
2077 This is a list of cons cells. Each cell contains:
2078 - a specification of the files to be considered, either a list of files,
2079 or a symbol whose function or variable value will be used to retrieve
2080 a file name or a list of file names. If you use `org-agenda-files' for
2081 that, all agenda files will be scanned for targets. Nil means consider
2082 headings in the current buffer.
2083 - A specification of how to find candidate refile targets. This may be
2084 any of:
2085 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2086 This tag has to be present in all target headlines, inheritance will
2087 not be considered.
2088 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2089 todo keyword.
2090 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2091 headlines that are refiling targets.
2092 - a cons cell (:level . N). Any headline of level N is considered a target.
2093 Note that, when `org-odd-levels-only' is set, level corresponds to
2094 order in hierarchy, not to the number of stars.
2095 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2099 Each element of this list generates a set of possible targets.
2100 The union of these sets is presented (with completion) to
2101 the user by `org-refile'.
2103 You can set the variable `org-refile-target-verify-function' to a function
2104 to verify each headline found by the simple criteria above.
2106 When this variable is nil, all top-level headlines in the current buffer
2107 are used, equivalent to the value `((nil . (:level . 1))'."
2108 :group 'org-refile
2109 :type '(repeat
2110 (cons
2111 (choice :value org-agenda-files
2112 (const :tag "All agenda files" org-agenda-files)
2113 (const :tag "Current buffer" nil)
2114 (function) (variable) (file))
2115 (choice :tag "Identify target headline by"
2116 (cons :tag "Specific tag" (const :value :tag) (string))
2117 (cons :tag "TODO keyword" (const :value :todo) (string))
2118 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2119 (cons :tag "Level number" (const :value :level) (integer))
2120 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2122 (defcustom org-refile-target-verify-function nil
2123 "Function to verify if the headline at point should be a refile target.
2124 The function will be called without arguments, with point at the
2125 beginning of the headline. It should return t and leave point
2126 where it is if the headline is a valid target for refiling.
2128 If the target should not be selected, the function must return nil.
2129 In addition to this, it may move point to a place from where the search
2130 should be continued. For example, the function may decide that the entire
2131 subtree of the current entry should be excluded and move point to the end
2132 of the subtree."
2133 :group 'org-refile
2134 :type 'function)
2136 (defcustom org-refile-use-cache nil
2137 "Non-nil means cache refile targets to speed up the process.
2138 The cache for a particular file will be updated automatically when
2139 the buffer has been killed, or when any of the marker used for flagging
2140 refile targets no longer points at a live buffer.
2141 If you have added new entries to a buffer that might themselves be targets,
2142 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2143 find that easier, `C-u C-u C-u C-c C-w'."
2144 :group 'org-refile
2145 :version "24.1"
2146 :type 'boolean)
2148 (defcustom org-refile-use-outline-path nil
2149 "Non-nil means provide refile targets as paths.
2150 So a level 3 headline will be available as level1/level2/level3.
2152 When the value is `file', also include the file name (without directory)
2153 into the path. In this case, you can also stop the completion after
2154 the file name, to get entries inserted as top level in the file.
2156 When `full-file-path', include the full file path."
2157 :group 'org-refile
2158 :type '(choice
2159 (const :tag "Not" nil)
2160 (const :tag "Yes" t)
2161 (const :tag "Start with file name" file)
2162 (const :tag "Start with full file path" full-file-path)))
2164 (defcustom org-outline-path-complete-in-steps t
2165 "Non-nil means complete the outline path in hierarchical steps.
2166 When Org-mode uses the refile interface to select an outline path
2167 \(see variable `org-refile-use-outline-path'), the completion of
2168 the path can be done is a single go, or if can be done in steps down
2169 the headline hierarchy. Going in steps is probably the best if you
2170 do not use a special completion package like `ido' or `icicles'.
2171 However, when using these packages, going in one step can be very
2172 fast, while still showing the whole path to the entry."
2173 :group 'org-refile
2174 :type 'boolean)
2176 (defcustom org-refile-allow-creating-parent-nodes nil
2177 "Non-nil means allow to create new nodes as refile targets.
2178 New nodes are then created by adding \"/new node name\" to the completion
2179 of an existing node. When the value of this variable is `confirm',
2180 new node creation must be confirmed by the user (recommended)
2181 When nil, the completion must match an existing entry.
2183 Note that, if the new heading is not seen by the criteria
2184 listed in `org-refile-targets', multiple instances of the same
2185 heading would be created by trying again to file under the new
2186 heading."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Never" nil)
2190 (const :tag "Always" t)
2191 (const :tag "Prompt for confirmation" confirm)))
2193 (defcustom org-refile-active-region-within-subtree nil
2194 "Non-nil means also refile active region within a subtree.
2196 By default `org-refile' doesn't allow refiling regions if they
2197 don't contain a set of subtrees, but it might be convenient to
2198 do so sometimes: in that case, the first line of the region is
2199 converted to a headline before refiling."
2200 :group 'org-refile
2201 :version "24.1"
2202 :type 'boolean)
2204 (defgroup org-todo nil
2205 "Options concerning TODO items in Org-mode."
2206 :tag "Org TODO"
2207 :group 'org)
2209 (defgroup org-progress nil
2210 "Options concerning Progress logging in Org-mode."
2211 :tag "Org Progress"
2212 :group 'org-time)
2214 (defvar org-todo-interpretation-widgets
2215 '((:tag "Sequence (cycling hits every state)" sequence)
2216 (:tag "Type (cycling directly to DONE)" type))
2217 "The available interpretation symbols for customizing `org-todo-keywords'.
2218 Interested libraries should add to this list.")
2220 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2221 "List of TODO entry keyword sequences and their interpretation.
2222 \\<org-mode-map>This is a list of sequences.
2224 Each sequence starts with a symbol, either `sequence' or `type',
2225 indicating if the keywords should be interpreted as a sequence of
2226 action steps, or as different types of TODO items. The first
2227 keywords are states requiring action - these states will select a headline
2228 for inclusion into the global TODO list Org-mode produces. If one of
2229 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2230 signify that no further action is necessary. If \"|\" is not found,
2231 the last keyword is treated as the only DONE state of the sequence.
2233 The command \\[org-todo] cycles an entry through these states, and one
2234 additional state where no keyword is present. For details about this
2235 cycling, see the manual.
2237 TODO keywords and interpretation can also be set on a per-file basis with
2238 the special #+SEQ_TODO and #+TYP_TODO lines.
2240 Each keyword can optionally specify a character for fast state selection
2241 \(in combination with the variable `org-use-fast-todo-selection')
2242 and specifiers for state change logging, using the same syntax that
2243 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2244 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2245 indicates to record a time stamp each time this state is selected.
2247 Each keyword may also specify if a timestamp or a note should be
2248 recorded when entering or leaving the state, by adding additional
2249 characters in the parenthesis after the keyword. This looks like this:
2250 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2251 record only the time of the state change. With X and Y being either
2252 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2253 Y when leaving the state if and only if the *target* state does not
2254 define X. You may omit any of the fast-selection key or X or /Y,
2255 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2257 For backward compatibility, this variable may also be just a list
2258 of keywords. In this case the interpretation (sequence or type) will be
2259 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2260 :group 'org-todo
2261 :group 'org-keywords
2262 :type '(choice
2263 (repeat :tag "Old syntax, just keywords"
2264 (string :tag "Keyword"))
2265 (repeat :tag "New syntax"
2266 (cons
2267 (choice
2268 :tag "Interpretation"
2269 ;;Quick and dirty way to see
2270 ;;`org-todo-interpretations'. This takes the
2271 ;;place of item arguments
2272 :convert-widget
2273 (lambda (widget)
2274 (widget-put widget
2275 :args (mapcar
2276 #'(lambda (x)
2277 (widget-convert
2278 (cons 'const x)))
2279 org-todo-interpretation-widgets))
2280 widget))
2281 (repeat
2282 (string :tag "Keyword"))))))
2284 (defvar org-todo-keywords-1 nil
2285 "All TODO and DONE keywords active in a buffer.")
2286 (make-variable-buffer-local 'org-todo-keywords-1)
2287 (defvar org-todo-keywords-for-agenda nil)
2288 (defvar org-done-keywords-for-agenda nil)
2289 (defvar org-drawers-for-agenda nil)
2290 (defvar org-todo-keyword-alist-for-agenda nil)
2291 (defvar org-tag-alist-for-agenda nil)
2292 (defvar org-agenda-contributing-files nil)
2293 (defvar org-not-done-keywords nil)
2294 (make-variable-buffer-local 'org-not-done-keywords)
2295 (defvar org-done-keywords nil)
2296 (make-variable-buffer-local 'org-done-keywords)
2297 (defvar org-todo-heads nil)
2298 (make-variable-buffer-local 'org-todo-heads)
2299 (defvar org-todo-sets nil)
2300 (make-variable-buffer-local 'org-todo-sets)
2301 (defvar org-todo-log-states nil)
2302 (make-variable-buffer-local 'org-todo-log-states)
2303 (defvar org-todo-kwd-alist nil)
2304 (make-variable-buffer-local 'org-todo-kwd-alist)
2305 (defvar org-todo-key-alist nil)
2306 (make-variable-buffer-local 'org-todo-key-alist)
2307 (defvar org-todo-key-trigger nil)
2308 (make-variable-buffer-local 'org-todo-key-trigger)
2310 (defcustom org-todo-interpretation 'sequence
2311 "Controls how TODO keywords are interpreted.
2312 This variable is in principle obsolete and is only used for
2313 backward compatibility, if the interpretation of todo keywords is
2314 not given already in `org-todo-keywords'. See that variable for
2315 more information."
2316 :group 'org-todo
2317 :group 'org-keywords
2318 :type '(choice (const sequence)
2319 (const type)))
2321 (defcustom org-use-fast-todo-selection t
2322 "Non-nil means use the fast todo selection scheme with C-c C-t.
2323 This variable describes if and under what circumstances the cycling
2324 mechanism for TODO keywords will be replaced by a single-key, direct
2325 selection scheme.
2327 When nil, fast selection is never used.
2329 When the symbol `prefix', it will be used when `org-todo' is called
2330 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2331 `C-u t' in an agenda buffer.
2333 When t, fast selection is used by default. In this case, the prefix
2334 argument forces cycling instead.
2336 In all cases, the special interface is only used if access keys have
2337 actually been assigned by the user, i.e. if keywords in the configuration
2338 are followed by a letter in parenthesis, like TODO(t)."
2339 :group 'org-todo
2340 :type '(choice
2341 (const :tag "Never" nil)
2342 (const :tag "By default" t)
2343 (const :tag "Only with C-u C-c C-t" prefix)))
2345 (defcustom org-provide-todo-statistics t
2346 "Non-nil means update todo statistics after insert and toggle.
2347 ALL-HEADLINES means update todo statistics by including headlines
2348 with no TODO keyword as well, counting them as not done.
2349 A list of TODO keywords means the same, but skip keywords that are
2350 not in this list.
2352 When this is set, todo statistics is updated in the parent of the
2353 current entry each time a todo state is changed."
2354 :group 'org-todo
2355 :type '(choice
2356 (const :tag "Yes, only for TODO entries" t)
2357 (const :tag "Yes, including all entries" 'all-headlines)
2358 (repeat :tag "Yes, for TODOs in this list"
2359 (string :tag "TODO keyword"))
2360 (other :tag "No TODO statistics" nil)))
2362 (defcustom org-hierarchical-todo-statistics t
2363 "Non-nil means TODO statistics covers just direct children.
2364 When nil, all entries in the subtree are considered.
2365 This has only an effect if `org-provide-todo-statistics' is set.
2366 To set this to nil for only a single subtree, use a COOKIE_DATA
2367 property and include the word \"recursive\" into the value."
2368 :group 'org-todo
2369 :type 'boolean)
2371 (defcustom org-after-todo-state-change-hook nil
2372 "Hook which is run after the state of a TODO item was changed.
2373 The new state (a string with a TODO keyword, or nil) is available in the
2374 Lisp variable `org-state'."
2375 :group 'org-todo
2376 :type 'hook)
2378 (defvar org-blocker-hook nil
2379 "Hook for functions that are allowed to block a state change.
2381 Functions in this hook should not modify the buffer.
2382 Each function gets as its single argument a property list,
2383 see `org-trigger-hook' for more information about this list.
2385 If any of the functions in this hook returns nil, the state change
2386 is blocked.")
2388 (defvar org-trigger-hook nil
2389 "Hook for functions that are triggered by a state change.
2391 Each function gets as its single argument a property list with at
2392 least the following elements:
2394 (:type type-of-change :position pos-at-entry-start
2395 :from old-state :to new-state)
2397 Depending on the type, more properties may be present.
2399 This mechanism is currently implemented for:
2401 TODO state changes
2402 ------------------
2403 :type todo-state-change
2404 :from previous state (keyword as a string), or nil, or a symbol
2405 'todo' or 'done', to indicate the general type of state.
2406 :to new state, like in :from")
2408 (defcustom org-enforce-todo-dependencies nil
2409 "Non-nil means undone TODO entries will block switching the parent to DONE.
2410 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2411 be blocked if any prior sibling is not yet done.
2412 Finally, if the parent is blocked because of ordered siblings of its own,
2413 the child will also be blocked."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-children-or-siblings-or-parent)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-children-or-siblings-or-parent)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-enforce-todo-checkbox-dependencies nil
2425 "Non-nil means unchecked boxes will block switching the parent to DONE.
2426 When this is nil, checkboxes have no influence on switching TODO states.
2427 When non-nil, you first need to check off all check boxes before the TODO
2428 entry can be switched to DONE.
2429 This variable needs to be set before org.el is loaded, and you need to
2430 restart Emacs after a change to make the change effective. The only way
2431 to change is while Emacs is running is through the customize interface."
2432 :set (lambda (var val)
2433 (set var val)
2434 (if val
2435 (add-hook 'org-blocker-hook
2436 'org-block-todo-from-checkboxes)
2437 (remove-hook 'org-blocker-hook
2438 'org-block-todo-from-checkboxes)))
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-insert-todo-heading-as-state-change nil
2443 "Non-nil means inserting a TODO heading is treated as state change.
2444 So when the command \\[org-insert-todo-heading] is used, state change
2445 logging will apply if appropriate. When nil, the new TODO item will
2446 be inserted directly, and no logging will take place."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2451 "Non-nil means switching TODO states with S-cursor counts as state change.
2452 This is the default behavior. However, setting this to nil allows a
2453 convenient way to select a TODO state and bypass any logging associated
2454 with that."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-todo-state-tags-triggers nil
2459 "Tag changes that should be triggered by TODO state changes.
2460 This is a list. Each entry is
2462 (state-change (tag . flag) .......)
2464 State-change can be a string with a state, and empty string to indicate the
2465 state that has no TODO keyword, or it can be one of the symbols `todo'
2466 or `done', meaning any not-done or done state, respectively."
2467 :group 'org-todo
2468 :group 'org-tags
2469 :type '(repeat
2470 (cons (choice :tag "When changing to"
2471 (const :tag "Not-done state" todo)
2472 (const :tag "Done state" done)
2473 (string :tag "State"))
2474 (repeat
2475 (cons :tag "Tag action"
2476 (string :tag "Tag")
2477 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2479 (defcustom org-log-done nil
2480 "Information to record when a task moves to the DONE state.
2482 Possible values are:
2484 nil Don't add anything, just change the keyword
2485 time Add a time stamp to the task
2486 note Prompt for a note and add it with template `org-log-note-headings'
2488 This option can also be set with on a per-file-basis with
2490 #+STARTUP: nologdone
2491 #+STARTUP: logdone
2492 #+STARTUP: lognotedone
2494 You can have local logging settings for a subtree by setting the LOGGING
2495 property to one or more of these keywords."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "No logging" nil)
2500 (const :tag "Record CLOSED timestamp" time)
2501 (const :tag "Record CLOSED timestamp with note." note)))
2503 ;; Normalize old uses of org-log-done.
2504 (cond
2505 ((eq org-log-done t) (setq org-log-done 'time))
2506 ((and (listp org-log-done) (memq 'done org-log-done))
2507 (setq org-log-done 'note)))
2509 (defcustom org-log-reschedule nil
2510 "Information to record when the scheduling date of a tasks is modified.
2512 Possible values are:
2514 nil Don't add anything, just change the date
2515 time Add a time stamp to the task
2516 note Prompt for a note and add it with template `org-log-note-headings'
2518 This option can also be set with on a per-file-basis with
2520 #+STARTUP: nologreschedule
2521 #+STARTUP: logreschedule
2522 #+STARTUP: lognotereschedule"
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "No logging" nil)
2527 (const :tag "Record timestamp" time)
2528 (const :tag "Record timestamp with note." note)))
2530 (defcustom org-log-redeadline nil
2531 "Information to record when the deadline date of a tasks is modified.
2533 Possible values are:
2535 nil Don't add anything, just change the date
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologredeadline
2542 #+STARTUP: logredeadline
2543 #+STARTUP: lognoteredeadline
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record timestamp" time)
2552 (const :tag "Record timestamp with note." note)))
2554 (defcustom org-log-note-clock-out nil
2555 "Non-nil means record a note when clocking out of an item.
2556 This can also be configured on a per-file basis by adding one of
2557 the following lines anywhere in the buffer:
2559 #+STARTUP: lognoteclock-out
2560 #+STARTUP: nolognoteclock-out"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-done-with-time t
2566 "Non-nil means the CLOSED time stamp will contain date and time.
2567 When nil, only the date will be recorded."
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-log-note-headings
2572 '((done . "CLOSING NOTE %t")
2573 (state . "State %-12s from %-12S %t")
2574 (note . "Note taken on %t")
2575 (reschedule . "Rescheduled from %S on %t")
2576 (delschedule . "Not scheduled, was %S on %t")
2577 (redeadline . "New deadline from %S on %t")
2578 (deldeadline . "Removed deadline, was %S on %t")
2579 (refile . "Refiled on %t")
2580 (clock-out . ""))
2581 "Headings for notes added to entries.
2582 The value is an alist, with the car being a symbol indicating the note
2583 context, and the cdr is the heading to be used. The heading may also be the
2584 empty string.
2585 %t in the heading will be replaced by a time stamp.
2586 %T will be an active time stamp instead the default inactive one
2587 %d will be replaced by a short-format time stamp.
2588 %D will be replaced by an active short-format time stamp.
2589 %s will be replaced by the new TODO state, in double quotes.
2590 %S will be replaced by the old TODO state, in double quotes.
2591 %u will be replaced by the user name.
2592 %U will be replaced by the full user name.
2594 In fact, it is not a good idea to change the `state' entry, because
2595 agenda log mode depends on the format of these entries."
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type '(list :greedy t
2599 (cons (const :tag "Heading when closing an item" done) string)
2600 (cons (const :tag
2601 "Heading when changing todo state (todo sequence only)"
2602 state) string)
2603 (cons (const :tag "Heading when just taking a note" note) string)
2604 (cons (const :tag "Heading when clocking out" clock-out) string)
2605 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2606 (cons (const :tag "Heading when rescheduling" reschedule) string)
2607 (cons (const :tag "Heading when changing deadline" redeadline) string)
2608 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2609 (cons (const :tag "Heading when refiling" refile) string)))
2611 (unless (assq 'note org-log-note-headings)
2612 (push '(note . "%t") org-log-note-headings))
2614 (defcustom org-log-into-drawer nil
2615 "Non-nil means insert state change notes and time stamps into a drawer.
2616 When nil, state changes notes will be inserted after the headline and
2617 any scheduling and clock lines, but not inside a drawer.
2619 The value of this variable should be the name of the drawer to use.
2620 LOGBOOK is proposed as the default drawer for this purpose, you can
2621 also set this to a string to define the drawer of your choice.
2623 A value of t is also allowed, representing \"LOGBOOK\".
2625 A value of t or nil can also be set with on a per-file-basis with
2627 #+STARTUP: logdrawer
2628 #+STARTUP: nologdrawer
2630 If this variable is set, `org-log-state-notes-insert-after-drawers'
2631 will be ignored.
2633 You can set the property LOG_INTO_DRAWER to overrule this setting for
2634 a subtree."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "Not into a drawer" nil)
2639 (const :tag "LOGBOOK" t)
2640 (string :tag "Other")))
2642 (if (fboundp 'defvaralias)
2643 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2645 (defun org-log-into-drawer ()
2646 "Return the value of `org-log-into-drawer', but let properties overrule.
2647 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2648 used instead of the default value."
2649 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2650 (cond
2651 ((not p) org-log-into-drawer)
2652 ((equal p "nil") nil)
2653 ((equal p "t") "LOGBOOK")
2654 (t p))))
2656 (defcustom org-log-state-notes-insert-after-drawers nil
2657 "Non-nil means insert state change notes after any drawers in entry.
2658 Only the drawers that *immediately* follow the headline and the
2659 deadline/scheduled line are skipped.
2660 When nil, insert notes right after the heading and perhaps the line
2661 with deadline/scheduling if present.
2663 This variable will have no effect if `org-log-into-drawer' is
2664 set."
2665 :group 'org-todo
2666 :group 'org-progress
2667 :type 'boolean)
2669 (defcustom org-log-states-order-reversed t
2670 "Non-nil means the latest state note will be directly after heading.
2671 When nil, the state change notes will be ordered according to time.
2673 This option can also be set with on a per-file-basis with
2675 #+STARTUP: logstatesreversed
2676 #+STARTUP: nologstatesreversed"
2677 :group 'org-todo
2678 :group 'org-progress
2679 :type 'boolean)
2681 (defcustom org-todo-repeat-to-state nil
2682 "The TODO state to which a repeater should return the repeating task.
2683 By default this is the first task in a TODO sequence, or the previous state
2684 in a TODO_TYP set. But you can specify another task here.
2685 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2686 :group 'org-todo
2687 :version "24.1"
2688 :type '(choice (const :tag "Head of sequence" nil)
2689 (string :tag "Specific state")))
2691 (defcustom org-log-repeat 'time
2692 "Non-nil means record moving through the DONE state when triggering repeat.
2693 An auto-repeating task is immediately switched back to TODO when
2694 marked DONE. If you are not logging state changes (by adding \"@\"
2695 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2696 record a closing note, there will be no record of the task moving
2697 through DONE. This variable forces taking a note anyway.
2699 nil Don't force a record
2700 time Record a time stamp
2701 note Prompt for a note and add it with template `org-log-note-headings'
2703 This option can also be set with on a per-file-basis with
2705 #+STARTUP: nologrepeat
2706 #+STARTUP: logrepeat
2707 #+STARTUP: lognoterepeat
2709 You can have local logging settings for a subtree by setting the LOGGING
2710 property to one or more of these keywords."
2711 :group 'org-todo
2712 :group 'org-progress
2713 :type '(choice
2714 (const :tag "Don't force a record" nil)
2715 (const :tag "Force recording the DONE state" time)
2716 (const :tag "Force recording a note with the DONE state" note)))
2719 (defgroup org-priorities nil
2720 "Priorities in Org-mode."
2721 :tag "Org Priorities"
2722 :group 'org-todo)
2724 (defcustom org-enable-priority-commands t
2725 "Non-nil means priority commands are active.
2726 When nil, these commands will be disabled, so that you never accidentally
2727 set a priority."
2728 :group 'org-priorities
2729 :type 'boolean)
2731 (defcustom org-highest-priority ?A
2732 "The highest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a smaller ASCII number than `org-lowest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-lowest-priority ?C
2738 "The lowest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a larger ASCII number than `org-highest-priority'."
2740 :group 'org-priorities
2741 :type 'character)
2743 (defcustom org-default-priority ?B
2744 "The default priority of TODO items.
2745 This is the priority an item gets if no explicit priority is given.
2746 When starting to cycle on an empty priority the first step in the cycle
2747 depends on `org-priority-start-cycle-with-default'. The resulting first
2748 step priority must not exceed the range from `org-highest-priority' to
2749 `org-lowest-priority' which means that `org-default-priority' has to be
2750 in this range exclusive or inclusive the range boundaries. Else the
2751 first step refuses to set the default and the second will fall back
2752 to (depending on the command used) the highest or lowest priority."
2753 :group 'org-priorities
2754 :type 'character)
2756 (defcustom org-priority-start-cycle-with-default t
2757 "Non-nil means start with default priority when starting to cycle.
2758 When this is nil, the first step in the cycle will be (depending on the
2759 command used) one higher or lower than the default priority.
2760 See also `org-default-priority'."
2761 :group 'org-priorities
2762 :type 'boolean)
2764 (defcustom org-get-priority-function nil
2765 "Function to extract the priority from a string.
2766 The string is normally the headline. If this is nil Org computes the
2767 priority from the priority cookie like [#A] in the headline. It returns
2768 an integer, increasing by 1000 for each priority level.
2769 The user can set a different function here, which should take a string
2770 as an argument and return the numeric priority."
2771 :group 'org-priorities
2772 :version "24.1"
2773 :type 'function)
2775 (defgroup org-time nil
2776 "Options concerning time stamps and deadlines in Org-mode."
2777 :tag "Org Time"
2778 :group 'org)
2780 (defcustom org-insert-labeled-timestamps-at-point nil
2781 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2782 When nil, these labeled time stamps are forces into the second line of an
2783 entry, just after the headline. When scheduling from the global TODO list,
2784 the time stamp will always be forced into the second line."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2789 "Formats for `format-time-string' which are used for time stamps.
2790 It is not recommended to change this constant.")
2792 (defcustom org-time-stamp-rounding-minutes '(0 5)
2793 "Number of minutes to round time stamps to.
2794 These are two values, the first applies when first creating a time stamp.
2795 The second applies when changing it with the commands `S-up' and `S-down'.
2796 When changing the time stamp, this means that it will change in steps
2797 of N minutes, as given by the second value.
2799 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2800 numbers should be factors of 60, so for example 5, 10, 15.
2802 When this is larger than 1, you can still force an exact time stamp by using
2803 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2804 and by using a prefix arg to `S-up/down' to specify the exact number
2805 of minutes to shift."
2806 :group 'org-time
2807 :get #'(lambda (var) ; Make sure both elements are there
2808 (if (integerp (default-value var))
2809 (list (default-value var) 5)
2810 (default-value var)))
2811 :type '(list
2812 (integer :tag "when inserting times")
2813 (integer :tag "when modifying times")))
2815 ;; Normalize old customizations of this variable.
2816 (when (integerp org-time-stamp-rounding-minutes)
2817 (setq org-time-stamp-rounding-minutes
2818 (list org-time-stamp-rounding-minutes
2819 org-time-stamp-rounding-minutes)))
2821 (defcustom org-display-custom-times nil
2822 "Non-nil means overlay custom formats over all time stamps.
2823 The formats are defined through the variable `org-time-stamp-custom-formats'.
2824 To turn this on on a per-file basis, insert anywhere in the file:
2825 #+STARTUP: customtime"
2826 :group 'org-time
2827 :set 'set-default
2828 :type 'sexp)
2829 (make-variable-buffer-local 'org-display-custom-times)
2831 (defcustom org-time-stamp-custom-formats
2832 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2833 "Custom formats for time stamps. See `format-time-string' for the syntax.
2834 These are overlaid over the default ISO format if the variable
2835 `org-display-custom-times' is set. Time like %H:%M should be at the
2836 end of the second format. The custom formats are also honored by export
2837 commands, if custom time display is turned on at the time of export."
2838 :group 'org-time
2839 :type 'sexp)
2841 (defun org-time-stamp-format (&optional long inactive)
2842 "Get the right format for a time string."
2843 (let ((f (if long (cdr org-time-stamp-formats)
2844 (car org-time-stamp-formats))))
2845 (if inactive
2846 (concat "[" (substring f 1 -1) "]")
2847 f)))
2849 (defcustom org-time-clocksum-format
2850 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2851 "The format string used when creating CLOCKSUM lines.
2852 This is also used when Org mode generates a time duration.
2854 The value can be a single format string containing two
2855 %-sequences, which will be filled with the number of hours and
2856 minutes in that order.
2858 Alternatively, the value can be a plist associating any of the
2859 keys :years, :months, :weeks, :days, :hours or :minutes with
2860 format strings. The time duration is formatted using only the
2861 time components that are needed and concatenating the results.
2862 If a time unit in absent, it falls back to the next smallest
2863 unit.
2865 The keys :require-years, :require-months, :require-days,
2866 :require-weeks, :require-hours, :require-minutes are also
2867 meaningful. A non-nil value for these keys indicates that the
2868 corresponding time component should always be included, even if
2869 its value is 0.
2872 For example,
2874 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2875 :require-minutes t)
2877 means durations longer than a day will be expressed in days,
2878 hours and minutes, and durations less than a day will always be
2879 expressed in hours and minutes (even for durations less than an
2880 hour).
2882 The value
2884 \(:days \"%dd\" :minutes \"%dm\")
2886 means durations longer than a day will be expressed in days and
2887 minutes, and durations less than a day will be expressed entirely
2888 in minutes (even for durations longer than an hour)."
2889 :group 'org-time
2890 :group 'org-clock
2891 :version "24.4"
2892 :package-version '(Org . "8.0")
2893 :type '(choice (string :tag "Format string")
2894 (set :tag "Plist"
2895 (group :inline t (const :tag "Years" :years)
2896 (string :tag "Format string"))
2897 (group :inline t
2898 (const :tag "Always show years" :require-years)
2899 (const t))
2900 (group :inline t (const :tag "Months" :months)
2901 (string :tag "Format string"))
2902 (group :inline t
2903 (const :tag "Always show months" :require-months)
2904 (const t))
2905 (group :inline t (const :tag "Weeks" :weeks)
2906 (string :tag "Format string"))
2907 (group :inline t
2908 (const :tag "Always show weeks" :require-weeks)
2909 (const t))
2910 (group :inline t (const :tag "Days" :days)
2911 (string :tag "Format string"))
2912 (group :inline t
2913 (const :tag "Always show days" :require-days)
2914 (const t))
2915 (group :inline t (const :tag "Hours" :hours)
2916 (string :tag "Format string"))
2917 (group :inline t
2918 (const :tag "Always show hours" :require-hours)
2919 (const t))
2920 (group :inline t (const :tag "Minutes" :minutes)
2921 (string :tag "Format string"))
2922 (group :inline t
2923 (const :tag "Always show minutes" :require-minutes)
2924 (const t)))))
2926 (defcustom org-time-clocksum-use-fractional nil
2927 "When non-nil, \\[org-clock-display] uses fractional times.
2928 See `org-time-clocksum-format' for more on time clock formats."
2929 :group 'org-time
2930 :group 'org-clock
2931 :version "24.3"
2932 :type 'boolean)
2934 (defcustom org-time-clocksum-use-effort-durations t
2935 "When non-nil, \\[org-clock-display] uses effort durations.
2936 E.g. by default, one day is considered to be a 8 hours effort,
2937 so a task that has been clocked for 16 hours will be displayed
2938 as during 2 days in the clock display or in the clocktable.
2940 See `org-effort-durations' on how to set effort durations
2941 and `org-time-clocksum-format' for more on time clock formats."
2942 :group 'org-time
2943 :group 'org-clock
2944 :version "24.4"
2945 :package-version '(Org . "8.0")
2946 :type 'boolean)
2948 (defcustom org-time-clocksum-fractional-format "%.2f"
2949 "The format string used when creating CLOCKSUM lines,
2950 or when Org mode generates a time duration, if
2951 `org-time-clocksum-use-fractional' is enabled.
2953 The value can be a single format string containing one
2954 %-sequence, which will be filled with the number of hours as
2955 a float.
2957 Alternatively, the value can be a plist associating any of the
2958 keys :years, :months, :weeks, :days, :hours or :minutes with
2959 a format string. The time duration is formatted using the
2960 largest time unit which gives a non-zero integer part. If all
2961 specified formats have zero integer part, the smallest time unit
2962 is used."
2963 :group 'org-time
2964 :type '(choice (string :tag "Format string")
2965 (set (group :inline t (const :tag "Years" :years)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Months" :months)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Weeks" :weeks)
2970 (string :tag "Format string"))
2971 (group :inline t (const :tag "Days" :days)
2972 (string :tag "Format string"))
2973 (group :inline t (const :tag "Hours" :hours)
2974 (string :tag "Format string"))
2975 (group :inline t (const :tag "Minutes" :minutes)
2976 (string :tag "Format string")))))
2978 (defcustom org-deadline-warning-days 14
2979 "Number of days before expiration during which a deadline becomes active.
2980 This variable governs the display in sparse trees and in the agenda.
2981 When 0 or negative, it means use this number (the absolute value of it)
2982 even if a deadline has a different individual lead time specified.
2984 Custom commands can set this variable in the options section."
2985 :group 'org-time
2986 :group 'org-agenda-daily/weekly
2987 :type 'integer)
2989 (defcustom org-scheduled-delay-days 0
2990 "Number of days before a scheduled item becomes active.
2991 This variable governs the display in sparse trees and in the agenda.
2992 The default value (i.e. 0) means: don't delay scheduled item.
2993 When negative, it means use this number (the absolute value of it)
2994 even if a scheduled item has a different individual delay time
2995 specified.
2997 Custom commands can set this variable in the options section."
2998 :group 'org-time
2999 :group 'org-agenda-daily/weekly
3000 :version "24.4"
3001 :package-version '(Org . "8.0")
3002 :type 'integer)
3004 (defcustom org-read-date-prefer-future t
3005 "Non-nil means assume future for incomplete date input from user.
3006 This affects the following situations:
3007 1. The user gives a month but not a year.
3008 For example, if it is April and you enter \"feb 2\", this will be read
3009 as Feb 2, *next* year. \"May 5\", however, will be this year.
3010 2. The user gives a day, but no month.
3011 For example, if today is the 15th, and you enter \"3\", Org-mode will
3012 read this as the third of *next* month. However, if you enter \"17\",
3013 it will be considered as *this* month.
3015 If you set this variable to the symbol `time', then also the following
3016 will work:
3018 3. If the user gives a time.
3019 If the time is before now, it will be interpreted as tomorrow.
3021 Currently none of this works for ISO week specifications.
3023 When this option is nil, the current day, month and year will always be
3024 used as defaults.
3026 See also `org-agenda-jump-prefer-future'."
3027 :group 'org-time
3028 :type '(choice
3029 (const :tag "Never" nil)
3030 (const :tag "Check month and day" t)
3031 (const :tag "Check month, day, and time" time)))
3033 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3034 "Should the agenda jump command prefer the future for incomplete dates?
3035 The default is to do the same as configured in `org-read-date-prefer-future'.
3036 But you can also set a deviating value here.
3037 This may t or nil, or the symbol `org-read-date-prefer-future'."
3038 :group 'org-agenda
3039 :group 'org-time
3040 :version "24.1"
3041 :type '(choice
3042 (const :tag "Use org-read-date-prefer-future"
3043 org-read-date-prefer-future)
3044 (const :tag "Never" nil)
3045 (const :tag "Always" t)))
3047 (defcustom org-read-date-force-compatible-dates t
3048 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3050 Depending on the system Emacs is running on, certain dates cannot
3051 be represented with the type used internally to represent time.
3052 Dates between 1970-1-1 and 2038-1-1 can always be represented
3053 correctly. Some systems allow for earlier dates, some for later,
3054 some for both. One way to find out it to insert any date into an
3055 Org buffer, putting the cursor on the year and hitting S-up and
3056 S-down to test the range.
3058 When this variable is set to t, the date/time prompt will not let
3059 you specify dates outside the 1970-2037 range, so it is certain that
3060 these dates will work in whatever version of Emacs you are
3061 running, and also that you can move a file from one Emacs implementation
3062 to another. WHenever Org is forcing the year for you, it will display
3063 a message and beep.
3065 When this variable is nil, Org will check if the date is
3066 representable in the specific Emacs implementation you are using.
3067 If not, it will force a year, usually the current year, and beep
3068 to remind you. Currently this setting is not recommended because
3069 the likelihood that you will open your Org files in an Emacs that
3070 has limited date range is not negligible.
3072 A workaround for this problem is to use diary sexp dates for time
3073 stamps outside of this range."
3074 :group 'org-time
3075 :version "24.1"
3076 :type 'boolean)
3078 (defcustom org-read-date-display-live t
3079 "Non-nil means display current interpretation of date prompt live.
3080 This display will be in an overlay, in the minibuffer."
3081 :group 'org-time
3082 :type 'boolean)
3084 (defcustom org-read-date-popup-calendar t
3085 "Non-nil means pop up a calendar when prompting for a date.
3086 In the calendar, the date can be selected with mouse-1. However, the
3087 minibuffer will also be active, and you can simply enter the date as well.
3088 When nil, only the minibuffer will be available."
3089 :group 'org-time
3090 :type 'boolean)
3091 (if (fboundp 'defvaralias)
3092 (defvaralias 'org-popup-calendar-for-date-prompt
3093 'org-read-date-popup-calendar))
3095 (make-obsolete-variable
3096 'org-read-date-minibuffer-setup-hook
3097 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3098 (defcustom org-read-date-minibuffer-setup-hook nil
3099 "Hook to be used to set up keys for the date/time interface.
3100 Add key definitions to `minibuffer-local-map', which will be a
3101 temporary copy.
3103 WARNING: This option is obsolete, you should use
3104 `org-read-date-minibuffer-local-map' to set up keys."
3105 :group 'org-time
3106 :type 'hook)
3108 (defcustom org-extend-today-until 0
3109 "The hour when your day really ends. Must be an integer.
3110 This has influence for the following applications:
3111 - When switching the agenda to \"today\". It it is still earlier than
3112 the time given here, the day recognized as TODAY is actually yesterday.
3113 - When a date is read from the user and it is still before the time given
3114 here, the current date and time will be assumed to be yesterday, 23:59.
3115 Also, timestamps inserted in capture templates follow this rule.
3117 IMPORTANT: This is a feature whose implementation is and likely will
3118 remain incomplete. Really, it is only here because past midnight seems to
3119 be the favorite working time of John Wiegley :-)"
3120 :group 'org-time
3121 :type 'integer)
3123 (defcustom org-use-effective-time nil
3124 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3125 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3126 \"effective time\" of any timestamps between midnight and 8am will be
3127 23:59 of the previous day."
3128 :group 'org-time
3129 :version "24.1"
3130 :type 'boolean)
3132 (defcustom org-use-last-clock-out-time-as-effective-time nil
3133 "When non-nil, use the last clock out time for `org-todo'.
3134 Note that this option has precedence over the combined use of
3135 `org-use-effective-time' and `org-extend-today-until'."
3136 :group 'org-time
3137 :version "24.4"
3138 :package-version '(Org . "8.0")
3139 :type 'boolean)
3141 (defcustom org-edit-timestamp-down-means-later nil
3142 "Non-nil means S-down will increase the time in a time stamp.
3143 When nil, S-up will increase."
3144 :group 'org-time
3145 :type 'boolean)
3147 (defcustom org-calendar-follow-timestamp-change t
3148 "Non-nil means make the calendar window follow timestamp changes.
3149 When a timestamp is modified and the calendar window is visible, it will be
3150 moved to the new date."
3151 :group 'org-time
3152 :type 'boolean)
3154 (defgroup org-tags nil
3155 "Options concerning tags in Org-mode."
3156 :tag "Org Tags"
3157 :group 'org)
3159 (defcustom org-tag-alist nil
3160 "List of tags allowed in Org-mode files.
3161 When this list is nil, Org-mode will base TAG input on what is already in the
3162 buffer.
3163 The value of this variable is an alist, the car of each entry must be a
3164 keyword as a string, the cdr may be a character that is used to select
3165 that tag through the fast-tag-selection interface.
3166 See the manual for details."
3167 :group 'org-tags
3168 :type '(repeat
3169 (choice
3170 (cons (string :tag "Tag name")
3171 (character :tag "Access char"))
3172 (list :tag "Start radio group"
3173 (const :startgroup)
3174 (option (string :tag "Group description")))
3175 (list :tag "End radio group"
3176 (const :endgroup)
3177 (option (string :tag "Group description")))
3178 (const :tag "New line" (:newline)))))
3180 (defcustom org-tag-persistent-alist nil
3181 "List of tags that will always appear in all Org-mode files.
3182 This is in addition to any in buffer settings or customizations
3183 of `org-tag-alist'.
3184 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3185 The value of this variable is an alist, the car of each entry must be a
3186 keyword as a string, the cdr may be a character that is used to select
3187 that tag through the fast-tag-selection interface.
3188 See the manual for details.
3189 To disable these tags on a per-file basis, insert anywhere in the file:
3190 #+STARTUP: noptag"
3191 :group 'org-tags
3192 :type '(repeat
3193 (choice
3194 (cons (string :tag "Tag name")
3195 (character :tag "Access char"))
3196 (const :tag "Start radio group" (:startgroup))
3197 (const :tag "End radio group" (:endgroup))
3198 (const :tag "New line" (:newline)))))
3200 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3201 "If non-nil, always offer completion for all tags of all agenda files.
3202 Instead of customizing this variable directly, you might want to
3203 set it locally for capture buffers, because there no list of
3204 tags in that file can be created dynamically (there are none).
3206 (add-hook 'org-capture-mode-hook
3207 (lambda ()
3208 (set (make-local-variable
3209 'org-complete-tags-always-offer-all-agenda-tags)
3210 t)))"
3211 :group 'org-tags
3212 :version "24.1"
3213 :type 'boolean)
3215 (defvar org-file-tags nil
3216 "List of tags that can be inherited by all entries in the file.
3217 The tags will be inherited if the variable `org-use-tag-inheritance'
3218 says they should be.
3219 This variable is populated from #+FILETAGS lines.")
3221 (defcustom org-use-fast-tag-selection 'auto
3222 "Non-nil means use fast tag selection scheme.
3223 This is a special interface to select and deselect tags with single keys.
3224 When nil, fast selection is never used.
3225 When the symbol `auto', fast selection is used if and only if selection
3226 characters for tags have been configured, either through the variable
3227 `org-tag-alist' or through a #+TAGS line in the buffer.
3228 When t, fast selection is always used and selection keys are assigned
3229 automatically if necessary."
3230 :group 'org-tags
3231 :type '(choice
3232 (const :tag "Always" t)
3233 (const :tag "Never" nil)
3234 (const :tag "When selection characters are configured" 'auto)))
3236 (defcustom org-fast-tag-selection-single-key nil
3237 "Non-nil means fast tag selection exits after first change.
3238 When nil, you have to press RET to exit it.
3239 During fast tag selection, you can toggle this flag with `C-c'.
3240 This variable can also have the value `expert'. In this case, the window
3241 displaying the tags menu is not even shown, until you press C-c again."
3242 :group 'org-tags
3243 :type '(choice
3244 (const :tag "No" nil)
3245 (const :tag "Yes" t)
3246 (const :tag "Expert" expert)))
3248 (defvar org-fast-tag-selection-include-todo nil
3249 "Non-nil means fast tags selection interface will also offer TODO states.
3250 This is an undocumented feature, you should not rely on it.")
3252 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3253 "The column to which tags should be indented in a headline.
3254 If this number is positive, it specifies the column. If it is negative,
3255 it means that the tags should be flushright to that column. For example,
3256 -80 works well for a normal 80 character screen.
3257 When 0, place tags directly after headline text, with only one space in
3258 between."
3259 :group 'org-tags
3260 :type 'integer)
3262 (defcustom org-auto-align-tags t
3263 "Non-nil keeps tags aligned when modifying headlines.
3264 Some operations (i.e. demoting) change the length of a headline and
3265 therefore shift the tags around. With this option turned on, after
3266 each such operation the tags are again aligned to `org-tags-column'."
3267 :group 'org-tags
3268 :type 'boolean)
3270 (defcustom org-use-tag-inheritance t
3271 "Non-nil means tags in levels apply also for sublevels.
3272 When nil, only the tags directly given in a specific line apply there.
3273 This may also be a list of tags that should be inherited, or a regexp that
3274 matches tags that should be inherited. Additional control is possible
3275 with the variable `org-tags-exclude-from-inheritance' which gives an
3276 explicit list of tags to be excluded from inheritance, even if the value of
3277 `org-use-tag-inheritance' would select it for inheritance.
3279 If this option is t, a match early-on in a tree can lead to a large
3280 number of matches in the subtree when constructing the agenda or creating
3281 a sparse tree. If you only want to see the first match in a tree during
3282 a search, check out the variable `org-tags-match-list-sublevels'."
3283 :group 'org-tags
3284 :type '(choice
3285 (const :tag "Not" nil)
3286 (const :tag "Always" t)
3287 (repeat :tag "Specific tags" (string :tag "Tag"))
3288 (regexp :tag "Tags matched by regexp")))
3290 (defcustom org-tags-exclude-from-inheritance nil
3291 "List of tags that should never be inherited.
3292 This is a way to exclude a few tags from inheritance. For way to do
3293 the opposite, to actively allow inheritance for selected tags,
3294 see the variable `org-use-tag-inheritance'."
3295 :group 'org-tags
3296 :type '(repeat (string :tag "Tag")))
3298 (defun org-tag-inherit-p (tag)
3299 "Check if TAG is one that should be inherited."
3300 (cond
3301 ((member tag org-tags-exclude-from-inheritance) nil)
3302 ((eq org-use-tag-inheritance t) t)
3303 ((not org-use-tag-inheritance) nil)
3304 ((stringp org-use-tag-inheritance)
3305 (string-match org-use-tag-inheritance tag))
3306 ((listp org-use-tag-inheritance)
3307 (member tag org-use-tag-inheritance))
3308 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3310 (defcustom org-tags-match-list-sublevels t
3311 "Non-nil means list also sublevels of headlines matching a search.
3312 This variable applies to tags/property searches, and also to stuck
3313 projects because this search is based on a tags match as well.
3315 When set to the symbol `indented', sublevels are indented with
3316 leading dots.
3318 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3319 the sublevels of a headline matching a tag search often also match
3320 the same search. Listing all of them can create very long lists.
3321 Setting this variable to nil causes subtrees of a match to be skipped.
3323 This variable is semi-obsolete and probably should always be true. It
3324 is better to limit inheritance to certain tags using the variables
3325 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3326 :group 'org-tags
3327 :type '(choice
3328 (const :tag "No, don't list them" nil)
3329 (const :tag "Yes, do list them" t)
3330 (const :tag "List them, indented with leading dots" indented)))
3332 (defcustom org-tags-sort-function nil
3333 "When set, tags are sorted using this function as a comparator."
3334 :group 'org-tags
3335 :type '(choice
3336 (const :tag "No sorting" nil)
3337 (const :tag "Alphabetical" string<)
3338 (const :tag "Reverse alphabetical" string>)
3339 (function :tag "Custom function" nil)))
3341 (defvar org-tags-history nil
3342 "History of minibuffer reads for tags.")
3343 (defvar org-last-tags-completion-table nil
3344 "The last used completion table for tags.")
3345 (defvar org-after-tags-change-hook nil
3346 "Hook that is run after the tags in a line have changed.")
3348 (defgroup org-properties nil
3349 "Options concerning properties in Org-mode."
3350 :tag "Org Properties"
3351 :group 'org)
3353 (defcustom org-property-format "%-10s %s"
3354 "How property key/value pairs should be formatted by `indent-line'.
3355 When `indent-line' hits a property definition, it will format the line
3356 according to this format, mainly to make sure that the values are
3357 lined-up with respect to each other."
3358 :group 'org-properties
3359 :type 'string)
3361 (defcustom org-properties-postprocess-alist nil
3362 "Alist of properties and functions to adjust inserted values.
3363 Elements of this alist must be of the form
3365 ([string] [function])
3367 where [string] must be a property name and [function] must be a
3368 lambda expression: this lambda expression must take one argument,
3369 the value to adjust, and return the new value as a string.
3371 For example, this element will allow the property \"Remaining\"
3372 to be updated wrt the relation between the \"Effort\" property
3373 and the clock summary:
3375 ((\"Remaining\" (lambda(value)
3376 (let ((clocksum (org-clock-sum-current-item))
3377 (effort (org-duration-string-to-minutes
3378 (org-entry-get (point) \"Effort\"))))
3379 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3380 :group 'org-properties
3381 :version "24.1"
3382 :type '(alist :key-type (string :tag "Property")
3383 :value-type (function :tag "Function")))
3385 (defcustom org-use-property-inheritance nil
3386 "Non-nil means properties apply also for sublevels.
3388 This setting is chiefly used during property searches. Turning it on can
3389 cause significant overhead when doing a search, which is why it is not
3390 on by default.
3392 When nil, only the properties directly given in the current entry count.
3393 When t, every property is inherited. The value may also be a list of
3394 properties that should have inheritance, or a regular expression matching
3395 properties that should be inherited.
3397 However, note that some special properties use inheritance under special
3398 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3399 and the properties ending in \"_ALL\" when they are used as descriptor
3400 for valid values of a property.
3402 Note for programmers:
3403 When querying an entry with `org-entry-get', you can control if inheritance
3404 should be used. By default, `org-entry-get' looks only at the local
3405 properties. You can request inheritance by setting the inherit argument
3406 to t (to force inheritance) or to `selective' (to respect the setting
3407 in this variable)."
3408 :group 'org-properties
3409 :type '(choice
3410 (const :tag "Not" nil)
3411 (const :tag "Always" t)
3412 (repeat :tag "Specific properties" (string :tag "Property"))
3413 (regexp :tag "Properties matched by regexp")))
3415 (defun org-property-inherit-p (property)
3416 "Check if PROPERTY is one that should be inherited."
3417 (cond
3418 ((eq org-use-property-inheritance t) t)
3419 ((not org-use-property-inheritance) nil)
3420 ((stringp org-use-property-inheritance)
3421 (string-match org-use-property-inheritance property))
3422 ((listp org-use-property-inheritance)
3423 (member property org-use-property-inheritance))
3424 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3426 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3427 "The default column format, if no other format has been defined.
3428 This variable can be set on the per-file basis by inserting a line
3430 #+COLUMNS: %25ITEM ....."
3431 :group 'org-properties
3432 :type 'string)
3434 (defcustom org-columns-ellipses ".."
3435 "The ellipses to be used when a field in column view is truncated.
3436 When this is the empty string, as many characters as possible are shown,
3437 but then there will be no visual indication that the field has been truncated.
3438 When this is a string of length N, the last N characters of a truncated
3439 field are replaced by this string. If the column is narrower than the
3440 ellipses string, only part of the ellipses string will be shown."
3441 :group 'org-properties
3442 :type 'string)
3444 (defcustom org-columns-modify-value-for-display-function nil
3445 "Function that modifies values for display in column view.
3446 For example, it can be used to cut out a certain part from a time stamp.
3447 The function must take 2 arguments:
3449 column-title The title of the column (*not* the property name)
3450 value The value that should be modified.
3452 The function should return the value that should be displayed,
3453 or nil if the normal value should be used."
3454 :group 'org-properties
3455 :type 'function)
3457 (defcustom org-effort-property "Effort"
3458 "The property that is being used to keep track of effort estimates.
3459 Effort estimates given in this property need to have the format H:MM."
3460 :group 'org-properties
3461 :group 'org-progress
3462 :type '(string :tag "Property"))
3464 (defconst org-global-properties-fixed
3465 '(("VISIBILITY_ALL" . "folded children content all")
3466 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3467 "List of property/value pairs that can be inherited by any entry.
3469 These are fixed values, for the preset properties. The user variable
3470 that can be used to add to this list is `org-global-properties'.
3472 The entries in this list are cons cells where the car is a property
3473 name and cdr is a string with the value. If the value represents
3474 multiple items like an \"_ALL\" property, separate the items by
3475 spaces.")
3477 (defcustom org-global-properties nil
3478 "List of property/value pairs that can be inherited by any entry.
3480 This list will be combined with the constant `org-global-properties-fixed'.
3482 The entries in this list are cons cells where the car is a property
3483 name and cdr is a string with the value.
3485 You can set buffer-local values for the same purpose in the variable
3486 `org-file-properties' this by adding lines like
3488 #+PROPERTY: NAME VALUE"
3489 :group 'org-properties
3490 :type '(repeat
3491 (cons (string :tag "Property")
3492 (string :tag "Value"))))
3494 (defvar org-file-properties nil
3495 "List of property/value pairs that can be inherited by any entry.
3496 Valid for the current buffer.
3497 This variable is populated from #+PROPERTY lines.")
3498 (make-variable-buffer-local 'org-file-properties)
3500 (defgroup org-agenda nil
3501 "Options concerning agenda views in Org-mode."
3502 :tag "Org Agenda"
3503 :group 'org)
3505 (defvar org-category nil
3506 "Variable used by org files to set a category for agenda display.
3507 Such files should use a file variable to set it, for example
3509 # -*- mode: org; org-category: \"ELisp\"
3511 or contain a special line
3513 #+CATEGORY: ELisp
3515 If the file does not specify a category, then file's base name
3516 is used instead.")
3517 (make-variable-buffer-local 'org-category)
3518 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3520 (defcustom org-agenda-files nil
3521 "The files to be used for agenda display.
3522 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3523 \\[org-remove-file]. You can also use customize to edit the list.
3525 If an entry is a directory, all files in that directory that are matched by
3526 `org-agenda-file-regexp' will be part of the file list.
3528 If the value of the variable is not a list but a single file name, then
3529 the list of agenda files is actually stored and maintained in that file, one
3530 agenda file per line. In this file paths can be given relative to
3531 `org-directory'. Tilde expansion and environment variable substitution
3532 are also made."
3533 :group 'org-agenda
3534 :type '(choice
3535 (repeat :tag "List of files and directories" file)
3536 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3538 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3539 "Regular expression to match files for `org-agenda-files'.
3540 If any element in the list in that variable contains a directory instead
3541 of a normal file, all files in that directory that are matched by this
3542 regular expression will be included."
3543 :group 'org-agenda
3544 :type 'regexp)
3546 (defcustom org-agenda-text-search-extra-files nil
3547 "List of extra files to be searched by text search commands.
3548 These files will be search in addition to the agenda files by the
3549 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3550 Note that these files will only be searched for text search commands,
3551 not for the other agenda views like todo lists, tag searches or the weekly
3552 agenda. This variable is intended to list notes and possibly archive files
3553 that should also be searched by these two commands.
3554 In fact, if the first element in the list is the symbol `agenda-archives',
3555 than all archive files of all agenda files will be added to the search
3556 scope."
3557 :group 'org-agenda
3558 :type '(set :greedy t
3559 (const :tag "Agenda Archives" agenda-archives)
3560 (repeat :inline t (file))))
3562 (if (fboundp 'defvaralias)
3563 (defvaralias 'org-agenda-multi-occur-extra-files
3564 'org-agenda-text-search-extra-files))
3566 (defcustom org-agenda-skip-unavailable-files nil
3567 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3568 A nil value means to remove them, after a query, from the list."
3569 :group 'org-agenda
3570 :type 'boolean)
3572 (defcustom org-calendar-to-agenda-key [?c]
3573 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3574 The command `org-calendar-goto-agenda' will be bound to this key. The
3575 default is the character `c' because then `c' can be used to switch back and
3576 forth between agenda and calendar."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-calendar-insert-diary-entry-key [?i]
3581 "The key to be installed in `calendar-mode-map' for adding diary entries.
3582 This option is irrelevant until `org-agenda-diary-file' has been configured
3583 to point to an Org-mode file. When that is the case, the command
3584 `org-agenda-diary-entry' will be bound to the key given here, by default
3585 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3586 if you want to continue doing this, you need to change this to a different
3587 key."
3588 :group 'org-agenda
3589 :type 'sexp)
3591 (defcustom org-agenda-diary-file 'diary-file
3592 "File to which to add new entries with the `i' key in agenda and calendar.
3593 When this is the symbol `diary-file', the functionality in the Emacs
3594 calendar will be used to add entries to the `diary-file'. But when this
3595 points to a file, `org-agenda-diary-entry' will be used instead."
3596 :group 'org-agenda
3597 :type '(choice
3598 (const :tag "The standard Emacs diary file" diary-file)
3599 (file :tag "Special Org file diary entries")))
3601 (eval-after-load "calendar"
3602 '(progn
3603 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3604 'org-calendar-goto-agenda)
3605 (add-hook 'calendar-mode-hook
3606 (lambda ()
3607 (unless (eq org-agenda-diary-file 'diary-file)
3608 (define-key calendar-mode-map
3609 org-calendar-insert-diary-entry-key
3610 'org-agenda-diary-entry))))))
3612 (defgroup org-latex nil
3613 "Options for embedding LaTeX code into Org-mode."
3614 :tag "Org LaTeX"
3615 :group 'org)
3617 (defcustom org-format-latex-options
3618 '(:foreground default :background default :scale 1.0
3619 :html-foreground "Black" :html-background "Transparent"
3620 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3621 "Options for creating images from LaTeX fragments.
3622 This is a property list with the following properties:
3623 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3624 `default' means use the foreground of the default face.
3625 `auto' means use the foreground from the text face.
3626 :background the background color, or \"Transparent\".
3627 `default' means use the background of the default face.
3628 `auto' means use the background from the text face.
3629 :scale a scaling factor for the size of the images, to get more pixels
3630 :html-foreground, :html-background, :html-scale
3631 the same numbers for HTML export.
3632 :matchers a list indicating which matchers should be used to
3633 find LaTeX fragments. Valid members of this list are:
3634 \"begin\" find environments
3635 \"$1\" find single characters surrounded by $.$
3636 \"$\" find math expressions surrounded by $...$
3637 \"$$\" find math expressions surrounded by $$....$$
3638 \"\\(\" find math expressions surrounded by \\(...\\)
3639 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3640 :group 'org-latex
3641 :type 'plist)
3643 (defcustom org-format-latex-signal-error t
3644 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3645 When nil, just push out a message."
3646 :group 'org-latex
3647 :version "24.1"
3648 :type 'boolean)
3650 (defcustom org-latex-to-mathml-jar-file nil
3651 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3652 Use this to specify additional executable file say a jar file.
3654 When using MathToWeb as the converter, specify the full-path to
3655 your mathtoweb.jar file."
3656 :group 'org-latex
3657 :version "24.1"
3658 :type '(choice
3659 (const :tag "None" nil)
3660 (file :tag "JAR file" :must-match t)))
3662 (defcustom org-latex-to-mathml-convert-command nil
3663 "Command to convert LaTeX fragments to MathML.
3664 Replace format-specifiers in the command as noted below and use
3665 `shell-command' to convert LaTeX to MathML.
3666 %j: Executable file in fully expanded form as specified by
3667 `org-latex-to-mathml-jar-file'.
3668 %I: Input LaTeX file in fully expanded form
3669 %o: Output MathML file
3670 This command is used by `org-create-math-formula'.
3672 When using MathToWeb as the converter, set this to
3673 \"java -jar %j -unicode -force -df %o %I\"."
3674 :group 'org-latex
3675 :version "24.1"
3676 :type '(choice
3677 (const :tag "None" nil)
3678 (string :tag "\nShell command")))
3680 (defcustom org-latex-create-formula-image-program 'dvipng
3681 "Program to convert LaTeX fragments with.
3683 dvipng Process the LaTeX fragments to dvi file, then convert
3684 dvi files to png files using dvipng.
3685 This will also include processing of non-math environments.
3686 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3687 to convert pdf files to png files"
3688 :group 'org-latex
3689 :version "24.1"
3690 :type '(choice
3691 (const :tag "dvipng" dvipng)
3692 (const :tag "imagemagick" imagemagick)))
3694 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3695 "Path to store latex preview images.
3696 A relative path here creates many directories relative to the
3697 processed org files paths. An absolute path puts all preview
3698 images at the same place."
3699 :group 'org-latex
3700 :version "24.3"
3701 :type 'string)
3703 (defun org-format-latex-mathml-available-p ()
3704 "Return t if `org-latex-to-mathml-convert-command' is usable."
3705 (save-match-data
3706 (when (and (boundp 'org-latex-to-mathml-convert-command)
3707 org-latex-to-mathml-convert-command)
3708 (let ((executable (car (split-string
3709 org-latex-to-mathml-convert-command))))
3710 (when (executable-find executable)
3711 (if (string-match
3712 "%j" org-latex-to-mathml-convert-command)
3713 (file-readable-p org-latex-to-mathml-jar-file)
3714 t))))))
3716 (defcustom org-format-latex-header "\\documentclass{article}
3717 \\usepackage[usenames]{color}
3718 \\usepackage{amsmath}
3719 \\usepackage[mathscr]{eucal}
3720 \\pagestyle{empty} % do not remove
3721 \[PACKAGES]
3722 \[DEFAULT-PACKAGES]
3723 % The settings below are copied from fullpage.sty
3724 \\setlength{\\textwidth}{\\paperwidth}
3725 \\addtolength{\\textwidth}{-3cm}
3726 \\setlength{\\oddsidemargin}{1.5cm}
3727 \\addtolength{\\oddsidemargin}{-2.54cm}
3728 \\setlength{\\evensidemargin}{\\oddsidemargin}
3729 \\setlength{\\textheight}{\\paperheight}
3730 \\addtolength{\\textheight}{-\\headheight}
3731 \\addtolength{\\textheight}{-\\headsep}
3732 \\addtolength{\\textheight}{-\\footskip}
3733 \\addtolength{\\textheight}{-3cm}
3734 \\setlength{\\topmargin}{1.5cm}
3735 \\addtolength{\\topmargin}{-2.54cm}"
3736 "The document header used for processing LaTeX fragments.
3737 It is imperative that this header make sure that no page number
3738 appears on the page. The package defined in the variables
3739 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3740 will either replace the placeholder \"[PACKAGES]\" in this
3741 header, or they will be appended."
3742 :group 'org-latex
3743 :type 'string)
3745 (defun org-set-packages-alist (var val)
3746 "Set the packages alist and make sure it has 3 elements per entry."
3747 (set var (mapcar (lambda (x)
3748 (if (and (consp x) (= (length x) 2))
3749 (list (car x) (nth 1 x) t)
3751 val)))
3753 (defun org-get-packages-alist (var)
3754 "Get the packages alist and make sure it has 3 elements per entry."
3755 (mapcar (lambda (x)
3756 (if (and (consp x) (= (length x) 2))
3757 (list (car x) (nth 1 x) t)
3759 (default-value var)))
3761 (defcustom org-latex-default-packages-alist
3762 '(("AUTO" "inputenc" t)
3763 ("T1" "fontenc" t)
3764 ("" "fixltx2e" nil)
3765 ("" "graphicx" t)
3766 ("" "longtable" nil)
3767 ("" "float" nil)
3768 ("" "wrapfig" nil)
3769 ("" "soul" t)
3770 ("" "textcomp" t)
3771 ("" "marvosym" t)
3772 ("" "wasysym" t)
3773 ("" "latexsym" t)
3774 ("" "amssymb" t)
3775 ("" "hyperref" nil)
3776 "\\tolerance=1000")
3777 "Alist of default packages to be inserted in the header.
3779 Change this only if one of the packages here causes an
3780 incompatibility with another package you are using.
3782 The packages in this list are needed by one part or another of
3783 Org mode to function properly:
3785 - inputenc, fontenc: for basic font and character selection
3786 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3787 symbols used for interpreting the entities in `org-entities'.
3788 You can skip some of these packages if you don't use any of the
3789 symbols in it.
3790 - graphicx: for including images
3791 - float, wrapfig: for figure placement
3792 - longtable: for long tables
3793 - hyperref: for cross references
3795 Therefore you should not modify this variable unless you know
3796 what you are doing. The one reason to change it anyway is that
3797 you might be loading some other package that conflicts with one
3798 of the default packages. Each cell is of the format
3799 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3800 the package also needs to be included when compiling LaTeX
3801 snippets into images for inclusion into non-LaTeX output."
3802 :group 'org-latex
3803 :group 'org-export-latex
3804 :set 'org-set-packages-alist
3805 :get 'org-get-packages-alist
3806 :version "24.1"
3807 :type '(repeat
3808 (choice
3809 (list :tag "options/package pair"
3810 (string :tag "options")
3811 (string :tag "package")
3812 (boolean :tag "Snippet"))
3813 (string :tag "A line of LaTeX"))))
3815 (defcustom org-latex-packages-alist nil
3816 "Alist of packages to be inserted in every LaTeX header.
3818 These will be inserted after `org-latex-default-packages-alist'.
3819 Each cell is of the format:
3821 \(\"options\" \"package\" snippet-flag)
3823 SNIPPET-FLAG, when t, indicates that this package is also needed
3824 when turning LaTeX snippets into images for inclusion into
3825 non-LaTeX output.
3827 Make sure that you only list packages here which:
3829 - you want in every file
3830 - do not conflict with the setup in `org-format-latex-header'.
3831 - do not conflict with the default packages in
3832 `org-latex-default-packages-alist'."
3833 :group 'org-latex
3834 :group 'org-export-latex
3835 :set 'org-set-packages-alist
3836 :get 'org-get-packages-alist
3837 :type '(repeat
3838 (choice
3839 (list :tag "options/package pair"
3840 (string :tag "options")
3841 (string :tag "package")
3842 (boolean :tag "Snippet"))
3843 (string :tag "A line of LaTeX"))))
3845 (defgroup org-appearance nil
3846 "Settings for Org-mode appearance."
3847 :tag "Org Appearance"
3848 :group 'org)
3850 (defcustom org-level-color-stars-only nil
3851 "Non-nil means fontify only the stars in each headline.
3852 When nil, the entire headline is fontified.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified."
3855 :group 'org-appearance
3856 :type 'boolean)
3858 (defcustom org-hide-leading-stars nil
3859 "Non-nil means hide the first N-1 stars in a headline.
3860 This works by using the face `org-hide' for these stars. This
3861 face is white for a light background, and black for a dark
3862 background. You may have to customize the face `org-hide' to
3863 make this work.
3864 Changing it requires restart of `font-lock-mode' to become effective
3865 also in regions already fontified.
3866 You may also set this on a per-file basis by adding one of the following
3867 lines to the buffer:
3869 #+STARTUP: hidestars
3870 #+STARTUP: showstars"
3871 :group 'org-appearance
3872 :type 'boolean)
3874 (defcustom org-hidden-keywords nil
3875 "List of symbols corresponding to keywords to be hidden the org buffer.
3876 For example, a value '(title) for this list will make the document's title
3877 appear in the buffer without the initial #+TITLE: keyword."
3878 :group 'org-appearance
3879 :version "24.1"
3880 :type '(set (const :tag "#+AUTHOR" author)
3881 (const :tag "#+DATE" date)
3882 (const :tag "#+EMAIL" email)
3883 (const :tag "#+TITLE" title)))
3885 (defcustom org-custom-properties nil
3886 "List of properties (as strings) with a special meaning.
3887 The default use of these custom properties is to let the user
3888 hide them with `org-toggle-custom-properties-visibility'."
3889 :group 'org-properties
3890 :group 'org-appearance
3891 :version "24.3"
3892 :type '(repeat (string :tag "Property Name")))
3894 (defcustom org-fontify-done-headline nil
3895 "Non-nil means change the face of a headline if it is marked DONE.
3896 Normally, only the TODO/DONE keyword indicates the state of a headline.
3897 When this is non-nil, the headline after the keyword is set to the
3898 `org-headline-done' as an additional indication."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-emphasized-text t
3903 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3904 Changing this variable requires a restart of Emacs to take effect."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-fontify-whole-heading-line nil
3909 "Non-nil means fontify the whole line for headings.
3910 This is useful when setting a background color for the
3911 org-level-* faces."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-highlight-latex-and-related nil
3916 "Non-nil means highlight LaTeX related syntax in the buffer.
3917 When non nil, the value should be a list containing any of the
3918 following symbols:
3919 `latex' Highlight LaTeX snippets and environments.
3920 `script' Highlight subscript and superscript.
3921 `entities' Highlight entities."
3922 :group 'org-appearance
3923 :version "24.4"
3924 :package-version '(Org . "8.0")
3925 :type '(choice
3926 (const :tag "No highlighting" nil)
3927 (set :greedy t :tag "Highlight"
3928 (const :tag "LaTeX snippets and environments" latex)
3929 (const :tag "Subscript and superscript" script)
3930 (const :tag "Entities" entities))))
3932 (defcustom org-hide-emphasis-markers nil
3933 "Non-nil mean font-lock should hide the emphasis marker characters."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-pretty-entities nil
3938 "Non-nil means show entities as UTF8 characters.
3939 When nil, the \\name form remains in the buffer."
3940 :group 'org-appearance
3941 :version "24.1"
3942 :type 'boolean)
3944 (defcustom org-pretty-entities-include-sub-superscripts t
3945 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3946 :group 'org-appearance
3947 :version "24.1"
3948 :type 'boolean)
3950 (defvar org-emph-re nil
3951 "Regular expression for matching emphasis.
3952 After a match, the match groups contain these elements:
3953 0 The match of the full regular expression, including the characters
3954 before and after the proper match
3955 1 The character before the proper match, or empty at beginning of line
3956 2 The proper match, including the leading and trailing markers
3957 3 The leading marker like * or /, indicating the type of highlighting
3958 4 The text between the emphasis markers, not including the markers
3959 5 The character after the match, empty at the end of a line")
3960 (defvar org-verbatim-re nil
3961 "Regular expression for matching verbatim text.")
3962 (defvar org-emphasis-regexp-components) ; defined just below
3963 (defvar org-emphasis-alist) ; defined just below
3964 (defun org-set-emph-re (var val)
3965 "Set variable and compute the emphasis regular expression."
3966 (set var val)
3967 (when (and (boundp 'org-emphasis-alist)
3968 (boundp 'org-emphasis-regexp-components)
3969 org-emphasis-alist org-emphasis-regexp-components)
3970 (let* ((e org-emphasis-regexp-components)
3971 (pre (car e))
3972 (post (nth 1 e))
3973 (border (nth 2 e))
3974 (body (nth 3 e))
3975 (nl (nth 4 e))
3976 (body1 (concat body "*?"))
3977 (markers (mapconcat 'car org-emphasis-alist ""))
3978 (vmarkers (mapconcat
3979 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3980 org-emphasis-alist "")))
3981 ;; make sure special characters appear at the right position in the class
3982 (if (string-match "\\^" markers)
3983 (setq markers (concat (replace-match "" t t markers) "^")))
3984 (if (string-match "-" markers)
3985 (setq markers (concat (replace-match "" t t markers) "-")))
3986 (if (string-match "\\^" vmarkers)
3987 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3988 (if (string-match "-" vmarkers)
3989 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3990 (if (> nl 0)
3991 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3992 (int-to-string nl) "\\}")))
3993 ;; Make the regexp
3994 (setq org-emph-re
3995 (concat "\\([" pre "]\\|^\\)"
3996 "\\("
3997 "\\([" markers "]\\)"
3998 "\\("
3999 "[^" border "]\\|"
4000 "[^" border "]"
4001 body1
4002 "[^" border "]"
4003 "\\)"
4004 "\\3\\)"
4005 "\\([" post "]\\|$\\)"))
4006 (setq org-verbatim-re
4007 (concat "\\([" pre "]\\|^\\)"
4008 "\\("
4009 "\\([" vmarkers "]\\)"
4010 "\\("
4011 "[^" border "]\\|"
4012 "[^" border "]"
4013 body1
4014 "[^" border "]"
4015 "\\)"
4016 "\\3\\)"
4017 "\\([" post "]\\|$\\)")))))
4019 (defcustom org-emphasis-regexp-components
4020 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4021 "Components used to build the regular expression for emphasis.
4022 This is a list with five entries. Terminology: In an emphasis string
4023 like \" *strong word* \", we call the initial space PREMATCH, the final
4024 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4025 and \"trong wor\" is the body. The different components in this variable
4026 specify what is allowed/forbidden in each part:
4028 pre Chars allowed as prematch. Beginning of line will be allowed too.
4029 post Chars allowed as postmatch. End of line will be allowed too.
4030 border The chars *forbidden* as border characters.
4031 body-regexp A regexp like \".\" to match a body character. Don't use
4032 non-shy groups here, and don't allow newline here.
4033 newline The maximum number of newlines allowed in an emphasis exp.
4035 Use customize to modify this, or restart Emacs after changing it."
4036 :group 'org-appearance
4037 :set 'org-set-emph-re
4038 :type '(list
4039 (sexp :tag "Allowed chars in pre ")
4040 (sexp :tag "Allowed chars in post ")
4041 (sexp :tag "Forbidden chars in border ")
4042 (sexp :tag "Regexp for body ")
4043 (integer :tag "number of newlines allowed")
4044 (option (boolean :tag "Please ignore this button"))))
4046 (defcustom org-emphasis-alist
4047 `(("*" bold "<b>" "</b>")
4048 ("/" italic "<i>" "</i>")
4049 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4050 ("=" org-code "<code>" "</code>" verbatim)
4051 ("~" org-verbatim "<code>" "</code>" verbatim)
4052 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4053 "<del>" "</del>")
4055 "Special syntax for emphasized text.
4056 Text starting and ending with a special character will be emphasized, for
4057 example *bold*, _underlined_ and /italic/. This variable sets the marker
4058 characters, the face to be used by font-lock for highlighting in Org-mode
4059 Emacs buffers, and the HTML tags to be used for this.
4060 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4061 Use customize to modify this, or restart Emacs after changing it."
4062 :group 'org-appearance
4063 :set 'org-set-emph-re
4064 :type '(repeat
4065 (list
4066 (string :tag "Marker character")
4067 (choice
4068 (face :tag "Font-lock-face")
4069 (plist :tag "Face property list"))
4070 (string :tag "HTML start tag")
4071 (string :tag "HTML end tag")
4072 (option (const verbatim)))))
4074 (defvar org-protecting-blocks
4075 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4076 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4077 This is needed for font-lock setup.")
4079 ;;; Miscellaneous options
4081 (defgroup org-completion nil
4082 "Completion in Org-mode."
4083 :tag "Org Completion"
4084 :group 'org)
4086 (defcustom org-completion-use-ido nil
4087 "Non-nil means use ido completion wherever possible.
4088 Note that `ido-mode' must be active for this variable to be relevant.
4089 If you decide to turn this variable on, you might well want to turn off
4090 `org-outline-path-complete-in-steps'.
4091 See also `org-completion-use-iswitchb'."
4092 :group 'org-completion
4093 :type 'boolean)
4095 (defcustom org-completion-use-iswitchb nil
4096 "Non-nil means use iswitchb completion wherever possible.
4097 Note that `iswitchb-mode' must be active for this variable to be relevant.
4098 If you decide to turn this variable on, you might well want to turn off
4099 `org-outline-path-complete-in-steps'.
4100 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4101 :group 'org-completion
4102 :type 'boolean)
4104 (defcustom org-completion-fallback-command 'hippie-expand
4105 "The expansion command called by \\[pcomplete] in normal context.
4106 Normal means, no org-mode-specific context."
4107 :group 'org-completion
4108 :type 'function)
4110 ;;; Functions and variables from their packages
4111 ;; Declared here to avoid compiler warnings
4113 ;; XEmacs only
4114 (defvar outline-mode-menu-heading)
4115 (defvar outline-mode-menu-show)
4116 (defvar outline-mode-menu-hide)
4117 (defvar zmacs-regions) ; XEmacs regions
4119 ;; Emacs only
4120 (defvar mark-active)
4122 ;; Various packages
4123 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4124 (declare-function calendar-forward-day "cal-move" (arg))
4125 (declare-function calendar-goto-date "cal-move" (date))
4126 (declare-function calendar-goto-today "cal-move" ())
4127 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4128 (defvar calc-embedded-close-formula)
4129 (defvar calc-embedded-open-formula)
4130 (declare-function cdlatex-tab "ext:cdlatex" ())
4131 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4132 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4133 (defvar font-lock-unfontify-region-function)
4134 (declare-function iswitchb-read-buffer "iswitchb"
4135 (prompt &optional default require-match start matches-set))
4136 (defvar iswitchb-temp-buflist)
4137 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4138 (defvar org-agenda-tags-todo-honor-ignore-options)
4139 (declare-function org-agenda-skip "org-agenda" ())
4140 (declare-function
4141 org-agenda-format-item "org-agenda"
4142 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4143 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4144 (declare-function org-agenda-change-all-lines "org-agenda"
4145 (newhead hdmarker &optional fixface just-this))
4146 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4147 (declare-function org-agenda-maybe-redo "org-agenda" ())
4148 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4149 (beg end))
4150 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4151 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4152 "org-agenda" (&optional end))
4153 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4154 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4155 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4156 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4157 (declare-function org-indent-mode "org-indent" (&optional arg))
4158 (declare-function parse-time-string "parse-time" (string))
4159 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4160 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4161 (defvar remember-data-file)
4162 (defvar texmathp-why)
4163 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4164 (declare-function table--at-cell-p "table" (position &optional object at-column))
4166 (defvar org-latex-regexps)
4168 ;;; Autoload and prepare some org modules
4170 ;; Some table stuff that needs to be defined here, because it is used
4171 ;; by the functions setting up org-mode or checking for table context.
4173 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4174 "Detect an org-type or table-type table.")
4175 (defconst org-table-line-regexp "^[ \t]*|"
4176 "Detect an org-type table line.")
4177 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4178 "Detect an org-type table line.")
4179 (defconst org-table-hline-regexp "^[ \t]*|-"
4180 "Detect an org-type table hline.")
4181 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4182 "Detect a table-type table hline.")
4183 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4184 "Detect the first line outside a table when searching from within it.
4185 This works for both table types.")
4187 ;; Autoload the functions in org-table.el that are needed by functions here.
4189 (eval-and-compile
4190 (org-autoload "org-table"
4191 '(org-table-begin org-table-blank-field org-table-end)))
4193 ;;;###autoload
4194 (defun turn-on-orgtbl ()
4195 "Unconditionally turn on `orgtbl-mode'."
4196 (require 'org-table)
4197 (orgtbl-mode 1))
4199 (defun org-at-table-p (&optional table-type)
4200 "Return t if the cursor is inside an org-type table.
4201 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4202 (if org-enable-table-editor
4203 (save-excursion
4204 (beginning-of-line 1)
4205 (looking-at (if table-type org-table-any-line-regexp
4206 org-table-line-regexp)))
4207 nil))
4208 (defsubst org-table-p () (org-at-table-p))
4210 (defun org-at-table.el-p ()
4211 "Return t if and only if we are at a table.el table."
4212 (and (org-at-table-p 'any)
4213 (save-excursion
4214 (goto-char (org-table-begin 'any))
4215 (looking-at org-table1-hline-regexp))))
4217 (defun org-table-recognize-table.el ()
4218 "If there is a table.el table nearby, recognize it and move into it."
4219 (if org-table-tab-recognizes-table.el
4220 (if (org-at-table.el-p)
4221 (progn
4222 (beginning-of-line 1)
4223 (if (looking-at org-table-dataline-regexp)
4225 (if (looking-at org-table1-hline-regexp)
4226 (progn
4227 (beginning-of-line 2)
4228 (if (looking-at org-table-any-border-regexp)
4229 (beginning-of-line -1)))))
4230 (if (re-search-forward "|" (org-table-end t) t)
4231 (progn
4232 (require 'table)
4233 (if (table--at-cell-p (point))
4235 (message "recognizing table.el table...")
4236 (table-recognize-table)
4237 (message "recognizing table.el table...done")))
4238 (error "This should not happen"))
4240 nil)
4241 nil))
4243 (defun org-at-table-hline-p ()
4244 "Return t if the cursor is inside a hline in a table."
4245 (if org-enable-table-editor
4246 (save-excursion
4247 (beginning-of-line 1)
4248 (looking-at org-table-hline-regexp))
4249 nil))
4251 (defvar org-table-clean-did-remove-column nil)
4252 (defun org-table-map-tables (function &optional quietly)
4253 "Apply FUNCTION to the start of all tables in the buffer."
4254 (save-excursion
4255 (save-restriction
4256 (widen)
4257 (goto-char (point-min))
4258 (while (re-search-forward org-table-any-line-regexp nil t)
4259 (unless quietly
4260 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4261 (beginning-of-line 1)
4262 (when (and (looking-at org-table-line-regexp)
4263 ;; Exclude tables in src/example/verbatim/clocktable blocks
4264 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4265 (save-excursion (funcall function))
4266 (or (looking-at org-table-line-regexp)
4267 (forward-char 1)))
4268 (re-search-forward org-table-any-border-regexp nil 1))))
4269 (unless quietly (message "Mapping tables: done")))
4271 ;; Declare and autoload functions from ox.el and al.
4273 (declare-function org-export-get-environment "ox"
4274 (&optional backend subtreep ext-plist))
4275 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4277 ;; Declare and autoload functions from org-agenda.el
4279 (eval-and-compile
4280 (org-autoload "org-agenda"
4281 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4283 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4284 (declare-function org-clock-update-mode-line "org-clock" ())
4285 (declare-function org-resolve-clocks "org-clock"
4286 (&optional also-non-dangling-p prompt last-valid))
4287 (defvar org-clock-start-time)
4288 (defvar org-clock-marker (make-marker)
4289 "Marker recording the last clock-in.")
4290 (defvar org-clock-hd-marker (make-marker)
4291 "Marker recording the last clock-in, but the headline position.")
4292 (defvar org-clock-heading ""
4293 "The heading of the current clock entry.")
4294 (defun org-clock-is-active ()
4295 "Return non-nil if clock is currently running.
4296 The return value is actually the clock marker."
4297 (marker-buffer org-clock-marker))
4299 (eval-and-compile
4300 (org-autoload "org-clock" '(org-clock-remove-overlays
4301 org-clock-update-time-maybe
4302 org-clocktable-shift)))
4304 (defun org-check-running-clock ()
4305 "Check if the current buffer contains the running clock.
4306 If yes, offer to stop it and to save the buffer with the changes."
4307 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4308 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4309 (buffer-name))))
4310 (org-clock-out)
4311 (when (y-or-n-p "Save changed buffer?")
4312 (save-buffer))))
4314 (defun org-clocktable-try-shift (dir n)
4315 "Check if this line starts a clock table, if yes, shift the time block."
4316 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4317 (org-clocktable-shift dir n)))
4319 ;;;###autoload
4320 (defun org-clock-persistence-insinuate ()
4321 "Set up hooks for clock persistence."
4322 (require 'org-clock)
4323 (add-hook 'org-mode-hook 'org-clock-load)
4324 (add-hook 'kill-emacs-hook 'org-clock-save))
4326 ;; Define the variable already here, to make sure we have it.
4327 (defvar org-indent-mode nil
4328 "Non-nil if Org-Indent mode is enabled.
4329 Use the command `org-indent-mode' to change this variable.")
4331 ;; Autoload archiving code
4332 ;; The stuff that is needed for cycling and tags has to be defined here.
4334 (defgroup org-archive nil
4335 "Options concerning archiving in Org-mode."
4336 :tag "Org Archive"
4337 :group 'org-structure)
4339 (defcustom org-archive-location "%s_archive::"
4340 "The location where subtrees should be archived.
4342 The value of this variable is a string, consisting of two parts,
4343 separated by a double-colon. The first part is a filename and
4344 the second part is a headline.
4346 When the filename is omitted, archiving happens in the same file.
4347 %s in the filename will be replaced by the current file
4348 name (without the directory part). Archiving to a different file
4349 is useful to keep archived entries from contributing to the
4350 Org-mode Agenda.
4352 The archived entries will be filed as subtrees of the specified
4353 headline. When the headline is omitted, the subtrees are simply
4354 filed away at the end of the file, as top-level entries. Also in
4355 the heading you can use %s to represent the file name, this can be
4356 useful when using the same archive for a number of different files.
4358 Here are a few examples:
4359 \"%s_archive::\"
4360 If the current file is Projects.org, archive in file
4361 Projects.org_archive, as top-level trees. This is the default.
4363 \"::* Archived Tasks\"
4364 Archive in the current file, under the top-level headline
4365 \"* Archived Tasks\".
4367 \"~/org/archive.org::\"
4368 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4370 \"~/org/archive.org::* From %s\"
4371 Archive in file ~/org/archive.org (absolute path), under headlines
4372 \"From FILENAME\" where file name is the current file name.
4374 \"~/org/datetree.org::datetree/* Finished Tasks\"
4375 The \"datetree/\" string is special, signifying to archive
4376 items to the datetree. Items are placed in either the CLOSED
4377 date of the item, or the current date if there is no CLOSED date.
4378 The heading will be a subentry to the current date. There doesn't
4379 need to be a heading, but there always needs to be a slash after
4380 datetree. For example, to store archived items directly in the
4381 datetree, use \"~/org/datetree.org::datetree/\".
4383 \"basement::** Finished Tasks\"
4384 Archive in file ./basement (relative path), as level 3 trees
4385 below the level 2 heading \"** Finished Tasks\".
4387 You may set this option on a per-file basis by adding to the buffer a
4388 line like
4390 #+ARCHIVE: basement::** Finished Tasks
4392 You may also define it locally for a subtree by setting an ARCHIVE property
4393 in the entry. If such a property is found in an entry, or anywhere up
4394 the hierarchy, it will be used."
4395 :group 'org-archive
4396 :type 'string)
4398 (defcustom org-archive-tag "ARCHIVE"
4399 "The tag that marks a subtree as archived.
4400 An archived subtree does not open during visibility cycling, and does
4401 not contribute to the agenda listings.
4402 After changing this, font-lock must be restarted in the relevant buffers to
4403 get the proper fontification."
4404 :group 'org-archive
4405 :group 'org-keywords
4406 :type 'string)
4408 (defcustom org-agenda-skip-archived-trees t
4409 "Non-nil means the agenda will skip any items located in archived trees.
4410 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4411 variable is no longer recommended, you should leave it at the value t.
4412 Instead, use the key `v' to cycle the archives-mode in the agenda."
4413 :group 'org-archive
4414 :group 'org-agenda-skip
4415 :type 'boolean)
4417 (defcustom org-columns-skip-archived-trees t
4418 "Non-nil means ignore archived trees when creating column view."
4419 :group 'org-archive
4420 :group 'org-properties
4421 :type 'boolean)
4423 (defcustom org-cycle-open-archived-trees nil
4424 "Non-nil means `org-cycle' will open archived trees.
4425 An archived tree is a tree marked with the tag ARCHIVE.
4426 When nil, archived trees will stay folded. You can still open them with
4427 normal outline commands like `show-all', but not with the cycling commands."
4428 :group 'org-archive
4429 :group 'org-cycle
4430 :type 'boolean)
4432 (defcustom org-sparse-tree-open-archived-trees nil
4433 "Non-nil means sparse tree construction shows matches in archived trees.
4434 When nil, matches in these trees are highlighted, but the trees are kept in
4435 collapsed state."
4436 :group 'org-archive
4437 :group 'org-sparse-trees
4438 :type 'boolean)
4440 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4441 "The default date type when building a sparse tree.
4442 When this is nil, a date is a scheduled or a deadline timestamp.
4443 Otherwise, these types are allowed:
4445 all: all timestamps
4446 active: only active timestamps (<...>)
4447 inactive: only inactive timestamps (<...)
4448 scheduled: only scheduled timestamps
4449 deadline: only deadline timestamps"
4450 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4451 (const :tag "All timestamps" all)
4452 (const :tag "Only active timestamps" active)
4453 (const :tag "Only inactive timestamps" inactive)
4454 (const :tag "Only scheduled timestamps" scheduled)
4455 (const :tag "Only deadline timestamps" deadline))
4456 :version "24.3"
4457 :group 'org-sparse-trees)
4459 (defun org-cycle-hide-archived-subtrees (state)
4460 "Re-hide all archived subtrees after a visibility state change."
4461 (when (and (not org-cycle-open-archived-trees)
4462 (not (memq state '(overview folded))))
4463 (save-excursion
4464 (let* ((globalp (memq state '(contents all)))
4465 (beg (if globalp (point-min) (point)))
4466 (end (if globalp (point-max) (org-end-of-subtree t))))
4467 (org-hide-archived-subtrees beg end)
4468 (goto-char beg)
4469 (if (looking-at (concat ".*:" org-archive-tag ":"))
4470 (message "%s" (substitute-command-keys
4471 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4473 (defun org-force-cycle-archived ()
4474 "Cycle subtree even if it is archived."
4475 (interactive)
4476 (setq this-command 'org-cycle)
4477 (let ((org-cycle-open-archived-trees t))
4478 (call-interactively 'org-cycle)))
4480 (defun org-hide-archived-subtrees (beg end)
4481 "Re-hide all archived subtrees after a visibility state change."
4482 (save-excursion
4483 (let* ((re (concat ":" org-archive-tag ":")))
4484 (goto-char beg)
4485 (while (re-search-forward re end t)
4486 (when (org-at-heading-p)
4487 (org-flag-subtree t)
4488 (org-end-of-subtree t))))))
4490 (declare-function outline-end-of-heading "outline" ())
4491 (declare-function outline-flag-region "outline" (from to flag))
4492 (defun org-flag-subtree (flag)
4493 (save-excursion
4494 (org-back-to-heading t)
4495 (outline-end-of-heading)
4496 (outline-flag-region (point)
4497 (progn (org-end-of-subtree t) (point))
4498 flag)))
4500 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4502 (eval-and-compile
4503 (org-autoload "org-archive"
4504 '(org-add-archive-files)))
4506 ;; Autoload Column View Code
4508 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4509 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4510 (declare-function org-columns-compute "org-colview" (property))
4512 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4513 '(org-columns-number-to-string
4514 org-columns-get-format-and-top-level
4515 org-columns-compute
4516 org-columns-remove-overlays))
4518 ;; Autoload ID code
4520 (declare-function org-id-store-link "org-id")
4521 (declare-function org-id-locations-load "org-id")
4522 (declare-function org-id-locations-save "org-id")
4523 (defvar org-id-track-globally)
4524 (org-autoload "org-id"
4525 '(org-id-new
4526 org-id-copy
4527 org-id-get-with-outline-path-completion
4528 org-id-get-with-outline-drilling))
4530 ;;; Variables for pre-computed regular expressions, all buffer local
4532 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4533 "Matches first line of a hidden block.")
4534 (make-variable-buffer-local 'org-drawer-regexp)
4535 (defvar org-todo-regexp nil
4536 "Matches any of the TODO state keywords.")
4537 (make-variable-buffer-local 'org-todo-regexp)
4538 (defvar org-not-done-regexp nil
4539 "Matches any of the TODO state keywords except the last one.")
4540 (make-variable-buffer-local 'org-not-done-regexp)
4541 (defvar org-not-done-heading-regexp nil
4542 "Matches a TODO headline that is not done.")
4543 (make-variable-buffer-local 'org-not-done-regexp)
4544 (defvar org-todo-line-regexp nil
4545 "Matches a headline and puts TODO state into group 2 if present.")
4546 (make-variable-buffer-local 'org-todo-line-regexp)
4547 (defvar org-complex-heading-regexp nil
4548 "Matches a headline and puts everything into groups:
4549 group 1: the stars
4550 group 2: The todo keyword, maybe
4551 group 3: Priority cookie
4552 group 4: True headline
4553 group 5: Tags")
4554 (make-variable-buffer-local 'org-complex-heading-regexp)
4555 (defvar org-complex-heading-regexp-format nil
4556 "Printf format to make regexp to match an exact headline.
4557 This regexp will match the headline of any node which has the
4558 exact headline text that is put into the format, but may have any
4559 TODO state, priority and tags.")
4560 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4561 (defvar org-todo-line-tags-regexp nil
4562 "Matches a headline and puts TODO state into group 2 if present.
4563 Also put tags into group 4 if tags are present.")
4564 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4565 (defvar org-ds-keyword-length 12
4566 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4567 (make-variable-buffer-local 'org-ds-keyword-length)
4568 (defvar org-deadline-regexp nil
4569 "Matches the DEADLINE keyword.")
4570 (make-variable-buffer-local 'org-deadline-regexp)
4571 (defvar org-deadline-time-regexp nil
4572 "Matches the DEADLINE keyword together with a time stamp.")
4573 (make-variable-buffer-local 'org-deadline-time-regexp)
4574 (defvar org-deadline-line-regexp nil
4575 "Matches the DEADLINE keyword and the rest of the line.")
4576 (make-variable-buffer-local 'org-deadline-line-regexp)
4577 (defvar org-scheduled-regexp nil
4578 "Matches the SCHEDULED keyword.")
4579 (make-variable-buffer-local 'org-scheduled-regexp)
4580 (defvar org-scheduled-time-regexp nil
4581 "Matches the SCHEDULED keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-regexp)
4583 (defvar org-closed-time-regexp nil
4584 "Matches the CLOSED keyword together with a time stamp.")
4585 (make-variable-buffer-local 'org-closed-time-regexp)
4587 (defvar org-keyword-time-regexp nil
4588 "Matches any of the 4 keywords, together with the time stamp.")
4589 (make-variable-buffer-local 'org-keyword-time-regexp)
4590 (defvar org-keyword-time-not-clock-regexp nil
4591 "Matches any of the 3 keywords, together with the time stamp.")
4592 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4593 (defvar org-maybe-keyword-time-regexp nil
4594 "Matches a timestamp, possibly preceded by a keyword.")
4595 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4596 (defvar org-all-time-keywords nil
4597 "List of time keywords.")
4598 (make-variable-buffer-local 'org-all-time-keywords)
4600 (defconst org-plain-time-of-day-regexp
4601 (concat
4602 "\\(\\<[012]?[0-9]"
4603 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4604 "\\(--?"
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\)?")
4608 "Regular expression to match a plain time or time range.
4609 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4610 groups carry important information:
4611 0 the full match
4612 1 the first time, range or not
4613 8 the second time, if it is a range.")
4615 (defconst org-plain-time-extension-regexp
4616 (concat
4617 "\\(\\<[012]?[0-9]"
4618 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4619 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4620 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4621 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4622 groups carry important information:
4623 0 the full match
4624 7 hours of duration
4625 9 minutes of duration")
4627 (defconst org-stamp-time-of-day-regexp
4628 (concat
4629 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4630 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4631 "\\(--?"
4632 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4633 "Regular expression to match a timestamp time or time range.
4634 After a match, the following groups carry important information:
4635 0 the full match
4636 1 date plus weekday, for back referencing to make sure both times are on the same day
4637 2 the first time, range or not
4638 4 the second time, if it is a range.")
4640 (defconst org-startup-options
4641 '(("fold" org-startup-folded t)
4642 ("overview" org-startup-folded t)
4643 ("nofold" org-startup-folded nil)
4644 ("showall" org-startup-folded nil)
4645 ("showeverything" org-startup-folded showeverything)
4646 ("content" org-startup-folded content)
4647 ("indent" org-startup-indented t)
4648 ("noindent" org-startup-indented nil)
4649 ("hidestars" org-hide-leading-stars t)
4650 ("showstars" org-hide-leading-stars nil)
4651 ("odd" org-odd-levels-only t)
4652 ("oddeven" org-odd-levels-only nil)
4653 ("align" org-startup-align-all-tables t)
4654 ("noalign" org-startup-align-all-tables nil)
4655 ("inlineimages" org-startup-with-inline-images t)
4656 ("noinlineimages" org-startup-with-inline-images nil)
4657 ("latexpreview" org-startup-with-latex-preview t)
4658 ("nolatexpreview" org-startup-with-latex-preview nil)
4659 ("customtime" org-display-custom-times t)
4660 ("logdone" org-log-done time)
4661 ("lognotedone" org-log-done note)
4662 ("nologdone" org-log-done nil)
4663 ("lognoteclock-out" org-log-note-clock-out t)
4664 ("nolognoteclock-out" org-log-note-clock-out nil)
4665 ("logrepeat" org-log-repeat state)
4666 ("lognoterepeat" org-log-repeat note)
4667 ("logdrawer" org-log-into-drawer t)
4668 ("nologdrawer" org-log-into-drawer nil)
4669 ("logstatesreversed" org-log-states-order-reversed t)
4670 ("nologstatesreversed" org-log-states-order-reversed nil)
4671 ("nologrepeat" org-log-repeat nil)
4672 ("logreschedule" org-log-reschedule time)
4673 ("lognotereschedule" org-log-reschedule note)
4674 ("nologreschedule" org-log-reschedule nil)
4675 ("logredeadline" org-log-redeadline time)
4676 ("lognoteredeadline" org-log-redeadline note)
4677 ("nologredeadline" org-log-redeadline nil)
4678 ("logrefile" org-log-refile time)
4679 ("lognoterefile" org-log-refile note)
4680 ("nologrefile" org-log-refile nil)
4681 ("fninline" org-footnote-define-inline t)
4682 ("nofninline" org-footnote-define-inline nil)
4683 ("fnlocal" org-footnote-section nil)
4684 ("fnauto" org-footnote-auto-label t)
4685 ("fnprompt" org-footnote-auto-label nil)
4686 ("fnconfirm" org-footnote-auto-label confirm)
4687 ("fnplain" org-footnote-auto-label plain)
4688 ("fnadjust" org-footnote-auto-adjust t)
4689 ("nofnadjust" org-footnote-auto-adjust nil)
4690 ("constcgs" constants-unit-system cgs)
4691 ("constSI" constants-unit-system SI)
4692 ("noptag" org-tag-persistent-alist nil)
4693 ("hideblocks" org-hide-block-startup t)
4694 ("nohideblocks" org-hide-block-startup nil)
4695 ("beamer" org-startup-with-beamer-mode t)
4696 ("entitiespretty" org-pretty-entities t)
4697 ("entitiesplain" org-pretty-entities nil))
4698 "Variable associated with STARTUP options for org-mode.
4699 Each element is a list of three items: the startup options (as written
4700 in the #+STARTUP line), the corresponding variable, and the value to set
4701 this variable to if the option is found. An optional forth element PUSH
4702 means to push this value onto the list in the variable.")
4704 (defun org-update-property-plist (key val props)
4705 "Update PROPS with KEY and VAL."
4706 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4707 (key (if appending (substring key 0 (- (length key) 1)) key))
4708 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4709 (previous (cdr (assoc key props))))
4710 (if appending
4711 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4712 (cons (cons key val) remainder))))
4714 (defconst org-block-regexp
4715 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4716 "Regular expression for hiding blocks.")
4717 (defconst org-heading-keyword-regexp-format
4718 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4719 "Printf format for a regexp matching a headline with some keyword.
4720 This regexp will match the headline of any node which has the
4721 exact keyword that is put into the format. The keyword isn't in
4722 any group by default, but the stars and the body are.")
4723 (defconst org-heading-keyword-maybe-regexp-format
4724 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4725 "Printf format for a regexp matching a headline, possibly with some keyword.
4726 This regexp can match any headline with the specified keyword, or
4727 without a keyword. The keyword isn't in any group by default,
4728 but the stars and the body are.")
4730 (defun org-set-regexps-and-options ()
4731 "Precompute regular expressions for current buffer."
4732 (when (derived-mode-p 'org-mode)
4733 (org-set-local 'org-todo-kwd-alist nil)
4734 (org-set-local 'org-todo-key-alist nil)
4735 (org-set-local 'org-todo-key-trigger nil)
4736 (org-set-local 'org-todo-keywords-1 nil)
4737 (org-set-local 'org-done-keywords nil)
4738 (org-set-local 'org-todo-heads nil)
4739 (org-set-local 'org-todo-sets nil)
4740 (org-set-local 'org-todo-log-states nil)
4741 (org-set-local 'org-file-properties nil)
4742 (org-set-local 'org-file-tags nil)
4743 (let ((re (org-make-options-regexp
4744 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4745 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4746 "SETUPFILE" "OPTIONS")
4747 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4748 (splitre "[ \t]+")
4749 (scripts org-use-sub-superscripts)
4750 kwds kws0 kwsa key log value cat arch tags const links hw dws
4751 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4752 (start 0))
4753 (save-excursion
4754 (save-restriction
4755 (widen)
4756 (goto-char (point-min))
4757 (while (or (and ext-setup-or-nil
4758 (string-match re ext-setup-or-nil start)
4759 (setq start (match-end 0)))
4760 (and (setq ext-setup-or-nil nil start 0)
4761 (re-search-forward re nil t)))
4762 (setq key (upcase (match-string 1 ext-setup-or-nil))
4763 value (org-match-string-no-properties 2 ext-setup-or-nil))
4764 (if (stringp value) (setq value (org-trim value)))
4765 (cond
4766 ((equal key "CATEGORY")
4767 (setq cat value))
4768 ((member key '("SEQ_TODO" "TODO"))
4769 (push (cons 'sequence (org-split-string value splitre)) kwds))
4770 ((equal key "TYP_TODO")
4771 (push (cons 'type (org-split-string value splitre)) kwds))
4772 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4773 ;; general TODO-like setup
4774 (push (cons (intern (downcase (match-string 1 key)))
4775 (org-split-string value splitre)) kwds))
4776 ((equal key "TAGS")
4777 (setq tags (append tags (if tags '("\\n") nil)
4778 (org-split-string value splitre))))
4779 ((equal key "COLUMNS")
4780 (org-set-local 'org-columns-default-format value))
4781 ((equal key "LINK")
4782 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4783 (push (cons (match-string 1 value)
4784 (org-trim (match-string 2 value)))
4785 links)))
4786 ((equal key "PRIORITIES")
4787 (setq prio (org-split-string value " +")))
4788 ((equal key "PROPERTY")
4789 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4790 (setq props (org-update-property-plist (match-string 1 value)
4791 (match-string 2 value)
4792 props))))
4793 ((equal key "FILETAGS")
4794 (when (string-match "\\S-" value)
4795 (setq ftags
4796 (append
4797 ftags
4798 (apply 'append
4799 (mapcar (lambda (x) (org-split-string x ":"))
4800 (org-split-string value)))))))
4801 ((equal key "DRAWERS")
4802 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4803 ((equal key "CONSTANTS")
4804 (setq const (append const (org-split-string value splitre))))
4805 ((equal key "STARTUP")
4806 (let ((opts (org-split-string value splitre))
4807 l var val)
4808 (while (setq l (pop opts))
4809 (when (setq l (assoc l org-startup-options))
4810 (setq var (nth 1 l) val (nth 2 l))
4811 (if (not (nth 3 l))
4812 (set (make-local-variable var) val)
4813 (if (not (listp (symbol-value var)))
4814 (set (make-local-variable var) nil))
4815 (set (make-local-variable var) (symbol-value var))
4816 (add-to-list var val))))))
4817 ((equal key "ARCHIVE")
4818 (setq arch value)
4819 (remove-text-properties 0 (length arch)
4820 '(face t fontified t) arch))
4821 ((equal key "OPTIONS")
4822 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4823 (setq scripts (read (match-string 2 value)))))
4824 ((equal key "SETUPFILE")
4825 (setq setup-contents (org-file-contents
4826 (expand-file-name
4827 (org-remove-double-quotes value))
4828 'noerror))
4829 (if (not ext-setup-or-nil)
4830 (setq ext-setup-or-nil setup-contents start 0)
4831 (setq ext-setup-or-nil
4832 (concat (substring ext-setup-or-nil 0 start)
4833 "\n" setup-contents "\n"
4834 (substring ext-setup-or-nil start)))))))
4835 ;; search for property blocks
4836 (goto-char (point-min))
4837 (while (re-search-forward org-block-regexp nil t)
4838 (when (equal "PROPERTY" (upcase (match-string 1)))
4839 (setq value (replace-regexp-in-string
4840 "[\n\r]" " " (match-string 4)))
4841 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4842 (setq props (org-update-property-plist (match-string 1 value)
4843 (match-string 2 value)
4844 props)))))))
4845 (org-set-local 'org-use-sub-superscripts scripts)
4846 (when cat
4847 (org-set-local 'org-category (intern cat))
4848 (push (cons "CATEGORY" cat) props))
4849 (when prio
4850 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4851 (setq prio (mapcar 'string-to-char prio))
4852 (org-set-local 'org-highest-priority (nth 0 prio))
4853 (org-set-local 'org-lowest-priority (nth 1 prio))
4854 (org-set-local 'org-default-priority (nth 2 prio)))
4855 (and props (org-set-local 'org-file-properties (nreverse props)))
4856 (and ftags (org-set-local 'org-file-tags
4857 (mapcar 'org-add-prop-inherited ftags)))
4858 (and drawers (org-set-local 'org-drawers drawers))
4859 (and arch (org-set-local 'org-archive-location arch))
4860 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4861 ;; Process the TODO keywords
4862 (unless kwds
4863 ;; Use the global values as if they had been given locally.
4864 (setq kwds (default-value 'org-todo-keywords))
4865 (if (stringp (car kwds))
4866 (setq kwds (list (cons org-todo-interpretation
4867 (default-value 'org-todo-keywords)))))
4868 (setq kwds (reverse kwds)))
4869 (setq kwds (nreverse kwds))
4870 (let (inter kws kw)
4871 (while (setq kws (pop kwds))
4872 (let ((kws (or
4873 (run-hook-with-args-until-success
4874 'org-todo-setup-filter-hook kws)
4875 kws)))
4876 (setq inter (pop kws) sep (member "|" kws)
4877 kws0 (delete "|" (copy-sequence kws))
4878 kwsa nil
4879 kws1 (mapcar
4880 (lambda (x)
4881 ;; 1 2
4882 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4883 (progn
4884 (setq kw (match-string 1 x)
4885 key (and (match-end 2) (match-string 2 x))
4886 log (org-extract-log-state-settings x))
4887 (push (cons kw (and key (string-to-char key))) kwsa)
4888 (and log (push log org-todo-log-states))
4890 (error "Invalid TODO keyword %s" x)))
4891 kws0)
4892 kwsa (if kwsa (append '((:startgroup))
4893 (nreverse kwsa)
4894 '((:endgroup))))
4895 hw (car kws1)
4896 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4897 tail (list inter hw (car dws) (org-last dws))))
4898 (add-to-list 'org-todo-heads hw 'append)
4899 (push kws1 org-todo-sets)
4900 (setq org-done-keywords (append org-done-keywords dws nil))
4901 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4902 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4903 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4904 (setq org-todo-sets (nreverse org-todo-sets)
4905 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4906 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4907 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4908 ;; Process the constants
4909 (when const
4910 (let (e cst)
4911 (while (setq e (pop const))
4912 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4913 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4914 (setq org-table-formula-constants-local cst)))
4916 ;; Process the tags.
4917 (when tags
4918 (let (e tgs)
4919 (while (setq e (pop tags))
4920 (cond
4921 ((equal e "{") (push '(:startgroup) tgs))
4922 ((equal e "}") (push '(:endgroup) tgs))
4923 ((equal e "\\n") (push '(:newline) tgs))
4924 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4925 (push (cons (match-string 1 e)
4926 (string-to-char (match-string 2 e)))
4927 tgs))
4928 (t (push (list e) tgs))))
4929 (org-set-local 'org-tag-alist nil)
4930 (while (setq e (pop tgs))
4931 (or (and (stringp (car e))
4932 (assoc (car e) org-tag-alist))
4933 (push e org-tag-alist)))))
4935 ;; Compute the regular expressions and other local variables.
4936 ;; Using `org-outline-regexp-bol' would complicate them much,
4937 ;; because of the fixed white space at the end of that string.
4938 (if (not org-done-keywords)
4939 (setq org-done-keywords (and org-todo-keywords-1
4940 (list (org-last org-todo-keywords-1)))))
4941 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4942 (length org-scheduled-string)
4943 (length org-clock-string)
4944 (length org-closed-string)))
4945 org-drawer-regexp
4946 (concat "^[ \t]*:\\("
4947 (mapconcat 'regexp-quote org-drawers "\\|")
4948 "\\):[ \t]*$")
4949 org-not-done-keywords
4950 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4951 org-todo-regexp
4952 (concat "\\("
4953 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4954 "\\)")
4955 org-not-done-regexp
4956 (concat "\\("
4957 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4958 "\\)")
4959 org-not-done-heading-regexp
4960 (format org-heading-keyword-regexp-format org-not-done-regexp)
4961 org-todo-line-regexp
4962 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4963 org-complex-heading-regexp
4964 (concat "^\\(\\*+\\)"
4965 "\\(?: +" org-todo-regexp "\\)?"
4966 "\\(?: +\\(\\[#.\\]\\)\\)?"
4967 "\\(?: +\\(.*?\\)\\)??"
4968 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4969 "[ \t]*$")
4970 org-complex-heading-regexp-format
4971 (concat "^\\(\\*+\\)"
4972 "\\(?: +" org-todo-regexp "\\)?"
4973 "\\(?: +\\(\\[#.\\]\\)\\)?"
4974 "\\(?: +"
4975 ;; Stats cookies can be stuck to body.
4976 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4977 "\\(%s\\)"
4978 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4979 "\\)"
4980 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4981 "[ \t]*$")
4982 org-todo-line-tags-regexp
4983 (concat "^\\(\\*+\\)"
4984 "\\(?: +" org-todo-regexp "\\)?"
4985 "\\(?: +\\(.*?\\)\\)??"
4986 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4987 "[ \t]*$")
4988 org-deadline-regexp (concat "\\<" org-deadline-string)
4989 org-deadline-time-regexp
4990 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4991 org-deadline-line-regexp
4992 (concat "\\<\\(" org-deadline-string "\\).*")
4993 org-scheduled-regexp
4994 (concat "\\<" org-scheduled-string)
4995 org-scheduled-time-regexp
4996 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4997 org-closed-time-regexp
4998 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4999 org-keyword-time-regexp
5000 (concat "\\<\\(" org-scheduled-string
5001 "\\|" org-deadline-string
5002 "\\|" org-closed-string
5003 "\\|" org-clock-string "\\)"
5004 " *[[<]\\([^]>]+\\)[]>]")
5005 org-keyword-time-not-clock-regexp
5006 (concat "\\<\\(" org-scheduled-string
5007 "\\|" org-deadline-string
5008 "\\|" org-closed-string
5009 "\\)"
5010 " *[[<]\\([^]>]+\\)[]>]")
5011 org-maybe-keyword-time-regexp
5012 (concat "\\(\\<\\(" org-scheduled-string
5013 "\\|" org-deadline-string
5014 "\\|" org-closed-string
5015 "\\|" org-clock-string "\\)\\)?"
5016 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5017 org-all-time-keywords
5018 (mapcar (lambda (w) (substring w 0 -1))
5019 (list org-scheduled-string org-deadline-string
5020 org-clock-string org-closed-string)))
5021 (org-compute-latex-and-related-regexp)
5022 (org-set-font-lock-defaults))))
5024 (defun org-file-contents (file &optional noerror)
5025 "Return the contents of FILE, as a string."
5026 (if (or (not file)
5027 (not (file-readable-p file)))
5028 (if noerror
5029 (progn
5030 (message "Cannot read file \"%s\"" file)
5031 (ding) (sit-for 2)
5033 (error "Cannot read file \"%s\"" file))
5034 (with-temp-buffer
5035 (insert-file-contents file)
5036 (buffer-string))))
5038 (defun org-extract-log-state-settings (x)
5039 "Extract the log state setting from a TODO keyword string.
5040 This will extract info from a string like \"WAIT(w@/!)\"."
5041 (let (kw key log1 log2)
5042 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log1 (and (match-end 3) (match-string 3 x))
5046 log2 (and (match-end 4) (match-string 4 x)))
5047 (and (or log1 log2)
5048 (list kw
5049 (and log1 (if (equal log1 "!") 'time 'note))
5050 (and log2 (if (equal log2 "!") 'time 'note)))))))
5052 (defun org-remove-keyword-keys (list)
5053 "Remove a pair of parenthesis at the end of each string in LIST."
5054 (mapcar (lambda (x)
5055 (if (string-match "(.*)$" x)
5056 (substring x 0 (match-beginning 0))
5058 list))
5060 (defun org-assign-fast-keys (alist)
5061 "Assign fast keys to a keyword-key alist.
5062 Respect keys that are already there."
5063 (let (new e (alt ?0))
5064 (while (setq e (pop alist))
5065 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5066 (cdr e)) ;; Key already assigned.
5067 (push e new)
5068 (let ((clist (string-to-list (downcase (car e))))
5069 (used (append new alist)))
5070 (when (= (car clist) ?@)
5071 (pop clist))
5072 (while (and clist (rassoc (car clist) used))
5073 (pop clist))
5074 (unless clist
5075 (while (rassoc alt used)
5076 (incf alt)))
5077 (push (cons (car e) (or (car clist) alt)) new))))
5078 (nreverse new)))
5080 ;;; Some variables used in various places
5082 (defvar org-window-configuration nil
5083 "Used in various places to store a window configuration.")
5084 (defvar org-selected-window nil
5085 "Used in various places to store a window configuration.")
5086 (defvar org-finish-function nil
5087 "Function to be called when `C-c C-c' is used.
5088 This is for getting out of special buffers like capture.")
5091 ;; FIXME: Occasionally check by commenting these, to make sure
5092 ;; no other functions uses these, forgetting to let-bind them.
5093 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5094 (defvar org-last-state)
5095 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5097 ;; Defined somewhere in this file, but used before definition.
5098 (defvar org-entities) ;; defined in org-entities.el
5099 (defvar org-struct-menu)
5100 (defvar org-org-menu)
5101 (defvar org-tbl-menu)
5103 ;;;; Define the Org-mode
5105 ;; We use a before-change function to check if a table might need
5106 ;; an update.
5107 (defvar org-table-may-need-update t
5108 "Indicates that a table might need an update.
5109 This variable is set by `org-before-change-function'.
5110 `org-table-align' sets it back to nil.")
5111 (defun org-before-change-function (beg end)
5112 "Every change indicates that a table might need an update."
5113 (setq org-table-may-need-update t))
5114 (defvar org-mode-map)
5115 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5116 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5117 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5118 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5119 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5120 (defvar org-table-buffer-is-an nil)
5122 (defvar bidi-paragraph-direction)
5123 (defvar buffer-face-mode-face)
5125 (require 'outline)
5126 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5127 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5128 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5130 ;; Other stuff we need.
5131 (require 'time-date)
5132 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5133 (require 'easymenu)
5134 (require 'overlay)
5136 ;; (require 'org-macs) moved higher up in the file before it is first used
5137 (require 'org-entities)
5138 ;; (require 'org-compat) moved higher up in the file before it is first used
5139 (require 'org-faces)
5140 (require 'org-list)
5141 (require 'org-pcomplete)
5142 (require 'org-src)
5143 (require 'org-footnote)
5144 (require 'org-macro)
5146 ;; babel
5147 (require 'ob)
5149 ;;;###autoload
5150 (define-derived-mode org-mode outline-mode "Org"
5151 "Outline-based notes management and organizer, alias
5152 \"Carsten's outline-mode for keeping track of everything.\"
5154 Org-mode develops organizational tasks around a NOTES file which
5155 contains information about projects as plain text. Org-mode is
5156 implemented on top of outline-mode, which is ideal to keep the content
5157 of large files well structured. It supports ToDo items, deadlines and
5158 time stamps, which magically appear in the diary listing of the Emacs
5159 calendar. Tables are easily created with a built-in table editor.
5160 Plain text URL-like links connect to websites, emails (VM), Usenet
5161 messages (Gnus), BBDB entries, and any files related to the project.
5162 For printing and sharing of notes, an Org-mode file (or a part of it)
5163 can be exported as a structured ASCII or HTML file.
5165 The following commands are available:
5167 \\{org-mode-map}"
5169 ;; Get rid of Outline menus, they are not needed
5170 ;; Need to do this here because define-derived-mode sets up
5171 ;; the keymap so late. Still, it is a waste to call this each time
5172 ;; we switch another buffer into org-mode.
5173 (if (featurep 'xemacs)
5174 (when (boundp 'outline-mode-menu-heading)
5175 ;; Assume this is Greg's port, it uses easymenu
5176 (easy-menu-remove outline-mode-menu-heading)
5177 (easy-menu-remove outline-mode-menu-show)
5178 (easy-menu-remove outline-mode-menu-hide))
5179 (define-key org-mode-map [menu-bar headings] 'undefined)
5180 (define-key org-mode-map [menu-bar hide] 'undefined)
5181 (define-key org-mode-map [menu-bar show] 'undefined))
5183 (org-load-modules-maybe)
5184 (easy-menu-add org-org-menu)
5185 (easy-menu-add org-tbl-menu)
5186 (org-install-agenda-files-menu)
5187 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5188 (add-to-invisibility-spec '(org-cwidth))
5189 (add-to-invisibility-spec '(org-hide-block . t))
5190 (when (featurep 'xemacs)
5191 (org-set-local 'line-move-ignore-invisible t))
5192 (org-set-local 'outline-regexp org-outline-regexp)
5193 (org-set-local 'outline-level 'org-outline-level)
5194 (setq bidi-paragraph-direction 'left-to-right)
5195 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5196 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5197 (when (and org-ellipsis
5198 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5199 (fboundp 'make-glyph-code))
5200 (unless org-display-table
5201 (setq org-display-table (make-display-table)))
5202 (set-display-table-slot
5203 org-display-table 4
5204 (vconcat (mapcar
5205 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5206 org-ellipsis)))
5207 (if (stringp org-ellipsis) org-ellipsis "..."))))
5208 (setq buffer-display-table org-display-table))
5209 (org-set-regexps-and-options)
5210 (when (and org-tag-faces (not org-tags-special-faces-re))
5211 ;; tag faces set outside customize.... force initialization.
5212 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5213 ;; Calc embedded
5214 (org-set-local 'calc-embedded-open-mode "# ")
5215 ;; Modify a few syntax entries
5216 (modify-syntax-entry ?@ "w")
5217 (modify-syntax-entry ?\" "\"")
5218 (if org-startup-truncated (setq truncate-lines t))
5219 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5220 (org-set-local 'font-lock-unfontify-region-function
5221 'org-unfontify-region)
5222 ;; Activate before-change-function
5223 (org-set-local 'org-table-may-need-update t)
5224 (org-add-hook 'before-change-functions 'org-before-change-function nil
5225 'local)
5226 ;; Check for running clock before killing a buffer
5227 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5228 ;; Initialize macros templates.
5229 (org-macro-initialize-templates)
5230 ;; Initialize radio targets.
5231 (org-update-radio-target-regexp)
5232 ;; Indentation.
5233 (org-set-local 'indent-line-function 'org-indent-line)
5234 (org-set-local 'indent-region-function 'org-indent-region)
5235 ;; Filling and auto-filling.
5236 (org-setup-filling)
5237 ;; Comments.
5238 (org-setup-comments-handling)
5239 ;; Beginning/end of defun
5240 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5241 (org-set-local 'end-of-defun-function 'org-forward-element)
5242 ;; Next error for sparse trees
5243 (org-set-local 'next-error-function 'org-occur-next-match)
5244 ;; Make sure dependence stuff works reliably, even for users who set it
5245 ;; too late :-(
5246 (if org-enforce-todo-dependencies
5247 (add-hook 'org-blocker-hook
5248 'org-block-todo-from-children-or-siblings-or-parent)
5249 (remove-hook 'org-blocker-hook
5250 'org-block-todo-from-children-or-siblings-or-parent))
5251 (if org-enforce-todo-checkbox-dependencies
5252 (add-hook 'org-blocker-hook
5253 'org-block-todo-from-checkboxes)
5254 (remove-hook 'org-blocker-hook
5255 'org-block-todo-from-checkboxes))
5257 ;; Align options lines
5258 (org-set-local
5259 'align-mode-rules-list
5260 '((org-in-buffer-settings
5261 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5262 (modes . '(org-mode)))))
5264 ;; Imenu
5265 (org-set-local 'imenu-create-index-function
5266 'org-imenu-get-tree)
5268 ;; Make isearch reveal context
5269 (if (or (featurep 'xemacs)
5270 (not (boundp 'outline-isearch-open-invisible-function)))
5271 ;; Emacs 21 and XEmacs make use of the hook
5272 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5273 ;; Emacs 22 deals with this through a special variable
5274 (org-set-local 'outline-isearch-open-invisible-function
5275 (lambda (&rest ignore) (org-show-context 'isearch)))
5276 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5278 ;; Setup the pcomplete hooks
5279 (set (make-local-variable 'pcomplete-command-completion-function)
5280 'org-pcomplete-initial)
5281 (set (make-local-variable 'pcomplete-command-name-function)
5282 'org-command-at-point)
5283 (set (make-local-variable 'pcomplete-default-completion-function)
5284 'ignore)
5285 (set (make-local-variable 'pcomplete-parse-arguments-function)
5286 'org-parse-arguments)
5287 (set (make-local-variable 'pcomplete-termination-string) "")
5288 (when (>= emacs-major-version 23)
5289 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5291 ;; If empty file that did not turn on org-mode automatically, make it to.
5292 (if (and org-insert-mode-line-in-empty-file
5293 (org-called-interactively-p 'any)
5294 (= (point-min) (point-max)))
5295 (insert "# -*- mode: org -*-\n\n"))
5296 (unless org-inhibit-startup
5297 (org-unmodified
5298 (and org-startup-with-beamer-mode (org-beamer-mode))
5299 (when org-startup-align-all-tables
5300 (org-table-map-tables 'org-table-align 'quietly))
5301 (when org-startup-with-inline-images
5302 (org-display-inline-images))
5303 (when org-startup-with-latex-preview
5304 (org-preview-latex-fragment))
5305 (unless org-inhibit-startup-visibility-stuff
5306 (org-set-startup-visibility))))
5307 ;; Try to set org-hide correctly
5308 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5310 (defvar org-mode-transpose-word-syntax-table
5311 (let ((st (make-syntax-table)))
5312 (mapc (lambda(c) (modify-syntax-entry
5313 (string-to-char (car c)) "w p" st))
5314 org-emphasis-alist)
5315 st))
5317 (when (fboundp 'abbrev-table-put)
5318 (abbrev-table-put org-mode-abbrev-table
5319 :parents (list text-mode-abbrev-table)))
5321 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5323 (defsubst org-fix-ellipsis-at-bol ()
5324 (save-excursion (goto-char (window-start)) (recenter 0)))
5326 (defun org-find-invisible-foreground ()
5327 (let ((candidates (remove
5328 "unspecified-bg"
5329 (nconc
5330 (list (face-background 'default)
5331 (face-background 'org-default))
5332 (mapcar
5333 (lambda (alist)
5334 (when (boundp alist)
5335 (cdr (assoc 'background-color (symbol-value alist)))))
5336 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5337 (list (face-foreground 'org-hide))))))
5338 (car (remove nil candidates))))
5340 (defun org-current-time (&optional rounding-minutes past)
5341 "Current time, possibly rounded to ROUNDING-MINUTES.
5342 When ROUNDING-MINUTES is not an integer, fall back on the car of
5343 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5344 the rounding returns a past time."
5345 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5346 (car org-time-stamp-rounding-minutes)))
5347 (time (decode-time)) res)
5348 (if (< r 1)
5349 (current-time)
5350 (setq res
5351 (apply 'encode-time
5352 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5353 (nthcdr 2 time))))
5354 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5355 (seconds-to-time (- (org-float-time res) (* r 60)))
5356 res))))
5358 (defun org-today ()
5359 "Return today date, considering `org-extend-today-until'."
5360 (time-to-days
5361 (time-subtract (current-time)
5362 (list 0 (* 3600 org-extend-today-until) 0))))
5364 ;;;; Font-Lock stuff, including the activators
5366 (defvar org-mouse-map (make-sparse-keymap))
5367 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5368 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5369 (when org-mouse-1-follows-link
5370 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5371 (when org-tab-follows-link
5372 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5373 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5375 (require 'font-lock)
5377 (defconst org-non-link-chars "]\t\n\r<>")
5378 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5379 "shell" "elisp" "doi" "message"))
5380 (defvar org-link-types-re nil
5381 "Matches a link that has a url-like prefix like \"http:\"")
5382 (defvar org-link-re-with-space nil
5383 "Matches a link with spaces, optional angular brackets around it.")
5384 (defvar org-link-re-with-space2 nil
5385 "Matches a link with spaces, optional angular brackets around it.")
5386 (defvar org-link-re-with-space3 nil
5387 "Matches a link with spaces, only for internal part in bracket links.")
5388 (defvar org-angle-link-re nil
5389 "Matches link with angular brackets, spaces are allowed.")
5390 (defvar org-plain-link-re nil
5391 "Matches plain link, without spaces.")
5392 (defvar org-bracket-link-regexp nil
5393 "Matches a link in double brackets.")
5394 (defvar org-bracket-link-analytic-regexp nil
5395 "Regular expression used to analyze links.
5396 Here is what the match groups contain after a match:
5397 1: http:
5398 2: http
5399 3: path
5400 4: [desc]
5401 5: desc")
5402 (defvar org-bracket-link-analytic-regexp++ nil
5403 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5404 (defvar org-any-link-re nil
5405 "Regular expression matching any link.")
5407 (defconst org-match-sexp-depth 3
5408 "Number of stacked braces for sub/superscript matching.")
5410 (defun org-create-multibrace-regexp (left right n)
5411 "Create a regular expression which will match a balanced sexp.
5412 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5413 as single character strings.
5414 The regexp returned will match the entire expression including the
5415 delimiters. It will also define a single group which contains the
5416 match except for the outermost delimiters. The maximum depth of
5417 stacked delimiters is N. Escaping delimiters is not possible."
5418 (let* ((nothing (concat "[^" left right "]*?"))
5419 (or "\\|")
5420 (re nothing)
5421 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5422 (while (> n 1)
5423 (setq n (1- n)
5424 re (concat re or next)
5425 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5426 (concat left "\\(" re "\\)" right)))
5428 (defvar org-match-substring-regexp
5429 (concat
5430 "\\(\\S-\\)\\([_^]\\)\\("
5431 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5432 "\\|"
5433 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5434 "\\|"
5435 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5436 "The regular expression matching a sub- or superscript.")
5438 (defvar org-match-substring-with-braces-regexp
5439 (concat
5440 "\\(\\S-\\)\\([_^]\\)\\("
5441 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5442 "\\)")
5443 "The regular expression matching a sub- or superscript, forcing braces.")
5445 (defun org-make-link-regexps ()
5446 "Update the link regular expressions.
5447 This should be called after the variable `org-link-types' has changed."
5448 (setq org-link-types-re
5449 (concat
5450 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5451 org-link-re-with-space
5452 (concat
5453 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5454 "\\([^" org-non-link-chars " ]"
5455 "[^" org-non-link-chars "]*"
5456 "[^" org-non-link-chars " ]\\)>?")
5457 org-link-re-with-space2
5458 (concat
5459 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5460 "\\([^" org-non-link-chars " ]"
5461 "[^\t\n\r]*"
5462 "[^" org-non-link-chars " ]\\)>?")
5463 org-link-re-with-space3
5464 (concat
5465 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5466 "\\([^" org-non-link-chars " ]"
5467 "[^\t\n\r]*\\)")
5468 org-angle-link-re
5469 (concat
5470 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5471 "\\([^" org-non-link-chars " ]"
5472 "[^" org-non-link-chars "]*"
5473 "\\)>")
5474 org-plain-link-re
5475 (concat
5476 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5477 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5478 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5479 org-bracket-link-regexp
5480 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5481 org-bracket-link-analytic-regexp
5482 (concat
5483 "\\[\\["
5484 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5485 "\\([^]]+\\)"
5486 "\\]"
5487 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5488 "\\]")
5489 org-bracket-link-analytic-regexp++
5490 (concat
5491 "\\[\\["
5492 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5493 "\\([^]]+\\)"
5494 "\\]"
5495 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5496 "\\]")
5497 org-any-link-re
5498 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5499 org-angle-link-re "\\)\\|\\("
5500 org-plain-link-re "\\)")))
5502 (org-make-link-regexps)
5504 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5505 "Regular expression for fast time stamp matching.")
5506 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5507 "Regular expression for fast time stamp matching.")
5508 (defconst org-ts-regexp0
5509 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5510 "Regular expression matching time strings for analysis.
5511 This one does not require the space after the date, so it can be used
5512 on a string that terminates immediately after the date.")
5513 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5514 "Regular expression matching time strings for analysis.")
5515 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5516 "Regular expression matching time stamps, with groups.")
5517 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5518 "Regular expression matching time stamps (also [..]), with groups.")
5519 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5520 "Regular expression matching a time stamp range.")
5521 (defconst org-tr-regexp-both
5522 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5523 "Regular expression matching a time stamp range.")
5524 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5525 org-ts-regexp "\\)?")
5526 "Regular expression matching a time stamp or time stamp range.")
5527 (defconst org-tsr-regexp-both
5528 (concat org-ts-regexp-both "\\(--?-?"
5529 org-ts-regexp-both "\\)?")
5530 "Regular expression matching a time stamp or time stamp range.
5531 The time stamps may be either active or inactive.")
5533 (defvar org-emph-face nil)
5535 (defun org-do-emphasis-faces (limit)
5536 "Run through the buffer and add overlays to emphasized strings."
5537 (let (rtn a)
5538 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5539 (if (not (= (char-after (match-beginning 3))
5540 (char-after (match-beginning 4))))
5541 (progn
5542 (setq rtn t)
5543 (setq a (assoc (match-string 3) org-emphasis-alist))
5544 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5545 'face
5546 (nth 1 a))
5547 (and (nth 4 a)
5548 (org-remove-flyspell-overlays-in
5549 (match-beginning 0) (match-end 0)))
5550 (add-text-properties (match-beginning 2) (match-end 2)
5551 '(font-lock-multiline t org-emphasis t))
5552 (when org-hide-emphasis-markers
5553 (add-text-properties (match-end 4) (match-beginning 5)
5554 '(invisible org-link))
5555 (add-text-properties (match-beginning 3) (match-end 3)
5556 '(invisible org-link)))))
5557 (backward-char 1))
5558 rtn))
5560 (defun org-emphasize (&optional char)
5561 "Insert or change an emphasis, i.e. a font like bold or italic.
5562 If there is an active region, change that region to a new emphasis.
5563 If there is no region, just insert the marker characters and position
5564 the cursor between them.
5565 CHAR should be either the marker character, or the first character of the
5566 HTML tag associated with that emphasis. If CHAR is a space, the means
5567 to remove the emphasis of the selected region.
5568 If char is not given (for example in an interactive call) it
5569 will be prompted for."
5570 (interactive)
5571 (let ((eal org-emphasis-alist) e det
5572 (erc org-emphasis-regexp-components)
5573 (prompt "")
5574 (string "") beg end move tag c s)
5575 (if (org-region-active-p)
5576 (setq beg (region-beginning) end (region-end)
5577 string (buffer-substring beg end))
5578 (setq move t))
5580 (while (setq e (pop eal))
5581 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5582 c (aref tag 0))
5583 (push (cons c (string-to-char (car e))) det)
5584 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5585 (substring tag 1)))))
5586 (setq det (nreverse det))
5587 (unless char
5588 (message "%s" (concat "Emphasis marker or tag:" prompt))
5589 (setq char (read-char-exclusive)))
5590 (setq char (or (cdr (assoc char det)) char))
5591 (if (equal char ?\ )
5592 (setq s "" move nil)
5593 (unless (assoc (char-to-string char) org-emphasis-alist)
5594 (error "No such emphasis marker: \"%c\"" char))
5595 (setq s (char-to-string char)))
5596 (while (and (> (length string) 1)
5597 (equal (substring string 0 1) (substring string -1))
5598 (assoc (substring string 0 1) org-emphasis-alist))
5599 (setq string (substring string 1 -1)))
5600 (setq string (concat s string s))
5601 (if beg (delete-region beg end))
5602 (unless (or (bolp)
5603 (string-match (concat "[" (nth 0 erc) "\n]")
5604 (char-to-string (char-before (point)))))
5605 (insert " "))
5606 (unless (or (eobp)
5607 (string-match (concat "[" (nth 1 erc) "\n]")
5608 (char-to-string (char-after (point)))))
5609 (insert " ") (backward-char 1))
5610 (insert string)
5611 (and move (backward-char 1))))
5613 (defconst org-nonsticky-props
5614 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5616 (defsubst org-rear-nonsticky-at (pos)
5617 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5619 (defun org-activate-plain-links (limit)
5620 "Run through the buffer and add overlays to links."
5621 (let (f hl)
5622 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5623 (not (org-in-src-block-p)))
5624 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5625 (setq f (get-text-property (match-beginning 0) 'face))
5626 (setq hl (org-match-string-no-properties 0))
5627 (if (or (eq f 'org-tag)
5628 (and (listp f) (memq 'org-tag f)))
5630 (add-text-properties (match-beginning 0) (match-end 0)
5631 (list 'mouse-face 'highlight
5632 'face 'org-link
5633 'htmlize-link `(:uri ,hl)
5634 'keymap org-mouse-map))
5635 (org-rear-nonsticky-at (match-end 0)))
5636 t)))
5638 (defun org-activate-code (limit)
5639 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5640 (progn
5641 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5642 (remove-text-properties (match-beginning 0) (match-end 0)
5643 '(display t invisible t intangible t))
5644 t)))
5646 (defcustom org-src-fontify-natively nil
5647 "When non-nil, fontify code in code blocks."
5648 :type 'boolean
5649 :version "24.1"
5650 :group 'org-appearance
5651 :group 'org-babel)
5653 (defcustom org-allow-promoting-top-level-subtree nil
5654 "When non-nil, allow promoting a top level subtree.
5655 The leading star of the top level headline will be replaced
5656 by a #."
5657 :type 'boolean
5658 :version "24.1"
5659 :group 'org-appearance)
5661 (defun org-fontify-meta-lines-and-blocks (limit)
5662 (condition-case nil
5663 (org-fontify-meta-lines-and-blocks-1 limit)
5664 (error (message "org-mode fontification error"))))
5666 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5667 "Fontify #+ lines and blocks, in the correct ways."
5668 (let ((case-fold-search t))
5669 (if (re-search-forward
5670 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5671 limit t)
5672 (let ((beg (match-beginning 0))
5673 (block-start (match-end 0))
5674 (block-end nil)
5675 (lang (match-string 7))
5676 (beg1 (line-beginning-position 2))
5677 (dc1 (downcase (match-string 2)))
5678 (dc3 (downcase (match-string 3)))
5679 end end1 quoting block-type ovl)
5680 (cond
5681 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5682 ;; a single line of backend-specific content
5683 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5684 (remove-text-properties (match-beginning 0) (match-end 0)
5685 '(display t invisible t intangible t))
5686 (add-text-properties (match-beginning 1) (match-end 3)
5687 '(font-lock-fontified t face org-meta-line))
5688 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5689 '(font-lock-fontified t face org-block))
5690 ; for backend-specific code
5692 ((and (match-end 4) (equal dc3 "+begin"))
5693 ;; Truly a block
5694 (setq block-type (downcase (match-string 5))
5695 quoting (member block-type org-protecting-blocks))
5696 (when (re-search-forward
5697 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5698 nil t) ;; on purpose, we look further than LIMIT
5699 (setq end (min (point-max) (match-end 0))
5700 end1 (min (point-max) (1- (match-beginning 0))))
5701 (setq block-end (match-beginning 0))
5702 (when quoting
5703 (remove-text-properties beg end
5704 '(display t invisible t intangible t)))
5705 (add-text-properties
5706 beg end
5707 '(font-lock-fontified t font-lock-multiline t))
5708 (add-text-properties beg beg1 '(face org-meta-line))
5709 (add-text-properties end1 (min (point-max) (1+ end))
5710 '(face org-meta-line)) ; for end_src
5711 (cond
5712 ((and lang (not (string= lang "")) org-src-fontify-natively)
5713 (org-src-font-lock-fontify-block lang block-start block-end)
5714 ;; remove old background overlays
5715 (mapc (lambda (ov)
5716 (if (eq (overlay-get ov 'face) 'org-block-background)
5717 (delete-overlay ov)))
5718 (overlays-at (/ (+ beg1 block-end) 2)))
5719 ;; add a background overlay
5720 (setq ovl (make-overlay beg1 block-end))
5721 (overlay-put ovl 'face 'org-block-background)
5722 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5723 (quoting
5724 (add-text-properties beg1 (min (point-max) (1+ end1))
5725 '(face org-block))) ; end of source block
5726 ((not org-fontify-quote-and-verse-blocks))
5727 ((string= block-type "quote")
5728 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5729 ((string= block-type "verse")
5730 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5731 (add-text-properties beg beg1 '(face org-block-begin-line))
5732 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5733 '(face org-block-end-line))
5735 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5736 (add-text-properties
5737 beg (match-end 3)
5738 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5739 '(font-lock-fontified t invisible t)
5740 '(font-lock-fontified t face org-document-info-keyword)))
5741 (add-text-properties
5742 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5743 (if (string-equal dc1 "+title:")
5744 '(font-lock-fontified t face org-document-title)
5745 '(font-lock-fontified t face org-document-info))))
5746 ((or (equal dc1 "+results")
5747 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5748 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5749 "+call:" "+header:" "+headers:" "+name:"))
5750 (and (match-end 4) (equal dc3 "+attr")))
5751 (add-text-properties
5752 beg (match-end 0)
5753 '(font-lock-fontified t face org-meta-line))
5755 ((member dc3 '(" " ""))
5756 (add-text-properties
5757 beg (match-end 0)
5758 '(font-lock-fontified t face font-lock-comment-face)))
5759 ((not (member (char-after beg) '(?\ ?\t)))
5760 ;; just any other in-buffer setting, but not indented
5761 (add-text-properties
5762 beg (match-end 0)
5763 '(font-lock-fontified t face org-meta-line))
5765 (t nil))))))
5767 (defun org-activate-angle-links (limit)
5768 "Run through the buffer and add overlays to links."
5769 (if (and (re-search-forward org-angle-link-re limit t)
5770 (not (org-in-src-block-p)))
5771 (progn
5772 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5773 (add-text-properties (match-beginning 0) (match-end 0)
5774 (list 'mouse-face 'highlight
5775 'keymap org-mouse-map))
5776 (org-rear-nonsticky-at (match-end 0))
5777 t)))
5779 (defun org-activate-footnote-links (limit)
5780 "Run through the buffer and add overlays to footnotes."
5781 (let ((fn (org-footnote-next-reference-or-definition limit)))
5782 (when fn
5783 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5784 (org-remove-flyspell-overlays-in beg end)
5785 (add-text-properties beg end
5786 (list 'mouse-face 'highlight
5787 'keymap org-mouse-map
5788 'help-echo
5789 (if (= (point-at-bol) beg)
5790 "Footnote definition"
5791 "Footnote reference")
5792 'font-lock-fontified t
5793 'font-lock-multiline t
5794 'face 'org-footnote))))))
5796 (defun org-activate-bracket-links (limit)
5797 "Run through the buffer and add overlays to bracketed links."
5798 (if (and (re-search-forward org-bracket-link-regexp limit t)
5799 (not (org-in-src-block-p)))
5800 (let* ((hl (org-match-string-no-properties 1))
5801 (help (concat "LINK: " hl))
5802 ;; FIXME: Above we should remove the escapes. But that
5803 ;; requires another match, protecting match data, a lot
5804 ;; of overhead for font-lock.
5805 (ip (org-maybe-intangible
5806 (list 'invisible 'org-link
5807 'keymap org-mouse-map 'mouse-face 'highlight
5808 'font-lock-multiline t 'help-echo help
5809 'htmlize-link `(:uri ,hl))))
5810 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5811 'font-lock-multiline t 'help-echo help
5812 'htmlize-link `(:uri ,hl))))
5813 ;; We need to remove the invisible property here. Table narrowing
5814 ;; may have made some of this invisible.
5815 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5816 (remove-text-properties (match-beginning 0) (match-end 0)
5817 '(invisible nil))
5818 (if (match-end 3)
5819 (progn
5820 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5821 (org-rear-nonsticky-at (match-beginning 3))
5822 (add-text-properties (match-beginning 3) (match-end 3) vp)
5823 (org-rear-nonsticky-at (match-end 3))
5824 (add-text-properties (match-end 3) (match-end 0) ip)
5825 (org-rear-nonsticky-at (match-end 0)))
5826 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5827 (org-rear-nonsticky-at (match-beginning 1))
5828 (add-text-properties (match-beginning 1) (match-end 1) vp)
5829 (org-rear-nonsticky-at (match-end 1))
5830 (add-text-properties (match-end 1) (match-end 0) ip)
5831 (org-rear-nonsticky-at (match-end 0)))
5832 t)))
5834 (defun org-activate-dates (limit)
5835 "Run through the buffer and add overlays to dates."
5836 (if (and (re-search-forward org-tsr-regexp-both limit t)
5837 (not (equal (char-before (match-beginning 0)) 91)))
5838 (progn
5839 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5840 (add-text-properties (match-beginning 0) (match-end 0)
5841 (list 'mouse-face 'highlight
5842 'keymap org-mouse-map))
5843 (org-rear-nonsticky-at (match-end 0))
5844 (when org-display-custom-times
5845 (if (match-end 3)
5846 (org-display-custom-time (match-beginning 3) (match-end 3)))
5847 (org-display-custom-time (match-beginning 1) (match-end 1)))
5848 t)))
5850 (defvar org-target-link-regexp nil
5851 "Regular expression matching radio targets in plain text.")
5852 (make-variable-buffer-local 'org-target-link-regexp)
5853 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5854 "Regular expression matching a link target.")
5855 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5856 "Regular expression matching a radio target.")
5857 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5858 "Regular expression matching any target.")
5860 (defun org-activate-target-links (limit)
5861 "Run through the buffer and add overlays to target matches."
5862 (when org-target-link-regexp
5863 (let ((case-fold-search t))
5864 (if (re-search-forward org-target-link-regexp limit t)
5865 (progn
5866 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5867 (add-text-properties (match-beginning 0) (match-end 0)
5868 (list 'mouse-face 'highlight
5869 'keymap org-mouse-map
5870 'help-echo "Radio target link"
5871 'org-linked-text t))
5872 (org-rear-nonsticky-at (match-end 0))
5873 t)))))
5875 (defun org-update-radio-target-regexp ()
5876 "Find all radio targets in this file and update the regular expression."
5877 (interactive)
5878 (when (memq 'radio org-activate-links)
5879 (setq org-target-link-regexp
5880 (org-make-target-link-regexp (org-all-targets 'radio)))
5881 (org-restart-font-lock)))
5883 (defun org-hide-wide-columns (limit)
5884 (let (s e)
5885 (setq s (text-property-any (point) (or limit (point-max))
5886 'org-cwidth t))
5887 (when s
5888 (setq e (next-single-property-change s 'org-cwidth))
5889 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5890 (goto-char e)
5891 t)))
5893 (defvar org-latex-and-related-regexp nil
5894 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5895 (defvar org-match-substring-regexp)
5896 (defvar org-match-substring-with-braces-regexp)
5898 (defun org-compute-latex-and-related-regexp ()
5899 "Compute regular expression for LaTeX, entities and sub/superscript.
5900 Result depends on variable `org-highlight-latex-and-related'."
5901 (org-set-local
5902 'org-latex-and-related-regexp
5903 (let* ((re-sub
5904 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5905 ((eq org-use-sub-superscripts '{})
5906 (list org-match-substring-with-braces-regexp))
5907 (org-use-sub-superscripts (list org-match-substring-regexp))))
5908 (re-latex
5909 (when (memq 'latex org-highlight-latex-and-related)
5910 (let ((matchers (plist-get org-format-latex-options :matchers)))
5911 (delq nil
5912 (mapcar (lambda (x)
5913 (and (member (car x) matchers) (nth 1 x)))
5914 org-latex-regexps)))))
5915 (re-entities
5916 (when (memq 'entities org-highlight-latex-and-related)
5917 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5918 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5920 (defun org-do-latex-and-related (limit)
5921 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5922 LIMIT bounds the search for syntax to highlight. Stop at first
5923 highlighted object, if any. Return t if some highlighting was
5924 done, nil otherwise."
5925 (when (org-string-nw-p org-latex-and-related-regexp)
5926 (catch 'found
5927 (while (re-search-forward org-latex-and-related-regexp limit t)
5928 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5929 'face))
5930 '(org-code org-verbatim underline))
5931 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5932 '(?_ ?^))
5934 0)))
5935 (font-lock-prepend-text-property
5936 (+ offset (match-beginning 0)) (match-end 0)
5937 'face 'org-latex-and-related)
5938 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5939 '(font-lock-multiline t)))
5940 (throw 'found t)))
5941 nil)))
5943 (defun org-restart-font-lock ()
5944 "Restart `font-lock-mode', to force refontification."
5945 (when (and (boundp 'font-lock-mode) font-lock-mode)
5946 (font-lock-mode -1)
5947 (font-lock-mode 1)))
5949 (defun org-all-targets (&optional radio)
5950 "Return a list of all targets in this file.
5951 When optional argument RADIO is non-nil, only find radio
5952 targets."
5953 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5954 (save-excursion
5955 (goto-char (point-min))
5956 (while (re-search-forward re nil t)
5957 ;; Make sure point is really within the object.
5958 (backward-char)
5959 (let ((obj (org-element-context)))
5960 (when (memq (org-element-type obj) '(radio-target target))
5961 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5962 rtn)))
5964 (defun org-make-target-link-regexp (targets)
5965 "Make regular expression matching all strings in TARGETS.
5966 The regular expression finds the targets also if there is a line break
5967 between words."
5968 (and targets
5969 (concat
5970 "\\<\\("
5971 (mapconcat
5972 (lambda (x)
5973 (setq x (regexp-quote x))
5974 (while (string-match " +" x)
5975 (setq x (replace-match "\\s-+" t t x)))
5977 targets
5978 "\\|")
5979 "\\)\\>")))
5981 (defun org-activate-tags (limit)
5982 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5983 (progn
5984 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5985 (add-text-properties (match-beginning 1) (match-end 1)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map))
5988 (org-rear-nonsticky-at (match-end 1))
5989 t)))
5991 (defun org-outline-level ()
5992 "Compute the outline level of the heading at point.
5993 If this is called at a normal headline, the level is the number of stars.
5994 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5995 (save-excursion
5996 (if (not (condition-case nil
5997 (org-back-to-heading t)
5998 (error nil)))
6000 (looking-at org-outline-regexp)
6001 (1- (- (match-end 0) (match-beginning 0))))))
6003 (defvar org-font-lock-keywords nil)
6005 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6006 "Regular expression matching a property line.")
6008 (defvar org-font-lock-hook nil
6009 "Functions to be called for special font lock stuff.")
6011 (defvar org-font-lock-set-keywords-hook nil
6012 "Functions that can manipulate `org-font-lock-extra-keywords'.
6013 This is called after `org-font-lock-extra-keywords' is defined, but before
6014 it is installed to be used by font lock. This can be useful if something
6015 needs to be inserted at a specific position in the font-lock sequence.")
6017 (defun org-font-lock-hook (limit)
6018 "Run `org-font-lock-hook' within LIMIT."
6019 (run-hook-with-args 'org-font-lock-hook limit))
6021 (defun org-set-font-lock-defaults ()
6022 "Set font lock defaults for the current buffer."
6023 (let* ((em org-fontify-emphasized-text)
6024 (lk org-activate-links)
6025 (org-font-lock-extra-keywords
6026 (list
6027 ;; Call the hook
6028 '(org-font-lock-hook)
6029 ;; Headlines
6030 `(,(if org-fontify-whole-heading-line
6031 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6032 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6033 (1 (org-get-level-face 1))
6034 (2 (org-get-level-face 2))
6035 (3 (org-get-level-face 3)))
6036 ;; Table lines
6037 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6038 (1 'org-table t))
6039 ;; Table internals
6040 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6041 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6042 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6043 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6044 ;; Drawers
6045 (list org-drawer-regexp '(0 'org-special-keyword t))
6046 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6047 ;; Properties
6048 (list org-property-re
6049 '(1 'org-special-keyword t)
6050 '(3 'org-property-value t))
6051 ;; Links
6052 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6053 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6054 (if (memq 'plain lk) '(org-activate-plain-links))
6055 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6056 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6057 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6058 (if (memq 'footnote lk) '(org-activate-footnote-links))
6059 ;; Targets.
6060 (list org-any-target-regexp '(0 'org-target t))
6061 ;; Diary sexps.
6062 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6063 '(org-hide-wide-columns (0 nil append))
6064 ;; TODO keyword
6065 (list (format org-heading-keyword-regexp-format
6066 org-todo-regexp)
6067 '(2 (org-get-todo-face 2) t))
6068 ;; DONE
6069 (if org-fontify-done-headline
6070 (list (format org-heading-keyword-regexp-format
6071 (concat
6072 "\\(?:"
6073 (mapconcat 'regexp-quote org-done-keywords "\\|")
6074 "\\)"))
6075 '(2 'org-headline-done t))
6076 nil)
6077 ;; Priorities
6078 '(org-font-lock-add-priority-faces)
6079 ;; Tags
6080 '(org-font-lock-add-tag-faces)
6081 ;; Special keywords
6082 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6083 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6084 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6085 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6086 ;; Emphasis
6087 (if em
6088 (if (featurep 'xemacs)
6089 '(org-do-emphasis-faces (0 nil append))
6090 '(org-do-emphasis-faces)))
6091 ;; Checkboxes
6092 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6093 1 'org-checkbox prepend)
6094 (if (cdr (assq 'checkbox org-list-automatic-rules))
6095 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6096 (0 (org-get-checkbox-statistics-face) t)))
6097 ;; Description list items
6098 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6099 1 'org-list-dt prepend)
6100 ;; ARCHIVEd headings
6101 (list (concat
6102 org-outline-regexp-bol
6103 "\\(.*:" org-archive-tag ":.*\\)")
6104 '(1 'org-archived prepend))
6105 ;; Specials
6106 '(org-do-latex-and-related)
6107 '(org-fontify-entities)
6108 '(org-raise-scripts)
6109 ;; Code
6110 '(org-activate-code (1 'org-code t))
6111 ;; COMMENT
6112 (list (format org-heading-keyword-regexp-format
6113 (concat "\\("
6114 org-comment-string "\\|" org-quote-string
6115 "\\)"))
6116 '(2 'org-special-keyword t))
6117 ;; Blocks and meta lines
6118 '(org-fontify-meta-lines-and-blocks)
6120 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6121 (run-hooks 'org-font-lock-set-keywords-hook)
6122 ;; Now set the full font-lock-keywords
6123 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6124 (org-set-local 'font-lock-defaults
6125 '(org-font-lock-keywords t nil nil backward-paragraph))
6126 (kill-local-variable 'font-lock-keywords) nil))
6128 (defun org-toggle-pretty-entities ()
6129 "Toggle the composition display of entities as UTF8 characters."
6130 (interactive)
6131 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6132 (org-restart-font-lock)
6133 (if org-pretty-entities
6134 (message "Entities are displayed as UTF8 characters")
6135 (save-restriction
6136 (widen)
6137 (org-decompose-region (point-min) (point-max))
6138 (message "Entities are displayed plain"))))
6140 (defvar org-custom-properties-overlays nil
6141 "List of overlays used for custom properties.")
6142 (make-variable-buffer-local 'org-custom-properties-overlays)
6144 (defun org-toggle-custom-properties-visibility ()
6145 "Display or hide properties in `org-custom-properties'."
6146 (interactive)
6147 (if org-custom-properties-overlays
6148 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6149 (setq org-custom-properties-overlays nil))
6150 (unless (not org-custom-properties)
6151 (save-excursion
6152 (save-restriction
6153 (widen)
6154 (goto-char (point-min))
6155 (while (re-search-forward org-property-re nil t)
6156 (mapc (lambda(p)
6157 (when (equal p (substring (match-string 1) 1 -1))
6158 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6159 (overlay-put o 'invisible t)
6160 (overlay-put o 'org-custom-property t)
6161 (push o org-custom-properties-overlays))))
6162 org-custom-properties)))))))
6164 (defun org-fontify-entities (limit)
6165 "Find an entity to fontify."
6166 (let (ee)
6167 (when org-pretty-entities
6168 (catch 'match
6169 (while (re-search-forward
6170 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6171 limit t)
6172 (if (and (not (org-in-indented-comment-line))
6173 (setq ee (org-entity-get (match-string 1)))
6174 (= (length (nth 6 ee)) 1))
6175 (let*
6176 ((end (if (equal (match-string 2) "{}")
6177 (match-end 2)
6178 (match-end 1))))
6179 (add-text-properties
6180 (match-beginning 0) end
6181 (list 'font-lock-fontified t))
6182 (compose-region (match-beginning 0) end
6183 (nth 6 ee) nil)
6184 (backward-char 1)
6185 (throw 'match t))))
6186 nil))))
6188 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6189 "Fontify string S like in Org-mode."
6190 (with-temp-buffer
6191 (insert s)
6192 (let ((org-odd-levels-only odd-levels))
6193 (org-mode)
6194 (font-lock-fontify-buffer)
6195 (buffer-string))))
6197 (defvar org-m nil)
6198 (defvar org-l nil)
6199 (defvar org-f nil)
6200 (defun org-get-level-face (n)
6201 "Get the right face for match N in font-lock matching of headlines."
6202 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6203 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6204 (if org-cycle-level-faces
6205 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6206 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6207 (cond
6208 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6209 ((eq n 2) org-f)
6210 (t (if org-level-color-stars-only nil org-f))))
6213 (defun org-get-todo-face (kwd)
6214 "Get the right face for a TODO keyword KWD.
6215 If KWD is a number, get the corresponding match group."
6216 (if (numberp kwd) (setq kwd (match-string kwd)))
6217 (or (org-face-from-face-or-color
6218 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6219 (and (member kwd org-done-keywords) 'org-done)
6220 'org-todo))
6222 (defun org-face-from-face-or-color (context inherit face-or-color)
6223 "Create a face list that inherits INHERIT, but sets the foreground color.
6224 When FACE-OR-COLOR is not a string, just return it."
6225 (if (stringp face-or-color)
6226 (list :inherit inherit
6227 (cdr (assoc context org-faces-easy-properties))
6228 face-or-color)
6229 face-or-color))
6231 (defun org-font-lock-add-tag-faces (limit)
6232 "Add the special tag faces."
6233 (when (and org-tag-faces org-tags-special-faces-re)
6234 (while (re-search-forward org-tags-special-faces-re limit t)
6235 (add-text-properties (match-beginning 1) (match-end 1)
6236 (list 'face (org-get-tag-face 1)
6237 'font-lock-fontified t))
6238 (backward-char 1))))
6240 (defun org-font-lock-add-priority-faces (limit)
6241 "Add the special priority faces."
6242 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6243 (when (save-match-data (org-at-heading-p))
6244 (add-text-properties
6245 (match-beginning 0) (match-end 0)
6246 (list 'face (or (org-face-from-face-or-color
6247 'priority 'org-priority
6248 (cdr (assoc (char-after (match-beginning 1))
6249 org-priority-faces)))
6250 'org-priority)
6251 'font-lock-fontified t)))))
6253 (defun org-get-tag-face (kwd)
6254 "Get the right face for a TODO keyword KWD.
6255 If KWD is a number, get the corresponding match group."
6256 (if (numberp kwd) (setq kwd (match-string kwd)))
6257 (or (org-face-from-face-or-color
6258 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6259 'org-tag))
6261 (defun org-unfontify-region (beg end &optional maybe_loudly)
6262 "Remove fontification and activation overlays from links."
6263 (font-lock-default-unfontify-region beg end)
6264 (let* ((buffer-undo-list t)
6265 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6266 (inhibit-modification-hooks t)
6267 deactivate-mark buffer-file-name buffer-file-truename)
6268 (org-decompose-region beg end)
6269 (remove-text-properties beg end
6270 '(mouse-face t keymap t org-linked-text t
6271 invisible t intangible t
6272 org-no-flyspell t org-emphasis t))
6273 (org-remove-font-lock-display-properties beg end)))
6275 (defconst org-script-display '(((raise -0.3) (height 0.7))
6276 ((raise 0.3) (height 0.7))
6277 ((raise -0.5))
6278 ((raise 0.5)))
6279 "Display properties for showing superscripts and subscripts.")
6281 (defun org-remove-font-lock-display-properties (beg end)
6282 "Remove specific display properties that have been added by font lock.
6283 The will remove the raise properties that are used to show superscripts
6284 and subscripts."
6285 (let (next prop)
6286 (while (< beg end)
6287 (setq next (next-single-property-change beg 'display nil end)
6288 prop (get-text-property beg 'display))
6289 (if (member prop org-script-display)
6290 (put-text-property beg next 'display nil))
6291 (setq beg next))))
6293 (defun org-raise-scripts (limit)
6294 "Add raise properties to sub/superscripts."
6295 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6296 (if (re-search-forward
6297 (if (eq org-use-sub-superscripts t)
6298 org-match-substring-regexp
6299 org-match-substring-with-braces-regexp)
6300 limit t)
6301 (let* ((pos (point)) table-p comment-p
6302 (mpos (match-beginning 3))
6303 (emph-p (get-text-property mpos 'org-emphasis))
6304 (link-p (get-text-property mpos 'mouse-face))
6305 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6306 (goto-char (point-at-bol))
6307 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6308 comment-p (org-looking-at-p "[ \t]*#"))
6309 (goto-char pos)
6310 ;; FIXME: Should we go back one character here, for a_b^c
6311 ;; (goto-char (1- pos)) ;????????????????????
6312 (if (or comment-p emph-p link-p keyw-p)
6314 (put-text-property (match-beginning 3) (match-end 0)
6315 'display
6316 (if (equal (char-after (match-beginning 2)) ?^)
6317 (nth (if table-p 3 1) org-script-display)
6318 (nth (if table-p 2 0) org-script-display)))
6319 (add-text-properties (match-beginning 2) (match-end 2)
6320 (list 'invisible t
6321 'org-dwidth t 'org-dwidth-n 1))
6322 (if (and (eq (char-after (match-beginning 3)) ?{)
6323 (eq (char-before (match-end 3)) ?}))
6324 (progn
6325 (add-text-properties
6326 (match-beginning 3) (1+ (match-beginning 3))
6327 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6328 (add-text-properties
6329 (1- (match-end 3)) (match-end 3)
6330 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6331 t)))))
6333 ;;;; Visibility cycling, including org-goto and indirect buffer
6335 ;;; Cycling
6337 (defvar org-cycle-global-status nil)
6338 (make-variable-buffer-local 'org-cycle-global-status)
6339 (put 'org-cycle-global-status 'org-state t)
6340 (defvar org-cycle-subtree-status nil)
6341 (make-variable-buffer-local 'org-cycle-subtree-status)
6342 (put 'org-cycle-subtree-status 'org-state t)
6344 (defvar org-inlinetask-min-level)
6346 ;;;###autoload
6347 (defun org-cycle (&optional arg)
6348 "TAB-action and visibility cycling for Org-mode.
6350 This is the command invoked in Org-mode by the TAB key. Its main purpose
6351 is outline visibility cycling, but it also invokes other actions
6352 in special contexts.
6354 - When this function is called with a prefix argument, rotate the entire
6355 buffer through 3 states (global cycling)
6356 1. OVERVIEW: Show only top-level headlines.
6357 2. CONTENTS: Show all headlines of all levels, but no body text.
6358 3. SHOW ALL: Show everything.
6359 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6360 determined by the variable `org-startup-folded', and by any VISIBILITY
6361 properties in the buffer.
6362 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6363 including any drawers.
6365 - When inside a table, re-align the table and move to the next field.
6367 - When point is at the beginning of a headline, rotate the subtree started
6368 by this line through 3 different states (local cycling)
6369 1. FOLDED: Only the main headline is shown.
6370 2. CHILDREN: The main headline and the direct children are shown.
6371 From this state, you can move to one of the children
6372 and zoom in further.
6373 3. SUBTREE: Show the entire subtree, including body text.
6374 If there is no subtree, switch directly from CHILDREN to FOLDED.
6376 - When point is at the beginning of an empty headline and the variable
6377 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6378 of the headline by demoting and promoting it to likely levels. This
6379 speeds up creation document structure by pressing TAB once or several
6380 times right after creating a new headline.
6382 - When there is a numeric prefix, go up to a heading with level ARG, do
6383 a `show-subtree' and return to the previous cursor position. If ARG
6384 is negative, go up that many levels.
6386 - When point is not at the beginning of a headline, execute the global
6387 binding for TAB, which is re-indenting the line. See the option
6388 `org-cycle-emulate-tab' for details.
6390 - Special case: if point is at the beginning of the buffer and there is
6391 no headline in line 1, this function will act as if called with prefix arg
6392 (C-u TAB, same as S-TAB) also when called without prefix arg.
6393 But only if also the variable `org-cycle-global-at-bob' is t."
6394 (interactive "P")
6395 (org-load-modules-maybe)
6396 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6397 (and org-cycle-level-after-item/entry-creation
6398 (or (org-cycle-level)
6399 (org-cycle-item-indentation))))
6400 (let* (message-log-max ; Don't populate the *Messages* buffer
6401 (limit-level
6402 (or org-cycle-max-level
6403 (and (boundp 'org-inlinetask-min-level)
6404 org-inlinetask-min-level
6405 (1- org-inlinetask-min-level))))
6406 (nstars (and limit-level
6407 (if org-odd-levels-only
6408 (and limit-level (1- (* limit-level 2)))
6409 limit-level)))
6410 (org-outline-regexp
6411 (if (not (derived-mode-p 'org-mode))
6412 outline-regexp
6413 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6414 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6415 (not (looking-at org-outline-regexp))))
6416 (org-cycle-hook
6417 (if bob-special
6418 (delq 'org-optimize-window-after-visibility-change
6419 (copy-sequence org-cycle-hook))
6420 org-cycle-hook))
6421 (pos (point)))
6423 (if (or bob-special (equal arg '(4)))
6424 ;; special case: use global cycling
6425 (setq arg t))
6427 (cond
6429 ((equal arg '(16))
6430 (setq last-command 'dummy)
6431 (org-set-startup-visibility)
6432 (message "Startup visibility, plus VISIBILITY properties"))
6434 ((equal arg '(64))
6435 (show-all)
6436 (message "Entire buffer visible, including drawers"))
6438 ;; Table: enter it or move to the next field.
6439 ((org-at-table-p 'any)
6440 (if (org-at-table.el-p)
6441 (message "Use C-c ' to edit table.el tables")
6442 (if arg (org-table-edit-field t)
6443 (org-table-justify-field-maybe)
6444 (call-interactively 'org-table-next-field))))
6446 ((run-hook-with-args-until-success
6447 'org-tab-after-check-for-table-hook))
6449 ;; Global cycling: delegate to `org-cycle-internal-global'.
6450 ((eq arg t) (org-cycle-internal-global))
6452 ;; Drawers: delegate to `org-flag-drawer'.
6453 ((and org-drawers org-drawer-regexp
6454 (save-excursion
6455 (beginning-of-line 1)
6456 (looking-at org-drawer-regexp)))
6457 (org-flag-drawer ; toggle block visibility
6458 (not (get-char-property (match-end 0) 'invisible))))
6460 ;; Show-subtree, ARG levels up from here.
6461 ((integerp arg)
6462 (save-excursion
6463 (org-back-to-heading)
6464 (outline-up-heading (if (< arg 0) (- arg)
6465 (- (funcall outline-level) arg)))
6466 (org-show-subtree)))
6468 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6469 ((and (featurep 'org-inlinetask)
6470 (org-inlinetask-at-task-p)
6471 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6472 (org-inlinetask-toggle-visibility))
6474 ((org-try-cdlatex-tab))
6476 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6477 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6478 (save-excursion (beginning-of-line 1)
6479 (looking-at org-outline-regexp)))
6480 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6481 (org-cycle-internal-local))
6483 ;; From there: TAB emulation and template completion.
6484 (buffer-read-only (org-back-to-heading))
6486 ((run-hook-with-args-until-success
6487 'org-tab-after-check-for-cycling-hook))
6489 ((org-try-structure-completion))
6491 ((run-hook-with-args-until-success
6492 'org-tab-before-tab-emulation-hook))
6494 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6495 (or (not (bolp))
6496 (not (looking-at org-outline-regexp))))
6497 (call-interactively (global-key-binding "\t")))
6499 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6500 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6501 (or (and (eq org-cycle-emulate-tab 'white)
6502 (= (match-end 0) (point-at-eol)))
6503 (and (eq org-cycle-emulate-tab 'whitestart)
6504 (>= (match-end 0) pos))))
6506 (eq org-cycle-emulate-tab t))
6507 (call-interactively (global-key-binding "\t")))
6509 (t (save-excursion
6510 (org-back-to-heading)
6511 (org-cycle)))))))
6513 (defun org-cycle-internal-global ()
6514 "Do the global cycling action."
6515 ;; Hack to avoid display of messages for .org attachments in Gnus
6516 (let (message-log-max ; Don't populate the *Messages* buffer
6517 (ga (string-match "\\*fontification" (buffer-name))))
6518 (cond
6519 ((and (eq last-command this-command)
6520 (eq org-cycle-global-status 'overview))
6521 ;; We just created the overview - now do table of contents
6522 ;; This can be slow in very large buffers, so indicate action
6523 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6524 (unless ga (message "CONTENTS..."))
6525 (org-content)
6526 (unless ga (message "CONTENTS...done"))
6527 (setq org-cycle-global-status 'contents)
6528 (run-hook-with-args 'org-cycle-hook 'contents))
6530 ((and (eq last-command this-command)
6531 (eq org-cycle-global-status 'contents))
6532 ;; We just showed the table of contents - now show everything
6533 (run-hook-with-args 'org-pre-cycle-hook 'all)
6534 (show-all)
6535 (unless ga (message "SHOW ALL"))
6536 (setq org-cycle-global-status 'all)
6537 (run-hook-with-args 'org-cycle-hook 'all))
6540 ;; Default action: go to overview
6541 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6542 (org-overview)
6543 (unless ga (message "OVERVIEW"))
6544 (setq org-cycle-global-status 'overview)
6545 (run-hook-with-args 'org-cycle-hook 'overview)))))
6547 (defun org-cycle-internal-local ()
6548 "Do the local cycling action."
6549 (let (message-log-max ; Don't populate the *Messages* buffer
6550 (goal-column 0) eoh eol eos has-children children-skipped struct)
6551 ;; First, determine end of headline (EOH), end of subtree or item
6552 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6553 (save-excursion
6554 (if (org-at-item-p)
6555 (progn
6556 (beginning-of-line)
6557 (setq struct (org-list-struct))
6558 (setq eoh (point-at-eol))
6559 (setq eos (org-list-get-item-end-before-blank (point) struct))
6560 (setq has-children (org-list-has-child-p (point) struct)))
6561 (org-back-to-heading)
6562 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6563 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6564 (setq has-children
6565 (or (save-excursion
6566 (let ((level (funcall outline-level)))
6567 (outline-next-heading)
6568 (and (org-at-heading-p t)
6569 (> (funcall outline-level) level))))
6570 (save-excursion
6571 (org-list-search-forward (org-item-beginning-re) eos t)))))
6572 ;; Determine end invisible part of buffer (EOL)
6573 (beginning-of-line 2)
6574 ;; XEmacs doesn't have `next-single-char-property-change'
6575 (if (featurep 'xemacs)
6576 (while (and (not (eobp)) ;; this is like `next-line'
6577 (get-char-property (1- (point)) 'invisible))
6578 (beginning-of-line 2))
6579 (while (and (not (eobp)) ;; this is like `next-line'
6580 (get-char-property (1- (point)) 'invisible))
6581 (goto-char (next-single-char-property-change (point) 'invisible))
6582 (and (eolp) (beginning-of-line 2))))
6583 (setq eol (point)))
6584 ;; Find out what to do next and set `this-command'
6585 (cond
6586 ((= eos eoh)
6587 ;; Nothing is hidden behind this heading
6588 (unless (org-before-first-heading-p)
6589 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6590 (message "EMPTY ENTRY")
6591 (setq org-cycle-subtree-status nil)
6592 (save-excursion
6593 (goto-char eos)
6594 (outline-next-heading)
6595 (if (outline-invisible-p) (org-flag-heading nil))))
6596 ((and (or (>= eol eos)
6597 (not (string-match "\\S-" (buffer-substring eol eos))))
6598 (or has-children
6599 (not (setq children-skipped
6600 org-cycle-skip-children-state-if-no-children))))
6601 ;; Entire subtree is hidden in one line: children view
6602 (unless (org-before-first-heading-p)
6603 (run-hook-with-args 'org-pre-cycle-hook 'children))
6604 (if (org-at-item-p)
6605 (org-list-set-item-visibility (point-at-bol) struct 'children)
6606 (org-show-entry)
6607 (org-with-limited-levels (show-children))
6608 ;; FIXME: This slows down the func way too much.
6609 ;; How keep drawers hidden in subtree anyway?
6610 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6611 ;; (org-cycle-hide-drawers 'subtree))
6613 ;; Fold every list in subtree to top-level items.
6614 (when (eq org-cycle-include-plain-lists 'integrate)
6615 (save-excursion
6616 (org-back-to-heading)
6617 (while (org-list-search-forward (org-item-beginning-re) eos t)
6618 (beginning-of-line 1)
6619 (let* ((struct (org-list-struct))
6620 (prevs (org-list-prevs-alist struct))
6621 (end (org-list-get-bottom-point struct)))
6622 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6623 (org-list-get-all-items (point) struct prevs))
6624 (goto-char end))))))
6625 (message "CHILDREN")
6626 (save-excursion
6627 (goto-char eos)
6628 (outline-next-heading)
6629 (if (outline-invisible-p) (org-flag-heading nil)))
6630 (setq org-cycle-subtree-status 'children)
6631 (unless (org-before-first-heading-p)
6632 (run-hook-with-args 'org-cycle-hook 'children)))
6633 ((or children-skipped
6634 (and (eq last-command this-command)
6635 (eq org-cycle-subtree-status 'children)))
6636 ;; We just showed the children, or no children are there,
6637 ;; now show everything.
6638 (unless (org-before-first-heading-p)
6639 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6640 (outline-flag-region eoh eos nil)
6641 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6642 (setq org-cycle-subtree-status 'subtree)
6643 (unless (org-before-first-heading-p)
6644 (run-hook-with-args 'org-cycle-hook 'subtree)))
6646 ;; Default action: hide the subtree.
6647 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6648 (outline-flag-region eoh eos t)
6649 (message "FOLDED")
6650 (setq org-cycle-subtree-status 'folded)
6651 (unless (org-before-first-heading-p)
6652 (run-hook-with-args 'org-cycle-hook 'folded))))))
6654 ;;;###autoload
6655 (defun org-global-cycle (&optional arg)
6656 "Cycle the global visibility. For details see `org-cycle'.
6657 With \\[universal-argument] prefix arg, switch to startup visibility.
6658 With a numeric prefix, show all headlines up to that level."
6659 (interactive "P")
6660 (let ((org-cycle-include-plain-lists
6661 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6662 (cond
6663 ((integerp arg)
6664 (show-all)
6665 (hide-sublevels arg)
6666 (setq org-cycle-global-status 'contents))
6667 ((equal arg '(4))
6668 (org-set-startup-visibility)
6669 (message "Startup visibility, plus VISIBILITY properties."))
6671 (org-cycle '(4))))))
6673 (defun org-set-startup-visibility ()
6674 "Set the visibility required by startup options and properties."
6675 (cond
6676 ((eq org-startup-folded t)
6677 (org-cycle '(4)))
6678 ((eq org-startup-folded 'content)
6679 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6680 (org-cycle '(4)) (org-cycle '(4)))))
6681 (unless (eq org-startup-folded 'showeverything)
6682 (if org-hide-block-startup (org-hide-block-all))
6683 (org-set-visibility-according-to-property 'no-cleanup)
6684 (org-cycle-hide-archived-subtrees 'all)
6685 (org-cycle-hide-drawers 'all)
6686 (org-cycle-show-empty-lines t)))
6688 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6689 "Switch subtree visibilities according to :VISIBILITY: property."
6690 (interactive)
6691 (let (org-show-entry-below state)
6692 (save-excursion
6693 (goto-char (point-min))
6694 (while (re-search-forward
6695 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6696 nil t)
6697 (setq state (match-string 1))
6698 (save-excursion
6699 (org-back-to-heading t)
6700 (hide-subtree)
6701 (org-reveal)
6702 (cond
6703 ((equal state '("fold" "folded"))
6704 (hide-subtree))
6705 ((equal state "children")
6706 (org-show-hidden-entry)
6707 (show-children))
6708 ((equal state "content")
6709 (save-excursion
6710 (save-restriction
6711 (org-narrow-to-subtree)
6712 (org-content))))
6713 ((member state '("all" "showall"))
6714 (show-subtree)))))
6715 (unless no-cleanup
6716 (org-cycle-hide-archived-subtrees 'all)
6717 (org-cycle-hide-drawers 'all)
6718 (org-cycle-show-empty-lines 'all)))))
6720 ;; This function uses outline-regexp instead of the more fundamental
6721 ;; org-outline-regexp so that org-cycle-global works outside of Org
6722 ;; buffers, where outline-regexp is needed.
6723 (defun org-overview ()
6724 "Switch to overview mode, showing only top-level headlines.
6725 Really, this shows all headlines with level equal or greater than the level
6726 of the first headline in the buffer. This is important, because if the
6727 first headline is not level one, then (hide-sublevels 1) gives confusing
6728 results."
6729 (interactive)
6730 (let ((l (org-current-line))
6731 (level (save-excursion
6732 (goto-char (point-min))
6733 (if (re-search-forward (concat "^" outline-regexp) nil t)
6734 (progn
6735 (goto-char (match-beginning 0))
6736 (funcall outline-level))))))
6737 (and level (hide-sublevels level))
6738 (recenter '(4))
6739 (org-goto-line l)))
6741 (defun org-content (&optional arg)
6742 "Show all headlines in the buffer, like a table of contents.
6743 With numerical argument N, show content up to level N."
6744 (interactive "P")
6745 (save-excursion
6746 ;; Visit all headings and show their offspring
6747 (and (integerp arg) (org-overview))
6748 (goto-char (point-max))
6749 (catch 'exit
6750 (while (and (progn (condition-case nil
6751 (outline-previous-visible-heading 1)
6752 (error (goto-char (point-min))))
6754 (looking-at org-outline-regexp))
6755 (if (integerp arg)
6756 (show-children (1- arg))
6757 (show-branches))
6758 (if (bobp) (throw 'exit nil))))))
6761 (defun org-optimize-window-after-visibility-change (state)
6762 "Adjust the window after a change in outline visibility.
6763 This function is the default value of the hook `org-cycle-hook'."
6764 (when (get-buffer-window (current-buffer))
6765 (cond
6766 ((eq state 'content) nil)
6767 ((eq state 'all) nil)
6768 ((eq state 'folded) nil)
6769 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6770 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6772 (defun org-remove-empty-overlays-at (pos)
6773 "Remove outline overlays that do not contain non-white stuff."
6774 (mapc
6775 (lambda (o)
6776 (and (eq 'outline (overlay-get o 'invisible))
6777 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6778 (overlay-end o))))
6779 (delete-overlay o)))
6780 (overlays-at pos)))
6782 (defun org-clean-visibility-after-subtree-move ()
6783 "Fix visibility issues after moving a subtree."
6784 ;; First, find a reasonable region to look at:
6785 ;; Start two siblings above, end three below
6786 (let* ((beg (save-excursion
6787 (and (org-get-last-sibling)
6788 (org-get-last-sibling))
6789 (point)))
6790 (end (save-excursion
6791 (and (org-get-next-sibling)
6792 (org-get-next-sibling)
6793 (org-get-next-sibling))
6794 (if (org-at-heading-p)
6795 (point-at-eol)
6796 (point))))
6797 (level (looking-at "\\*+"))
6798 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6799 (save-excursion
6800 (save-restriction
6801 (narrow-to-region beg end)
6802 (when re
6803 ;; Properly fold already folded siblings
6804 (goto-char (point-min))
6805 (while (re-search-forward re nil t)
6806 (if (and (not (outline-invisible-p))
6807 (save-excursion
6808 (goto-char (point-at-eol)) (outline-invisible-p)))
6809 (hide-entry))))
6810 (org-cycle-show-empty-lines 'overview)
6811 (org-cycle-hide-drawers 'overview)))))
6813 (defun org-cycle-show-empty-lines (state)
6814 "Show empty lines above all visible headlines.
6815 The region to be covered depends on STATE when called through
6816 `org-cycle-hook'. Lisp program can use t for STATE to get the
6817 entire buffer covered. Note that an empty line is only shown if there
6818 are at least `org-cycle-separator-lines' empty lines before the headline."
6819 (when (not (= org-cycle-separator-lines 0))
6820 (save-excursion
6821 (let* ((n (abs org-cycle-separator-lines))
6822 (re (cond
6823 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6824 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6825 (t (let ((ns (number-to-string (- n 2))))
6826 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6827 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6828 beg end b e)
6829 (cond
6830 ((memq state '(overview contents t))
6831 (setq beg (point-min) end (point-max)))
6832 ((memq state '(children folded))
6833 (setq beg (point) end (progn (org-end-of-subtree t t)
6834 (beginning-of-line 2)
6835 (point)))))
6836 (when beg
6837 (goto-char beg)
6838 (while (re-search-forward re end t)
6839 (unless (get-char-property (match-end 1) 'invisible)
6840 (setq e (match-end 1))
6841 (if (< org-cycle-separator-lines 0)
6842 (setq b (save-excursion
6843 (goto-char (match-beginning 0))
6844 (org-back-over-empty-lines)
6845 (if (save-excursion
6846 (goto-char (max (point-min) (1- (point))))
6847 (org-at-heading-p))
6848 (1- (point))
6849 (point))))
6850 (setq b (match-beginning 1)))
6851 (outline-flag-region b e nil)))))))
6852 ;; Never hide empty lines at the end of the file.
6853 (save-excursion
6854 (goto-char (point-max))
6855 (outline-previous-heading)
6856 (outline-end-of-heading)
6857 (if (and (looking-at "[ \t\n]+")
6858 (= (match-end 0) (point-max)))
6859 (outline-flag-region (point) (match-end 0) nil))))
6861 (defun org-show-empty-lines-in-parent ()
6862 "Move to the parent and re-show empty lines before visible headlines."
6863 (save-excursion
6864 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6865 (org-cycle-show-empty-lines context))))
6867 (defun org-files-list ()
6868 "Return `org-agenda-files' list, plus all open org-mode files.
6869 This is useful for operations that need to scan all of a user's
6870 open and agenda-wise Org files."
6871 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6872 (dolist (buf (buffer-list))
6873 (with-current-buffer buf
6874 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6875 (let ((file (expand-file-name (buffer-file-name))))
6876 (unless (member file files)
6877 (push file files))))))
6878 files))
6880 (defsubst org-entry-beginning-position ()
6881 "Return the beginning position of the current entry."
6882 (save-excursion (outline-back-to-heading t) (point)))
6884 (defsubst org-entry-end-position ()
6885 "Return the end position of the current entry."
6886 (save-excursion (outline-next-heading) (point)))
6888 (defun org-cycle-hide-drawers (state)
6889 "Re-hide all drawers after a visibility state change."
6890 (when (and (derived-mode-p 'org-mode)
6891 (not (memq state '(overview folded contents))))
6892 (save-excursion
6893 (let* ((globalp (memq state '(contents all)))
6894 (beg (if globalp (point-min) (point)))
6895 (end (if globalp (point-max)
6896 (if (eq state 'children)
6897 (save-excursion (outline-next-heading) (point))
6898 (org-end-of-subtree t)))))
6899 (goto-char beg)
6900 (while (re-search-forward org-drawer-regexp end t)
6901 (org-flag-drawer t))))))
6903 (defun org-cycle-hide-inline-tasks (state)
6904 "Re-hide inline task when switching to 'contents visibility state."
6905 (when (and (eq state 'contents)
6906 (boundp 'org-inlinetask-min-level)
6907 org-inlinetask-min-level)
6908 (hide-sublevels (1- org-inlinetask-min-level))))
6910 (defun org-flag-drawer (flag)
6911 "When FLAG is non-nil, hide the drawer we are within.
6912 Otherwise make it visible."
6913 (save-excursion
6914 (beginning-of-line 1)
6915 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6916 (let ((b (match-end 0)))
6917 (if (re-search-forward
6918 "^[ \t]*:END:"
6919 (save-excursion (outline-next-heading) (point)) t)
6920 (outline-flag-region b (point-at-eol) flag)
6921 (error ":END: line missing at position %s" b))))))
6923 (defun org-subtree-end-visible-p ()
6924 "Is the end of the current subtree visible?"
6925 (pos-visible-in-window-p
6926 (save-excursion (org-end-of-subtree t) (point))))
6928 (defun org-first-headline-recenter (&optional N)
6929 "Move cursor to the first headline and recenter the headline.
6930 Optional argument N means put the headline into the Nth line of the window."
6931 (goto-char (point-min))
6932 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6933 (beginning-of-line)
6934 (recenter (prefix-numeric-value N))))
6936 ;;; Saving and restoring visibility
6938 (defun org-outline-overlay-data (&optional use-markers)
6939 "Return a list of the locations of all outline overlays.
6940 These are overlays with the `invisible' property value `outline'.
6941 The return value is a list of cons cells, with start and stop
6942 positions for each overlay.
6943 If USE-MARKERS is set, return the positions as markers."
6944 (let (beg end)
6945 (save-excursion
6946 (save-restriction
6947 (widen)
6948 (delq nil
6949 (mapcar (lambda (o)
6950 (when (eq (overlay-get o 'invisible) 'outline)
6951 (setq beg (overlay-start o)
6952 end (overlay-end o))
6953 (and beg end (> end beg)
6954 (if use-markers
6955 (cons (move-marker (make-marker) beg)
6956 (move-marker (make-marker) end))
6957 (cons beg end)))))
6958 (overlays-in (point-min) (point-max))))))))
6960 (defun org-set-outline-overlay-data (data)
6961 "Create visibility overlays for all positions in DATA.
6962 DATA should have been made by `org-outline-overlay-data'."
6963 (let (o)
6964 (save-excursion
6965 (save-restriction
6966 (widen)
6967 (show-all)
6968 (mapc (lambda (c)
6969 (outline-flag-region (car c) (cdr c) t))
6970 data)))))
6972 ;;; Folding of blocks
6974 (defvar org-hide-block-overlays nil
6975 "Overlays hiding blocks.")
6976 (make-variable-buffer-local 'org-hide-block-overlays)
6978 (defun org-block-map (function &optional start end)
6979 "Call FUNCTION at the head of all source blocks in the current buffer.
6980 Optional arguments START and END can be used to limit the range."
6981 (let ((start (or start (point-min)))
6982 (end (or end (point-max))))
6983 (save-excursion
6984 (goto-char start)
6985 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6986 (save-excursion
6987 (save-match-data
6988 (goto-char (match-beginning 0))
6989 (funcall function)))))))
6991 (defun org-hide-block-toggle-all ()
6992 "Toggle the visibility of all blocks in the current buffer."
6993 (org-block-map #'org-hide-block-toggle))
6995 (defun org-hide-block-all ()
6996 "Fold all blocks in the current buffer."
6997 (interactive)
6998 (org-show-block-all)
6999 (org-block-map #'org-hide-block-toggle-maybe))
7001 (defun org-show-block-all ()
7002 "Unfold all blocks in the current buffer."
7003 (interactive)
7004 (mapc 'delete-overlay org-hide-block-overlays)
7005 (setq org-hide-block-overlays nil))
7007 (defun org-hide-block-toggle-maybe ()
7008 "Toggle visibility of block at point."
7009 (interactive)
7010 (let ((case-fold-search t))
7011 (if (save-excursion
7012 (beginning-of-line 1)
7013 (looking-at org-block-regexp))
7014 (progn (org-hide-block-toggle)
7015 t) ;; to signal that we took action
7016 nil))) ;; to signal that we did not
7018 (defun org-hide-block-toggle (&optional force)
7019 "Toggle the visibility of the current block."
7020 (interactive)
7021 (save-excursion
7022 (beginning-of-line)
7023 (if (re-search-forward org-block-regexp nil t)
7024 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7025 (end (match-end 0)) ;; end of entire body
7027 (if (memq t (mapcar (lambda (overlay)
7028 (eq (overlay-get overlay 'invisible)
7029 'org-hide-block))
7030 (overlays-at start)))
7031 (if (or (not force) (eq force 'off))
7032 (mapc (lambda (ov)
7033 (when (member ov org-hide-block-overlays)
7034 (setq org-hide-block-overlays
7035 (delq ov org-hide-block-overlays)))
7036 (when (eq (overlay-get ov 'invisible)
7037 'org-hide-block)
7038 (delete-overlay ov)))
7039 (overlays-at start)))
7040 (setq ov (make-overlay start end))
7041 (overlay-put ov 'invisible 'org-hide-block)
7042 ;; make the block accessible to isearch
7043 (overlay-put
7044 ov 'isearch-open-invisible
7045 (lambda (ov)
7046 (when (member ov org-hide-block-overlays)
7047 (setq org-hide-block-overlays
7048 (delq ov org-hide-block-overlays)))
7049 (when (eq (overlay-get ov 'invisible)
7050 'org-hide-block)
7051 (delete-overlay ov))))
7052 (push ov org-hide-block-overlays)))
7053 (error "Not looking at a source block"))))
7055 ;; org-tab-after-check-for-cycling-hook
7056 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7057 ;; Remove overlays when changing major mode
7058 (add-hook 'org-mode-hook
7059 (lambda () (org-add-hook 'change-major-mode-hook
7060 'org-show-block-all 'append 'local)))
7062 ;;; Org-goto
7064 (defvar org-goto-window-configuration nil)
7065 (defvar org-goto-marker nil)
7066 (defvar org-goto-map)
7067 (defun org-goto-map ()
7068 "Set the keymap `org-goto'."
7069 (setq org-goto-map
7070 (let ((map (make-sparse-keymap)))
7071 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7072 mouse-drag-region universal-argument org-occur))
7073 cmd)
7074 (while (setq cmd (pop cmds))
7075 (substitute-key-definition cmd cmd map global-map)))
7076 (suppress-keymap map)
7077 (org-defkey map "\C-m" 'org-goto-ret)
7078 (org-defkey map [(return)] 'org-goto-ret)
7079 (org-defkey map [(left)] 'org-goto-left)
7080 (org-defkey map [(right)] 'org-goto-right)
7081 (org-defkey map [(control ?g)] 'org-goto-quit)
7082 (org-defkey map "\C-i" 'org-cycle)
7083 (org-defkey map [(tab)] 'org-cycle)
7084 (org-defkey map [(down)] 'outline-next-visible-heading)
7085 (org-defkey map [(up)] 'outline-previous-visible-heading)
7086 (if org-goto-auto-isearch
7087 (if (fboundp 'define-key-after)
7088 (define-key-after map [t] 'org-goto-local-auto-isearch)
7089 nil)
7090 (org-defkey map "q" 'org-goto-quit)
7091 (org-defkey map "n" 'outline-next-visible-heading)
7092 (org-defkey map "p" 'outline-previous-visible-heading)
7093 (org-defkey map "f" 'outline-forward-same-level)
7094 (org-defkey map "b" 'outline-backward-same-level)
7095 (org-defkey map "u" 'outline-up-heading))
7096 (org-defkey map "/" 'org-occur)
7097 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7098 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7099 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7100 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7101 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7102 map)))
7104 (defconst org-goto-help
7105 "Browse buffer copy, to find location or copy text.%s
7106 RET=jump to location C-g=quit and return to previous location
7107 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7109 (defvar org-goto-start-pos) ; dynamically scoped parameter
7111 ;; FIXME: Docstring does not mention both interfaces
7112 (defun org-goto (&optional alternative-interface)
7113 "Look up a different location in the current file, keeping current visibility.
7115 When you want look-up or go to a different location in a
7116 document, the fastest way is often to fold the entire buffer and
7117 then dive into the tree. This method has the disadvantage, that
7118 the previous location will be folded, which may not be what you
7119 want.
7121 This command works around this by showing a copy of the current
7122 buffer in an indirect buffer, in overview mode. You can dive
7123 into the tree in that copy, use org-occur and incremental search
7124 to find a location. When pressing RET or `Q', the command
7125 returns to the original buffer in which the visibility is still
7126 unchanged. After RET it will also jump to the location selected
7127 in the indirect buffer and expose the headline hierarchy above.
7129 With a prefix argument, use the alternative interface: e.g. if
7130 `org-goto-interface' is 'outline use 'outline-path-completion."
7131 (interactive "P")
7132 (org-goto-map)
7133 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7134 (org-refile-use-outline-path t)
7135 (org-refile-target-verify-function nil)
7136 (interface
7137 (if (not alternative-interface)
7138 org-goto-interface
7139 (if (eq org-goto-interface 'outline)
7140 'outline-path-completion
7141 'outline)))
7142 (org-goto-start-pos (point))
7143 (selected-point
7144 (if (eq interface 'outline)
7145 (car (org-get-location (current-buffer) org-goto-help))
7146 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7147 (org-refile-check-position pa)
7148 (nth 3 pa)))))
7149 (if selected-point
7150 (progn
7151 (org-mark-ring-push org-goto-start-pos)
7152 (goto-char selected-point)
7153 (if (or (outline-invisible-p) (org-invisible-p2))
7154 (org-show-context 'org-goto)))
7155 (message "Quit"))))
7157 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7158 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7159 (defvar org-goto-local-auto-isearch-map) ; defined below
7161 (defun org-get-location (buf help)
7162 "Let the user select a location in the Org-mode buffer BUF.
7163 This function uses a recursive edit. It returns the selected position
7164 or nil."
7165 (org-no-popups
7166 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7167 (isearch-hide-immediately nil)
7168 (isearch-search-fun-function
7169 (lambda () 'org-goto-local-search-headings))
7170 (org-goto-selected-point org-goto-exit-command))
7171 (save-excursion
7172 (save-window-excursion
7173 (delete-other-windows)
7174 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7175 (org-pop-to-buffer-same-window
7176 (condition-case nil
7177 (make-indirect-buffer (current-buffer) "*org-goto*")
7178 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7179 (with-output-to-temp-buffer "*Org Help*"
7180 (princ (format help (if org-goto-auto-isearch
7181 " Just type for auto-isearch."
7182 " n/p/f/b/u to navigate, q to quit."))))
7183 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7184 (setq buffer-read-only nil)
7185 (let ((org-startup-truncated t)
7186 (org-startup-folded nil)
7187 (org-startup-align-all-tables nil))
7188 (org-mode)
7189 (org-overview))
7190 (setq buffer-read-only t)
7191 (if (and (boundp 'org-goto-start-pos)
7192 (integer-or-marker-p org-goto-start-pos))
7193 (let ((org-show-hierarchy-above t)
7194 (org-show-siblings t)
7195 (org-show-following-heading t))
7196 (goto-char org-goto-start-pos)
7197 (and (outline-invisible-p) (org-show-context)))
7198 (goto-char (point-min)))
7199 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7200 (message "Select location and press RET")
7201 (use-local-map org-goto-map)
7202 (recursive-edit)))
7203 (kill-buffer "*org-goto*")
7204 (cons org-goto-selected-point org-goto-exit-command))))
7206 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7207 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7208 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7209 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7211 (defun org-goto-local-search-headings (string bound noerror)
7212 "Search and make sure that any matches are in headlines."
7213 (catch 'return
7214 (while (if isearch-forward
7215 (search-forward string bound noerror)
7216 (search-backward string bound noerror))
7217 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7218 (and (member :headline context)
7219 (not (member :tags context))))
7220 (throw 'return (point))))))
7222 (defun org-goto-local-auto-isearch ()
7223 "Start isearch."
7224 (interactive)
7225 (goto-char (point-min))
7226 (let ((keys (this-command-keys)))
7227 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7228 (isearch-mode t)
7229 (isearch-process-search-char (string-to-char keys)))))
7231 (defun org-goto-ret (&optional arg)
7232 "Finish `org-goto' by going to the new location."
7233 (interactive "P")
7234 (setq org-goto-selected-point (point)
7235 org-goto-exit-command 'return)
7236 (throw 'exit nil))
7238 (defun org-goto-left ()
7239 "Finish `org-goto' by going to the new location."
7240 (interactive)
7241 (if (org-at-heading-p)
7242 (progn
7243 (beginning-of-line 1)
7244 (setq org-goto-selected-point (point)
7245 org-goto-exit-command 'left)
7246 (throw 'exit nil))
7247 (error "Not on a heading")))
7249 (defun org-goto-right ()
7250 "Finish `org-goto' by going to the new location."
7251 (interactive)
7252 (if (org-at-heading-p)
7253 (progn
7254 (setq org-goto-selected-point (point)
7255 org-goto-exit-command 'right)
7256 (throw 'exit nil))
7257 (error "Not on a heading")))
7259 (defun org-goto-quit ()
7260 "Finish `org-goto' without cursor motion."
7261 (interactive)
7262 (setq org-goto-selected-point nil)
7263 (setq org-goto-exit-command 'quit)
7264 (throw 'exit nil))
7266 ;;; Indirect buffer display of subtrees
7268 (defvar org-indirect-dedicated-frame nil
7269 "This is the frame being used for indirect tree display.")
7270 (defvar org-last-indirect-buffer nil)
7272 (defun org-tree-to-indirect-buffer (&optional arg)
7273 "Create indirect buffer and narrow it to current subtree.
7274 With a numerical prefix ARG, go up to this level and then take that tree.
7275 If ARG is negative, go up that many levels.
7277 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7278 indirect buffer previously made with this command, to avoid proliferation of
7279 indirect buffers. However, when you call the command with a \
7280 \\[universal-argument] prefix, or
7281 when `org-indirect-buffer-display' is `new-frame', the last buffer
7282 is kept so that you can work with several indirect buffers at the same time.
7283 If `org-indirect-buffer-display' is `dedicated-frame', the \
7284 \\[universal-argument] prefix also
7285 requests that a new frame be made for the new buffer, so that the dedicated
7286 frame is not changed."
7287 (interactive "P")
7288 (let ((cbuf (current-buffer))
7289 (cwin (selected-window))
7290 (pos (point))
7291 beg end level heading ibuf)
7292 (save-excursion
7293 (org-back-to-heading t)
7294 (when (numberp arg)
7295 (setq level (org-outline-level))
7296 (if (< arg 0) (setq arg (+ level arg)))
7297 (while (> (setq level (org-outline-level)) arg)
7298 (org-up-heading-safe)))
7299 (setq beg (point)
7300 heading (org-get-heading))
7301 (org-end-of-subtree t t)
7302 (if (org-at-heading-p) (backward-char 1))
7303 (setq end (point)))
7304 (if (and (buffer-live-p org-last-indirect-buffer)
7305 (not (eq org-indirect-buffer-display 'new-frame))
7306 (not arg))
7307 (kill-buffer org-last-indirect-buffer))
7308 (setq ibuf (org-get-indirect-buffer cbuf)
7309 org-last-indirect-buffer ibuf)
7310 (cond
7311 ((or (eq org-indirect-buffer-display 'new-frame)
7312 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7313 (select-frame (make-frame))
7314 (delete-other-windows)
7315 (org-pop-to-buffer-same-window ibuf)
7316 (org-set-frame-title heading))
7317 ((eq org-indirect-buffer-display 'dedicated-frame)
7318 (raise-frame
7319 (select-frame (or (and org-indirect-dedicated-frame
7320 (frame-live-p org-indirect-dedicated-frame)
7321 org-indirect-dedicated-frame)
7322 (setq org-indirect-dedicated-frame (make-frame)))))
7323 (delete-other-windows)
7324 (org-pop-to-buffer-same-window ibuf)
7325 (org-set-frame-title (concat "Indirect: " heading)))
7326 ((eq org-indirect-buffer-display 'current-window)
7327 (org-pop-to-buffer-same-window ibuf))
7328 ((eq org-indirect-buffer-display 'other-window)
7329 (pop-to-buffer ibuf))
7330 (t (error "Invalid value")))
7331 (if (featurep 'xemacs)
7332 (save-excursion (org-mode) (turn-on-font-lock)))
7333 (narrow-to-region beg end)
7334 (show-all)
7335 (goto-char pos)
7336 (run-hook-with-args 'org-cycle-hook 'all)
7337 (and (window-live-p cwin) (select-window cwin))))
7339 (defun org-get-indirect-buffer (&optional buffer)
7340 (setq buffer (or buffer (current-buffer)))
7341 (let ((n 1) (base (buffer-name buffer)) bname)
7342 (while (buffer-live-p
7343 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7344 (setq n (1+ n)))
7345 (condition-case nil
7346 (make-indirect-buffer buffer bname 'clone)
7347 (error (make-indirect-buffer buffer bname)))))
7349 (defun org-set-frame-title (title)
7350 "Set the title of the current frame to the string TITLE."
7351 ;; FIXME: how to name a single frame in XEmacs???
7352 (unless (featurep 'xemacs)
7353 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7355 ;;;; Structure editing
7357 ;;; Inserting headlines
7359 (defun org-previous-line-empty-p (&optional next)
7360 "Is the previous line a blank line?
7361 When NEXT is non-nil, check the next line instead."
7362 (save-excursion
7363 (and (not (bobp))
7364 (or (beginning-of-line (if next 2 0)) t)
7365 (save-match-data
7366 (looking-at "[ \t]*$")))))
7368 (defun org-insert-heading (&optional arg invisible-ok)
7369 "Insert a new heading or item with same depth at point.
7370 If point is in a plain list and ARG is nil, create a new list item.
7371 With one universal prefix argument, insert a heading even in lists.
7372 With two universal prefix arguments, insert the heading at the end
7373 of the parent subtree.
7375 If point is at the beginning of a headline, insert a sibling before
7376 the current headline. If point is not at the beginning, split the line
7377 and create a new headline with the text in the current line after point
7378 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7380 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7381 This is important for non-interactive uses of the command."
7382 (interactive "P")
7383 (if (or (= (buffer-size) 0)
7384 (and (not (save-excursion
7385 (and (ignore-errors (org-back-to-heading invisible-ok))
7386 (org-at-heading-p))))
7387 (or arg (not (org-in-item-p)))))
7388 (progn
7389 (insert
7390 (if (org-previous-line-empty-p) "" "\n")
7391 (if (org-in-src-block-p) ",* " "* "))
7392 (run-hooks 'org-insert-heading-hook))
7393 (when (or arg
7394 (not (org-insert-item
7395 (save-excursion
7396 (beginning-of-line)
7397 (looking-at org-list-full-item-re)
7398 (match-string 3)))))
7399 (let* ((empty-line-p nil)
7400 (eops (equal arg '(16))) ; insert at end of parent subtree
7401 (org-insert-heading-respect-content
7402 (or (not (null arg)) org-insert-heading-respect-content))
7403 (level nil)
7404 (on-heading (org-at-heading-p))
7405 (head (save-excursion
7406 (condition-case nil
7407 (progn
7408 (org-back-to-heading invisible-ok)
7409 (when (and (not on-heading)
7410 (featurep 'org-inlinetask)
7411 (integerp org-inlinetask-min-level)
7412 (>= (length (match-string 0))
7413 org-inlinetask-min-level))
7414 ;; Find a heading level before the inline task
7415 (while (and (setq level (org-up-heading-safe))
7416 (>= level org-inlinetask-min-level)))
7417 (if (org-at-heading-p)
7418 (org-back-to-heading invisible-ok)
7419 (error "This should not happen")))
7420 (unless (and (save-excursion
7421 (save-match-data
7422 (org-backward-heading-same-level 1 invisible-ok))
7423 (= (point) (match-beginning 0)))
7424 (not (org-previous-line-empty-p t)))
7425 (setq empty-line-p (org-previous-line-empty-p)))
7426 (match-string 0))
7427 (error "* "))))
7428 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7429 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7430 pos hide-previous previous-pos)
7431 (cond
7432 ;; At the beginning of a heading, open a new line for insertiong
7433 ((and (bolp) (org-at-heading-p)
7434 (not eops)
7435 (or (bobp)
7436 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7437 (open-line (if blank 2 1)))
7439 (save-excursion
7440 (setq previous-pos (point-at-bol))
7441 (end-of-line)
7442 (setq hide-previous (outline-invisible-p)))
7443 (and org-insert-heading-respect-content
7444 (save-excursion
7445 (while (outline-invisible-p)
7446 (org-show-subtree)
7447 (org-up-heading-safe))))
7448 (let ((split
7449 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7450 (save-excursion
7451 (let ((p (point)))
7452 (goto-char (point-at-bol))
7453 (and (looking-at org-complex-heading-regexp)
7454 (match-beginning 4)
7455 (> p (match-beginning 4)))))))
7456 tags pos)
7457 (cond
7458 ;; Insert a new line, possibly at end of parent subtree
7459 (org-insert-heading-respect-content
7460 (if (not eops)
7461 (progn
7462 (org-end-of-subtree nil t)
7463 (and (looking-at "^\\*") (backward-char 1))
7464 (while (and (not (bobp))
7465 ;; Don't delete spaces in empty headlines
7466 (not (looking-back org-outline-regexp))
7467 (member (char-before) '(?\ ?\t ?\n)))
7468 (backward-delete-char 1)))
7469 (let ((p (point)))
7470 (org-up-heading-safe)
7471 (if (= p (point))
7472 (goto-char (point-max))
7473 (org-end-of-subtree nil t))))
7474 (when (featurep 'org-inlinetask)
7475 (while (and (not (eobp))
7476 (looking-at "\\(\\*+\\)[ \t]+")
7477 (>= (length (match-string 1))
7478 org-inlinetask-min-level))
7479 (org-end-of-subtree nil t)))
7480 (or (bolp) (newline))
7481 (or (org-previous-line-empty-p)
7482 (and blank (newline)))
7483 (if (or empty-line-p eops) (open-line 1)))
7484 ;; Insert a headling containing text after point
7485 ((org-at-heading-p)
7486 (when hide-previous
7487 (show-children)
7488 (org-show-entry))
7489 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7490 (setq tags (and (match-end 2) (match-string 2)))
7491 (and (match-end 1)
7492 (delete-region (match-beginning 1) (match-end 1)))
7493 (setq pos (point-at-bol))
7494 (or split (end-of-line 1))
7495 (delete-horizontal-space)
7496 (if (string-match "\\`\\*+\\'"
7497 (buffer-substring (point-at-bol) (point)))
7498 (insert " "))
7499 (newline (if blank 2 1))
7500 (when tags
7501 (save-excursion
7502 (goto-char pos)
7503 (end-of-line 1)
7504 (insert " " tags)
7505 (org-set-tags nil 'align))))
7507 (or split (end-of-line 1))
7508 (newline (if blank 2 1)))))))
7509 (insert head) (just-one-space)
7510 (setq pos (point))
7511 (end-of-line 1)
7512 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7513 (when (and org-insert-heading-respect-content hide-previous)
7514 (save-excursion
7515 (goto-char previous-pos)
7516 (hide-subtree)))
7517 (run-hooks 'org-insert-heading-hook)))))
7519 (defun org-get-heading (&optional no-tags no-todo)
7520 "Return the heading of the current entry, without the stars.
7521 When NO-TAGS is non-nil, don't include tags.
7522 When NO-TODO is non-nil, don't include TODO keywords."
7523 (save-excursion
7524 (org-back-to-heading t)
7525 (cond
7526 ((and no-tags no-todo)
7527 (looking-at org-complex-heading-regexp)
7528 (match-string 4))
7529 (no-tags
7530 (looking-at (concat org-outline-regexp
7531 "\\(.*?\\)"
7532 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7533 (match-string 1))
7534 (no-todo
7535 (looking-at org-todo-line-regexp)
7536 (match-string 3))
7537 (t (looking-at org-heading-regexp)
7538 (match-string 2)))))
7540 (defvar orgstruct-mode) ; defined below
7542 (defun org-heading-components ()
7543 "Return the components of the current heading.
7544 This is a list with the following elements:
7545 - the level as an integer
7546 - the reduced level, different if `org-odd-levels-only' is set.
7547 - the TODO keyword, or nil
7548 - the priority character, like ?A, or nil if no priority is given
7549 - the headline text itself, or the tags string if no headline text
7550 - the tags string, or nil."
7551 (save-excursion
7552 (org-back-to-heading t)
7553 (if (let (case-fold-search)
7554 (looking-at
7555 (if orgstruct-mode
7556 org-heading-regexp
7557 org-complex-heading-regexp)))
7558 (if orgstruct-mode
7559 (list (length (match-string 1))
7560 (org-reduced-level (length (match-string 1)))
7563 (match-string 2)
7564 nil)
7565 (list (length (match-string 1))
7566 (org-reduced-level (length (match-string 1)))
7567 (org-match-string-no-properties 2)
7568 (and (match-end 3) (aref (match-string 3) 2))
7569 (org-match-string-no-properties 4)
7570 (org-match-string-no-properties 5))))))
7572 (defun org-get-entry ()
7573 "Get the entry text, after heading, entire subtree."
7574 (save-excursion
7575 (org-back-to-heading t)
7576 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7578 (defun org-insert-heading-after-current ()
7579 "Insert a new heading with same level as current, after current subtree."
7580 (interactive)
7581 (org-back-to-heading)
7582 (org-insert-heading)
7583 (org-move-subtree-down)
7584 (end-of-line 1))
7586 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7587 "Insert heading with `org-insert-heading-respect-content' set to t."
7588 (interactive "P")
7589 (let ((org-insert-heading-respect-content t))
7590 (org-insert-heading arg invisible-ok)))
7592 (defun org-insert-todo-heading-respect-content (&optional force-state)
7593 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7594 (interactive "P")
7595 (let ((org-insert-heading-respect-content t))
7596 (org-insert-todo-heading force-state t)))
7598 (defun org-insert-todo-heading (arg &optional force-heading)
7599 "Insert a new heading with the same level and TODO state as current heading.
7600 If the heading has no TODO state, or if the state is DONE, use the first
7601 state (TODO by default). Also one prefix arg, force first state. With two
7602 prefix args, force inserting at the end of the parent subtree."
7603 (interactive "P")
7604 (when (or force-heading (not (org-insert-item 'checkbox)))
7605 (org-insert-heading (or (and (equal arg '(16)) '(16))
7606 force-heading))
7607 (save-excursion
7608 (org-back-to-heading)
7609 (outline-previous-heading)
7610 (looking-at org-todo-line-regexp))
7611 (let*
7612 ((new-mark-x
7613 (if (or arg
7614 (not (match-beginning 2))
7615 (member (match-string 2) org-done-keywords))
7616 (car org-todo-keywords-1)
7617 (match-string 2)))
7618 (new-mark
7620 (run-hook-with-args-until-success
7621 'org-todo-get-default-hook new-mark-x nil)
7622 new-mark-x)))
7623 (beginning-of-line 1)
7624 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7625 (if org-treat-insert-todo-heading-as-state-change
7626 (org-todo new-mark)
7627 (insert new-mark " "))))
7628 (when org-provide-todo-statistics
7629 (org-update-parent-todo-statistics))))
7631 (defun org-insert-subheading (arg)
7632 "Insert a new subheading and demote it.
7633 Works for outline headings and for plain lists alike."
7634 (interactive "P")
7635 (org-insert-heading arg)
7636 (cond
7637 ((org-at-heading-p) (org-do-demote))
7638 ((org-at-item-p) (org-indent-item))))
7640 (defun org-insert-todo-subheading (arg)
7641 "Insert a new subheading with TODO keyword or checkbox and demote it.
7642 Works for outline headings and for plain lists alike."
7643 (interactive "P")
7644 (org-insert-todo-heading arg)
7645 (cond
7646 ((org-at-heading-p) (org-do-demote))
7647 ((org-at-item-p) (org-indent-item))))
7649 ;;; Promotion and Demotion
7651 (defvar org-after-demote-entry-hook nil
7652 "Hook run after an entry has been demoted.
7653 The cursor will be at the beginning of the entry.
7654 When a subtree is being demoted, the hook will be called for each node.")
7656 (defvar org-after-promote-entry-hook nil
7657 "Hook run after an entry has been promoted.
7658 The cursor will be at the beginning of the entry.
7659 When a subtree is being promoted, the hook will be called for each node.")
7661 (defun org-promote-subtree ()
7662 "Promote the entire subtree.
7663 See also `org-promote'."
7664 (interactive)
7665 (save-excursion
7666 (org-with-limited-levels (org-map-tree 'org-promote)))
7667 (org-fix-position-after-promote))
7669 (defun org-demote-subtree ()
7670 "Demote the entire subtree. See `org-demote'.
7671 See also `org-promote'."
7672 (interactive)
7673 (save-excursion
7674 (org-with-limited-levels (org-map-tree 'org-demote)))
7675 (org-fix-position-after-promote))
7678 (defun org-do-promote ()
7679 "Promote the current heading higher up the tree.
7680 If the region is active in `transient-mark-mode', promote all headings
7681 in the region."
7682 (interactive)
7683 (save-excursion
7684 (if (org-region-active-p)
7685 (org-map-region 'org-promote (region-beginning) (region-end))
7686 (org-promote)))
7687 (org-fix-position-after-promote))
7689 (defun org-do-demote ()
7690 "Demote the current heading lower down the tree.
7691 If the region is active in `transient-mark-mode', demote all headings
7692 in the region."
7693 (interactive)
7694 (save-excursion
7695 (if (org-region-active-p)
7696 (org-map-region 'org-demote (region-beginning) (region-end))
7697 (org-demote)))
7698 (org-fix-position-after-promote))
7700 (defun org-fix-position-after-promote ()
7701 "Make sure that after pro/demotion cursor position is right."
7702 (let ((pos (point)))
7703 (when (save-excursion
7704 (beginning-of-line 1)
7705 (looking-at org-todo-line-regexp)
7706 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7707 (cond ((eobp) (insert " "))
7708 ((eolp) (insert " "))
7709 ((equal (char-after) ?\ ) (forward-char 1))))))
7711 (defun org-current-level ()
7712 "Return the level of the current entry, or nil if before the first headline.
7713 The level is the number of stars at the beginning of the headline."
7714 (save-excursion
7715 (org-with-limited-levels
7716 (if (ignore-errors (org-back-to-heading t))
7717 (funcall outline-level)))))
7719 (defun org-get-previous-line-level ()
7720 "Return the outline depth of the last headline before the current line.
7721 Returns 0 for the first headline in the buffer, and nil if before the
7722 first headline."
7723 (let ((current-level (org-current-level))
7724 (prev-level (when (> (line-number-at-pos) 1)
7725 (save-excursion
7726 (beginning-of-line 0)
7727 (org-current-level)))))
7728 (cond ((null current-level) nil) ; Before first headline
7729 ((null prev-level) 0) ; At first headline
7730 (prev-level))))
7732 (defun org-reduced-level (l)
7733 "Compute the effective level of a heading.
7734 This takes into account the setting of `org-odd-levels-only'."
7735 (cond
7736 ((zerop l) 0)
7737 (org-odd-levels-only (1+ (floor (/ l 2))))
7738 (t l)))
7740 (defun org-level-increment ()
7741 "Return the number of stars that will be added or removed at a
7742 time to headlines when structure editing, based on the value of
7743 `org-odd-levels-only'."
7744 (if org-odd-levels-only 2 1))
7746 (defun org-get-valid-level (level &optional change)
7747 "Rectify a level change under the influence of `org-odd-levels-only'
7748 LEVEL is a current level, CHANGE is by how much the level should be
7749 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7750 even level numbers will become the next higher odd number."
7751 (if org-odd-levels-only
7752 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7753 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7754 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7755 (max 1 (+ level (or change 0)))))
7757 (if (boundp 'define-obsolete-function-alias)
7758 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7759 (define-obsolete-function-alias 'org-get-legal-level
7760 'org-get-valid-level)
7761 (define-obsolete-function-alias 'org-get-legal-level
7762 'org-get-valid-level "23.1")))
7764 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7765 ;; ̀org-with-limited-levels'
7766 (defun org-promote ()
7767 "Promote the current heading higher up the tree.
7768 If the region is active in `transient-mark-mode', promote all headings
7769 in the region."
7770 (org-back-to-heading t)
7771 (let* ((level (save-match-data (funcall outline-level)))
7772 (after-change-functions (remove 'flyspell-after-change-function
7773 after-change-functions))
7774 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7775 (diff (abs (- level (length up-head) -1))))
7776 (cond ((and (= level 1) org-called-with-limited-levels
7777 org-allow-promoting-top-level-subtree)
7778 (replace-match "# " nil t))
7779 ((= level 1)
7780 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7781 (t (replace-match up-head nil t)))
7782 ;; Fixup tag positioning
7783 (unless (= level 1)
7784 (and org-auto-align-tags (org-set-tags nil t))
7785 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7786 (run-hooks 'org-after-promote-entry-hook)))
7788 (defun org-demote ()
7789 "Demote the current heading lower down the tree.
7790 If the region is active in `transient-mark-mode', demote all headings
7791 in the region."
7792 (org-back-to-heading t)
7793 (let* ((level (save-match-data (funcall outline-level)))
7794 (after-change-functions (remove 'flyspell-after-change-function
7795 after-change-functions))
7796 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7797 (diff (abs (- level (length down-head) -1))))
7798 (replace-match down-head nil t)
7799 ;; Fixup tag positioning
7800 (and org-auto-align-tags (org-set-tags nil t))
7801 (if org-adapt-indentation (org-fixup-indentation diff))
7802 (run-hooks 'org-after-demote-entry-hook)))
7804 (defun org-cycle-level ()
7805 "Cycle the level of an empty headline through possible states.
7806 This goes first to child, then to parent, level, then up the hierarchy.
7807 After top level, it switches back to sibling level."
7808 (interactive)
7809 (let ((org-adapt-indentation nil))
7810 (when (org-point-at-end-of-empty-headline)
7811 (setq this-command 'org-cycle-level) ; Only needed for caching
7812 (let ((cur-level (org-current-level))
7813 (prev-level (org-get-previous-line-level)))
7814 (cond
7815 ;; If first headline in file, promote to top-level.
7816 ((= prev-level 0)
7817 (loop repeat (/ (- cur-level 1) (org-level-increment))
7818 do (org-do-promote)))
7819 ;; If same level as prev, demote one.
7820 ((= prev-level cur-level)
7821 (org-do-demote))
7822 ;; If parent is top-level, promote to top level if not already.
7823 ((= prev-level 1)
7824 (loop repeat (/ (- cur-level 1) (org-level-increment))
7825 do (org-do-promote)))
7826 ;; If top-level, return to prev-level.
7827 ((= cur-level 1)
7828 (loop repeat (/ (- prev-level 1) (org-level-increment))
7829 do (org-do-demote)))
7830 ;; If less than prev-level, promote one.
7831 ((< cur-level prev-level)
7832 (org-do-promote))
7833 ;; If deeper than prev-level, promote until higher than
7834 ;; prev-level.
7835 ((> cur-level prev-level)
7836 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7837 do (org-do-promote))))
7838 t))))
7840 (defun org-map-tree (fun)
7841 "Call FUN for every heading underneath the current one."
7842 (org-back-to-heading)
7843 (let ((level (funcall outline-level)))
7844 (save-excursion
7845 (funcall fun)
7846 (while (and (progn
7847 (outline-next-heading)
7848 (> (funcall outline-level) level))
7849 (not (eobp)))
7850 (funcall fun)))))
7852 (defun org-map-region (fun beg end)
7853 "Call FUN for every heading between BEG and END."
7854 (let ((org-ignore-region t))
7855 (save-excursion
7856 (setq end (copy-marker end))
7857 (goto-char beg)
7858 (if (and (re-search-forward org-outline-regexp-bol nil t)
7859 (< (point) end))
7860 (funcall fun))
7861 (while (and (progn
7862 (outline-next-heading)
7863 (< (point) end))
7864 (not (eobp)))
7865 (funcall fun)))))
7867 (defvar org-property-end-re) ; silence byte-compiler
7868 (defun org-fixup-indentation (diff)
7869 "Change the indentation in the current entry by DIFF.
7870 However, if any line in the current entry has no indentation, or if it
7871 would end up with no indentation after the change, nothing at all is done."
7872 (save-excursion
7873 (let ((end (save-excursion (outline-next-heading)
7874 (point-marker)))
7875 (prohibit (if (> diff 0)
7876 "^\\S-"
7877 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7878 col)
7879 (unless (save-excursion (end-of-line 1)
7880 (re-search-forward prohibit end t))
7881 (while (and (< (point) end)
7882 (re-search-forward "^[ \t]+" end t))
7883 (goto-char (match-end 0))
7884 (setq col (current-column))
7885 (if (< diff 0) (replace-match ""))
7886 (org-indent-to-column (+ diff col))))
7887 (move-marker end nil))))
7889 (defun org-convert-to-odd-levels ()
7890 "Convert an org-mode file with all levels allowed to one with odd levels.
7891 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7892 level 5 etc."
7893 (interactive)
7894 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7895 (let ((outline-level 'org-outline-level)
7896 (org-odd-levels-only nil) n)
7897 (save-excursion
7898 (goto-char (point-min))
7899 (while (re-search-forward "^\\*\\*+ " nil t)
7900 (setq n (- (length (match-string 0)) 2))
7901 (while (>= (setq n (1- n)) 0)
7902 (org-demote))
7903 (end-of-line 1))))))
7905 (defun org-convert-to-oddeven-levels ()
7906 "Convert an org-mode file with only odd levels to one with odd/even levels.
7907 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7908 file contains a section with an even level, conversion would
7909 destroy the structure of the file. An error is signaled in this
7910 case."
7911 (interactive)
7912 (goto-char (point-min))
7913 ;; First check if there are no even levels
7914 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7915 (org-show-context t)
7916 (error "Not all levels are odd in this file. Conversion not possible"))
7917 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7918 (let ((outline-regexp org-outline-regexp)
7919 (outline-level 'org-outline-level)
7920 (org-odd-levels-only nil) n)
7921 (save-excursion
7922 (goto-char (point-min))
7923 (while (re-search-forward "^\\*\\*+ " nil t)
7924 (setq n (/ (1- (length (match-string 0))) 2))
7925 (while (>= (setq n (1- n)) 0)
7926 (org-promote))
7927 (end-of-line 1))))))
7929 (defun org-tr-level (n)
7930 "Make N odd if required."
7931 (if org-odd-levels-only (1+ (/ n 2)) n))
7933 ;;; Vertical tree motion, cutting and pasting of subtrees
7935 (defun org-move-subtree-up (&optional arg)
7936 "Move the current subtree up past ARG headlines of the same level."
7937 (interactive "p")
7938 (org-move-subtree-down (- (prefix-numeric-value arg))))
7940 (defun org-move-subtree-down (&optional arg)
7941 "Move the current subtree down past ARG headlines of the same level."
7942 (interactive "p")
7943 (setq arg (prefix-numeric-value arg))
7944 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7945 'org-get-last-sibling))
7946 (ins-point (make-marker))
7947 (cnt (abs arg))
7948 (col (current-column))
7949 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7950 ;; Select the tree
7951 (org-back-to-heading)
7952 (setq beg0 (point))
7953 (save-excursion
7954 (setq ne-beg (org-back-over-empty-lines))
7955 (setq beg (point)))
7956 (save-match-data
7957 (save-excursion (outline-end-of-heading)
7958 (setq folded (outline-invisible-p)))
7959 (outline-end-of-subtree))
7960 (outline-next-heading)
7961 (setq ne-end (org-back-over-empty-lines))
7962 (setq end (point))
7963 (goto-char beg0)
7964 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7965 ;; include less whitespace
7966 (save-excursion
7967 (goto-char beg)
7968 (forward-line (- ne-beg ne-end))
7969 (setq beg (point))))
7970 ;; Find insertion point, with error handling
7971 (while (> cnt 0)
7972 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7973 (progn (goto-char beg0)
7974 (user-error "Cannot move past superior level or buffer limit")))
7975 (setq cnt (1- cnt)))
7976 (if (> arg 0)
7977 ;; Moving forward - still need to move over subtree
7978 (progn (org-end-of-subtree t t)
7979 (save-excursion
7980 (org-back-over-empty-lines)
7981 (or (bolp) (newline)))))
7982 (setq ne-ins (org-back-over-empty-lines))
7983 (move-marker ins-point (point))
7984 (setq txt (buffer-substring beg end))
7985 (org-save-markers-in-region beg end)
7986 (delete-region beg end)
7987 (org-remove-empty-overlays-at beg)
7988 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7989 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7990 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7991 (let ((bbb (point)))
7992 (insert-before-markers txt)
7993 (org-reinstall-markers-in-region bbb)
7994 (move-marker ins-point bbb))
7995 (or (bolp) (insert "\n"))
7996 (setq ins-end (point))
7997 (goto-char ins-point)
7998 (org-skip-whitespace)
7999 (when (and (< arg 0)
8000 (org-first-sibling-p)
8001 (> ne-ins ne-beg))
8002 ;; Move whitespace back to beginning
8003 (save-excursion
8004 (goto-char ins-end)
8005 (let ((kill-whole-line t))
8006 (kill-line (- ne-ins ne-beg)) (point)))
8007 (insert (make-string (- ne-ins ne-beg) ?\n)))
8008 (move-marker ins-point nil)
8009 (if folded
8010 (hide-subtree)
8011 (org-show-entry)
8012 (show-children)
8013 (org-cycle-hide-drawers 'children))
8014 (org-clean-visibility-after-subtree-move)
8015 ;; move back to the initial column we were at
8016 (move-to-column col)))
8018 (defvar org-subtree-clip ""
8019 "Clipboard for cut and paste of subtrees.
8020 This is actually only a copy of the kill, because we use the normal kill
8021 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8023 (defvar org-subtree-clip-folded nil
8024 "Was the last copied subtree folded?
8025 This is used to fold the tree back after pasting.")
8027 (defun org-cut-subtree (&optional n)
8028 "Cut the current subtree into the clipboard.
8029 With prefix arg N, cut this many sequential subtrees.
8030 This is a short-hand for marking the subtree and then cutting it."
8031 (interactive "p")
8032 (org-copy-subtree n 'cut))
8034 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8035 "Cut the current subtree into the clipboard.
8036 With prefix arg N, cut this many sequential subtrees.
8037 This is a short-hand for marking the subtree and then copying it.
8038 If CUT is non-nil, actually cut the subtree.
8039 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8040 of some markers in the region, even if CUT is non-nil. This is
8041 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8042 (interactive "p")
8043 (let (beg end folded (beg0 (point)))
8044 (if (org-called-interactively-p 'any)
8045 (org-back-to-heading nil) ; take what looks like a subtree
8046 (org-back-to-heading t)) ; take what is really there
8047 (setq beg (point))
8048 (skip-chars-forward " \t\r\n")
8049 (save-match-data
8050 (if nosubtrees
8051 (outline-next-heading)
8052 (save-excursion (outline-end-of-heading)
8053 (setq folded (outline-invisible-p)))
8054 (condition-case nil
8055 (org-forward-heading-same-level (1- n) t)
8056 (error nil))
8057 (org-end-of-subtree t t)))
8058 (setq end (point))
8059 (goto-char beg0)
8060 (when (> end beg)
8061 (setq org-subtree-clip-folded folded)
8062 (when (or cut force-store-markers)
8063 (org-save-markers-in-region beg end))
8064 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8065 (setq org-subtree-clip (current-kill 0))
8066 (message "%s: Subtree(s) with %d characters"
8067 (if cut "Cut" "Copied")
8068 (length org-subtree-clip)))))
8070 (defun org-paste-subtree (&optional level tree for-yank)
8071 "Paste the clipboard as a subtree, with modification of headline level.
8072 The entire subtree is promoted or demoted in order to match a new headline
8073 level.
8075 If the cursor is at the beginning of a headline, the same level as
8076 that headline is used to paste the tree.
8078 If not, the new level is derived from the *visible* headings
8079 before and after the insertion point, and taken to be the inferior headline
8080 level of the two. So if the previous visible heading is level 3 and the
8081 next is level 4 (or vice versa), level 4 will be used for insertion.
8082 This makes sure that the subtree remains an independent subtree and does
8083 not swallow low level entries.
8085 You can also force a different level, either by using a numeric prefix
8086 argument, or by inserting the heading marker by hand. For example, if the
8087 cursor is after \"*****\", then the tree will be shifted to level 5.
8089 If optional TREE is given, use this text instead of the kill ring.
8091 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8092 move back over whitespace before inserting, and move point to the end of
8093 the inserted text when done."
8094 (interactive "P")
8095 (setq tree (or tree (and kill-ring (current-kill 0))))
8096 (unless (org-kill-is-subtree-p tree)
8097 (error "%s"
8098 (substitute-command-keys
8099 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8100 (org-with-limited-levels
8101 (let* ((visp (not (outline-invisible-p)))
8102 (txt tree)
8103 (^re_ "\\(\\*+\\)[ \t]*")
8104 (old-level (if (string-match org-outline-regexp-bol txt)
8105 (- (match-end 0) (match-beginning 0) 1)
8106 -1))
8107 (force-level (cond (level (prefix-numeric-value level))
8108 ((and (looking-at "[ \t]*$")
8109 (string-match
8110 "^\\*+$" (buffer-substring
8111 (point-at-bol) (point))))
8112 (- (match-end 1) (match-beginning 1)))
8113 ((and (bolp)
8114 (looking-at org-outline-regexp))
8115 (- (match-end 0) (point) 1))))
8116 (previous-level (save-excursion
8117 (condition-case nil
8118 (progn
8119 (outline-previous-visible-heading 1)
8120 (if (looking-at ^re_)
8121 (- (match-end 0) (match-beginning 0) 1)
8123 (error 1))))
8124 (next-level (save-excursion
8125 (condition-case nil
8126 (progn
8127 (or (looking-at org-outline-regexp)
8128 (outline-next-visible-heading 1))
8129 (if (looking-at ^re_)
8130 (- (match-end 0) (match-beginning 0) 1)
8132 (error 1))))
8133 (new-level (or force-level (max previous-level next-level)))
8134 (shift (if (or (= old-level -1)
8135 (= new-level -1)
8136 (= old-level new-level))
8138 (- new-level old-level)))
8139 (delta (if (> shift 0) -1 1))
8140 (func (if (> shift 0) 'org-demote 'org-promote))
8141 (org-odd-levels-only nil)
8142 beg end newend)
8143 ;; Remove the forced level indicator
8144 (if force-level
8145 (delete-region (point-at-bol) (point)))
8146 ;; Paste
8147 (beginning-of-line (if (bolp) 1 2))
8148 (setq beg (point))
8149 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8150 (insert-before-markers txt)
8151 (unless (string-match "\n\\'" txt) (insert "\n"))
8152 (setq newend (point))
8153 (org-reinstall-markers-in-region beg)
8154 (setq end (point))
8155 (goto-char beg)
8156 (skip-chars-forward " \t\n\r")
8157 (setq beg (point))
8158 (if (and (outline-invisible-p) visp)
8159 (save-excursion (outline-show-heading)))
8160 ;; Shift if necessary
8161 (unless (= shift 0)
8162 (save-restriction
8163 (narrow-to-region beg end)
8164 (while (not (= shift 0))
8165 (org-map-region func (point-min) (point-max))
8166 (setq shift (+ delta shift)))
8167 (goto-char (point-min))
8168 (setq newend (point-max))))
8169 (when (or (org-called-interactively-p 'interactive) for-yank)
8170 (message "Clipboard pasted as level %d subtree" new-level))
8171 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8172 kill-ring
8173 (eq org-subtree-clip (current-kill 0))
8174 org-subtree-clip-folded)
8175 ;; The tree was folded before it was killed/copied
8176 (hide-subtree))
8177 (and for-yank (goto-char newend)))))
8179 (defun org-kill-is-subtree-p (&optional txt)
8180 "Check if the current kill is an outline subtree, or a set of trees.
8181 Returns nil if kill does not start with a headline, or if the first
8182 headline level is not the largest headline level in the tree.
8183 So this will actually accept several entries of equal levels as well,
8184 which is OK for `org-paste-subtree'.
8185 If optional TXT is given, check this string instead of the current kill."
8186 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8187 (re (org-get-limited-outline-regexp))
8188 (^re (concat "^" re))
8189 (start-level (and kill
8190 (string-match
8191 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8192 kill)
8193 (- (match-end 2) (match-beginning 2) 1)))
8194 (start (1+ (or (match-beginning 2) -1))))
8195 (if (not start-level)
8196 (progn
8197 nil) ;; does not even start with a heading
8198 (catch 'exit
8199 (while (setq start (string-match ^re kill (1+ start)))
8200 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8201 (throw 'exit nil)))
8202 t))))
8204 (defvar org-markers-to-move nil
8205 "Markers that should be moved with a cut-and-paste operation.
8206 Those markers are stored together with their positions relative to
8207 the start of the region.")
8209 (defun org-save-markers-in-region (beg end)
8210 "Check markers in region.
8211 If these markers are between BEG and END, record their position relative
8212 to BEG, so that after moving the block of text, we can put the markers back
8213 into place.
8214 This function gets called just before an entry or tree gets cut from the
8215 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8216 called immediately, to move the markers with the entries."
8217 (setq org-markers-to-move nil)
8218 (when (featurep 'org-clock)
8219 (org-clock-save-markers-for-cut-and-paste beg end))
8220 (when (featurep 'org-agenda)
8221 (org-agenda-save-markers-for-cut-and-paste beg end)))
8223 (defun org-check-and-save-marker (marker beg end)
8224 "Check if MARKER is between BEG and END.
8225 If yes, remember the marker and the distance to BEG."
8226 (when (and (marker-buffer marker)
8227 (equal (marker-buffer marker) (current-buffer)))
8228 (if (and (>= marker beg) (< marker end))
8229 (push (cons marker (- marker beg)) org-markers-to-move))))
8231 (defun org-reinstall-markers-in-region (beg)
8232 "Move all remembered markers to their position relative to BEG."
8233 (mapc (lambda (x)
8234 (move-marker (car x) (+ beg (cdr x))))
8235 org-markers-to-move)
8236 (setq org-markers-to-move nil))
8238 (defun org-narrow-to-subtree ()
8239 "Narrow buffer to the current subtree."
8240 (interactive)
8241 (save-excursion
8242 (save-match-data
8243 (org-with-limited-levels
8244 (narrow-to-region
8245 (progn (org-back-to-heading t) (point))
8246 (progn (org-end-of-subtree t t)
8247 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8248 (point)))))))
8250 (defun org-narrow-to-block ()
8251 "Narrow buffer to the current block."
8252 (interactive)
8253 (let* ((case-fold-search t)
8254 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8255 "^[ \t]*#\\+end_.*")))
8256 (if blockp
8257 (narrow-to-region (car blockp) (cdr blockp))
8258 (error "Not in a block"))))
8260 (eval-when-compile
8261 (defvar org-property-drawer-re))
8263 (defvar org-property-start-re) ;; defined below
8264 (defun org-clone-subtree-with-time-shift (n &optional shift)
8265 "Clone the task (subtree) at point N times.
8266 The clones will be inserted as siblings.
8268 In interactive use, the user will be prompted for the number of
8269 clones to be produced, and for a time SHIFT, which may be a
8270 repeater as used in time stamps, for example `+3d'.
8272 When a valid repeater is given and the entry contains any time
8273 stamps, the clones will become a sequence in time, with time
8274 stamps in the subtree shifted for each clone produced. If SHIFT
8275 is nil or the empty string, time stamps will be left alone. The
8276 ID property of the original subtree is removed.
8278 If the original subtree did contain time stamps with a repeater,
8279 the following will happen:
8280 - the repeater will be removed in each clone
8281 - an additional clone will be produced, with the current, unshifted
8282 date(s) in the entry.
8283 - the original entry will be placed *after* all the clones, with
8284 repeater intact.
8285 - the start days in the repeater in the original entry will be shifted
8286 to past the last clone.
8287 In this way you can spell out a number of instances of a repeating task,
8288 and still retain the repeater to cover future instances of the task."
8289 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8290 (let (beg end template task idprop
8291 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8292 (drawer-re org-drawer-regexp))
8293 (if (not (and (integerp n) (> n 0)))
8294 (error "Invalid number of replications %s" n))
8295 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8296 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8297 shift)))
8298 (error "Invalid shift specification %s" shift))
8299 (when doshift
8300 (setq shift-n (string-to-number (match-string 1 shift))
8301 shift-what (cdr (assoc (match-string 2 shift)
8302 '(("d" . day) ("w" . week)
8303 ("m" . month) ("y" . year))))))
8304 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8305 (setq nmin 1 nmax n)
8306 (org-back-to-heading t)
8307 (setq beg (point))
8308 (setq idprop (org-entry-get nil "ID"))
8309 (org-end-of-subtree t t)
8310 (or (bolp) (insert "\n"))
8311 (setq end (point))
8312 (setq template (buffer-substring beg end))
8313 (when (and doshift
8314 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8315 (delete-region beg end)
8316 (setq end beg)
8317 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8318 (goto-char end)
8319 (loop for n from nmin to nmax do
8320 ;; prepare clone
8321 (with-temp-buffer
8322 (insert template)
8323 (org-mode)
8324 (goto-char (point-min))
8325 (org-show-subtree)
8326 (and idprop (if org-clone-delete-id
8327 (org-entry-delete nil "ID")
8328 (org-id-get-create t)))
8329 (unless (= n 0)
8330 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8331 (kill-whole-line))
8332 (goto-char (point-min))
8333 (while (re-search-forward drawer-re nil t)
8334 (mapc (lambda (d)
8335 (org-remove-empty-drawer-at d (point))) org-drawers)))
8336 (goto-char (point-min))
8337 (when doshift
8338 (while (re-search-forward org-ts-regexp-both nil t)
8339 (org-timestamp-change (* n shift-n) shift-what))
8340 (unless (= n n-no-remove)
8341 (goto-char (point-min))
8342 (while (re-search-forward org-ts-regexp nil t)
8343 (save-excursion
8344 (goto-char (match-beginning 0))
8345 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8346 (delete-region (match-beginning 1) (match-end 1)))))))
8347 (setq task (buffer-string)))
8348 (insert task))
8349 (goto-char beg)))
8351 ;;; Outline Sorting
8353 (defun org-sort (with-case)
8354 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8355 Optional argument WITH-CASE means sort case-sensitively."
8356 (interactive "P")
8357 (cond
8358 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8359 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8361 (org-call-with-arg 'org-sort-entries with-case))))
8363 (defun org-sort-remove-invisible (s)
8364 "Remove invisible links from string S."
8365 (remove-text-properties 0 (length s) org-rm-props s)
8366 (while (string-match org-bracket-link-regexp s)
8367 (setq s (replace-match (if (match-end 2)
8368 (match-string 3 s)
8369 (match-string 1 s)) t t s)))
8370 (let ((st (format " %s " s)))
8371 (while (string-match org-emph-re st)
8372 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8373 (setq s (substring st 1 -1)))
8376 (defvar org-priority-regexp) ; defined later in the file
8378 (defvar org-after-sorting-entries-or-items-hook nil
8379 "Hook that is run after a bunch of entries or items have been sorted.
8380 When children are sorted, the cursor is in the parent line when this
8381 hook gets called. When a region or a plain list is sorted, the cursor
8382 will be in the first entry of the sorted region/list.")
8384 (defun org-sort-entries
8385 (&optional with-case sorting-type getkey-func compare-func property)
8386 "Sort entries on a certain level of an outline tree.
8387 If there is an active region, the entries in the region are sorted.
8388 Else, if the cursor is before the first entry, sort the top-level items.
8389 Else, the children of the entry at point are sorted.
8391 Sorting can be alphabetically, numerically, by date/time as given by
8392 a time stamp, by a property, by priority order, or by a custom function.
8394 The command prompts for the sorting type unless it has been given to the
8395 function through the SORTING-TYPE argument, which needs to be a character,
8396 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8397 precise meaning of each character:
8399 n Numerically, by converting the beginning of the entry/item to a number.
8400 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8401 o By order of TODO keywords.
8402 t By date/time, either the first active time stamp in the entry, or, if
8403 none exist, by the first inactive one.
8404 s By the scheduled date/time.
8405 d By deadline date/time.
8406 c By creation time, which is assumed to be the first inactive time stamp
8407 at the beginning of a line.
8408 p By priority according to the cookie.
8409 r By the value of a property.
8411 Capital letters will reverse the sort order.
8413 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8414 called with point at the beginning of the record. It must return either
8415 a string or a number that should serve as the sorting key for that record.
8417 Comparing entries ignores case by default. However, with an optional argument
8418 WITH-CASE, the sorting considers case as well.
8420 Sorting is done against the visible part of the headlines, it ignores hidden
8421 links."
8422 (interactive "P")
8423 (let ((case-func (if with-case 'identity 'downcase))
8424 (cmstr
8425 ;; The clock marker is lost when using `sort-subr', let's
8426 ;; store the clocking string.
8427 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8428 (save-excursion
8429 (goto-char org-clock-marker)
8430 (looking-back "^.*") (match-string-no-properties 0))))
8431 start beg end stars re re2
8432 txt what tmp)
8433 ;; Find beginning and end of region to sort
8434 (cond
8435 ((org-region-active-p)
8436 ;; we will sort the region
8437 (setq end (region-end)
8438 what "region")
8439 (goto-char (region-beginning))
8440 (if (not (org-at-heading-p)) (outline-next-heading))
8441 (setq start (point)))
8442 ((or (org-at-heading-p)
8443 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8444 ;; we will sort the children of the current headline
8445 (org-back-to-heading)
8446 (setq start (point)
8447 end (progn (org-end-of-subtree t t)
8448 (or (bolp) (insert "\n"))
8449 (org-back-over-empty-lines)
8450 (point))
8451 what "children")
8452 (goto-char start)
8453 (show-subtree)
8454 (outline-next-heading))
8456 ;; we will sort the top-level entries in this file
8457 (goto-char (point-min))
8458 (or (org-at-heading-p) (outline-next-heading))
8459 (setq start (point))
8460 (goto-char (point-max))
8461 (beginning-of-line 1)
8462 (when (looking-at ".*?\\S-")
8463 ;; File ends in a non-white line
8464 (end-of-line 1)
8465 (insert "\n"))
8466 (setq end (point-max))
8467 (setq what "top-level")
8468 (goto-char start)
8469 (show-all)))
8471 (setq beg (point))
8472 (if (>= beg end) (error "Nothing to sort"))
8474 (looking-at "\\(\\*+\\)")
8475 (setq stars (match-string 1)
8476 re (concat "^" (regexp-quote stars) " +")
8477 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8478 txt (buffer-substring beg end))
8479 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8480 (if (and (not (equal stars "*")) (string-match re2 txt))
8481 (error "Region to sort contains a level above the first entry"))
8483 (unless sorting-type
8484 (message
8485 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8486 [t]ime [s]cheduled [d]eadline [c]reated
8487 A/N/P/R/O/F/T/S/D/C means reversed:"
8488 what)
8489 (setq sorting-type (read-char-exclusive))
8491 (unless getkey-func
8492 (and (= (downcase sorting-type) ?f)
8493 (setq getkey-func
8494 (org-icompleting-read "Sort using function: "
8495 obarray 'fboundp t nil nil))
8496 (setq getkey-func (intern getkey-func))))
8498 (and (= (downcase sorting-type) ?r)
8499 (not property)
8500 (setq property
8501 (org-icompleting-read "Property: "
8502 (mapcar 'list (org-buffer-property-keys t))
8503 nil t))))
8505 (message "Sorting entries...")
8507 (save-restriction
8508 (narrow-to-region start end)
8509 (let ((dcst (downcase sorting-type))
8510 (case-fold-search nil)
8511 (now (current-time)))
8512 (sort-subr
8513 (/= dcst sorting-type)
8514 ;; This function moves to the beginning character of the "record" to
8515 ;; be sorted.
8516 (lambda nil
8517 (if (re-search-forward re nil t)
8518 (goto-char (match-beginning 0))
8519 (goto-char (point-max))))
8520 ;; This function moves to the last character of the "record" being
8521 ;; sorted.
8522 (lambda nil
8523 (save-match-data
8524 (condition-case nil
8525 (outline-forward-same-level 1)
8526 (error
8527 (goto-char (point-max))))))
8528 ;; This function returns the value that gets sorted against.
8529 (lambda nil
8530 (cond
8531 ((= dcst ?n)
8532 (if (looking-at org-complex-heading-regexp)
8533 (string-to-number (org-sort-remove-invisible (match-string 4)))
8534 nil))
8535 ((= dcst ?a)
8536 (if (looking-at org-complex-heading-regexp)
8537 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8538 nil))
8539 ((= dcst ?t)
8540 (let ((end (save-excursion (outline-next-heading) (point))))
8541 (if (or (re-search-forward org-ts-regexp end t)
8542 (re-search-forward org-ts-regexp-both end t))
8543 (org-time-string-to-seconds (match-string 0))
8544 (org-float-time now))))
8545 ((= dcst ?c)
8546 (let ((end (save-excursion (outline-next-heading) (point))))
8547 (if (re-search-forward
8548 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8549 end t)
8550 (org-time-string-to-seconds (match-string 0))
8551 (org-float-time now))))
8552 ((= dcst ?s)
8553 (let ((end (save-excursion (outline-next-heading) (point))))
8554 (if (re-search-forward org-scheduled-time-regexp end t)
8555 (org-time-string-to-seconds (match-string 1))
8556 (org-float-time now))))
8557 ((= dcst ?d)
8558 (let ((end (save-excursion (outline-next-heading) (point))))
8559 (if (re-search-forward org-deadline-time-regexp end t)
8560 (org-time-string-to-seconds (match-string 1))
8561 (org-float-time now))))
8562 ((= dcst ?p)
8563 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8564 (string-to-char (match-string 2))
8565 org-default-priority))
8566 ((= dcst ?r)
8567 (or (org-entry-get nil property) ""))
8568 ((= dcst ?o)
8569 (if (looking-at org-complex-heading-regexp)
8570 (- 9999 (length (member (match-string 2)
8571 org-todo-keywords-1)))))
8572 ((= dcst ?f)
8573 (if getkey-func
8574 (progn
8575 (setq tmp (funcall getkey-func))
8576 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8577 tmp)
8578 (error "Invalid key function `%s'" getkey-func)))
8579 (t (error "Invalid sorting type `%c'" sorting-type))))
8581 (cond
8582 ((= dcst ?a) 'string<)
8583 ((= dcst ?f) compare-func)
8584 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8585 (run-hooks 'org-after-sorting-entries-or-items-hook)
8586 ;; Reset the clock marker if needed
8587 (when cmstr
8588 (save-excursion
8589 (goto-char start)
8590 (search-forward cmstr nil t)
8591 (move-marker org-clock-marker (point))))
8592 (message "Sorting entries...done")))
8594 (defun org-do-sort (table what &optional with-case sorting-type)
8595 "Sort TABLE of WHAT according to SORTING-TYPE.
8596 The user will be prompted for the SORTING-TYPE if the call to this
8597 function does not specify it. WHAT is only for the prompt, to indicate
8598 what is being sorted. The sorting key will be extracted from
8599 the car of the elements of the table.
8600 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8601 (unless sorting-type
8602 (message
8603 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8604 what)
8605 (setq sorting-type (read-char-exclusive)))
8606 (let ((dcst (downcase sorting-type))
8607 extractfun comparefun)
8608 ;; Define the appropriate functions
8609 (cond
8610 ((= dcst ?n)
8611 (setq extractfun 'string-to-number
8612 comparefun (if (= dcst sorting-type) '< '>)))
8613 ((= dcst ?a)
8614 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8615 (lambda(x) (downcase (org-sort-remove-invisible x))))
8616 comparefun (if (= dcst sorting-type)
8617 'string<
8618 (lambda (a b) (and (not (string< a b))
8619 (not (string= a b)))))))
8620 ((= dcst ?t)
8621 (setq extractfun
8622 (lambda (x)
8623 (if (or (string-match org-ts-regexp x)
8624 (string-match org-ts-regexp-both x))
8625 (org-float-time
8626 (org-time-string-to-time (match-string 0 x)))
8628 comparefun (if (= dcst sorting-type) '< '>)))
8629 (t (error "Invalid sorting type `%c'" sorting-type)))
8631 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8632 table)
8633 (lambda (a b) (funcall comparefun (car a) (car b))))))
8636 ;;; The orgstruct minor mode
8638 ;; Define a minor mode which can be used in other modes in order to
8639 ;; integrate the org-mode structure editing commands.
8641 ;; This is really a hack, because the org-mode structure commands use
8642 ;; keys which normally belong to the major mode. Here is how it
8643 ;; works: The minor mode defines all the keys necessary to operate the
8644 ;; structure commands, but wraps the commands into a function which
8645 ;; tests if the cursor is currently at a headline or a plain list
8646 ;; item. If that is the case, the structure command is used,
8647 ;; temporarily setting many Org-mode variables like regular
8648 ;; expressions for filling etc. However, when any of those keys is
8649 ;; used at a different location, function uses `key-binding' to look
8650 ;; up if the key has an associated command in another currently active
8651 ;; keymap (minor modes, major mode, global), and executes that
8652 ;; command. There might be problems if any of the keys is otherwise
8653 ;; used as a prefix key.
8655 (defcustom orgstruct-heading-prefix-regexp ""
8656 "Regexp that matches the custom prefix of Org headlines in
8657 orgstruct(++)-mode."
8658 :group 'org
8659 :version "24.4"
8660 :package-version '(Org . "8.0")
8661 :type 'string)
8662 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8664 (defcustom orgstruct-setup-hook nil
8665 "Hook run after orgstruct-mode-map is filled."
8666 :group 'org
8667 :version "24.4"
8668 :package-version '(Org . "8.0")
8669 :type 'hook)
8671 (defvar orgstruct-initialized nil)
8673 (defvar org-local-vars nil
8674 "List of local variables, for use by `orgstruct-mode'.")
8676 ;;;###autoload
8677 (define-minor-mode orgstruct-mode
8678 "Toggle the minor mode `orgstruct-mode'.
8679 This mode is for using Org-mode structure commands in other
8680 modes. The following keys behave as if Org-mode were active, if
8681 the cursor is on a headline, or on a plain list item (both as
8682 defined by Org-mode)."
8683 nil " OrgStruct" (make-sparse-keymap)
8684 (when orgstruct-mode
8685 (org-load-modules-maybe)
8686 (unless orgstruct-initialized
8687 (orgstruct-setup)
8688 (setq orgstruct-initialized t))))
8690 ;;;###autoload
8691 (defun turn-on-orgstruct ()
8692 "Unconditionally turn on `orgstruct-mode'."
8693 (orgstruct-mode 1))
8695 (defvar org-fb-vars nil)
8696 (make-variable-buffer-local 'org-fb-vars)
8697 (defun orgstruct++-mode (&optional arg)
8698 "Toggle `orgstruct-mode', the enhanced version of it.
8699 In addition to setting orgstruct-mode, this also exports all
8700 indentation and autofilling variables from org-mode into the
8701 buffer. It will also recognize item context in multiline items."
8702 (interactive "P")
8703 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8704 (if (< arg 1)
8705 (progn (orgstruct-mode -1)
8706 (mapc (lambda(v)
8707 (org-set-local (car v)
8708 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8709 org-fb-vars))
8710 (orgstruct-mode 1)
8711 (setq org-fb-vars nil)
8712 (let (var val)
8713 (mapc
8714 (lambda (x)
8715 (when (string-match
8716 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8717 (symbol-name (car x)))
8718 (setq var (car x) val (nth 1 x))
8719 (push (list var `(quote ,(eval var))) org-fb-vars)
8720 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8721 org-local-vars)
8722 (org-set-local 'orgstruct-is-++ t))))
8724 (defvar orgstruct-is-++ nil
8725 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8726 (make-variable-buffer-local 'orgstruct-is-++)
8728 ;;;###autoload
8729 (defun turn-on-orgstruct++ ()
8730 "Unconditionally turn on `orgstruct++-mode'."
8731 (orgstruct++-mode 1))
8733 (defun orgstruct-error ()
8734 "Error when there is no default binding for a structure key."
8735 (interactive)
8736 (error "This key has no function outside structure elements"))
8738 (defun orgstruct-setup ()
8739 "Setup orgstruct keymap."
8740 (dolist (f
8741 '("org-meta"
8742 "org-shift"
8743 "org-shiftmeta"
8744 org-shifttab
8745 org-backward-element
8746 org-backward-heading-same-level
8747 org-ctrl-c-ret
8748 org-cycle
8749 org-forward-heading-same-level
8750 org-insert-heading
8751 org-insert-heading-respect-content
8752 org-kill-note-or-show-branches
8753 org-mark-subtree
8754 org-narrow-to-subtree
8755 org-promote-subtree
8756 org-reveal
8757 org-show-subtree
8758 org-sort
8759 org-up-element
8760 outline-demote
8761 outline-next-visible-heading
8762 outline-previous-visible-heading
8763 outline-promote
8764 outline-up-heading
8765 show-children))
8766 (dolist (f (if (stringp f)
8767 (let ((flist))
8768 (dolist (postfix
8769 '("-return" "tab" "left" "right" "up" "down")
8770 flist)
8771 (let ((f (intern (concat f postfix))))
8772 (when (fboundp f)
8773 (push f flist)))))
8774 (list f)))
8775 (dolist (binding (nconc (where-is-internal f org-mode-map)
8776 (where-is-internal f outline-mode-map)))
8777 ;; TODO use local-function-key-map
8778 (dolist (rep '(("<tab>" . "TAB")
8779 ("<return>" . "RET")
8780 ("<escape>" . "ESC")
8781 ("<delete>" . "DEL")))
8782 (setq binding (read-kbd-macro (replace-regexp-in-string
8783 (regexp-quote (car rep))
8784 (cdr rep)
8785 (key-description binding)))))
8786 (let ((key (lookup-key orgstruct-mode-map binding)))
8787 (when (or (not key) (numberp key))
8788 (condition-case nil
8789 (org-defkey orgstruct-mode-map
8790 binding
8791 (orgstruct-make-binding f binding))
8792 (error nil)))))))
8793 (run-hooks 'orgstruct-setup-hook))
8795 (defun orgstruct-make-binding (fun key)
8796 "Create a function for binding in the structure minor mode.
8797 FUN is the command to call inside a table. KEY is the key that
8798 should be checked in for a command to execute outside of tables."
8799 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8800 (let ((nname name)
8801 (i 0))
8802 (while (fboundp (intern nname))
8803 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8804 (setq name (intern nname)))
8805 (eval
8806 (let ((bindings '((org-heading-regexp
8807 (concat "^"
8808 orgstruct-heading-prefix-regexp
8809 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8810 (org-outline-regexp
8811 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8812 (org-outline-regexp-bol
8813 (concat "^" org-outline-regexp))
8814 (outline-regexp org-outline-regexp)
8815 (outline-heading-end-regexp "\n")
8816 (outline-level 'outline-level)
8817 (outline-heading-alist))))
8818 `(defun ,name (arg)
8819 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8820 "Outside of structure, run the binding of `"
8821 (key-description key) "'.")
8822 (interactive "p")
8823 (unless
8824 (let* ,bindings
8825 (when (org-context-p 'headline 'item
8826 ,(when (memq fun '(org-insert-heading))
8827 '(when orgstruct-is-++
8828 'item-body)))
8829 (org-run-like-in-org-mode
8830 (lambda ()
8831 (interactive)
8832 (let* ,bindings
8833 (call-interactively ',fun))))
8835 (let* ((orgstruct-mode)
8836 (binding (key-binding ,key)))
8837 (if (keymapp binding)
8838 (set-temporary-overlay-map binding)
8839 (call-interactively
8840 (or binding 'orgstruct-error))))))))
8841 name))
8843 (defun org-contextualize-keys (alist contexts)
8844 "Return valid elements in ALIST depending on CONTEXTS.
8846 `org-agenda-custom-commands' or `org-capture-templates' are the
8847 values used for ALIST, and `org-agenda-custom-commands-contexts'
8848 or `org-capture-templates-contexts' are the associated contexts
8849 definitions."
8850 (let ((contexts
8851 ;; normalize contexts
8852 (mapcar
8853 (lambda(c) (cond ((listp (cadr c))
8854 (list (car c) (car c) (cadr c)))
8855 ((string= "" (cadr c))
8856 (list (car c) (car c) (caddr c)))
8857 (t c))) contexts))
8858 (a alist) c r s)
8859 ;; loop over all commands or templates
8860 (while (setq c (pop a))
8861 (let (vrules repl)
8862 (cond
8863 ((not (assoc (car c) contexts))
8864 (push c r))
8865 ((and (assoc (car c) contexts)
8866 (setq vrules (org-contextualize-validate-key
8867 (car c) contexts)))
8868 (mapc (lambda (vr)
8869 (when (not (equal (car vr) (cadr vr)))
8870 (setq repl vr))) vrules)
8871 (if (not repl) (push c r)
8872 (push (cadr repl) s)
8873 (push
8874 (cons (car c)
8875 (cdr (or (assoc (cadr repl) alist)
8876 (error "Undefined key `%s' as contextual replacement for `%s'"
8877 (cadr repl) (car c)))))
8878 r))))))
8879 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8880 (delq
8882 (delete-dups
8883 (mapcar (lambda (x)
8884 (let ((tpl (car x)))
8885 (when (not (delq
8887 (mapcar (lambda(y)
8888 (equal y tpl)) s))) x)))
8889 (reverse r))))))
8891 (defun org-contextualize-validate-key (key contexts)
8892 "Check CONTEXTS for agenda or capture KEY."
8893 (let (r rr res)
8894 (while (setq r (pop contexts))
8895 (mapc
8896 (lambda (rr)
8897 (when
8898 (and (equal key (car r))
8899 (if (functionp rr) (funcall rr)
8900 (or (and (eq (car rr) 'in-file)
8901 (buffer-file-name)
8902 (string-match (cdr rr) (buffer-file-name)))
8903 (and (eq (car rr) 'in-mode)
8904 (string-match (cdr rr) (symbol-name major-mode)))
8905 (and (eq (car rr) 'in-buffer)
8906 (string-match (cdr rr) (buffer-name)))
8907 (when (and (eq (car rr) 'not-in-file)
8908 (buffer-file-name))
8909 (not (string-match (cdr rr) (buffer-file-name))))
8910 (when (eq (car rr) 'not-in-mode)
8911 (not (string-match (cdr rr) (symbol-name major-mode))))
8912 (when (eq (car rr) 'not-in-buffer)
8913 (not (string-match (cdr rr) (buffer-name)))))))
8914 (push r res)))
8915 (car (last r))))
8916 (delete-dups (delq nil res))))
8918 (defun org-context-p (&rest contexts)
8919 "Check if local context is any of CONTEXTS.
8920 Possible values in the list of contexts are `table', `headline', and `item'."
8921 (let ((pos (point)))
8922 (goto-char (point-at-bol))
8923 (prog1 (or (and (memq 'table contexts)
8924 (looking-at "[ \t]*|"))
8925 (and (memq 'headline contexts)
8926 (looking-at org-outline-regexp))
8927 (and (memq 'item contexts)
8928 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8929 (and (memq 'item-body contexts)
8930 (org-in-item-p)))
8931 (goto-char pos))))
8933 (defun org-get-local-variables ()
8934 "Return a list of all local variables in an Org mode buffer."
8935 (let (varlist)
8936 (with-current-buffer (get-buffer-create "*Org tmp*")
8937 (erase-buffer)
8938 (org-mode)
8939 (setq varlist (buffer-local-variables)))
8940 (kill-buffer "*Org tmp*")
8941 (delq nil
8942 (mapcar
8943 (lambda (x)
8944 (setq x
8945 (if (symbolp x)
8946 (list x)
8947 (list (car x) (cdr x))))
8948 (if (and (not (get (car x) 'org-state))
8949 (string-match
8950 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8951 (symbol-name (car x))))
8952 x nil))
8953 varlist))))
8955 (defun org-clone-local-variables (from-buffer &optional regexp)
8956 "Clone local variables from FROM-BUFFER.
8957 Optional argument REGEXP selects variables to clone."
8958 (mapc
8959 (lambda (pair)
8960 (and (symbolp (car pair))
8961 (or (null regexp)
8962 (string-match regexp (symbol-name (car pair))))
8963 (set (make-local-variable (car pair))
8964 (cdr pair))))
8965 (buffer-local-variables from-buffer)))
8967 ;;;###autoload
8968 (defun org-run-like-in-org-mode (cmd)
8969 "Run a command, pretending that the current buffer is in Org-mode.
8970 This will temporarily bind local variables that are typically bound in
8971 Org-mode to the values they have in Org-mode, and then interactively
8972 call CMD."
8973 (org-load-modules-maybe)
8974 (unless org-local-vars
8975 (setq org-local-vars (org-get-local-variables)))
8976 (let (binds)
8977 (dolist (var org-local-vars)
8978 (when (or (not (boundp (car var)))
8979 (eq (symbol-value (car var))
8980 (default-value (car var))))
8981 (push (list (car var) `(quote ,(cadr var))) binds)))
8982 (eval `(let ,binds
8983 (call-interactively (quote ,cmd))))))
8985 ;;;; Archiving
8987 (defun org-get-category (&optional pos force-refresh)
8988 "Get the category applying to position POS."
8989 (save-match-data
8990 (if force-refresh (org-refresh-category-properties))
8991 (let ((pos (or pos (point))))
8992 (or (get-text-property pos 'org-category)
8993 (progn (org-refresh-category-properties)
8994 (get-text-property pos 'org-category))))))
8996 (defun org-refresh-category-properties ()
8997 "Refresh category text properties in the buffer."
8998 (let ((case-fold-search t)
8999 (inhibit-read-only t)
9000 (def-cat (cond
9001 ((null org-category)
9002 (if buffer-file-name
9003 (file-name-sans-extension
9004 (file-name-nondirectory buffer-file-name))
9005 "???"))
9006 ((symbolp org-category) (symbol-name org-category))
9007 (t org-category)))
9008 beg end cat pos optionp)
9009 (org-with-silent-modifications
9010 (save-excursion
9011 (save-restriction
9012 (widen)
9013 (goto-char (point-min))
9014 (put-text-property (point) (point-max) 'org-category def-cat)
9015 (while (re-search-forward
9016 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9017 (setq pos (match-end 0)
9018 optionp (equal (char-after (match-beginning 0)) ?#)
9019 cat (org-trim (match-string 2)))
9020 (if optionp
9021 (setq beg (point-at-bol) end (point-max))
9022 (org-back-to-heading t)
9023 (setq beg (point) end (org-end-of-subtree t t)))
9024 (put-text-property beg end 'org-category cat)
9025 (put-text-property beg end 'org-category-position beg)
9026 (goto-char pos)))))))
9028 (defun org-refresh-properties (dprop tprop)
9029 "Refresh buffer text properties.
9030 DPROP is the drawer property and TPROP is the corresponding text
9031 property to set."
9032 (let ((case-fold-search t)
9033 (inhibit-read-only t) p)
9034 (org-with-silent-modifications
9035 (save-excursion
9036 (save-restriction
9037 (widen)
9038 (goto-char (point-min))
9039 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9040 (setq p (org-match-string-no-properties 1))
9041 (save-excursion
9042 (org-back-to-heading t)
9043 (put-text-property
9044 (point-at-bol) (point-at-eol) tprop p))))))))
9047 ;;;; Link Stuff
9049 ;;; Link abbreviations
9051 (defun org-link-expand-abbrev (link)
9052 "Apply replacements as defined in `org-link-abbrev-alist'."
9053 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9054 (let* ((key (match-string 1 link))
9055 (as (or (assoc key org-link-abbrev-alist-local)
9056 (assoc key org-link-abbrev-alist)))
9057 (tag (and (match-end 2) (match-string 3 link)))
9058 rpl)
9059 (if (not as)
9060 link
9061 (setq rpl (cdr as))
9062 (cond
9063 ((symbolp rpl) (funcall rpl tag))
9064 ((string-match "%(\\([^)]+\\))" rpl)
9065 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9066 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9067 ((string-match "%h" rpl)
9068 (replace-match (url-hexify-string (or tag "")) t t rpl))
9069 (t (concat rpl tag)))))
9070 link))
9072 ;;; Storing and inserting links
9074 (defvar org-insert-link-history nil
9075 "Minibuffer history for links inserted with `org-insert-link'.")
9077 (defvar org-stored-links nil
9078 "Contains the links stored with `org-store-link'.")
9080 (defvar org-store-link-plist nil
9081 "Plist with info about the most recently link created with `org-store-link'.")
9083 (defvar org-link-protocols nil
9084 "Link protocols added to Org-mode using `org-add-link-type'.")
9086 (defvar org-store-link-functions nil
9087 "List of functions that are called to create and store a link.
9088 Each function will be called in turn until one returns a non-nil
9089 value. Each function should check if it is responsible for creating
9090 this link (for example by looking at the major mode).
9091 If not, it must exit and return nil.
9092 If yes, it should return a non-nil value after a calling
9093 `org-store-link-props' with a list of properties and values.
9094 Special properties are:
9096 :type The link prefix, like \"http\". This must be given.
9097 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9098 This is obligatory as well.
9099 :description Optional default description for the second pair
9100 of brackets in an Org-mode link. The user can still change
9101 this when inserting this link into an Org-mode buffer.
9103 In addition to these, any additional properties can be specified
9104 and then used in capture templates.")
9106 (defun org-add-link-type (type &optional follow export)
9107 "Add TYPE to the list of `org-link-types'.
9108 Re-compute all regular expressions depending on `org-link-types'
9110 FOLLOW and EXPORT are two functions.
9112 FOLLOW should take the link path as the single argument and do whatever
9113 is necessary to follow the link, for example find a file or display
9114 a mail message.
9116 EXPORT should format the link path for export to one of the export formats.
9117 It should be a function accepting three arguments:
9119 path the path of the link, the text after the prefix (like \"http:\")
9120 desc the description of the link, if any, or a description added by
9121 org-export-normalize-links if there is none
9122 format the export format, a symbol like `html' or `latex' or `ascii'..
9124 The function may use the FORMAT information to return different values
9125 depending on the format. The return value will be put literally into
9126 the exported file. If the return value is nil, this means Org should
9127 do what it normally does with links which do not have EXPORT defined.
9129 Org-mode has a built-in default for exporting links. If you are happy with
9130 this default, there is no need to define an export function for the link
9131 type. For a simple example of an export function, see `org-bbdb.el'."
9132 (add-to-list 'org-link-types type t)
9133 (org-make-link-regexps)
9134 (if (assoc type org-link-protocols)
9135 (setcdr (assoc type org-link-protocols) (list follow export))
9136 (push (list type follow export) org-link-protocols)))
9138 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9139 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9141 ;;;###autoload
9142 (defun org-store-link (arg)
9143 "\\<org-mode-map>Store an org-link to the current location.
9144 This link is added to `org-stored-links' and can later be inserted
9145 into an org-buffer with \\[org-insert-link].
9147 For some link types, a prefix arg is interpreted.
9148 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9149 For file links, arg negates `org-context-in-file-links'.
9151 A double prefix arg force skipping storing functions that are not
9152 part of Org's core."
9153 (interactive "P")
9154 (org-load-modules-maybe)
9155 (setq org-store-link-plist nil) ; reset
9156 (org-with-limited-levels
9157 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9158 (cond
9159 ((and (not (equal arg '(16)))
9160 (setq sfuns
9161 (delq
9162 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9163 org-store-link-functions))
9164 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9165 (or (and (cdr sfuns)
9166 (funcall (intern
9167 (completing-read "Which function for creating the link? "
9168 sfunsn t (car sfunsn)))))
9169 (funcall (caar sfuns)))
9170 (setq link (plist-get org-store-link-plist :link)
9171 desc (or (plist-get org-store-link-plist :description) link))))
9172 ((org-src-edit-buffer-p)
9173 (let (label gc)
9174 (while (or (not label)
9175 (save-excursion
9176 (save-restriction
9177 (widen)
9178 (goto-char (point-min))
9179 (re-search-forward
9180 (regexp-quote (format org-coderef-label-format label))
9181 nil t))))
9182 (when label (message "Label exists already") (sit-for 2))
9183 (setq label (read-string "Code line label: " label)))
9184 (end-of-line 1)
9185 (setq link (format org-coderef-label-format label))
9186 (setq gc (- 79 (length link)))
9187 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9188 (insert link)
9189 (setq link (concat "(" label ")") desc nil)))
9191 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9192 ;; We are in the agenda, link to referenced location
9193 (let ((m (or (get-text-property (point) 'org-hd-marker)
9194 (get-text-property (point) 'org-marker))))
9195 (when m
9196 (org-with-point-at m
9197 (setq agenda-link
9198 (if (org-called-interactively-p 'any)
9199 (call-interactively 'org-store-link)
9200 (org-store-link nil)))))))
9202 ((eq major-mode 'calendar-mode)
9203 (let ((cd (calendar-cursor-to-date)))
9204 (setq link
9205 (format-time-string
9206 (car org-time-stamp-formats)
9207 (apply 'encode-time
9208 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9209 nil nil nil))))
9210 (org-store-link-props :type "calendar" :date cd)))
9212 ((eq major-mode 'help-mode)
9213 (setq link (concat "help:" (save-excursion
9214 (goto-char (point-min))
9215 (looking-at "^[^ ]+")
9216 (match-string 0))))
9217 (org-store-link-props :type "help"))
9219 ((eq major-mode 'w3-mode)
9220 (setq cpltxt (if (and (buffer-name)
9221 (not (string-match "Untitled" (buffer-name))))
9222 (buffer-name)
9223 (url-view-url t))
9224 link (url-view-url t))
9225 (org-store-link-props :type "w3" :url (url-view-url t)))
9227 ((setq search (run-hook-with-args-until-success
9228 'org-create-file-search-functions))
9229 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9230 "::" search))
9231 (setq cpltxt (or description link)))
9233 ((eq major-mode 'image-mode)
9234 (setq cpltxt (concat "file:"
9235 (abbreviate-file-name buffer-file-name))
9236 link cpltxt)
9237 (org-store-link-props :type "image" :file buffer-file-name))
9239 ((eq major-mode 'dired-mode)
9240 ;; link to the file in the current line
9241 (let ((file (dired-get-filename nil t)))
9242 (setq file (if file
9243 (abbreviate-file-name
9244 (expand-file-name (dired-get-filename nil t)))
9245 ;; otherwise, no file so use current directory.
9246 default-directory))
9247 (setq cpltxt (concat "file:" file)
9248 link cpltxt)))
9250 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9251 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9252 (cond
9253 ((org-in-regexp "<<\\(.*?\\)>>")
9254 (setq cpltxt
9255 (concat "file:"
9256 (abbreviate-file-name
9257 (buffer-file-name (buffer-base-buffer)))
9258 "::" (match-string 1))
9259 link cpltxt))
9260 ((and (featurep 'org-id)
9261 (or (eq org-id-link-to-org-use-id t)
9262 (and (org-called-interactively-p 'any)
9263 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9264 (and (eq org-id-link-to-org-use-id
9265 'create-if-interactive-and-no-custom-id)
9266 (not custom-id))))
9267 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9268 ;; We can make a link using the ID.
9269 (setq link (condition-case nil
9270 (prog1 (org-id-store-link)
9271 (setq desc (plist-get org-store-link-plist :description)))
9272 (error
9273 ;; probably before first headline, link to file only
9274 (concat "file:"
9275 (abbreviate-file-name
9276 (buffer-file-name (buffer-base-buffer))))))))
9278 ;; Just link to current headline
9279 (setq cpltxt (concat "file:"
9280 (abbreviate-file-name
9281 (buffer-file-name (buffer-base-buffer)))))
9282 ;; Add a context search string
9283 (when (org-xor org-context-in-file-links arg)
9284 (let* ((ee (org-element-at-point))
9285 (et (org-element-type ee))
9286 (ev (plist-get (cadr ee) :value)))
9287 (setq txt (cond
9288 ((org-at-heading-p) nil)
9289 ((eq et 'keyword) ev)
9290 ((org-region-active-p)
9291 (buffer-substring (region-beginning) (region-end)))))
9292 (when (or (null txt) (string-match "\\S-" txt))
9293 (setq cpltxt
9294 (concat cpltxt "::"
9295 (condition-case nil
9296 (org-make-org-heading-search-string txt)
9297 (error "")))
9298 desc (or (and (eq et 'keyword) ev)
9299 (nth 4 (ignore-errors (org-heading-components)))
9300 "NONE")))))
9301 (if (string-match "::\\'" cpltxt)
9302 (setq cpltxt (substring cpltxt 0 -2)))
9303 (setq link cpltxt))))
9305 ((buffer-file-name (buffer-base-buffer))
9306 ;; Just link to this file here.
9307 (setq cpltxt (concat "file:"
9308 (abbreviate-file-name
9309 (buffer-file-name (buffer-base-buffer)))))
9310 ;; Add a context string
9311 (when (org-xor org-context-in-file-links arg)
9312 (setq txt (if (org-region-active-p)
9313 (buffer-substring (region-beginning) (region-end))
9314 (buffer-substring (point-at-bol) (point-at-eol))))
9315 ;; Only use search option if there is some text.
9316 (when (string-match "\\S-" txt)
9317 (setq cpltxt
9318 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9319 desc "NONE")))
9320 (setq link cpltxt))
9322 ((org-called-interactively-p 'interactive)
9323 (user-error "No method for storing a link from this buffer"))
9325 (t (setq link nil)))
9327 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9328 (setq link (or link cpltxt)
9329 desc (or desc cpltxt))
9330 (cond ((equal desc "NONE") (setq desc nil))
9331 ((string-match org-bracket-link-regexp desc)
9332 (setq desc (replace-regexp-in-string
9333 org-bracket-link-regexp
9334 (concat "\\3" (if (equal (length (match-string 0 desc))
9335 (length desc)) "*" "")) desc))))
9337 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9338 (progn
9339 (setq org-stored-links
9340 (cons (list link desc) org-stored-links))
9341 (message "Stored: %s" (or desc link))
9342 (when custom-id
9343 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9344 "::#" custom-id))
9345 (setq org-stored-links
9346 (cons (list link desc) org-stored-links))))
9347 (or agenda-link (and link (org-make-link-string link desc)))))))
9349 (defun org-store-link-props (&rest plist)
9350 "Store link properties, extract names and addresses."
9351 (let (x adr)
9352 (when (setq x (plist-get plist :from))
9353 (setq adr (mail-extract-address-components x))
9354 (setq plist (plist-put plist :fromname (car adr)))
9355 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9356 (when (setq x (plist-get plist :to))
9357 (setq adr (mail-extract-address-components x))
9358 (setq plist (plist-put plist :toname (car adr)))
9359 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9360 (let ((from (plist-get plist :from))
9361 (to (plist-get plist :to)))
9362 (when (and from to org-from-is-user-regexp)
9363 (setq plist
9364 (plist-put plist :fromto
9365 (if (string-match org-from-is-user-regexp from)
9366 (concat "to %t")
9367 (concat "from %f"))))))
9368 (setq org-store-link-plist plist))
9370 (defun org-add-link-props (&rest plist)
9371 "Add these properties to the link property list."
9372 (let (key value)
9373 (while plist
9374 (setq key (pop plist) value (pop plist))
9375 (setq org-store-link-plist
9376 (plist-put org-store-link-plist key value)))))
9378 (defun org-email-link-description (&optional fmt)
9379 "Return the description part of an email link.
9380 This takes information from `org-store-link-plist' and formats it
9381 according to FMT (default from `org-email-link-description-format')."
9382 (setq fmt (or fmt org-email-link-description-format))
9383 (let* ((p org-store-link-plist)
9384 (to (plist-get p :toaddress))
9385 (from (plist-get p :fromaddress))
9386 (table
9387 (list
9388 (cons "%c" (plist-get p :fromto))
9389 (cons "%F" (plist-get p :from))
9390 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9391 (cons "%T" (plist-get p :to))
9392 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9393 (cons "%s" (plist-get p :subject))
9394 (cons "%d" (plist-get p :date))
9395 (cons "%m" (plist-get p :message-id)))))
9396 (when (string-match "%c" fmt)
9397 ;; Check if the user wrote this message
9398 (if (and org-from-is-user-regexp from to
9399 (save-match-data (string-match org-from-is-user-regexp from)))
9400 (setq fmt (replace-match "to %t" t t fmt))
9401 (setq fmt (replace-match "from %f" t t fmt))))
9402 (org-replace-escapes fmt table)))
9404 (defun org-make-org-heading-search-string (&optional string)
9405 "Make search string for the current headline or STRING."
9406 (let ((s (or string
9407 (and (derived-mode-p 'org-mode)
9408 (save-excursion
9409 (org-back-to-heading t)
9410 (org-element-property :raw-value (org-element-at-point))))))
9411 (lines org-context-in-file-links))
9412 (or string (setq s (concat "*" s))) ; Add * for headlines
9413 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9414 (when (and string (integerp lines) (> lines 0))
9415 (let ((slines (org-split-string s "\n")))
9416 (when (< lines (length slines))
9417 (setq s (mapconcat
9418 'identity
9419 (reverse (nthcdr (- (length slines) lines)
9420 (reverse slines))) "\n")))))
9421 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9423 (defun org-make-link-string (link &optional description)
9424 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9425 (unless (string-match "\\S-" link)
9426 (error "Empty link"))
9427 (when (and description
9428 (stringp description)
9429 (not (string-match "\\S-" description)))
9430 (setq description nil))
9431 (when (stringp description)
9432 ;; Remove brackets from the description, they are fatal.
9433 (while (string-match "\\[" description)
9434 (setq description (replace-match "{" t t description)))
9435 (while (string-match "\\]" description)
9436 (setq description (replace-match "}" t t description))))
9437 (when (equal link description)
9438 ;; No description needed, it is identical
9439 (setq description nil))
9440 (when (and (not description)
9441 (not (string-match (org-image-file-name-regexp) link))
9442 (not (equal link (org-link-escape link))))
9443 (setq description (org-extract-attributes link)))
9444 (setq link
9445 (cond ((string-match (org-image-file-name-regexp) link) link)
9446 ((string-match org-link-types-re link)
9447 (concat (match-string 1 link)
9448 (org-link-escape (substring link (match-end 1)))))
9449 (t (org-link-escape link))))
9450 (concat "[[" link "]"
9451 (if description (concat "[" description "]") "")
9452 "]"))
9454 (defconst org-link-escape-chars
9455 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9456 "List of characters that should be escaped in link.
9457 This is the list that is used for internal purposes.")
9459 (defconst org-link-escape-chars-browser
9460 '(?\ )
9461 "List of escapes for characters that are problematic in links.
9462 This is the list that is used before handing over to the browser.")
9464 (defun org-link-escape (text &optional table merge)
9465 "Return percent escaped representation of TEXT.
9466 TEXT is a string with the text to escape.
9467 Optional argument TABLE is a list with characters that should be
9468 escaped. When nil, `org-link-escape-chars' is used.
9469 If optional argument MERGE is set, merge TABLE into
9470 `org-link-escape-chars'."
9471 (cond
9472 ((and table merge)
9473 (mapc (lambda (defchr)
9474 (unless (member defchr table)
9475 (setq table (cons defchr table)))) org-link-escape-chars))
9476 ((null table)
9477 (setq table org-link-escape-chars)))
9478 (mapconcat
9479 (lambda (char)
9480 (if (or (member char table)
9481 (and (or (< char 32) (= char 37) (> char 126))
9482 org-url-hexify-p))
9483 (mapconcat (lambda (sequence-element)
9484 (format "%%%.2X" sequence-element))
9485 (or (encode-coding-char char 'utf-8)
9486 (error "Unable to percent escape character: %s"
9487 (char-to-string char))) "")
9488 (char-to-string char))) text ""))
9490 (defun org-link-unescape (str)
9491 "Unhex hexified Unicode strings as returned from the JavaScript function
9492 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9493 (unless (and (null str) (string= "" str))
9494 (let ((pos 0) (case-fold-search t) unhexed)
9495 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9496 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9497 (setq str (replace-match unhexed t t str))
9498 (setq pos (+ pos (length unhexed))))))
9499 str)
9501 (defun org-link-unescape-compound (hex)
9502 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9503 Note: this function also decodes single byte encodings like
9504 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9505 (save-match-data
9506 (let* ((bytes (cdr (split-string hex "%")))
9507 (ret "")
9508 (eat 0)
9509 (sum 0))
9510 (while bytes
9511 (let* ((val (string-to-number (pop bytes) 16))
9512 (shift-xor
9513 (if (= 0 eat)
9514 (cond
9515 ((>= val 252) (cons 6 252))
9516 ((>= val 248) (cons 5 248))
9517 ((>= val 240) (cons 4 240))
9518 ((>= val 224) (cons 3 224))
9519 ((>= val 192) (cons 2 192))
9520 (t (cons 0 0)))
9521 (cons 6 128))))
9522 (if (>= val 192) (setq eat (car shift-xor)))
9523 (setq val (logxor val (cdr shift-xor)))
9524 (setq sum (+ (lsh sum (car shift-xor)) val))
9525 (if (> eat 0) (setq eat (- eat 1)))
9526 (cond
9527 ((= 0 eat) ;multi byte
9528 (setq ret (concat ret (org-char-to-string sum)))
9529 (setq sum 0))
9530 ((not bytes) ; single byte(s)
9531 (setq ret (org-link-unescape-single-byte-sequence hex))))
9532 )) ;; end (while bytes
9533 ret )))
9535 (defun org-link-unescape-single-byte-sequence (hex)
9536 "Unhexify hex-encoded single byte character sequences."
9537 (mapconcat (lambda (byte)
9538 (char-to-string (string-to-number byte 16)))
9539 (cdr (split-string hex "%")) ""))
9541 (defun org-xor (a b)
9542 "Exclusive or."
9543 (if a (not b) b))
9545 (defun org-fixup-message-id-for-http (s)
9546 "Replace special characters in a message id, so it can be used in an http query."
9547 (when (string-match "%" s)
9548 (setq s (mapconcat (lambda (c)
9549 (if (eq c ?%)
9550 "%25"
9551 (char-to-string c)))
9552 s "")))
9553 (while (string-match "<" s)
9554 (setq s (replace-match "%3C" t t s)))
9555 (while (string-match ">" s)
9556 (setq s (replace-match "%3E" t t s)))
9557 (while (string-match "@" s)
9558 (setq s (replace-match "%40" t t s)))
9561 (defun org-link-prettify (link)
9562 "Return a human-readable representation of LINK.
9563 The car of LINK must be a raw link the cdr of LINK must be either
9564 a link description or nil."
9565 (let ((desc (or (cadr link) "<no description>")))
9566 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9567 "<" (car link) ">")))
9569 ;;;###autoload
9570 (defun org-insert-link-global ()
9571 "Insert a link like Org-mode does.
9572 This command can be called in any mode to insert a link in Org-mode syntax."
9573 (interactive)
9574 (org-load-modules-maybe)
9575 (org-run-like-in-org-mode 'org-insert-link))
9577 (defun org-insert-all-links (&optional keep)
9578 "Insert all links in `org-stored-links'."
9579 (interactive "P")
9580 (let ((links (copy-sequence org-stored-links)) l)
9581 (while (setq l (if keep (pop links) (pop org-stored-links)))
9582 (insert "- ")
9583 (org-insert-link nil (car l) (cadr l))
9584 (insert "\n"))))
9586 (defun org-link-fontify-links-to-this-file ()
9587 "Fontify links to the current file in `org-stored-links'."
9588 (let ((f (buffer-file-name)) a b)
9589 (setq a (mapcar (lambda(l)
9590 (let ((ll (car l)))
9591 (when (and (string-match "^file:\\(.+\\)::" ll)
9592 (equal f (expand-file-name (match-string 1 ll))))
9593 ll)))
9594 org-stored-links))
9595 (when (featurep 'org-id)
9596 (setq b (mapcar (lambda(l)
9597 (let ((ll (car l)))
9598 (when (and (string-match "^id:\\(.+\\)$" ll)
9599 (equal f (expand-file-name
9600 (or (org-id-find-id-file
9601 (match-string 1 ll)) ""))))
9602 ll)))
9603 org-stored-links)))
9604 (mapcar (lambda(l)
9605 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9606 (delq nil (append a b)))))
9608 (defvar org-link-links-in-this-file nil)
9609 (defun org-insert-link (&optional complete-file link-location default-description)
9610 "Insert a link. At the prompt, enter the link.
9612 Completion can be used to insert any of the link protocol prefixes like
9613 http or ftp in use.
9615 The history can be used to select a link previously stored with
9616 `org-store-link'. When the empty string is entered (i.e. if you just
9617 press RET at the prompt), the link defaults to the most recently
9618 stored link. As SPC triggers completion in the minibuffer, you need to
9619 use M-SPC or C-q SPC to force the insertion of a space character.
9621 You will also be prompted for a description, and if one is given, it will
9622 be displayed in the buffer instead of the link.
9624 If there is already a link at point, this command will allow you to edit link
9625 and description parts.
9627 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9628 be selected using completion. The path to the file will be relative to the
9629 current directory if the file is in the current directory or a subdirectory.
9630 Otherwise, the link will be the absolute path as completed in the minibuffer
9631 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9632 option `org-link-file-path-type'.
9634 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9635 the current directory or below.
9637 With three \\[universal-argument] prefixes, negate the meaning of
9638 `org-keep-stored-link-after-insertion'.
9640 If `org-make-link-description-function' is non-nil, this function will be
9641 called with the link target, and the result will be the default
9642 link description.
9644 If the LINK-LOCATION parameter is non-nil, this value will be
9645 used as the link location instead of reading one interactively.
9647 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9648 be used as the default description."
9649 (interactive "P")
9650 (let* ((wcf (current-window-configuration))
9651 (origbuf (current-buffer))
9652 (region (if (org-region-active-p)
9653 (buffer-substring (region-beginning) (region-end))))
9654 (remove (and region (list (region-beginning) (region-end))))
9655 (desc region)
9656 tmphist ; byte-compile incorrectly complains about this
9657 (link link-location)
9658 (abbrevs org-link-abbrev-alist-local)
9659 entry file all-prefixes auto-desc)
9660 (cond
9661 (link-location) ; specified by arg, just use it.
9662 ((org-in-regexp org-bracket-link-regexp 1)
9663 ;; We do have a link at point, and we are going to edit it.
9664 (setq remove (list (match-beginning 0) (match-end 0)))
9665 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9666 (setq link (read-string "Link: "
9667 (org-link-unescape
9668 (org-match-string-no-properties 1)))))
9669 ((or (org-in-regexp org-angle-link-re)
9670 (org-in-regexp org-plain-link-re))
9671 ;; Convert to bracket link
9672 (setq remove (list (match-beginning 0) (match-end 0))
9673 link (read-string "Link: "
9674 (org-remove-angle-brackets (match-string 0)))))
9675 ((member complete-file '((4) (16)))
9676 ;; Completing read for file names.
9677 (setq link (org-file-complete-link complete-file)))
9679 ;; Read link, with completion for stored links.
9680 (org-link-fontify-links-to-this-file)
9681 (org-switch-to-buffer-other-window "*Org Links*")
9682 (with-current-buffer "*Org Links*"
9683 (erase-buffer)
9684 (insert "Insert a link.
9685 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9686 (when org-stored-links
9687 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9688 (insert (mapconcat 'org-link-prettify
9689 (reverse org-stored-links) "\n")))
9690 (goto-char (point-min)))
9691 (let ((cw (selected-window)))
9692 (select-window (get-buffer-window "*Org Links*" 'visible))
9693 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9694 (unless (pos-visible-in-window-p (point-max))
9695 (org-fit-window-to-buffer))
9696 (and (window-live-p cw) (select-window cw)))
9697 ;; Fake a link history, containing the stored links.
9698 (setq tmphist (append (mapcar 'car org-stored-links)
9699 org-insert-link-history))
9700 (setq all-prefixes (append (mapcar 'car abbrevs)
9701 (mapcar 'car org-link-abbrev-alist)
9702 org-link-types))
9703 (unwind-protect
9704 (progn
9705 (setq link
9706 (org-completing-read
9707 "Link: "
9708 (append
9709 (mapcar (lambda (x) (concat x ":"))
9710 all-prefixes)
9711 (mapcar 'car org-stored-links))
9712 nil nil nil
9713 'tmphist
9714 (caar org-stored-links)))
9715 (if (not (string-match "\\S-" link))
9716 (error "No link selected"))
9717 (mapc (lambda(l)
9718 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9719 org-stored-links)
9720 (if (or (member link all-prefixes)
9721 (and (equal ":" (substring link -1))
9722 (member (substring link 0 -1) all-prefixes)
9723 (setq link (substring link 0 -1))))
9724 (setq link (with-current-buffer origbuf
9725 (org-link-try-special-completion link)))))
9726 (set-window-configuration wcf)
9727 (kill-buffer "*Org Links*"))
9728 (setq entry (assoc link org-stored-links))
9729 (or entry (push link org-insert-link-history))
9730 (setq desc (or desc (nth 1 entry)))))
9732 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9733 (not org-keep-stored-link-after-insertion))
9734 (setq org-stored-links (delq (assoc link org-stored-links)
9735 org-stored-links)))
9737 (if (string-match org-plain-link-re link)
9738 ;; URL-like link, normalize the use of angular brackets.
9739 (setq link (org-remove-angle-brackets link)))
9741 ;; Check if we are linking to the current file with a search
9742 ;; option If yes, simplify the link by using only the search
9743 ;; option.
9744 (when (and buffer-file-name
9745 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9746 (let* ((path (match-string 1 link))
9747 (case-fold-search nil)
9748 (search (match-string 2 link)))
9749 (save-match-data
9750 (if (equal (file-truename buffer-file-name) (file-truename path))
9751 ;; We are linking to this same file, with a search option
9752 (setq link search)))))
9754 ;; Check if we can/should use a relative path. If yes, simplify the link
9755 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9756 (let* ((type (match-string 1 link))
9757 (path (match-string 2 link))
9758 (origpath path)
9759 (case-fold-search nil))
9760 (cond
9761 ((or (eq org-link-file-path-type 'absolute)
9762 (equal complete-file '(16)))
9763 (setq path (abbreviate-file-name (expand-file-name path))))
9764 ((eq org-link-file-path-type 'noabbrev)
9765 (setq path (expand-file-name path)))
9766 ((eq org-link-file-path-type 'relative)
9767 (setq path (file-relative-name path)))
9769 (save-match-data
9770 (if (string-match (concat "^" (regexp-quote
9771 (expand-file-name
9772 (file-name-as-directory
9773 default-directory))))
9774 (expand-file-name path))
9775 ;; We are linking a file with relative path name.
9776 (setq path (substring (expand-file-name path)
9777 (match-end 0)))
9778 (setq path (abbreviate-file-name (expand-file-name path)))))))
9779 (setq link (concat type path))
9780 (if (equal desc origpath)
9781 (setq desc path))))
9783 (if org-make-link-description-function
9784 (setq desc
9785 (or (condition-case nil
9786 (funcall org-make-link-description-function link desc)
9787 (error (progn (message "Can't get link description from `%s'"
9788 (symbol-name org-make-link-description-function))
9789 (sit-for 2) nil)))
9790 (read-string "Description: " default-description)))
9791 (if default-description (setq desc default-description)
9792 (setq desc (or (and auto-desc desc)
9793 (read-string "Description: " desc)))))
9795 (unless (string-match "\\S-" desc) (setq desc nil))
9796 (if remove (apply 'delete-region remove))
9797 (insert (org-make-link-string link desc))))
9799 (defun org-link-try-special-completion (type)
9800 "If there is completion support for link type TYPE, offer it."
9801 (let ((fun (intern (concat "org-" type "-complete-link"))))
9802 (if (functionp fun)
9803 (funcall fun)
9804 (read-string "Link (no completion support): " (concat type ":")))))
9806 (defun org-file-complete-link (&optional arg)
9807 "Create a file link using completion."
9808 (let (file link)
9809 (setq file (org-iread-file-name "File: "))
9810 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9811 (pwd1 (file-name-as-directory (abbreviate-file-name
9812 (expand-file-name ".")))))
9813 (cond
9814 ((equal arg '(16))
9815 (setq link (concat
9816 "file:"
9817 (abbreviate-file-name (expand-file-name file)))))
9818 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9819 (setq link (concat "file:" (match-string 1 file))))
9820 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9821 (expand-file-name file))
9822 (setq link (concat
9823 "file:" (match-string 1 (expand-file-name file)))))
9824 (t (setq link (concat "file:" file)))))
9825 link))
9827 (defun org-iread-file-name (&rest args)
9828 "Read-file-name using `ido-mode' speedup if available.
9829 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9830 See `read-file-name' for a description of parameters."
9831 (org-without-partial-completion
9832 (if (and org-completion-use-ido
9833 (fboundp 'ido-read-file-name)
9834 (boundp 'ido-mode) ido-mode
9835 (listp (second args)))
9836 (let ((ido-enter-matching-directory nil))
9837 (apply 'ido-read-file-name args))
9838 (apply 'read-file-name args))))
9840 (defun org-completing-read (&rest args)
9841 "Completing-read with SPACE being a normal character."
9842 (let ((enable-recursive-minibuffers t)
9843 (minibuffer-local-completion-map
9844 (copy-keymap minibuffer-local-completion-map)))
9845 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9846 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9847 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9848 (apply 'org-icompleting-read args)))
9850 (defun org-completing-read-no-i (&rest args)
9851 (let (org-completion-use-ido org-completion-use-iswitchb)
9852 (apply 'org-completing-read args)))
9854 (defun org-iswitchb-completing-read (prompt choices &rest args)
9855 "Use iswitch as a completing-read replacement to choose from choices.
9856 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9857 from."
9858 (let* ((iswitchb-use-virtual-buffers nil)
9859 (iswitchb-make-buflist-hook
9860 (lambda ()
9861 (setq iswitchb-temp-buflist choices))))
9862 (iswitchb-read-buffer prompt)))
9864 (defun org-icompleting-read (&rest args)
9865 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9866 (org-without-partial-completion
9867 (if (and org-completion-use-ido
9868 (fboundp 'ido-completing-read)
9869 (boundp 'ido-mode) ido-mode
9870 (listp (second args)))
9871 (let ((ido-enter-matching-directory nil))
9872 (apply 'ido-completing-read (concat (car args))
9873 (if (consp (car (nth 1 args)))
9874 (mapcar 'car (nth 1 args))
9875 (nth 1 args))
9876 (cddr args)))
9877 (if (and org-completion-use-iswitchb
9878 (boundp 'iswitchb-mode) iswitchb-mode
9879 (listp (second args)))
9880 (apply 'org-iswitchb-completing-read (concat (car args))
9881 (if (consp (car (nth 1 args)))
9882 (mapcar 'car (nth 1 args))
9883 (nth 1 args))
9884 (cddr args))
9885 (apply 'completing-read args)))))
9887 (defun org-extract-attributes (s)
9888 "Extract the attributes cookie from a string and set as text property."
9889 (let (a attr (start 0) key value)
9890 (save-match-data
9891 (when (string-match "{{\\([^}]+\\)}}$" s)
9892 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9893 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9894 (setq key (match-string 1 a) value (match-string 2 a)
9895 start (match-end 0)
9896 attr (plist-put attr (intern key) value))))
9897 (org-add-props s nil 'org-attr attr))
9900 (defun org-extract-attributes-from-string (tag)
9901 (let (key value attr)
9902 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9903 (setq key (match-string 1 tag) value (match-string 2 tag)
9904 tag (replace-match "" t t tag)
9905 attr (plist-put attr (intern key) value)))
9906 (cons tag attr)))
9908 (defun org-attributes-to-string (plist)
9909 "Format a property list into an HTML attribute list."
9910 (let ((s "") key value)
9911 (while plist
9912 (setq key (pop plist) value (pop plist))
9913 (and value
9914 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9917 ;;; Opening/following a link
9919 (defvar org-link-search-failed nil)
9921 (defvar org-open-link-functions nil
9922 "Hook for functions finding a plain text link.
9923 These functions must take a single argument, the link content.
9924 They will be called for links that look like [[link text][description]]
9925 when LINK TEXT does not have a protocol like \"http:\" and does not look
9926 like a filename (e.g. \"./blue.png\").
9928 These functions will be called *before* Org attempts to resolve the
9929 link by doing text searches in the current buffer - so if you want a
9930 link \"[[target]]\" to still find \"<<target>>\", your function should
9931 handle this as a special case.
9933 When the function does handle the link, it must return a non-nil value.
9934 If it decides that it is not responsible for this link, it must return
9935 nil to indicate that that Org-mode can continue with other options
9936 like exact and fuzzy text search.")
9938 (defun org-next-link (&optional search-backward)
9939 "Move forward to the next link.
9940 If the link is in hidden text, expose it."
9941 (interactive "P")
9942 (when (and org-link-search-failed (eq this-command last-command))
9943 (goto-char (point-min))
9944 (message "Link search wrapped back to beginning of buffer"))
9945 (setq org-link-search-failed nil)
9946 (let* ((pos (point))
9947 (ct (org-context))
9948 (a (assoc :link ct))
9949 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9950 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9951 ((looking-at org-any-link-re)
9952 ;; Don't stay stuck at link without an org-link face
9953 (forward-char (if search-backward -1 1))))
9954 (if (funcall srch-fun org-any-link-re nil t)
9955 (progn
9956 (goto-char (match-beginning 0))
9957 (if (outline-invisible-p) (org-show-context)))
9958 (goto-char pos)
9959 (setq org-link-search-failed t)
9960 (message "No further link found"))))
9962 (defun org-previous-link ()
9963 "Move backward to the previous link.
9964 If the link is in hidden text, expose it."
9965 (interactive)
9966 (funcall 'org-next-link t))
9968 (defun org-translate-link (s)
9969 "Translate a link string if a translation function has been defined."
9970 (if (and org-link-translation-function
9971 (fboundp org-link-translation-function)
9972 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9973 (progn
9974 (setq s (funcall org-link-translation-function
9975 (match-string 1 s) (match-string 2 s)))
9976 (concat (car s) ":" (cdr s)))
9979 (defun org-translate-link-from-planner (type path)
9980 "Translate a link from Emacs Planner syntax so that Org can follow it.
9981 This is still an experimental function, your mileage may vary."
9982 (cond
9983 ((member type '("http" "https" "news" "ftp"))
9984 ;; standard Internet links are the same.
9985 nil)
9986 ((and (equal type "irc") (string-match "^//" path))
9987 ;; Planner has two / at the beginning of an irc link, we have 1.
9988 ;; We should have zero, actually....
9989 (setq path (substring path 1)))
9990 ((and (equal type "lisp") (string-match "^/" path))
9991 ;; Planner has a slash, we do not.
9992 (setq type "elisp" path (substring path 1)))
9993 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9994 ;; A typical message link. Planner has the id after the final slash,
9995 ;; we separate it with a hash mark
9996 (setq path (concat (match-string 1 path) "#"
9997 (org-remove-angle-brackets (match-string 2 path)))))
9999 (cons type path))
10001 (defun org-find-file-at-mouse (ev)
10002 "Open file link or URL at mouse."
10003 (interactive "e")
10004 (mouse-set-point ev)
10005 (org-open-at-point 'in-emacs))
10007 (defun org-open-at-mouse (ev)
10008 "Open file link or URL at mouse.
10009 See the docstring of `org-open-file' for details."
10010 (interactive "e")
10011 (mouse-set-point ev)
10012 (if (eq major-mode 'org-agenda-mode)
10013 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10014 (org-open-at-point))
10016 (defvar org-window-config-before-follow-link nil
10017 "The window configuration before following a link.
10018 This is saved in case the need arises to restore it.")
10020 (defvar org-open-link-marker (make-marker)
10021 "Marker pointing to the location where `org-open-at-point; was called.")
10023 ;;;###autoload
10024 (defun org-open-at-point-global ()
10025 "Follow a link like Org-mode does.
10026 This command can be called in any mode to follow a link that has
10027 Org-mode syntax."
10028 (interactive)
10029 (org-run-like-in-org-mode 'org-open-at-point))
10031 ;;;###autoload
10032 (defun org-open-link-from-string (s &optional arg reference-buffer)
10033 "Open a link in the string S, as if it was in Org-mode."
10034 (interactive "sLink: \nP")
10035 (let ((reference-buffer (or reference-buffer (current-buffer))))
10036 (with-temp-buffer
10037 (let ((org-inhibit-startup (not reference-buffer)))
10038 (org-mode)
10039 (insert s)
10040 (goto-char (point-min))
10041 (when reference-buffer
10042 (setq org-link-abbrev-alist-local
10043 (with-current-buffer reference-buffer
10044 org-link-abbrev-alist-local)))
10045 (org-open-at-point arg reference-buffer)))))
10047 (defvar org-open-at-point-functions nil
10048 "Hook that is run when following a link at point.
10050 Functions in this hook must return t if they identify and follow
10051 a link at point. If they don't find anything interesting at point,
10052 they must return nil.")
10054 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10055 (defun org-open-at-point (&optional arg reference-buffer)
10056 "Open link at or after point.
10057 If there is no link at point, this function will search forward up to
10058 the end of the current line.
10059 Normally, files will be opened by an appropriate application. If the
10060 optional prefix argument ARG is non-nil, Emacs will visit the file.
10061 With a double prefix argument, try to open outside of Emacs, in the
10062 application the system uses for this file type."
10063 (interactive "P")
10064 ;; if in a code block, then open the block's results
10065 (unless (call-interactively #'org-babel-open-src-block-result)
10066 (org-load-modules-maybe)
10067 (move-marker org-open-link-marker (point))
10068 (setq org-window-config-before-follow-link (current-window-configuration))
10069 (org-remove-occur-highlights nil nil t)
10070 (cond
10071 ((and (org-at-heading-p)
10072 (not (org-at-timestamp-p t))
10073 (not (org-in-regexp
10074 (concat org-plain-link-re "\\|"
10075 org-bracket-link-regexp "\\|"
10076 org-angle-link-re "\\|"
10077 "[ \t]:[^ \t\n]+:[ \t]*$")))
10078 (not (get-text-property (point) 'org-linked-text)))
10079 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10080 (lk0 (car lkall))
10081 (lk (if (stringp lk0) (list lk0) lk0))
10082 (lkend (cdr lkall)))
10083 (mapcar (lambda(l)
10084 (search-forward l nil lkend)
10085 (goto-char (match-beginning 0))
10086 (org-open-at-point))
10087 lk))
10088 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10089 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10090 ((and (org-at-timestamp-p t)
10091 (not (org-in-regexp org-bracket-link-regexp)))
10092 (org-follow-timestamp-link))
10093 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10094 (not (org-in-regexp org-any-link-re)))
10095 (org-footnote-action))
10097 (let (type path link line search (pos (point)))
10098 (catch 'match
10099 (save-excursion
10100 (skip-chars-forward "^]\n\r")
10101 (when (org-in-regexp org-bracket-link-regexp 1)
10102 (setq link (org-extract-attributes
10103 (org-link-unescape (org-match-string-no-properties 1))))
10104 (while (string-match " *\n *" link)
10105 (setq link (replace-match " " t t link)))
10106 (setq link (org-link-expand-abbrev link))
10107 (cond
10108 ((or (file-name-absolute-p link)
10109 (string-match "^\\.\\.?/" link))
10110 (setq type "file" path link))
10111 ((string-match org-link-re-with-space3 link)
10112 (setq type (match-string 1 link) path (match-string 2 link)))
10113 ((string-match "^help:+\\(.+\\)" link)
10114 (setq type "help" path (match-string 1 link)))
10115 (t (setq type "thisfile" path link)))
10116 (throw 'match t)))
10118 (when (get-text-property (point) 'org-linked-text)
10119 (setq type "thisfile"
10120 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10121 (1+ (point)) (point))
10122 path (buffer-substring
10123 (or (previous-single-property-change pos 'org-linked-text)
10124 (point-min))
10125 (or (next-single-property-change pos 'org-linked-text)
10126 (point-max))))
10127 (throw 'match t))
10129 (save-excursion
10130 (when (or (org-in-regexp org-angle-link-re)
10131 (let ((match (org-in-regexp org-plain-link-re)))
10132 ;; Check a plain link is not within a bracket link
10133 (and match
10134 (save-excursion
10135 (progn
10136 (goto-char (car match))
10137 (not (org-in-regexp org-bracket-link-regexp))))))
10138 (let ((line_ending (save-excursion (end-of-line) (point))))
10139 ;; We are in a line before a plain or bracket link
10140 (or (re-search-forward org-plain-link-re line_ending t)
10141 (re-search-forward org-bracket-link-regexp line_ending t))))
10142 (setq type (match-string 1)
10143 path (org-link-unescape (match-string 2)))
10144 (throw 'match t)))
10145 (save-excursion
10146 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10147 (setq type "tags"
10148 path (match-string 1))
10149 (while (string-match ":" path)
10150 (setq path (replace-match "+" t t path)))
10151 (throw 'match t)))
10152 (when (org-in-regexp "<\\([^><\n]+\\)>")
10153 (setq type "tree-match"
10154 path (match-string 1))
10155 (throw 'match t)))
10156 (unless path
10157 (user-error "No link found"))
10159 ;; switch back to reference buffer
10160 ;; needed when if called in a temporary buffer through
10161 ;; org-open-link-from-string
10162 (with-current-buffer (or reference-buffer (current-buffer))
10164 ;; Remove any trailing spaces in path
10165 (if (string-match " +\\'" path)
10166 (setq path (replace-match "" t t path)))
10167 (if (and org-link-translation-function
10168 (fboundp org-link-translation-function))
10169 ;; Check if we need to translate the link
10170 (let ((tmp (funcall org-link-translation-function type path)))
10171 (setq type (car tmp) path (cdr tmp))))
10173 (cond
10175 ((assoc type org-link-protocols)
10176 (funcall (nth 1 (assoc type org-link-protocols)) path))
10178 ((equal type "help")
10179 (let ((f-or-v (intern path)))
10180 (cond ((fboundp f-or-v)
10181 (describe-function f-or-v))
10182 ((boundp f-or-v)
10183 (describe-variable f-or-v))
10184 (t (error "Not a known function or variable")))))
10186 ((equal type "mailto")
10187 (let ((cmd (car org-link-mailto-program))
10188 (args (cdr org-link-mailto-program)) args1
10189 (address path) (subject "") a)
10190 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10191 (setq address (match-string 1 path)
10192 subject (org-link-escape (match-string 2 path))))
10193 (while args
10194 (cond
10195 ((not (stringp (car args))) (push (pop args) args1))
10196 (t (setq a (pop args))
10197 (if (string-match "%a" a)
10198 (setq a (replace-match address t t a)))
10199 (if (string-match "%s" a)
10200 (setq a (replace-match subject t t a)))
10201 (push a args1))))
10202 (apply cmd (nreverse args1))))
10204 ((member type '("http" "https" "ftp" "news"))
10205 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10206 (org-link-escape
10207 path org-link-escape-chars-browser)
10208 path))))
10210 ((string= type "doi")
10211 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10212 (org-link-escape
10213 path org-link-escape-chars-browser)
10214 path))))
10216 ((member type '("message"))
10217 (browse-url (concat type ":" path)))
10219 ((string= type "tags")
10220 (org-tags-view arg path))
10222 ((string= type "tree-match")
10223 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10225 ((string= type "file")
10226 (if (string-match "::\\([0-9]+\\)\\'" path)
10227 (setq line (string-to-number (match-string 1 path))
10228 path (substring path 0 (match-beginning 0)))
10229 (if (string-match "::\\(.+\\)\\'" path)
10230 (setq search (match-string 1 path)
10231 path (substring path 0 (match-beginning 0)))))
10232 (if (string-match "[*?{]" (file-name-nondirectory path))
10233 (dired path)
10234 (org-open-file path arg line search)))
10236 ((string= type "shell")
10237 (let ((buf (generate-new-buffer "*Org Shell Output"))
10238 (cmd path))
10239 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10240 (string-match org-confirm-shell-link-not-regexp cmd))
10241 (not org-confirm-shell-link-function)
10242 (funcall org-confirm-shell-link-function
10243 (format "Execute \"%s\" in shell? "
10244 (org-add-props cmd nil
10245 'face 'org-warning))))
10246 (progn
10247 (message "Executing %s" cmd)
10248 (shell-command cmd buf)
10249 (if (featurep 'midnight)
10250 (setq clean-buffer-list-kill-buffer-names
10251 (cons buf clean-buffer-list-kill-buffer-names))))
10252 (error "Abort"))))
10254 ((string= type "elisp")
10255 (let ((cmd path))
10256 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10257 (string-match org-confirm-elisp-link-not-regexp cmd))
10258 (not org-confirm-elisp-link-function)
10259 (funcall org-confirm-elisp-link-function
10260 (format "Execute \"%s\" as elisp? "
10261 (org-add-props cmd nil
10262 'face 'org-warning))))
10263 (message "%s => %s" cmd
10264 (if (equal (string-to-char cmd) ?\()
10265 (eval (read cmd))
10266 (call-interactively (read cmd))))
10267 (error "Abort"))))
10269 ((and (string= type "thisfile")
10270 (run-hook-with-args-until-success
10271 'org-open-link-functions path)))
10273 ((string= type "thisfile")
10274 (if arg
10275 (switch-to-buffer-other-window
10276 (org-get-buffer-for-internal-link (current-buffer)))
10277 (org-mark-ring-push))
10278 (let ((cmd `(org-link-search
10279 ,path
10280 ,(cond ((equal arg '(4)) ''occur)
10281 ((equal arg '(16)) ''org-occur))
10282 ,pos)))
10283 (condition-case nil (let ((org-link-search-inhibit-query t))
10284 (eval cmd))
10285 (error (progn (widen) (eval cmd))))))
10287 (t (browse-url-at-point)))))))
10288 (move-marker org-open-link-marker nil)
10289 (run-hook-with-args 'org-follow-link-hook)))
10291 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10292 "Offer links in the current entry and return the selected link.
10293 If there is only one link, return it.
10294 If NTH is an integer, return the NTH link found.
10295 If ZERO is a string, check also this string for a link, and if
10296 there is one, return it."
10297 (with-current-buffer buffer
10298 (save-excursion
10299 (save-restriction
10300 (widen)
10301 (goto-char marker)
10302 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10303 "\\(" org-angle-link-re "\\)\\|"
10304 "\\(" org-plain-link-re "\\)"))
10305 (cnt ?0)
10306 (in-emacs (if (integerp nth) nil nth))
10307 have-zero end links link c)
10308 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10309 (push (match-string 0 zero) links)
10310 (setq cnt (1- cnt) have-zero t))
10311 (save-excursion
10312 (org-back-to-heading t)
10313 (setq end (save-excursion (outline-next-heading) (point)))
10314 (while (re-search-forward re end t)
10315 (push (match-string 0) links))
10316 (setq links (org-uniquify (reverse links))))
10317 (cond
10318 ((null links)
10319 (message "No links"))
10320 ((equal (length links) 1)
10321 (setq link (car links)))
10322 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10323 (setq link (nth (if have-zero nth (1- nth)) links)))
10324 (t ; we have to select a link
10325 (save-excursion
10326 (save-window-excursion
10327 (delete-other-windows)
10328 (with-output-to-temp-buffer "*Select Link*"
10329 (mapc (lambda (l)
10330 (if (not (string-match org-bracket-link-regexp l))
10331 (princ (format "[%c] %s\n" (incf cnt)
10332 (org-remove-angle-brackets l)))
10333 (if (match-end 3)
10334 (princ (format "[%c] %s (%s)\n" (incf cnt)
10335 (match-string 3 l) (match-string 1 l)))
10336 (princ (format "[%c] %s\n" (incf cnt)
10337 (match-string 1 l))))))
10338 links))
10339 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10340 (message "Select link to open, RET to open all:")
10341 (setq c (read-char-exclusive))
10342 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10343 (when (equal c ?q) (error "Abort"))
10344 (if (equal c ?\C-m)
10345 (setq link links)
10346 (setq nth (- c ?0))
10347 (if have-zero (setq nth (1+ nth)))
10348 (unless (and (integerp nth) (>= (length links) nth))
10349 (error "Invalid link selection"))
10350 (setq link (nth (1- nth) links)))))
10351 (cons link end))))))
10353 ;; Add special file links that specify the way of opening
10355 (org-add-link-type "file+sys" 'org-open-file-with-system)
10356 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10357 (defun org-open-file-with-system (path)
10358 "Open file at PATH using the system way of opening it."
10359 (org-open-file path 'system))
10360 (defun org-open-file-with-emacs (path)
10361 "Open file at PATH in Emacs."
10362 (org-open-file path 'emacs))
10365 ;;; File search
10367 (defvar org-create-file-search-functions nil
10368 "List of functions to construct the right search string for a file link.
10369 These functions are called in turn with point at the location to
10370 which the link should point.
10372 A function in the hook should first test if it would like to
10373 handle this file type, for example by checking the `major-mode'
10374 or the file extension. If it decides not to handle this file, it
10375 should just return nil to give other functions a chance. If it
10376 does handle the file, it must return the search string to be used
10377 when following the link. The search string will be part of the
10378 file link, given after a double colon, and `org-open-at-point'
10379 will automatically search for it. If special measures must be
10380 taken to make the search successful, another function should be
10381 added to the companion hook `org-execute-file-search-functions',
10382 which see.
10384 A function in this hook may also use `setq' to set the variable
10385 `description' to provide a suggestion for the descriptive text to
10386 be used for this link when it gets inserted into an Org-mode
10387 buffer with \\[org-insert-link].")
10389 (defvar org-execute-file-search-functions nil
10390 "List of functions to execute a file search triggered by a link.
10392 Functions added to this hook must accept a single argument, the
10393 search string that was part of the file link, the part after the
10394 double colon. The function must first check if it would like to
10395 handle this search, for example by checking the `major-mode' or
10396 the file extension. If it decides not to handle this search, it
10397 should just return nil to give other functions a chance. If it
10398 does handle the search, it must return a non-nil value to keep
10399 other functions from trying.
10401 Each function can access the current prefix argument through the
10402 variable `current-prefix-argument'. Note that a single prefix is
10403 used to force opening a link in Emacs, so it may be good to only
10404 use a numeric or double prefix to guide the search function.
10406 In case this is needed, a function in this hook can also restore
10407 the window configuration before `org-open-at-point' was called using:
10409 (set-window-configuration org-window-config-before-follow-link)")
10411 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10412 (defun org-link-search (s &optional type avoid-pos stealth)
10413 "Search for a link search option.
10414 If S is surrounded by forward slashes, it is interpreted as a
10415 regular expression. In org-mode files, this will create an `org-occur'
10416 sparse tree. In ordinary files, `occur' will be used to list matches.
10417 If the current buffer is in `dired-mode', grep will be used to search
10418 in all files. If AVOID-POS is given, ignore matches near that position.
10420 When optional argument STEALTH is non-nil, do not modify
10421 visibility around point, thus ignoring
10422 `org-show-hierarchy-above', `org-show-following-heading' and
10423 `org-show-siblings' variables."
10424 (let ((case-fold-search t)
10425 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10426 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10427 (append '(("") (" ") ("\t") ("\n"))
10428 org-emphasis-alist)
10429 "\\|") "\\)"))
10430 (pos (point))
10431 (pre nil) (post nil)
10432 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10433 (cond
10434 ;; First check if there are any special search functions
10435 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10436 ;; Now try the builtin stuff
10437 ((and (equal (string-to-char s0) ?#)
10438 (> (length s0) 1)
10439 (save-excursion
10440 (goto-char (point-min))
10441 (and
10442 (re-search-forward
10443 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10444 (setq type 'dedicated
10445 pos (match-beginning 0))))
10446 ;; There is an exact target for this
10447 (goto-char pos)
10448 (org-back-to-heading t)))
10449 ((save-excursion
10450 (goto-char (point-min))
10451 (and
10452 (re-search-forward
10453 (concat "<<" (regexp-quote s0) ">>") nil t)
10454 (setq type 'dedicated
10455 pos (match-beginning 0))))
10456 ;; There is an exact target for this
10457 (goto-char pos))
10458 ((save-excursion
10459 (goto-char (point-min))
10460 (and
10461 (re-search-forward
10462 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10463 (setq type 'dedicated pos (match-beginning 0))))
10464 ;; Found an invisible target.
10465 (goto-char pos))
10466 ((save-excursion
10467 (goto-char (point-min))
10468 (and
10469 (re-search-forward
10470 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10471 (setq type 'dedicated pos (match-beginning 0))))
10472 ;; Found an element with a matching #+name affiliated keyword.
10473 (goto-char pos))
10474 ((and (string-match "^(\\(.*\\))$" s0)
10475 (save-excursion
10476 (goto-char (point-min))
10477 (and
10478 (re-search-forward
10479 (concat "[^[]" (regexp-quote
10480 (format org-coderef-label-format
10481 (match-string 1 s0))))
10482 nil t)
10483 (setq type 'dedicated
10484 pos (1+ (match-beginning 0))))))
10485 ;; There is a coderef target for this
10486 (goto-char pos))
10487 ((string-match "^/\\(.*\\)/$" s)
10488 ;; A regular expression
10489 (cond
10490 ((derived-mode-p 'org-mode)
10491 (org-occur (match-string 1 s)))
10492 (t (org-do-occur (match-string 1 s)))))
10493 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10494 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10495 (goto-char (point-min))
10496 (cond
10497 ((let (case-fold-search)
10498 (re-search-forward (format org-complex-heading-regexp-format
10499 (regexp-quote s))
10500 nil t))
10501 ;; OK, found a match
10502 (setq type 'dedicated)
10503 (goto-char (match-beginning 0)))
10504 ((and (not org-link-search-inhibit-query)
10505 (eq org-link-search-must-match-exact-headline 'query-to-create)
10506 (y-or-n-p "No match - create this as a new heading? "))
10507 (goto-char (point-max))
10508 (or (bolp) (newline))
10509 (insert "* " s "\n")
10510 (beginning-of-line 0))
10512 (goto-char pos)
10513 (error "No match"))))
10515 ;; A normal search string
10516 (when (equal (string-to-char s) ?*)
10517 ;; Anchor on headlines, post may include tags.
10518 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10519 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10520 s (substring s 1)))
10521 (remove-text-properties
10522 0 (length s)
10523 '(face nil mouse-face nil keymap nil fontified nil) s)
10524 ;; Make a series of regular expressions to find a match
10525 (setq words (org-split-string s "[ \n\r\t]+")
10527 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10528 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10529 "\\)" markers)
10530 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10531 re2a (concat "[ \t\r\n]" re2a_)
10532 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10533 re4 (concat "[^a-zA-Z_]" re4_)
10535 re1 (concat pre re2 post)
10536 re3 (concat pre (if pre re4_ re4) post)
10537 re5 (concat pre ".*" re4)
10538 re2 (concat pre re2)
10539 re2a (concat pre (if pre re2a_ re2a))
10540 re4 (concat pre (if pre re4_ re4))
10541 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10542 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10543 re5 "\\)"
10545 (cond
10546 ((eq type 'org-occur) (org-occur reall))
10547 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10548 (t (goto-char (point-min))
10549 (setq type 'fuzzy)
10550 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10551 (org-search-not-self 1 re1 nil t)
10552 (org-search-not-self 1 re2 nil t)
10553 (org-search-not-self 1 re2a nil t)
10554 (org-search-not-self 1 re3 nil t)
10555 (org-search-not-self 1 re4 nil t)
10556 (org-search-not-self 1 re5 nil t)
10558 (goto-char (match-beginning 1))
10559 (goto-char pos)
10560 (error "No match"))))))
10561 (and (derived-mode-p 'org-mode)
10562 (not stealth)
10563 (org-show-context 'link-search))
10564 type))
10566 (defun org-search-not-self (group &rest args)
10567 "Execute `re-search-forward', but only accept matches that do not
10568 enclose the position of `org-open-link-marker'."
10569 (let ((m org-open-link-marker))
10570 (catch 'exit
10571 (while (apply 're-search-forward args)
10572 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10573 (goto-char (match-end group))
10574 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10575 (> (match-beginning 0) (marker-position m))
10576 (< (match-end 0) (marker-position m)))
10577 (save-match-data
10578 (or (not (org-in-regexp
10579 org-bracket-link-analytic-regexp 1))
10580 (not (match-end 4)) ; no description
10581 (and (<= (match-beginning 4) (point))
10582 (>= (match-end 4) (point))))))
10583 (throw 'exit (point))))))))
10585 (defun org-get-buffer-for-internal-link (buffer)
10586 "Return a buffer to be used for displaying the link target of internal links."
10587 (cond
10588 ((not org-display-internal-link-with-indirect-buffer)
10589 buffer)
10590 ((string-match "(Clone)$" (buffer-name buffer))
10591 (message "Buffer is already a clone, not making another one")
10592 ;; we also do not modify visibility in this case
10593 buffer)
10594 (t ; make a new indirect buffer for displaying the link
10595 (let* ((bn (buffer-name buffer))
10596 (ibn (concat bn "(Clone)"))
10597 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10598 (with-current-buffer ib (org-overview))
10599 ib))))
10601 (defun org-do-occur (regexp &optional cleanup)
10602 "Call the Emacs command `occur'.
10603 If CLEANUP is non-nil, remove the printout of the regular expression
10604 in the *Occur* buffer. This is useful if the regex is long and not useful
10605 to read."
10606 (occur regexp)
10607 (when cleanup
10608 (let ((cwin (selected-window)) win beg end)
10609 (when (setq win (get-buffer-window "*Occur*"))
10610 (select-window win))
10611 (goto-char (point-min))
10612 (when (re-search-forward "match[a-z]+" nil t)
10613 (setq beg (match-end 0))
10614 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10615 (setq end (1- (match-beginning 0)))))
10616 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10617 (goto-char (point-min))
10618 (select-window cwin))))
10620 ;;; The mark ring for links jumps
10622 (defvar org-mark-ring nil
10623 "Mark ring for positions before jumps in Org-mode.")
10624 (defvar org-mark-ring-last-goto nil
10625 "Last position in the mark ring used to go back.")
10626 ;; Fill and close the ring
10627 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10628 (loop for i from 1 to org-mark-ring-length do
10629 (push (make-marker) org-mark-ring))
10630 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10631 org-mark-ring)
10633 (defun org-mark-ring-push (&optional pos buffer)
10634 "Put the current position or POS into the mark ring and rotate it."
10635 (interactive)
10636 (setq pos (or pos (point)))
10637 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10638 (move-marker (car org-mark-ring)
10639 (or pos (point))
10640 (or buffer (current-buffer)))
10641 (message "%s"
10642 (substitute-command-keys
10643 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10645 (defun org-mark-ring-goto (&optional n)
10646 "Jump to the previous position in the mark ring.
10647 With prefix arg N, jump back that many stored positions. When
10648 called several times in succession, walk through the entire ring.
10649 Org-mode commands jumping to a different position in the current file,
10650 or to another Org-mode file, automatically push the old position
10651 onto the ring."
10652 (interactive "p")
10653 (let (p m)
10654 (if (eq last-command this-command)
10655 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10656 (setq p org-mark-ring))
10657 (setq org-mark-ring-last-goto p)
10658 (setq m (car p))
10659 (org-pop-to-buffer-same-window (marker-buffer m))
10660 (goto-char m)
10661 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10663 (defun org-remove-angle-brackets (s)
10664 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10665 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10667 (defun org-add-angle-brackets (s)
10668 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10669 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10671 (defun org-remove-double-quotes (s)
10672 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10673 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10676 ;;; Following specific links
10678 (defun org-follow-timestamp-link ()
10679 "Open an agenda view for the time-stamp date/range at point."
10680 (cond
10681 ((org-at-date-range-p t)
10682 (let ((org-agenda-start-on-weekday)
10683 (t1 (match-string 1))
10684 (t2 (match-string 2)) tt1 tt2)
10685 (setq tt1 (time-to-days (org-time-string-to-time t1))
10686 tt2 (time-to-days (org-time-string-to-time t2)))
10687 (let ((org-agenda-buffer-tmp-name
10688 (format "*Org Agenda(a:%s)"
10689 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10690 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10691 ((org-at-timestamp-p t)
10692 (let ((org-agenda-buffer-tmp-name
10693 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10694 (org-agenda-list nil (time-to-days (org-time-string-to-time
10695 (substring (match-string 1) 0 10)))
10696 1)))
10697 (t (error "This should not happen"))))
10700 ;;; Following file links
10701 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10702 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10703 (declare-function mailcap-mime-info
10704 "mailcap" (string &optional request no-decode))
10705 (defvar org-wait nil)
10706 (defun org-open-file (path &optional in-emacs line search)
10707 "Open the file at PATH.
10708 First, this expands any special file name abbreviations. Then the
10709 configuration variable `org-file-apps' is checked if it contains an
10710 entry for this file type, and if yes, the corresponding command is launched.
10712 If no application is found, Emacs simply visits the file.
10714 With optional prefix argument IN-EMACS, Emacs will visit the file.
10715 With a double \\[universal-argument] \\[universal-argument] \
10716 prefix arg, Org tries to avoid opening in Emacs
10717 and to use an external application to visit the file.
10719 Optional LINE specifies a line to go to, optional SEARCH a string
10720 to search for. If LINE or SEARCH is given, the file will be
10721 opened in Emacs, unless an entry from org-file-apps that makes
10722 use of groups in a regexp matches.
10724 If you want to change the way frames are used when following a
10725 link, please customize `org-link-frame-setup'.
10727 If the file does not exist, an error is thrown."
10728 (let* ((file (if (equal path "")
10729 buffer-file-name
10730 (substitute-in-file-name (expand-file-name path))))
10731 (file-apps (append org-file-apps (org-default-apps)))
10732 (apps (org-remove-if
10733 'org-file-apps-entry-match-against-dlink-p file-apps))
10734 (apps-dlink (org-remove-if-not
10735 'org-file-apps-entry-match-against-dlink-p file-apps))
10736 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10737 (dirp (if remp nil (file-directory-p file)))
10738 (file (if (and dirp org-open-directory-means-index-dot-org)
10739 (concat (file-name-as-directory file) "index.org")
10740 file))
10741 (a-m-a-p (assq 'auto-mode apps))
10742 (dfile (downcase file))
10743 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10744 (link (cond ((and (eq line nil)
10745 (eq search nil))
10746 file)
10747 (line
10748 (concat file "::" (number-to-string line)))
10749 (search
10750 (concat file "::" search))))
10751 (dlink (downcase link))
10752 (old-buffer (current-buffer))
10753 (old-pos (point))
10754 (old-mode major-mode)
10755 ext cmd link-match-data)
10756 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10757 (setq ext (match-string 1 dfile))
10758 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10759 (setq ext (match-string 1 dfile))))
10760 (cond
10761 ((member in-emacs '((16) system))
10762 (setq cmd (cdr (assoc 'system apps))))
10763 (in-emacs (setq cmd 'emacs))
10765 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10766 (and dirp (cdr (assoc 'directory apps)))
10767 ; first, try matching against apps-dlink
10768 ; if we get a match here, store the match data for later
10769 (let ((match (assoc-default dlink apps-dlink
10770 'string-match)))
10771 (if match
10772 (progn (setq link-match-data (match-data))
10773 match)
10774 (progn (setq in-emacs (or in-emacs line search))
10775 nil))) ; if we have no match in apps-dlink,
10776 ; always open the file in emacs if line or search
10777 ; is given (for backwards compatibility)
10778 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10779 'string-match)
10780 (cdr (assoc ext apps))
10781 (cdr (assoc t apps))))))
10782 (when (eq cmd 'system)
10783 (setq cmd (cdr (assoc 'system apps))))
10784 (when (eq cmd 'default)
10785 (setq cmd (cdr (assoc t apps))))
10786 (when (eq cmd 'mailcap)
10787 (require 'mailcap)
10788 (mailcap-parse-mailcaps)
10789 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10790 (command (mailcap-mime-info mime-type)))
10791 (if (stringp command)
10792 (setq cmd command)
10793 (setq cmd 'emacs))))
10794 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10795 (not (file-exists-p file))
10796 (not org-open-non-existing-files))
10797 (error "No such file: %s" file))
10798 (cond
10799 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10800 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10801 (while (string-match "['\"]%s['\"]" cmd)
10802 (setq cmd (replace-match "%s" t t cmd)))
10803 (while (string-match "%s" cmd)
10804 (setq cmd (replace-match
10805 (save-match-data
10806 (shell-quote-argument
10807 (convert-standard-filename file)))
10808 t t cmd)))
10810 ;; Replace "%1", "%2" etc. in command with group matches from regex
10811 (save-match-data
10812 (let ((match-index 1)
10813 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10814 (set-match-data link-match-data)
10815 (while (<= match-index number-of-groups)
10816 (let ((regex (concat "%" (number-to-string match-index)))
10817 (replace-with (match-string match-index dlink)))
10818 (while (string-match regex cmd)
10819 (setq cmd (replace-match replace-with t t cmd))))
10820 (setq match-index (+ match-index 1)))))
10822 (save-window-excursion
10823 (message "Running %s...done" cmd)
10824 (start-process-shell-command cmd nil cmd)
10825 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10826 ((or (stringp cmd)
10827 (eq cmd 'emacs))
10828 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10829 (widen)
10830 (if line (org-goto-line line)
10831 (if search (org-link-search search))))
10832 ((consp cmd)
10833 (let ((file (convert-standard-filename file)))
10834 (save-match-data
10835 (set-match-data link-match-data)
10836 (eval cmd))))
10837 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10838 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10839 (or (not (equal old-buffer (current-buffer)))
10840 (not (equal old-pos (point))))
10841 (org-mark-ring-push old-pos old-buffer))))
10843 (defun org-file-apps-entry-match-against-dlink-p (entry)
10844 "This function returns non-nil if `entry' uses a regular
10845 expression which should be matched against the whole link by
10846 org-open-file.
10848 It assumes that is the case when the entry uses a regular
10849 expression which has at least one grouping construct and the
10850 action is either a lisp form or a command string containing
10851 '%1', i.e. using at least one subexpression match as a
10852 parameter."
10853 (let ((selector (car entry))
10854 (action (cdr entry)))
10855 (if (stringp selector)
10856 (and (> (regexp-opt-depth selector) 0)
10857 (or (and (stringp action)
10858 (string-match "%[0-9]" action))
10859 (consp action)))
10860 nil)))
10862 (defun org-default-apps ()
10863 "Return the default applications for this operating system."
10864 (cond
10865 ((eq system-type 'darwin)
10866 org-file-apps-defaults-macosx)
10867 ((eq system-type 'windows-nt)
10868 org-file-apps-defaults-windowsnt)
10869 (t org-file-apps-defaults-gnu)))
10871 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10872 "Convert extensions to regular expressions in the cars of LIST.
10873 Also, weed out any non-string entries, because the return value is used
10874 only for regexp matching.
10875 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10876 point to the symbol `emacs', indicating that the file should
10877 be opened in Emacs."
10878 (append
10879 (delq nil
10880 (mapcar (lambda (x)
10881 (if (not (stringp (car x)))
10883 (if (string-match "\\W" (car x))
10885 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10886 list))
10887 (if add-auto-mode
10888 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10890 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10891 (defun org-file-remote-p (file)
10892 "Test whether FILE specifies a location on a remote system.
10893 Return non-nil if the location is indeed remote.
10895 For example, the filename \"/user@host:/foo\" specifies a location
10896 on the system \"/user@host:\"."
10897 (cond ((fboundp 'file-remote-p)
10898 (file-remote-p file))
10899 ((fboundp 'tramp-handle-file-remote-p)
10900 (tramp-handle-file-remote-p file))
10901 ((and (boundp 'ange-ftp-name-format)
10902 (string-match (car ange-ftp-name-format) file))
10903 t)))
10906 ;;;; Refiling
10908 (defun org-get-org-file ()
10909 "Read a filename, with default directory `org-directory'."
10910 (let ((default (or org-default-notes-file remember-data-file)))
10911 (read-file-name (format "File name [%s]: " default)
10912 (file-name-as-directory org-directory)
10913 default)))
10915 (defun org-notes-order-reversed-p ()
10916 "Check if the current file should receive notes in reversed order."
10917 (cond
10918 ((not org-reverse-note-order) nil)
10919 ((eq t org-reverse-note-order) t)
10920 ((not (listp org-reverse-note-order)) nil)
10921 (t (catch 'exit
10922 (let ((all org-reverse-note-order)
10923 entry)
10924 (while (setq entry (pop all))
10925 (if (string-match (car entry) buffer-file-name)
10926 (throw 'exit (cdr entry))))
10927 nil)))))
10929 (defvar org-refile-target-table nil
10930 "The list of refile targets, created by `org-refile'.")
10932 (defvar org-agenda-new-buffers nil
10933 "Buffers created to visit agenda files.")
10935 (defvar org-refile-cache nil
10936 "Cache for refile targets.")
10938 (defvar org-refile-markers nil
10939 "All the markers used for caching refile locations.")
10941 (defun org-refile-marker (pos)
10942 "Get a new refile marker, but only if caching is in use."
10943 (if (not org-refile-use-cache)
10945 (let ((m (make-marker)))
10946 (move-marker m pos)
10947 (push m org-refile-markers)
10948 m)))
10950 (defun org-refile-cache-clear ()
10951 "Clear the refile cache and disable all the markers."
10952 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10953 (setq org-refile-markers nil)
10954 (setq org-refile-cache nil)
10955 (message "Refile cache has been cleared"))
10957 (defun org-refile-cache-check-set (set)
10958 "Check if all the markers in the cache still have live buffers."
10959 (let (marker)
10960 (catch 'exit
10961 (while (and set (setq marker (nth 3 (pop set))))
10962 ;; if org-refile-use-outline-path is 'file, marker may be nil
10963 (when (and marker (null (marker-buffer marker)))
10964 (message "not found") (sit-for 3)
10965 (throw 'exit nil)))
10966 t)))
10968 (defun org-refile-cache-put (set &rest identifiers)
10969 "Push the refile targets SET into the cache, under IDENTIFIERS."
10970 (let* ((key (sha1 (prin1-to-string identifiers)))
10971 (entry (assoc key org-refile-cache)))
10972 (if entry
10973 (setcdr entry set)
10974 (push (cons key set) org-refile-cache))))
10976 (defun org-refile-cache-get (&rest identifiers)
10977 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10978 (cond
10979 ((not org-refile-cache) nil)
10980 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10982 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10983 org-refile-cache))))
10984 (and set (org-refile-cache-check-set set) set)))))
10986 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10987 "Produce a table with refile targets."
10988 (let ((case-fold-search nil)
10989 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10990 (entries (or org-refile-targets '((nil . (:level . 1)))))
10991 targets tgs txt re files f desc descre fast-path-p level pos0)
10992 (message "Getting targets...")
10993 (with-current-buffer (or default-buffer (current-buffer))
10994 (while (setq entry (pop entries))
10995 (setq files (car entry) desc (cdr entry))
10996 (setq fast-path-p nil)
10997 (cond
10998 ((null files) (setq files (list (current-buffer))))
10999 ((eq files 'org-agenda-files)
11000 (setq files (org-agenda-files 'unrestricted)))
11001 ((and (symbolp files) (fboundp files))
11002 (setq files (funcall files)))
11003 ((and (symbolp files) (boundp files))
11004 (setq files (symbol-value files))))
11005 (if (stringp files) (setq files (list files)))
11006 (cond
11007 ((eq (car desc) :tag)
11008 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11009 ((eq (car desc) :todo)
11010 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11011 ((eq (car desc) :regexp)
11012 (setq descre (cdr desc)))
11013 ((eq (car desc) :level)
11014 (setq descre (concat "^\\*\\{" (number-to-string
11015 (if org-odd-levels-only
11016 (1- (* 2 (cdr desc)))
11017 (cdr desc)))
11018 "\\}[ \t]")))
11019 ((eq (car desc) :maxlevel)
11020 (setq fast-path-p t)
11021 (setq descre (concat "^\\*\\{1," (number-to-string
11022 (if org-odd-levels-only
11023 (1- (* 2 (cdr desc)))
11024 (cdr desc)))
11025 "\\}[ \t]")))
11026 (t (error "Bad refiling target description %s" desc)))
11027 (while (setq f (pop files))
11028 (with-current-buffer
11029 (if (bufferp f) f (org-get-agenda-file-buffer f))
11031 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11032 (progn
11033 (if (bufferp f) (setq f (buffer-file-name
11034 (buffer-base-buffer f))))
11035 (setq f (and f (expand-file-name f)))
11036 (if (eq org-refile-use-outline-path 'file)
11037 (push (list (file-name-nondirectory f) f nil nil) tgs))
11038 (save-excursion
11039 (save-restriction
11040 (widen)
11041 (goto-char (point-min))
11042 (while (re-search-forward descre nil t)
11043 (goto-char (setq pos0 (point-at-bol)))
11044 (catch 'next
11045 (when org-refile-target-verify-function
11046 (save-match-data
11047 (or (funcall org-refile-target-verify-function)
11048 (throw 'next t))))
11049 (when (and (looking-at org-complex-heading-regexp)
11050 (not (member (match-string 4) excluded-entries))
11051 (match-string 4))
11052 (setq level (org-reduced-level
11053 (- (match-end 1) (match-beginning 1)))
11054 txt (org-link-display-format (match-string 4))
11055 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11056 re (format org-complex-heading-regexp-format
11057 (regexp-quote (match-string 4))))
11058 (when org-refile-use-outline-path
11059 (setq txt (mapconcat
11060 'org-protect-slash
11061 (append
11062 (if (eq org-refile-use-outline-path
11063 'file)
11064 (list (file-name-nondirectory
11065 (buffer-file-name
11066 (buffer-base-buffer))))
11067 (if (eq org-refile-use-outline-path
11068 'full-file-path)
11069 (list (buffer-file-name
11070 (buffer-base-buffer)))))
11071 (org-get-outline-path fast-path-p
11072 level txt)
11073 (list txt))
11074 "/")))
11075 (push (list txt f re (org-refile-marker (point)))
11076 tgs)))
11077 (when (= (point) pos0)
11078 ;; verification function has not moved point
11079 (goto-char (point-at-eol))))))))
11080 (when org-refile-use-cache
11081 (org-refile-cache-put tgs (buffer-file-name) descre))
11082 (setq targets (append tgs targets))
11083 ))))
11084 (message "Getting targets...done")
11085 (nreverse targets)))
11087 (defun org-protect-slash (s)
11088 (while (string-match "/" s)
11089 (setq s (replace-match "\\" t t s)))
11092 (defvar org-olpa (make-vector 20 nil))
11094 (defun org-get-outline-path (&optional fastp level heading)
11095 "Return the outline path to the current entry, as a list.
11097 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11098 routine which makes outline path derivations for an entire file,
11099 avoiding backtracing. Refile target collection makes use of that."
11100 (if fastp
11101 (progn
11102 (if (> level 19)
11103 (error "Outline path failure, more than 19 levels"))
11104 (loop for i from level upto 19 do
11105 (aset org-olpa i nil))
11106 (prog1
11107 (delq nil (append org-olpa nil))
11108 (aset org-olpa level heading)))
11109 (let (rtn case-fold-search)
11110 (save-excursion
11111 (save-restriction
11112 (widen)
11113 (while (org-up-heading-safe)
11114 (when (looking-at org-complex-heading-regexp)
11115 (push (org-match-string-no-properties 4) rtn)))
11116 rtn)))))
11118 (defun org-format-outline-path (path &optional width prefix separator)
11119 "Format the outline path PATH for display.
11120 WIDTH is the maximum number of characters that is available.
11121 PREFIX is a prefix to be included in the returned string,
11122 such as the file name.
11123 SEPARATOR is inserted between the different parts of the path,
11124 the default is \"/\"."
11125 (setq width (or width 79))
11126 (if prefix (setq width (- width (length prefix))))
11127 (if (not path)
11128 (or prefix "")
11129 (let* ((nsteps (length path))
11130 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11131 (maxwidth (if (<= total-width width)
11132 10000 ;; everything fits
11133 ;; we need to shorten the level headings
11134 (/ (- width nsteps) nsteps)))
11135 (org-odd-levels-only nil)
11136 (n 0)
11137 (total (1+ (length prefix))))
11138 (setq maxwidth (max maxwidth 10))
11139 (concat prefix
11140 (if prefix (or separator "/"))
11141 (mapconcat
11142 (lambda (h)
11143 (setq n (1+ n))
11144 (if (and (= n nsteps) (< maxwidth 10000))
11145 (setq maxwidth (- total-width total)))
11146 (if (< (length h) maxwidth)
11147 (progn (setq total (+ total (length h) 1)) h)
11148 (setq h (substring h 0 (- maxwidth 2))
11149 total (+ total maxwidth 1))
11150 (if (string-match "[ \t]+\\'" h)
11151 (setq h (substring h 0 (match-beginning 0))))
11152 (setq h (concat h "..")))
11153 (org-add-props h nil 'face
11154 (nth (% (1- n) org-n-level-faces)
11155 org-level-faces))
11157 path (or separator "/"))))))
11159 (defun org-display-outline-path (&optional file current separator just-return-string)
11160 "Display the current outline path in the echo area.
11162 If FILE is non-nil, prepend the output with the file name.
11163 If CURRENT is non-nil, append the current heading to the output.
11164 SEPARATOR is passed through to `org-format-outline-path'. It separates
11165 the different parts of the path and defaults to \"/\".
11166 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11167 (interactive "P")
11168 (let* (case-fold-search
11169 message-log-max ; Don't populate the *Messages* buffer
11170 (bfn (buffer-file-name (buffer-base-buffer)))
11171 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11172 res)
11173 (if current (setq path (append path
11174 (save-excursion
11175 (org-back-to-heading t)
11176 (if (looking-at org-complex-heading-regexp)
11177 (list (match-string 4)))))))
11178 (setq res
11179 (org-format-outline-path
11180 path
11181 (1- (frame-width))
11182 (and file bfn (concat (file-name-nondirectory bfn) separator))
11183 separator))
11184 (if just-return-string
11185 (org-no-properties res)
11186 (message "%s" res))))
11188 (defvar org-refile-history nil
11189 "History for refiling operations.")
11191 (defvar org-after-refile-insert-hook nil
11192 "Hook run after `org-refile' has inserted its stuff at the new location.
11193 Note that this is still *before* the stuff will be removed from
11194 the *old* location.")
11196 (defvar org-capture-last-stored-marker)
11197 (defvar org-refile-keep nil
11198 "Non-nil means `org-refile' will copy instead of refile.")
11200 (defun org-copy ()
11201 "Like `org-refile', but copy."
11202 (interactive)
11203 (let ((org-refile-keep t))
11204 (funcall 'org-refile nil nil nil "Copy")))
11206 (defun org-refile (&optional goto default-buffer rfloc msg)
11207 "Move the entry or entries at point to another heading.
11208 The list of target headings is compiled using the information in
11209 `org-refile-targets', which see.
11211 At the target location, the entry is filed as a subitem of the target
11212 heading. Depending on `org-reverse-note-order', the new subitem will
11213 either be the first or the last subitem.
11215 If there is an active region, all entries in that region will be moved.
11216 However, the region must fulfill the requirement that the first heading
11217 is the first one sets the top-level of the moved text - at most siblings
11218 below it are allowed.
11220 With prefix arg GOTO, the command will only visit the target location
11221 and not actually move anything.
11223 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11224 go to the location where the last refiling operation has put the subtree.
11225 With a prefix argument of `2', refile to the running clock.
11227 RFLOC can be a refile location obtained in a different way.
11229 MSG is a string to replace \"Refile\" in the default prompt with
11230 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11232 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11234 If you are using target caching (see `org-refile-use-cache'),
11235 you have to clear the target cache in order to find new targets.
11236 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11237 prefix argument (`C-u C-u C-u C-c C-w')."
11239 (interactive "P")
11240 (if (member goto '(0 (64)))
11241 (org-refile-cache-clear)
11242 (let* ((actionmsg (or msg "Refile"))
11243 (cbuf (current-buffer))
11244 (regionp (org-region-active-p))
11245 (region-start (and regionp (region-beginning)))
11246 (region-end (and regionp (region-end)))
11247 (region-length (and regionp (- region-end region-start)))
11248 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11249 pos it nbuf file re level reversed)
11250 (setq last-command nil)
11251 (when regionp
11252 (goto-char region-start)
11253 (or (bolp) (goto-char (point-at-bol)))
11254 (setq region-start (point))
11255 (unless (or (org-kill-is-subtree-p
11256 (buffer-substring region-start region-end))
11257 (prog1 org-refile-active-region-within-subtree
11258 (org-toggle-heading)))
11259 (error "The region is not a (sequence of) subtree(s)")))
11260 (if (equal goto '(16))
11261 (org-refile-goto-last-stored)
11262 (when (or
11263 (and (equal goto 2)
11264 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11265 (prog1
11266 (setq it (list (or org-clock-heading "running clock")
11267 (buffer-file-name
11268 (marker-buffer org-clock-hd-marker))
11270 (marker-position org-clock-hd-marker)))
11271 (setq goto nil)))
11272 (setq it (or rfloc
11273 (let (heading-text)
11274 (save-excursion
11275 (unless goto
11276 (org-back-to-heading t)
11277 (setq heading-text
11278 (nth 4 (org-heading-components))))
11280 (org-refile-get-location
11281 (cond (goto "Goto")
11282 (regionp (concat actionmsg " region to"))
11283 (t (concat actionmsg " subtree \""
11284 heading-text "\" to")))
11285 default-buffer
11286 (and (not (equal '(4) goto))
11287 org-refile-allow-creating-parent-nodes)
11288 goto))))))
11289 (setq file (nth 1 it)
11290 re (nth 2 it)
11291 pos (nth 3 it))
11292 (if (and (not goto)
11294 (equal (buffer-file-name) file)
11295 (if regionp
11296 (and (>= pos region-start)
11297 (<= pos region-end))
11298 (and (>= pos (point))
11299 (< pos (save-excursion
11300 (org-end-of-subtree t t))))))
11301 (error "Cannot refile to position inside the tree or region"))
11303 (setq nbuf (or (find-buffer-visiting file)
11304 (find-file-noselect file)))
11305 (if goto
11306 (progn
11307 (org-pop-to-buffer-same-window nbuf)
11308 (goto-char pos)
11309 (org-show-context 'org-goto))
11310 (if regionp
11311 (progn
11312 (org-kill-new (buffer-substring region-start region-end))
11313 (org-save-markers-in-region region-start region-end))
11314 (org-copy-subtree 1 nil t))
11315 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11316 (find-file-noselect file)))
11317 (setq reversed (org-notes-order-reversed-p))
11318 (save-excursion
11319 (save-restriction
11320 (widen)
11321 (if pos
11322 (progn
11323 (goto-char pos)
11324 (looking-at org-outline-regexp)
11325 (setq level (org-get-valid-level (funcall outline-level) 1))
11326 (goto-char
11327 (if reversed
11328 (or (outline-next-heading) (point-max))
11329 (or (save-excursion (org-get-next-sibling))
11330 (org-end-of-subtree t t)
11331 (point-max)))))
11332 (setq level 1)
11333 (if (not reversed)
11334 (goto-char (point-max))
11335 (goto-char (point-min))
11336 (or (outline-next-heading) (goto-char (point-max)))))
11337 (if (not (bolp)) (newline))
11338 (org-paste-subtree level)
11339 (when org-log-refile
11340 (org-add-log-setup 'refile nil nil 'findpos
11341 org-log-refile)
11342 (unless (eq org-log-refile 'note)
11343 (save-excursion (org-add-log-note))))
11344 (and org-auto-align-tags
11345 (let ((org-loop-over-headlines-in-active-region nil))
11346 (org-set-tags nil t)))
11347 (with-demoted-errors
11348 (bookmark-set "org-refile-last-stored"))
11349 ;; If we are refiling for capture, make sure that the
11350 ;; last-capture pointers point here
11351 (when (org-bound-and-true-p org-refile-for-capture)
11352 (with-demoted-errors
11353 (bookmark-set "org-capture-last-stored-marker"))
11354 (move-marker org-capture-last-stored-marker (point)))
11355 (if (fboundp 'deactivate-mark) (deactivate-mark))
11356 (run-hooks 'org-after-refile-insert-hook))))
11357 (unless org-refile-keep
11358 (if regionp
11359 (delete-region (point) (+ (point) region-length))
11360 (org-cut-subtree)))
11361 (when (featurep 'org-inlinetask)
11362 (org-inlinetask-remove-END-maybe))
11363 (setq org-markers-to-move nil)
11364 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11366 (defun org-refile-goto-last-stored ()
11367 "Go to the location where the last refile was stored."
11368 (interactive)
11369 (bookmark-jump "org-refile-last-stored")
11370 (message "This is the location of the last refile"))
11372 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11373 no-exclude)
11374 "Prompt the user for a refile location, using PROMPT.
11375 PROMPT should not be suffixed with a colon and a space, because
11376 this function appends the default value from
11377 `org-refile-history' automatically, if that is not empty.
11378 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11379 this is used for the GOTO interface."
11380 (let ((org-refile-targets org-refile-targets)
11381 (org-refile-use-outline-path org-refile-use-outline-path)
11382 excluded-entries)
11383 (when (and (derived-mode-p 'org-mode)
11384 (not org-refile-use-cache)
11385 (not no-exclude))
11386 (org-map-tree
11387 (lambda()
11388 (setq excluded-entries
11389 (append excluded-entries (list (org-get-heading t t)))))))
11390 (setq org-refile-target-table
11391 (org-refile-get-targets default-buffer excluded-entries)))
11392 (unless org-refile-target-table
11393 (error "No refile targets"))
11394 (let* ((cbuf (current-buffer))
11395 (partial-completion-mode nil)
11396 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11397 (cfunc (if (and org-refile-use-outline-path
11398 org-outline-path-complete-in-steps)
11399 'org-olpath-completing-read
11400 'org-icompleting-read))
11401 (extra (if org-refile-use-outline-path "/" ""))
11402 (cbnex (concat (buffer-name) extra))
11403 (filename (and cfn (expand-file-name cfn)))
11404 (tbl (mapcar
11405 (lambda (x)
11406 (if (and (not (member org-refile-use-outline-path
11407 '(file full-file-path)))
11408 (not (equal filename (nth 1 x))))
11409 (cons (concat (car x) extra " ("
11410 (file-name-nondirectory (nth 1 x)) ")")
11411 (cdr x))
11412 (cons (concat (car x) extra) (cdr x))))
11413 org-refile-target-table))
11414 (completion-ignore-case t)
11415 cdef
11416 (prompt (concat prompt
11417 (or (and (car org-refile-history)
11418 (concat " (default " (car org-refile-history) ")"))
11419 (and (assoc cbnex tbl) (setq cdef cbnex)
11420 (concat " (default " cbnex ")"))) ": "))
11421 pa answ parent-target child parent old-hist)
11422 (setq old-hist org-refile-history)
11423 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11424 nil 'org-refile-history (or cdef (car org-refile-history))))
11425 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11426 (org-refile-check-position pa)
11427 (if pa
11428 (progn
11429 (when (or (not org-refile-history)
11430 (not (eq old-hist org-refile-history))
11431 (not (equal (car pa) (car org-refile-history))))
11432 (setq org-refile-history
11433 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11434 org-refile-history
11435 (cdr org-refile-history))))
11436 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11437 (pop org-refile-history)))
11439 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11440 (progn
11441 (setq parent (match-string 1 answ)
11442 child (match-string 2 answ))
11443 (setq parent-target (or (assoc parent tbl)
11444 (assoc (concat parent "/") tbl)))
11445 (when (and parent-target
11446 (or (eq new-nodes t)
11447 (and (eq new-nodes 'confirm)
11448 (y-or-n-p (format "Create new node \"%s\"? "
11449 child)))))
11450 (org-refile-new-child parent-target child)))
11451 (error "Invalid target location")))))
11453 (declare-function org-string-nw-p "org-macs" (s))
11454 (defun org-refile-check-position (refile-pointer)
11455 "Check if the refile pointer matches the headline to which it points."
11456 (let* ((file (nth 1 refile-pointer))
11457 (re (nth 2 refile-pointer))
11458 (pos (nth 3 refile-pointer))
11459 buffer)
11460 (if (and (not (markerp pos)) (not file))
11461 (error "Please save the buffer to a file before refiling")
11462 (when (org-string-nw-p re)
11463 (setq buffer (if (markerp pos)
11464 (marker-buffer pos)
11465 (or (find-buffer-visiting file)
11466 (find-file-noselect file))))
11467 (with-current-buffer buffer
11468 (save-excursion
11469 (save-restriction
11470 (widen)
11471 (goto-char pos)
11472 (beginning-of-line 1)
11473 (unless (org-looking-at-p re)
11474 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11476 (defun org-refile-new-child (parent-target child)
11477 "Use refile target PARENT-TARGET to add new CHILD below it."
11478 (unless parent-target
11479 (error "Cannot find parent for new node"))
11480 (let ((file (nth 1 parent-target))
11481 (pos (nth 3 parent-target))
11482 level)
11483 (with-current-buffer (or (find-buffer-visiting file)
11484 (find-file-noselect file))
11485 (save-excursion
11486 (save-restriction
11487 (widen)
11488 (if pos
11489 (goto-char pos)
11490 (goto-char (point-max))
11491 (if (not (bolp)) (newline)))
11492 (when (looking-at org-outline-regexp)
11493 (setq level (funcall outline-level))
11494 (org-end-of-subtree t t))
11495 (org-back-over-empty-lines)
11496 (insert "\n" (make-string
11497 (if pos (org-get-valid-level level 1) 1) ?*)
11498 " " child "\n")
11499 (beginning-of-line 0)
11500 (list (concat (car parent-target) "/" child) file "" (point)))))))
11502 (defun org-olpath-completing-read (prompt collection &rest args)
11503 "Read an outline path like a file name."
11504 (let ((thetable collection)
11505 (org-completion-use-ido nil) ; does not work with ido.
11506 (org-completion-use-iswitchb nil)) ; or iswitchb
11507 (apply
11508 'org-icompleting-read prompt
11509 (lambda (string predicate &optional flag)
11510 (let (rtn r f (l (length string)))
11511 (cond
11512 ((eq flag nil)
11513 ;; try completion
11514 (try-completion string thetable))
11515 ((eq flag t)
11516 ;; all-completions
11517 (setq rtn (all-completions string thetable predicate))
11518 (mapcar
11519 (lambda (x)
11520 (setq r (substring x l))
11521 (if (string-match " ([^)]*)$" x)
11522 (setq f (match-string 0 x))
11523 (setq f ""))
11524 (if (string-match "/" r)
11525 (concat string (substring r 0 (match-end 0)) f)
11527 rtn))
11528 ((eq flag 'lambda)
11529 ;; exact match?
11530 (assoc string thetable)))))
11531 args)))
11533 ;;;; Dynamic blocks
11535 (defun org-find-dblock (name)
11536 "Find the first dynamic block with name NAME in the buffer.
11537 If not found, stay at current position and return nil."
11538 (let ((case-fold-search t) pos)
11539 (save-excursion
11540 (goto-char (point-min))
11541 (setq pos (and (re-search-forward
11542 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11543 (match-beginning 0))))
11544 (if pos (goto-char pos))
11545 pos))
11547 (defconst org-dblock-start-re
11548 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11549 "Matches the start line of a dynamic block, with parameters.")
11551 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11552 "Matches the end of a dynamic block.")
11554 (defun org-create-dblock (plist)
11555 "Create a dynamic block section, with parameters taken from PLIST.
11556 PLIST must contain a :name entry which is used as name of the block."
11557 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11558 (end-of-line 1)
11559 (newline))
11560 (let ((col (current-column))
11561 (name (plist-get plist :name)))
11562 (insert "#+BEGIN: " name)
11563 (while plist
11564 (if (eq (car plist) :name)
11565 (setq plist (cddr plist))
11566 (insert " " (prin1-to-string (pop plist)))))
11567 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11568 (beginning-of-line -2)))
11570 (defun org-prepare-dblock ()
11571 "Prepare dynamic block for refresh.
11572 This empties the block, puts the cursor at the insert position and returns
11573 the property list including an extra property :name with the block name."
11574 (unless (looking-at org-dblock-start-re)
11575 (error "Not at a dynamic block"))
11576 (let* ((begdel (1+ (match-end 0)))
11577 (name (org-no-properties (match-string 1)))
11578 (params (append (list :name name)
11579 (read (concat "(" (match-string 3) ")")))))
11580 (save-excursion
11581 (beginning-of-line 1)
11582 (skip-chars-forward " \t")
11583 (setq params (plist-put params :indentation-column (current-column))))
11584 (unless (re-search-forward org-dblock-end-re nil t)
11585 (error "Dynamic block not terminated"))
11586 (setq params
11587 (append params
11588 (list :content (buffer-substring
11589 begdel (match-beginning 0)))))
11590 (delete-region begdel (match-beginning 0))
11591 (goto-char begdel)
11592 (open-line 1)
11593 params))
11595 (defun org-map-dblocks (&optional command)
11596 "Apply COMMAND to all dynamic blocks in the current buffer.
11597 If COMMAND is not given, use `org-update-dblock'."
11598 (let ((cmd (or command 'org-update-dblock)))
11599 (save-excursion
11600 (goto-char (point-min))
11601 (while (re-search-forward org-dblock-start-re nil t)
11602 (goto-char (match-beginning 0))
11603 (save-excursion
11604 (condition-case nil
11605 (funcall cmd)
11606 (error (message "Error during update of dynamic block"))))
11607 (unless (re-search-forward org-dblock-end-re nil t)
11608 (error "Dynamic block not terminated"))))))
11610 (defun org-dblock-update (&optional arg)
11611 "User command for updating dynamic blocks.
11612 Update the dynamic block at point. With prefix ARG, update all dynamic
11613 blocks in the buffer."
11614 (interactive "P")
11615 (if arg
11616 (org-update-all-dblocks)
11617 (or (looking-at org-dblock-start-re)
11618 (org-beginning-of-dblock))
11619 (org-update-dblock)))
11621 (defun org-update-dblock ()
11622 "Update the dynamic block at point.
11623 This means to empty the block, parse for parameters and then call
11624 the correct writing function."
11625 (interactive)
11626 (save-window-excursion
11627 (let* ((pos (point))
11628 (line (org-current-line))
11629 (params (org-prepare-dblock))
11630 (name (plist-get params :name))
11631 (indent (plist-get params :indentation-column))
11632 (cmd (intern (concat "org-dblock-write:" name))))
11633 (message "Updating dynamic block `%s' at line %d..." name line)
11634 (funcall cmd params)
11635 (message "Updating dynamic block `%s' at line %d...done" name line)
11636 (goto-char pos)
11637 (when (and indent (> indent 0))
11638 (setq indent (make-string indent ?\ ))
11639 (save-excursion
11640 (org-beginning-of-dblock)
11641 (forward-line 1)
11642 (while (not (looking-at org-dblock-end-re))
11643 (insert indent)
11644 (beginning-of-line 2))
11645 (when (looking-at org-dblock-end-re)
11646 (and (looking-at "[ \t]+")
11647 (replace-match ""))
11648 (insert indent)))))))
11650 (defun org-beginning-of-dblock ()
11651 "Find the beginning of the dynamic block at point.
11652 Error if there is no such block at point."
11653 (let ((pos (point))
11654 beg)
11655 (end-of-line 1)
11656 (if (and (re-search-backward org-dblock-start-re nil t)
11657 (setq beg (match-beginning 0))
11658 (re-search-forward org-dblock-end-re nil t)
11659 (> (match-end 0) pos))
11660 (goto-char beg)
11661 (goto-char pos)
11662 (error "Not in a dynamic block"))))
11664 (defun org-update-all-dblocks ()
11665 "Update all dynamic blocks in the buffer.
11666 This function can be used in a hook."
11667 (interactive)
11668 (when (derived-mode-p 'org-mode)
11669 (org-map-dblocks 'org-update-dblock)))
11672 ;;;; Completion
11674 (defun org-get-export-keywords ()
11675 "Return a list of all currently understood export keywords.
11676 Export keywords include options, block names, attributes and
11677 keywords relative to each registered export back-end."
11678 (delq nil
11679 (let (keywords)
11680 (mapc
11681 (lambda (back-end)
11682 (let ((props (cdr back-end)))
11683 ;; Back-end name (for keywords, like #+LATEX:)
11684 (push (upcase (symbol-name (car back-end))) keywords)
11685 ;; Back-end options.
11686 (mapc (lambda (option) (push (cadr option) keywords))
11687 (plist-get (cdr back-end) :options-alist))))
11688 (org-bound-and-true-p org-export-registered-backends))
11689 keywords)))
11691 (defconst org-options-keywords
11692 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11693 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11694 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11695 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11696 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11698 (defcustom org-structure-template-alist
11699 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11700 "<src lang=\"?\">\n\n</src>")
11701 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11702 "<example>\n?\n</example>")
11703 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11704 "<quote>\n?\n</quote>")
11705 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11706 "<verse>\n?\n</verse>")
11707 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11708 "<verbatim>\n?\n</verbatim>")
11709 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11710 "<center>\n?\n</center>")
11711 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11712 "<literal style=\"latex\">\n?\n</literal>")
11713 ("L" "#+LaTeX: "
11714 "<literal style=\"latex\">?</literal>")
11715 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11716 "<literal style=\"html\">\n?\n</literal>")
11717 ("H" "#+HTML: "
11718 "<literal style=\"html\">?</literal>")
11719 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11720 ("A" "#+ASCII: ")
11721 ("i" "#+INDEX: ?"
11722 "#+INDEX: ?")
11723 ("I" "#+INCLUDE: %file ?"
11724 "<include file=%file markup=\"?\">"))
11725 "Structure completion elements.
11726 This is a list of abbreviation keys and values. The value gets inserted
11727 if you type `<' followed by the key and then press the completion key,
11728 usually `M-TAB'. %file will be replaced by a file name after prompting
11729 for the file using completion. The cursor will be placed at the position
11730 of the `?` in the template.
11731 There are two templates for each key, the first uses the original Org syntax,
11732 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11733 the default when the /org-mtags.el/ module has been loaded. See also the
11734 variable `org-mtags-prefer-muse-templates'."
11735 :group 'org-completion
11736 :type '(repeat
11737 (string :tag "Key")
11738 (string :tag "Template")
11739 (string :tag "Muse Template")))
11741 (defun org-try-structure-completion ()
11742 "Try to complete a structure template before point.
11743 This looks for strings like \"<e\" on an otherwise empty line and
11744 expands them."
11745 (let ((l (buffer-substring (point-at-bol) (point)))
11747 (when (and (looking-at "[ \t]*$")
11748 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11749 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11750 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11751 (match-beginning 1)) a)
11752 t)))
11754 (defun org-complete-expand-structure-template (start cell)
11755 "Expand a structure template."
11756 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11757 (rpl (nth (if musep 2 1) cell))
11758 (ind ""))
11759 (delete-region start (point))
11760 (when (string-match "\\`#\\+" rpl)
11761 (cond
11762 ((bolp))
11763 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11764 (setq ind (buffer-substring (point-at-bol) (point))))
11765 (t (newline))))
11766 (setq start (point))
11767 (if (string-match "%file" rpl)
11768 (setq rpl (replace-match
11769 (concat
11770 "\""
11771 (save-match-data
11772 (abbreviate-file-name (read-file-name "Include file: ")))
11773 "\"")
11774 t t rpl)))
11775 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11776 (concat "\n" ind)))
11777 (insert rpl)
11778 (if (re-search-backward "\\?" start t) (delete-char 1))))
11780 ;;;; TODO, DEADLINE, Comments
11782 (defun org-toggle-comment ()
11783 "Change the COMMENT state of an entry."
11784 (interactive)
11785 (save-excursion
11786 (org-back-to-heading)
11787 (let (case-fold-search)
11788 (cond
11789 ((looking-at (format org-heading-keyword-regexp-format
11790 org-comment-string))
11791 (goto-char (match-end 1))
11792 (looking-at (concat " +" org-comment-string))
11793 (replace-match "" t t)
11794 (when (eolp) (insert " ")))
11795 ((looking-at org-outline-regexp)
11796 (goto-char (match-end 0))
11797 (insert org-comment-string " "))))))
11799 (defvar org-last-todo-state-is-todo nil
11800 "This is non-nil when the last TODO state change led to a TODO state.
11801 If the last change removed the TODO tag or switched to DONE, then
11802 this is nil.")
11804 (defvar org-setting-tags nil) ; dynamically skipped
11806 (defvar org-todo-setup-filter-hook nil
11807 "Hook for functions that pre-filter todo specs.
11808 Each function takes a todo spec and returns either nil or the spec
11809 transformed into canonical form." )
11811 (defvar org-todo-get-default-hook nil
11812 "Hook for functions that get a default item for todo.
11813 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11814 nil or a string to be used for the todo mark." )
11816 (defvar org-agenda-headline-snapshot-before-repeat)
11818 (defun org-current-effective-time ()
11819 "Return current time adjusted for `org-extend-today-until' variable."
11820 (let* ((ct (org-current-time))
11821 (dct (decode-time ct))
11822 (ct1
11823 (cond
11824 (org-use-last-clock-out-time-as-effective-time
11825 (or (org-clock-get-last-clock-out-time) ct))
11826 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11827 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11828 (t ct))))
11829 ct1))
11831 (defun org-todo-yesterday (&optional arg)
11832 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11833 (interactive "P")
11834 (if (eq major-mode 'org-agenda-mode)
11835 (apply 'org-agenda-todo-yesterday arg)
11836 (let* ((hour (third (decode-time
11837 (org-current-time))))
11838 (org-extend-today-until (1+ hour)))
11839 (org-todo arg))))
11841 (defvar org-block-entry-blocking ""
11842 "First entry preventing the TODO state change.")
11844 (defun org-todo (&optional arg)
11845 "Change the TODO state of an item.
11846 The state of an item is given by a keyword at the start of the heading,
11847 like
11848 *** TODO Write paper
11849 *** DONE Call mom
11851 The different keywords are specified in the variable `org-todo-keywords'.
11852 By default the available states are \"TODO\" and \"DONE\".
11853 So for this example: when the item starts with TODO, it is changed to DONE.
11854 When it starts with DONE, the DONE is removed. And when neither TODO nor
11855 DONE are present, add TODO at the beginning of the heading.
11857 With \\[universal-argument] prefix arg, use completion to determine the new \
11858 state.
11859 With numeric prefix arg, switch to that state.
11860 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11861 keywords (nextset).
11862 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11863 With a numeric prefix arg of 0, inhibit note taking for the change.
11865 For calling through lisp, arg is also interpreted in the following way:
11866 'none -> empty state
11867 \"\"(empty string) -> switch to empty state
11868 'done -> switch to DONE
11869 'nextset -> switch to the next set of keywords
11870 'previousset -> switch to the previous set of keywords
11871 \"WAITING\" -> switch to the specified keyword, but only if it
11872 really is a member of `org-todo-keywords'."
11873 (interactive "P")
11874 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11875 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11876 'region-start-level 'region))
11877 org-loop-over-headlines-in-active-region)
11878 (org-map-entries
11879 `(org-todo ,arg)
11880 org-loop-over-headlines-in-active-region
11881 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11882 (if (equal arg '(16)) (setq arg 'nextset))
11883 (let ((org-blocker-hook org-blocker-hook)
11884 commentp
11885 case-fold-search)
11886 (when (equal arg '(64))
11887 (setq arg nil org-blocker-hook nil))
11888 (when (and org-blocker-hook
11889 (or org-inhibit-blocking
11890 (org-entry-get nil "NOBLOCKING")))
11891 (setq org-blocker-hook nil))
11892 (save-excursion
11893 (catch 'exit
11894 (org-back-to-heading t)
11895 (when (looking-at (concat "^\\*+ " org-comment-string))
11896 (org-toggle-comment)
11897 (setq commentp t))
11898 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11899 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11900 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11901 (let* ((match-data (match-data))
11902 (startpos (point-at-bol))
11903 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11904 (org-log-done org-log-done)
11905 (org-log-repeat org-log-repeat)
11906 (org-todo-log-states org-todo-log-states)
11907 (org-inhibit-logging
11908 (if (equal arg 0)
11909 (progn (setq arg nil) 'note) org-inhibit-logging))
11910 (this (match-string 1))
11911 (hl-pos (match-beginning 0))
11912 (head (org-get-todo-sequence-head this))
11913 (ass (assoc head org-todo-kwd-alist))
11914 (interpret (nth 1 ass))
11915 (done-word (nth 3 ass))
11916 (final-done-word (nth 4 ass))
11917 (org-last-state (or this ""))
11918 (completion-ignore-case t)
11919 (member (member this org-todo-keywords-1))
11920 (tail (cdr member))
11921 (org-state (cond
11922 ((and org-todo-key-trigger
11923 (or (and (equal arg '(4))
11924 (eq org-use-fast-todo-selection 'prefix))
11925 (and (not arg) org-use-fast-todo-selection
11926 (not (eq org-use-fast-todo-selection
11927 'prefix)))))
11928 ;; Use fast selection
11929 (org-fast-todo-selection))
11930 ((and (equal arg '(4))
11931 (or (not org-use-fast-todo-selection)
11932 (not org-todo-key-trigger)))
11933 ;; Read a state with completion
11934 (org-icompleting-read
11935 "State: " (mapcar (lambda(x) (list x))
11936 org-todo-keywords-1)
11937 nil t))
11938 ((eq arg 'right)
11939 (if this
11940 (if tail (car tail) nil)
11941 (car org-todo-keywords-1)))
11942 ((eq arg 'left)
11943 (if (equal member org-todo-keywords-1)
11945 (if this
11946 (nth (- (length org-todo-keywords-1)
11947 (length tail) 2)
11948 org-todo-keywords-1)
11949 (org-last org-todo-keywords-1))))
11950 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11951 (setq arg nil))) ; hack to fall back to cycling
11952 (arg
11953 ;; user or caller requests a specific state
11954 (cond
11955 ((equal arg "") nil)
11956 ((eq arg 'none) nil)
11957 ((eq arg 'done) (or done-word (car org-done-keywords)))
11958 ((eq arg 'nextset)
11959 (or (car (cdr (member head org-todo-heads)))
11960 (car org-todo-heads)))
11961 ((eq arg 'previousset)
11962 (let ((org-todo-heads (reverse org-todo-heads)))
11963 (or (car (cdr (member head org-todo-heads)))
11964 (car org-todo-heads))))
11965 ((car (member arg org-todo-keywords-1)))
11966 ((stringp arg)
11967 (error "State `%s' not valid in this file" arg))
11968 ((nth (1- (prefix-numeric-value arg))
11969 org-todo-keywords-1))))
11970 ((null member) (or head (car org-todo-keywords-1)))
11971 ((equal this final-done-word) nil) ;; -> make empty
11972 ((null tail) nil) ;; -> first entry
11973 ((memq interpret '(type priority))
11974 (if (eq this-command last-command)
11975 (car tail)
11976 (if (> (length tail) 0)
11977 (or done-word (car org-done-keywords))
11978 nil)))
11980 (car tail))))
11981 (org-state (or
11982 (run-hook-with-args-until-success
11983 'org-todo-get-default-hook org-state org-last-state)
11984 org-state))
11985 (next (if org-state (concat " " org-state " ") " "))
11986 (change-plist (list :type 'todo-state-change :from this :to org-state
11987 :position startpos))
11988 dolog now-done-p)
11989 (when org-blocker-hook
11990 (setq org-last-todo-state-is-todo
11991 (not (member this org-done-keywords)))
11992 (unless (save-excursion
11993 (save-match-data
11994 (org-with-wide-buffer
11995 (run-hook-with-args-until-failure
11996 'org-blocker-hook change-plist))))
11997 (if (org-called-interactively-p 'interactive)
11998 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11999 this org-state org-block-entry-blocking)
12000 ;; fail silently
12001 (message "TODO state change from %s to %s blocked (by \"%s\")"
12002 this org-state org-block-entry-blocking)
12003 (throw 'exit nil))))
12004 (store-match-data match-data)
12005 (replace-match next t t)
12006 (unless (pos-visible-in-window-p hl-pos)
12007 (message "TODO state changed to %s" (org-trim next)))
12008 (unless head
12009 (setq head (org-get-todo-sequence-head org-state)
12010 ass (assoc head org-todo-kwd-alist)
12011 interpret (nth 1 ass)
12012 done-word (nth 3 ass)
12013 final-done-word (nth 4 ass)))
12014 (when (memq arg '(nextset previousset))
12015 (message "Keyword-Set %d/%d: %s"
12016 (- (length org-todo-sets) -1
12017 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12018 (length org-todo-sets)
12019 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12020 (setq org-last-todo-state-is-todo
12021 (not (member org-state org-done-keywords)))
12022 (setq now-done-p (and (member org-state org-done-keywords)
12023 (not (member this org-done-keywords))))
12024 (and logging (org-local-logging logging))
12025 (when (and (or org-todo-log-states org-log-done)
12026 (not (eq org-inhibit-logging t))
12027 (not (memq arg '(nextset previousset))))
12028 ;; we need to look at recording a time and note
12029 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12030 (nth 2 (assoc this org-todo-log-states))))
12031 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12032 (setq dolog 'time))
12033 (when (and org-state
12034 (member org-state org-not-done-keywords)
12035 (not (member this org-not-done-keywords)))
12036 ;; This is now a todo state and was not one before
12037 ;; If there was a CLOSED time stamp, get rid of it.
12038 (org-add-planning-info nil nil 'closed))
12039 (when (and now-done-p org-log-done)
12040 ;; It is now done, and it was not done before
12041 (org-add-planning-info 'closed (org-current-effective-time))
12042 (if (and (not dolog) (eq 'note org-log-done))
12043 (org-add-log-setup 'done org-state this 'findpos 'note)))
12044 (when (and org-state dolog)
12045 ;; This is a non-nil state, and we need to log it
12046 (org-add-log-setup 'state org-state this 'findpos dolog)))
12047 ;; Fixup tag positioning
12048 (org-todo-trigger-tag-changes org-state)
12049 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12050 (when org-provide-todo-statistics
12051 (org-update-parent-todo-statistics))
12052 (run-hooks 'org-after-todo-state-change-hook)
12053 (if (and arg (not (member org-state org-done-keywords)))
12054 (setq head (org-get-todo-sequence-head org-state)))
12055 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12056 ;; Do we need to trigger a repeat?
12057 (when now-done-p
12058 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12059 ;; This is for the agenda, take a snapshot of the headline.
12060 (save-match-data
12061 (setq org-agenda-headline-snapshot-before-repeat
12062 (org-get-heading))))
12063 (org-auto-repeat-maybe org-state))
12064 ;; Fixup cursor location if close to the keyword
12065 (if (and (outline-on-heading-p)
12066 (not (bolp))
12067 (save-excursion (beginning-of-line 1)
12068 (looking-at org-todo-line-regexp))
12069 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12070 (progn
12071 (goto-char (or (match-end 2) (match-end 1)))
12072 (and (looking-at " ") (just-one-space))))
12073 (when org-trigger-hook
12074 (save-excursion
12075 (run-hook-with-args 'org-trigger-hook change-plist)))
12076 (when commentp (org-toggle-comment))))))))
12078 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12079 "Block turning an entry into a TODO, using the hierarchy.
12080 This checks whether the current task should be blocked from state
12081 changes. Such blocking occurs when:
12083 1. The task has children which are not all in a completed state.
12085 2. A task has a parent with the property :ORDERED:, and there
12086 are siblings prior to the current task with incomplete
12087 status.
12089 3. The parent of the task is blocked because it has siblings that should
12090 be done first, or is child of a block grandparent TODO entry."
12092 (if (not org-enforce-todo-dependencies)
12093 t ; if locally turned off don't block
12094 (catch 'dont-block
12095 ;; If this is not a todo state change, or if this entry is already DONE,
12096 ;; do not block
12097 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12098 (member (plist-get change-plist :from)
12099 (cons 'done org-done-keywords))
12100 (member (plist-get change-plist :to)
12101 (cons 'todo org-not-done-keywords))
12102 (not (plist-get change-plist :to)))
12103 (throw 'dont-block t))
12104 ;; If this task has children, and any are undone, it's blocked
12105 (save-excursion
12106 (org-back-to-heading t)
12107 (let ((this-level (funcall outline-level)))
12108 (outline-next-heading)
12109 (let ((child-level (funcall outline-level)))
12110 (while (and (not (eobp))
12111 (> child-level this-level))
12112 ;; this todo has children, check whether they are all
12113 ;; completed
12114 (if (and (not (org-entry-is-done-p))
12115 (org-entry-is-todo-p))
12116 (progn (setq org-block-entry-blocking (org-get-heading))
12117 (throw 'dont-block nil)))
12118 (outline-next-heading)
12119 (setq child-level (funcall outline-level))))))
12120 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12121 ;; any previous siblings are undone, it's blocked
12122 (save-excursion
12123 (org-back-to-heading t)
12124 (let* ((pos (point))
12125 (parent-pos (and (org-up-heading-safe) (point))))
12126 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12127 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12128 (forward-line 1)
12129 (re-search-forward org-not-done-heading-regexp pos t))
12130 (setq org-block-entry-blocking (match-string 0))
12131 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12132 ;; Search further up the hierarchy, to see if an ancestor is blocked
12133 (while t
12134 (goto-char parent-pos)
12135 (if (not (looking-at org-not-done-heading-regexp))
12136 (throw 'dont-block t)) ; do not block, parent is not a TODO
12137 (setq pos (point))
12138 (setq parent-pos (and (org-up-heading-safe) (point)))
12139 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12140 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12141 (forward-line 1)
12142 (re-search-forward org-not-done-heading-regexp pos t)
12143 (setq org-block-entry-blocking (org-get-heading)))
12144 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12146 (defcustom org-track-ordered-property-with-tag nil
12147 "Should the ORDERED property also be shown as a tag?
12148 The ORDERED property decides if an entry should require subtasks to be
12149 completed in sequence. Since a property is not very visible, setting
12150 this option means that toggling the ORDERED property with the command
12151 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12152 not relevant for the behavior, but it makes things more visible.
12154 Note that toggling the tag with tags commands will not change the property
12155 and therefore not influence behavior!
12157 This can be t, meaning the tag ORDERED should be used, It can also be a
12158 string to select a different tag for this task."
12159 :group 'org-todo
12160 :type '(choice
12161 (const :tag "No tracking" nil)
12162 (const :tag "Track with ORDERED tag" t)
12163 (string :tag "Use other tag")))
12165 (defun org-toggle-ordered-property ()
12166 "Toggle the ORDERED property of the current entry.
12167 For better visibility, you can track the value of this property with a tag.
12168 See variable `org-track-ordered-property-with-tag'."
12169 (interactive)
12170 (let* ((t1 org-track-ordered-property-with-tag)
12171 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12172 (save-excursion
12173 (org-back-to-heading)
12174 (if (org-entry-get nil "ORDERED")
12175 (progn
12176 (org-delete-property "ORDERED" "PROPERTIES")
12177 (and tag (org-toggle-tag tag 'off))
12178 (message "Subtasks can be completed in arbitrary order"))
12179 (org-entry-put nil "ORDERED" "t")
12180 (and tag (org-toggle-tag tag 'on))
12181 (message "Subtasks must be completed in sequence")))))
12183 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12184 (defun org-block-todo-from-checkboxes (change-plist)
12185 "Block turning an entry into a TODO, using checkboxes.
12186 This checks whether the current task should be blocked from state
12187 changes because there are unchecked boxes in this entry."
12188 (if (not org-enforce-todo-checkbox-dependencies)
12189 t ; if locally turned off don't block
12190 (catch 'dont-block
12191 ;; If this is not a todo state change, or if this entry is already DONE,
12192 ;; do not block
12193 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12194 (member (plist-get change-plist :from)
12195 (cons 'done org-done-keywords))
12196 (member (plist-get change-plist :to)
12197 (cons 'todo org-not-done-keywords))
12198 (not (plist-get change-plist :to)))
12199 (throw 'dont-block t))
12200 ;; If this task has checkboxes that are not checked, it's blocked
12201 (save-excursion
12202 (org-back-to-heading t)
12203 (let ((beg (point)) end)
12204 (outline-next-heading)
12205 (setq end (point))
12206 (goto-char beg)
12207 (if (org-list-search-forward
12208 (concat (org-item-beginning-re)
12209 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12210 "\\[[- ]\\]")
12211 end t)
12212 (progn
12213 (if (boundp 'org-blocked-by-checkboxes)
12214 (setq org-blocked-by-checkboxes t))
12215 (throw 'dont-block nil)))))
12216 t))) ; do not block
12218 (defun org-entry-blocked-p ()
12219 "Is the current entry blocked?"
12220 (org-with-silent-modifications
12221 (if (org-entry-get nil "NOBLOCKING")
12222 nil ;; Never block this entry
12223 (not (run-hook-with-args-until-failure
12224 'org-blocker-hook
12225 (list :type 'todo-state-change
12226 :position (point)
12227 :from 'todo
12228 :to 'done))))))
12230 (defun org-update-statistics-cookies (all)
12231 "Update the statistics cookie, either from TODO or from checkboxes.
12232 This should be called with the cursor in a line with a statistics cookie."
12233 (interactive "P")
12234 (if all
12235 (progn
12236 (org-update-checkbox-count 'all)
12237 (org-map-entries 'org-update-parent-todo-statistics))
12238 (if (not (org-at-heading-p))
12239 (org-update-checkbox-count)
12240 (let ((pos (point-marker))
12241 end l1 l2)
12242 (ignore-errors (org-back-to-heading t))
12243 (if (not (org-at-heading-p))
12244 (org-update-checkbox-count)
12245 (setq l1 (org-outline-level))
12246 (setq end (save-excursion
12247 (outline-next-heading)
12248 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12249 (point)))
12250 (if (and (save-excursion
12251 (re-search-forward
12252 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12253 (not (save-excursion (re-search-forward
12254 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12255 (org-update-checkbox-count)
12256 (if (and l2 (> l2 l1))
12257 (progn
12258 (goto-char end)
12259 (org-update-parent-todo-statistics))
12260 (goto-char pos)
12261 (beginning-of-line 1)
12262 (while (re-search-forward
12263 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12264 (point-at-eol) t)
12265 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12266 (goto-char pos)
12267 (move-marker pos nil)))))
12269 (defvar org-entry-property-inherited-from) ;; defined below
12270 (defun org-update-parent-todo-statistics ()
12271 "Update any statistics cookie in the parent of the current headline.
12272 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12273 the entire subtree and this will travel up the hierarchy and update
12274 statistics everywhere."
12275 (let* ((prop (save-excursion (org-up-heading-safe)
12276 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12277 (recursive (or (not org-hierarchical-todo-statistics)
12278 (and prop (string-match "\\<recursive\\>" prop))))
12279 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12281 (first t)
12282 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12283 level ltoggle l1 new ndel
12284 (cnt-all 0) (cnt-done 0) is-percent kwd
12285 checkbox-beg ov ovs ove cookie-present)
12286 (catch 'exit
12287 (save-excursion
12288 (beginning-of-line 1)
12289 (setq ltoggle (funcall outline-level))
12290 ;; Three situations are to consider:
12292 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12293 ;; to the top-level ancestor on the headline;
12295 ;; 2. If parent has "recursive" property, repeat up to the
12296 ;; headline setting that property, taking inheritance into
12297 ;; account;
12299 ;; 3. Else, move up to direct parent and proceed only once.
12300 (while (and (setq level (org-up-heading-safe))
12301 (or recursive first)
12302 (>= (point) lim))
12303 (setq first nil cookie-present nil)
12304 (unless (and level
12305 (not (string-match
12306 "\\<checkbox\\>"
12307 (downcase (or (org-entry-get nil "COOKIE_DATA")
12308 "")))))
12309 (throw 'exit nil))
12310 (while (re-search-forward box-re (point-at-eol) t)
12311 (setq cnt-all 0 cnt-done 0 cookie-present t)
12312 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12313 (save-match-data
12314 (unless (outline-next-heading) (throw 'exit nil))
12315 (while (and (looking-at org-complex-heading-regexp)
12316 (> (setq l1 (length (match-string 1))) level))
12317 (setq kwd (and (or recursive (= l1 ltoggle))
12318 (match-string 2)))
12319 (if (or (eq org-provide-todo-statistics 'all-headlines)
12320 (and (listp org-provide-todo-statistics)
12321 (or (member kwd org-provide-todo-statistics)
12322 (member kwd org-done-keywords))))
12323 (setq cnt-all (1+ cnt-all))
12324 (if (eq org-provide-todo-statistics t)
12325 (and kwd (setq cnt-all (1+ cnt-all)))))
12326 (and (member kwd org-done-keywords)
12327 (setq cnt-done (1+ cnt-done)))
12328 (outline-next-heading)))
12329 (setq new
12330 (if is-percent
12331 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12332 (format "[%d/%d]" cnt-done cnt-all))
12333 ndel (- (match-end 0) checkbox-beg))
12334 ;; handle overlays when updating cookie from column view
12335 (when (setq ov (car (overlays-at checkbox-beg)))
12336 (setq ovs (overlay-start ov) ove (overlay-end ov))
12337 (delete-overlay ov))
12338 (goto-char checkbox-beg)
12339 (insert new)
12340 (delete-region (point) (+ (point) ndel))
12341 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12342 (when ov (move-overlay ov ovs ove)))
12343 (when cookie-present
12344 (run-hook-with-args 'org-after-todo-statistics-hook
12345 cnt-done (- cnt-all cnt-done))))))
12346 (run-hooks 'org-todo-statistics-hook)))
12348 (defvar org-after-todo-statistics-hook nil
12349 "Hook that is called after a TODO statistics cookie has been updated.
12350 Each function is called with two arguments: the number of not-done entries
12351 and the number of done entries.
12353 For example, the following function, when added to this hook, will switch
12354 an entry to DONE when all children are done, and back to TODO when new
12355 entries are set to a TODO status. Note that this hook is only called
12356 when there is a statistics cookie in the headline!
12358 (defun org-summary-todo (n-done n-not-done)
12359 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12360 (let (org-log-done org-log-states) ; turn off logging
12361 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12364 (defvar org-todo-statistics-hook nil
12365 "Hook that is run whenever Org thinks TODO statistics should be updated.
12366 This hook runs even if there is no statistics cookie present, in which case
12367 `org-after-todo-statistics-hook' would not run.")
12369 (defun org-todo-trigger-tag-changes (state)
12370 "Apply the changes defined in `org-todo-state-tags-triggers'."
12371 (let ((l org-todo-state-tags-triggers)
12372 changes)
12373 (when (or (not state) (equal state ""))
12374 (setq changes (append changes (cdr (assoc "" l)))))
12375 (when (and (stringp state) (> (length state) 0))
12376 (setq changes (append changes (cdr (assoc state l)))))
12377 (when (member state org-not-done-keywords)
12378 (setq changes (append changes (cdr (assoc 'todo l)))))
12379 (when (member state org-done-keywords)
12380 (setq changes (append changes (cdr (assoc 'done l)))))
12381 (dolist (c changes)
12382 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12384 (defun org-local-logging (value)
12385 "Get logging settings from a property VALUE."
12386 (let* (words w a)
12387 ;; directly set the variables, they are already local.
12388 (setq org-log-done nil
12389 org-log-repeat nil
12390 org-todo-log-states nil)
12391 (setq words (org-split-string value))
12392 (while (setq w (pop words))
12393 (cond
12394 ((setq a (assoc w org-startup-options))
12395 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12396 (set (nth 1 a) (nth 2 a))))
12397 ((setq a (org-extract-log-state-settings w))
12398 (and (member (car a) org-todo-keywords-1)
12399 (push a org-todo-log-states)))))))
12401 (defun org-get-todo-sequence-head (kwd)
12402 "Return the head of the TODO sequence to which KWD belongs.
12403 If KWD is not set, check if there is a text property remembering the
12404 right sequence."
12405 (let (p)
12406 (cond
12407 ((not kwd)
12408 (or (get-text-property (point-at-bol) 'org-todo-head)
12409 (progn
12410 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12411 nil (point-at-eol)))
12412 (get-text-property p 'org-todo-head))))
12413 ((not (member kwd org-todo-keywords-1))
12414 (car org-todo-keywords-1))
12415 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12417 (defun org-fast-todo-selection ()
12418 "Fast TODO keyword selection with single keys.
12419 Returns the new TODO keyword, or nil if no state change should occur."
12420 (let* ((fulltable org-todo-key-alist)
12421 (done-keywords org-done-keywords) ;; needed for the faces.
12422 (maxlen (apply 'max (mapcar
12423 (lambda (x)
12424 (if (stringp (car x)) (string-width (car x)) 0))
12425 fulltable)))
12426 (expert nil)
12427 (fwidth (+ maxlen 3 1 3))
12428 (ncol (/ (- (window-width) 4) fwidth))
12429 tg cnt e c tbl
12430 groups ingroup)
12431 (save-excursion
12432 (save-window-excursion
12433 (if expert
12434 (set-buffer (get-buffer-create " *Org todo*"))
12435 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12436 (erase-buffer)
12437 (org-set-local 'org-done-keywords done-keywords)
12438 (setq tbl fulltable cnt 0)
12439 (while (setq e (pop tbl))
12440 (cond
12441 ((equal e '(:startgroup))
12442 (push '() groups) (setq ingroup t)
12443 (when (not (= cnt 0))
12444 (setq cnt 0)
12445 (insert "\n"))
12446 (insert "{ "))
12447 ((equal e '(:endgroup))
12448 (setq ingroup nil cnt 0)
12449 (insert "}\n"))
12450 ((equal e '(:newline))
12451 (when (not (= cnt 0))
12452 (setq cnt 0)
12453 (insert "\n")
12454 (setq e (car tbl))
12455 (while (equal (car tbl) '(:newline))
12456 (insert "\n")
12457 (setq tbl (cdr tbl)))))
12459 (setq tg (car e) c (cdr e))
12460 (if ingroup (push tg (car groups)))
12461 (setq tg (org-add-props tg nil 'face
12462 (org-get-todo-face tg)))
12463 (if (and (= cnt 0) (not ingroup)) (insert " "))
12464 (insert "[" c "] " tg (make-string
12465 (- fwidth 4 (length tg)) ?\ ))
12466 (when (= (setq cnt (1+ cnt)) ncol)
12467 (insert "\n")
12468 (if ingroup (insert " "))
12469 (setq cnt 0)))))
12470 (insert "\n")
12471 (goto-char (point-min))
12472 (if (not expert) (org-fit-window-to-buffer))
12473 (message "[a-z..]:Set [SPC]:clear")
12474 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12475 (cond
12476 ((or (= c ?\C-g)
12477 (and (= c ?q) (not (rassoc c fulltable))))
12478 (setq quit-flag t))
12479 ((= c ?\ ) nil)
12480 ((setq e (rassoc c fulltable) tg (car e))
12482 (t (setq quit-flag t)))))))
12484 (defun org-entry-is-todo-p ()
12485 (member (org-get-todo-state) org-not-done-keywords))
12487 (defun org-entry-is-done-p ()
12488 (member (org-get-todo-state) org-done-keywords))
12490 (defun org-get-todo-state ()
12491 (save-excursion
12492 (org-back-to-heading t)
12493 (and (looking-at org-todo-line-regexp)
12494 (match-end 2)
12495 (match-string 2))))
12497 (defun org-at-date-range-p (&optional inactive-ok)
12498 "Is the cursor inside a date range?"
12499 (interactive)
12500 (save-excursion
12501 (catch 'exit
12502 (let ((pos (point)))
12503 (skip-chars-backward "^[<\r\n")
12504 (skip-chars-backward "<[")
12505 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12506 (>= (match-end 0) pos)
12507 (throw 'exit t))
12508 (skip-chars-backward "^<[\r\n")
12509 (skip-chars-backward "<[")
12510 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12511 (>= (match-end 0) pos)
12512 (throw 'exit t)))
12513 nil)))
12515 (defun org-get-repeat (&optional tagline)
12516 "Check if there is a deadline/schedule with repeater in this entry."
12517 (save-match-data
12518 (save-excursion
12519 (org-back-to-heading t)
12520 (and (re-search-forward (if tagline
12521 (concat tagline "\\s-*" org-repeat-re)
12522 org-repeat-re)
12523 (org-entry-end-position) t)
12524 (match-string-no-properties 1)))))
12526 (defvar org-last-changed-timestamp)
12527 (defvar org-last-inserted-timestamp)
12528 (defvar org-log-post-message)
12529 (defvar org-log-note-purpose)
12530 (defvar org-log-note-how)
12531 (defvar org-log-note-extra)
12532 (defun org-auto-repeat-maybe (done-word)
12533 "Check if the current headline contains a repeated deadline/schedule.
12534 If yes, set TODO state back to what it was and change the base date
12535 of repeating deadline/scheduled time stamps to new date.
12536 This function is run automatically after each state change to a DONE state."
12537 ;; last-state is dynamically scoped into this function
12538 (let* ((repeat (org-get-repeat))
12539 (aa (assoc org-last-state org-todo-kwd-alist))
12540 (interpret (nth 1 aa))
12541 (head (nth 2 aa))
12542 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12543 (msg "Entry repeats: ")
12544 (org-log-done nil)
12545 (org-todo-log-states nil)
12546 re type n what ts time to-state)
12547 (when repeat
12548 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12549 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12550 org-todo-repeat-to-state))
12551 (unless (and to-state (member to-state org-todo-keywords-1))
12552 (setq to-state (if (eq interpret 'type) org-last-state head)))
12553 (org-todo to-state)
12554 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12555 (org-entry-put nil "LAST_REPEAT" (format-time-string
12556 (org-time-stamp-format t t))))
12557 (when org-log-repeat
12558 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12559 (memq 'org-add-log-note post-command-hook))
12560 ;; OK, we are already setup for some record
12561 (if (eq org-log-repeat 'note)
12562 ;; make sure we take a note, not only a time stamp
12563 (setq org-log-note-how 'note))
12564 ;; Set up for taking a record
12565 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12566 org-last-state
12567 'findpos org-log-repeat)))
12568 (org-back-to-heading t)
12569 (org-add-planning-info nil nil 'closed)
12570 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12571 org-deadline-time-regexp "\\)\\|\\("
12572 org-ts-regexp "\\)"))
12573 (while (re-search-forward
12574 re (save-excursion (outline-next-heading) (point)) t)
12575 (setq type (if (match-end 1) org-scheduled-string
12576 (if (match-end 3) org-deadline-string "Plain:"))
12577 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12578 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12579 (setq n (string-to-number (match-string 2 ts))
12580 what (match-string 3 ts))
12581 (if (equal what "w") (setq n (* n 7) what "d"))
12582 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12583 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12584 ;; Preparation, see if we need to modify the start date for the change
12585 (when (match-end 1)
12586 (setq time (save-match-data (org-time-string-to-time ts)))
12587 (cond
12588 ((equal (match-string 1 ts) ".")
12589 ;; Shift starting date to today
12590 (org-timestamp-change
12591 (- (org-today) (time-to-days time))
12592 'day))
12593 ((equal (match-string 1 ts) "+")
12594 (let ((nshiftmax 10) (nshift 0))
12595 (while (or (= nshift 0)
12596 (<= (time-to-days time)
12597 (time-to-days (current-time))))
12598 (when (= (incf nshift) nshiftmax)
12599 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12600 (error "Abort")))
12601 (org-timestamp-change n (cdr (assoc what whata)))
12602 (org-at-timestamp-p t)
12603 (setq ts (match-string 1))
12604 (setq time (save-match-data (org-time-string-to-time ts)))))
12605 (org-timestamp-change (- n) (cdr (assoc what whata)))
12606 ;; rematch, so that we have everything in place for the real shift
12607 (org-at-timestamp-p t)
12608 (setq ts (match-string 1))
12609 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12610 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12611 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12612 (setq org-log-post-message msg)
12613 (message "%s" msg))))
12615 (defun org-show-todo-tree (arg)
12616 "Make a compact tree which shows all headlines marked with TODO.
12617 The tree will show the lines where the regexp matches, and all higher
12618 headlines above the match.
12619 With a \\[universal-argument] prefix, prompt for a regexp to match.
12620 With a numeric prefix N, construct a sparse tree for the Nth element
12621 of `org-todo-keywords-1'."
12622 (interactive "P")
12623 (let ((case-fold-search nil)
12624 (kwd-re
12625 (cond ((null arg) org-not-done-regexp)
12626 ((equal arg '(4))
12627 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12628 (mapcar 'list org-todo-keywords-1))))
12629 (concat "\\("
12630 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12631 "\\)\\>")))
12632 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12633 (regexp-quote (nth (1- (prefix-numeric-value arg))
12634 org-todo-keywords-1)))
12635 (t (error "Invalid prefix argument: %s" arg)))))
12636 (message "%d TODO entries found"
12637 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12639 (defun org-deadline (arg &optional time)
12640 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12641 With one universal prefix argument, remove any deadline from the item.
12642 With two universal prefix arguments, prompt for a warning delay.
12643 With argument TIME, set the deadline at the corresponding date. TIME
12644 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12645 (interactive "P")
12646 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12647 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12648 'region-start-level 'region))
12649 org-loop-over-headlines-in-active-region)
12650 (org-map-entries
12651 `(org-deadline ',arg ,time)
12652 org-loop-over-headlines-in-active-region
12653 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12654 (let* ((old-date (org-entry-get nil "DEADLINE"))
12655 (old-date-time (if old-date (org-time-string-to-time old-date)))
12656 (repeater (and old-date
12657 (string-match
12658 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12659 old-date)
12660 (match-string 1 old-date))))
12661 (cond
12662 ((equal arg '(4))
12663 (when (and old-date org-log-redeadline)
12664 (org-add-log-setup 'deldeadline nil old-date 'findpos
12665 org-log-redeadline))
12666 (org-remove-timestamp-with-keyword org-deadline-string)
12667 (message "Item no longer has a deadline."))
12668 ((equal arg '(16))
12669 (save-excursion
12670 (if (re-search-forward
12671 org-deadline-time-regexp
12672 (save-excursion (outline-next-heading) (point)) t)
12673 (let* ((rpl0 (match-string 1))
12674 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12675 (replace-match
12676 (concat org-deadline-string
12677 " <" rpl
12678 (format " -%dd"
12679 (abs
12680 (- (time-to-days
12681 (save-match-data
12682 (org-read-date nil t nil "Warn starting from" old-date-time)))
12683 (time-to-days old-date-time))))
12684 ">") t t))
12685 (user-error "No deadline information to update"))))
12687 (org-add-planning-info 'deadline time 'closed)
12688 (when (and old-date org-log-redeadline
12689 (not (equal old-date
12690 (substring org-last-inserted-timestamp 1 -1))))
12691 (org-add-log-setup 'redeadline nil old-date 'findpos
12692 org-log-redeadline))
12693 (when repeater
12694 (save-excursion
12695 (org-back-to-heading t)
12696 (when (re-search-forward (concat org-deadline-string " "
12697 org-last-inserted-timestamp)
12698 (save-excursion
12699 (outline-next-heading) (point)) t)
12700 (goto-char (1- (match-end 0)))
12701 (insert " " repeater)
12702 (setq org-last-inserted-timestamp
12703 (concat (substring org-last-inserted-timestamp 0 -1)
12704 " " repeater
12705 (substring org-last-inserted-timestamp -1))))))
12706 (message "Deadline on %s" org-last-inserted-timestamp))))))
12708 (defun org-schedule (arg &optional time)
12709 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12710 With one universal prefix argument, remove any scheduling date from the item.
12711 With two universal prefix arguments, prompt for a delay cookie.
12712 With argument TIME, scheduled at the corresponding date. TIME can
12713 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12714 (interactive "P")
12715 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12716 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12717 'region-start-level 'region))
12718 org-loop-over-headlines-in-active-region)
12719 (org-map-entries
12720 `(org-schedule ',arg ,time)
12721 org-loop-over-headlines-in-active-region
12722 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12723 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12724 (old-date-time (if old-date (org-time-string-to-time old-date)))
12725 (repeater (and old-date
12726 (string-match
12727 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12728 old-date)
12729 (match-string 1 old-date))))
12730 (cond
12731 ((equal arg '(4))
12732 (progn
12733 (when (and old-date org-log-reschedule)
12734 (org-add-log-setup 'delschedule nil old-date 'findpos
12735 org-log-reschedule))
12736 (org-remove-timestamp-with-keyword org-scheduled-string)
12737 (message "Item is no longer scheduled.")))
12738 ((equal arg '(16))
12739 (save-excursion
12740 (if (re-search-forward
12741 org-scheduled-time-regexp
12742 (save-excursion (outline-next-heading) (point)) t)
12743 (let* ((rpl0 (match-string 1))
12744 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12745 (replace-match
12746 (concat org-scheduled-string
12747 " <" rpl
12748 (format " -%dd"
12749 (abs
12750 (- (time-to-days
12751 (save-match-data
12752 (org-read-date nil t nil "Delay until" old-date-time)))
12753 (time-to-days old-date-time))))
12754 ">") t t))
12755 (user-error "No scheduled information to update"))))
12757 (org-add-planning-info 'scheduled time 'closed)
12758 (when (and old-date org-log-reschedule
12759 (not (equal old-date
12760 (substring org-last-inserted-timestamp 1 -1))))
12761 (org-add-log-setup 'reschedule nil old-date 'findpos
12762 org-log-reschedule))
12763 (when repeater
12764 (save-excursion
12765 (org-back-to-heading t)
12766 (when (re-search-forward (concat org-scheduled-string " "
12767 org-last-inserted-timestamp)
12768 (save-excursion
12769 (outline-next-heading) (point)) t)
12770 (goto-char (1- (match-end 0)))
12771 (insert " " repeater)
12772 (setq org-last-inserted-timestamp
12773 (concat (substring org-last-inserted-timestamp 0 -1)
12774 " " repeater
12775 (substring org-last-inserted-timestamp -1))))))
12776 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12778 (defun org-get-scheduled-time (pom &optional inherit)
12779 "Get the scheduled time as a time tuple, of a format suitable
12780 for calling org-schedule with, or if there is no scheduling,
12781 returns nil."
12782 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12783 (when time
12784 (apply 'encode-time (org-parse-time-string time)))))
12786 (defun org-get-deadline-time (pom &optional inherit)
12787 "Get the deadline as a time tuple, of a format suitable for
12788 calling org-deadline with, or if there is no scheduling, returns
12789 nil."
12790 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12791 (when time
12792 (apply 'encode-time (org-parse-time-string time)))))
12794 (defun org-remove-timestamp-with-keyword (keyword)
12795 "Remove all time stamps with KEYWORD in the current entry."
12796 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12797 beg)
12798 (save-excursion
12799 (org-back-to-heading t)
12800 (setq beg (point))
12801 (outline-next-heading)
12802 (while (re-search-backward re beg t)
12803 (replace-match "")
12804 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12805 (equal (char-before) ?\ ))
12806 (backward-delete-char 1)
12807 (if (string-match "^[ \t]*$" (buffer-substring
12808 (point-at-bol) (point-at-eol)))
12809 (delete-region (point-at-bol)
12810 (min (point-max) (1+ (point-at-eol))))))))))
12812 (defun org-add-planning-info (what &optional time &rest remove)
12813 "Insert new timestamp with keyword in the line directly after the headline.
12814 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12815 If non is given, the user is prompted for a date.
12816 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12817 be removed."
12818 (interactive)
12819 (let (org-time-was-given org-end-time-was-given ts
12820 end default-time default-input)
12822 (catch 'exit
12823 (when (and (memq what '(scheduled deadline))
12824 (or (not time)
12825 (and (stringp time)
12826 (string-match "^[-+]+[0-9]" time))))
12827 ;; Try to get a default date/time from existing timestamp
12828 (save-excursion
12829 (org-back-to-heading t)
12830 (setq end (save-excursion (outline-next-heading) (point)))
12831 (when (re-search-forward (if (eq what 'scheduled)
12832 org-scheduled-time-regexp
12833 org-deadline-time-regexp)
12834 end t)
12835 (setq ts (match-string 1)
12836 default-time
12837 (apply 'encode-time (org-parse-time-string ts))
12838 default-input (and ts (org-get-compact-tod ts))))))
12839 (when what
12840 (setq time
12841 (if (stringp time)
12842 ;; This is a string (relative or absolute), set proper date
12843 (apply 'encode-time
12844 (org-read-date-analyze
12845 time default-time (decode-time default-time)))
12846 ;; If necessary, get the time from the user
12847 (or time (org-read-date nil 'to-time nil nil
12848 default-time default-input)))))
12850 (when (and org-insert-labeled-timestamps-at-point
12851 (member what '(scheduled deadline)))
12852 (insert
12853 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12854 (org-insert-time-stamp time org-time-was-given
12855 nil nil nil (list org-end-time-was-given))
12856 (setq what nil))
12857 (save-excursion
12858 (save-restriction
12859 (let (col list elt ts buffer-invisibility-spec)
12860 (org-back-to-heading t)
12861 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12862 (goto-char (match-end 1))
12863 (setq col (current-column))
12864 (goto-char (match-end 0))
12865 (if (eobp) (insert "\n") (forward-char 1))
12866 (when (and (not what)
12867 (not (looking-at
12868 (concat "[ \t]*"
12869 org-keyword-time-not-clock-regexp))))
12870 ;; Nothing to add, nothing to remove...... :-)
12871 (throw 'exit nil))
12872 (if (and (not (looking-at org-outline-regexp))
12873 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12874 "[^\r\n]*"))
12875 (not (equal (match-string 1) org-clock-string)))
12876 (narrow-to-region (match-beginning 0) (match-end 0))
12877 (insert-before-markers "\n")
12878 (backward-char 1)
12879 (narrow-to-region (point) (point))
12880 (and org-adapt-indentation (org-indent-to-column col)))
12881 ;; Check if we have to remove something.
12882 (setq list (cons what remove))
12883 (while list
12884 (setq elt (pop list))
12885 (when (or (and (eq elt 'scheduled)
12886 (re-search-forward org-scheduled-time-regexp nil t))
12887 (and (eq elt 'deadline)
12888 (re-search-forward org-deadline-time-regexp nil t))
12889 (and (eq elt 'closed)
12890 (re-search-forward org-closed-time-regexp nil t)))
12891 (replace-match "")
12892 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12893 (and (looking-at "[ \t]+") (replace-match ""))
12894 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12895 (when what
12896 (insert
12897 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12898 (cond ((eq what 'scheduled) org-scheduled-string)
12899 ((eq what 'deadline) org-deadline-string)
12900 ((eq what 'closed) org-closed-string))
12901 " ")
12902 (setq ts (org-insert-time-stamp
12903 time
12904 (or org-time-was-given
12905 (and (eq what 'closed) org-log-done-with-time))
12906 (eq what 'closed)
12907 nil nil (list org-end-time-was-given)))
12908 (insert
12909 (if (not (or (bolp) (eq (char-before) ?\ )
12910 (memq (char-after) '(32 10))
12911 (eobp))) " " ""))
12912 (end-of-line 1))
12913 (goto-char (point-min))
12914 (widen)
12915 (if (and (looking-at "[ \t]*\n")
12916 (equal (char-before) ?\n))
12917 (delete-region (1- (point)) (point-at-eol)))
12918 ts))))))
12920 (defvar org-log-note-marker (make-marker))
12921 (defvar org-log-note-purpose nil)
12922 (defvar org-log-note-state nil)
12923 (defvar org-log-note-previous-state nil)
12924 (defvar org-log-note-how nil)
12925 (defvar org-log-note-extra nil)
12926 (defvar org-log-note-window-configuration nil)
12927 (defvar org-log-note-return-to (make-marker))
12928 (defvar org-log-note-effective-time nil
12929 "Remembered current time so that dynamically scoped
12930 `org-extend-today-until' affects tha timestamps in state change
12931 log")
12933 (defvar org-log-post-message nil
12934 "Message to be displayed after a log note has been stored.
12935 The auto-repeater uses this.")
12937 (defun org-add-note ()
12938 "Add a note to the current entry.
12939 This is done in the same way as adding a state change note."
12940 (interactive)
12941 (org-add-log-setup 'note nil nil 'findpos nil))
12943 (defvar org-property-end-re)
12944 (defun org-add-log-setup (&optional purpose state prev-state
12945 findpos how extra)
12946 "Set up the post command hook to take a note.
12947 If this is about to TODO state change, the new state is expected in STATE.
12948 When FINDPOS is non-nil, find the correct position for the note in
12949 the current entry. If not, assume that it can be inserted at point.
12950 HOW is an indicator what kind of note should be created.
12951 EXTRA is additional text that will be inserted into the notes buffer."
12952 (let* ((org-log-into-drawer (org-log-into-drawer))
12953 (drawer (cond ((stringp org-log-into-drawer)
12954 org-log-into-drawer)
12955 (org-log-into-drawer "LOGBOOK"))))
12956 (save-restriction
12957 (save-excursion
12958 (when findpos
12959 (org-back-to-heading t)
12960 (narrow-to-region (point) (save-excursion
12961 (outline-next-heading) (point)))
12962 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12963 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12964 "[^\r\n]*\\)?"))
12965 (goto-char (match-end 0))
12966 (cond
12967 (drawer
12968 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12969 nil t)
12970 (progn
12971 (goto-char (match-end 0))
12972 (or org-log-states-order-reversed
12973 (and (re-search-forward org-property-end-re nil t)
12974 (goto-char (1- (match-beginning 0))))))
12975 (insert "\n:" drawer ":\n:END:")
12976 (beginning-of-line 0)
12977 (org-indent-line)
12978 (beginning-of-line 2)
12979 (org-indent-line)
12980 (end-of-line 0)))
12981 ((and org-log-state-notes-insert-after-drawers
12982 (save-excursion
12983 (forward-line) (looking-at org-drawer-regexp)))
12984 (forward-line)
12985 (while (looking-at org-drawer-regexp)
12986 (goto-char (match-end 0))
12987 (re-search-forward org-property-end-re (point-max) t)
12988 (forward-line))
12989 (forward-line -1)))
12990 (unless org-log-states-order-reversed
12991 (and (= (char-after) ?\n) (forward-char 1))
12992 (org-skip-over-state-notes)
12993 (skip-chars-backward " \t\n\r")))
12994 (move-marker org-log-note-marker (point))
12995 (setq org-log-note-purpose purpose
12996 org-log-note-state state
12997 org-log-note-previous-state prev-state
12998 org-log-note-how how
12999 org-log-note-extra extra
13000 org-log-note-effective-time (org-current-effective-time))
13001 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13003 (defun org-skip-over-state-notes ()
13004 "Skip past the list of State notes in an entry."
13005 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13006 (when (ignore-errors (goto-char (org-in-item-p)))
13007 (let* ((struct (org-list-struct))
13008 (prevs (org-list-prevs-alist struct)))
13009 (while (looking-at "[ \t]*- State")
13010 (goto-char (or (org-list-get-next-item (point) struct prevs)
13011 (org-list-get-item-end (point) struct)))))))
13013 (defun org-add-log-note (&optional purpose)
13014 "Pop up a window for taking a note, and add this note later at point."
13015 (remove-hook 'post-command-hook 'org-add-log-note)
13016 (setq org-log-note-window-configuration (current-window-configuration))
13017 (delete-other-windows)
13018 (move-marker org-log-note-return-to (point))
13019 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13020 (goto-char org-log-note-marker)
13021 (org-switch-to-buffer-other-window "*Org Note*")
13022 (erase-buffer)
13023 (if (memq org-log-note-how '(time state))
13024 (let (current-prefix-arg) (org-store-log-note))
13025 (let ((org-inhibit-startup t)) (org-mode))
13026 (insert (format "# Insert note for %s.
13027 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13028 (cond
13029 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13030 ((eq org-log-note-purpose 'done) "closed todo item")
13031 ((eq org-log-note-purpose 'state)
13032 (format "state change from \"%s\" to \"%s\""
13033 (or org-log-note-previous-state "")
13034 (or org-log-note-state "")))
13035 ((eq org-log-note-purpose 'reschedule)
13036 "rescheduling")
13037 ((eq org-log-note-purpose 'delschedule)
13038 "no longer scheduled")
13039 ((eq org-log-note-purpose 'redeadline)
13040 "changing deadline")
13041 ((eq org-log-note-purpose 'deldeadline)
13042 "removing deadline")
13043 ((eq org-log-note-purpose 'refile)
13044 "refiling")
13045 ((eq org-log-note-purpose 'note)
13046 "this entry")
13047 (t (error "This should not happen")))))
13048 (if org-log-note-extra (insert org-log-note-extra))
13049 (org-set-local 'org-finish-function 'org-store-log-note)
13050 (run-hooks 'org-log-buffer-setup-hook)))
13052 (defvar org-note-abort nil) ; dynamically scoped
13053 (defun org-store-log-note ()
13054 "Finish taking a log note, and insert it to where it belongs."
13055 (let ((txt (buffer-string)))
13056 (kill-buffer (current-buffer))
13057 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13058 lines ind bul)
13059 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13060 (setq txt (replace-match "" t t txt)))
13061 (if (string-match "\\s-+\\'" txt)
13062 (setq txt (replace-match "" t t txt)))
13063 (setq lines (org-split-string txt "\n"))
13064 (when (and note (string-match "\\S-" note))
13065 (setq note
13066 (org-replace-escapes
13067 note
13068 (list (cons "%u" (user-login-name))
13069 (cons "%U" user-full-name)
13070 (cons "%t" (format-time-string
13071 (org-time-stamp-format 'long 'inactive)
13072 org-log-note-effective-time))
13073 (cons "%T" (format-time-string
13074 (org-time-stamp-format 'long nil)
13075 org-log-note-effective-time))
13076 (cons "%d" (format-time-string
13077 (org-time-stamp-format nil 'inactive)
13078 org-log-note-effective-time))
13079 (cons "%D" (format-time-string
13080 (org-time-stamp-format nil nil)
13081 org-log-note-effective-time))
13082 (cons "%s" (if org-log-note-state
13083 (concat "\"" org-log-note-state "\"")
13084 ""))
13085 (cons "%S" (if org-log-note-previous-state
13086 (concat "\"" org-log-note-previous-state "\"")
13087 "\"\"")))))
13088 (if lines (setq note (concat note " \\\\")))
13089 (push note lines))
13090 (when (or current-prefix-arg org-note-abort)
13091 (when org-log-into-drawer
13092 (org-remove-empty-drawer-at
13093 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13094 org-log-note-marker))
13095 (setq lines nil))
13096 (when lines
13097 (with-current-buffer (marker-buffer org-log-note-marker)
13098 (save-excursion
13099 (goto-char org-log-note-marker)
13100 (move-marker org-log-note-marker nil)
13101 (end-of-line 1)
13102 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13103 (setq ind (save-excursion
13104 (if (ignore-errors (goto-char (org-in-item-p)))
13105 (let ((struct (org-list-struct)))
13106 (org-list-get-ind
13107 (org-list-get-top-point struct) struct))
13108 (skip-chars-backward " \r\t\n")
13109 (cond
13110 ((and (org-at-heading-p)
13111 org-adapt-indentation)
13112 (1+ (org-current-level)))
13113 ((org-at-heading-p) 0)
13114 (t (org-get-indentation))))))
13115 (setq bul (org-list-bullet-string "-"))
13116 (org-indent-line-to ind)
13117 (insert bul (pop lines))
13118 (let ((ind-body (+ (length bul) ind)))
13119 (while lines
13120 (insert "\n")
13121 (org-indent-line-to ind-body)
13122 (insert (pop lines))))
13123 (message "Note stored")
13124 (org-back-to-heading t)
13125 (org-cycle-hide-drawers 'children))))))
13126 (set-window-configuration org-log-note-window-configuration)
13127 (with-current-buffer (marker-buffer org-log-note-return-to)
13128 (goto-char org-log-note-return-to))
13129 (move-marker org-log-note-return-to nil)
13130 (and org-log-post-message (message "%s" org-log-post-message)))
13132 (defun org-remove-empty-drawer-at (drawer pos)
13133 "Remove an empty drawer DRAWER at position POS.
13134 POS may also be a marker."
13135 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13136 (save-excursion
13137 (save-restriction
13138 (widen)
13139 (goto-char pos)
13140 (if (org-in-regexp
13141 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13142 (replace-match ""))))))
13144 (defvar org-ts-type nil)
13145 (defun org-sparse-tree (&optional arg type)
13146 "Create a sparse tree, prompt for the details.
13147 This command can create sparse trees. You first need to select the type
13148 of match used to create the tree:
13150 t Show all TODO entries.
13151 T Show entries with a specific TODO keyword.
13152 m Show entries selected by a tags/property match.
13153 p Enter a property name and its value (both with completion on existing
13154 names/values) and show entries with that property.
13155 r Show entries matching a regular expression (`/' can be used as well).
13156 b Show deadlines and scheduled items before a date.
13157 a Show deadlines and scheduled items after a date.
13158 d Show deadlines due within `org-deadline-warning-days'.
13159 D Show deadlines and scheduled items between a date range."
13160 (interactive "P")
13161 (let (ans kwd value ts-type)
13162 (setq type (or type org-sparse-tree-default-date-type))
13163 (setq org-ts-type type)
13164 (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"
13165 (cond ((eq type 'all) "all timestamps")
13166 ((eq type 'scheduled) "only scheduled")
13167 ((eq type 'deadline) "only deadline")
13168 ((eq type 'active) "only active timestamps")
13169 ((eq type 'inactive) "only inactive timestamps")
13170 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13171 (t "scheduled/deadline")))
13172 (setq ans (read-char-exclusive))
13173 (cond
13174 ((equal ans ?c)
13175 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13176 ((equal ans ?d)
13177 (call-interactively 'org-check-deadlines))
13178 ((equal ans ?b)
13179 (call-interactively 'org-check-before-date))
13180 ((equal ans ?a)
13181 (call-interactively 'org-check-after-date))
13182 ((equal ans ?D)
13183 (call-interactively 'org-check-dates-range))
13184 ((equal ans ?t)
13185 (call-interactively 'org-show-todo-tree))
13186 ((equal ans ?T)
13187 (org-show-todo-tree '(4)))
13188 ((member ans '(?T ?m))
13189 (call-interactively 'org-match-sparse-tree))
13190 ((member ans '(?p ?P))
13191 (setq kwd (org-icompleting-read "Property: "
13192 (mapcar 'list (org-buffer-property-keys))))
13193 (setq value (org-icompleting-read "Value: "
13194 (mapcar 'list (org-property-values kwd))))
13195 (unless (string-match "\\`{.*}\\'" value)
13196 (setq value (concat "\"" value "\"")))
13197 (org-match-sparse-tree arg (concat kwd "=" value)))
13198 ((member ans '(?r ?R ?/))
13199 (call-interactively 'org-occur))
13200 (t (error "No such sparse tree command \"%c\"" ans)))))
13202 (defvar org-occur-highlights nil
13203 "List of overlays used for occur matches.")
13204 (make-variable-buffer-local 'org-occur-highlights)
13205 (defvar org-occur-parameters nil
13206 "Parameters of the active org-occur calls.
13207 This is a list, each call to org-occur pushes as cons cell,
13208 containing the regular expression and the callback, onto the list.
13209 The list can contain several entries if `org-occur' has been called
13210 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13211 will only contain one set of parameters. When the highlights are
13212 removed (for example with `C-c C-c', or with the next edit (depending
13213 on `org-remove-highlights-with-change'), this variable is emptied
13214 as well.")
13215 (make-variable-buffer-local 'org-occur-parameters)
13217 (defun org-occur (regexp &optional keep-previous callback)
13218 "Make a compact tree which shows all matches of REGEXP.
13219 The tree will show the lines where the regexp matches, and all higher
13220 headlines above the match. It will also show the heading after the match,
13221 to make sure editing the matching entry is easy.
13222 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13223 call to `org-occur' will be kept, to allow stacking of calls to this
13224 command.
13225 If CALLBACK is non-nil, it is a function which is called to confirm
13226 that the match should indeed be shown."
13227 (interactive "sRegexp: \nP")
13228 (when (equal regexp "")
13229 (error "Regexp cannot be empty"))
13230 (unless keep-previous
13231 (org-remove-occur-highlights nil nil t))
13232 (push (cons regexp callback) org-occur-parameters)
13233 (let ((cnt 0))
13234 (save-excursion
13235 (goto-char (point-min))
13236 (if (or (not keep-previous) ; do not want to keep
13237 (not org-occur-highlights)) ; no previous matches
13238 ;; hide everything
13239 (org-overview))
13240 (while (re-search-forward regexp nil t)
13241 (when (or (not callback)
13242 (save-match-data (funcall callback)))
13243 (setq cnt (1+ cnt))
13244 (when org-highlight-sparse-tree-matches
13245 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13246 (org-show-context 'occur-tree))))
13247 (when org-remove-highlights-with-change
13248 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13249 nil 'local))
13250 (unless org-sparse-tree-open-archived-trees
13251 (org-hide-archived-subtrees (point-min) (point-max)))
13252 (run-hooks 'org-occur-hook)
13253 (if (org-called-interactively-p 'interactive)
13254 (message "%d match(es) for regexp %s" cnt regexp))
13255 cnt))
13257 (defun org-occur-next-match (&optional n reset)
13258 "Function for `next-error-function' to find sparse tree matches.
13259 N is the number of matches to move, when negative move backwards.
13260 RESET is entirely ignored - this function always goes back to the
13261 starting point when no match is found."
13262 (let* ((limit (if (< n 0) (point-min) (point-max)))
13263 (search-func (if (< n 0)
13264 'previous-single-char-property-change
13265 'next-single-char-property-change))
13266 (n (abs n))
13267 (pos (point))
13269 (catch 'exit
13270 (while (setq p1 (funcall search-func (point) 'org-type))
13271 (when (equal p1 limit)
13272 (goto-char pos)
13273 (error "No more matches"))
13274 (when (equal (get-char-property p1 'org-type) 'org-occur)
13275 (setq n (1- n))
13276 (when (= n 0)
13277 (goto-char p1)
13278 (throw 'exit (point))))
13279 (goto-char p1))
13280 (goto-char p1)
13281 (error "No more matches"))))
13283 (defun org-show-context (&optional key)
13284 "Make sure point and context are visible.
13285 How much context is shown depends upon the variables
13286 `org-show-hierarchy-above', `org-show-following-heading',
13287 `org-show-entry-below' and `org-show-siblings'."
13288 (let ((heading-p (org-at-heading-p t))
13289 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13290 (following-p (org-get-alist-option org-show-following-heading key))
13291 (entry-p (org-get-alist-option org-show-entry-below key))
13292 (siblings-p (org-get-alist-option org-show-siblings key)))
13293 ;; Show heading or entry text
13294 (if (and heading-p (not entry-p))
13295 (org-flag-heading nil) ; only show the heading
13296 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13297 (org-show-hidden-entry))) ; show entire entry
13298 (when following-p
13299 ;; Show next sibling, or heading below text
13300 (save-excursion
13301 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13302 (org-flag-heading nil))))
13303 (when siblings-p (org-show-siblings))
13304 (when hierarchy-p
13305 ;; show all higher headings, possibly with siblings
13306 (save-excursion
13307 (while (and (condition-case nil
13308 (progn (org-up-heading-all 1) t)
13309 (error nil))
13310 (not (bobp)))
13311 (org-flag-heading nil)
13312 (when siblings-p (org-show-siblings)))))
13313 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13315 (defvar org-reveal-start-hook nil
13316 "Hook run before revealing a location.")
13318 (defun org-reveal (&optional siblings)
13319 "Show current entry, hierarchy above it, and the following headline.
13320 This can be used to show a consistent set of context around locations
13321 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13322 not t for the search context.
13324 With optional argument SIBLINGS, on each level of the hierarchy all
13325 siblings are shown. This repairs the tree structure to what it would
13326 look like when opened with hierarchical calls to `org-cycle'.
13327 With double optional argument \\[universal-argument] \\[universal-argument], \
13328 go to the parent and show the
13329 entire tree."
13330 (interactive "P")
13331 (run-hooks 'org-reveal-start-hook)
13332 (let ((org-show-hierarchy-above t)
13333 (org-show-following-heading t)
13334 (org-show-siblings (if siblings t org-show-siblings)))
13335 (org-show-context nil))
13336 (when (equal siblings '(16))
13337 (save-excursion
13338 (when (org-up-heading-safe)
13339 (org-show-subtree)
13340 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13342 (defun org-highlight-new-match (beg end)
13343 "Highlight from BEG to END and mark the highlight is an occur headline."
13344 (let ((ov (make-overlay beg end)))
13345 (overlay-put ov 'face 'secondary-selection)
13346 (overlay-put ov 'org-type 'org-occur)
13347 (push ov org-occur-highlights)))
13349 (defun org-remove-occur-highlights (&optional beg end noremove)
13350 "Remove the occur highlights from the buffer.
13351 BEG and END are ignored. If NOREMOVE is nil, remove this function
13352 from the `before-change-functions' in the current buffer."
13353 (interactive)
13354 (unless org-inhibit-highlight-removal
13355 (mapc 'delete-overlay org-occur-highlights)
13356 (setq org-occur-highlights nil)
13357 (setq org-occur-parameters nil)
13358 (unless noremove
13359 (remove-hook 'before-change-functions
13360 'org-remove-occur-highlights 'local))))
13362 ;;;; Priorities
13364 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13365 "Regular expression matching the priority indicator.")
13367 (defvar org-remove-priority-next-time nil)
13369 (defun org-priority-up ()
13370 "Increase the priority of the current item."
13371 (interactive)
13372 (org-priority 'up))
13374 (defun org-priority-down ()
13375 "Decrease the priority of the current item."
13376 (interactive)
13377 (org-priority 'down))
13379 (defun org-priority (&optional action show)
13380 "Change the priority of an item.
13381 ACTION can be `set', `up', `down', or a character."
13382 (interactive "P")
13383 (if (equal action '(4))
13384 (org-show-priority)
13385 (unless org-enable-priority-commands
13386 (error "Priority commands are disabled"))
13387 (setq action (or action 'set))
13388 (let (current new news have remove)
13389 (save-excursion
13390 (org-back-to-heading t)
13391 (if (looking-at org-priority-regexp)
13392 (setq current (string-to-char (match-string 2))
13393 have t))
13394 (cond
13395 ((eq action 'remove)
13396 (setq remove t new ?\ ))
13397 ((or (eq action 'set)
13398 (if (featurep 'xemacs) (characterp action) (integerp action)))
13399 (if (not (eq action 'set))
13400 (setq new action)
13401 (message "Priority %c-%c, SPC to remove: "
13402 org-highest-priority org-lowest-priority)
13403 (save-match-data
13404 (setq new (read-char-exclusive))))
13405 (if (and (= (upcase org-highest-priority) org-highest-priority)
13406 (= (upcase org-lowest-priority) org-lowest-priority))
13407 (setq new (upcase new)))
13408 (cond ((equal new ?\ ) (setq remove t))
13409 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13410 (error "Priority must be between `%c' and `%c'"
13411 org-highest-priority org-lowest-priority))))
13412 ((eq action 'up)
13413 (setq new (if have
13414 (1- current) ; normal cycling
13415 ;; last priority was empty
13416 (if (eq last-command this-command)
13417 org-lowest-priority ; wrap around empty to lowest
13418 ;; default
13419 (if org-priority-start-cycle-with-default
13420 org-default-priority
13421 (1- org-default-priority))))))
13422 ((eq action 'down)
13423 (setq new (if have
13424 (1+ current) ; normal cycling
13425 ;; last priority was empty
13426 (if (eq last-command this-command)
13427 org-highest-priority ; wrap around empty to highest
13428 ;; default
13429 (if org-priority-start-cycle-with-default
13430 org-default-priority
13431 (1+ org-default-priority))))))
13432 (t (error "Invalid action")))
13433 (if (or (< (upcase new) org-highest-priority)
13434 (> (upcase new) org-lowest-priority))
13435 (if (and (memq action '(up down))
13436 (not have) (not (eq last-command this-command)))
13437 ;; `new' is from default priority
13438 (error
13439 "The default can not be set, see `org-default-priority' why")
13440 ;; normal cycling: `new' is beyond highest/lowest priority
13441 ;; and is wrapped around to the empty priority
13442 (setq remove t)))
13443 (setq news (format "%c" new))
13444 (if have
13445 (if remove
13446 (replace-match "" t t nil 1)
13447 (replace-match news t t nil 2))
13448 (if remove
13449 (error "No priority cookie found in line")
13450 (let ((case-fold-search nil))
13451 (looking-at org-todo-line-regexp))
13452 (if (match-end 2)
13453 (progn
13454 (goto-char (match-end 2))
13455 (insert " [#" news "]"))
13456 (goto-char (match-beginning 3))
13457 (insert "[#" news "] "))))
13458 (org-preserve-lc (org-set-tags nil 'align)))
13459 (if remove
13460 (message "Priority removed")
13461 (message "Priority of current item set to %s" news)))))
13463 (defun org-show-priority ()
13464 "Show the priority of the current item.
13465 This priority is composed of the main priority given with the [#A] cookies,
13466 and by additional input from the age of a schedules or deadline entry."
13467 (interactive)
13468 (let ((pri (if (eq major-mode 'org-agenda-mode)
13469 (org-get-at-bol 'priority)
13470 (save-excursion
13471 (save-match-data
13472 (beginning-of-line)
13473 (and (looking-at org-heading-regexp)
13474 (org-get-priority (match-string 0))))))))
13475 (message "Priority is %d" (if pri pri -1000))))
13477 (defun org-get-priority (s)
13478 "Find priority cookie and return priority."
13479 (save-match-data
13480 (if (functionp org-get-priority-function)
13481 (funcall org-get-priority-function)
13482 (if (not (string-match org-priority-regexp s))
13483 (* 1000 (- org-lowest-priority org-default-priority))
13484 (* 1000 (- org-lowest-priority
13485 (string-to-char (match-string 2 s))))))))
13487 ;;;; Tags
13489 (defvar org-agenda-archives-mode)
13490 (defvar org-map-continue-from nil
13491 "Position from where mapping should continue.
13492 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13494 (defvar org-scanner-tags nil
13495 "The current tag list while the tags scanner is running.")
13496 (defvar org-trust-scanner-tags nil
13497 "Should `org-get-tags-at' use the tags for the scanner.
13498 This is for internal dynamical scoping only.
13499 When this is non-nil, the function `org-get-tags-at' will return the value
13500 of `org-scanner-tags' instead of building the list by itself. This
13501 can lead to large speed-ups when the tags scanner is used in a file with
13502 many entries, and when the list of tags is retrieved, for example to
13503 obtain a list of properties. Building the tags list for each entry in such
13504 a file becomes an N^2 operation - but with this variable set, it scales
13505 as N.")
13507 (defun org-scan-tags (action matcher todo-only &optional start-level)
13508 "Sca headline tags with inheritance and produce output ACTION.
13510 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13511 or `agenda' to produce an entry list for an agenda view. It can also be
13512 a Lisp form or a function that should be called at each matched headline, in
13513 this case the return value is a list of all return values from these calls.
13515 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13516 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13517 only lines with a not-done TODO keyword are included in the output.
13518 This should be the same variable that was scoped into
13519 and set by `org-make-tags-matcher' when it constructed MATCHER.
13521 START-LEVEL can be a string with asterisks, reducing the scope to
13522 headlines matching this string."
13523 (require 'org-agenda)
13524 (let* ((re (concat "^"
13525 (if start-level
13526 ;; Get the correct level to match
13527 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13528 org-outline-regexp)
13529 " *\\(\\<\\("
13530 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13531 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13532 (props (list 'face 'default
13533 'done-face 'org-agenda-done
13534 'undone-face 'default
13535 'mouse-face 'highlight
13536 'org-not-done-regexp org-not-done-regexp
13537 'org-todo-regexp org-todo-regexp
13538 'org-complex-heading-regexp org-complex-heading-regexp
13539 'help-echo
13540 (format "mouse-2 or RET jump to org file %s"
13541 (abbreviate-file-name
13542 (or (buffer-file-name (buffer-base-buffer))
13543 (buffer-name (buffer-base-buffer)))))))
13544 (case-fold-search nil)
13545 (org-map-continue-from nil)
13546 lspos tags tags-list
13547 (tags-alist (list (cons 0 org-file-tags)))
13548 (llast 0) rtn rtn1 level category i txt
13549 todo marker entry priority)
13550 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13551 (setq action (list 'lambda nil action)))
13552 (save-excursion
13553 (goto-char (point-min))
13554 (when (eq action 'sparse-tree)
13555 (org-overview)
13556 (org-remove-occur-highlights))
13557 (while (re-search-forward re nil t)
13558 (setq org-map-continue-from nil)
13559 (catch :skip
13560 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13561 tags (if (match-end 4) (org-match-string-no-properties 4)))
13562 (goto-char (setq lspos (match-beginning 0)))
13563 (setq level (org-reduced-level (org-outline-level))
13564 category (org-get-category))
13565 (setq i llast llast level)
13566 ;; remove tag lists from same and sublevels
13567 (while (>= i level)
13568 (when (setq entry (assoc i tags-alist))
13569 (setq tags-alist (delete entry tags-alist)))
13570 (setq i (1- i)))
13571 ;; add the next tags
13572 (when tags
13573 (setq tags (org-split-string tags ":")
13574 tags-alist
13575 (cons (cons level tags) tags-alist)))
13576 ;; compile tags for current headline
13577 (setq tags-list
13578 (if org-use-tag-inheritance
13579 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13580 tags)
13581 org-scanner-tags tags-list)
13582 (when org-use-tag-inheritance
13583 (setcdr (car tags-alist)
13584 (mapcar (lambda (x)
13585 (setq x (copy-sequence x))
13586 (org-add-prop-inherited x))
13587 (cdar tags-alist))))
13588 (when (and tags org-use-tag-inheritance
13589 (or (not (eq t org-use-tag-inheritance))
13590 org-tags-exclude-from-inheritance))
13591 ;; selective inheritance, remove uninherited ones
13592 (setcdr (car tags-alist)
13593 (org-remove-uninherited-tags (cdar tags-alist))))
13594 (when (and
13596 ;; eval matcher only when the todo condition is OK
13597 (and (or (not todo-only) (member todo org-not-done-keywords))
13598 (let ((case-fold-search t) (org-trust-scanner-tags t))
13599 (eval matcher)))
13601 ;; Call the skipper, but return t if it does not skip,
13602 ;; so that the `and' form continues evaluating
13603 (progn
13604 (unless (eq action 'sparse-tree) (org-agenda-skip))
13607 ;; Check if timestamps are deselecting this entry
13608 (or (not todo-only)
13609 (and (member todo org-not-done-keywords)
13610 (or (not org-agenda-tags-todo-honor-ignore-options)
13611 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13613 ;; select this headline
13614 (cond
13615 ((eq action 'sparse-tree)
13616 (and org-highlight-sparse-tree-matches
13617 (org-get-heading) (match-end 0)
13618 (org-highlight-new-match
13619 (match-beginning 1) (match-end 1)))
13620 (org-show-context 'tags-tree))
13621 ((eq action 'agenda)
13622 (setq txt (org-agenda-format-item
13624 (concat
13625 (if (eq org-tags-match-list-sublevels 'indented)
13626 (make-string (1- level) ?.) "")
13627 (org-get-heading))
13628 level category
13629 tags-list)
13630 priority (org-get-priority txt))
13631 (goto-char lspos)
13632 (setq marker (org-agenda-new-marker))
13633 (org-add-props txt props
13634 'org-marker marker 'org-hd-marker marker 'org-category category
13635 'todo-state todo
13636 'priority priority 'type "tagsmatch")
13637 (push txt rtn))
13638 ((functionp action)
13639 (setq org-map-continue-from nil)
13640 (save-excursion
13641 (setq rtn1 (funcall action))
13642 (push rtn1 rtn)))
13643 (t (error "Invalid action")))
13645 ;; if we are to skip sublevels, jump to end of subtree
13646 (unless org-tags-match-list-sublevels
13647 (org-end-of-subtree t)
13648 (backward-char 1))))
13649 ;; Get the correct position from where to continue
13650 (if org-map-continue-from
13651 (goto-char org-map-continue-from)
13652 (and (= (point) lspos) (end-of-line 1)))))
13653 (when (and (eq action 'sparse-tree)
13654 (not org-sparse-tree-open-archived-trees))
13655 (org-hide-archived-subtrees (point-min) (point-max)))
13656 (nreverse rtn)))
13658 (defun org-remove-uninherited-tags (tags)
13659 "Remove all tags that are not inherited from the list TAGS."
13660 (cond
13661 ((eq org-use-tag-inheritance t)
13662 (if org-tags-exclude-from-inheritance
13663 (org-delete-all org-tags-exclude-from-inheritance tags)
13664 tags))
13665 ((not org-use-tag-inheritance) nil)
13666 ((stringp org-use-tag-inheritance)
13667 (delq nil (mapcar
13668 (lambda (x)
13669 (if (and (string-match org-use-tag-inheritance x)
13670 (not (member x org-tags-exclude-from-inheritance)))
13671 x nil))
13672 tags)))
13673 ((listp org-use-tag-inheritance)
13674 (delq nil (mapcar
13675 (lambda (x)
13676 (if (member x org-use-tag-inheritance) x nil))
13677 tags)))))
13679 (defun org-match-sparse-tree (&optional todo-only match)
13680 "Create a sparse tree according to tags string MATCH.
13681 MATCH can contain positive and negative selection of tags, like
13682 \"+WORK+URGENT-WITHBOSS\".
13683 If optional argument TODO-ONLY is non-nil, only select lines that are
13684 also TODO lines."
13685 (interactive "P")
13686 (org-agenda-prepare-buffers (list (current-buffer)))
13687 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13689 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13691 (defvar org-cached-props nil)
13692 (defun org-cached-entry-get (pom property)
13693 (if (or (eq t org-use-property-inheritance)
13694 (and (stringp org-use-property-inheritance)
13695 (string-match org-use-property-inheritance property))
13696 (and (listp org-use-property-inheritance)
13697 (member property org-use-property-inheritance)))
13698 ;; Caching is not possible, check it directly
13699 (org-entry-get pom property 'inherit)
13700 ;; Get all properties, so that we can do complicated checks easily
13701 (cdr (assoc property (or org-cached-props
13702 (setq org-cached-props
13703 (org-entry-properties pom)))))))
13705 (defun org-global-tags-completion-table (&optional files)
13706 "Return the list of all tags in all agenda buffer/files.
13707 Optional FILES argument is a list of files which can be used
13708 instead of the agenda files."
13709 (save-excursion
13710 (org-uniquify
13711 (delq nil
13712 (apply 'append
13713 (mapcar
13714 (lambda (file)
13715 (set-buffer (find-file-noselect file))
13716 (append (org-get-buffer-tags)
13717 (mapcar (lambda (x) (if (stringp (car-safe x))
13718 (list (car-safe x)) nil))
13719 org-tag-alist)))
13720 (if (and files (car files))
13721 files
13722 (org-agenda-files))))))))
13724 (defun org-make-tags-matcher (match)
13725 "Create the TAGS/TODO matcher form for the selection string MATCH.
13727 The variable `todo-only' is scoped dynamically into this function.
13728 It will be set to t if the matcher restricts matching to TODO entries,
13729 otherwise will not be touched.
13731 Returns a cons of the selection string MATCH and the constructed
13732 lisp form implementing the matcher. The matcher is to be evaluated
13733 at an Org entry, with point on the headline, and returns t if the
13734 entry matches the selection string MATCH. The returned lisp form
13735 references two variables with information about the entry, which
13736 must be bound around the form's evaluation: todo, the TODO keyword
13737 at the entry (or nil of none); and tags-list, the list of all tags
13738 at the entry including inherited ones. Additionally, the category
13739 of the entry (if any) must be specified as the text property
13740 'org-category on the headline.
13742 See also `org-scan-tags'.
13744 (declare (special todo-only))
13745 (unless (boundp 'todo-only)
13746 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13747 (unless match
13748 ;; Get a new match request, with completion
13749 (let ((org-last-tags-completion-table
13750 (org-global-tags-completion-table)))
13751 (setq match (org-completing-read-no-i
13752 "Match: " 'org-tags-completion-function nil nil nil
13753 'org-tags-history))))
13755 ;; Parse the string and create a lisp form
13756 (let ((match0 match)
13757 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13758 minus tag mm
13759 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13760 orterms term orlist re-p str-p level-p level-op time-p
13761 prop-p pn pv po gv rest)
13762 (if (string-match "/+" match)
13763 ;; match contains also a todo-matching request
13764 (progn
13765 (setq tagsmatch (substring match 0 (match-beginning 0))
13766 todomatch (substring match (match-end 0)))
13767 (if (string-match "^!" todomatch)
13768 (setq todo-only t todomatch (substring todomatch 1)))
13769 (if (string-match "^\\s-*$" todomatch)
13770 (setq todomatch nil)))
13771 ;; only matching tags
13772 (setq tagsmatch match todomatch nil))
13774 ;; Make the tags matcher
13775 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13776 (setq tagsmatcher t)
13777 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13778 (while (setq term (pop orterms))
13779 (while (and (equal (substring term -1) "\\") orterms)
13780 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13781 (while (string-match re term)
13782 (setq rest (substring term (match-end 0))
13783 minus (and (match-end 1)
13784 (equal (match-string 1 term) "-"))
13785 tag (save-match-data (replace-regexp-in-string
13786 "\\\\-" "-"
13787 (match-string 2 term)))
13788 re-p (equal (string-to-char tag) ?{)
13789 level-p (match-end 4)
13790 prop-p (match-end 5)
13791 mm (cond
13792 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13793 (level-p
13794 (setq level-op (org-op-to-function (match-string 3 term)))
13795 `(,level-op level ,(string-to-number
13796 (match-string 4 term))))
13797 (prop-p
13798 (setq pn (match-string 5 term)
13799 po (match-string 6 term)
13800 pv (match-string 7 term)
13801 re-p (equal (string-to-char pv) ?{)
13802 str-p (equal (string-to-char pv) ?\")
13803 time-p (save-match-data
13804 (string-match "^\"[[<].*[]>]\"$" pv))
13805 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13806 (if time-p (setq pv (org-matcher-time pv)))
13807 (setq po (org-op-to-function po (if time-p 'time str-p)))
13808 (cond
13809 ((equal pn "CATEGORY")
13810 (setq gv '(get-text-property (point) 'org-category)))
13811 ((equal pn "TODO")
13812 (setq gv 'todo))
13814 (setq gv `(org-cached-entry-get nil ,pn))))
13815 (if re-p
13816 (if (eq po 'org<>)
13817 `(not (string-match ,pv (or ,gv "")))
13818 `(string-match ,pv (or ,gv "")))
13819 (if str-p
13820 `(,po (or ,gv "") ,pv)
13821 `(,po (string-to-number (or ,gv ""))
13822 ,(string-to-number pv) ))))
13823 (t `(member ,tag tags-list)))
13824 mm (if minus (list 'not mm) mm)
13825 term rest)
13826 (push mm tagsmatcher))
13827 (push (if (> (length tagsmatcher) 1)
13828 (cons 'and tagsmatcher)
13829 (car tagsmatcher))
13830 orlist)
13831 (setq tagsmatcher nil))
13832 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13833 (setq tagsmatcher
13834 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13835 ;; Make the todo matcher
13836 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13837 (setq todomatcher t)
13838 (setq orterms (org-split-string todomatch "|") orlist nil)
13839 (while (setq term (pop orterms))
13840 (while (string-match re term)
13841 (setq minus (and (match-end 1)
13842 (equal (match-string 1 term) "-"))
13843 kwd (match-string 2 term)
13844 re-p (equal (string-to-char kwd) ?{)
13845 term (substring term (match-end 0))
13846 mm (if re-p
13847 `(string-match ,(substring kwd 1 -1) todo)
13848 (list 'equal 'todo kwd))
13849 mm (if minus (list 'not mm) mm))
13850 (push mm todomatcher))
13851 (push (if (> (length todomatcher) 1)
13852 (cons 'and todomatcher)
13853 (car todomatcher))
13854 orlist)
13855 (setq todomatcher nil))
13856 (setq todomatcher (if (> (length orlist) 1)
13857 (cons 'or orlist) (car orlist))))
13859 ;; Return the string and lisp forms of the matcher
13860 (setq matcher (if todomatcher
13861 (list 'and tagsmatcher todomatcher)
13862 tagsmatcher))
13863 (when todo-only
13864 (setq matcher (list 'and '(member todo org-not-done-keywords)
13865 matcher)))
13866 (cons match0 matcher)))
13868 (defun org-op-to-function (op &optional stringp)
13869 "Turn an operator into the appropriate function."
13870 (setq op
13871 (cond
13872 ((equal op "<" ) '(< string< org-time<))
13873 ((equal op ">" ) '(> org-string> org-time>))
13874 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13875 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13876 ((member op '("=" "==")) '(= string= org-time=))
13877 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13878 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13880 (defun org<> (a b) (not (= a b)))
13881 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13882 (defun org-string>= (a b) (not (string< a b)))
13883 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13884 (defun org-string<> (a b) (not (string= a b)))
13885 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13886 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13887 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13888 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13889 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13890 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13891 (defun org-2ft (s)
13892 "Convert S to a floating point time.
13893 If S is already a number, just return it. If it is a string, parse
13894 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13895 (cond
13896 ((numberp s) s)
13897 ((stringp s)
13898 (condition-case nil
13899 (float-time (apply 'encode-time (org-parse-time-string s)))
13900 (error 0.)))
13901 (t 0.)))
13903 (defun org-time-today ()
13904 "Time in seconds today at 0:00.
13905 Returns the float number of seconds since the beginning of the
13906 epoch to the beginning of today (00:00)."
13907 (float-time (apply 'encode-time
13908 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13910 (defun org-matcher-time (s)
13911 "Interpret a time comparison value."
13912 (save-match-data
13913 (cond
13914 ((string= s "<now>") (float-time))
13915 ((string= s "<today>") (org-time-today))
13916 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13917 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13918 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13919 (+ (org-time-today)
13920 (* (string-to-number (match-string 1 s))
13921 (cdr (assoc (match-string 2 s)
13922 '(("d" . 86400.0) ("w" . 604800.0)
13923 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13924 (t (org-2ft s)))))
13926 (defun org-match-any-p (re list)
13927 "Does re match any element of list?"
13928 (setq list (mapcar (lambda (x) (string-match re x)) list))
13929 (delq nil list))
13931 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13932 (defvar org-tags-overlay (make-overlay 1 1))
13933 (org-detach-overlay org-tags-overlay)
13935 (defun org-get-local-tags-at (&optional pos)
13936 "Get a list of tags defined in the current headline."
13937 (org-get-tags-at pos 'local))
13939 (defun org-get-local-tags ()
13940 "Get a list of tags defined in the current headline."
13941 (org-get-tags-at nil 'local))
13943 (defun org-get-tags-at (&optional pos local)
13944 "Get a list of all headline tags applicable at POS.
13945 POS defaults to point. If tags are inherited, the list contains
13946 the targets in the same sequence as the headlines appear, i.e.
13947 the tags of the current headline come last.
13948 When LOCAL is non-nil, only return tags from the current headline,
13949 ignore inherited ones."
13950 (interactive)
13951 (if (and org-trust-scanner-tags
13952 (or (not pos) (equal pos (point)))
13953 (not local))
13954 org-scanner-tags
13955 (let (tags ltags lastpos parent)
13956 (save-excursion
13957 (save-restriction
13958 (widen)
13959 (goto-char (or pos (point)))
13960 (save-match-data
13961 (catch 'done
13962 (condition-case nil
13963 (progn
13964 (org-back-to-heading t)
13965 (while (not (equal lastpos (point)))
13966 (setq lastpos (point))
13967 (when (looking-at
13968 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13969 (setq ltags (org-split-string
13970 (org-match-string-no-properties 1) ":"))
13971 (when parent
13972 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13973 (setq tags (append
13974 (if parent
13975 (org-remove-uninherited-tags ltags)
13976 ltags)
13977 tags)))
13978 (or org-use-tag-inheritance (throw 'done t))
13979 (if local (throw 'done t))
13980 (or (org-up-heading-safe) (error nil))
13981 (setq parent t)))
13982 (error nil)))))
13983 (if local
13984 tags
13985 (reverse (delete-dups
13986 (reverse (append
13987 (org-remove-uninherited-tags
13988 org-file-tags) tags)))))))))
13990 (defun org-add-prop-inherited (s)
13991 (add-text-properties 0 (length s) '(inherited t) s)
13994 (defun org-toggle-tag (tag &optional onoff)
13995 "Toggle the tag TAG for the current line.
13996 If ONOFF is `on' or `off', don't toggle but set to this state."
13997 (let (res current)
13998 (save-excursion
13999 (org-back-to-heading t)
14000 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14001 (point-at-eol) t)
14002 (progn
14003 (setq current (match-string 1))
14004 (replace-match ""))
14005 (setq current ""))
14006 (setq current (nreverse (org-split-string current ":")))
14007 (cond
14008 ((eq onoff 'on)
14009 (setq res t)
14010 (or (member tag current) (push tag current)))
14011 ((eq onoff 'off)
14012 (or (not (member tag current)) (setq current (delete tag current))))
14013 (t (if (member tag current)
14014 (setq current (delete tag current))
14015 (setq res t)
14016 (push tag current))))
14017 (end-of-line 1)
14018 (if current
14019 (progn
14020 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14021 (org-set-tags nil t))
14022 (delete-horizontal-space))
14023 (run-hooks 'org-after-tags-change-hook))
14024 res))
14026 (defun org-align-tags-here (to-col)
14027 ;; Assumes that this is a headline
14028 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14029 (beginning-of-line 1)
14030 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14031 (< pos (match-beginning 2)))
14032 (progn
14033 (setq tags-l (- (match-end 2) (match-beginning 2)))
14034 (goto-char (match-beginning 1))
14035 (insert " ")
14036 (delete-region (point) (1+ (match-beginning 2)))
14037 (setq ncol (max (current-column)
14038 (1+ col)
14039 (if (> to-col 0)
14040 to-col
14041 (- (abs to-col) tags-l))))
14042 (setq p (point))
14043 (insert (make-string (- ncol (current-column)) ?\ ))
14044 (setq ncol (current-column))
14045 (when indent-tabs-mode (tabify p (point-at-eol)))
14046 (org-move-to-column (min ncol col) t))
14047 (goto-char pos))))
14049 (defun org-set-tags-command (&optional arg just-align)
14050 "Call the set-tags command for the current entry."
14051 (interactive "P")
14052 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14053 (org-set-tags arg just-align)
14054 (save-excursion
14055 (unless (and (org-region-active-p)
14056 org-loop-over-headlines-in-active-region)
14057 (org-back-to-heading t))
14058 (org-set-tags arg just-align))))
14060 (defun org-set-tags-to (data)
14061 "Set the tags of the current entry to DATA, replacing the current tags.
14062 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14063 If DATA is nil or the empty string, any tags will be removed."
14064 (interactive "sTags: ")
14065 (setq data
14066 (cond
14067 ((eq data nil) "")
14068 ((equal data "") "")
14069 ((stringp data)
14070 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14071 ":"))
14072 ((listp data)
14073 (concat ":" (mapconcat 'identity data ":") ":"))))
14074 (when data
14075 (save-excursion
14076 (org-back-to-heading t)
14077 (when (looking-at org-complex-heading-regexp)
14078 (if (match-end 5)
14079 (progn
14080 (goto-char (match-beginning 5))
14081 (insert data)
14082 (delete-region (point) (point-at-eol))
14083 (org-set-tags nil 'align))
14084 (goto-char (point-at-eol))
14085 (insert " " data)
14086 (org-set-tags nil 'align)))
14087 (beginning-of-line 1)
14088 (if (looking-at ".*?\\([ \t]+\\)$")
14089 (delete-region (match-beginning 1) (match-end 1))))))
14091 (defun org-align-all-tags ()
14092 "Align the tags i all headings."
14093 (interactive)
14094 (save-excursion
14095 (or (ignore-errors (org-back-to-heading t))
14096 (outline-next-heading))
14097 (if (org-at-heading-p)
14098 (org-set-tags t)
14099 (message "No headings"))))
14101 (defvar org-indent-indentation-per-level)
14102 (defun org-set-tags (&optional arg just-align)
14103 "Set the tags for the current headline.
14104 With prefix ARG, realign all tags in headings in the current buffer."
14105 (interactive "P")
14106 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14107 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14108 'region-start-level 'region))
14109 org-loop-over-headlines-in-active-region)
14110 (org-map-entries
14111 ;; We don't use ARG and JUST-ALIGN here these args are not
14112 ;; useful when looping over headlines
14113 `(org-set-tags)
14114 org-loop-over-headlines-in-active-region
14115 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14116 (let* ((re org-outline-regexp-bol)
14117 (current (unless arg (org-get-tags-string)))
14118 (col (current-column))
14119 (org-setting-tags t)
14120 table current-tags inherited-tags ; computed below when needed
14121 tags p0 c0 c1 rpl di tc level)
14122 (if arg
14123 (save-excursion
14124 (goto-char (point-min))
14125 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14126 (while (re-search-forward re nil t)
14127 (org-set-tags nil t)
14128 (end-of-line 1)))
14129 (message "All tags realigned to column %d" org-tags-column))
14130 (if just-align
14131 (setq tags current)
14132 ;; Get a new set of tags from the user
14133 (save-excursion
14134 (setq table (append org-tag-persistent-alist
14135 (or org-tag-alist (org-get-buffer-tags))
14136 (and
14137 org-complete-tags-always-offer-all-agenda-tags
14138 (org-global-tags-completion-table
14139 (org-agenda-files))))
14140 org-last-tags-completion-table table
14141 current-tags (org-split-string current ":")
14142 inherited-tags (nreverse
14143 (nthcdr (length current-tags)
14144 (nreverse (org-get-tags-at))))
14145 tags
14146 (if (or (eq t org-use-fast-tag-selection)
14147 (and org-use-fast-tag-selection
14148 (delq nil (mapcar 'cdr table))))
14149 (org-fast-tag-selection
14150 current-tags inherited-tags table
14151 (if org-fast-tag-selection-include-todo
14152 org-todo-key-alist))
14153 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14154 (org-trim
14155 (org-icompleting-read "Tags: "
14156 'org-tags-completion-function
14157 nil nil current 'org-tags-history))))))
14158 (while (string-match "[-+&]+" tags)
14159 ;; No boolean logic, just a list
14160 (setq tags (replace-match ":" t t tags))))
14162 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14164 (if org-tags-sort-function
14165 (setq tags (mapconcat 'identity
14166 (sort (org-split-string
14167 tags (org-re "[^[:alnum:]_@#%]+"))
14168 org-tags-sort-function) ":")))
14170 (if (string-match "\\`[\t ]*\\'" tags)
14171 (setq tags "")
14172 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14173 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14175 ;; Insert new tags at the correct column
14176 (beginning-of-line 1)
14177 (setq level (or (and (looking-at org-outline-regexp)
14178 (- (match-end 0) (point) 1))
14180 (cond
14181 ((and (equal current "") (equal tags "")))
14182 ((re-search-forward
14183 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14184 (point-at-eol) t)
14185 (if (equal tags "")
14186 (setq rpl "")
14187 (goto-char (match-beginning 0))
14188 (setq c0 (current-column)
14189 ;; compute offset for the case of org-indent-mode active
14190 di (if org-indent-mode
14191 (* (1- org-indent-indentation-per-level) (1- level))
14193 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14194 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14195 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14196 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14197 (replace-match rpl t t)
14198 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14199 tags)
14200 (t (error "Tags alignment failed")))
14201 (org-move-to-column col)
14202 (unless just-align
14203 (run-hooks 'org-after-tags-change-hook))))))
14205 (defun org-change-tag-in-region (beg end tag off)
14206 "Add or remove TAG for each entry in the region.
14207 This works in the agenda, and also in an org-mode buffer."
14208 (interactive
14209 (list (region-beginning) (region-end)
14210 (let ((org-last-tags-completion-table
14211 (if (derived-mode-p 'org-mode)
14212 (org-get-buffer-tags)
14213 (org-global-tags-completion-table))))
14214 (org-icompleting-read
14215 "Tag: " 'org-tags-completion-function nil nil nil
14216 'org-tags-history))
14217 (progn
14218 (message "[s]et or [r]emove? ")
14219 (equal (read-char-exclusive) ?r))))
14220 (if (fboundp 'deactivate-mark) (deactivate-mark))
14221 (let ((agendap (equal major-mode 'org-agenda-mode))
14222 l1 l2 m buf pos newhead (cnt 0))
14223 (goto-char end)
14224 (setq l2 (1- (org-current-line)))
14225 (goto-char beg)
14226 (setq l1 (org-current-line))
14227 (loop for l from l1 to l2 do
14228 (org-goto-line l)
14229 (setq m (get-text-property (point) 'org-hd-marker))
14230 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14231 (and agendap m))
14232 (setq buf (if agendap (marker-buffer m) (current-buffer))
14233 pos (if agendap m (point)))
14234 (with-current-buffer buf
14235 (save-excursion
14236 (save-restriction
14237 (goto-char pos)
14238 (setq cnt (1+ cnt))
14239 (org-toggle-tag tag (if off 'off 'on))
14240 (setq newhead (org-get-heading)))))
14241 (and agendap (org-agenda-change-all-lines newhead m))))
14242 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14244 (defun org-tags-completion-function (string predicate &optional flag)
14245 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14246 (confirm (lambda (x) (stringp (car x)))))
14247 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14248 (setq s1 (match-string 1 string)
14249 s2 (match-string 2 string))
14250 (setq s1 "" s2 string))
14251 (cond
14252 ((eq flag nil)
14253 ;; try completion
14254 (setq rtn (try-completion s2 ctable confirm))
14255 (if (stringp rtn)
14256 (setq rtn
14257 (concat s1 s2 (substring rtn (length s2))
14258 (if (and org-add-colon-after-tag-completion
14259 (assoc rtn ctable))
14260 ":" ""))))
14261 rtn)
14262 ((eq flag t)
14263 ;; all-completions
14264 (all-completions s2 ctable confirm)
14266 ((eq flag 'lambda)
14267 ;; exact match?
14268 (assoc s2 ctable)))
14271 (defun org-fast-tag-insert (kwd tags face &optional end)
14272 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14273 (insert (format "%-12s" (concat kwd ":"))
14274 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14275 (or end "")))
14277 (defun org-fast-tag-show-exit (flag)
14278 (save-excursion
14279 (org-goto-line 3)
14280 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14281 (replace-match ""))
14282 (when flag
14283 (end-of-line 1)
14284 (org-move-to-column (- (window-width) 19) t)
14285 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14287 (defun org-set-current-tags-overlay (current prefix)
14288 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14289 (if (featurep 'xemacs)
14290 (org-overlay-display org-tags-overlay (concat prefix s)
14291 'secondary-selection)
14292 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14293 (org-overlay-display org-tags-overlay (concat prefix s)))))
14295 (defvar org-last-tag-selection-key nil)
14296 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14297 "Fast tag selection with single keys.
14298 CURRENT is the current list of tags in the headline, INHERITED is the
14299 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14300 possibly with grouping information. TODO-TABLE is a similar table with
14301 TODO keywords, should these have keys assigned to them.
14302 If the keys are nil, a-z are automatically assigned.
14303 Returns the new tags string, or nil to not change the current settings."
14304 (let* ((fulltable (append table todo-table))
14305 (maxlen (apply 'max (mapcar
14306 (lambda (x)
14307 (if (stringp (car x)) (string-width (car x)) 0))
14308 fulltable)))
14309 (buf (current-buffer))
14310 (expert (eq org-fast-tag-selection-single-key 'expert))
14311 (buffer-tags nil)
14312 (fwidth (+ maxlen 3 1 3))
14313 (ncol (/ (- (window-width) 4) fwidth))
14314 (i-face 'org-done)
14315 (c-face 'org-todo)
14316 tg cnt e c char c1 c2 ntable tbl rtn
14317 ov-start ov-end ov-prefix
14318 (exit-after-next org-fast-tag-selection-single-key)
14319 (done-keywords org-done-keywords)
14320 groups ingroup)
14321 (save-excursion
14322 (beginning-of-line 1)
14323 (if (looking-at
14324 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14325 (setq ov-start (match-beginning 1)
14326 ov-end (match-end 1)
14327 ov-prefix "")
14328 (setq ov-start (1- (point-at-eol))
14329 ov-end (1+ ov-start))
14330 (skip-chars-forward "^\n\r")
14331 (setq ov-prefix
14332 (concat
14333 (buffer-substring (1- (point)) (point))
14334 (if (> (current-column) org-tags-column)
14336 (make-string (- org-tags-column (current-column)) ?\ ))))))
14337 (move-overlay org-tags-overlay ov-start ov-end)
14338 (save-window-excursion
14339 (if expert
14340 (set-buffer (get-buffer-create " *Org tags*"))
14341 (delete-other-windows)
14342 (split-window-vertically)
14343 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14344 (erase-buffer)
14345 (org-set-local 'org-done-keywords done-keywords)
14346 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14347 (org-fast-tag-insert "Current" current c-face "\n\n")
14348 (org-fast-tag-show-exit exit-after-next)
14349 (org-set-current-tags-overlay current ov-prefix)
14350 (setq tbl fulltable char ?a cnt 0)
14351 (while (setq e (pop tbl))
14352 (cond
14353 ((equal (car e) :startgroup)
14354 (push '() groups) (setq ingroup t)
14355 (when (not (= cnt 0))
14356 (setq cnt 0)
14357 (insert "\n"))
14358 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14359 ((equal (car e) :endgroup)
14360 (setq ingroup nil cnt 0)
14361 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14362 ((equal e '(:newline))
14363 (when (not (= cnt 0))
14364 (setq cnt 0)
14365 (insert "\n")
14366 (setq e (car tbl))
14367 (while (equal (car tbl) '(:newline))
14368 (insert "\n")
14369 (setq tbl (cdr tbl)))))
14371 (setq tg (copy-sequence (car e)) c2 nil)
14372 (if (cdr e)
14373 (setq c (cdr e))
14374 ;; automatically assign a character.
14375 (setq c1 (string-to-char
14376 (downcase (substring
14377 tg (if (= (string-to-char tg) ?@) 1 0)))))
14378 (if (or (rassoc c1 ntable) (rassoc c1 table))
14379 (while (or (rassoc char ntable) (rassoc char table))
14380 (setq char (1+ char)))
14381 (setq c2 c1))
14382 (setq c (or c2 char)))
14383 (if ingroup (push tg (car groups)))
14384 (setq tg (org-add-props tg nil 'face
14385 (cond
14386 ((not (assoc tg table))
14387 (org-get-todo-face tg))
14388 ((member tg current) c-face)
14389 ((member tg inherited) i-face))))
14390 (if (and (= cnt 0) (not ingroup)) (insert " "))
14391 (insert "[" c "] " tg (make-string
14392 (- fwidth 4 (length tg)) ?\ ))
14393 (push (cons tg c) ntable)
14394 (when (= (setq cnt (1+ cnt)) ncol)
14395 (insert "\n")
14396 (if ingroup (insert " "))
14397 (setq cnt 0)))))
14398 (setq ntable (nreverse ntable))
14399 (insert "\n")
14400 (goto-char (point-min))
14401 (if (not expert) (org-fit-window-to-buffer))
14402 (setq rtn
14403 (catch 'exit
14404 (while t
14405 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14406 (if (not groups) "no " "")
14407 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14408 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14409 (setq org-last-tag-selection-key c)
14410 (cond
14411 ((= c ?\r) (throw 'exit t))
14412 ((= c ?!)
14413 (setq groups (not groups))
14414 (goto-char (point-min))
14415 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14416 ((= c ?\C-c)
14417 (if (not expert)
14418 (org-fast-tag-show-exit
14419 (setq exit-after-next (not exit-after-next)))
14420 (setq expert nil)
14421 (delete-other-windows)
14422 (set-window-buffer (split-window-vertically) " *Org tags*")
14423 (org-switch-to-buffer-other-window " *Org tags*")
14424 (org-fit-window-to-buffer)))
14425 ((or (= c ?\C-g)
14426 (and (= c ?q) (not (rassoc c ntable))))
14427 (org-detach-overlay org-tags-overlay)
14428 (setq quit-flag t))
14429 ((= c ?\ )
14430 (setq current nil)
14431 (if exit-after-next (setq exit-after-next 'now)))
14432 ((= c ?\t)
14433 (condition-case nil
14434 (setq tg (org-icompleting-read
14435 "Tag: "
14436 (or buffer-tags
14437 (with-current-buffer buf
14438 (org-get-buffer-tags)))))
14439 (quit (setq tg "")))
14440 (when (string-match "\\S-" tg)
14441 (add-to-list 'buffer-tags (list tg))
14442 (if (member tg current)
14443 (setq current (delete tg current))
14444 (push tg current)))
14445 (if exit-after-next (setq exit-after-next 'now)))
14446 ((setq e (rassoc c todo-table) tg (car e))
14447 (with-current-buffer buf
14448 (save-excursion (org-todo tg)))
14449 (if exit-after-next (setq exit-after-next 'now)))
14450 ((setq e (rassoc c ntable) tg (car e))
14451 (if (member tg current)
14452 (setq current (delete tg current))
14453 (loop for g in groups do
14454 (if (member tg g)
14455 (mapc (lambda (x)
14456 (setq current (delete x current)))
14457 g)))
14458 (push tg current))
14459 (if exit-after-next (setq exit-after-next 'now))))
14461 ;; Create a sorted list
14462 (setq current
14463 (sort current
14464 (lambda (a b)
14465 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14466 (if (eq exit-after-next 'now) (throw 'exit t))
14467 (goto-char (point-min))
14468 (beginning-of-line 2)
14469 (delete-region (point) (point-at-eol))
14470 (org-fast-tag-insert "Current" current c-face)
14471 (org-set-current-tags-overlay current ov-prefix)
14472 (while (re-search-forward
14473 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14474 (setq tg (match-string 1))
14475 (add-text-properties
14476 (match-beginning 1) (match-end 1)
14477 (list 'face
14478 (cond
14479 ((member tg current) c-face)
14480 ((member tg inherited) i-face)
14481 (t (get-text-property (match-beginning 1) 'face))))))
14482 (goto-char (point-min)))))
14483 (org-detach-overlay org-tags-overlay)
14484 (if rtn
14485 (mapconcat 'identity current ":")
14486 nil))))
14488 (defun org-get-tags-string ()
14489 "Get the TAGS string in the current headline."
14490 (unless (org-at-heading-p t)
14491 (error "Not on a heading"))
14492 (save-excursion
14493 (beginning-of-line 1)
14494 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14495 (org-match-string-no-properties 1)
14496 "")))
14498 (defun org-get-tags ()
14499 "Get the list of tags specified in the current headline."
14500 (org-split-string (org-get-tags-string) ":"))
14502 (defun org-get-buffer-tags ()
14503 "Get a table of all tags used in the buffer, for completion."
14504 (let (tags)
14505 (save-excursion
14506 (goto-char (point-min))
14507 (while (re-search-forward
14508 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14509 (when (equal (char-after (point-at-bol 0)) ?*)
14510 (mapc (lambda (x) (add-to-list 'tags x))
14511 (org-split-string (org-match-string-no-properties 1) ":")))))
14512 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14513 (mapcar 'list tags)))
14515 ;;;; The mapping API
14517 (defun org-map-entries (func &optional match scope &rest skip)
14518 "Call FUNC at each headline selected by MATCH in SCOPE.
14520 FUNC is a function or a lisp form. The function will be called without
14521 arguments, with the cursor positioned at the beginning of the headline.
14522 The return values of all calls to the function will be collected and
14523 returned as a list.
14525 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14526 does not need to preserve point. After evaluation, the cursor will be
14527 moved to the end of the line (presumably of the headline of the
14528 processed entry) and search continues from there. Under some
14529 circumstances, this may not produce the wanted results. For example,
14530 if you have removed (e.g. archived) the current (sub)tree it could
14531 mean that the next entry will be skipped entirely. In such cases, you
14532 can specify the position from where search should continue by making
14533 FUNC set the variable `org-map-continue-from' to the desired buffer
14534 position.
14536 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14537 Only headlines that are matched by this query will be considered during
14538 the iteration. When MATCH is nil or t, all headlines will be
14539 visited by the iteration.
14541 SCOPE determines the scope of this command. It can be any of:
14543 nil The current buffer, respecting the restriction if any
14544 tree The subtree started with the entry at point
14545 region The entries within the active region, if any
14546 region-start-level
14547 The entries within the active region, but only those at
14548 the same level than the first one.
14549 file The current buffer, without restriction
14550 file-with-archives
14551 The current buffer, and any archives associated with it
14552 agenda All agenda files
14553 agenda-with-archives
14554 All agenda files with any archive files associated with them
14555 \(file1 file2 ...)
14556 If this is a list, all files in the list will be scanned
14558 The remaining args are treated as settings for the skipping facilities of
14559 the scanner. The following items can be given here:
14561 archive skip trees with the archive tag
14562 comment skip trees with the COMMENT keyword
14563 function or Emacs Lisp form:
14564 will be used as value for `org-agenda-skip-function', so
14565 whenever the function returns a position, FUNC will not be
14566 called for that entry and search will continue from the
14567 position returned
14569 If your function needs to retrieve the tags including inherited tags
14570 at the *current* entry, you can use the value of the variable
14571 `org-scanner-tags' which will be much faster than getting the value
14572 with `org-get-tags-at'. If your function gets properties with
14573 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14574 to t around the call to `org-entry-properties' to get the same speedup.
14575 Note that if your function moves around to retrieve tags and properties at
14576 a *different* entry, you cannot use these techniques."
14577 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14578 (not (org-region-active-p)))
14579 (let* ((org-agenda-archives-mode nil) ; just to make sure
14580 (org-agenda-skip-archived-trees (memq 'archive skip))
14581 (org-agenda-skip-comment-trees (memq 'comment skip))
14582 (org-agenda-skip-function
14583 (car (org-delete-all '(comment archive) skip)))
14584 (org-tags-match-list-sublevels t)
14585 (start-level (eq scope 'region-start-level))
14586 matcher file res
14587 org-todo-keywords-for-agenda
14588 org-done-keywords-for-agenda
14589 org-todo-keyword-alist-for-agenda
14590 org-drawers-for-agenda
14591 org-tag-alist-for-agenda
14592 todo-only)
14594 (cond
14595 ((eq match t) (setq matcher t))
14596 ((eq match nil) (setq matcher t))
14597 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14599 (save-excursion
14600 (save-restriction
14601 (cond ((eq scope 'tree)
14602 (org-back-to-heading t)
14603 (org-narrow-to-subtree)
14604 (setq scope nil))
14605 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14606 (org-region-active-p))
14607 ;; If needed, set start-level to a string like "2"
14608 (when start-level
14609 (save-excursion
14610 (goto-char (region-beginning))
14611 (unless (org-at-heading-p) (outline-next-heading))
14612 (setq start-level (org-current-level))))
14613 (narrow-to-region (region-beginning)
14614 (save-excursion
14615 (goto-char (region-end))
14616 (unless (and (bolp) (org-at-heading-p))
14617 (outline-next-heading))
14618 (point)))
14619 (setq scope nil)))
14621 (if (not scope)
14622 (progn
14623 (org-agenda-prepare-buffers
14624 (list (buffer-file-name (current-buffer))))
14625 (setq res (org-scan-tags func matcher todo-only start-level)))
14626 ;; Get the right scope
14627 (cond
14628 ((and scope (listp scope) (symbolp (car scope)))
14629 (setq scope (eval scope)))
14630 ((eq scope 'agenda)
14631 (setq scope (org-agenda-files t)))
14632 ((eq scope 'agenda-with-archives)
14633 (setq scope (org-agenda-files t))
14634 (setq scope (org-add-archive-files scope)))
14635 ((eq scope 'file)
14636 (setq scope (list (buffer-file-name))))
14637 ((eq scope 'file-with-archives)
14638 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14639 (org-agenda-prepare-buffers scope)
14640 (while (setq file (pop scope))
14641 (with-current-buffer (org-find-base-buffer-visiting file)
14642 (save-excursion
14643 (save-restriction
14644 (widen)
14645 (goto-char (point-min))
14646 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14647 res)))
14649 ;;;; Properties
14651 ;;; Setting and retrieving properties
14653 (defconst org-special-properties
14654 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14655 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14656 "The special properties valid in Org-mode.
14658 These are properties that are not defined in the property drawer,
14659 but in some other way.")
14661 (defconst org-default-properties
14662 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14663 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14664 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14665 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14666 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14667 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14668 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14669 "Some properties that are used by Org-mode for various purposes.
14670 Being in this list makes sure that they are offered for completion.")
14672 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14673 "Regular expression matching the first line of a property drawer.")
14675 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14676 "Regular expression matching the last line of a property drawer.")
14678 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14679 "Regular expression matching the first line of a property drawer.")
14681 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14682 "Regular expression matching the first line of a property drawer.")
14684 (defconst org-property-drawer-re
14685 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14686 org-property-end-re "\\)\n?")
14687 "Matches an entire property drawer.")
14689 (defconst org-clock-drawer-re
14690 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14691 org-property-end-re "\\)\n?")
14692 "Matches an entire clock drawer.")
14694 (defsubst org-re-property (property)
14695 "Return a regexp matching a PROPERTY line.
14696 Match group 1 will be set to the value."
14697 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14699 (defsubst org-re-property-keyword (property)
14700 "Return a regexp matching a PROPERTY line, possibly with no
14701 value for the property."
14702 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14704 (defun org-property-action ()
14705 "Do an action on properties."
14706 (interactive)
14707 (let (c)
14708 (org-at-property-p)
14709 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14710 (setq c (read-char-exclusive))
14711 (cond
14712 ((equal c ?s)
14713 (call-interactively 'org-set-property))
14714 ((equal c ?d)
14715 (call-interactively 'org-delete-property))
14716 ((equal c ?D)
14717 (call-interactively 'org-delete-property-globally))
14718 ((equal c ?c)
14719 (call-interactively 'org-compute-property-at-point))
14720 (t (error "No such property action %c" c)))))
14722 (defun org-inc-effort ()
14723 "Increment the value of the effort property in the current entry."
14724 (interactive)
14725 (org-set-effort nil t))
14727 (defvar org-clock-effort) ;; Defined in org-clock.el
14728 (defvar org-clock-current-task) ;; Defined in org-clock.el
14729 (defun org-set-effort (&optional value increment)
14730 "Set the effort property of the current entry.
14731 With numerical prefix arg, use the nth allowed value, 0 stands for the
14732 10th allowed value.
14734 When INCREMENT is non-nil, set the property to the next allowed value."
14735 (interactive "P")
14736 (if (equal value 0) (setq value 10))
14737 (let* ((completion-ignore-case t)
14738 (prop org-effort-property)
14739 (cur (org-entry-get nil prop))
14740 (allowed (org-property-get-allowed-values nil prop 'table))
14741 (existing (mapcar 'list (org-property-values prop)))
14742 (heading (nth 4 (org-heading-components)))
14744 (val (cond
14745 ((stringp value) value)
14746 ((and allowed (integerp value))
14747 (or (car (nth (1- value) allowed))
14748 (car (org-last allowed))))
14749 ((and allowed increment)
14750 (or (caadr (member (list cur) allowed))
14751 (error "Allowed effort values are not set")))
14752 (allowed
14753 (message "Select 1-9,0, [RET%s]: %s"
14754 (if cur (concat "=" cur) "")
14755 (mapconcat 'car allowed " "))
14756 (setq rpl (read-char-exclusive))
14757 (if (equal rpl ?\r)
14759 (setq rpl (- rpl ?0))
14760 (if (equal rpl 0) (setq rpl 10))
14761 (if (and (> rpl 0) (<= rpl (length allowed)))
14762 (car (nth (1- rpl) allowed))
14763 (org-completing-read "Effort: " allowed nil))))
14765 (let (org-completion-use-ido org-completion-use-iswitchb)
14766 (org-completing-read
14767 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14768 (concat "[" cur "]") "")
14769 ": ")
14770 existing nil nil "" nil cur))))))
14771 (unless (equal (org-entry-get nil prop) val)
14772 (org-entry-put nil prop val))
14773 (save-excursion
14774 (org-back-to-heading t)
14775 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14776 (when (string= heading org-clock-current-task)
14777 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14778 (org-clock-update-mode-line))
14779 (message "%s is now %s" prop val)))
14781 (defun org-at-property-p ()
14782 "Is cursor inside a property drawer?"
14783 (save-excursion
14784 (beginning-of-line 1)
14785 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14786 (save-match-data ;; Used by calling procedures
14787 (let ((p (point))
14788 (range (unless (org-before-first-heading-p)
14789 (org-get-property-block))))
14790 (and range (<= (car range) p) (< p (cdr range))))))))
14792 (defun org-get-property-block (&optional beg end force)
14793 "Return the (beg . end) range of the body of the property drawer.
14794 BEG and END are the beginning and end of the current subtree, or of
14795 the part before the first headline. If they are not given, they will
14796 be found. If the drawer does not exist and FORCE is non-nil, create
14797 the drawer."
14798 (catch 'exit
14799 (save-excursion
14800 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14801 (progn (org-back-to-heading t) (point))))
14802 (end (or end (and (not (outline-next-heading)) (point-max))
14803 (point))))
14804 (goto-char beg)
14805 (if (re-search-forward org-property-start-re end t)
14806 (setq beg (1+ (match-end 0)))
14807 (if force
14808 (save-excursion
14809 (org-insert-property-drawer)
14810 (setq end (progn (outline-next-heading) (point))))
14811 (throw 'exit nil))
14812 (goto-char beg)
14813 (if (re-search-forward org-property-start-re end t)
14814 (setq beg (1+ (match-end 0)))))
14815 (if (re-search-forward org-property-end-re end t)
14816 (setq end (match-beginning 0))
14817 (or force (throw 'exit nil))
14818 (goto-char beg)
14819 (setq end beg)
14820 (org-indent-line)
14821 (insert ":END:\n"))
14822 (cons beg end)))))
14824 (defun org-entry-properties (&optional pom which specific)
14825 "Get all properties of the entry at point-or-marker POM.
14826 This includes the TODO keyword, the tags, time strings for deadline,
14827 scheduled, and clocking, and any additional properties defined in the
14828 entry. The return value is an alist, keys may occur multiple times
14829 if the property key was used several times.
14830 POM may also be nil, in which case the current entry is used.
14831 If WHICH is nil or `all', get all properties. If WHICH is
14832 `special' or `standard', only get that subclass. If WHICH
14833 is a string only get exactly this property. SPECIFIC can be a string, the
14834 specific property we are interested in. Specifying it can speed
14835 things up because then unnecessary parsing is avoided."
14836 (setq which (or which 'all))
14837 (org-with-point-at pom
14838 (let ((clockstr (substring org-clock-string 0 -1))
14839 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14840 (case-fold-search nil)
14841 beg end range props sum-props key key1 value string clocksum clocksumt)
14842 (save-excursion
14843 (when (condition-case nil
14844 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14845 (error nil))
14846 (setq beg (point))
14847 (setq sum-props (get-text-property (point) 'org-summaries))
14848 (setq clocksum (get-text-property (point) :org-clock-minutes)
14849 clocksumt (get-text-property (point) :org-clock-minutes-today))
14850 (outline-next-heading)
14851 (setq end (point))
14852 (when (memq which '(all special))
14853 ;; Get the special properties, like TODO and tags
14854 (goto-char beg)
14855 (when (and (or (not specific) (string= specific "TODO"))
14856 (looking-at org-todo-line-regexp) (match-end 2))
14857 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14858 (when (and (or (not specific) (string= specific "PRIORITY"))
14859 (looking-at org-priority-regexp))
14860 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14861 (when (or (not specific) (string= specific "FILE"))
14862 (push (cons "FILE" buffer-file-name) props))
14863 (when (and (or (not specific) (string= specific "TAGS"))
14864 (setq value (org-get-tags-string))
14865 (string-match "\\S-" value))
14866 (push (cons "TAGS" value) props))
14867 (when (and (or (not specific) (string= specific "ALLTAGS"))
14868 (setq value (org-get-tags-at)))
14869 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14870 ":"))
14871 props))
14872 (when (or (not specific) (string= specific "BLOCKED"))
14873 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14874 (when (or (not specific)
14875 (member specific
14876 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14877 "TIMESTAMP" "TIMESTAMP_IA")))
14878 (catch 'match
14879 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14880 (setq key (if (match-end 1)
14881 (substring (org-match-string-no-properties 1)
14882 0 -1))
14883 string (if (equal key clockstr)
14884 (org-trim
14885 (buffer-substring-no-properties
14886 (match-beginning 3) (goto-char
14887 (point-at-eol))))
14888 (substring (org-match-string-no-properties 3)
14889 1 -1)))
14890 ;; Get the correct property name from the key. This is
14891 ;; necessary if the user has configured time keywords.
14892 (setq key1 (concat key ":"))
14893 (cond
14894 ((not key)
14895 (setq key
14896 (if (= (char-after (match-beginning 3)) ?\[)
14897 "TIMESTAMP_IA" "TIMESTAMP")))
14898 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14899 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14900 ((equal key1 org-closed-string) (setq key "CLOSED"))
14901 ((equal key1 org-clock-string) (setq key "CLOCK")))
14902 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14903 (progn
14904 (push (cons key string) props)
14905 ;; no need to search further if match is found
14906 (throw 'match t))
14907 (when (or (equal key "CLOCK") (not (assoc key props)))
14908 (push (cons key string) props)))))))
14910 (when (memq which '(all standard))
14911 ;; Get the standard properties, like :PROP: ...
14912 (setq range (org-get-property-block beg end))
14913 (when range
14914 (goto-char (car range))
14915 (while (re-search-forward
14916 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14917 (cdr range) t)
14918 (setq key (org-match-string-no-properties 1)
14919 value (org-trim (or (org-match-string-no-properties 2) "")))
14920 (unless (member key excluded)
14921 (push (cons key (or value "")) props)))))
14922 (if clocksum
14923 (push (cons "CLOCKSUM"
14924 (org-columns-number-to-string (/ (float clocksum) 60.)
14925 'add_times))
14926 props))
14927 (if clocksumt
14928 (push (cons "CLOCKSUM_T"
14929 (org-columns-number-to-string (/ (float clocksumt) 60.)
14930 'add_times))
14931 props))
14932 (unless (assoc "CATEGORY" props)
14933 (push (cons "CATEGORY" (org-get-category)) props))
14934 (append sum-props (nreverse props)))))))
14936 (defun org-entry-get (pom property &optional inherit literal-nil)
14937 "Get value of PROPERTY for entry or content at point-or-marker POM.
14938 If INHERIT is non-nil and the entry does not have the property,
14939 then also check higher levels of the hierarchy.
14940 If INHERIT is the symbol `selective', use inheritance only if the setting
14941 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14942 If the property is present but empty, the return value is the empty string.
14943 If the property is not present at all, nil is returned.
14945 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14946 do not interpret it as the list atom nil. This is used for inheritance
14947 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14948 (org-with-point-at pom
14949 (if (and inherit (if (eq inherit 'selective)
14950 (org-property-inherit-p property)
14952 (org-entry-get-with-inheritance property literal-nil)
14953 (if (member property org-special-properties)
14954 ;; We need a special property. Use `org-entry-properties' to
14955 ;; retrieve it, but specify the wanted property
14956 (cdr (assoc property (org-entry-properties nil 'special property)))
14957 (let ((range (org-get-property-block)))
14958 (when (and range (not (eq (car range) (cdr range))))
14959 (let* ((props (list (or (assoc property org-file-properties)
14960 (assoc property org-global-properties)
14961 (assoc property org-global-properties-fixed))))
14962 (ap (lambda (key)
14963 (when (re-search-forward
14964 (org-re-property key) (cdr range) t)
14965 (setq props
14966 (org-update-property-plist
14968 (if (match-end 1)
14969 (org-match-string-no-properties 1) "")
14970 props)))))
14971 val)
14972 (goto-char (car range))
14973 (funcall ap property)
14974 (goto-char (car range))
14975 (while (funcall ap (concat property "+")))
14976 (setq val (cdr (assoc property props)))
14977 (when val (if literal-nil val (org-not-nil val))))))))))
14979 (defun org-property-or-variable-value (var &optional inherit)
14980 "Check if there is a property fixing the value of VAR.
14981 If yes, return this value. If not, return the current value of the variable."
14982 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14983 (if (and prop (stringp prop) (string-match "\\S-" prop))
14984 (read prop)
14985 (symbol-value var))))
14987 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14988 "Delete the property PROPERTY from entry at point-or-marker POM.
14989 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14990 an empty drawer to delete."
14991 (org-with-point-at pom
14992 (if (member property org-special-properties)
14993 nil ; cannot delete these properties.
14994 (let ((range (org-get-property-block)))
14995 (if (and range
14996 (goto-char (car range))
14997 (re-search-forward
14998 (org-re-property property)
14999 (cdr range) t))
15000 (progn
15001 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15002 (and delete-empty-drawer
15003 (org-remove-empty-drawer-at
15004 delete-empty-drawer (car range)))
15006 nil)))))
15008 ;; Multi-values properties are properties that contain multiple values
15009 ;; These values are assumed to be single words, separated by whitespace.
15010 (defun org-entry-add-to-multivalued-property (pom property value)
15011 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15012 (let* ((old (org-entry-get pom property))
15013 (values (and old (org-split-string old "[ \t]"))))
15014 (setq value (org-entry-protect-space value))
15015 (unless (member value values)
15016 (setq values (cons value values))
15017 (org-entry-put pom property
15018 (mapconcat 'identity values " ")))))
15020 (defun org-entry-remove-from-multivalued-property (pom property value)
15021 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15022 (let* ((old (org-entry-get pom property))
15023 (values (and old (org-split-string old "[ \t]"))))
15024 (setq value (org-entry-protect-space value))
15025 (when (member value values)
15026 (setq values (delete value values))
15027 (org-entry-put pom property
15028 (mapconcat 'identity values " ")))))
15030 (defun org-entry-member-in-multivalued-property (pom property value)
15031 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15032 (let* ((old (org-entry-get pom property))
15033 (values (and old (org-split-string old "[ \t]"))))
15034 (setq value (org-entry-protect-space value))
15035 (member value values)))
15037 (defun org-entry-get-multivalued-property (pom property)
15038 "Return a list of values in a multivalued property."
15039 (let* ((value (org-entry-get pom property))
15040 (values (and value (org-split-string value "[ \t]"))))
15041 (mapcar 'org-entry-restore-space values)))
15043 (defun org-entry-put-multivalued-property (pom property &rest values)
15044 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15045 VALUES should be a list of strings. Spaces will be protected."
15046 (org-entry-put pom property
15047 (mapconcat 'org-entry-protect-space values " "))
15048 (let* ((value (org-entry-get pom property))
15049 (values (and value (org-split-string value "[ \t]"))))
15050 (mapcar 'org-entry-restore-space values)))
15052 (defun org-entry-protect-space (s)
15053 "Protect spaces and newline in string S."
15054 (while (string-match " " s)
15055 (setq s (replace-match "%20" t t s)))
15056 (while (string-match "\n" s)
15057 (setq s (replace-match "%0A" t t s)))
15060 (defun org-entry-restore-space (s)
15061 "Restore spaces and newline in string S."
15062 (while (string-match "%20" s)
15063 (setq s (replace-match " " t t s)))
15064 (while (string-match "%0A" s)
15065 (setq s (replace-match "\n" t t s)))
15068 (defvar org-entry-property-inherited-from (make-marker)
15069 "Marker pointing to the entry from where a property was inherited.
15070 Each call to `org-entry-get-with-inheritance' will set this marker to the
15071 location of the entry where the inheritance search matched. If there was
15072 no match, the marker will point nowhere.
15073 Note that also `org-entry-get' calls this function, if the INHERIT flag
15074 is set.")
15076 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15077 "Get PROPERTY of entry or content at point, search higher levels if needed.
15078 The search will stop at the first ancestor which has the property defined.
15079 If the value found is \"nil\", return nil to show that the property
15080 should be considered as undefined (this is the meaning of nil here).
15081 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15082 (move-marker org-entry-property-inherited-from nil)
15083 (let (tmp)
15084 (save-excursion
15085 (save-restriction
15086 (widen)
15087 (catch 'ex
15088 (while t
15089 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15090 (or (ignore-errors (org-back-to-heading t))
15091 (goto-char (point-min)))
15092 (move-marker org-entry-property-inherited-from (point))
15093 (throw 'ex tmp))
15094 (or (ignore-errors (org-up-heading-safe))
15095 (throw 'ex nil))))))
15096 (setq tmp (or tmp
15097 (cdr (assoc property org-file-properties))
15098 (cdr (assoc property org-global-properties))
15099 (cdr (assoc property org-global-properties-fixed))))
15100 (if literal-nil tmp (org-not-nil tmp))))
15102 (defvar org-property-changed-functions nil
15103 "Hook called when the value of a property has changed.
15104 Each hook function should accept two arguments, the name of the property
15105 and the new value.")
15107 (defun org-entry-put (pom property value)
15108 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15109 (org-with-point-at pom
15110 (org-back-to-heading t)
15111 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15112 range)
15113 (cond
15114 ((equal property "TODO")
15115 (when (and (stringp value) (string-match "\\S-" value)
15116 (not (member value org-todo-keywords-1)))
15117 (error "\"%s\" is not a valid TODO state" value))
15118 (if (or (not value)
15119 (not (string-match "\\S-" value)))
15120 (setq value 'none))
15121 (org-todo value)
15122 (org-set-tags nil 'align))
15123 ((equal property "PRIORITY")
15124 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15125 (string-to-char value) ?\ ))
15126 (org-set-tags nil 'align))
15127 ((equal property "CLOCKSUM")
15128 (if (not (re-search-forward
15129 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15130 (error "Cannot find a clock log")
15131 (goto-char (- (match-end 1) 2))
15132 (cond
15133 ((eq value 'earlier) (org-timestamp-down))
15134 ((eq value 'later) (org-timestamp-up)))
15135 (org-clock-sum-current-item)))
15136 ((equal property "SCHEDULED")
15137 (if (re-search-forward org-scheduled-time-regexp end t)
15138 (cond
15139 ((eq value 'earlier) (org-timestamp-change -1 'day))
15140 ((eq value 'later) (org-timestamp-change 1 'day))
15141 (t (call-interactively 'org-schedule)))
15142 (call-interactively 'org-schedule)))
15143 ((equal property "DEADLINE")
15144 (if (re-search-forward org-deadline-time-regexp end t)
15145 (cond
15146 ((eq value 'earlier) (org-timestamp-change -1 'day))
15147 ((eq value 'later) (org-timestamp-change 1 'day))
15148 (t (call-interactively 'org-deadline)))
15149 (call-interactively 'org-deadline)))
15150 ((member property org-special-properties)
15151 (error "The %s property can not yet be set with `org-entry-put'"
15152 property))
15153 (t ; a non-special property
15154 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15155 (setq range (org-get-property-block beg end 'force))
15156 (goto-char (car range))
15157 (if (re-search-forward
15158 (org-re-property-keyword property) (cdr range) t)
15159 (progn
15160 (delete-region (match-beginning 0) (match-end 0))
15161 (goto-char (match-beginning 0)))
15162 (goto-char (cdr range))
15163 (insert "\n")
15164 (backward-char 1)
15165 (org-indent-line))
15166 (insert ":" property ":")
15167 (and value (insert " " value))
15168 (org-indent-line)))))
15169 (run-hook-with-args 'org-property-changed-functions property value)))
15171 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15172 "Get all property keys in the current buffer.
15173 With INCLUDE-SPECIALS, also list the special properties that reflect things
15174 like tags and TODO state.
15175 With INCLUDE-DEFAULTS, also include properties that has special meaning
15176 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15177 and others.
15178 With INCLUDE-COLUMNS, also include property names given in COLUMN
15179 formats in the current buffer."
15180 (let (rtn range cfmt s p)
15181 (save-excursion
15182 (save-restriction
15183 (widen)
15184 (goto-char (point-min))
15185 (while (re-search-forward org-property-start-re nil t)
15186 (setq range (org-get-property-block))
15187 (goto-char (car range))
15188 (while (re-search-forward
15189 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15190 (cdr range) t)
15191 (add-to-list 'rtn (org-match-string-no-properties 1)))
15192 (outline-next-heading))))
15194 (when include-specials
15195 (setq rtn (append org-special-properties rtn)))
15197 (when include-defaults
15198 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15199 (add-to-list 'rtn org-effort-property))
15201 (when include-columns
15202 (save-excursion
15203 (save-restriction
15204 (widen)
15205 (goto-char (point-min))
15206 (while (re-search-forward
15207 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15208 nil t)
15209 (setq cfmt (match-string 2) s 0)
15210 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15211 cfmt s)
15212 (setq s (match-end 0)
15213 p (match-string 1 cfmt))
15214 (unless (or (equal p "ITEM")
15215 (member p org-special-properties))
15216 (add-to-list 'rtn (match-string 1 cfmt))))))))
15218 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15220 (defun org-property-values (key)
15221 "Return a list of all values of property KEY in the current buffer."
15222 (save-excursion
15223 (save-restriction
15224 (widen)
15225 (goto-char (point-min))
15226 (let ((re (org-re-property key))
15227 values)
15228 (while (re-search-forward re nil t)
15229 (add-to-list 'values (org-trim (match-string 1))))
15230 (delete "" values)))))
15232 (defun org-insert-property-drawer ()
15233 "Insert a property drawer into the current entry."
15234 (org-back-to-heading t)
15235 (looking-at org-outline-regexp)
15236 (let ((indent (if org-adapt-indentation
15237 (- (match-end 0) (match-beginning 0))
15239 (beg (point))
15240 (re (concat "^[ \t]*" org-keyword-time-regexp))
15241 end hiddenp)
15242 (outline-next-heading)
15243 (setq end (point))
15244 (goto-char beg)
15245 (while (re-search-forward re end t))
15246 (setq hiddenp (outline-invisible-p))
15247 (end-of-line 1)
15248 (and (equal (char-after) ?\n) (forward-char 1))
15249 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15250 (if (member (match-string 1) '("CLOCK:" ":END:"))
15251 ;; just skip this line
15252 (beginning-of-line 2)
15253 ;; Drawer start, find the end
15254 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15255 (beginning-of-line 1)))
15256 (org-skip-over-state-notes)
15257 (skip-chars-backward " \t\n\r")
15258 (if (eq (char-before) ?*) (forward-char 1))
15259 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15260 (beginning-of-line 0)
15261 (org-indent-to-column indent)
15262 (beginning-of-line 2)
15263 (org-indent-to-column indent)
15264 (beginning-of-line 0)
15265 (if hiddenp
15266 (save-excursion
15267 (org-back-to-heading t)
15268 (hide-entry))
15269 (org-flag-drawer t))))
15271 (defun org-insert-drawer (&optional arg drawer)
15272 "Insert a drawer at point.
15274 Optional argument DRAWER, when non-nil, is a string representing
15275 drawer's name. Otherwise, the user is prompted for a name.
15277 If a region is active, insert the drawer around that region
15278 instead.
15280 Point is left between drawer's boundaries."
15281 (interactive "P")
15282 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15283 "LOGBOOK"))
15284 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15285 ;; internally by Org. They are meant to be inserted
15286 ;; automatically.
15287 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15288 ;; Remove system drawers from list. Note: For some reason,
15289 ;; `org-completing-read' ignores the predicate while
15290 ;; `completing-read' handles it fine.
15291 (drawer (if arg "PROPERTIES"
15292 (or drawer
15293 (completing-read
15294 "Drawer: " org-drawers
15295 (lambda (d) (not (member d system-drawers))))))))
15296 (cond
15297 ;; With C-u, fall back on `org-insert-property-drawer'
15298 (arg (org-insert-property-drawer))
15299 ;; With an active region, insert a drawer at point.
15300 ((not (org-region-active-p))
15301 (progn
15302 (unless (bolp) (insert "\n"))
15303 (insert (format ":%s:\n\n:END:\n" drawer))
15304 (forward-line -2)))
15305 ;; Otherwise, insert the drawer at point
15307 (let ((rbeg (region-beginning))
15308 (rend (copy-marker (region-end))))
15309 (unwind-protect
15310 (progn
15311 (goto-char rbeg)
15312 (beginning-of-line)
15313 (when (save-excursion
15314 (re-search-forward org-outline-regexp-bol rend t))
15315 (error "Drawers cannot contain headlines"))
15316 ;; Position point at the beginning of the first
15317 ;; non-blank line in region. Insert drawer's opening
15318 ;; there, then indent it.
15319 (org-skip-whitespace)
15320 (beginning-of-line)
15321 (insert ":" drawer ":\n")
15322 (forward-line -1)
15323 (indent-for-tab-command)
15324 ;; Move point to the beginning of the first blank line
15325 ;; after the last non-blank line in region. Insert
15326 ;; drawer's closing, then indent it.
15327 (goto-char rend)
15328 (skip-chars-backward " \r\t\n")
15329 (insert "\n:END:")
15330 (deactivate-mark t)
15331 (indent-for-tab-command)
15332 (unless (eolp) (insert "\n")))
15333 ;; Clear marker, whatever the outcome of insertion is.
15334 (set-marker rend nil)))))))
15336 (defvar org-property-set-functions-alist nil
15337 "Property set function alist.
15338 Each entry should have the following format:
15340 (PROPERTY . READ-FUNCTION)
15342 The read function will be called with the same argument as
15343 `org-completing-read'.")
15345 (defun org-set-property-function (property)
15346 "Get the function that should be used to set PROPERTY.
15347 This is computed according to `org-property-set-functions-alist'."
15348 (or (cdr (assoc property org-property-set-functions-alist))
15349 'org-completing-read))
15351 (defun org-read-property-value (property)
15352 "Read PROPERTY value from user."
15353 (let* ((completion-ignore-case t)
15354 (allowed (org-property-get-allowed-values nil property 'table))
15355 (cur (org-entry-get nil property))
15356 (prompt (concat property " value"
15357 (if (and cur (string-match "\\S-" cur))
15358 (concat " [" cur "]") "") ": "))
15359 (set-function (org-set-property-function property))
15360 (val (if allowed
15361 (funcall set-function prompt allowed nil
15362 (not (get-text-property 0 'org-unrestricted
15363 (caar allowed))))
15364 (let (org-completion-use-ido org-completion-use-iswitchb)
15365 (funcall set-function prompt
15366 (mapcar 'list (org-property-values property))
15367 nil nil "" nil cur)))))
15368 (if (equal val "")
15370 val)))
15372 (defvar org-last-set-property nil)
15373 (defvar org-last-set-property-value nil)
15374 (defun org-read-property-name ()
15375 "Read a property name."
15376 (let* ((completion-ignore-case t)
15377 (keys (org-buffer-property-keys nil t t))
15378 (default-prop (or (save-excursion
15379 (save-match-data
15380 (beginning-of-line)
15381 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15382 (null (string= (match-string 1) "END"))
15383 (match-string 1))))
15384 org-last-set-property))
15385 (property (org-icompleting-read
15386 (concat "Property"
15387 (if default-prop (concat " [" default-prop "]") "")
15388 ": ")
15389 (mapcar 'list keys)
15390 nil nil nil nil
15391 default-prop)))
15392 (if (member property keys)
15393 property
15394 (or (cdr (assoc (downcase property)
15395 (mapcar (lambda (x) (cons (downcase x) x))
15396 keys)))
15397 property))))
15399 (defun org-set-property-and-value (use-last)
15400 "Allow to set [PROPERTY]: [value] direction from prompt.
15401 When use-default, don't even ask, just use the last
15402 \"[PROPERTY]: [value]\" string from the history."
15403 (interactive "P")
15404 (let* ((completion-ignore-case t)
15405 (pv (or (and use-last org-last-set-property-value)
15406 (org-completing-read
15407 "Enter a \"[Property]: [value]\" pair: "
15408 nil nil nil nil nil
15409 org-last-set-property-value)))
15410 prop val)
15411 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15412 (setq prop (match-string 1 pv)
15413 val (match-string 2 pv))
15414 (org-set-property prop val))))
15416 (defun org-set-property (property value)
15417 "In the current entry, set PROPERTY to VALUE.
15418 When called interactively, this will prompt for a property name, offering
15419 completion on existing and default properties. And then it will prompt
15420 for a value, offering completion either on allowed values (via an inherited
15421 xxx_ALL property) or on existing values in other instances of this property
15422 in the current file."
15423 (interactive (list nil nil))
15424 (let* ((property (or property (org-read-property-name)))
15425 (value (or value (org-read-property-value property)))
15426 (fn (cdr (assoc property org-properties-postprocess-alist))))
15427 (setq org-last-set-property property)
15428 (setq org-last-set-property-value (concat property ": " value))
15429 ;; Possibly postprocess the inserted value:
15430 (when fn (setq value (funcall fn value)))
15431 (unless (equal (org-entry-get nil property) value)
15432 (org-entry-put nil property value))))
15434 (defun org-delete-property (property &optional delete-empty-drawer)
15435 "In the current entry, delete PROPERTY.
15436 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15437 an empty drawer to delete."
15438 (interactive
15439 (let* ((completion-ignore-case t)
15440 (prop (org-icompleting-read "Property: "
15441 (org-entry-properties nil 'standard))))
15442 (list prop)))
15443 (message "Property %s %s" property
15444 (if (org-entry-delete nil property delete-empty-drawer)
15445 "deleted"
15446 "was not present in the entry")))
15448 (defun org-delete-property-globally (property)
15449 "Remove PROPERTY globally, from all entries."
15450 (interactive
15451 (let* ((completion-ignore-case t)
15452 (prop (org-icompleting-read
15453 "Globally remove property: "
15454 (mapcar 'list (org-buffer-property-keys)))))
15455 (list prop)))
15456 (save-excursion
15457 (save-restriction
15458 (widen)
15459 (goto-char (point-min))
15460 (let ((cnt 0))
15461 (while (re-search-forward
15462 (org-re-property property)
15463 nil t)
15464 (setq cnt (1+ cnt))
15465 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15466 (message "Property \"%s\" removed from %d entries" property cnt)))))
15468 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15470 (defun org-compute-property-at-point ()
15471 "Compute the property at point.
15472 This looks for an enclosing column format, extracts the operator and
15473 then applies it to the property in the column format's scope."
15474 (interactive)
15475 (unless (org-at-property-p)
15476 (error "Not at a property"))
15477 (let ((prop (org-match-string-no-properties 2)))
15478 (org-columns-get-format-and-top-level)
15479 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15480 (error "No operator defined for property %s" prop))
15481 (org-columns-compute prop)))
15483 (defvar org-property-allowed-value-functions nil
15484 "Hook for functions supplying allowed values for a specific property.
15485 The functions must take a single argument, the name of the property, and
15486 return a flat list of allowed values. If \":ETC\" is one of
15487 the values, this means that these values are intended as defaults for
15488 completion, but that other values should be allowed too.
15489 The functions must return nil if they are not responsible for this
15490 property.")
15492 (defun org-property-get-allowed-values (pom property &optional table)
15493 "Get allowed values for the property PROPERTY.
15494 When TABLE is non-nil, return an alist that can directly be used for
15495 completion."
15496 (let (vals)
15497 (cond
15498 ((equal property "TODO")
15499 (setq vals (org-with-point-at pom
15500 (append org-todo-keywords-1 '("")))))
15501 ((equal property "PRIORITY")
15502 (let ((n org-lowest-priority))
15503 (while (>= n org-highest-priority)
15504 (push (char-to-string n) vals)
15505 (setq n (1- n)))))
15506 ((member property org-special-properties))
15507 ((setq vals (run-hook-with-args-until-success
15508 'org-property-allowed-value-functions property)))
15510 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15511 (when (and vals (string-match "\\S-" vals))
15512 (setq vals (car (read-from-string (concat "(" vals ")"))))
15513 (setq vals (mapcar (lambda (x)
15514 (cond ((stringp x) x)
15515 ((numberp x) (number-to-string x))
15516 ((symbolp x) (symbol-name x))
15517 (t "???")))
15518 vals)))))
15519 (when (member ":ETC" vals)
15520 (setq vals (remove ":ETC" vals))
15521 (org-add-props (car vals) '(org-unrestricted t)))
15522 (if table (mapcar 'list vals) vals)))
15524 (defun org-property-previous-allowed-value (&optional previous)
15525 "Switch to the next allowed value for this property."
15526 (interactive)
15527 (org-property-next-allowed-value t))
15529 (defun org-property-next-allowed-value (&optional previous)
15530 "Switch to the next allowed value for this property."
15531 (interactive)
15532 (unless (org-at-property-p)
15533 (error "Not at a property"))
15534 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15535 (key (match-string 2))
15536 (value (match-string 3))
15537 (allowed (or (org-property-get-allowed-values (point) key)
15538 (and (member value '("[ ]" "[-]" "[X]"))
15539 '("[ ]" "[X]"))))
15540 (heading (save-match-data (nth 4 (org-heading-components))))
15541 nval)
15542 (unless allowed
15543 (error "Allowed values for this property have not been defined"))
15544 (if previous (setq allowed (reverse allowed)))
15545 (if (member value allowed)
15546 (setq nval (car (cdr (member value allowed)))))
15547 (setq nval (or nval (car allowed)))
15548 (if (equal nval value)
15549 (error "Only one allowed value for this property"))
15550 (org-at-property-p)
15551 (replace-match (concat " :" key ": " nval) t t)
15552 (org-indent-line)
15553 (beginning-of-line 1)
15554 (skip-chars-forward " \t")
15555 (when (equal prop org-effort-property)
15556 (save-excursion
15557 (org-back-to-heading t)
15558 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15559 (when (string= org-clock-current-task heading)
15560 (setq org-clock-effort nval)
15561 (org-clock-update-mode-line)))
15562 (run-hook-with-args 'org-property-changed-functions key nval)))
15564 (defun org-find-olp (path &optional this-buffer)
15565 "Return a marker pointing to the entry at outline path OLP.
15566 If anything goes wrong, throw an error.
15567 You can wrap this call to catch the error like this:
15569 (condition-case msg
15570 (org-mobile-locate-entry (match-string 4))
15571 (error (nth 1 msg)))
15573 The return value will then be either a string with the error message,
15574 or a marker if everything is OK.
15576 If THIS-BUFFER is set, the outline path does not contain a file,
15577 only headings."
15578 (let* ((file (if this-buffer buffer-file-name (pop path)))
15579 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15580 (level 1)
15581 (lmin 1)
15582 (lmax 1)
15583 limit re end found pos heading cnt flevel)
15584 (unless buffer (error "File not found :%s" file))
15585 (with-current-buffer buffer
15586 (save-excursion
15587 (save-restriction
15588 (widen)
15589 (setq limit (point-max))
15590 (goto-char (point-min))
15591 (while (setq heading (pop path))
15592 (setq re (format org-complex-heading-regexp-format
15593 (regexp-quote heading)))
15594 (setq cnt 0 pos (point))
15595 (while (re-search-forward re end t)
15596 (setq level (- (match-end 1) (match-beginning 1)))
15597 (if (and (>= level lmin) (<= level lmax))
15598 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15599 (when (= cnt 0) (error "Heading not found on level %d: %s"
15600 lmax heading))
15601 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15602 lmax heading))
15603 (goto-char found)
15604 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15605 (setq end (save-excursion (org-end-of-subtree t t))))
15606 (when (org-at-heading-p)
15607 (point-marker)))))))
15609 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15610 "Find node HEADING in BUFFER.
15611 Return a marker to the heading if it was found, or nil if not.
15612 If POS-ONLY is set, return just the position instead of a marker.
15614 The heading text must match exact, but it may have a TODO keyword,
15615 a priority cookie and tags in the standard locations."
15616 (with-current-buffer (or buffer (current-buffer))
15617 (save-excursion
15618 (save-restriction
15619 (widen)
15620 (goto-char (point-min))
15621 (let (case-fold-search)
15622 (if (re-search-forward
15623 (format org-complex-heading-regexp-format
15624 (regexp-quote heading)) nil t)
15625 (if pos-only
15626 (match-beginning 0)
15627 (move-marker (make-marker) (match-beginning 0)))))))))
15629 (defun org-find-exact-heading-in-directory (heading &optional dir)
15630 "Find Org node headline HEADING in all .org files in directory DIR.
15631 When the target headline is found, return a marker to this location."
15632 (let ((files (directory-files (or dir default-directory)
15633 nil "\\`[^.#].*\\.org\\'"))
15634 file visiting m buffer)
15635 (catch 'found
15636 (while (setq file (pop files))
15637 (message "trying %s" file)
15638 (setq visiting (org-find-base-buffer-visiting file))
15639 (setq buffer (or visiting (find-file-noselect file)))
15640 (setq m (org-find-exact-headline-in-buffer
15641 heading buffer))
15642 (when (and (not m) (not visiting)) (kill-buffer buffer))
15643 (and m (throw 'found m))))))
15645 (defun org-find-entry-with-id (ident)
15646 "Locate the entry that contains the ID property with exact value IDENT.
15647 IDENT can be a string, a symbol or a number, this function will search for
15648 the string representation of it.
15649 Return the position where this entry starts, or nil if there is no such entry."
15650 (interactive "sID: ")
15651 (let ((id (cond
15652 ((stringp ident) ident)
15653 ((symbol-name ident) (symbol-name ident))
15654 ((numberp ident) (number-to-string ident))
15655 (t (error "IDENT %s must be a string, symbol or number" ident))))
15656 (case-fold-search nil))
15657 (save-excursion
15658 (save-restriction
15659 (widen)
15660 (goto-char (point-min))
15661 (when (re-search-forward
15662 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15663 nil t)
15664 (org-back-to-heading t)
15665 (point))))))
15667 ;;;; Timestamps
15669 (defvar org-last-changed-timestamp nil)
15670 (defvar org-last-inserted-timestamp nil
15671 "The last time stamp inserted with `org-insert-time-stamp'.")
15672 (defvar org-time-was-given) ; dynamically scoped parameter
15673 (defvar org-end-time-was-given) ; dynamically scoped parameter
15674 (defvar org-ts-what) ; dynamically scoped parameter
15676 (defun org-time-stamp (arg &optional inactive)
15677 "Prompt for a date/time and insert a time stamp.
15678 If the user specifies a time like HH:MM or if this command is
15679 called with at least one prefix argument, the time stamp contains
15680 the date and the time. Otherwise, only the date is be included.
15682 All parts of a date not specified by the user is filled in from
15683 the current date/time. So if you just press return without
15684 typing anything, the time stamp will represent the current
15685 date/time.
15687 If there is already a timestamp at the cursor, it will be
15688 modified.
15690 With two universal prefix arguments, insert an active timestamp
15691 with the current time without prompting the user."
15692 (interactive "P")
15693 (let* ((ts nil)
15694 (default-time
15695 ;; Default time is either today, or, when entering a range,
15696 ;; the range start.
15697 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15698 (save-excursion
15699 (re-search-backward
15700 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15701 (- (point) 20) t)))
15702 (apply 'encode-time (org-parse-time-string (match-string 1)))
15703 (current-time)))
15704 (default-input (and ts (org-get-compact-tod ts)))
15705 (repeater (save-excursion
15706 (save-match-data
15707 (beginning-of-line)
15708 (when (re-search-forward
15709 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15710 (save-excursion (progn (end-of-line) (point))) t)
15711 (match-string 0)))))
15712 org-time-was-given org-end-time-was-given time)
15713 (cond
15714 ((and (org-at-timestamp-p t)
15715 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15716 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15717 (insert "--")
15718 (setq time (let ((this-command this-command))
15719 (org-read-date arg 'totime nil nil
15720 default-time default-input inactive)))
15721 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15722 ((org-at-timestamp-p t)
15723 (setq time (let ((this-command this-command))
15724 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15725 (when (org-at-timestamp-p t) ; just to get the match data
15726 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15727 (replace-match "")
15728 (setq org-last-changed-timestamp
15729 (org-insert-time-stamp
15730 time (or org-time-was-given arg)
15731 inactive nil nil (list org-end-time-was-given)))
15732 (when repeater (goto-char (1- (point))) (insert " " repeater)
15733 (setq org-last-changed-timestamp
15734 (concat (substring org-last-inserted-timestamp 0 -1)
15735 " " repeater ">"))))
15736 (message "Timestamp updated"))
15737 ((equal arg '(16))
15738 (org-insert-time-stamp (current-time) t))
15740 (setq time (let ((this-command this-command))
15741 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15742 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15743 nil nil (list org-end-time-was-given))))))
15745 ;; FIXME: can we use this for something else, like computing time differences?
15746 (defun org-get-compact-tod (s)
15747 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15748 (let* ((t1 (match-string 1 s))
15749 (h1 (string-to-number (match-string 2 s)))
15750 (m1 (string-to-number (match-string 3 s)))
15751 (t2 (and (match-end 4) (match-string 5 s)))
15752 (h2 (and t2 (string-to-number (match-string 6 s))))
15753 (m2 (and t2 (string-to-number (match-string 7 s))))
15754 dh dm)
15755 (if (not t2)
15757 (setq dh (- h2 h1) dm (- m2 m1))
15758 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15759 (concat t1 "+" (number-to-string dh)
15760 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15762 (defun org-time-stamp-inactive (&optional arg)
15763 "Insert an inactive time stamp.
15764 An inactive time stamp is enclosed in square brackets instead of angle
15765 brackets. It is inactive in the sense that it does not trigger agenda entries,
15766 does not link to the calendar and cannot be changed with the S-cursor keys.
15767 So these are more for recording a certain time/date."
15768 (interactive "P")
15769 (org-time-stamp arg 'inactive))
15771 (defvar org-date-ovl (make-overlay 1 1))
15772 (overlay-put org-date-ovl 'face 'org-date-selected)
15773 (org-detach-overlay org-date-ovl)
15775 (defvar org-ans1) ; dynamically scoped parameter
15776 (defvar org-ans2) ; dynamically scoped parameter
15778 (defvar org-plain-time-of-day-regexp) ; defined below
15780 (defvar org-overriding-default-time nil) ; dynamically scoped
15781 (defvar org-read-date-overlay nil)
15782 (defvar org-dcst nil) ; dynamically scoped
15783 (defvar org-read-date-history nil)
15784 (defvar org-read-date-final-answer nil)
15785 (defvar org-read-date-analyze-futurep nil)
15786 (defvar org-read-date-analyze-forced-year nil)
15787 (defvar org-read-date-inactive)
15789 (defvar org-read-date-minibuffer-local-map
15790 (let ((map (make-sparse-keymap)))
15791 (set-keymap-parent map minibuffer-local-map)
15792 (org-defkey map (kbd ".")
15793 (lambda () (interactive)
15794 (org-eval-in-calendar '(calendar-goto-today))))
15795 (org-defkey map [(meta shift left)]
15796 (lambda () (interactive)
15797 (org-eval-in-calendar '(calendar-backward-month 1))))
15798 (org-defkey map [(meta shift right)]
15799 (lambda () (interactive)
15800 (org-eval-in-calendar '(calendar-forward-month 1))))
15801 (org-defkey map [(meta shift up)]
15802 (lambda () (interactive)
15803 (org-eval-in-calendar '(calendar-backward-year 1))))
15804 (org-defkey map [(meta shift down)]
15805 (lambda () (interactive)
15806 (org-eval-in-calendar '(calendar-forward-year 1))))
15807 (org-defkey map [?\e (shift left)]
15808 (lambda () (interactive)
15809 (org-eval-in-calendar '(calendar-backward-month 1))))
15810 (org-defkey map [?\e (shift right)]
15811 (lambda () (interactive)
15812 (org-eval-in-calendar '(calendar-forward-month 1))))
15813 (org-defkey map [?\e (shift up)]
15814 (lambda () (interactive)
15815 (org-eval-in-calendar '(calendar-backward-year 1))))
15816 (org-defkey map [?\e (shift down)]
15817 (lambda () (interactive)
15818 (org-eval-in-calendar '(calendar-forward-year 1))))
15819 (org-defkey map [(shift up)]
15820 (lambda () (interactive)
15821 (org-eval-in-calendar '(calendar-backward-week 1))))
15822 (org-defkey map [(shift down)]
15823 (lambda () (interactive)
15824 (org-eval-in-calendar '(calendar-forward-week 1))))
15825 (org-defkey map [(shift left)]
15826 (lambda () (interactive)
15827 (org-eval-in-calendar '(calendar-backward-day 1))))
15828 (org-defkey map [(shift right)]
15829 (lambda () (interactive)
15830 (org-eval-in-calendar '(calendar-forward-day 1))))
15831 (org-defkey map "!"
15832 (lambda () (interactive)
15833 (org-eval-in-calendar '(diary-view-entries))
15834 (message "")))
15835 (org-defkey map ">"
15836 (lambda () (interactive)
15837 (org-eval-in-calendar '(scroll-calendar-left 1))))
15838 (org-defkey map "<"
15839 (lambda () (interactive)
15840 (org-eval-in-calendar '(scroll-calendar-right 1))))
15841 (org-defkey map "\C-v"
15842 (lambda () (interactive)
15843 (org-eval-in-calendar
15844 '(calendar-scroll-left-three-months 1))))
15845 (org-defkey map "\M-v"
15846 (lambda () (interactive)
15847 (org-eval-in-calendar
15848 '(calendar-scroll-right-three-months 1))))
15849 map)
15850 "Keymap for minibuffer commands when using `org-read-date'.")
15852 (defun org-read-date (&optional org-with-time to-time from-string prompt
15853 default-time default-input inactive)
15854 "Read a date, possibly a time, and make things smooth for the user.
15855 The prompt will suggest to enter an ISO date, but you can also enter anything
15856 which will at least partially be understood by `parse-time-string'.
15857 Unrecognized parts of the date will default to the current day, month, year,
15858 hour and minute. If this command is called to replace a timestamp at point,
15859 or to enter the second timestamp of a range, the default time is taken
15860 from the existing stamp. Furthermore, the command prefers the future,
15861 so if you are giving a date where the year is not given, and the day-month
15862 combination is already past in the current year, it will assume you
15863 mean next year. For details, see the manual. A few examples:
15865 3-2-5 --> 2003-02-05
15866 feb 15 --> currentyear-02-15
15867 2/15 --> currentyear-02-15
15868 sep 12 9 --> 2009-09-12
15869 12:45 --> today 12:45
15870 22 sept 0:34 --> currentyear-09-22 0:34
15871 12 --> currentyear-currentmonth-12
15872 Fri --> nearest Friday (today or later)
15873 etc.
15875 Furthermore you can specify a relative date by giving, as the *first* thing
15876 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15877 change in days weeks, months, years.
15878 With a single plus or minus, the date is relative to today. With a double
15879 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15880 +4d --> four days from today
15881 +4 --> same as above
15882 +2w --> two weeks from today
15883 ++5 --> five days from default date
15885 The function understands only English month and weekday abbreviations.
15887 While prompting, a calendar is popped up - you can also select the
15888 date with the mouse (button 1). The calendar shows a period of three
15889 months. To scroll it to other months, use the keys `>' and `<'.
15890 If you don't like the calendar, turn it off with
15891 \(setq org-read-date-popup-calendar nil)
15893 With optional argument TO-TIME, the date will immediately be converted
15894 to an internal time.
15895 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15896 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15897 still enter a time, and this function will inform the calling routine
15898 about this change. The calling routine may then choose to change the
15899 format used to insert the time stamp into the buffer to include the time.
15900 With optional argument FROM-STRING, read from this string instead from
15901 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15902 the time/date that is used for everything that is not specified by the
15903 user."
15904 (require 'parse-time)
15905 (let* ((org-time-stamp-rounding-minutes
15906 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15907 (org-dcst org-display-custom-times)
15908 (ct (org-current-time))
15909 (org-def (or org-overriding-default-time default-time ct))
15910 (org-defdecode (decode-time org-def))
15911 (dummy (progn
15912 (when (< (nth 2 org-defdecode) org-extend-today-until)
15913 (setcar (nthcdr 2 org-defdecode) -1)
15914 (setcar (nthcdr 1 org-defdecode) 59)
15915 (setq org-def (apply 'encode-time org-defdecode)
15916 org-defdecode (decode-time org-def)))))
15917 (mouse-autoselect-window nil) ; Don't let the mouse jump
15918 (calendar-frame-setup nil)
15919 (calendar-setup nil)
15920 (calendar-move-hook nil)
15921 (calendar-view-diary-initially-flag nil)
15922 (calendar-view-holidays-initially-flag nil)
15923 (timestr (format-time-string
15924 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15925 (prompt (concat (if prompt (concat prompt " ") "")
15926 (format "Date+time [%s]: " timestr)))
15927 ans (org-ans0 "") org-ans1 org-ans2 final)
15929 (cond
15930 (from-string (setq ans from-string))
15931 (org-read-date-popup-calendar
15932 (save-excursion
15933 (save-window-excursion
15934 (calendar)
15935 (org-eval-in-calendar '(setq cursor-type nil) t)
15936 (unwind-protect
15937 (progn
15938 (calendar-forward-day (- (time-to-days org-def)
15939 (calendar-absolute-from-gregorian
15940 (calendar-current-date))))
15941 (org-eval-in-calendar nil t)
15942 (let* ((old-map (current-local-map))
15943 (map (copy-keymap calendar-mode-map))
15944 (minibuffer-local-map
15945 (copy-keymap org-read-date-minibuffer-local-map)))
15946 (org-defkey map (kbd "RET") 'org-calendar-select)
15947 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15948 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15949 (unwind-protect
15950 (progn
15951 (use-local-map map)
15952 (setq org-read-date-inactive inactive)
15953 (add-hook 'post-command-hook 'org-read-date-display)
15954 (setq org-ans0 (read-string prompt default-input
15955 'org-read-date-history nil))
15956 ;; org-ans0: from prompt
15957 ;; org-ans1: from mouse click
15958 ;; org-ans2: from calendar motion
15959 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15960 (remove-hook 'post-command-hook 'org-read-date-display)
15961 (use-local-map old-map)
15962 (when org-read-date-overlay
15963 (delete-overlay org-read-date-overlay)
15964 (setq org-read-date-overlay nil)))))
15965 (bury-buffer "*Calendar*")))))
15967 (t ; Naked prompt only
15968 (unwind-protect
15969 (setq ans (read-string prompt default-input
15970 'org-read-date-history timestr))
15971 (when org-read-date-overlay
15972 (delete-overlay org-read-date-overlay)
15973 (setq org-read-date-overlay nil)))))
15975 (setq final (org-read-date-analyze ans org-def org-defdecode))
15977 (when org-read-date-analyze-forced-year
15978 (message "Year was forced into %s"
15979 (if org-read-date-force-compatible-dates
15980 "compatible range (1970-2037)"
15981 "range representable on this machine"))
15982 (ding))
15984 ;; One round trip to get rid of 34th of August and stuff like that....
15985 (setq final (decode-time (apply 'encode-time final)))
15987 (setq org-read-date-final-answer ans)
15989 (if to-time
15990 (apply 'encode-time final)
15991 (if (and (boundp 'org-time-was-given) org-time-was-given)
15992 (format "%04d-%02d-%02d %02d:%02d"
15993 (nth 5 final) (nth 4 final) (nth 3 final)
15994 (nth 2 final) (nth 1 final))
15995 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15997 (defvar org-def)
15998 (defvar org-defdecode)
15999 (defvar org-with-time)
16000 (defun org-read-date-display ()
16001 "Display the current date prompt interpretation in the minibuffer."
16002 (when org-read-date-display-live
16003 (when org-read-date-overlay
16004 (delete-overlay org-read-date-overlay))
16005 (when (minibufferp (current-buffer))
16006 (save-excursion
16007 (end-of-line 1)
16008 (while (not (equal (buffer-substring
16009 (max (point-min) (- (point) 4)) (point))
16010 " "))
16011 (insert " ")))
16012 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16013 " " (or org-ans1 org-ans2)))
16014 (org-end-time-was-given nil)
16015 (f (org-read-date-analyze ans org-def org-defdecode))
16016 (fmts (if org-dcst
16017 org-time-stamp-custom-formats
16018 org-time-stamp-formats))
16019 (fmt (if (or org-with-time
16020 (and (boundp 'org-time-was-given) org-time-was-given))
16021 (cdr fmts)
16022 (car fmts)))
16023 (txt (format-time-string fmt (apply 'encode-time f)))
16024 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16025 (txt (concat "=> " txt)))
16026 (when (and org-end-time-was-given
16027 (string-match org-plain-time-of-day-regexp txt))
16028 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16029 org-end-time-was-given
16030 (substring txt (match-end 0)))))
16031 (when org-read-date-analyze-futurep
16032 (setq txt (concat txt " (=>F)")))
16033 (setq org-read-date-overlay
16034 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16035 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16037 (defun org-read-date-analyze (ans org-def org-defdecode)
16038 "Analyze the combined answer of the date prompt."
16039 ;; FIXME: cleanup and comment
16040 (let ((nowdecode (decode-time (current-time)))
16041 delta deltan deltaw deltadef year month day
16042 hour minute second wday pm h2 m2 tl wday1
16043 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16044 (setq org-read-date-analyze-futurep nil
16045 org-read-date-analyze-forced-year nil)
16046 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16047 (setq ans "+0"))
16049 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16050 (setq ans (replace-match "" t t ans)
16051 deltan (car delta)
16052 deltaw (nth 1 delta)
16053 deltadef (nth 2 delta)))
16055 ;; Check if there is an iso week date in there. If yes, store the
16056 ;; info and postpone interpreting it until the rest of the parsing
16057 ;; is done.
16058 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16059 (setq iso-year (if (match-end 1)
16060 (org-small-year-to-year
16061 (string-to-number (match-string 1 ans))))
16062 iso-weekday (if (match-end 3)
16063 (string-to-number (match-string 3 ans)))
16064 iso-week (string-to-number (match-string 2 ans)))
16065 (setq ans (replace-match "" t t ans)))
16067 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16068 (when (string-match
16069 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16070 (setq year (if (match-end 2)
16071 (string-to-number (match-string 2 ans))
16072 (progn (setq kill-year t)
16073 (string-to-number (format-time-string "%Y"))))
16074 month (string-to-number (match-string 3 ans))
16075 day (string-to-number (match-string 4 ans)))
16076 (if (< year 100) (setq year (+ 2000 year)))
16077 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16078 t nil ans)))
16080 ;; Help matching dotted european dates
16081 (when (string-match
16082 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16083 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16084 (setq kill-year t)
16085 (string-to-number (format-time-string "%Y")))
16086 day (string-to-number (match-string 1 ans))
16087 month (string-to-number (match-string 2 ans))
16088 ans (replace-match (format "%04d-%02d-%02d" year month day)
16089 t nil ans)))
16091 ;; Help matching american dates, like 5/30 or 5/30/7
16092 (when (string-match
16093 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16094 (setq year (if (match-end 4)
16095 (string-to-number (match-string 4 ans))
16096 (progn (setq kill-year t)
16097 (string-to-number (format-time-string "%Y"))))
16098 month (string-to-number (match-string 1 ans))
16099 day (string-to-number (match-string 2 ans)))
16100 (if (< year 100) (setq year (+ 2000 year)))
16101 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16102 t nil ans)))
16103 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16104 ;; If there is a time with am/pm, and *no* time without it, we convert
16105 ;; so that matching will be successful.
16106 (loop for i from 1 to 2 do ; twice, for end time as well
16107 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16108 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16109 (setq hour (string-to-number (match-string 1 ans))
16110 minute (if (match-end 3)
16111 (string-to-number (match-string 3 ans))
16113 pm (equal ?p
16114 (string-to-char (downcase (match-string 4 ans)))))
16115 (if (and (= hour 12) (not pm))
16116 (setq hour 0)
16117 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16118 (setq ans (replace-match (format "%02d:%02d" hour minute)
16119 t t ans))))
16121 ;; Check if a time range is given as a duration
16122 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16123 (setq hour (string-to-number (match-string 1 ans))
16124 h2 (+ hour (string-to-number (match-string 3 ans)))
16125 minute (string-to-number (match-string 2 ans))
16126 m2 (+ minute (if (match-end 5) (string-to-number
16127 (match-string 5 ans))0)))
16128 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16129 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16130 t t ans)))
16132 ;; Check if there is a time range
16133 (when (boundp 'org-end-time-was-given)
16134 (setq org-time-was-given nil)
16135 (when (and (string-match org-plain-time-of-day-regexp ans)
16136 (match-end 8))
16137 (setq org-end-time-was-given (match-string 8 ans))
16138 (setq ans (concat (substring ans 0 (match-beginning 7))
16139 (substring ans (match-end 7))))))
16141 (setq tl (parse-time-string ans)
16142 day (or (nth 3 tl) (nth 3 org-defdecode))
16143 month (or (nth 4 tl)
16144 (if (and org-read-date-prefer-future
16145 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16146 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16147 (nth 4 org-defdecode)))
16148 year (or (and (not kill-year) (nth 5 tl))
16149 (if (and org-read-date-prefer-future
16150 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16151 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16152 (nth 5 org-defdecode)))
16153 hour (or (nth 2 tl) (nth 2 org-defdecode))
16154 minute (or (nth 1 tl) (nth 1 org-defdecode))
16155 second (or (nth 0 tl) 0)
16156 wday (nth 6 tl))
16158 (when (and (eq org-read-date-prefer-future 'time)
16159 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16160 (equal day (nth 3 nowdecode))
16161 (equal month (nth 4 nowdecode))
16162 (equal year (nth 5 nowdecode))
16163 (nth 2 tl)
16164 (or (< (nth 2 tl) (nth 2 nowdecode))
16165 (and (= (nth 2 tl) (nth 2 nowdecode))
16166 (nth 1 tl)
16167 (< (nth 1 tl) (nth 1 nowdecode)))))
16168 (setq day (1+ day)
16169 futurep t))
16171 ;; Special date definitions below
16172 (cond
16173 (iso-week
16174 ;; There was an iso week
16175 (require 'cal-iso)
16176 (setq futurep nil)
16177 (setq year (or iso-year year)
16178 day (or iso-weekday wday 1)
16179 wday nil ; to make sure that the trigger below does not match
16180 iso-date (calendar-gregorian-from-absolute
16181 (calendar-absolute-from-iso
16182 (list iso-week day year))))
16183 ; FIXME: Should we also push ISO weeks into the future?
16184 ; (when (and org-read-date-prefer-future
16185 ; (not iso-year)
16186 ; (< (calendar-absolute-from-gregorian iso-date)
16187 ; (time-to-days (current-time))))
16188 ; (setq year (1+ year)
16189 ; iso-date (calendar-gregorian-from-absolute
16190 ; (calendar-absolute-from-iso
16191 ; (list iso-week day year)))))
16192 (setq month (car iso-date)
16193 year (nth 2 iso-date)
16194 day (nth 1 iso-date)))
16195 (deltan
16196 (setq futurep nil)
16197 (unless deltadef
16198 (let ((now (decode-time (current-time))))
16199 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16200 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16201 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16202 ((equal deltaw "m") (setq month (+ month deltan)))
16203 ((equal deltaw "y") (setq year (+ year deltan)))))
16204 ((and wday (not (nth 3 tl)))
16205 ;; Weekday was given, but no day, so pick that day in the week
16206 ;; on or after the derived date.
16207 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16208 (unless (equal wday wday1)
16209 (setq day (+ day (% (- wday wday1 -7) 7))))))
16210 (if (and (boundp 'org-time-was-given)
16211 (nth 2 tl))
16212 (setq org-time-was-given t))
16213 (if (< year 100) (setq year (+ 2000 year)))
16214 ;; Check of the date is representable
16215 (if org-read-date-force-compatible-dates
16216 (progn
16217 (if (< year 1970)
16218 (setq year 1970 org-read-date-analyze-forced-year t))
16219 (if (> year 2037)
16220 (setq year 2037 org-read-date-analyze-forced-year t)))
16221 (condition-case nil
16222 (ignore (encode-time second minute hour day month year))
16223 (error
16224 (setq year (nth 5 org-defdecode))
16225 (setq org-read-date-analyze-forced-year t))))
16226 (setq org-read-date-analyze-futurep futurep)
16227 (list second minute hour day month year)))
16229 (defvar parse-time-weekdays)
16230 (defun org-read-date-get-relative (s today default)
16231 "Check string S for special relative date string.
16232 TODAY and DEFAULT are internal times, for today and for a default.
16233 Return shift list (N what def-flag)
16234 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16235 N is the number of WHATs to shift.
16236 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16237 the DEFAULT date rather than TODAY."
16238 (require 'parse-time)
16239 (when (and
16240 (string-match
16241 (concat
16242 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16243 "\\([0-9]+\\)?"
16244 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16245 "\\([ \t]\\|$\\)") s)
16246 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16247 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16248 (string-to-char (substring (match-string 1 s) -1))
16249 ?+))
16250 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16251 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16252 (what (if (match-end 3) (match-string 3 s) "d"))
16253 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16254 (date (if rel default today))
16255 (wday (nth 6 (decode-time date)))
16256 delta)
16257 (if wday1
16258 (progn
16259 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16260 (if (= dir ?-) (setq delta (- delta 7)))
16261 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16262 (list delta "d" rel))
16263 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16265 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16266 "Turn a user-specified date into the internal representation.
16267 The internal representation needed by the calendar is (month day year).
16268 This is a wrapper to handle the brain-dead convention in calendar that
16269 user function argument order change dependent on argument order."
16270 (if (boundp 'calendar-date-style)
16271 (cond
16272 ((eq calendar-date-style 'american)
16273 (list arg1 arg2 arg3))
16274 ((eq calendar-date-style 'european)
16275 (list arg2 arg1 arg3))
16276 ((eq calendar-date-style 'iso)
16277 (list arg2 arg3 arg1)))
16278 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16279 (if (org-bound-and-true-p european-calendar-style)
16280 (list arg2 arg1 arg3)
16281 (list arg1 arg2 arg3)))))
16283 (defun org-eval-in-calendar (form &optional keepdate)
16284 "Eval FORM in the calendar window and return to current window.
16285 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16286 otherwise stick to the current value of `org-ans2'."
16287 (let ((sf (selected-frame))
16288 (sw (selected-window)))
16289 (select-window (get-buffer-window "*Calendar*" t))
16290 (eval form)
16291 (when (and (not keepdate) (calendar-cursor-to-date))
16292 (let* ((date (calendar-cursor-to-date))
16293 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16294 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16295 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16296 (select-window sw)
16297 (org-select-frame-set-input-focus sf)))
16299 (defun org-calendar-select ()
16300 "Return to `org-read-date' with the date currently selected.
16301 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16302 (interactive)
16303 (when (calendar-cursor-to-date)
16304 (let* ((date (calendar-cursor-to-date))
16305 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16306 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16307 (if (active-minibuffer-window) (exit-minibuffer))))
16309 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16310 "Insert a date stamp for the date given by the internal TIME.
16311 WITH-HM means use the stamp format that includes the time of the day.
16312 INACTIVE means use square brackets instead of angular ones, so that the
16313 stamp will not contribute to the agenda.
16314 PRE and POST are optional strings to be inserted before and after the
16315 stamp.
16316 The command returns the inserted time stamp."
16317 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16318 stamp)
16319 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16320 (insert-before-markers (or pre ""))
16321 (when (listp extra)
16322 (setq extra (car extra))
16323 (if (and (stringp extra)
16324 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16325 (setq extra (format "-%02d:%02d"
16326 (string-to-number (match-string 1 extra))
16327 (string-to-number (match-string 2 extra))))
16328 (setq extra nil)))
16329 (when extra
16330 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16331 (insert-before-markers (setq stamp (format-time-string fmt time)))
16332 (insert-before-markers (or post ""))
16333 (setq org-last-inserted-timestamp stamp)))
16335 (defun org-toggle-time-stamp-overlays ()
16336 "Toggle the use of custom time stamp formats."
16337 (interactive)
16338 (setq org-display-custom-times (not org-display-custom-times))
16339 (unless org-display-custom-times
16340 (let ((p (point-min)) (bmp (buffer-modified-p)))
16341 (while (setq p (next-single-property-change p 'display))
16342 (if (and (get-text-property p 'display)
16343 (eq (get-text-property p 'face) 'org-date))
16344 (remove-text-properties
16345 p (setq p (next-single-property-change p 'display))
16346 '(display t))))
16347 (set-buffer-modified-p bmp)))
16348 (if (featurep 'xemacs)
16349 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16350 (org-restart-font-lock)
16351 (setq org-table-may-need-update t)
16352 (if org-display-custom-times
16353 (message "Time stamps are overlaid with custom format")
16354 (message "Time stamp overlays removed")))
16356 (defun org-display-custom-time (beg end)
16357 "Overlay modified time stamp format over timestamp between BEG and END."
16358 (let* ((ts (buffer-substring beg end))
16359 t1 w1 with-hm tf time str w2 (off 0))
16360 (save-match-data
16361 (setq t1 (org-parse-time-string ts t))
16362 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16363 (setq off (- (match-end 0) (match-beginning 0)))))
16364 (setq end (- end off))
16365 (setq w1 (- end beg)
16366 with-hm (and (nth 1 t1) (nth 2 t1))
16367 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16368 time (org-fix-decoded-time t1)
16369 str (org-add-props
16370 (format-time-string
16371 (substring tf 1 -1) (apply 'encode-time time))
16372 nil 'mouse-face 'highlight)
16373 w2 (length str))
16374 (if (not (= w2 w1))
16375 (add-text-properties (1+ beg) (+ 2 beg)
16376 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16377 (if (featurep 'xemacs)
16378 (progn
16379 (put-text-property beg end 'invisible t)
16380 (put-text-property beg end 'end-glyph (make-glyph str)))
16381 (put-text-property beg end 'display str))))
16383 (defun org-translate-time (string)
16384 "Translate all timestamps in STRING to custom format.
16385 But do this only if the variable `org-display-custom-times' is set."
16386 (when org-display-custom-times
16387 (save-match-data
16388 (let* ((start 0)
16389 (re org-ts-regexp-both)
16390 t1 with-hm inactive tf time str beg end)
16391 (while (setq start (string-match re string start))
16392 (setq beg (match-beginning 0)
16393 end (match-end 0)
16394 t1 (save-match-data
16395 (org-parse-time-string (substring string beg end) t))
16396 with-hm (and (nth 1 t1) (nth 2 t1))
16397 inactive (equal (substring string beg (1+ beg)) "[")
16398 tf (funcall (if with-hm 'cdr 'car)
16399 org-time-stamp-custom-formats)
16400 time (org-fix-decoded-time t1)
16401 str (format-time-string
16402 (concat
16403 (if inactive "[" "<") (substring tf 1 -1)
16404 (if inactive "]" ">"))
16405 (apply 'encode-time time))
16406 string (replace-match str t t string)
16407 start (+ start (length str)))))))
16408 string)
16410 (defun org-fix-decoded-time (time)
16411 "Set 0 instead of nil for the first 6 elements of time.
16412 Don't touch the rest."
16413 (let ((n 0))
16414 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16416 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16418 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16419 "Difference between TIMESTAMP-STRING and now in days.
16420 If SECONDS is non-nil, return the difference in seconds."
16421 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16422 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16423 (funcall fdiff (current-time)))))
16425 (defun org-deadline-close (timestamp-string &optional ndays)
16426 "Is the time in TIMESTAMP-STRING close to the current date?"
16427 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16428 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16429 (not (org-entry-is-done-p))))
16431 (defun org-get-wdays (ts &optional delay zero-delay)
16432 "Get the deadline lead time appropriate for timestring TS.
16433 When DELAY is non-nil, get the delay time for scheduled items
16434 instead of the deadline lead time. When ZERO-DELAY is non-nil
16435 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16436 don't try to find the delay cookie in the scheduled timestamp."
16437 (let ((tv (if delay org-scheduled-delay-days
16438 org-deadline-warning-days)))
16439 (cond
16440 ((or (and delay (< tv 0))
16441 (and delay zero-delay (<= tv 0))
16442 (and (not delay) (<= tv 0)))
16443 ;; Enforce this value no matter what
16444 (- tv))
16445 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16446 ;; lead time is specified.
16447 (floor (* (string-to-number (match-string 1 ts))
16448 (cdr (assoc (match-string 2 ts)
16449 '(("d" . 1) ("w" . 7)
16450 ("m" . 30.4) ("y" . 365.25)
16451 ("h" . 0.041667)))))))
16452 ;; go for the default.
16453 (t tv))))
16455 (defun org-calendar-select-mouse (ev)
16456 "Return to `org-read-date' with the date currently selected.
16457 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16458 (interactive "e")
16459 (mouse-set-point ev)
16460 (when (calendar-cursor-to-date)
16461 (let* ((date (calendar-cursor-to-date))
16462 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16463 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16464 (if (active-minibuffer-window) (exit-minibuffer))))
16466 (defun org-check-deadlines (ndays)
16467 "Check if there are any deadlines due or past due.
16468 A deadline is considered due if it happens within `org-deadline-warning-days'
16469 days from today's date. If the deadline appears in an entry marked DONE,
16470 it is not shown. The prefix arg NDAYS can be used to test that many
16471 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16472 (interactive "P")
16473 (let* ((org-warn-days
16474 (cond
16475 ((equal ndays '(4)) 100000)
16476 (ndays (prefix-numeric-value ndays))
16477 (t (abs org-deadline-warning-days))))
16478 (case-fold-search nil)
16479 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16480 (callback
16481 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16483 (message "%d deadlines past-due or due within %d days"
16484 (org-occur regexp nil callback)
16485 org-warn-days)))
16487 (defsubst org-re-timestamp (type)
16488 "Return a regexp for timestamp TYPE.
16489 Allowed values for TYPE are:
16491 all: all timestamps
16492 active: only active timestamps (<...>)
16493 inactive: only inactive timestamps ([...])
16494 scheduled: only scheduled timestamps
16495 deadline: only deadline timestamps
16497 When TYPE is nil, fall back on returning a regexp that matches
16498 both scheduled and deadline timestamps."
16499 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16500 ((eq type 'active) org-ts-regexp)
16501 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16502 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16503 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16504 ((eq type 'scheduled-or-deadline)
16505 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16507 (defun org-check-before-date (date)
16508 "Check if there are deadlines or scheduled entries before DATE."
16509 (interactive (list (org-read-date)))
16510 (let ((case-fold-search nil)
16511 (regexp (org-re-timestamp org-ts-type))
16512 (callback
16513 (lambda () (time-less-p
16514 (org-time-string-to-time (match-string 1))
16515 (org-time-string-to-time date)))))
16516 (message "%d entries before %s"
16517 (org-occur regexp nil callback) date)))
16519 (defun org-check-after-date (date)
16520 "Check if there are deadlines or scheduled entries after DATE."
16521 (interactive (list (org-read-date)))
16522 (let ((case-fold-search nil)
16523 (regexp (org-re-timestamp org-ts-type))
16524 (callback
16525 (lambda () (not
16526 (time-less-p
16527 (org-time-string-to-time (match-string 1))
16528 (org-time-string-to-time date))))))
16529 (message "%d entries after %s"
16530 (org-occur regexp nil callback) date)))
16532 (defun org-check-dates-range (start-date end-date)
16533 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16534 (interactive (list (org-read-date nil nil nil "Range starts")
16535 (org-read-date nil nil nil "Range end")))
16536 (let ((case-fold-search nil)
16537 (regexp (org-re-timestamp org-ts-type))
16538 (callback
16539 (lambda ()
16540 (let ((match (match-string 1)))
16541 (and
16542 (not (time-less-p
16543 (org-time-string-to-time match)
16544 (org-time-string-to-time start-date)))
16545 (time-less-p
16546 (org-time-string-to-time match)
16547 (org-time-string-to-time end-date)))))))
16548 (message "%d entries between %s and %s"
16549 (org-occur regexp nil callback) start-date end-date)))
16551 (defun org-evaluate-time-range (&optional to-buffer)
16552 "Evaluate a time range by computing the difference between start and end.
16553 Normally the result is just printed in the echo area, but with prefix arg
16554 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16555 If the time range is actually in a table, the result is inserted into the
16556 next column.
16557 For time difference computation, a year is assumed to be exactly 365
16558 days in order to avoid rounding problems."
16559 (interactive "P")
16561 (org-clock-update-time-maybe)
16562 (save-excursion
16563 (unless (org-at-date-range-p t)
16564 (goto-char (point-at-bol))
16565 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16566 (if (not (org-at-date-range-p t))
16567 (error "Not at a time-stamp range, and none found in current line")))
16568 (let* ((ts1 (match-string 1))
16569 (ts2 (match-string 2))
16570 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16571 (match-end (match-end 0))
16572 (time1 (org-time-string-to-time ts1))
16573 (time2 (org-time-string-to-time ts2))
16574 (t1 (org-float-time time1))
16575 (t2 (org-float-time time2))
16576 (diff (abs (- t2 t1)))
16577 (negative (< (- t2 t1) 0))
16578 ;; (ys (floor (* 365 24 60 60)))
16579 (ds (* 24 60 60))
16580 (hs (* 60 60))
16581 (fy "%dy %dd %02d:%02d")
16582 (fy1 "%dy %dd")
16583 (fd "%dd %02d:%02d")
16584 (fd1 "%dd")
16585 (fh "%02d:%02d")
16586 y d h m align)
16587 (if havetime
16588 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16590 d (floor (/ diff ds)) diff (mod diff ds)
16591 h (floor (/ diff hs)) diff (mod diff hs)
16592 m (floor (/ diff 60)))
16593 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16595 d (floor (+ (/ diff ds) 0.5))
16596 h 0 m 0))
16597 (if (not to-buffer)
16598 (message "%s" (org-make-tdiff-string y d h m))
16599 (if (org-at-table-p)
16600 (progn
16601 (goto-char match-end)
16602 (setq align t)
16603 (and (looking-at " *|") (goto-char (match-end 0))))
16604 (goto-char match-end))
16605 (if (looking-at
16606 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16607 (replace-match ""))
16608 (if negative (insert " -"))
16609 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16610 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16611 (insert " " (format fh h m))))
16612 (if align (org-table-align))
16613 (message "Time difference inserted")))))
16615 (defun org-make-tdiff-string (y d h m)
16616 (let ((fmt "")
16617 (l nil))
16618 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16619 l (push y l)))
16620 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16621 l (push d l)))
16622 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16623 l (push h l)))
16624 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16625 l (push m l)))
16626 (apply 'format fmt (nreverse l))))
16628 (defun org-time-string-to-time (s &optional buffer pos)
16629 "Convert a timestamp string into internal time."
16630 (condition-case errdata
16631 (apply 'encode-time (org-parse-time-string s))
16632 (error (error "Bad timestamp `%s'%s\nError was: %s"
16633 s (if (not (and buffer pos))
16635 (format " at %d in buffer `%s'" pos buffer))
16636 (cdr errdata)))))
16638 (defun org-time-string-to-seconds (s)
16639 "Convert a timestamp string to a number of seconds."
16640 (org-float-time (org-time-string-to-time s)))
16642 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16643 "Convert a time stamp to an absolute day number.
16644 If there is a specifier for a cyclic time stamp, get the closest
16645 date to DAYNR.
16646 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16647 The variable date is bound by the calendar when this is called."
16648 (cond
16649 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16650 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16651 daynr
16652 (+ daynr 1000)))
16653 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16654 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16655 (time-to-days (current-time))) (match-string 0 s)
16656 prefer show-all))
16657 (t (time-to-days
16658 (condition-case errdata
16659 (apply 'encode-time (org-parse-time-string s))
16660 (error (error "Bad timestamp `%s'%s\nError was: %s"
16661 s (if (not (and buffer pos))
16663 (format " at %d in buffer `%s'" pos buffer))
16664 (cdr errdata))))))))
16666 (defun org-days-to-iso-week (days)
16667 "Return the iso week number."
16668 (require 'cal-iso)
16669 (car (calendar-iso-from-absolute days)))
16671 (defun org-small-year-to-year (year)
16672 "Convert 2-digit years into 4-digit years.
16673 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16674 The year 2000 cannot be abbreviated. Any year larger than 99
16675 is returned unchanged."
16676 (if (< year 38)
16677 (setq year (+ 2000 year))
16678 (if (< year 100)
16679 (setq year (+ 1900 year))))
16680 year)
16682 (defun org-time-from-absolute (d)
16683 "Return the time corresponding to date D.
16684 D may be an absolute day number, or a calendar-type list (month day year)."
16685 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16686 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16688 (defun org-calendar-holiday ()
16689 "List of holidays, for Diary display in Org-mode."
16690 (require 'holidays)
16691 (let ((hl (funcall
16692 (if (fboundp 'calendar-check-holidays)
16693 'calendar-check-holidays 'check-calendar-holidays) date)))
16694 (if hl (mapconcat 'identity hl "; "))))
16696 (defun org-diary-sexp-entry (sexp entry date)
16697 "Process a SEXP diary ENTRY for DATE."
16698 (require 'diary-lib)
16699 (let ((result (if calendar-debug-sexp
16700 (let ((stack-trace-on-error t))
16701 (eval (car (read-from-string sexp))))
16702 (condition-case nil
16703 (eval (car (read-from-string sexp)))
16704 (error
16705 (beep)
16706 (message "Bad sexp at line %d in %s: %s"
16707 (org-current-line)
16708 (buffer-file-name) sexp)
16709 (sleep-for 2))))))
16710 (cond ((stringp result) (split-string result "; "))
16711 ((and (consp result)
16712 (not (consp (cdr result)))
16713 (stringp (cdr result))) (cdr result))
16714 ((and (consp result)
16715 (stringp (car result))) result)
16716 (result entry))))
16718 (defun org-diary-to-ical-string (frombuf)
16719 "Get iCalendar entries from diary entries in buffer FROMBUF.
16720 This uses the icalendar.el library."
16721 (let* ((tmpdir (if (featurep 'xemacs)
16722 (temp-directory)
16723 temporary-file-directory))
16724 (tmpfile (make-temp-name
16725 (expand-file-name "orgics" tmpdir)))
16726 buf rtn b e)
16727 (with-current-buffer frombuf
16728 (icalendar-export-region (point-min) (point-max) tmpfile)
16729 (setq buf (find-buffer-visiting tmpfile))
16730 (set-buffer buf)
16731 (goto-char (point-min))
16732 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16733 (setq b (match-beginning 0)))
16734 (goto-char (point-max))
16735 (if (re-search-backward "^END:VEVENT" nil t)
16736 (setq e (match-end 0)))
16737 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16738 (kill-buffer buf)
16739 (delete-file tmpfile)
16740 rtn))
16742 (defun org-closest-date (start current change prefer show-all)
16743 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16744 When PREFER is `past', return a date that is either CURRENT or past.
16745 When PREFER is `future', return a date that is either CURRENT or future.
16746 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16747 ;; Make the proper lists from the dates
16748 (catch 'exit
16749 (let ((a1 '(("h" . hour)
16750 ("d" . day)
16751 ("w" . week)
16752 ("m" . month)
16753 ("y" . year)))
16754 (shour (nth 2 (org-parse-time-string start)))
16755 dn dw sday cday n1 n2 n0
16756 d m y y1 y2 date1 date2 nmonths nm ny m2)
16758 (setq start (org-date-to-gregorian start)
16759 current (org-date-to-gregorian
16760 (if show-all
16761 current
16762 (time-to-days (current-time))))
16763 sday (calendar-absolute-from-gregorian start)
16764 cday (calendar-absolute-from-gregorian current))
16766 (if (<= cday sday) (throw 'exit sday))
16768 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16769 (setq dn (string-to-number (match-string 1 change))
16770 dw (cdr (assoc (match-string 2 change) a1)))
16771 (error "Invalid change specifier: %s" change))
16772 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16773 (cond
16774 ((eq dw 'hour)
16775 (let ((missing-hours
16776 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16777 dn)))
16778 (setq n1 (if (zerop missing-hours) cday
16779 (- cday (1+ (floor (/ missing-hours 24)))))
16780 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16781 ((eq dw 'day)
16782 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16783 n2 (+ n1 dn)))
16784 ((eq dw 'year)
16785 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16786 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16787 (setq date1 (list m d y1)
16788 n1 (calendar-absolute-from-gregorian date1)
16789 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16790 n2 (calendar-absolute-from-gregorian date2)))
16791 ((eq dw 'month)
16792 ;; approx number of month between the two dates
16793 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16794 ;; How often does dn fit in there?
16795 (setq d (nth 1 start) m (car start) y (nth 2 start)
16796 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16797 m (+ m nm)
16798 ny (floor (/ m 12))
16799 y (+ y ny)
16800 m (- m (* ny 12)))
16801 (while (> m 12) (setq m (- m 12) y (1+ y)))
16802 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16803 (setq m2 (+ m dn) y2 y)
16804 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16805 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16806 (while (<= n2 cday)
16807 (setq n1 n2 m m2 y y2)
16808 (setq m2 (+ m dn) y2 y)
16809 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16810 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16811 ;; Make sure n1 is the earlier date
16812 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16813 (if show-all
16814 (cond
16815 ((eq prefer 'past) (if (= cday n2) n2 n1))
16816 ((eq prefer 'future) (if (= cday n1) n1 n2))
16817 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16818 (cond
16819 ((eq prefer 'past) (if (= cday n2) n2 n1))
16820 ((eq prefer 'future) (if (= cday n1) n1 n2))
16821 (t (if (= cday n1) n1 n2)))))))
16823 (defun org-date-to-gregorian (date)
16824 "Turn any specification of DATE into a Gregorian date for the calendar."
16825 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16826 ((and (listp date) (= (length date) 3)) date)
16827 ((stringp date)
16828 (setq date (org-parse-time-string date))
16829 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16830 ((listp date)
16831 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16833 (defun org-parse-time-string (s &optional nodefault)
16834 "Parse the standard Org-mode time string.
16835 This should be a lot faster than the normal `parse-time-string'.
16836 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16837 hour and minute fields will be nil if not given."
16838 (cond ((string-match org-ts-regexp0 s)
16839 (list 0
16840 (if (or (match-beginning 8) (not nodefault))
16841 (string-to-number (or (match-string 8 s) "0")))
16842 (if (or (match-beginning 7) (not nodefault))
16843 (string-to-number (or (match-string 7 s) "0")))
16844 (string-to-number (match-string 4 s))
16845 (string-to-number (match-string 3 s))
16846 (string-to-number (match-string 2 s))
16847 nil nil nil))
16848 ((string-match "^<[^>]+>$" s)
16849 (decode-time (seconds-to-time (org-matcher-time s))))
16850 (t (error "Not a standard Org-mode time string: %s" s))))
16852 (defun org-timestamp-up (&optional arg)
16853 "Increase the date item at the cursor by one.
16854 If the cursor is on the year, change the year. If it is on the month,
16855 the day or the time, change that.
16856 With prefix ARG, change by that many units."
16857 (interactive "p")
16858 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16860 (defun org-timestamp-down (&optional arg)
16861 "Decrease the date item at the cursor by one.
16862 If the cursor is on the year, change the year. If it is on the month,
16863 the day or the time, change that.
16864 With prefix ARG, change by that many units."
16865 (interactive "p")
16866 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16868 (defun org-timestamp-up-day (&optional arg)
16869 "Increase the date in the time stamp by one day.
16870 With prefix ARG, change that many days."
16871 (interactive "p")
16872 (if (and (not (org-at-timestamp-p t))
16873 (org-at-heading-p))
16874 (org-todo 'up)
16875 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16877 (defun org-timestamp-down-day (&optional arg)
16878 "Decrease the date in the time stamp by one day.
16879 With prefix ARG, change that many days."
16880 (interactive "p")
16881 (if (and (not (org-at-timestamp-p t))
16882 (org-at-heading-p))
16883 (org-todo 'down)
16884 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16886 (defun org-at-timestamp-p (&optional inactive-ok)
16887 "Determine if the cursor is in or at a timestamp."
16888 (interactive)
16889 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16890 (pos (point))
16891 (ans (or (looking-at tsr)
16892 (save-excursion
16893 (skip-chars-backward "^[<\n\r\t")
16894 (if (> (point) (point-min)) (backward-char 1))
16895 (and (looking-at tsr)
16896 (> (- (match-end 0) pos) -1))))))
16897 (and ans
16898 (boundp 'org-ts-what)
16899 (setq org-ts-what
16900 (cond
16901 ((= pos (match-beginning 0)) 'bracket)
16902 ;; Point is considered to be "on the bracket" whether
16903 ;; it's really on it or right after it.
16904 ((= pos (1- (match-end 0))) 'bracket)
16905 ((= pos (match-end 0)) 'after)
16906 ((org-pos-in-match-range pos 2) 'year)
16907 ((org-pos-in-match-range pos 3) 'month)
16908 ((org-pos-in-match-range pos 7) 'hour)
16909 ((org-pos-in-match-range pos 8) 'minute)
16910 ((or (org-pos-in-match-range pos 4)
16911 (org-pos-in-match-range pos 5)) 'day)
16912 ((and (> pos (or (match-end 8) (match-end 5)))
16913 (< pos (match-end 0)))
16914 (- pos (or (match-end 8) (match-end 5))))
16915 (t 'day))))
16916 ans))
16918 (defun org-toggle-timestamp-type ()
16919 "Toggle the type (<active> or [inactive]) of a time stamp."
16920 (interactive)
16921 (when (org-at-timestamp-p t)
16922 (let ((beg (match-beginning 0)) (end (match-end 0))
16923 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16924 (save-excursion
16925 (goto-char beg)
16926 (while (re-search-forward "[][<>]" end t)
16927 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16928 t t)))
16929 (message "Timestamp is now %sactive"
16930 (if (equal (char-after beg) ?<) "" "in")))))
16932 (defun org-at-clock-log-p nil
16933 "Is the cursor on the clock log line?"
16934 (save-excursion
16935 (move-beginning-of-line 1)
16936 (looking-at "^[ \t]*CLOCK:")))
16938 (defvar org-clock-history) ; defined in org-clock.el
16939 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16940 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16941 "Change the date in the time stamp at point.
16942 The date will be changed by N times WHAT. WHAT can be `day', `month',
16943 `year', `minute', `second'. If WHAT is not given, the cursor position
16944 in the timestamp determines what will be changed.
16945 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16946 (let ((origin (point)) origin-cat
16947 with-hm inactive
16948 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16949 org-ts-what
16950 extra rem
16951 ts time time0 fixnext clrgx)
16952 (if (not (org-at-timestamp-p t))
16953 (error "Not at a timestamp"))
16954 (if (and (not what) (eq org-ts-what 'bracket))
16955 (org-toggle-timestamp-type)
16956 ;; Point isn't on brackets. Remember the part of the time-stamp
16957 ;; the point was in. Indeed, size of time-stamps may change,
16958 ;; but point must be kept in the same category nonetheless.
16959 (setq origin-cat org-ts-what)
16960 (if (and (not what) (not (eq org-ts-what 'day))
16961 org-display-custom-times
16962 (get-text-property (point) 'display)
16963 (not (get-text-property (1- (point)) 'display)))
16964 (setq org-ts-what 'day))
16965 (setq org-ts-what (or what org-ts-what)
16966 inactive (= (char-after (match-beginning 0)) ?\[)
16967 ts (match-string 0))
16968 (replace-match "")
16969 (when (string-match
16970 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16972 (setq extra (match-string 1 ts))
16973 (if suppress-tmp-delay
16974 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16975 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16976 (setq with-hm t))
16977 (setq time0 (org-parse-time-string ts))
16978 (when (and updown
16979 (eq org-ts-what 'minute)
16980 (not current-prefix-arg))
16981 ;; This looks like s-up and s-down. Change by one rounding step.
16982 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16983 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16984 (setcar (cdr time0) (+ (nth 1 time0)
16985 (if (> n 0) (- rem) (- dm rem))))))
16986 (setq time
16987 (encode-time (or (car time0) 0)
16988 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16989 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16990 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16991 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16992 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16993 (nthcdr 6 time0)))
16994 (when (and (member org-ts-what '(hour minute))
16995 extra
16996 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16997 (setq extra (org-modify-ts-extra
16998 extra
16999 (if (eq org-ts-what 'hour) 2 5)
17000 n dm)))
17001 (when (integerp org-ts-what)
17002 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17003 (if (eq what 'calendar)
17004 (let ((cal-date (org-get-date-from-calendar)))
17005 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17006 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17007 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17008 (setcar time0 (or (car time0) 0))
17009 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17010 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17011 (setq time (apply 'encode-time time0))))
17012 ;; Insert the new time-stamp, and ensure point stays in the same
17013 ;; category as before (i.e. not after the last position in that
17014 ;; category).
17015 (let ((pos (point)))
17016 ;; Stay before inserted string. `save-excursion' is of no use.
17017 (setq org-last-changed-timestamp
17018 (org-insert-time-stamp time with-hm inactive nil nil extra))
17019 (goto-char pos))
17020 (save-match-data
17021 (looking-at org-ts-regexp3)
17022 (goto-char (cond
17023 ;; `day' category ends before `hour' if any, or at
17024 ;; the end of the day name.
17025 ((eq origin-cat 'day)
17026 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17027 ((eq origin-cat 'hour) (min (match-end 7) origin))
17028 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17029 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17030 ;; `year' and `month' have both fixed size: point
17031 ;; couldn't have moved into another part.
17032 (t origin))))
17033 ;; Update clock if on a CLOCK line.
17034 (org-clock-update-time-maybe)
17035 ;; Maybe adjust the closest clock in `org-clock-history'
17036 (when org-clock-adjust-closest
17037 (if (not (and (org-at-clock-log-p)
17038 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17039 org-clock-history))))))
17040 (message "No clock to adjust")
17041 (cond ((save-excursion ; fix previous clock?
17042 (re-search-backward org-ts-regexp0 nil t)
17043 (org-looking-back (concat org-clock-string " \\[")))
17044 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17045 ((save-excursion ; fix next clock?
17046 (re-search-backward org-ts-regexp0 nil t)
17047 (looking-at (concat org-ts-regexp0 "\\] =>")))
17048 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17049 (save-window-excursion
17050 ;; Find closest clock to point, adjust the previous/next one in history
17051 (let* ((p (save-excursion (org-back-to-heading t)))
17052 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17053 (clfixnth
17054 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17055 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17056 (if (not clfixpos)
17057 (message "No clock to adjust")
17058 (save-excursion
17059 (org-goto-marker-or-bmk clfixpos)
17060 (org-show-subtree)
17061 (when (re-search-forward clrgx nil t)
17062 (goto-char (match-beginning 1))
17063 (let (org-clock-adjust-closest)
17064 (org-timestamp-change n org-ts-what updown))
17065 (message "Clock adjusted in %s for heading: %s"
17066 (file-name-nondirectory (buffer-file-name))
17067 (org-get-heading t t)))))))))
17068 ;; Try to recenter the calendar window, if any.
17069 (if (and org-calendar-follow-timestamp-change
17070 (get-buffer-window "*Calendar*" t)
17071 (memq org-ts-what '(day month year)))
17072 (org-recenter-calendar (time-to-days time))))))
17074 (defun org-modify-ts-extra (s pos n dm)
17075 "Change the different parts of the lead-time and repeat fields in timestamp."
17076 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17077 ng h m new rem)
17078 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17079 (cond
17080 ((or (org-pos-in-match-range pos 2)
17081 (org-pos-in-match-range pos 3))
17082 (setq m (string-to-number (match-string 3 s))
17083 h (string-to-number (match-string 2 s)))
17084 (if (org-pos-in-match-range pos 2)
17085 (setq h (+ h n))
17086 (setq n (* dm (org-no-warnings (signum n))))
17087 (when (not (= 0 (setq rem (% m dm))))
17088 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17089 (setq m (+ m n)))
17090 (if (< m 0) (setq m (+ m 60) h (1- h)))
17091 (if (> m 59) (setq m (- m 60) h (1+ h)))
17092 (setq h (min 24 (max 0 h)))
17093 (setq ng 1 new (format "-%02d:%02d" h m)))
17094 ((org-pos-in-match-range pos 6)
17095 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17096 ((org-pos-in-match-range pos 5)
17097 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17099 ((org-pos-in-match-range pos 9)
17100 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17101 ((org-pos-in-match-range pos 8)
17102 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17104 (when ng
17105 (setq s (concat
17106 (substring s 0 (match-beginning ng))
17108 (substring s (match-end ng))))))
17111 (defun org-recenter-calendar (date)
17112 "If the calendar is visible, recenter it to DATE."
17113 (let ((cwin (get-buffer-window "*Calendar*" t)))
17114 (when cwin
17115 (let ((calendar-move-hook nil))
17116 (with-selected-window cwin
17117 (calendar-goto-date (if (listp date) date
17118 (calendar-gregorian-from-absolute date))))))))
17120 (defun org-goto-calendar (&optional arg)
17121 "Go to the Emacs calendar at the current date.
17122 If there is a time stamp in the current line, go to that date.
17123 A prefix ARG can be used to force the current date."
17124 (interactive "P")
17125 (let ((tsr org-ts-regexp) diff
17126 (calendar-move-hook nil)
17127 (calendar-view-holidays-initially-flag nil)
17128 (calendar-view-diary-initially-flag nil))
17129 (if (or (org-at-timestamp-p)
17130 (save-excursion
17131 (beginning-of-line 1)
17132 (looking-at (concat ".*" tsr))))
17133 (let ((d1 (time-to-days (current-time)))
17134 (d2 (time-to-days
17135 (org-time-string-to-time (match-string 1)))))
17136 (setq diff (- d2 d1))))
17137 (calendar)
17138 (calendar-goto-today)
17139 (if (and diff (not arg)) (calendar-forward-day diff))))
17141 (defun org-get-date-from-calendar ()
17142 "Return a list (month day year) of date at point in calendar."
17143 (with-current-buffer "*Calendar*"
17144 (save-match-data
17145 (calendar-cursor-to-date))))
17147 (defun org-date-from-calendar ()
17148 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17149 If there is already a time stamp at the cursor position, update it."
17150 (interactive)
17151 (if (org-at-timestamp-p t)
17152 (org-timestamp-change 0 'calendar)
17153 (let ((cal-date (org-get-date-from-calendar)))
17154 (org-insert-time-stamp
17155 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17157 (defcustom org-effort-durations
17158 `(("h" . 60)
17159 ("d" . ,(* 60 8))
17160 ("w" . ,(* 60 8 5))
17161 ("m" . ,(* 60 8 5 4))
17162 ("y" . ,(* 60 8 5 40)))
17163 "Conversion factor to minutes for an effort modifier.
17165 Each entry has the form (MODIFIER . MINUTES).
17167 In an effort string, a number followed by MODIFIER is multiplied
17168 by the specified number of MINUTES to obtain an effort in
17169 minutes.
17171 For example, if the value of this variable is ((\"hours\" . 60)), then an
17172 effort string \"2hours\" is equivalent to 120 minutes."
17173 :group 'org-agenda
17174 :version "24.1"
17175 :type '(alist :key-type (string :tag "Modifier")
17176 :value-type (number :tag "Minutes")))
17178 (defun org-minutes-to-clocksum-string (m)
17179 "Format number of minutes as a clocksum string.
17180 The format is determined by `org-time-clocksum-format',
17181 `org-time-clocksum-use-fractional' and
17182 `org-time-clocksum-fractional-format' and
17183 `org-time-clocksum-use-effort-durations'."
17184 (let ((clocksum "") h d w mo y fmt n)
17185 (setq h (if org-time-clocksum-use-effort-durations
17186 (cdr (assoc "h" org-effort-durations)) 60)
17187 d (if org-time-clocksum-use-effort-durations
17188 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17189 w (if org-time-clocksum-use-effort-durations
17190 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17191 mo (if org-time-clocksum-use-effort-durations
17192 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17193 y (if org-time-clocksum-use-effort-durations
17194 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17195 ;; fractional format
17196 (if org-time-clocksum-use-fractional
17197 (cond
17198 ;; single format string
17199 ((stringp org-time-clocksum-fractional-format)
17200 (format org-time-clocksum-fractional-format (/ m (float h))))
17201 ;; choice of fractional formats for different time units
17202 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17203 (> (/ (truncate m) (* y d h)) 0))
17204 (format fmt (/ m (* y d (float h)))))
17205 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17206 (> (/ (truncate m) (* mo d h)) 0))
17207 (format fmt (/ m (* mo d (float h)))))
17208 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17209 (> (/ (truncate m) (* w d h)) 0))
17210 (format fmt (/ m (* w d (float h)))))
17211 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17212 (> (/ (truncate m) (* d h)) 0))
17213 (format fmt (/ m (* d (float h)))))
17214 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17215 (> (/ (truncate m) h) 0))
17216 (format fmt (/ m (float h))))
17217 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17218 (format fmt m))
17219 ;; fall back to smallest time unit with a format
17220 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17221 (format fmt (/ m (float h))))
17222 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17223 (format fmt (/ m (* d (float h)))))
17224 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17225 (format fmt (/ m (* w d (float h)))))
17226 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17227 (format fmt (/ m (* mo d (float h)))))
17228 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17229 (format fmt (/ m (* y d (float h))))))
17230 ;; standard (non-fractional) format, with single format string
17231 (if (stringp org-time-clocksum-format)
17232 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17233 ;; separate formats components
17234 (and (setq fmt (plist-get org-time-clocksum-format :years))
17235 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17236 (plist-get org-time-clocksum-format :require-years))
17237 (setq clocksum (concat clocksum (format fmt n))
17238 m (- m (* n y d h))))
17239 (and (setq fmt (plist-get org-time-clocksum-format :months))
17240 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17241 (plist-get org-time-clocksum-format :require-months))
17242 (setq clocksum (concat clocksum (format fmt n))
17243 m (- m (* n mo d h))))
17244 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17245 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17246 (plist-get org-time-clocksum-format :require-weeks))
17247 (setq clocksum (concat clocksum (format fmt n))
17248 m (- m (* n w d h))))
17249 (and (setq fmt (plist-get org-time-clocksum-format :days))
17250 (or (> (setq n (/ (truncate m) (* d h))) 0)
17251 (plist-get org-time-clocksum-format :require-days))
17252 (setq clocksum (concat clocksum (format fmt n))
17253 m (- m (* n d h))))
17254 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17255 (or (> (setq n (/ (truncate m) h)) 0)
17256 (plist-get org-time-clocksum-format :require-hours))
17257 (setq clocksum (concat clocksum (format fmt n))
17258 m (- m (* n h))))
17259 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17260 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17261 (setq clocksum (concat clocksum (format fmt m))))
17262 ;; return formatted time duration
17263 clocksum))))
17265 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17266 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17267 "Org mode version 8.0")
17269 (defun org-hours-to-clocksum-string (n)
17270 (org-minutes-to-clocksum-string (* n 60)))
17272 (defun org-hh:mm-string-to-minutes (s)
17273 "Convert a string H:MM to a number of minutes.
17274 If the string is just a number, interpret it as minutes.
17275 In fact, the first hh:mm or number in the string will be taken,
17276 there can be extra stuff in the string.
17277 If no number is found, the return value is 0."
17278 (cond
17279 ((integerp s) s)
17280 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17281 (+ (* (string-to-number (match-string 1 s)) 60)
17282 (string-to-number (match-string 2 s))))
17283 ((string-match "\\([0-9]+\\)" s)
17284 (string-to-number (match-string 1 s)))
17285 (t 0)))
17287 (defcustom org-image-actual-width t
17288 "Should we use the actual width of images when inlining them?
17290 When set to `t', always use the image width.
17292 When set to a number, use imagemagick (when available) to set
17293 the image's width to this value.
17295 When set to a number in a list, try to get the width from the
17296 #+ATTR.* keyword if it matches a width specification like
17297 width=\"[0-9]+\", and fall back on that number if none is found.
17299 When set to nil, try to get the width from an #+ATTR.* keyword
17300 and fall back on the original width if none is found.
17302 This requires Emacs >= 24.1, build with imagemagick support."
17303 :group 'org-appearance
17304 :version "24.4"
17305 :package-version '(Org . "8.0")
17306 :type '(choice
17307 (const :tag "Use the image width" t)
17308 (integer :tag "Use a number of pixels")
17309 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17310 (const :tag "Use #+ATTR* or don't resize" nil)))
17312 (defcustom org-agenda-inhibit-startup nil
17313 "Inhibit startup when preparing agenda buffers.
17314 When this variable is `t' (the default), the initialization of
17315 the Org agenda buffers is inhibited: e.g. the visibility state
17316 is not set, the tables are not re-aligned, etc."
17317 :type 'boolean
17318 :version "24.3"
17319 :group 'org-agenda)
17321 (defun org-duration-string-to-minutes (s &optional output-to-string)
17322 "Convert a duration string S to minutes.
17324 A bare number is interpreted as minutes, modifiers can be set by
17325 customizing `org-effort-durations' (which see).
17327 Entries containing a colon are interpreted as H:MM by
17328 `org-hh:mm-string-to-minutes'."
17329 (let ((result 0)
17330 (re (concat "\\([0-9.]+\\) *\\("
17331 (regexp-opt (mapcar 'car org-effort-durations))
17332 "\\)")))
17333 (while (string-match re s)
17334 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17335 (string-to-number (match-string 1 s))))
17336 (setq s (replace-match "" nil t s)))
17337 (setq result (floor result))
17338 (incf result (org-hh:mm-string-to-minutes s))
17339 (if output-to-string (number-to-string result) result)))
17341 ;;;; Files
17343 (defun org-save-all-org-buffers ()
17344 "Save all Org-mode buffers without user confirmation."
17345 (interactive)
17346 (message "Saving all Org-mode buffers...")
17347 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17348 (when (featurep 'org-id) (org-id-locations-save))
17349 (message "Saving all Org-mode buffers... done"))
17351 (defun org-revert-all-org-buffers ()
17352 "Revert all Org-mode buffers.
17353 Prompt for confirmation when there are unsaved changes.
17354 Be sure you know what you are doing before letting this function
17355 overwrite your changes.
17357 This function is useful in a setup where one tracks org files
17358 with a version control system, to revert on one machine after pulling
17359 changes from another. I believe the procedure must be like this:
17361 1. M-x org-save-all-org-buffers
17362 2. Pull changes from the other machine, resolve conflicts
17363 3. M-x org-revert-all-org-buffers"
17364 (interactive)
17365 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17366 (error "Abort"))
17367 (save-excursion
17368 (save-window-excursion
17369 (mapc
17370 (lambda (b)
17371 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17372 (with-current-buffer b buffer-file-name))
17373 (org-pop-to-buffer-same-window b)
17374 (revert-buffer t 'no-confirm)))
17375 (buffer-list))
17376 (when (and (featurep 'org-id) org-id-track-globally)
17377 (org-id-locations-load)))))
17379 ;;;; Agenda files
17381 ;;;###autoload
17382 (defun org-switchb (&optional arg)
17383 "Switch between Org buffers.
17384 With one prefix argument, restrict available buffers to files.
17385 With two prefix arguments, restrict available buffers to agenda files.
17387 Defaults to `iswitchb' for buffer name completion.
17388 Set `org-completion-use-ido' to make it use ido instead."
17389 (interactive "P")
17390 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17391 ((equal arg '(16)) (org-buffer-list 'agenda))
17392 (t (org-buffer-list))))
17393 (org-completion-use-iswitchb org-completion-use-iswitchb)
17394 (org-completion-use-ido org-completion-use-ido))
17395 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17396 (setq org-completion-use-iswitchb t))
17397 (org-pop-to-buffer-same-window
17398 (org-icompleting-read "Org buffer: "
17399 (mapcar 'list (mapcar 'buffer-name blist))
17400 nil t))))
17402 ;;; Define some older names previously used for this functionality
17403 ;;;###autoload
17404 (defalias 'org-ido-switchb 'org-switchb)
17405 ;;;###autoload
17406 (defalias 'org-iswitchb 'org-switchb)
17408 (defun org-buffer-list (&optional predicate exclude-tmp)
17409 "Return a list of Org buffers.
17410 PREDICATE can be `export', `files' or `agenda'.
17412 export restrict the list to Export buffers.
17413 files restrict the list to buffers visiting Org files.
17414 agenda restrict the list to buffers visiting agenda files.
17416 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17417 (let* ((bfn nil)
17418 (agenda-files (and (eq predicate 'agenda)
17419 (mapcar 'file-truename (org-agenda-files t))))
17420 (filter
17421 (cond
17422 ((eq predicate 'files)
17423 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17424 ((eq predicate 'export)
17425 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17426 ((eq predicate 'agenda)
17427 (lambda (b)
17428 (with-current-buffer b
17429 (and (derived-mode-p 'org-mode)
17430 (setq bfn (buffer-file-name b))
17431 (member (file-truename bfn) agenda-files)))))
17432 (t (lambda (b) (with-current-buffer b
17433 (or (derived-mode-p 'org-mode)
17434 (string-match "\*Org .*Export"
17435 (buffer-name b)))))))))
17436 (delq nil
17437 (mapcar
17438 (lambda(b)
17439 (if (and (funcall filter b)
17440 (or (not exclude-tmp)
17441 (not (string-match "tmp" (buffer-name b)))))
17443 nil))
17444 (buffer-list)))))
17446 (defun org-agenda-files (&optional unrestricted archives)
17447 "Get the list of agenda files.
17448 Optional UNRESTRICTED means return the full list even if a restriction
17449 is currently in place.
17450 When ARCHIVES is t, include all archive files that are really being
17451 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17452 `org-agenda-archives-mode' is t."
17453 (let ((files
17454 (cond
17455 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17456 ((stringp org-agenda-files) (org-read-agenda-file-list))
17457 ((listp org-agenda-files) org-agenda-files)
17458 (t (error "Invalid value of `org-agenda-files'")))))
17459 (setq files (apply 'append
17460 (mapcar (lambda (f)
17461 (if (file-directory-p f)
17462 (directory-files
17463 f t org-agenda-file-regexp)
17464 (list f)))
17465 files)))
17466 (when org-agenda-skip-unavailable-files
17467 (setq files (delq nil
17468 (mapcar (function
17469 (lambda (file)
17470 (and (file-readable-p file) file)))
17471 files))))
17472 (when (or (eq archives t)
17473 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17474 (setq files (org-add-archive-files files)))
17475 files))
17477 (defun org-agenda-file-p (&optional file)
17478 "Return non-nil, if FILE is an agenda file.
17479 If FILE is omitted, use the file associated with the current
17480 buffer."
17481 (member (or file (buffer-file-name))
17482 (org-agenda-files t)))
17484 (defun org-edit-agenda-file-list ()
17485 "Edit the list of agenda files.
17486 Depending on setup, this either uses customize to edit the variable
17487 `org-agenda-files', or it visits the file that is holding the list. In the
17488 latter case, the buffer is set up in a way that saving it automatically kills
17489 the buffer and restores the previous window configuration."
17490 (interactive)
17491 (if (stringp org-agenda-files)
17492 (let ((cw (current-window-configuration)))
17493 (find-file org-agenda-files)
17494 (org-set-local 'org-window-configuration cw)
17495 (org-add-hook 'after-save-hook
17496 (lambda ()
17497 (set-window-configuration
17498 (prog1 org-window-configuration
17499 (kill-buffer (current-buffer))))
17500 (org-install-agenda-files-menu)
17501 (message "New agenda file list installed"))
17502 nil 'local)
17503 (message "%s" (substitute-command-keys
17504 "Edit list and finish with \\[save-buffer]")))
17505 (customize-variable 'org-agenda-files)))
17507 (defun org-store-new-agenda-file-list (list)
17508 "Set new value for the agenda file list and save it correctly."
17509 (if (stringp org-agenda-files)
17510 (let ((fe (org-read-agenda-file-list t)) b u)
17511 (while (setq b (find-buffer-visiting org-agenda-files))
17512 (kill-buffer b))
17513 (with-temp-file org-agenda-files
17514 (insert
17515 (mapconcat
17516 (lambda (f) ;; Keep un-expanded entries.
17517 (if (setq u (assoc f fe))
17518 (cdr u)
17520 list "\n")
17521 "\n")))
17522 (let ((org-mode-hook nil) (org-inhibit-startup t)
17523 (org-insert-mode-line-in-empty-file nil))
17524 (setq org-agenda-files list)
17525 (customize-save-variable 'org-agenda-files org-agenda-files))))
17527 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17528 "Read the list of agenda files from a file.
17529 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17530 filenames, used by `org-store-new-agenda-file-list' to write back
17531 un-expanded file names."
17532 (when (file-directory-p org-agenda-files)
17533 (error "`org-agenda-files' cannot be a single directory"))
17534 (when (stringp org-agenda-files)
17535 (with-temp-buffer
17536 (insert-file-contents org-agenda-files)
17537 (mapcar
17538 (lambda (f)
17539 (let ((e (expand-file-name (substitute-in-file-name f)
17540 org-directory)))
17541 (if pair-with-expansion
17542 (cons e f)
17543 e)))
17544 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17546 ;;;###autoload
17547 (defun org-cycle-agenda-files ()
17548 "Cycle through the files in `org-agenda-files'.
17549 If the current buffer visits an agenda file, find the next one in the list.
17550 If the current buffer does not, find the first agenda file."
17551 (interactive)
17552 (let* ((fs (org-agenda-files t))
17553 (files (append fs (list (car fs))))
17554 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17555 file)
17556 (unless files (error "No agenda files"))
17557 (catch 'exit
17558 (while (setq file (pop files))
17559 (if (equal (file-truename file) tcf)
17560 (when (car files)
17561 (find-file (car files))
17562 (throw 'exit t))))
17563 (find-file (car fs)))
17564 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17566 (defun org-agenda-file-to-front (&optional to-end)
17567 "Move/add the current file to the top of the agenda file list.
17568 If the file is not present in the list, it is added to the front. If it is
17569 present, it is moved there. With optional argument TO-END, add/move to the
17570 end of the list."
17571 (interactive "P")
17572 (let ((org-agenda-skip-unavailable-files nil)
17573 (file-alist (mapcar (lambda (x)
17574 (cons (file-truename x) x))
17575 (org-agenda-files t)))
17576 (ctf (file-truename
17577 (or buffer-file-name
17578 (error "Please save the current buffer to a file"))))
17579 x had)
17580 (setq x (assoc ctf file-alist) had x)
17582 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17583 (if to-end
17584 (setq file-alist (append (delq x file-alist) (list x)))
17585 (setq file-alist (cons x (delq x file-alist))))
17586 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17587 (org-install-agenda-files-menu)
17588 (message "File %s to %s of agenda file list"
17589 (if had "moved" "added") (if to-end "end" "front"))))
17591 (defun org-remove-file (&optional file)
17592 "Remove current file from the list of files in variable `org-agenda-files'.
17593 These are the files which are being checked for agenda entries.
17594 Optional argument FILE means use this file instead of the current."
17595 (interactive)
17596 (let* ((org-agenda-skip-unavailable-files nil)
17597 (file (or file buffer-file-name
17598 (error "Current buffer does not visit a file")))
17599 (true-file (file-truename file))
17600 (afile (abbreviate-file-name file))
17601 (files (delq nil (mapcar
17602 (lambda (x)
17603 (if (equal true-file
17604 (file-truename x))
17605 nil x))
17606 (org-agenda-files t)))))
17607 (if (not (= (length files) (length (org-agenda-files t))))
17608 (progn
17609 (org-store-new-agenda-file-list files)
17610 (org-install-agenda-files-menu)
17611 (message "Removed file: %s" afile))
17612 (message "File was not in list: %s (not removed)" afile))))
17614 (defun org-file-menu-entry (file)
17615 (vector file (list 'find-file file) t))
17617 (defun org-check-agenda-file (file)
17618 "Make sure FILE exists. If not, ask user what to do."
17619 (when (not (file-exists-p file))
17620 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17621 (abbreviate-file-name file))
17622 (let ((r (downcase (read-char-exclusive))))
17623 (cond
17624 ((equal r ?r)
17625 (org-remove-file file)
17626 (throw 'nextfile t))
17627 (t (error "Abort"))))))
17629 (defun org-get-agenda-file-buffer (file)
17630 "Get a buffer visiting FILE. If the buffer needs to be created, add
17631 it to the list of buffers which might be released later."
17632 (let ((buf (org-find-base-buffer-visiting file)))
17633 (if buf
17634 buf ; just return it
17635 ;; Make a new buffer and remember it
17636 (setq buf (find-file-noselect file))
17637 (if buf (push buf org-agenda-new-buffers))
17638 buf)))
17640 (defun org-release-buffers (blist)
17641 "Release all buffers in list, asking the user for confirmation when needed.
17642 When a buffer is unmodified, it is just killed. When modified, it is saved
17643 \(if the user agrees) and then killed."
17644 (let (buf file)
17645 (while (setq buf (pop blist))
17646 (setq file (buffer-file-name buf))
17647 (when (and (buffer-modified-p buf)
17648 file
17649 (y-or-n-p (format "Save file %s? " file)))
17650 (with-current-buffer buf (save-buffer)))
17651 (kill-buffer buf))))
17653 (defun org-agenda-prepare-buffers (files)
17654 "Create buffers for all agenda files, protect archived trees and comments."
17655 (interactive)
17656 (let ((pa '(:org-archived t))
17657 (pc '(:org-comment t))
17658 (pall '(:org-archived t :org-comment t))
17659 (inhibit-read-only t)
17660 (org-inhibit-startup org-agenda-inhibit-startup)
17661 (rea (concat ":" org-archive-tag ":"))
17662 file re)
17663 (save-excursion
17664 (save-restriction
17665 (while (setq file (pop files))
17666 (catch 'nextfile
17667 (if (bufferp file)
17668 (set-buffer file)
17669 (org-check-agenda-file file)
17670 (set-buffer (org-get-agenda-file-buffer file)))
17671 (widen)
17672 (org-refresh-category-properties)
17673 (org-refresh-properties org-effort-property 'org-effort)
17674 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17675 (setq org-todo-keywords-for-agenda
17676 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17677 (setq org-done-keywords-for-agenda
17678 (append org-done-keywords-for-agenda org-done-keywords))
17679 (setq org-todo-keyword-alist-for-agenda
17680 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17681 (setq org-drawers-for-agenda
17682 (append org-drawers-for-agenda org-drawers))
17683 (setq org-tag-alist-for-agenda
17684 (append org-tag-alist-for-agenda org-tag-alist))
17685 (org-with-silent-modifications
17686 (save-excursion
17687 (remove-text-properties (point-min) (point-max) pall)
17688 (when org-agenda-skip-archived-trees
17689 (goto-char (point-min))
17690 (while (re-search-forward rea nil t)
17691 (if (org-at-heading-p t)
17692 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17693 (goto-char (point-min))
17694 (setq re (format org-heading-keyword-regexp-format
17695 org-comment-string))
17696 (while (re-search-forward re nil t)
17697 (add-text-properties
17698 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17699 (setq org-todo-keywords-for-agenda
17700 (org-uniquify org-todo-keywords-for-agenda))
17701 (setq org-todo-keyword-alist-for-agenda
17702 (org-uniquify org-todo-keyword-alist-for-agenda)
17703 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17706 ;;;; CDLaTeX minor mode
17708 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17709 "Keymap for the minor `org-cdlatex-mode'.")
17711 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17712 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17713 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17714 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17715 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17717 (defvar org-cdlatex-texmathp-advice-is-done nil
17718 "Flag remembering if we have applied the advice to texmathp already.")
17720 (define-minor-mode org-cdlatex-mode
17721 "Toggle the minor `org-cdlatex-mode'.
17722 This mode supports entering LaTeX environment and math in LaTeX fragments
17723 in Org-mode.
17724 \\{org-cdlatex-mode-map}"
17725 nil " OCDL" nil
17726 (when org-cdlatex-mode
17727 (require 'cdlatex)
17728 (run-hooks 'cdlatex-mode-hook)
17729 (cdlatex-compute-tables))
17730 (unless org-cdlatex-texmathp-advice-is-done
17731 (setq org-cdlatex-texmathp-advice-is-done t)
17732 (defadvice texmathp (around org-math-always-on activate)
17733 "Always return t in org-mode buffers.
17734 This is because we want to insert math symbols without dollars even outside
17735 the LaTeX math segments. If Orgmode thinks that point is actually inside
17736 an embedded LaTeX fragment, let texmathp do its job.
17737 \\[org-cdlatex-mode-map]"
17738 (interactive)
17739 (let (p)
17740 (cond
17741 ((not (derived-mode-p 'org-mode)) ad-do-it)
17742 ((eq this-command 'cdlatex-math-symbol)
17743 (setq ad-return-value t
17744 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17746 (let ((p (org-inside-LaTeX-fragment-p)))
17747 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17748 (setq ad-return-value t
17749 texmathp-why '("Org-mode embedded math" . 0))
17750 (if p ad-do-it)))))))))
17752 (defun turn-on-org-cdlatex ()
17753 "Unconditionally turn on `org-cdlatex-mode'."
17754 (org-cdlatex-mode 1))
17756 (defun org-try-cdlatex-tab ()
17757 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17758 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17759 - inside a LaTeX fragment, or
17760 - after the first word in a line, where an abbreviation expansion could
17761 insert a LaTeX environment."
17762 (when org-cdlatex-mode
17763 (cond
17764 ;; Before any word on the line: No expansion possible.
17765 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17766 ;; Just after first word on the line: Expand it. Make sure it
17767 ;; cannot happen on headlines, though.
17768 ((save-excursion
17769 (skip-chars-backward "a-zA-Z0-9*")
17770 (skip-chars-backward " \t")
17771 (and (bolp) (not (org-at-heading-p))))
17772 (cdlatex-tab) t)
17773 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17775 (defun org-cdlatex-underscore-caret (&optional arg)
17776 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17777 Revert to the normal definition outside of these fragments."
17778 (interactive "P")
17779 (if (org-inside-LaTeX-fragment-p)
17780 (call-interactively 'cdlatex-sub-superscript)
17781 (let (org-cdlatex-mode)
17782 (call-interactively (key-binding (vector last-input-event))))))
17784 (defun org-cdlatex-math-modify (&optional arg)
17785 "Execute `cdlatex-math-modify' in LaTeX fragments.
17786 Revert to the normal definition outside of these fragments."
17787 (interactive "P")
17788 (if (org-inside-LaTeX-fragment-p)
17789 (call-interactively 'cdlatex-math-modify)
17790 (let (org-cdlatex-mode)
17791 (call-interactively (key-binding (vector last-input-event))))))
17795 ;;;; LaTeX fragments
17797 (defvar org-latex-regexps
17798 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17799 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17800 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17801 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17802 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17803 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17804 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17805 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17806 "Regular expressions for matching embedded LaTeX.")
17808 (defun org-inside-LaTeX-fragment-p ()
17809 "Test if point is inside a LaTeX fragment.
17810 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17811 sequence appearing also before point.
17812 Even though the matchers for math are configurable, this function assumes
17813 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17814 delimiters are skipped when they have been removed by customization.
17815 The return value is nil, or a cons cell with the delimiter and the
17816 position of this delimiter.
17818 This function does a reasonably good job, but can locally be fooled by
17819 for example currency specifications. For example it will assume being in
17820 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17821 fragments that are properly closed, but during editing, we have to live
17822 with the uncertainty caused by missing closing delimiters. This function
17823 looks only before point, not after."
17824 (catch 'exit
17825 (let ((pos (point))
17826 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17827 (lim (progn
17828 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17829 (point)))
17830 dd-on str (start 0) m re)
17831 (goto-char pos)
17832 (when dodollar
17833 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17834 re (nth 1 (assoc "$" org-latex-regexps)))
17835 (while (string-match re str start)
17836 (cond
17837 ((= (match-end 0) (length str))
17838 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17839 ((= (match-end 0) (- (length str) 5))
17840 (throw 'exit nil))
17841 (t (setq start (match-end 0))))))
17842 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17843 (goto-char pos)
17844 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17845 (and (match-beginning 2) (throw 'exit nil))
17846 ;; count $$
17847 (while (re-search-backward "\\$\\$" lim t)
17848 (setq dd-on (not dd-on)))
17849 (goto-char pos)
17850 (if dd-on (cons "$$" m))))))
17852 (defun org-inside-latex-macro-p ()
17853 "Is point inside a LaTeX macro or its arguments?"
17854 (save-match-data
17855 (org-in-regexp
17856 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17858 (defvar org-latex-fragment-image-overlays nil
17859 "List of overlays carrying the images of latex fragments.")
17860 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17862 (defun org-remove-latex-fragment-image-overlays ()
17863 "Remove all overlays with LaTeX fragment images in current buffer."
17864 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17865 (setq org-latex-fragment-image-overlays nil))
17867 (defun org-preview-latex-fragment (&optional subtree)
17868 "Preview the LaTeX fragment at point, or all locally or globally.
17869 If the cursor is in a LaTeX fragment, create the image and overlay
17870 it over the source code. If there is no fragment at point, display
17871 all fragments in the current text, from one headline to the next. With
17872 prefix SUBTREE, display all fragments in the current subtree. With a
17873 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17874 the cursor is before the first headline,
17875 display all fragments in the buffer.
17876 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17877 (interactive "P")
17878 (unless buffer-file-name
17879 (error "Can't preview LaTeX fragment in a non-file buffer"))
17880 (org-remove-latex-fragment-image-overlays)
17881 (save-excursion
17882 (save-restriction
17883 (let (beg end at msg)
17884 (cond
17885 ((or (equal subtree '(16))
17886 (not (save-excursion
17887 (re-search-backward org-outline-regexp-bol nil t))))
17888 (setq beg (point-min) end (point-max)
17889 msg "Creating images for buffer...%s"))
17890 ((equal subtree '(4))
17891 (org-back-to-heading)
17892 (setq beg (point) end (org-end-of-subtree t)
17893 msg "Creating images for subtree...%s"))
17895 (if (setq at (org-inside-LaTeX-fragment-p))
17896 (goto-char (max (point-min) (- (cdr at) 2)))
17897 (org-back-to-heading))
17898 (setq beg (point) end (progn (outline-next-heading) (point))
17899 msg (if at "Creating image...%s"
17900 "Creating images for entry...%s"))))
17901 (message msg "")
17902 (narrow-to-region beg end)
17903 (goto-char beg)
17904 (org-format-latex
17905 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17906 (file-name-nondirectory
17907 buffer-file-name)))
17908 default-directory 'overlays msg at 'forbuffer
17909 org-latex-create-formula-image-program)
17910 (message msg "done. Use `C-c C-c' to remove images.")))))
17912 (defun org-format-latex (prefix &optional dir overlays msg at
17913 forbuffer processing-type)
17914 "Replace LaTeX fragments with links to an image, and produce images.
17915 Some of the options can be changed using the variable
17916 `org-format-latex-options'."
17917 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17918 (let* ((prefixnodir (file-name-nondirectory prefix))
17919 (absprefix (expand-file-name prefix dir))
17920 (todir (file-name-directory absprefix))
17921 (opt org-format-latex-options)
17922 (optnew org-format-latex-options)
17923 (matchers (plist-get opt :matchers))
17924 (re-list org-latex-regexps)
17925 (cnt 0) txt hash link beg end re e checkdir
17926 string
17927 m n block-type block linkfile movefile ov)
17928 ;; Check the different regular expressions
17929 (while (setq e (pop re-list))
17930 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17931 block (if block-type "\n\n" ""))
17932 (when (member m matchers)
17933 (goto-char (point-min))
17934 (while (re-search-forward re nil t)
17935 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17936 (or (not overlays)
17937 (not (eq (get-char-property (match-beginning n)
17938 'org-overlay-type)
17939 'org-latex-overlay))))
17940 (cond
17941 ((eq processing-type 'verbatim))
17942 ((eq processing-type 'mathjax)
17943 ;; Prepare for MathJax processing.
17944 (setq string (match-string n))
17945 (when (member m '("$" "$1"))
17946 (save-excursion
17947 (delete-region (match-beginning n) (match-end n))
17948 (goto-char (match-beginning n))
17949 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17950 ((or (eq processing-type 'dvipng)
17951 (eq processing-type 'imagemagick))
17952 ;; Process to an image.
17953 (setq txt (match-string n)
17954 beg (match-beginning n) end (match-end n)
17955 cnt (1+ cnt))
17956 (let ((face (face-at-point))
17957 (fg (plist-get opt :foreground))
17958 (bg (plist-get opt :background))
17959 ;; Ensure full list is printed.
17960 print-length print-level)
17961 (when forbuffer
17962 ;; Get the colors from the face at point.
17963 (goto-char beg)
17964 (when (eq fg 'auto)
17965 (setq fg (face-attribute face :foreground nil 'default)))
17966 (when (eq bg 'auto)
17967 (setq bg (face-attribute face :background nil 'default)))
17968 (setq optnew (copy-sequence opt))
17969 (plist-put optnew :foreground fg)
17970 (plist-put optnew :background bg))
17971 (setq hash (sha1 (prin1-to-string
17972 (list org-format-latex-header
17973 org-latex-default-packages-alist
17974 org-latex-packages-alist
17975 org-format-latex-options
17976 forbuffer txt fg bg)))
17977 linkfile (format "%s_%s.png" prefix hash)
17978 movefile (format "%s_%s.png" absprefix hash)))
17979 (setq link (concat block "[[file:" linkfile "]]" block))
17980 (if msg (message msg cnt))
17981 (goto-char beg)
17982 (unless checkdir ; Ensure the directory exists.
17983 (setq checkdir t)
17984 (or (file-directory-p todir) (make-directory todir t)))
17985 (unless (file-exists-p movefile)
17986 (org-create-formula-image
17987 txt movefile optnew forbuffer processing-type))
17988 (if overlays
17989 (progn
17990 (mapc (lambda (o)
17991 (if (eq (overlay-get o 'org-overlay-type)
17992 'org-latex-overlay)
17993 (delete-overlay o)))
17994 (overlays-in beg end))
17995 (setq ov (make-overlay beg end))
17996 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17997 (if (featurep 'xemacs)
17998 (progn
17999 (overlay-put ov 'invisible t)
18000 (overlay-put
18001 ov 'end-glyph
18002 (make-glyph (vector 'png :file movefile))))
18003 (overlay-put
18004 ov 'display
18005 (list 'image :type 'png :file movefile :ascent 'center)))
18006 (push ov org-latex-fragment-image-overlays)
18007 (goto-char end))
18008 (delete-region beg end)
18009 (insert (org-add-props link
18010 (list 'org-latex-src
18011 (replace-regexp-in-string
18012 "\"" "" txt)
18013 'org-latex-src-embed-type
18014 (if block-type 'paragraph 'character))))))
18015 ((eq processing-type 'mathml)
18016 ;; Process to MathML
18017 (unless (save-match-data (org-format-latex-mathml-available-p))
18018 (error "LaTeX to MathML converter not configured"))
18019 (setq txt (match-string n)
18020 beg (match-beginning n) end (match-end n)
18021 cnt (1+ cnt))
18022 (if msg (message msg cnt))
18023 (goto-char beg)
18024 (delete-region beg end)
18025 (insert (org-format-latex-as-mathml
18026 txt block-type prefix dir)))
18028 (error "Unknown conversion type %s for latex fragments"
18029 processing-type)))))))))
18031 (defun org-create-math-formula (latex-frag &optional mathml-file)
18032 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18033 Use `org-latex-to-mathml-convert-command'. If the conversion is
18034 sucessful, return the portion between \"<math...> </math>\"
18035 elements otherwise return nil. When MATHML-FILE is specified,
18036 write the results in to that file. When invoked as an
18037 interactive command, prompt for LATEX-FRAG, with initial value
18038 set to the current active region and echo the results for user
18039 inspection."
18040 (interactive (list (let ((frag (when (org-region-active-p)
18041 (buffer-substring-no-properties
18042 (region-beginning) (region-end)))))
18043 (read-string "LaTeX Fragment: " frag nil frag))))
18044 (unless latex-frag (error "Invalid latex-frag"))
18045 (let* ((tmp-in-file (file-relative-name
18046 (make-temp-name (expand-file-name "ltxmathml-in"))))
18047 (ignore (write-region latex-frag nil tmp-in-file))
18048 (tmp-out-file (file-relative-name
18049 (make-temp-name (expand-file-name "ltxmathml-out"))))
18050 (cmd (format-spec
18051 org-latex-to-mathml-convert-command
18052 `((?j . ,(shell-quote-argument
18053 (expand-file-name org-latex-to-mathml-jar-file)))
18054 (?I . ,(shell-quote-argument tmp-in-file))
18055 (?o . ,(shell-quote-argument tmp-out-file)))))
18056 mathml shell-command-output)
18057 (when (org-called-interactively-p 'any)
18058 (unless (org-format-latex-mathml-available-p)
18059 (error "LaTeX to MathML converter not configured")))
18060 (message "Running %s" cmd)
18061 (setq shell-command-output (shell-command-to-string cmd))
18062 (setq mathml
18063 (when (file-readable-p tmp-out-file)
18064 (with-current-buffer (find-file-noselect tmp-out-file t)
18065 (goto-char (point-min))
18066 (when (re-search-forward
18067 (concat
18068 (regexp-quote
18069 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18070 "\\(.\\|\n\\)*"
18071 (regexp-quote "</math>")) nil t)
18072 (prog1 (match-string 0) (kill-buffer))))))
18073 (cond
18074 (mathml
18075 (setq mathml
18076 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18077 (when mathml-file
18078 (write-region mathml nil mathml-file))
18079 (when (org-called-interactively-p 'any)
18080 (message mathml)))
18081 ((message "LaTeX to MathML conversion failed")
18082 (message shell-command-output)))
18083 (delete-file tmp-in-file)
18084 (when (file-exists-p tmp-out-file)
18085 (delete-file tmp-out-file))
18086 mathml))
18088 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18089 prefix &optional dir)
18090 "Use `org-create-math-formula' but check local cache first."
18091 (let* ((absprefix (expand-file-name prefix dir))
18092 (print-length nil) (print-level nil)
18093 (formula-id (concat
18094 "formula-"
18095 (sha1
18096 (prin1-to-string
18097 (list latex-frag
18098 org-latex-to-mathml-convert-command)))))
18099 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18100 (formula-cache-dir (file-name-directory formula-cache)))
18102 (unless (file-directory-p formula-cache-dir)
18103 (make-directory formula-cache-dir t))
18105 (unless (file-exists-p formula-cache)
18106 (org-create-math-formula latex-frag formula-cache))
18108 (if (file-exists-p formula-cache)
18109 ;; Successful conversion. Return the link to MathML file.
18110 (org-add-props
18111 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18112 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18113 'org-latex-src-embed-type (if latex-frag-type
18114 'paragraph 'character)))
18115 ;; Failed conversion. Return the LaTeX fragment verbatim
18116 latex-frag)))
18118 (defun org-create-formula-image (string tofile options buffer &optional type)
18119 "Create an image from LaTeX source using dvipng or convert.
18120 This function calls either `org-create-formula-image-with-dvipng'
18121 or `org-create-formula-image-with-imagemagick' depending on the
18122 value of `org-latex-create-formula-image-program' or on the value
18123 of the optional TYPE variable.
18125 Note: ultimately these two function should be combined as they
18126 share a good deal of logic."
18127 (org-check-external-command
18128 "latex" "needed to convert LaTeX fragments to images")
18129 (funcall
18130 (case (or type org-latex-create-formula-image-program)
18131 ('dvipng
18132 (org-check-external-command
18133 "dvipng" "needed to convert LaTeX fragments to images")
18134 #'org-create-formula-image-with-dvipng)
18135 ('imagemagick
18136 (org-check-external-command
18137 "convert" "you need to install imagemagick")
18138 #'org-create-formula-image-with-imagemagick)
18139 (t (error
18140 "invalid value of `org-latex-create-formula-image-program'")))
18141 string tofile options buffer))
18143 (declare-function org-export--get-global-options "ox" (&optional backend))
18144 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18145 (defun org-create-formula--latex-header ()
18146 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18147 (org-latex-guess-inputenc
18148 (org-splice-latex-header
18149 org-format-latex-header
18150 org-latex-default-packages-alist
18151 org-latex-packages-alist t
18152 (plist-get
18153 (org-combine-plists
18154 (org-export--get-global-options 'latex)
18155 (org-export--get-inbuffer-options 'latex))
18156 :latex-header-extra))))
18158 ;; This function borrows from Ganesh Swami's latex2png.el
18159 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18160 "This calls dvipng."
18161 (require 'ox-latex)
18162 (let* ((tmpdir (if (featurep 'xemacs)
18163 (temp-directory)
18164 temporary-file-directory))
18165 (texfilebase (make-temp-name
18166 (expand-file-name "orgtex" tmpdir)))
18167 (texfile (concat texfilebase ".tex"))
18168 (dvifile (concat texfilebase ".dvi"))
18169 (pngfile (concat texfilebase ".png"))
18170 (fnh (if (featurep 'xemacs)
18171 (font-height (face-font 'default))
18172 (face-attribute 'default :height nil)))
18173 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18174 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18175 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18176 "Black"))
18177 (bg (or (plist-get options (if buffer :background :html-background))
18178 "Transparent")))
18179 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18180 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18181 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18182 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18183 (let ((latex-header (org-create-formula--latex-header)))
18184 (with-temp-file texfile
18185 (insert latex-header)
18186 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18187 (let ((dir default-directory))
18188 (condition-case nil
18189 (progn
18190 (cd tmpdir)
18191 (call-process "latex" nil nil nil texfile))
18192 (error nil))
18193 (cd dir))
18194 (if (not (file-exists-p dvifile))
18195 (progn (message "Failed to create dvi file from %s" texfile) nil)
18196 (condition-case nil
18197 (if (featurep 'xemacs)
18198 (call-process "dvipng" nil nil nil
18199 "-fg" fg "-bg" bg
18200 "-T" "tight"
18201 "-o" pngfile
18202 dvifile)
18203 (call-process "dvipng" nil nil nil
18204 "-fg" fg "-bg" bg
18205 "-D" dpi
18206 ;;"-x" scale "-y" scale
18207 "-T" "tight"
18208 "-o" pngfile
18209 dvifile))
18210 (error nil))
18211 (if (not (file-exists-p pngfile))
18212 (if org-format-latex-signal-error
18213 (error "Failed to create png file from %s" texfile)
18214 (message "Failed to create png file from %s" texfile)
18215 nil)
18216 ;; Use the requested file name and clean up
18217 (copy-file pngfile tofile 'replace)
18218 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18219 (if (file-exists-p (concat texfilebase e))
18220 (delete-file (concat texfilebase e))))
18221 pngfile))))
18223 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18224 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18225 "This calls convert, which is included into imagemagick."
18226 (require 'ox-latex)
18227 (let* ((tmpdir (if (featurep 'xemacs)
18228 (temp-directory)
18229 temporary-file-directory))
18230 (texfilebase (make-temp-name
18231 (expand-file-name "orgtex" tmpdir)))
18232 (texfile (concat texfilebase ".tex"))
18233 (pdffile (concat texfilebase ".pdf"))
18234 (pngfile (concat texfilebase ".png"))
18235 (fnh (if (featurep 'xemacs)
18236 (font-height (face-font 'default))
18237 (face-attribute 'default :height nil)))
18238 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18239 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18240 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18241 "black"))
18242 (bg (or (plist-get options (if buffer :background :html-background))
18243 "white")))
18244 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18245 (setq fg (org-latex-color-format fg)))
18246 (if (eq bg 'default) (setq bg (org-latex-color :background))
18247 (setq bg (org-latex-color-format
18248 (if (string= bg "Transparent") "white" bg))))
18249 (let ((latex-header (org-create-formula--latex-header)))
18250 (with-temp-file texfile
18251 (insert latex-header)
18252 (insert "\n\\begin{document}\n"
18253 "\\definecolor{fg}{rgb}{" fg "}\n"
18254 "\\definecolor{bg}{rgb}{" bg "}\n"
18255 "\n\\pagecolor{bg}\n"
18256 "\n{\\color{fg}\n"
18257 string
18258 "\n}\n"
18259 "\n\\end{document}\n")))
18260 (org-latex-compile texfile t)
18261 (if (not (file-exists-p pdffile))
18262 (progn (message "Failed to create pdf file from %s" texfile) nil)
18263 (condition-case nil
18264 (if (featurep 'xemacs)
18265 (call-process "convert" nil nil nil
18266 "-density" "96"
18267 "-trim"
18268 "-antialias"
18269 pdffile
18270 "-quality" "100"
18271 ;; "-sharpen" "0x1.0"
18272 pngfile)
18273 (call-process "convert" nil nil nil
18274 "-density" dpi
18275 "-trim"
18276 "-antialias"
18277 pdffile
18278 "-quality" "100"
18279 ;; "-sharpen" "0x1.0"
18280 pngfile))
18281 (error nil))
18282 (if (not (file-exists-p pngfile))
18283 (if org-format-latex-signal-error
18284 (error "Failed to create png file from %s" texfile)
18285 (message "Failed to create png file from %s" texfile)
18286 nil)
18287 ;; Use the requested file name and clean up
18288 (copy-file pngfile tofile 'replace)
18289 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18290 (if (file-exists-p (concat texfilebase e))
18291 (delete-file (concat texfilebase e))))
18292 pngfile))))
18294 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18295 "Fill a LaTeX header template TPL.
18296 In the template, the following place holders will be recognized:
18298 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18299 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18300 [PACKAGES] \\usepackage statements for PKG
18301 [NO-PACKAGES] do not include PKG
18302 [EXTRA] the string EXTRA
18303 [NO-EXTRA] do not include EXTRA
18305 For backward compatibility, if both the positive and the negative place
18306 holder is missing, the positive one (without the \"NO-\") will be
18307 assumed to be present at the end of the template.
18308 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18309 EXTRA is a string.
18310 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18311 (let (rpl (end ""))
18312 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18313 (setq rpl (if (or (match-end 1) (not def-pkg))
18314 "" (org-latex-packages-to-string def-pkg snippets-p t))
18315 tpl (replace-match rpl t t tpl))
18316 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18318 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18319 (setq rpl (if (or (match-end 1) (not pkg))
18320 "" (org-latex-packages-to-string pkg snippets-p t))
18321 tpl (replace-match rpl t t tpl))
18322 (if pkg (setq end
18323 (concat end "\n"
18324 (org-latex-packages-to-string pkg snippets-p)))))
18326 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18327 (setq rpl (if (or (match-end 1) (not extra))
18328 "" (concat extra "\n"))
18329 tpl (replace-match rpl t t tpl))
18330 (if (and extra (string-match "\\S-" extra))
18331 (setq end (concat end "\n" extra))))
18333 (if (string-match "\\S-" end)
18334 (concat tpl "\n" end)
18335 tpl)))
18337 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18338 "Turn an alist of packages into a string with the \\usepackage macros."
18339 (setq pkg (mapconcat (lambda(p)
18340 (cond
18341 ((stringp p) p)
18342 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18343 (format "%% Package %s omitted" (cadr p)))
18344 ((equal "" (car p))
18345 (format "\\usepackage{%s}" (cadr p)))
18347 (format "\\usepackage[%s]{%s}"
18348 (car p) (cadr p)))))
18350 "\n"))
18351 (if newline (concat pkg "\n") pkg))
18353 (defun org-dvipng-color (attr)
18354 "Return a RGB color specification for dvipng."
18355 (apply 'format "rgb %s %s %s"
18356 (mapcar 'org-normalize-color
18357 (if (featurep 'xemacs)
18358 (color-rgb-components
18359 (face-property 'default
18360 (cond ((eq attr :foreground) 'foreground)
18361 ((eq attr :background) 'background))))
18362 (color-values (face-attribute 'default attr nil))))))
18364 (defun org-dvipng-color-format (color-name)
18365 "Convert COLOR-NAME to a RGB color value for dvipng."
18366 (apply 'format "rgb %s %s %s"
18367 (mapcar 'org-normalize-color
18368 (color-values color-name))))
18370 (defun org-latex-color (attr)
18371 "Return a RGB color for the LaTeX color package."
18372 (apply 'format "%s,%s,%s"
18373 (mapcar 'org-normalize-color
18374 (if (featurep 'xemacs)
18375 (color-rgb-components
18376 (face-property 'default
18377 (cond ((eq attr :foreground) 'foreground)
18378 ((eq attr :background) 'background))))
18379 (color-values (face-attribute 'default attr nil))))))
18381 (defun org-latex-color-format (color-name)
18382 "Convert COLOR-NAME to a RGB color value."
18383 (apply 'format "%s,%s,%s"
18384 (mapcar 'org-normalize-color
18385 (color-values color-name))))
18387 (defun org-normalize-color (value)
18388 "Return string to be used as color value for an RGB component."
18389 (format "%g" (/ value 65535.0)))
18393 ;; Image display
18395 (defvar org-inline-image-overlays nil)
18396 (make-variable-buffer-local 'org-inline-image-overlays)
18398 (defun org-toggle-inline-images (&optional include-linked)
18399 "Toggle the display of inline images.
18400 INCLUDE-LINKED is passed to `org-display-inline-images'."
18401 (interactive "P")
18402 (if org-inline-image-overlays
18403 (progn
18404 (org-remove-inline-images)
18405 (message "Inline image display turned off"))
18406 (org-display-inline-images include-linked)
18407 (if (and (org-called-interactively-p)
18408 org-inline-image-overlays)
18409 (message "%d images displayed inline"
18410 (length org-inline-image-overlays))
18411 (message "No images to display inline"))))
18413 (defun org-redisplay-inline-images ()
18414 "Refresh the display of inline images."
18415 (interactive)
18416 (if (not org-inline-image-overlays)
18417 (org-toggle-inline-images)
18418 (org-toggle-inline-images)
18419 (org-toggle-inline-images)))
18421 (defun org-display-inline-images (&optional include-linked refresh beg end)
18422 "Display inline images.
18423 Normally only links without a description part are inlined, because this
18424 is how it will work for export. When INCLUDE-LINKED is set, also links
18425 with a description part will be inlined. This can be nice for a quick
18426 look at those images, but it does not reflect what exported files will look
18427 like.
18428 When REFRESH is set, refresh existing images between BEG and END.
18429 This will create new image displays only if necessary.
18430 BEG and END default to the buffer boundaries."
18431 (interactive "P")
18432 (unless refresh
18433 (org-remove-inline-images)
18434 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18435 (save-excursion
18436 (save-restriction
18437 (widen)
18438 (setq beg (or beg (point-min)) end (or end (point-max)))
18439 (goto-char beg)
18440 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18441 (substring (org-image-file-name-regexp) 0 -2)
18442 "\\)\\]" (if include-linked "" "\\]")))
18443 old file ov img type attrwidth width)
18444 (while (re-search-forward re end t)
18445 (setq old (get-char-property-and-overlay (match-beginning 1)
18446 'org-image-overlay)
18447 file (expand-file-name
18448 (concat (or (match-string 3) "") (match-string 4))))
18449 (when (image-type-available-p 'imagemagick)
18450 (setq attrwidth (if (or (listp org-image-actual-width)
18451 (null org-image-actual-width))
18452 (save-excursion
18453 (save-match-data
18454 (when (re-search-backward
18455 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18456 (save-excursion
18457 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18458 (string-to-number (match-string 1))))))
18459 width (cond ((eq org-image-actual-width t) nil)
18460 ((null org-image-actual-width) attrwidth)
18461 ((numberp org-image-actual-width)
18462 org-image-actual-width)
18463 ((listp org-image-actual-width)
18464 (or attrwidth (car org-image-actual-width))))
18465 type (if width 'imagemagick)))
18466 (when (file-exists-p file)
18467 (if (and (car-safe old) refresh)
18468 (image-refresh (overlay-get (cdr old) 'display))
18469 (setq img (save-match-data (create-image file type nil :width width)))
18470 (when img
18471 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18472 (overlay-put ov 'display img)
18473 (overlay-put ov 'face 'default)
18474 (overlay-put ov 'org-image-overlay t)
18475 (overlay-put ov 'modification-hooks
18476 (list 'org-display-inline-remove-overlay))
18477 (push ov org-inline-image-overlays)))))))))
18479 (define-obsolete-function-alias
18480 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18482 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18483 "Remove inline-display overlay if a corresponding region is modified."
18484 (let ((inhibit-modification-hooks t))
18485 (when (and ov after)
18486 (delete ov org-inline-image-overlays)
18487 (delete-overlay ov))))
18489 (defun org-remove-inline-images ()
18490 "Remove inline display of images."
18491 (interactive)
18492 (mapc 'delete-overlay org-inline-image-overlays)
18493 (setq org-inline-image-overlays nil))
18495 ;;;; Key bindings
18497 ;; Outline functions from `outline-mode-prefix-map'
18498 ;; that can be remapped in Org:
18499 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18500 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18501 (define-key org-mode-map [remap outline-forward-same-level]
18502 'org-forward-heading-same-level)
18503 (define-key org-mode-map [remap outline-backward-same-level]
18504 'org-backward-heading-same-level)
18505 (define-key org-mode-map [remap show-branches]
18506 'org-kill-note-or-show-branches)
18507 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18508 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18509 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18511 ;; Outline functions from `outline-mode-prefix-map' that can not
18512 ;; be remapped in Org:
18514 ;; - the column "key binding" shows whether the Outline function is still
18515 ;; available in Org mode on the same key that it has been bound to in
18516 ;; Outline mode:
18517 ;; - "overridden": key used for a different functionality in Org mode
18518 ;; - else: key still bound to the same Outline function in Org mode
18520 ;; | Outline function | key binding | Org replacement |
18521 ;; |------------------------------------+-------------+-----------------------|
18522 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18523 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18524 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18525 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18526 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18527 ;; | `show-entry' | overridden | no replacement |
18528 ;; | `show-children' | `C-c C-i' | visibility cycling |
18529 ;; | `show-branches' | `C-c C-k' | still same function |
18530 ;; | `show-subtree' | overridden | visibility cycling |
18531 ;; | `show-all' | overridden | no replacement |
18532 ;; | `hide-subtree' | overridden | visibility cycling |
18533 ;; | `hide-body' | overridden | no replacement |
18534 ;; | `hide-entry' | overridden | visibility cycling |
18535 ;; | `hide-leaves' | overridden | no replacement |
18536 ;; | `hide-sublevels' | overridden | no replacement |
18537 ;; | `hide-other' | overridden | no replacement |
18539 ;; Make `C-c C-x' a prefix key
18540 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18542 ;; TAB key with modifiers
18543 (org-defkey org-mode-map "\C-i" 'org-cycle)
18544 (org-defkey org-mode-map [(tab)] 'org-cycle)
18545 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18546 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18547 ;; The following line is necessary under Suse GNU/Linux
18548 (unless (featurep 'xemacs)
18549 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18550 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18551 (define-key org-mode-map [backtab] 'org-shifttab)
18553 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18554 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18555 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18557 ;; Cursor keys with modifiers
18558 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18559 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18560 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18561 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18563 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18564 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18565 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18566 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18568 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18569 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18570 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18571 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18573 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18574 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18575 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18576 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18578 ;; Babel keys
18579 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18580 (mapc (lambda (pair)
18581 (define-key org-babel-map (car pair) (cdr pair)))
18582 org-babel-key-bindings)
18584 ;;; Extra keys for tty access.
18585 ;; We only set them when really needed because otherwise the
18586 ;; menus don't show the simple keys
18588 (when (or org-use-extra-keys
18589 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18590 (not window-system))
18591 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18592 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18593 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18594 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18595 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18596 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18597 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18598 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18599 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18600 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18601 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18602 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18603 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18604 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18605 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18606 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18607 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18608 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18609 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18610 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18611 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18612 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18613 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18614 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18615 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18616 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18617 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18618 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18620 ;; All the other keys
18622 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18623 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18624 (if (boundp 'narrow-map)
18625 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18626 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18627 (if (boundp 'narrow-map)
18628 (org-defkey narrow-map "b" 'org-narrow-to-block)
18629 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18630 (if (boundp 'narrow-map)
18631 (org-defkey narrow-map "e" 'org-narrow-to-element)
18632 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18633 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18634 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18635 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18636 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18637 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18638 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18639 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18640 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18641 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18642 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18643 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18644 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18645 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18646 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18647 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18648 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18649 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18650 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18651 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18652 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18653 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18654 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18655 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18656 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18657 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18658 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18659 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18660 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18661 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18662 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18663 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18664 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18665 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18666 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18667 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18668 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18669 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18670 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18671 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18672 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18673 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18674 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18675 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18676 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18677 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18678 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18679 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18680 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18681 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18682 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18683 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18684 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18685 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18686 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18687 (org-defkey org-mode-map "\C-c^" 'org-sort)
18688 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18689 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18690 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18691 (org-defkey org-mode-map "\C-m" 'org-return)
18692 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18693 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18694 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18695 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18696 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18697 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18698 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18699 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18700 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18701 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18702 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18703 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18704 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18705 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18706 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18707 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18708 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18709 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18710 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18711 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18712 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18713 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18714 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18716 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18717 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18718 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18720 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18721 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18722 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18723 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18724 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18725 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18726 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18727 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18728 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18729 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18730 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18731 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18732 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18733 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18734 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18735 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18736 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18737 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18738 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18739 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18740 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18741 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18742 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18744 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18745 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18746 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18747 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18748 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18750 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18752 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18754 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18755 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18757 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18760 (when (featurep 'xemacs)
18761 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18764 (defconst org-speed-commands-default
18766 ("Outline Navigation")
18767 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18768 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18769 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18770 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18771 ("F" . org-next-block)
18772 ("B" . org-previous-block)
18773 ("u" . (org-speed-move-safe 'outline-up-heading))
18774 ("j" . org-goto)
18775 ("g" . (org-refile t))
18776 ("Outline Visibility")
18777 ("c" . org-cycle)
18778 ("C" . org-shifttab)
18779 (" " . org-display-outline-path)
18780 ("=" . org-columns)
18781 ("Outline Structure Editing")
18782 ("U" . org-shiftmetaup)
18783 ("D" . org-shiftmetadown)
18784 ("r" . org-metaright)
18785 ("l" . org-metaleft)
18786 ("R" . org-shiftmetaright)
18787 ("L" . org-shiftmetaleft)
18788 ("i" . (progn (forward-char 1) (call-interactively
18789 'org-insert-heading-respect-content)))
18790 ("^" . org-sort)
18791 ("w" . org-refile)
18792 ("a" . org-archive-subtree-default-with-confirmation)
18793 ("@" . org-mark-subtree)
18794 ("#" . org-toggle-comment)
18795 ("Clock Commands")
18796 ("I" . org-clock-in)
18797 ("O" . org-clock-out)
18798 ("Meta Data Editing")
18799 ("t" . org-todo)
18800 ("," . (org-priority))
18801 ("0" . (org-priority ?\ ))
18802 ("1" . (org-priority ?A))
18803 ("2" . (org-priority ?B))
18804 ("3" . (org-priority ?C))
18805 (":" . org-set-tags-command)
18806 ("e" . org-set-effort)
18807 ("E" . org-inc-effort)
18808 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18809 (org-entry-put (point) "APPT_WARNTIME" m)))
18810 ("Agenda Views etc")
18811 ("v" . org-agenda)
18812 ("/" . org-sparse-tree)
18813 ("Misc")
18814 ("o" . org-open-at-point)
18815 ("?" . org-speed-command-help)
18816 ("<" . (org-agenda-set-restriction-lock 'subtree))
18817 (">" . (org-agenda-remove-restriction-lock))
18819 "The default speed commands.")
18821 (defun org-print-speed-command (e)
18822 (if (> (length (car e)) 1)
18823 (progn
18824 (princ "\n")
18825 (princ (car e))
18826 (princ "\n")
18827 (princ (make-string (length (car e)) ?-))
18828 (princ "\n"))
18829 (princ (car e))
18830 (princ " ")
18831 (if (symbolp (cdr e))
18832 (princ (symbol-name (cdr e)))
18833 (prin1 (cdr e)))
18834 (princ "\n")))
18836 (defun org-speed-command-help ()
18837 "Show the available speed commands."
18838 (interactive)
18839 (if (not org-use-speed-commands)
18840 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18841 (with-output-to-temp-buffer "*Help*"
18842 (princ "User-defined Speed commands\n===========================\n")
18843 (mapc 'org-print-speed-command org-speed-commands-user)
18844 (princ "\n")
18845 (princ "Built-in Speed commands\n=======================\n")
18846 (mapc 'org-print-speed-command org-speed-commands-default))
18847 (with-current-buffer "*Help*"
18848 (setq truncate-lines t))))
18850 (defun org-speed-move-safe (cmd)
18851 "Execute CMD, but make sure that the cursor always ends up in a headline.
18852 If not, return to the original position and throw an error."
18853 (interactive)
18854 (let ((pos (point)))
18855 (call-interactively cmd)
18856 (unless (and (bolp) (org-at-heading-p))
18857 (goto-char pos)
18858 (error "Boundary reached while executing %s" cmd))))
18860 (defvar org-self-insert-command-undo-counter 0)
18862 (defvar org-table-auto-blank-field) ; defined in org-table.el
18863 (defvar org-speed-command nil)
18865 (define-obsolete-function-alias
18866 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18868 (defun org-speed-command-activate (keys)
18869 "Hook for activating single-letter speed commands.
18870 `org-speed-commands-default' specifies a minimal command set.
18871 Use `org-speed-commands-user' for further customization."
18872 (when (or (and (bolp) (looking-at org-outline-regexp))
18873 (and (functionp org-use-speed-commands)
18874 (funcall org-use-speed-commands)))
18875 (cdr (assoc keys (append org-speed-commands-user
18876 org-speed-commands-default)))))
18878 (define-obsolete-function-alias
18879 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18881 (defun org-babel-speed-command-activate (keys)
18882 "Hook for activating single-letter code block commands."
18883 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18884 (cdr (assoc keys org-babel-key-bindings))))
18886 (defcustom org-speed-command-hook
18887 '(org-speed-command-default-hook org-babel-speed-command-hook)
18888 "Hook for activating speed commands at strategic locations.
18889 Hook functions are called in sequence until a valid handler is
18890 found.
18892 Each hook takes a single argument, a user-pressed command key
18893 which is also a `self-insert-command' from the global map.
18895 Within the hook, examine the cursor position and the command key
18896 and return nil or a valid handler as appropriate. Handler could
18897 be one of an interactive command, a function, or a form.
18899 Set `org-use-speed-commands' to non-nil value to enable this
18900 hook. The default setting is `org-speed-command-activate'."
18901 :group 'org-structure
18902 :version "24.1"
18903 :type 'hook)
18905 (defun org-self-insert-command (N)
18906 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18907 If the cursor is in a table looking at whitespace, the whitespace is
18908 overwritten, and the table is not marked as requiring realignment."
18909 (interactive "p")
18910 (org-check-before-invisible-edit 'insert)
18911 (cond
18912 ((and org-use-speed-commands
18913 (setq org-speed-command
18914 (run-hook-with-args-until-success
18915 'org-speed-command-hook (this-command-keys))))
18916 (cond
18917 ((commandp org-speed-command)
18918 (setq this-command org-speed-command)
18919 (call-interactively org-speed-command))
18920 ((functionp org-speed-command)
18921 (funcall org-speed-command))
18922 ((and org-speed-command (listp org-speed-command))
18923 (eval org-speed-command))
18924 (t (let (org-use-speed-commands)
18925 (call-interactively 'org-self-insert-command)))))
18926 ((and
18927 (org-table-p)
18928 (progn
18929 ;; check if we blank the field, and if that triggers align
18930 (and (featurep 'org-table) org-table-auto-blank-field
18931 (member last-command
18932 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18933 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18934 ;; got extra space, this field does not determine column width
18935 (let (org-table-may-need-update) (org-table-blank-field))
18936 ;; no extra space, this field may determine column width
18937 (org-table-blank-field)))
18939 (eq N 1)
18940 (looking-at "[^|\n]* |"))
18941 (let (org-table-may-need-update)
18942 (goto-char (1- (match-end 0)))
18943 (backward-delete-char 1)
18944 (goto-char (match-beginning 0))
18945 (self-insert-command N)))
18947 (setq org-table-may-need-update t)
18948 (self-insert-command N)
18949 (org-fix-tags-on-the-fly)
18950 (if org-self-insert-cluster-for-undo
18951 (if (not (eq last-command 'org-self-insert-command))
18952 (setq org-self-insert-command-undo-counter 1)
18953 (if (>= org-self-insert-command-undo-counter 20)
18954 (setq org-self-insert-command-undo-counter 1)
18955 (and (> org-self-insert-command-undo-counter 0)
18956 buffer-undo-list (listp buffer-undo-list)
18957 (not (cadr buffer-undo-list)) ; remove nil entry
18958 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18959 (setq org-self-insert-command-undo-counter
18960 (1+ org-self-insert-command-undo-counter))))))))
18962 (defun org-check-before-invisible-edit (kind)
18963 "Check is editing if kind KIND would be dangerous with invisible text around.
18964 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18965 ;; First, try to get out of here as quickly as possible, to reduce overhead
18966 (if (and org-catch-invisible-edits
18967 (or (not (boundp 'visible-mode)) (not visible-mode))
18968 (or (get-char-property (point) 'invisible)
18969 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18970 ;; OK, we need to take a closer look
18971 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18972 (invisible-before-point (if (bobp) nil (get-char-property
18973 (1- (point)) 'invisible)))
18974 (border-and-ok-direction
18976 ;; Check if we are acting predictably before invisible text
18977 (and invisible-at-point (not invisible-before-point)
18978 (memq kind '(insert delete-backward)))
18979 ;; Check if we are acting predictably after invisible text
18980 ;; This works not well, and I have turned it off. It seems
18981 ;; better to always show and stop after invisible text.
18982 ;; (and (not invisible-at-point) invisible-before-point
18983 ;; (memq kind '(insert delete)))
18985 (when (or (memq invisible-at-point '(outline org-hide-block t))
18986 (memq invisible-before-point '(outline org-hide-block t)))
18987 (if (eq org-catch-invisible-edits 'error)
18988 (error "Editing in invisible areas is prohibited - make visible first"))
18989 (if (and org-custom-properties-overlays
18990 (y-or-n-p "Display invisible properties in this buffer? "))
18991 (org-toggle-custom-properties-visibility)
18992 ;; Make the area visible
18993 (save-excursion
18994 (if invisible-before-point
18995 (goto-char (previous-single-char-property-change
18996 (point) 'invisible)))
18997 (org-cycle))
18998 (cond
18999 ((eq org-catch-invisible-edits 'show)
19000 ;; That's it, we do the edit after showing
19001 (message
19002 "Unfolding invisible region around point before editing")
19003 (sit-for 1))
19004 ((and (eq org-catch-invisible-edits 'smart)
19005 border-and-ok-direction)
19006 (message "Unfolding invisible region around point before editing"))
19008 ;; Don't do the edit, make the user repeat it in full visibility
19009 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19011 (defun org-fix-tags-on-the-fly ()
19012 (when (and (equal (char-after (point-at-bol)) ?*)
19013 (org-at-heading-p))
19014 (org-align-tags-here org-tags-column)))
19016 (defun org-delete-backward-char (N)
19017 "Like `delete-backward-char', insert whitespace at field end in tables.
19018 When deleting backwards, in tables this function will insert whitespace in
19019 front of the next \"|\" separator, to keep the table aligned. The table will
19020 still be marked for re-alignment if the field did fill the entire column,
19021 because, in this case the deletion might narrow the column."
19022 (interactive "p")
19023 (save-match-data
19024 (org-check-before-invisible-edit 'delete-backward)
19025 (if (and (org-table-p)
19026 (eq N 1)
19027 (string-match "|" (buffer-substring (point-at-bol) (point)))
19028 (looking-at ".*?|"))
19029 (let ((pos (point))
19030 (noalign (looking-at "[^|\n\r]* |"))
19031 (c org-table-may-need-update))
19032 (backward-delete-char N)
19033 (if (not overwrite-mode)
19034 (progn
19035 (skip-chars-forward "^|")
19036 (insert " ")
19037 (goto-char (1- pos))))
19038 ;; noalign: if there were two spaces at the end, this field
19039 ;; does not determine the width of the column.
19040 (if noalign (setq org-table-may-need-update c)))
19041 (backward-delete-char N)
19042 (org-fix-tags-on-the-fly))))
19044 (defun org-delete-char (N)
19045 "Like `delete-char', but insert whitespace at field end in tables.
19046 When deleting characters, in tables this function will insert whitespace in
19047 front of the next \"|\" separator, to keep the table aligned. The table will
19048 still be marked for re-alignment if the field did fill the entire column,
19049 because, in this case the deletion might narrow the column."
19050 (interactive "p")
19051 (save-match-data
19052 (org-check-before-invisible-edit 'delete)
19053 (if (and (org-table-p)
19054 (not (bolp))
19055 (not (= (char-after) ?|))
19056 (eq N 1))
19057 (if (looking-at ".*?|")
19058 (let ((pos (point))
19059 (noalign (looking-at "[^|\n\r]* |"))
19060 (c org-table-may-need-update))
19061 (replace-match (concat
19062 (substring (match-string 0) 1 -1)
19063 " |"))
19064 (goto-char pos)
19065 ;; noalign: if there were two spaces at the end, this field
19066 ;; does not determine the width of the column.
19067 (if noalign (setq org-table-may-need-update c)))
19068 (delete-char N))
19069 (delete-char N)
19070 (org-fix-tags-on-the-fly))))
19072 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19073 (put 'org-self-insert-command 'delete-selection t)
19074 (put 'orgtbl-self-insert-command 'delete-selection t)
19075 (put 'org-delete-char 'delete-selection 'supersede)
19076 (put 'org-delete-backward-char 'delete-selection 'supersede)
19077 (put 'org-yank 'delete-selection 'yank)
19079 ;; Make `flyspell-mode' delay after some commands
19080 (put 'org-self-insert-command 'flyspell-delayed t)
19081 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19082 (put 'org-delete-char 'flyspell-delayed t)
19083 (put 'org-delete-backward-char 'flyspell-delayed t)
19085 ;; Make pabbrev-mode expand after org-mode commands
19086 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19087 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19089 ;; How to do this: Measure non-white length of current string
19090 ;; If equal to column width, we should realign.
19092 (defun org-remap (map &rest commands)
19093 "In MAP, remap the functions given in COMMANDS.
19094 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19095 (let (new old)
19096 (while commands
19097 (setq old (pop commands) new (pop commands))
19098 (if (fboundp 'command-remapping)
19099 (org-defkey map (vector 'remap old) new)
19100 (substitute-key-definition old new map global-map)))))
19102 (defun org-transpose-words ()
19103 "Transpose words for Org.
19104 This uses the `org-mode-transpose-word-syntax-table' syntax
19105 table, which interprets characters in `org-emphasis-alist' as
19106 word constituants."
19107 (interactive)
19108 (with-syntax-table org-mode-transpose-word-syntax-table
19109 (call-interactively 'transpose-words)))
19110 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19112 (when (eq org-enable-table-editor 'optimized)
19113 ;; If the user wants maximum table support, we need to hijack
19114 ;; some standard editing functions
19115 (org-remap org-mode-map
19116 'self-insert-command 'org-self-insert-command
19117 'delete-char 'org-delete-char
19118 'delete-backward-char 'org-delete-backward-char)
19119 (org-defkey org-mode-map "|" 'org-force-self-insert))
19121 (defvar org-ctrl-c-ctrl-c-hook nil
19122 "Hook for functions attaching themselves to `C-c C-c'.
19124 This can be used to add additional functionality to the C-c C-c
19125 key which executes context-dependent commands. This hook is run
19126 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19127 run after the last test.
19129 Each function will be called with no arguments. The function
19130 must check if the context is appropriate for it to act. If yes,
19131 it should do its thing and then return a non-nil value. If the
19132 context is wrong, just do nothing and return nil.")
19134 (defvar org-ctrl-c-ctrl-c-final-hook nil
19135 "Hook for functions attaching themselves to `C-c C-c'.
19137 This can be used to add additional functionality to the C-c C-c
19138 key which executes context-dependent commands. This hook is run
19139 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19140 before the first test.
19142 Each function will be called with no arguments. The function
19143 must check if the context is appropriate for it to act. If yes,
19144 it should do its thing and then return a non-nil value. If the
19145 context is wrong, just do nothing and return nil.")
19147 (defvar org-tab-first-hook nil
19148 "Hook for functions to attach themselves to TAB.
19149 See `org-ctrl-c-ctrl-c-hook' for more information.
19150 This hook runs as the first action when TAB is pressed, even before
19151 `org-cycle' messes around with the `outline-regexp' to cater for
19152 inline tasks and plain list item folding.
19153 If any function in this hook returns t, any other actions that
19154 would have been caused by TAB (such as table field motion or visibility
19155 cycling) will not occur.")
19157 (defvar org-tab-after-check-for-table-hook nil
19158 "Hook for functions to attach themselves to TAB.
19159 See `org-ctrl-c-ctrl-c-hook' for more information.
19160 This hook runs after it has been established that the cursor is not in a
19161 table, but before checking if the cursor is in a headline or if global cycling
19162 should be done.
19163 If any function in this hook returns t, not other actions like visibility
19164 cycling will be done.")
19166 (defvar org-tab-after-check-for-cycling-hook nil
19167 "Hook for functions to attach themselves to TAB.
19168 See `org-ctrl-c-ctrl-c-hook' for more information.
19169 This hook runs after it has been established that not table field motion and
19170 not visibility should be done because of current context. This is probably
19171 the place where a package like yasnippets can hook in.")
19173 (defvar org-tab-before-tab-emulation-hook nil
19174 "Hook for functions to attach themselves to TAB.
19175 See `org-ctrl-c-ctrl-c-hook' for more information.
19176 This hook runs after every other options for TAB have been exhausted, but
19177 before indentation and \t insertion takes place.")
19179 (defvar org-metaleft-hook nil
19180 "Hook for functions attaching themselves to `M-left'.
19181 See `org-ctrl-c-ctrl-c-hook' for more information.")
19182 (defvar org-metaright-hook nil
19183 "Hook for functions attaching themselves to `M-right'.
19184 See `org-ctrl-c-ctrl-c-hook' for more information.")
19185 (defvar org-metaup-hook nil
19186 "Hook for functions attaching themselves to `M-up'.
19187 See `org-ctrl-c-ctrl-c-hook' for more information.")
19188 (defvar org-metadown-hook nil
19189 "Hook for functions attaching themselves to `M-down'.
19190 See `org-ctrl-c-ctrl-c-hook' for more information.")
19191 (defvar org-shiftmetaleft-hook nil
19192 "Hook for functions attaching themselves to `M-S-left'.
19193 See `org-ctrl-c-ctrl-c-hook' for more information.")
19194 (defvar org-shiftmetaright-hook nil
19195 "Hook for functions attaching themselves to `M-S-right'.
19196 See `org-ctrl-c-ctrl-c-hook' for more information.")
19197 (defvar org-shiftmetaup-hook nil
19198 "Hook for functions attaching themselves to `M-S-up'.
19199 See `org-ctrl-c-ctrl-c-hook' for more information.")
19200 (defvar org-shiftmetadown-hook nil
19201 "Hook for functions attaching themselves to `M-S-down'.
19202 See `org-ctrl-c-ctrl-c-hook' for more information.")
19203 (defvar org-metareturn-hook nil
19204 "Hook for functions attaching themselves to `M-RET'.
19205 See `org-ctrl-c-ctrl-c-hook' for more information.")
19206 (defvar org-shiftup-hook nil
19207 "Hook for functions attaching themselves to `S-up'.
19208 See `org-ctrl-c-ctrl-c-hook' for more information.")
19209 (defvar org-shiftup-final-hook nil
19210 "Hook for functions attaching themselves to `S-up'.
19211 This one runs after all other options except shift-select have been excluded.
19212 See `org-ctrl-c-ctrl-c-hook' for more information.")
19213 (defvar org-shiftdown-hook nil
19214 "Hook for functions attaching themselves to `S-down'.
19215 See `org-ctrl-c-ctrl-c-hook' for more information.")
19216 (defvar org-shiftdown-final-hook nil
19217 "Hook for functions attaching themselves to `S-down'.
19218 This one runs after all other options except shift-select have been excluded.
19219 See `org-ctrl-c-ctrl-c-hook' for more information.")
19220 (defvar org-shiftleft-hook nil
19221 "Hook for functions attaching themselves to `S-left'.
19222 See `org-ctrl-c-ctrl-c-hook' for more information.")
19223 (defvar org-shiftleft-final-hook nil
19224 "Hook for functions attaching themselves to `S-left'.
19225 This one runs after all other options except shift-select have been excluded.
19226 See `org-ctrl-c-ctrl-c-hook' for more information.")
19227 (defvar org-shiftright-hook nil
19228 "Hook for functions attaching themselves to `S-right'.
19229 See `org-ctrl-c-ctrl-c-hook' for more information.")
19230 (defvar org-shiftright-final-hook nil
19231 "Hook for functions attaching themselves to `S-right'.
19232 This one runs after all other options except shift-select have been excluded.
19233 See `org-ctrl-c-ctrl-c-hook' for more information.")
19235 (defun org-modifier-cursor-error ()
19236 "Throw an error, a modified cursor command was applied in wrong context."
19237 (error "This command is active in special context like tables, headlines or items"))
19239 (defun org-shiftselect-error ()
19240 "Throw an error because Shift-Cursor command was applied in wrong context."
19241 (if (and (boundp 'shift-select-mode) shift-select-mode)
19242 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19243 (error "This command works only in special context like headlines or timestamps")))
19245 (defun org-call-for-shift-select (cmd)
19246 (let ((this-command-keys-shift-translated t))
19247 (call-interactively cmd)))
19249 (defun org-shifttab (&optional arg)
19250 "Global visibility cycling or move to previous table field.
19251 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19252 on context.
19253 See the individual commands for more information."
19254 (interactive "P")
19255 (cond
19256 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19257 ((integerp arg)
19258 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19259 (message "Content view to level: %d" arg)
19260 (org-content (prefix-numeric-value arg2))
19261 (setq org-cycle-global-status 'overview)))
19262 (t (call-interactively 'org-global-cycle))))
19264 (defun org-shiftmetaleft ()
19265 "Promote subtree or delete table column.
19266 Calls `org-promote-subtree', `org-outdent-item-tree', or
19267 `org-table-delete-column', depending on context. See the
19268 individual commands for more information."
19269 (interactive)
19270 (cond
19271 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19272 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19273 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19274 ((if (not (org-region-active-p)) (org-at-item-p)
19275 (save-excursion (goto-char (region-beginning))
19276 (org-at-item-p)))
19277 (call-interactively 'org-outdent-item-tree))
19278 (t (org-modifier-cursor-error))))
19280 (defun org-shiftmetaright ()
19281 "Demote subtree or insert table column.
19282 Calls `org-demote-subtree', `org-indent-item-tree', or
19283 `org-table-insert-column', depending on context. See the
19284 individual commands for more information."
19285 (interactive)
19286 (cond
19287 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19288 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19289 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19290 ((if (not (org-region-active-p)) (org-at-item-p)
19291 (save-excursion (goto-char (region-beginning))
19292 (org-at-item-p)))
19293 (call-interactively 'org-indent-item-tree))
19294 (t (org-modifier-cursor-error))))
19296 (defun org-shiftmetaup (&optional arg)
19297 "Move subtree up or kill table row.
19298 Calls `org-move-subtree-up' or `org-table-kill-row' or
19299 `org-move-item-up' or `org-timestamp-up', depending on context.
19300 See the individual commands for more information."
19301 (interactive "P")
19302 (cond
19303 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19304 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19305 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19306 ((org-at-item-p) (call-interactively 'org-move-item-up))
19307 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19308 (call-interactively 'org-timestamp-up)))
19309 (t (call-interactively 'org-drag-line-backward))))
19311 (defun org-shiftmetadown (&optional arg)
19312 "Move subtree down or insert table row.
19313 Calls `org-move-subtree-down' or `org-table-insert-row' or
19314 `org-move-item-down' or `org-timestamp-up', depending on context.
19315 See the individual commands for more information."
19316 (interactive "P")
19317 (cond
19318 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19319 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19320 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19321 ((org-at-item-p) (call-interactively 'org-move-item-down))
19322 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19323 (call-interactively 'org-timestamp-down)))
19324 (t (call-interactively 'org-drag-line-forward))))
19326 (defsubst org-hidden-tree-error ()
19327 (error
19328 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19330 (defun org-metaleft (&optional arg)
19331 "Promote heading or move table column to left.
19332 Calls `org-do-promote' or `org-table-move-column', depending on context.
19333 With no specific context, calls the Emacs default `backward-word'.
19334 See the individual commands for more information."
19335 (interactive "P")
19336 (cond
19337 ((run-hook-with-args-until-success 'org-metaleft-hook))
19338 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19339 ((org-with-limited-levels
19340 (or (org-at-heading-p)
19341 (and (org-region-active-p)
19342 (save-excursion
19343 (goto-char (region-beginning))
19344 (org-at-heading-p)))))
19345 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19346 (call-interactively 'org-do-promote))
19347 ;; At an inline task.
19348 ((org-at-heading-p)
19349 (call-interactively 'org-inlinetask-promote))
19350 ((or (org-at-item-p)
19351 (and (org-region-active-p)
19352 (save-excursion
19353 (goto-char (region-beginning))
19354 (org-at-item-p))))
19355 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19356 (call-interactively 'org-outdent-item))
19357 (t (call-interactively 'backward-word))))
19359 (defun org-metaright (&optional arg)
19360 "Demote a subtree, a list item or move table column to right.
19361 In front of a drawer or a block keyword, indent it correctly.
19362 With no specific context, calls the Emacs default `forward-word'.
19363 See the individual commands for more information."
19364 (interactive "P")
19365 (cond
19366 ((run-hook-with-args-until-success 'org-metaright-hook))
19367 ((org-at-table-p) (call-interactively 'org-table-move-column))
19368 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19369 ((org-at-block-p) (call-interactively 'org-indent-block))
19370 ((org-with-limited-levels
19371 (or (org-at-heading-p)
19372 (and (org-region-active-p)
19373 (save-excursion
19374 (goto-char (region-beginning))
19375 (org-at-heading-p)))))
19376 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19377 (call-interactively 'org-do-demote))
19378 ;; At an inline task.
19379 ((org-at-heading-p)
19380 (call-interactively 'org-inlinetask-demote))
19381 ((or (org-at-item-p)
19382 (and (org-region-active-p)
19383 (save-excursion
19384 (goto-char (region-beginning))
19385 (org-at-item-p))))
19386 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19387 (call-interactively 'org-indent-item))
19388 (t (call-interactively 'forward-word))))
19390 (defun org-check-for-hidden (what)
19391 "Check if there are hidden headlines/items in the current visual line.
19392 WHAT can be either `headlines' or `items'. If the current line is
19393 an outline or item heading and it has a folded subtree below it,
19394 this function returns t, nil otherwise."
19395 (let ((re (cond
19396 ((eq what 'headlines) org-outline-regexp-bol)
19397 ((eq what 'items) (org-item-beginning-re))
19398 (t (error "This should not happen"))))
19399 beg end)
19400 (save-excursion
19401 (catch 'exit
19402 (unless (org-region-active-p)
19403 (setq beg (point-at-bol))
19404 (beginning-of-line 2)
19405 (while (and (not (eobp)) ;; this is like `next-line'
19406 (get-char-property (1- (point)) 'invisible))
19407 (beginning-of-line 2))
19408 (setq end (point))
19409 (goto-char beg)
19410 (goto-char (point-at-eol))
19411 (setq end (max end (point)))
19412 (while (re-search-forward re end t)
19413 (if (get-char-property (match-beginning 0) 'invisible)
19414 (throw 'exit t))))
19415 nil))))
19417 (defun org-metaup (&optional arg)
19418 "Move subtree up or move table row up.
19419 Calls `org-move-subtree-up' or `org-table-move-row' or
19420 `org-move-item-up', depending on context. See the individual commands
19421 for more information."
19422 (interactive "P")
19423 (cond
19424 ((run-hook-with-args-until-success 'org-metaup-hook))
19425 ((org-region-active-p)
19426 (let* ((a (min (region-beginning) (region-end)))
19427 (b (1- (max (region-beginning) (region-end))))
19428 (c (save-excursion (goto-char a)
19429 (move-beginning-of-line 0)))
19430 (d (save-excursion (goto-char a)
19431 (move-end-of-line 0) (point))))
19432 (transpose-regions a b c d)
19433 (goto-char c)))
19434 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19435 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19436 ((org-at-item-p) (call-interactively 'org-move-item-up))
19437 (t (org-drag-element-backward))))
19439 (defun org-metadown (&optional arg)
19440 "Move subtree down or move table row down.
19441 Calls `org-move-subtree-down' or `org-table-move-row' or
19442 `org-move-item-down', depending on context. See the individual
19443 commands for more information."
19444 (interactive "P")
19445 (cond
19446 ((run-hook-with-args-until-success 'org-metadown-hook))
19447 ((org-region-active-p)
19448 (let* ((a (min (region-beginning) (region-end)))
19449 (b (max (region-beginning) (region-end)))
19450 (c (save-excursion (goto-char b)
19451 (move-beginning-of-line 1)))
19452 (d (save-excursion (goto-char b)
19453 (move-end-of-line 1) (1+ (point)))))
19454 (transpose-regions a b c d)
19455 (goto-char d)))
19456 ((org-at-table-p) (call-interactively 'org-table-move-row))
19457 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19458 ((org-at-item-p) (call-interactively 'org-move-item-down))
19459 (t (org-drag-element-forward))))
19461 (defun org-shiftup (&optional arg)
19462 "Increase item in timestamp or increase priority of current headline.
19463 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19464 depending on context. See the individual commands for more information."
19465 (interactive "P")
19466 (cond
19467 ((run-hook-with-args-until-success 'org-shiftup-hook))
19468 ((and org-support-shift-select (org-region-active-p))
19469 (org-call-for-shift-select 'previous-line))
19470 ((org-at-timestamp-p t)
19471 (call-interactively (if org-edit-timestamp-down-means-later
19472 'org-timestamp-down 'org-timestamp-up)))
19473 ((and (not (eq org-support-shift-select 'always))
19474 org-enable-priority-commands
19475 (org-at-heading-p))
19476 (call-interactively 'org-priority-up))
19477 ((and (not org-support-shift-select) (org-at-item-p))
19478 (call-interactively 'org-previous-item))
19479 ((org-clocktable-try-shift 'up arg))
19480 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19481 (org-support-shift-select
19482 (org-call-for-shift-select 'previous-line))
19483 (t (org-shiftselect-error))))
19485 (defun org-shiftdown (&optional arg)
19486 "Decrease item in timestamp or decrease priority of current headline.
19487 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19488 depending on context. See the individual commands for more information."
19489 (interactive "P")
19490 (cond
19491 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19492 ((and org-support-shift-select (org-region-active-p))
19493 (org-call-for-shift-select 'next-line))
19494 ((org-at-timestamp-p t)
19495 (call-interactively (if org-edit-timestamp-down-means-later
19496 'org-timestamp-up 'org-timestamp-down)))
19497 ((and (not (eq org-support-shift-select 'always))
19498 org-enable-priority-commands
19499 (org-at-heading-p))
19500 (call-interactively 'org-priority-down))
19501 ((and (not org-support-shift-select) (org-at-item-p))
19502 (call-interactively 'org-next-item))
19503 ((org-clocktable-try-shift 'down arg))
19504 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19505 (org-support-shift-select
19506 (org-call-for-shift-select 'next-line))
19507 (t (org-shiftselect-error))))
19509 (defun org-shiftright (&optional arg)
19510 "Cycle the thing at point or in the current line, depending on context.
19511 Depending on context, this does one of the following:
19513 - switch a timestamp at point one day into the future
19514 - on a headline, switch to the next TODO keyword.
19515 - on an item, switch entire list to the next bullet type
19516 - on a property line, switch to the next allowed value
19517 - on a clocktable definition line, move time block into the future"
19518 (interactive "P")
19519 (cond
19520 ((run-hook-with-args-until-success 'org-shiftright-hook))
19521 ((and org-support-shift-select (org-region-active-p))
19522 (org-call-for-shift-select 'forward-char))
19523 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19524 ((and (not (eq org-support-shift-select 'always))
19525 (org-at-heading-p))
19526 (let ((org-inhibit-logging
19527 (not org-treat-S-cursor-todo-selection-as-state-change))
19528 (org-inhibit-blocking
19529 (not org-treat-S-cursor-todo-selection-as-state-change)))
19530 (org-call-with-arg 'org-todo 'right)))
19531 ((or (and org-support-shift-select
19532 (not (eq org-support-shift-select 'always))
19533 (org-at-item-bullet-p))
19534 (and (not org-support-shift-select) (org-at-item-p)))
19535 (org-call-with-arg 'org-cycle-list-bullet nil))
19536 ((and (not (eq org-support-shift-select 'always))
19537 (org-at-property-p))
19538 (call-interactively 'org-property-next-allowed-value))
19539 ((org-clocktable-try-shift 'right arg))
19540 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19541 (org-support-shift-select
19542 (org-call-for-shift-select 'forward-char))
19543 (t (org-shiftselect-error))))
19545 (defun org-shiftleft (&optional arg)
19546 "Cycle the thing at point or in the current line, depending on context.
19547 Depending on context, this does one of the following:
19549 - switch a timestamp at point one day into the past
19550 - on a headline, switch to the previous TODO keyword.
19551 - on an item, switch entire list to the previous bullet type
19552 - on a property line, switch to the previous allowed value
19553 - on a clocktable definition line, move time block into the past"
19554 (interactive "P")
19555 (cond
19556 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19557 ((and org-support-shift-select (org-region-active-p))
19558 (org-call-for-shift-select 'backward-char))
19559 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19560 ((and (not (eq org-support-shift-select 'always))
19561 (org-at-heading-p))
19562 (let ((org-inhibit-logging
19563 (not org-treat-S-cursor-todo-selection-as-state-change))
19564 (org-inhibit-blocking
19565 (not org-treat-S-cursor-todo-selection-as-state-change)))
19566 (org-call-with-arg 'org-todo 'left)))
19567 ((or (and org-support-shift-select
19568 (not (eq org-support-shift-select 'always))
19569 (org-at-item-bullet-p))
19570 (and (not org-support-shift-select) (org-at-item-p)))
19571 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19572 ((and (not (eq org-support-shift-select 'always))
19573 (org-at-property-p))
19574 (call-interactively 'org-property-previous-allowed-value))
19575 ((org-clocktable-try-shift 'left arg))
19576 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19577 (org-support-shift-select
19578 (org-call-for-shift-select 'backward-char))
19579 (t (org-shiftselect-error))))
19581 (defun org-shiftcontrolright ()
19582 "Switch to next TODO set."
19583 (interactive)
19584 (cond
19585 ((and org-support-shift-select (org-region-active-p))
19586 (org-call-for-shift-select 'forward-word))
19587 ((and (not (eq org-support-shift-select 'always))
19588 (org-at-heading-p))
19589 (org-call-with-arg 'org-todo 'nextset))
19590 (org-support-shift-select
19591 (org-call-for-shift-select 'forward-word))
19592 (t (org-shiftselect-error))))
19594 (defun org-shiftcontrolleft ()
19595 "Switch to previous TODO set."
19596 (interactive)
19597 (cond
19598 ((and org-support-shift-select (org-region-active-p))
19599 (org-call-for-shift-select 'backward-word))
19600 ((and (not (eq org-support-shift-select 'always))
19601 (org-at-heading-p))
19602 (org-call-with-arg 'org-todo 'previousset))
19603 (org-support-shift-select
19604 (org-call-for-shift-select 'backward-word))
19605 (t (org-shiftselect-error))))
19607 (defun org-shiftcontrolup (&optional n)
19608 "Change timestamps synchronously up in CLOCK log lines.
19609 Optional argument N tells to change by that many units."
19610 (interactive "P")
19611 (cond ((and (not org-support-shift-select)
19612 (org-at-clock-log-p)
19613 (org-at-timestamp-p t))
19614 (org-clock-timestamps-up n))
19615 (t (org-shiftselect-error))))
19617 (defun org-shiftcontroldown (&optional n)
19618 "Change timestamps synchronously down in CLOCK log lines.
19619 Optional argument N tells to change by that many units."
19620 (interactive "P")
19621 (cond ((and (not org-support-shift-select)
19622 (org-at-clock-log-p)
19623 (org-at-timestamp-p t))
19624 (org-clock-timestamps-down n))
19625 (t (org-shiftselect-error))))
19627 (defun org-ctrl-c-ret ()
19628 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19629 (interactive)
19630 (cond
19631 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19632 (t (call-interactively 'org-insert-heading))))
19634 (defun org-find-visible ()
19635 (let ((s (point)))
19636 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19637 (get-char-property s 'invisible)))
19639 (defun org-find-invisible ()
19640 (let ((s (point)))
19641 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19642 (not (get-char-property s 'invisible))))
19645 (defun org-copy-visible (beg end)
19646 "Copy the visible parts of the region."
19647 (interactive "r")
19648 (let (snippets s)
19649 (save-excursion
19650 (save-restriction
19651 (narrow-to-region beg end)
19652 (setq s (goto-char (point-min)))
19653 (while (not (= (point) (point-max)))
19654 (goto-char (org-find-invisible))
19655 (push (buffer-substring s (point)) snippets)
19656 (setq s (goto-char (org-find-visible))))))
19657 (kill-new (apply 'concat (nreverse snippets)))))
19659 (defun org-copy-special ()
19660 "Copy region in table or copy current subtree.
19661 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19662 See the individual commands for more information."
19663 (interactive)
19664 (call-interactively
19665 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19667 (defun org-cut-special ()
19668 "Cut region in table or cut current subtree.
19669 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19670 See the individual commands for more information."
19671 (interactive)
19672 (call-interactively
19673 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19675 (defun org-paste-special (arg)
19676 "Paste rectangular region into table, or past subtree relative to level.
19677 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19678 See the individual commands for more information."
19679 (interactive "P")
19680 (if (org-at-table-p)
19681 (org-table-paste-rectangle)
19682 (org-paste-subtree arg)))
19684 (defsubst org-in-fixed-width-region-p ()
19685 "Is point in a fixed-width region?"
19686 (save-match-data
19687 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19689 (defun org-edit-special (&optional arg)
19690 "Call a special editor for the element at point.
19691 When at a table, call the formula editor with `org-table-edit-formulas'.
19692 When in a source code block, call `org-edit-src-code'.
19693 When in a fixed-width region, call `org-edit-fixed-width-region'.
19694 When at an #+INCLUDE keyword, visit the included file.
19695 On a link, call `ffap' to visit the link at point.
19696 Otherwise, return a user error."
19697 (interactive)
19698 (let ((element (org-element-at-point)))
19699 (assert (not buffer-read-only) nil
19700 "Buffer is read-only: %s" (buffer-name))
19701 (case (org-element-type element)
19702 (src-block
19703 (if (not arg) (org-edit-src-code)
19704 (let* ((info (org-babel-get-src-block-info))
19705 (lang (nth 0 info))
19706 (params (nth 2 info))
19707 (session (cdr (assq :session params))))
19708 (if (not session) (org-edit-src-code)
19709 ;; At a src-block with a session and function called with
19710 ;; an ARG: switch to the buffer related to the inferior
19711 ;; process.
19712 (funcall (intern (concat "org-babel-prep-session:" lang))
19713 session params)))))
19714 (keyword
19715 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19716 (find-file
19717 (org-remove-double-quotes
19718 (car (org-split-string (org-element-property :value element)))))
19719 (user-error "No special environment to edit here")))
19720 (table
19721 (if (eq (org-element-property :type element) 'table.el)
19722 (org-edit-src-code)
19723 (call-interactively 'org-table-edit-formulas)))
19724 ;; Only Org tables contain `table-row' type elements.
19725 (table-row (call-interactively 'org-table-edit-formulas))
19726 ((example-block export-block) (org-edit-src-code))
19727 (fixed-width (org-edit-fixed-width-region))
19728 (otherwise
19729 ;; No notable element at point. Though, we may be at a link,
19730 ;; which is an object. Thus, scan deeper.
19731 (if (eq (org-element-type (org-element-context element)) 'link)
19732 (call-interactively 'ffap)
19733 (user-error "No special environment to edit here"))))))
19735 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19736 (defun org-ctrl-c-ctrl-c (&optional arg)
19737 "Set tags in headline, or update according to changed information at point.
19739 This command does many different things, depending on context:
19741 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19742 this is what we do.
19744 - If the cursor is on a statistics cookie, update it.
19746 - If the cursor is in a headline, prompt for tags and insert them
19747 into the current line, aligned to `org-tags-column'. When called
19748 with prefix arg, realign all tags in the current buffer.
19750 - If the cursor is in one of the special #+KEYWORD lines, this
19751 triggers scanning the buffer for these lines and updating the
19752 information.
19754 - If the cursor is inside a table, realign the table. This command
19755 works even if the automatic table editor has been turned off.
19757 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19758 the entire table.
19760 - If the cursor is at a footnote reference or definition, jump to
19761 the corresponding definition or references, respectively.
19763 - If the cursor is a the beginning of a dynamic block, update it.
19765 - If the current buffer is a capture buffer, close note and file it.
19767 - If the cursor is on a <<<target>>>, update radio targets and
19768 corresponding links in this buffer.
19770 - If the cursor is on a numbered item in a plain list, renumber the
19771 ordered list.
19773 - If the cursor is on a checkbox, toggle it.
19775 - If the cursor is on a code block, evaluate it. The variable
19776 `org-confirm-babel-evaluate' can be used to control prompting
19777 before code block evaluation, by default every code block
19778 evaluation requires confirmation. Code block evaluation can be
19779 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19780 (interactive "P")
19781 (cond
19782 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19783 org-occur-highlights
19784 org-latex-fragment-image-overlays)
19785 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19786 (org-remove-occur-highlights)
19787 (org-remove-latex-fragment-image-overlays)
19788 (message "Temporary highlights/overlays removed from current buffer"))
19789 ((and (local-variable-p 'org-finish-function (current-buffer))
19790 (fboundp org-finish-function))
19791 (funcall org-finish-function))
19792 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19794 (let* ((context (org-element-context)) (type (org-element-type context)))
19795 ;; Test if point is within a blank line.
19796 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19797 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19798 (user-error "C-c C-c can do nothing useful at this location"))
19799 ;; For convenience: at the first line of a paragraph on the
19800 ;; same line as an item, apply function on that item instead.
19801 (when (eq type 'paragraph)
19802 (let ((parent (org-element-property :parent context)))
19803 (when (and (eq (org-element-type parent) 'item)
19804 (= (point-at-bol) (org-element-property :begin parent)))
19805 (setq context parent type 'item))))
19806 ;; Act according to type of element or object at point.
19807 (case type
19808 (clock (org-clock-update-time-maybe))
19809 (dynamic-block
19810 (save-excursion
19811 (goto-char (org-element-property :post-affiliated context))
19812 (org-update-dblock)))
19813 (footnote-definition
19814 (goto-char (org-element-property :post-affiliated context))
19815 (call-interactively 'org-footnote-action))
19816 (footnote-reference (call-interactively 'org-footnote-action))
19817 ((headline inlinetask)
19818 (save-excursion (goto-char (org-element-property :begin context))
19819 (call-interactively 'org-set-tags)))
19820 (item
19821 ;; At an item: a double C-u set checkbox to "[-]"
19822 ;; unconditionally, whereas a single one will toggle its
19823 ;; presence. Without an universal argument, if the item
19824 ;; has a checkbox, toggle it. Otherwise repair the list.
19825 (let* ((box (org-element-property :checkbox context))
19826 (struct (org-element-property :structure context))
19827 (old-struct (copy-tree struct))
19828 (parents (org-list-parents-alist struct))
19829 (prevs (org-list-prevs-alist struct))
19830 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19831 (org-list-set-checkbox
19832 (org-element-property :begin context) struct
19833 (cond ((equal arg '(16)) "[-]")
19834 ((and (not box) (equal arg '(4))) "[ ]")
19835 ((or (not box) (equal arg '(4))) nil)
19836 ((eq box 'on) "[ ]")
19837 (t "[X]")))
19838 ;; Mimic `org-list-write-struct' but with grabbing
19839 ;; a return value from `org-list-struct-fix-box'.
19840 (org-list-struct-fix-ind struct parents 2)
19841 (org-list-struct-fix-item-end struct)
19842 (org-list-struct-fix-bul struct prevs)
19843 (org-list-struct-fix-ind struct parents)
19844 (let ((block-item
19845 (org-list-struct-fix-box struct parents prevs orderedp)))
19846 (if (and box (equal struct old-struct))
19847 (if (equal arg '(16))
19848 (message "Checkboxes already reset")
19849 (user-error "Cannot toggle this checkbox: %s"
19850 (if (eq box 'on)
19851 "all subitems checked"
19852 "unchecked subitems")))
19853 (org-list-struct-apply-struct struct old-struct)
19854 (org-update-checkbox-count-maybe))
19855 (when block-item
19856 (message "Checkboxes were removed due to empty box at line %d"
19857 (org-current-line block-item))))))
19858 (keyword
19859 (let ((org-inhibit-startup-visibility-stuff t)
19860 (org-startup-align-all-tables nil))
19861 (when (boundp 'org-table-coordinate-overlays)
19862 (mapc 'delete-overlay org-table-coordinate-overlays)
19863 (setq org-table-coordinate-overlays nil))
19864 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19865 (message "Local setup has been refreshed"))
19866 (plain-list
19867 ;; At a plain list, with a double C-u argument, set
19868 ;; checkboxes of each item to "[-]", whereas a single one
19869 ;; will toggle their presence according to the state of the
19870 ;; first item in the list. Without an argument, repair the
19871 ;; list.
19872 (let* ((begin (org-element-property :contents-begin context))
19873 (struct (org-element-property :structure context))
19874 (old-struct (copy-tree struct))
19875 (first-box (save-excursion
19876 (goto-char begin)
19877 (looking-at org-list-full-item-re)
19878 (match-string-no-properties 3)))
19879 (new-box (cond ((equal arg '(16)) "[-]")
19880 ((equal arg '(4)) (unless first-box "[ ]"))
19881 ((equal first-box "[X]") "[ ]")
19882 (t "[X]"))))
19883 (cond
19884 (arg
19885 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19886 (org-list-get-all-items
19887 begin struct (org-list-prevs-alist struct))))
19888 ((and first-box (eq (point) begin))
19889 ;; For convenience, when point is at bol on the first
19890 ;; item of the list and no argument is provided, simply
19891 ;; toggle checkbox of that item, if any.
19892 (org-list-set-checkbox begin struct new-box)))
19893 (org-list-write-struct
19894 struct (org-list-parents-alist struct) old-struct)
19895 (org-update-checkbox-count-maybe)
19896 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19897 ((property-drawer node-property)
19898 (call-interactively 'org-property-action))
19899 ((radio-target target)
19900 (call-interactively 'org-update-radio-target-regexp))
19901 (statistics-cookie
19902 (call-interactively 'org-update-statistics-cookies))
19903 ((table table-cell table-row)
19904 ;; At a table, recalculate every field and align it. Also
19905 ;; send the table if necessary. If the table has
19906 ;; a `table.el' type, just give up. At a table row or
19907 ;; cell, maybe recalculate line but always align table.
19908 (if (eq (org-element-property :type context) 'table.el)
19909 (message "Use C-c ' to edit table.el tables")
19910 (let ((org-enable-table-editor t))
19911 (if (or (eq type 'table)
19912 ;; Check if point is at a TBLFM line.
19913 (and (eq type 'table-row)
19914 (= (point) (org-element-property :end context))))
19915 (save-excursion
19916 (goto-char (org-element-property :contents-begin context))
19917 (org-call-with-arg 'org-table-recalculate (or arg t))
19918 (orgtbl-send-table 'maybe))
19919 (org-table-maybe-eval-formula)
19920 (cond (arg (call-interactively 'org-table-recalculate))
19921 ((org-table-maybe-recalculate-line))
19922 (t (org-table-align)))))))
19923 (timestamp (org-timestamp-change 0 'day))
19924 (otherwise
19925 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19926 (user-error
19927 "C-c C-c can do nothing useful at this location")))))))))
19929 (defun org-mode-restart ()
19930 "Restart Org-mode, to scan again for special lines.
19931 Also updates the keyword regular expressions."
19932 (interactive)
19933 (org-mode)
19934 (message "Org-mode restarted"))
19936 (defun org-kill-note-or-show-branches ()
19937 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19938 (interactive)
19939 (if (not org-finish-function)
19940 (progn
19941 (hide-subtree)
19942 (call-interactively 'show-branches))
19943 (let ((org-note-abort t))
19944 (funcall org-finish-function))))
19946 (defun org-return (&optional indent)
19947 "Goto next table row or insert a newline.
19948 Calls `org-table-next-row' or `newline', depending on context.
19949 See the individual commands for more information."
19950 (interactive)
19951 (let (org-ts-what)
19952 (cond
19953 ((or (bobp) (org-in-src-block-p))
19954 (if indent (newline-and-indent) (newline)))
19955 ((org-at-table-p)
19956 (org-table-justify-field-maybe)
19957 (call-interactively 'org-table-next-row))
19958 ;; when `newline-and-indent' is called within a list, make sure
19959 ;; text moved stays inside the item.
19960 ((and (org-in-item-p) indent)
19961 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19962 (progn
19963 (save-match-data (newline))
19964 (org-indent-line-to (length (match-string 0))))
19965 (let ((ind (org-get-indentation)))
19966 (newline)
19967 (if (org-looking-back org-list-end-re)
19968 (org-indent-line)
19969 (org-indent-line-to ind)))))
19970 ((and org-return-follows-link
19971 (org-at-timestamp-p t)
19972 (not (eq org-ts-what 'after)))
19973 (org-follow-timestamp-link))
19974 ((and org-return-follows-link
19975 (let ((tprop (get-text-property (point) 'face)))
19976 (or (eq tprop 'org-link)
19977 (and (listp tprop) (memq 'org-link tprop)))))
19978 (call-interactively 'org-open-at-point))
19979 ((and (org-at-heading-p)
19980 (looking-at
19981 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19982 (org-show-entry)
19983 (end-of-line 1)
19984 (newline))
19985 (t (if indent (newline-and-indent) (newline))))))
19987 (defun org-return-indent ()
19988 "Goto next table row or insert a newline and indent.
19989 Calls `org-table-next-row' or `newline-and-indent', depending on
19990 context. See the individual commands for more information."
19991 (interactive)
19992 (org-return t))
19994 (defun org-ctrl-c-star ()
19995 "Compute table, or change heading status of lines.
19996 Calls `org-table-recalculate' or `org-toggle-heading',
19997 depending on context."
19998 (interactive)
19999 (cond
20000 ((org-at-table-p)
20001 (call-interactively 'org-table-recalculate))
20003 ;; Convert all lines in region to list items
20004 (call-interactively 'org-toggle-heading))))
20006 (defun org-ctrl-c-minus ()
20007 "Insert separator line in table or modify bullet status of line.
20008 Also turns a plain line or a region of lines into list items.
20009 Calls `org-table-insert-hline', `org-toggle-item', or
20010 `org-cycle-list-bullet', depending on context."
20011 (interactive)
20012 (cond
20013 ((org-at-table-p)
20014 (call-interactively 'org-table-insert-hline))
20015 ((org-region-active-p)
20016 (call-interactively 'org-toggle-item))
20017 ((org-in-item-p)
20018 (call-interactively 'org-cycle-list-bullet))
20020 (call-interactively 'org-toggle-item))))
20022 (defun org-toggle-item (arg)
20023 "Convert headings or normal lines to items, items to normal lines.
20024 If there is no active region, only the current line is considered.
20026 If the first non blank line in the region is a headline, convert
20027 all headlines to items, shifting text accordingly.
20029 If it is an item, convert all items to normal lines.
20031 If it is normal text, change region into an item. With a prefix
20032 argument ARG, change each line in region into an item."
20033 (interactive "P")
20034 (let ((shift-text
20035 (function
20036 ;; Shift text in current section to IND, from point to END.
20037 ;; The function leaves point to END line.
20038 (lambda (ind end)
20039 (let ((min-i 1000) (end (copy-marker end)))
20040 ;; First determine the minimum indentation (MIN-I) of
20041 ;; the text.
20042 (save-excursion
20043 (catch 'exit
20044 (while (< (point) end)
20045 (let ((i (org-get-indentation)))
20046 (cond
20047 ;; Skip blank lines and inline tasks.
20048 ((looking-at "^[ \t]*$"))
20049 ((looking-at org-outline-regexp-bol))
20050 ;; We can't find less than 0 indentation.
20051 ((zerop i) (throw 'exit (setq min-i 0)))
20052 ((< i min-i) (setq min-i i))))
20053 (forward-line))))
20054 ;; Then indent each line so that a line indented to
20055 ;; MIN-I becomes indented to IND. Ignore blank lines
20056 ;; and inline tasks in the process.
20057 (let ((delta (- ind min-i)))
20058 (while (< (point) end)
20059 (unless (or (looking-at "^[ \t]*$")
20060 (looking-at org-outline-regexp-bol))
20061 (org-indent-line-to (+ (org-get-indentation) delta)))
20062 (forward-line)))))))
20063 (skip-blanks
20064 (function
20065 ;; Return beginning of first non-blank line, starting from
20066 ;; line at POS.
20067 (lambda (pos)
20068 (save-excursion
20069 (goto-char pos)
20070 (skip-chars-forward " \r\t\n")
20071 (point-at-bol)))))
20072 beg end)
20073 ;; Determine boundaries of changes.
20074 (if (org-region-active-p)
20075 (setq beg (funcall skip-blanks (region-beginning))
20076 end (copy-marker (region-end)))
20077 (setq beg (funcall skip-blanks (point-at-bol))
20078 end (copy-marker (point-at-eol))))
20079 ;; Depending on the starting line, choose an action on the text
20080 ;; between BEG and END.
20081 (org-with-limited-levels
20082 (save-excursion
20083 (goto-char beg)
20084 (cond
20085 ;; Case 1. Start at an item: de-itemize. Note that it only
20086 ;; happens when a region is active: `org-ctrl-c-minus'
20087 ;; would call `org-cycle-list-bullet' otherwise.
20088 ((org-at-item-p)
20089 (while (< (point) end)
20090 (when (org-at-item-p)
20091 (skip-chars-forward " \t")
20092 (delete-region (point) (match-end 0)))
20093 (forward-line)))
20094 ;; Case 2. Start at an heading: convert to items.
20095 ((org-at-heading-p)
20096 (let* ((bul (org-list-bullet-string "-"))
20097 (bul-len (length bul))
20098 ;; Indentation of the first heading. It should be
20099 ;; relative to the indentation of its parent, if any.
20100 (start-ind (save-excursion
20101 (cond
20102 ((not org-adapt-indentation) 0)
20103 ((not (outline-previous-heading)) 0)
20104 (t (length (match-string 0))))))
20105 ;; Level of first heading. Further headings will be
20106 ;; compared to it to determine hierarchy in the list.
20107 (ref-level (org-reduced-level (org-outline-level))))
20108 (while (< (point) end)
20109 (let* ((level (org-reduced-level (org-outline-level)))
20110 (delta (max 0 (- level ref-level))))
20111 ;; If current headline is less indented than the first
20112 ;; one, set it as reference, in order to preserve
20113 ;; subtrees.
20114 (when (< level ref-level) (setq ref-level level))
20115 (replace-match bul t t)
20116 (org-indent-line-to (+ start-ind (* delta bul-len)))
20117 ;; Ensure all text down to END (or SECTION-END) belongs
20118 ;; to the newly created item.
20119 (let ((section-end (save-excursion
20120 (or (outline-next-heading) (point)))))
20121 (forward-line)
20122 (funcall shift-text
20123 (+ start-ind (* (1+ delta) bul-len))
20124 (min end section-end)))))))
20125 ;; Case 3. Normal line with ARG: turn each non-item line into
20126 ;; an item.
20127 (arg
20128 (while (< (point) end)
20129 (unless (or (org-at-heading-p) (org-at-item-p))
20130 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20131 (replace-match
20132 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20133 (forward-line)))
20134 ;; Case 4. Normal line without ARG: make the first line of
20135 ;; region an item, and shift indentation of others
20136 ;; lines to set them as item's body.
20137 (t (let* ((bul (org-list-bullet-string "-"))
20138 (bul-len (length bul))
20139 (ref-ind (org-get-indentation)))
20140 (skip-chars-forward " \t")
20141 (insert bul)
20142 (forward-line)
20143 (while (< (point) end)
20144 ;; Ensure that lines less indented than first one
20145 ;; still get included in item body.
20146 (funcall shift-text
20147 (+ ref-ind bul-len)
20148 (min end (save-excursion (or (outline-next-heading)
20149 (point)))))
20150 (forward-line)))))))))
20152 (defun org-toggle-heading (&optional nstars)
20153 "Convert headings to normal text, or items or text to headings.
20154 If there is no active region, only the current line is considered.
20156 With a \\[universal-argument] prefix, convert the whole list at
20157 point into heading.
20159 In a region:
20161 - If the first non blank line is a headline, remove the stars
20162 from all headlines in the region.
20164 - If it is a normal line turn each and every normal line (i.e. not an
20165 heading or an item) in the region into a heading.
20167 - If it is a plain list item, turn all plain list items into headings.
20169 When converting a line into a heading, the number of stars is chosen
20170 such that the lines become children of the current entry. However,
20171 when a prefix argument is given, its value determines the number of
20172 stars to add."
20173 (interactive "P")
20174 (let ((skip-blanks
20175 (function
20176 ;; Return beginning of first non-blank line, starting from
20177 ;; line at POS.
20178 (lambda (pos)
20179 (save-excursion
20180 (goto-char pos)
20181 (while (org-at-comment-p) (forward-line))
20182 (skip-chars-forward " \r\t\n")
20183 (point-at-bol)))))
20184 beg end toggled)
20185 ;; Determine boundaries of changes. If a universal prefix has
20186 ;; been given, put the list in a region. If region ends at a bol,
20187 ;; do not consider the last line to be in the region.
20189 (when (and current-prefix-arg (org-at-item-p))
20190 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20191 (org-mark-element))
20193 (if (org-region-active-p)
20194 (setq beg (funcall skip-blanks (region-beginning))
20195 end (copy-marker (save-excursion
20196 (goto-char (region-end))
20197 (if (bolp) (point) (point-at-eol)))))
20198 (setq beg (funcall skip-blanks (point-at-bol))
20199 end (copy-marker (point-at-eol))))
20200 ;; Ensure inline tasks don't count as headings.
20201 (org-with-limited-levels
20202 (save-excursion
20203 (goto-char beg)
20204 (cond
20205 ;; Case 1. Started at an heading: de-star headings.
20206 ((org-at-heading-p)
20207 (while (< (point) end)
20208 (when (org-at-heading-p t)
20209 (looking-at org-outline-regexp) (replace-match "")
20210 (setq toggled t))
20211 (forward-line)))
20212 ;; Case 2. Started at an item: change items into headlines.
20213 ;; One star will be added by `org-list-to-subtree'.
20214 ((org-at-item-p)
20215 (let* ((stars (make-string
20216 (if nstars
20217 ;; subtract the star that will be added again by
20218 ;; `org-list-to-subtree'
20219 (1- (prefix-numeric-value current-prefix-arg))
20220 (or (org-current-level) 0))
20221 ?*))
20222 (add-stars
20223 (cond (nstars "") ; stars from prefix only
20224 ((equal stars "") "") ; before first heading
20225 (org-odd-levels-only "*") ; inside heading, odd
20226 (t "")))) ; inside heading, oddeven
20227 (while (< (point) end)
20228 (when (org-at-item-p)
20229 ;; Pay attention to cases when region ends before list.
20230 (let* ((struct (org-list-struct))
20231 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20232 (save-restriction
20233 (narrow-to-region (point) list-end)
20234 (insert
20235 (org-list-to-subtree
20236 (org-list-parse-list t)
20237 '(:istart (concat stars add-stars (funcall get-stars depth))
20238 :icount (concat stars add-stars (funcall get-stars depth)))))))
20239 (setq toggled t))
20240 (forward-line))))
20241 ;; Case 3. Started at normal text: make every line an heading,
20242 ;; skipping headlines and items.
20243 (t (let* ((stars (make-string
20244 (if nstars
20245 (prefix-numeric-value current-prefix-arg)
20246 (or (org-current-level) 0))
20247 ?*))
20248 (add-stars
20249 (cond (nstars "") ; stars from prefix only
20250 ((equal stars "") "*") ; before first heading
20251 (org-odd-levels-only "**") ; inside heading, odd
20252 (t "*"))) ; inside heading, oddeven
20253 (rpl (concat stars add-stars " ")))
20254 (while (< (point) end)
20255 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20256 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20257 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20258 (forward-line)))))))
20259 (unless toggled (message "Cannot toggle heading from here"))))
20261 (defun org-meta-return (&optional arg)
20262 "Insert a new heading or wrap a region in a table.
20263 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20264 See the individual commands for more information."
20265 (interactive "P")
20266 (cond
20267 ((run-hook-with-args-until-success 'org-metareturn-hook))
20268 ((or (org-at-drawer-p) (org-at-property-p))
20269 (newline-and-indent))
20270 ((org-at-table-p)
20271 (call-interactively 'org-table-wrap-region))
20272 (t (call-interactively 'org-insert-heading))))
20274 ;;; Menu entries
20276 (defsubst org-in-subtree-not-table-p ()
20277 "Are we in a subtree and not in a table?"
20278 (and (not (org-before-first-heading-p))
20279 (not (org-at-table-p))))
20281 ;; Define the Org-mode menus
20282 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20283 '("Tbl"
20284 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20285 ["Next Field" org-cycle (org-at-table-p)]
20286 ["Previous Field" org-shifttab (org-at-table-p)]
20287 ["Next Row" org-return (org-at-table-p)]
20288 "--"
20289 ["Blank Field" org-table-blank-field (org-at-table-p)]
20290 ["Edit Field" org-table-edit-field (org-at-table-p)]
20291 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20292 "--"
20293 ("Column"
20294 ["Move Column Left" org-metaleft (org-at-table-p)]
20295 ["Move Column Right" org-metaright (org-at-table-p)]
20296 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20297 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20298 ("Row"
20299 ["Move Row Up" org-metaup (org-at-table-p)]
20300 ["Move Row Down" org-metadown (org-at-table-p)]
20301 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20302 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20303 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20304 "--"
20305 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20306 ("Rectangle"
20307 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20308 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20309 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20310 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20311 "--"
20312 ("Calculate"
20313 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20314 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20315 ["Edit Formulas" org-edit-special (org-at-table-p)]
20316 "--"
20317 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20318 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20319 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20320 "--"
20321 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20322 "--"
20323 ["Sum Column/Rectangle" org-table-sum
20324 (or (org-at-table-p) (org-region-active-p))]
20325 ["Which Column?" org-table-current-column (org-at-table-p)])
20326 ["Debug Formulas"
20327 org-table-toggle-formula-debugger
20328 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20329 ["Show Col/Row Numbers"
20330 org-table-toggle-coordinate-overlays
20331 :style toggle
20332 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20333 "--"
20334 ["Create" org-table-create (and (not (org-at-table-p))
20335 org-enable-table-editor)]
20336 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20337 ["Import from File" org-table-import (not (org-at-table-p))]
20338 ["Export to File" org-table-export (org-at-table-p)]
20339 "--"
20340 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20342 (easy-menu-define org-org-menu org-mode-map "Org menu"
20343 '("Org"
20344 ("Show/Hide"
20345 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20346 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20347 ["Sparse Tree..." org-sparse-tree t]
20348 ["Reveal Context" org-reveal t]
20349 ["Show All" show-all t]
20350 "--"
20351 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20352 "--"
20353 ["New Heading" org-insert-heading t]
20354 ("Navigate Headings"
20355 ["Up" outline-up-heading t]
20356 ["Next" outline-next-visible-heading t]
20357 ["Previous" outline-previous-visible-heading t]
20358 ["Next Same Level" outline-forward-same-level t]
20359 ["Previous Same Level" outline-backward-same-level t]
20360 "--"
20361 ["Jump" org-goto t])
20362 ("Edit Structure"
20363 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20364 "--"
20365 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20366 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20367 "--"
20368 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20369 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20370 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20371 "--"
20372 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20373 "--"
20374 ["Copy visible text" org-copy-visible t]
20375 "--"
20376 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20377 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20378 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20379 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20380 "--"
20381 ["Sort Region/Children" org-sort t]
20382 "--"
20383 ["Convert to odd levels" org-convert-to-odd-levels t]
20384 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20385 ("Editing"
20386 ["Emphasis..." org-emphasize t]
20387 ["Edit Source Example" org-edit-special t]
20388 "--"
20389 ["Footnote new/jump" org-footnote-action t]
20390 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20391 ("Archive"
20392 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20393 "--"
20394 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20395 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20396 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20398 "--"
20399 ("Hyperlinks"
20400 ["Store Link (Global)" org-store-link t]
20401 ["Find existing link to here" org-occur-link-in-agenda-files t]
20402 ["Insert Link" org-insert-link t]
20403 ["Follow Link" org-open-at-point t]
20404 "--"
20405 ["Next link" org-next-link t]
20406 ["Previous link" org-previous-link t]
20407 "--"
20408 ["Descriptive Links"
20409 org-toggle-link-display
20410 :style radio
20411 :selected org-descriptive-links
20413 ["Literal Links"
20414 org-toggle-link-display
20415 :style radio
20416 :selected (not org-descriptive-links)])
20417 "--"
20418 ("TODO Lists"
20419 ["TODO/DONE/-" org-todo t]
20420 ("Select keyword"
20421 ["Next keyword" org-shiftright (org-at-heading-p)]
20422 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20423 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20424 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20425 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20426 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20427 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20428 "--"
20429 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20430 :selected org-enforce-todo-dependencies :style toggle :active t]
20431 "Settings for tree at point"
20432 ["Do Children sequentially" org-toggle-ordered-property :style radio
20433 :selected (org-entry-get nil "ORDERED")
20434 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20435 ["Do Children parallel" org-toggle-ordered-property :style radio
20436 :selected (not (org-entry-get nil "ORDERED"))
20437 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20438 "--"
20439 ["Set Priority" org-priority t]
20440 ["Priority Up" org-shiftup t]
20441 ["Priority Down" org-shiftdown t]
20442 "--"
20443 ["Get news from all feeds" org-feed-update-all t]
20444 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20445 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20446 ("TAGS and Properties"
20447 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20448 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20449 "--"
20450 ["Set property" org-set-property (not (org-before-first-heading-p))]
20451 ["Column view of properties" org-columns t]
20452 ["Insert Column View DBlock" org-insert-columns-dblock t])
20453 ("Dates and Scheduling"
20454 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20455 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20456 ("Change Date"
20457 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20458 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20459 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20460 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20461 ["Compute Time Range" org-evaluate-time-range t]
20462 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20463 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20464 "--"
20465 ["Custom time format" org-toggle-time-stamp-overlays
20466 :style radio :selected org-display-custom-times]
20467 "--"
20468 ["Goto Calendar" org-goto-calendar t]
20469 ["Date from Calendar" org-date-from-calendar t]
20470 "--"
20471 ["Start/Restart Timer" org-timer-start t]
20472 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20473 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20474 ["Insert Timer String" org-timer t]
20475 ["Insert Timer Item" org-timer-item t])
20476 ("Logging work"
20477 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20478 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20479 ["Clock out" org-clock-out t]
20480 ["Clock cancel" org-clock-cancel t]
20481 "--"
20482 ["Mark as default task" org-clock-mark-default-task t]
20483 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20484 ["Goto running clock" org-clock-goto t]
20485 "--"
20486 ["Display times" org-clock-display t]
20487 ["Create clock table" org-clock-report t]
20488 "--"
20489 ["Record DONE time"
20490 (progn (setq org-log-done (not org-log-done))
20491 (message "Switching to %s will %s record a timestamp"
20492 (car org-done-keywords)
20493 (if org-log-done "automatically" "not")))
20494 :style toggle :selected org-log-done])
20495 "--"
20496 ["Agenda Command..." org-agenda t]
20497 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20498 ("File List for Agenda")
20499 ("Special views current file"
20500 ["TODO Tree" org-show-todo-tree t]
20501 ["Check Deadlines" org-check-deadlines t]
20502 ["Timeline" org-timeline t]
20503 ["Tags/Property tree" org-match-sparse-tree t])
20504 "--"
20505 ["Export/Publish..." org-export-dispatch t]
20506 ("LaTeX"
20507 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20508 :selected org-cdlatex-mode]
20509 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20510 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20511 ["Modify math symbol" org-cdlatex-math-modify
20512 (org-inside-LaTeX-fragment-p)]
20513 ["Insert citation" org-reftex-citation t]
20514 "--"
20515 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20516 "--"
20517 ("MobileOrg"
20518 ["Push Files and Views" org-mobile-push t]
20519 ["Get Captured and Flagged" org-mobile-pull t]
20520 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20521 "--"
20522 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20523 "--"
20524 ("Documentation"
20525 ["Show Version" org-version t]
20526 ["Info Documentation" org-info t])
20527 ("Customize"
20528 ["Browse Org Group" org-customize t]
20529 "--"
20530 ["Expand This Menu" org-create-customize-menu
20531 (fboundp 'customize-menu-create)])
20532 ["Send bug report" org-submit-bug-report t]
20533 "--"
20534 ("Refresh/Reload"
20535 ["Refresh setup current buffer" org-mode-restart t]
20536 ["Reload Org (after update)" org-reload t]
20537 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20540 (defun org-info (&optional node)
20541 "Read documentation for Org-mode in the info system.
20542 With optional NODE, go directly to that node."
20543 (interactive)
20544 (info (format "(org)%s" (or node ""))))
20546 ;;;###autoload
20547 (defun org-submit-bug-report ()
20548 "Submit a bug report on Org-mode via mail.
20550 Don't hesitate to report any problems or inaccurate documentation.
20552 If you don't have setup sending mail from (X)Emacs, please copy the
20553 output buffer into your mail program, as it gives us important
20554 information about your Org-mode version and configuration."
20555 (interactive)
20556 (require 'reporter)
20557 (org-load-modules-maybe)
20558 (org-require-autoloaded-modules)
20559 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20560 (reporter-submit-bug-report
20561 "emacs-orgmode@gnu.org"
20562 (org-version nil 'full)
20563 (let (list)
20564 (save-window-excursion
20565 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20566 (delete-other-windows)
20567 (erase-buffer)
20568 (insert "You are about to submit a bug report to the Org-mode mailing list.
20570 We would like to add your full Org-mode and Outline configuration to the
20571 bug report. This greatly simplifies the work of the maintainer and
20572 other experts on the mailing list.
20574 HOWEVER, some variables you have customized may contain private
20575 information. The names of customers, colleagues, or friends, might
20576 appear in the form of file names, tags, todo states, or search strings.
20577 If you answer yes to the prompt, you might want to check and remove
20578 such private information before sending the email.")
20579 (add-text-properties (point-min) (point-max) '(face org-warning))
20580 (when (yes-or-no-p "Include your Org-mode configuration ")
20581 (mapatoms
20582 (lambda (v)
20583 (and (boundp v)
20584 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20585 (or (and (symbol-value v)
20586 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20587 (and
20588 (get v 'custom-type) (get v 'standard-value)
20589 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20590 (push v list)))))
20591 (kill-buffer (get-buffer "*Warn about privacy*"))
20592 list))
20593 nil nil
20594 "Remember to cover the basics, that is, what you expected to happen and
20595 what in fact did happen. You don't know how to make a good report? See
20597 http://orgmode.org/manual/Feedback.html#Feedback
20599 Your bug report will be posted to the Org-mode mailing list.
20600 ------------------------------------------------------------------------")
20601 (save-excursion
20602 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20603 (replace-match "\\1Bug: \\3 [\\2]")))))
20606 (defun org-install-agenda-files-menu ()
20607 (let ((bl (buffer-list)))
20608 (save-excursion
20609 (while bl
20610 (set-buffer (pop bl))
20611 (if (derived-mode-p 'org-mode) (setq bl nil)))
20612 (when (derived-mode-p 'org-mode)
20613 (easy-menu-change
20614 '("Org") "File List for Agenda"
20615 (append
20616 (list
20617 ["Edit File List" (org-edit-agenda-file-list) t]
20618 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20619 ["Remove Current File from List" org-remove-file t]
20620 ["Cycle through agenda files" org-cycle-agenda-files t]
20621 ["Occur in all agenda files" org-occur-in-agenda-files t]
20622 "--")
20623 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20625 ;;;; Documentation
20627 (defun org-require-autoloaded-modules ()
20628 (interactive)
20629 (mapc 'require
20630 '(org-agenda org-archive org-attach org-clock org-colview org-id
20631 org-remember org-table org-timer)))
20633 ;;;###autoload
20634 (defun org-reload (&optional uncompiled)
20635 "Reload all org lisp files.
20636 With prefix arg UNCOMPILED, load the uncompiled versions."
20637 (interactive "P")
20638 (require 'loadhist)
20639 (let* ((org-dir (org-find-library-dir "org"))
20640 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20641 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20642 (remove-re (mapconcat 'identity
20643 (mapcar (lambda (f) (concat "^" f "$"))
20644 (list (if (featurep 'xemacs)
20645 "org-colview"
20646 "org-colview-xemacs")
20647 "org" "org-loaddefs" "org-version"))
20648 "\\|"))
20649 (feats (delete-dups
20650 (mapcar 'file-name-sans-extension
20651 (mapcar 'file-name-nondirectory
20652 (delq nil
20653 (mapcar 'feature-file
20654 features))))))
20655 (lfeat (append
20656 (sort
20657 (setq feats
20658 (delq nil (mapcar
20659 (lambda (f)
20660 (if (and (string-match feature-re f)
20661 (not (string-match remove-re f)))
20662 f nil))
20663 feats)))
20664 'string-lessp)
20665 (list "org-version" "org")))
20666 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20667 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20668 load-uncore load-misses)
20669 (setq load-misses
20670 (delq 't
20671 (mapcar (lambda (f)
20672 (or (org-load-noerror-mustsuffix (concat org-dir f))
20673 (and (string= org-dir contrib-dir)
20674 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20675 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20676 (add-to-list 'load-uncore f 'append)
20679 lfeat)))
20680 (if load-uncore
20681 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20682 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20683 (if load-misses
20684 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20685 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20686 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20688 ;;;###autoload
20689 (defun org-customize ()
20690 "Call the customize function with org as argument."
20691 (interactive)
20692 (org-load-modules-maybe)
20693 (org-require-autoloaded-modules)
20694 (customize-browse 'org))
20696 (defun org-create-customize-menu ()
20697 "Create a full customization menu for Org-mode, insert it into the menu."
20698 (interactive)
20699 (org-load-modules-maybe)
20700 (org-require-autoloaded-modules)
20701 (if (fboundp 'customize-menu-create)
20702 (progn
20703 (easy-menu-change
20704 '("Org") "Customize"
20705 `(["Browse Org group" org-customize t]
20706 "--"
20707 ,(customize-menu-create 'org)
20708 ["Set" Custom-set t]
20709 ["Save" Custom-save t]
20710 ["Reset to Current" Custom-reset-current t]
20711 ["Reset to Saved" Custom-reset-saved t]
20712 ["Reset to Standard Settings" Custom-reset-standard t]))
20713 (message "\"Org\"-menu now contains full customization menu"))
20714 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20716 ;;;; Miscellaneous stuff
20718 ;;; Generally useful functions
20720 (defun org-get-at-bol (property)
20721 "Get text property PROPERTY at beginning of line."
20722 (get-text-property (point-at-bol) property))
20724 (defun org-find-text-property-in-string (prop s)
20725 "Return the first non-nil value of property PROP in string S."
20726 (or (get-text-property 0 prop s)
20727 (get-text-property (or (next-single-property-change 0 prop s) 0)
20728 prop s)))
20730 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20731 "Display the given MESSAGE as a warning."
20732 (if (fboundp 'display-warning)
20733 (display-warning 'org message
20734 (if (featurep 'xemacs) 'warning :warning))
20735 (let ((buf (get-buffer-create "*Org warnings*")))
20736 (with-current-buffer buf
20737 (goto-char (point-max))
20738 (insert "Warning (Org): " message)
20739 (unless (bolp)
20740 (newline)))
20741 (display-buffer buf)
20742 (sit-for 0))))
20744 (defun org-eval (form)
20745 "Eval FORM and return result."
20746 (condition-case error
20747 (eval form)
20748 (error (format "%%![Error: %s]" error))))
20750 (defun org-in-clocktable-p ()
20751 "Check if the cursor is in a clocktable."
20752 (let ((pos (point)) start)
20753 (save-excursion
20754 (end-of-line 1)
20755 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20756 (setq start (match-beginning 0))
20757 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20758 (>= (match-end 0) pos)
20759 start))))
20761 (defun org-in-commented-line ()
20762 "Is point in a line starting with `#'?"
20763 (equal (char-after (point-at-bol)) ?#))
20765 (defun org-in-indented-comment-line ()
20766 "Is point in a line starting with `#' after some white space?"
20767 (save-excursion
20768 (save-match-data
20769 (goto-char (point-at-bol))
20770 (looking-at "[ \t]*#"))))
20772 (defun org-in-verbatim-emphasis ()
20773 (save-match-data
20774 (and (org-in-regexp org-emph-re 2)
20775 (>= (point) (match-beginning 3))
20776 (<= (point) (match-end 4))
20777 (member (match-string 3) '("=" "~")))))
20779 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20780 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20781 (if (and marker (marker-buffer marker)
20782 (buffer-live-p (marker-buffer marker)))
20783 (progn
20784 (org-pop-to-buffer-same-window (marker-buffer marker))
20785 (if (or (> marker (point-max)) (< marker (point-min)))
20786 (widen))
20787 (goto-char marker)
20788 (org-show-context 'org-goto))
20789 (if bookmark
20790 (bookmark-jump bookmark)
20791 (error "Cannot find location"))))
20793 (defun org-quote-csv-field (s)
20794 "Quote field for inclusion in CSV material."
20795 (if (string-match "[\",]" s)
20796 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20799 (defun org-force-self-insert (N)
20800 "Needed to enforce self-insert under remapping."
20801 (interactive "p")
20802 (self-insert-command N))
20804 (defun org-string-width (s)
20805 "Compute width of string, ignoring invisible characters.
20806 This ignores character with invisibility property `org-link', and also
20807 characters with property `org-cwidth', because these will become invisible
20808 upon the next fontification round."
20809 (let (b l)
20810 (when (or (eq t buffer-invisibility-spec)
20811 (assq 'org-link buffer-invisibility-spec))
20812 (while (setq b (text-property-any 0 (length s)
20813 'invisible 'org-link s))
20814 (setq s (concat (substring s 0 b)
20815 (substring s (or (next-single-property-change
20816 b 'invisible s) (length s)))))))
20817 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20818 (setq s (concat (substring s 0 b)
20819 (substring s (or (next-single-property-change
20820 b 'org-cwidth s) (length s))))))
20821 (setq l (string-width s) b -1)
20822 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20823 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20826 (defun org-shorten-string (s maxlength)
20827 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20828 If the string is shorter or has length MAXLENGTH, just return the
20829 original string. If it is longer, the functions finds a space in the
20830 string, breaks this string off at that locations and adds three dots
20831 as ellipsis. Including the ellipsis, the string will not be longer
20832 than MAXLENGTH. If finding a good breaking point in the string does
20833 not work, the string is just chopped off in the middle of a word
20834 if necessary."
20835 (if (<= (length s) maxlength)
20837 (let* ((n (max (- maxlength 4) 1))
20838 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20839 (if (string-match re s)
20840 (concat (match-string 1 s) "...")
20841 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20843 (defun org-get-indentation (&optional line)
20844 "Get the indentation of the current line, interpreting tabs.
20845 When LINE is given, assume it represents a line and compute its indentation."
20846 (if line
20847 (if (string-match "^ *" (org-remove-tabs line))
20848 (match-end 0))
20849 (save-excursion
20850 (beginning-of-line 1)
20851 (skip-chars-forward " \t")
20852 (current-column))))
20854 (defun org-get-string-indentation (s)
20855 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20856 (let ((n -1) (i 0) (w tab-width) c)
20857 (catch 'exit
20858 (while (< (setq n (1+ n)) (length s))
20859 (setq c (aref s n))
20860 (cond ((= c ?\ ) (setq i (1+ i)))
20861 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20862 (t (throw 'exit t)))))
20865 (defun org-remove-tabs (s &optional width)
20866 "Replace tabulators in S with spaces.
20867 Assumes that s is a single line, starting in column 0."
20868 (setq width (or width tab-width))
20869 (while (string-match "\t" s)
20870 (setq s (replace-match
20871 (make-string
20872 (- (* width (/ (+ (match-beginning 0) width) width))
20873 (match-beginning 0)) ?\ )
20874 t t s)))
20877 (defun org-fix-indentation (line ind)
20878 "Fix indentation in LINE.
20879 IND is a cons cell with target and minimum indentation.
20880 If the current indentation in LINE is smaller than the minimum,
20881 leave it alone. If it is larger than ind, set it to the target."
20882 (let* ((l (org-remove-tabs line))
20883 (i (org-get-indentation l))
20884 (i1 (car ind)) (i2 (cdr ind)))
20885 (if (>= i i2) (setq l (substring line i2)))
20886 (if (> i1 0)
20887 (concat (make-string i1 ?\ ) l)
20888 l)))
20890 (defun org-remove-indentation (code &optional n)
20891 "Remove the maximum common indentation from the lines in CODE.
20892 N may optionally be the number of spaces to remove."
20893 (with-temp-buffer
20894 (insert code)
20895 (org-do-remove-indentation n)
20896 (buffer-string)))
20898 (defun org-do-remove-indentation (&optional n)
20899 "Remove the maximum common indentation from the buffer."
20900 (untabify (point-min) (point-max))
20901 (let ((min 10000) re)
20902 (if n
20903 (setq min n)
20904 (goto-char (point-min))
20905 (while (re-search-forward "^ *[^ \n]" nil t)
20906 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20907 (unless (or (= min 0) (= min 10000))
20908 (setq re (format "^ \\{%d\\}" min))
20909 (goto-char (point-min))
20910 (while (re-search-forward re nil t)
20911 (replace-match "")
20912 (end-of-line 1))
20913 min)))
20915 (defun org-fill-template (template alist)
20916 "Find each %key of ALIST in TEMPLATE and replace it."
20917 (let ((case-fold-search nil)
20918 entry key value)
20919 (setq alist (sort (copy-sequence alist)
20920 (lambda (a b) (< (length (car a)) (length (car b))))))
20921 (while (setq entry (pop alist))
20922 (setq template
20923 (replace-regexp-in-string
20924 (concat "%" (regexp-quote (car entry)))
20925 (or (cdr entry) "") template t t)))
20926 template))
20928 (defun org-base-buffer (buffer)
20929 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20930 (if (not buffer)
20931 buffer
20932 (or (buffer-base-buffer buffer)
20933 buffer)))
20935 (defun org-trim (s)
20936 "Remove whitespace at beginning and end of string."
20937 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20938 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20941 (defun org-wrap (string &optional width lines)
20942 "Wrap string to either a number of lines, or a width in characters.
20943 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20944 that costs. If there is a word longer than WIDTH, the text is actually
20945 wrapped to the length of that word.
20946 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20947 many lines, whatever width that takes.
20948 The return value is a list of lines, without newlines at the end."
20949 (let* ((words (org-split-string string "[ \t\n]+"))
20950 (maxword (apply 'max (mapcar 'org-string-width words)))
20951 w ll)
20952 (cond (width
20953 (org-do-wrap words (max maxword width)))
20954 (lines
20955 (setq w maxword)
20956 (setq ll (org-do-wrap words maxword))
20957 (if (<= (length ll) lines)
20959 (setq ll words)
20960 (while (> (length ll) lines)
20961 (setq w (1+ w))
20962 (setq ll (org-do-wrap words w)))
20963 ll))
20964 (t (error "Cannot wrap this")))))
20966 (defun org-do-wrap (words width)
20967 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20968 (let (lines line)
20969 (while words
20970 (setq line (pop words))
20971 (while (and words (< (+ (length line) (length (car words))) width))
20972 (setq line (concat line " " (pop words))))
20973 (setq lines (push line lines)))
20974 (nreverse lines)))
20976 (defun org-split-string (string &optional separators)
20977 "Splits STRING into substrings at SEPARATORS.
20978 No empty strings are returned if there are matches at the beginning
20979 and end of string."
20980 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20981 (start 0)
20982 notfirst
20983 (list nil))
20984 (while (and (string-match rexp string
20985 (if (and notfirst
20986 (= start (match-beginning 0))
20987 (< start (length string)))
20988 (1+ start) start))
20989 (< (match-beginning 0) (length string)))
20990 (setq notfirst t)
20991 (or (eq (match-beginning 0) 0)
20992 (and (eq (match-beginning 0) (match-end 0))
20993 (eq (match-beginning 0) start))
20994 (setq list
20995 (cons (substring string start (match-beginning 0))
20996 list)))
20997 (setq start (match-end 0)))
20998 (or (eq start (length string))
20999 (setq list
21000 (cons (substring string start)
21001 list)))
21002 (nreverse list)))
21004 (defun org-quote-vert (s)
21005 "Replace \"|\" with \"\\vert\"."
21006 (while (string-match "|" s)
21007 (setq s (replace-match "\\vert" t t s)))
21010 (defun org-uuidgen-p (s)
21011 "Is S an ID created by UUIDGEN?"
21012 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21014 (defun org-in-src-block-p (&optional inside)
21015 "Whether point is in a code source block.
21016 When INSIDE is non-nil, don't consider we are within a src block
21017 when point is at #+BEGIN_SRC or #+END_SRC."
21018 (let ((case-fold-search t) ov)
21019 (or (and (setq ov (overlays-at (point)))
21020 (memq 'org-block-background
21021 (overlay-properties (car ov))))
21022 (and (not inside)
21023 (save-match-data
21024 (save-excursion
21025 (beginning-of-line)
21026 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21028 (defun org-context ()
21029 "Return a list of contexts of the current cursor position.
21030 If several contexts apply, all are returned.
21031 Each context entry is a list with a symbol naming the context, and
21032 two positions indicating start and end of the context. Possible
21033 contexts are:
21035 :headline anywhere in a headline
21036 :headline-stars on the leading stars in a headline
21037 :todo-keyword on a TODO keyword (including DONE) in a headline
21038 :tags on the TAGS in a headline
21039 :priority on the priority cookie in a headline
21040 :item on the first line of a plain list item
21041 :item-bullet on the bullet/number of a plain list item
21042 :checkbox on the checkbox in a plain list item
21043 :table in an org-mode table
21044 :table-special on a special filed in a table
21045 :table-table in a table.el table
21046 :clocktable in a clocktable
21047 :src-block in a source block
21048 :link on a hyperlink
21049 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21050 :target on a <<target>>
21051 :radio-target on a <<<radio-target>>>
21052 :latex-fragment on a LaTeX fragment
21053 :latex-preview on a LaTeX fragment with overlaid preview image
21055 This function expects the position to be visible because it uses font-lock
21056 faces as a help to recognize the following contexts: :table-special, :link,
21057 and :keyword."
21058 (let* ((f (get-text-property (point) 'face))
21059 (faces (if (listp f) f (list f)))
21060 (case-fold-search t)
21061 (p (point)) clist o)
21062 ;; First the large context
21063 (cond
21064 ((org-at-heading-p t)
21065 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21066 (when (progn
21067 (beginning-of-line 1)
21068 (looking-at org-todo-line-tags-regexp))
21069 (push (org-point-in-group p 1 :headline-stars) clist)
21070 (push (org-point-in-group p 2 :todo-keyword) clist)
21071 (push (org-point-in-group p 4 :tags) clist))
21072 (goto-char p)
21073 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21074 (if (looking-at "\\[#[A-Z0-9]\\]")
21075 (push (org-point-in-group p 0 :priority) clist)))
21077 ((org-at-item-p)
21078 (push (org-point-in-group p 2 :item-bullet) clist)
21079 (push (list :item (point-at-bol)
21080 (save-excursion (org-end-of-item) (point)))
21081 clist)
21082 (and (org-at-item-checkbox-p)
21083 (push (org-point-in-group p 0 :checkbox) clist)))
21085 ((org-at-table-p)
21086 (push (list :table (org-table-begin) (org-table-end)) clist)
21087 (if (memq 'org-formula faces)
21088 (push (list :table-special
21089 (previous-single-property-change p 'face)
21090 (next-single-property-change p 'face)) clist)))
21091 ((org-at-table-p 'any)
21092 (push (list :table-table) clist)))
21093 (goto-char p)
21095 (let ((case-fold-search t))
21096 ;; New the "medium" contexts: clocktables, source blocks
21097 (cond ((org-in-clocktable-p)
21098 (push (list :clocktable
21099 (and (or (looking-at "#\\+BEGIN: clocktable")
21100 (search-backward "#+BEGIN: clocktable" nil t))
21101 (match-beginning 0))
21102 (and (re-search-forward "#\\+END:?" nil t)
21103 (match-end 0))) clist))
21104 ((org-in-src-block-p)
21105 (push (list :src-block
21106 (and (or (looking-at "#\\+BEGIN_SRC")
21107 (search-backward "#+BEGIN_SRC" nil t))
21108 (match-beginning 0))
21109 (and (search-forward "#+END_SRC" nil t)
21110 (match-beginning 0))) clist))))
21111 (goto-char p)
21113 ;; Now the small context
21114 (cond
21115 ((org-at-timestamp-p)
21116 (push (org-point-in-group p 0 :timestamp) clist))
21117 ((memq 'org-link faces)
21118 (push (list :link
21119 (previous-single-property-change p 'face)
21120 (next-single-property-change p 'face)) clist))
21121 ((memq 'org-special-keyword faces)
21122 (push (list :keyword
21123 (previous-single-property-change p 'face)
21124 (next-single-property-change p 'face)) clist))
21125 ((org-at-target-p)
21126 (push (org-point-in-group p 0 :target) clist)
21127 (goto-char (1- (match-beginning 0)))
21128 (if (looking-at org-radio-target-regexp)
21129 (push (org-point-in-group p 0 :radio-target) clist))
21130 (goto-char p))
21131 ((setq o (car (delq nil
21132 (mapcar
21133 (lambda (x)
21134 (if (memq x org-latex-fragment-image-overlays) x))
21135 (overlays-at (point))))))
21136 (push (list :latex-fragment
21137 (overlay-start o) (overlay-end o)) clist)
21138 (push (list :latex-preview
21139 (overlay-start o) (overlay-end o)) clist))
21140 ((org-inside-LaTeX-fragment-p)
21141 ;; FIXME: positions wrong.
21142 (push (list :latex-fragment (point) (point)) clist)))
21144 (setq clist (nreverse (delq nil clist)))
21145 clist))
21147 ;; FIXME: Compare with at-regexp-p Do we need both?
21148 (defun org-in-regexp (re &optional nlines visually)
21149 "Check if point is inside a match of regexp.
21150 Normally only the current line is checked, but you can include NLINES extra
21151 lines both before and after point into the search.
21152 If VISUALLY is set, require that the cursor is not after the match but
21153 really on, so that the block visually is on the match."
21154 (catch 'exit
21155 (let ((pos (point))
21156 (eol (point-at-eol (+ 1 (or nlines 0))))
21157 (inc (if visually 1 0)))
21158 (save-excursion
21159 (beginning-of-line (- 1 (or nlines 0)))
21160 (while (re-search-forward re eol t)
21161 (if (and (<= (match-beginning 0) pos)
21162 (>= (+ inc (match-end 0)) pos))
21163 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21165 (defun org-at-regexp-p (regexp)
21166 "Is point inside a match of REGEXP in the current line?"
21167 (catch 'exit
21168 (save-excursion
21169 (let ((pos (point)) (end (point-at-eol)))
21170 (beginning-of-line 1)
21171 (while (re-search-forward regexp end t)
21172 (if (and (<= (match-beginning 0) pos)
21173 (>= (match-end 0) pos))
21174 (throw 'exit t)))
21175 nil))))
21177 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21178 "Non-nil when point is between matches of START-RE and END-RE.
21180 Also return a non-nil value when point is on one of the matches.
21182 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21183 buffer positions. Default values are the positions of headlines
21184 surrounding the point.
21186 The functions returns a cons cell whose car (resp. cdr) is the
21187 position before START-RE (resp. after END-RE)."
21188 (save-match-data
21189 (let ((pos (point))
21190 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21191 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21192 beg end)
21193 (save-excursion
21194 ;; Point is on a block when on START-RE or if START-RE can be
21195 ;; found before it...
21196 (and (or (org-at-regexp-p start-re)
21197 (re-search-backward start-re limit-up t))
21198 (setq beg (match-beginning 0))
21199 ;; ... and END-RE after it...
21200 (goto-char (match-end 0))
21201 (re-search-forward end-re limit-down t)
21202 (> (setq end (match-end 0)) pos)
21203 ;; ... without another START-RE in-between.
21204 (goto-char (match-beginning 0))
21205 (not (re-search-backward start-re (1+ beg) t))
21206 ;; Return value.
21207 (cons beg end))))))
21209 (defun org-in-block-p (names)
21210 "Non-nil when point belongs to a block whose name belongs to NAMES.
21212 NAMES is a list of strings containing names of blocks.
21214 Return first block name matched, or nil. Beware that in case of
21215 nested blocks, the returned name may not belong to the closest
21216 block from point."
21217 (save-match-data
21218 (catch 'exit
21219 (let ((case-fold-search t)
21220 (lim-up (save-excursion (outline-previous-heading)))
21221 (lim-down (save-excursion (outline-next-heading))))
21222 (mapc (lambda (name)
21223 (let ((n (regexp-quote name)))
21224 (when (org-between-regexps-p
21225 (concat "^[ \t]*#\\+begin_" n)
21226 (concat "^[ \t]*#\\+end_" n)
21227 lim-up lim-down)
21228 (throw 'exit n))))
21229 names))
21230 nil)))
21232 (defun org-occur-in-agenda-files (regexp &optional nlines)
21233 "Call `multi-occur' with buffers for all agenda files."
21234 (interactive "sOrg-files matching: \np")
21235 (let* ((files (org-agenda-files))
21236 (tnames (mapcar 'file-truename files))
21237 (extra org-agenda-text-search-extra-files)
21239 (when (eq (car extra) 'agenda-archives)
21240 (setq extra (cdr extra))
21241 (setq files (org-add-archive-files files)))
21242 (while (setq f (pop extra))
21243 (unless (member (file-truename f) tnames)
21244 (add-to-list 'files f 'append)
21245 (add-to-list 'tnames (file-truename f) 'append)))
21246 (multi-occur
21247 (mapcar (lambda (x)
21248 (with-current-buffer
21249 (or (get-file-buffer x) (find-file-noselect x))
21250 (widen)
21251 (current-buffer)))
21252 files)
21253 regexp)))
21255 (if (boundp 'occur-mode-find-occurrence-hook)
21256 ;; Emacs 23
21257 (add-hook 'occur-mode-find-occurrence-hook
21258 (lambda ()
21259 (when (derived-mode-p 'org-mode)
21260 (org-reveal))))
21261 ;; Emacs 22
21262 (defadvice occur-mode-goto-occurrence
21263 (after org-occur-reveal activate)
21264 (and (derived-mode-p 'org-mode) (org-reveal)))
21265 (defadvice occur-mode-goto-occurrence-other-window
21266 (after org-occur-reveal activate)
21267 (and (derived-mode-p 'org-mode) (org-reveal)))
21268 (defadvice occur-mode-display-occurrence
21269 (after org-occur-reveal activate)
21270 (when (derived-mode-p 'org-mode)
21271 (let ((pos (occur-mode-find-occurrence)))
21272 (with-current-buffer (marker-buffer pos)
21273 (save-excursion
21274 (goto-char pos)
21275 (org-reveal)))))))
21277 (defun org-occur-link-in-agenda-files ()
21278 "Create a link and search for it in the agendas.
21279 The link is not stored in `org-stored-links', it is just created
21280 for the search purpose."
21281 (interactive)
21282 (let ((link (condition-case nil
21283 (org-store-link nil)
21284 (error "Unable to create a link to here"))))
21285 (org-occur-in-agenda-files (regexp-quote link))))
21287 (defun org-reverse-string (string)
21288 "Return the reverse of STRING."
21289 (apply 'string (reverse (string-to-list string))))
21291 (defun org-uniquify (list)
21292 "Remove duplicate elements from LIST."
21293 (let (res)
21294 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21295 res))
21297 (defun org-delete-all (elts list)
21298 "Remove all elements in ELTS from LIST."
21299 (while elts
21300 (setq list (delete (pop elts) list)))
21301 list)
21303 (defun org-count (cl-item cl-seq)
21304 "Count the number of occurrences of ITEM in SEQ.
21305 Taken from `count' in cl-seq.el with all keyword arguments removed."
21306 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21307 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21308 (while (< cl-start cl-end)
21309 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21310 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21311 (setq cl-start (1+ cl-start)))
21312 cl-count))
21314 (defun org-remove-if (predicate seq)
21315 "Remove everything from SEQ that fulfills PREDICATE."
21316 (let (res e)
21317 (while seq
21318 (setq e (pop seq))
21319 (if (not (funcall predicate e)) (push e res)))
21320 (nreverse res)))
21322 (defun org-remove-if-not (predicate seq)
21323 "Remove everything from SEQ that does not fulfill PREDICATE."
21324 (let (res e)
21325 (while seq
21326 (setq e (pop seq))
21327 (if (funcall predicate e) (push e res)))
21328 (nreverse res)))
21330 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21331 "Reduce two-argument FUNCTION across SEQ.
21332 Taken from `reduce' in cl-seq.el with all keyword arguments but
21333 \":initial-value\" removed."
21334 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21335 (cadr (memq :initial-value cl-keys)))
21336 (cl-seq (pop cl-seq))
21337 (t (funcall cl-func)))))
21338 (while cl-seq
21339 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21340 cl-accum))
21342 (defun org-back-over-empty-lines ()
21343 "Move backwards over whitespace, to the beginning of the first empty line.
21344 Returns the number of empty lines passed."
21345 (let ((pos (point)))
21346 (if (cdr (assoc 'heading org-blank-before-new-entry))
21347 (skip-chars-backward " \t\n\r")
21348 (unless (eobp)
21349 (forward-line -1)))
21350 (beginning-of-line 2)
21351 (goto-char (min (point) pos))
21352 (count-lines (point) pos)))
21354 (defun org-skip-whitespace ()
21355 (skip-chars-forward " \t\n\r"))
21357 (defun org-point-in-group (point group &optional context)
21358 "Check if POINT is in match-group GROUP.
21359 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21360 match. If the match group does not exist or point is not inside it,
21361 return nil."
21362 (and (match-beginning group)
21363 (>= point (match-beginning group))
21364 (<= point (match-end group))
21365 (if context
21366 (list context (match-beginning group) (match-end group))
21367 t)))
21369 (defun org-switch-to-buffer-other-window (&rest args)
21370 "Switch to buffer in a second window on the current frame.
21371 In particular, do not allow pop-up frames.
21372 Returns the newly created buffer."
21373 (org-no-popups
21374 (apply 'switch-to-buffer-other-window args)))
21376 (defun org-combine-plists (&rest plists)
21377 "Create a single property list from all plists in PLISTS.
21378 The process starts by copying the first list, and then setting properties
21379 from the other lists. Settings in the last list are the most significant
21380 ones and overrule settings in the other lists."
21381 (let ((rtn (copy-sequence (pop plists)))
21382 p v ls)
21383 (while plists
21384 (setq ls (pop plists))
21385 (while ls
21386 (setq p (pop ls) v (pop ls))
21387 (setq rtn (plist-put rtn p v))))
21388 rtn))
21390 (defun org-replace-escapes (string table)
21391 "Replace %-escapes in STRING with values in TABLE.
21392 TABLE is an association list with keys like \"%a\" and string values.
21393 The sequences in STRING may contain normal field width and padding information,
21394 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21395 so values can contain further %-escapes if they are define later in TABLE."
21396 (let ((tbl (copy-alist table))
21397 (case-fold-search nil)
21398 (pchg 0)
21399 e re rpl)
21400 (while (setq e (pop tbl))
21401 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21402 (when (and (cdr e) (string-match re (cdr e)))
21403 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21404 (safe "SREF"))
21405 (add-text-properties 0 3 (list 'sref sref) safe)
21406 (setcdr e (replace-match safe t t (cdr e)))))
21407 (while (string-match re string)
21408 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21409 (cdr e)))
21410 (setq string (replace-match rpl t t string))))
21411 (while (setq pchg (next-property-change pchg string))
21412 (let ((sref (get-text-property pchg 'sref string)))
21413 (when (and sref (string-match "SREF" string pchg))
21414 (setq string (replace-match sref t t string)))))
21415 string))
21417 (defun org-sublist (list start end)
21418 "Return a section of LIST, from START to END.
21419 Counting starts at 1."
21420 (let (rtn (c start))
21421 (setq list (nthcdr (1- start) list))
21422 (while (and list (<= c end))
21423 (push (pop list) rtn)
21424 (setq c (1+ c)))
21425 (nreverse rtn)))
21427 (defun org-find-base-buffer-visiting (file)
21428 "Like `find-buffer-visiting' but always return the base buffer and
21429 not an indirect buffer."
21430 (let ((buf (or (get-file-buffer file)
21431 (find-buffer-visiting file))))
21432 (if buf
21433 (or (buffer-base-buffer buf) buf)
21434 nil)))
21436 (defun org-image-file-name-regexp (&optional extensions)
21437 "Return regexp matching the file names of images.
21438 If EXTENSIONS is given, only match these."
21439 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21440 (image-file-name-regexp)
21441 (let ((image-file-name-extensions
21442 (or extensions
21443 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21444 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21445 (concat "\\."
21446 (regexp-opt (nconc (mapcar 'upcase
21447 image-file-name-extensions)
21448 image-file-name-extensions)
21450 "\\'"))))
21452 (defun org-file-image-p (file &optional extensions)
21453 "Return non-nil if FILE is an image."
21454 (save-match-data
21455 (string-match (org-image-file-name-regexp extensions) file)))
21457 (defun org-get-cursor-date (&optional with-time)
21458 "Return the date at cursor in as a time.
21459 This works in the calendar and in the agenda, anywhere else it just
21460 returns the current time.
21461 If WITH-TIME is non-nil, returns the time of the event at point (in
21462 the agenda) or the current time of the day."
21463 (let (date day defd tp tm hod mod)
21464 (when with-time
21465 (setq tp (get-text-property (point) 'time))
21466 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21467 (setq hod (string-to-number (match-string 1 tp))
21468 mod (string-to-number (match-string 2 tp))))
21469 (or tp (setq hod (nth 2 (decode-time (current-time)))
21470 mod (nth 1 (decode-time (current-time))))))
21471 (cond
21472 ((eq major-mode 'calendar-mode)
21473 (setq date (calendar-cursor-to-date)
21474 defd (encode-time 0 (or mod 0) (or hod 0)
21475 (nth 1 date) (nth 0 date) (nth 2 date))))
21476 ((eq major-mode 'org-agenda-mode)
21477 (setq day (get-text-property (point) 'day))
21478 (if day
21479 (setq date (calendar-gregorian-from-absolute day)
21480 defd (encode-time 0 (or mod 0) (or hod 0)
21481 (nth 1 date) (nth 0 date) (nth 2 date))))))
21482 (or defd (current-time))))
21484 (defun org-mark-subtree (&optional up)
21485 "Mark the current subtree.
21486 This puts point at the start of the current subtree, and mark at
21487 the end. If a numeric prefix UP is given, move up into the
21488 hierarchy of headlines by UP levels before marking the subtree."
21489 (interactive "P")
21490 (org-with-limited-levels
21491 (cond ((org-at-heading-p) (beginning-of-line))
21492 ((org-before-first-heading-p) (error "Not in a subtree"))
21493 (t (outline-previous-visible-heading 1))))
21494 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21495 (if (org-called-interactively-p 'any)
21496 (call-interactively 'org-mark-element)
21497 (org-mark-element)))
21500 ;;; Indentation
21502 (defun org-indent-line ()
21503 "Indent line depending on context."
21504 (interactive)
21505 (let* ((pos (point))
21506 (itemp (org-at-item-p))
21507 (case-fold-search t)
21508 (org-drawer-regexp (or org-drawer-regexp "\000"))
21509 (inline-task-p (and (featurep 'org-inlinetask)
21510 (org-inlinetask-in-task-p)))
21511 (inline-re (and inline-task-p
21512 (org-inlinetask-outline-regexp)))
21513 column)
21514 (if (and orgstruct-is-++ (eq pos (point)))
21515 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21516 (indent-according-to-mode))
21517 (beginning-of-line 1)
21518 (cond
21519 ;; Headings
21520 ((looking-at org-outline-regexp) (setq column 0))
21521 ;; Footnote definition
21522 ((looking-at org-footnote-definition-re) (setq column 0))
21523 ;; Literal examples
21524 ((looking-at "[ \t]*:\\( \\|$\\)")
21525 (setq column (org-get-indentation))) ; do nothing
21526 ;; Lists
21527 ((ignore-errors (goto-char (org-in-item-p)))
21528 (setq column (if itemp
21529 (org-get-indentation)
21530 (org-list-item-body-column (point))))
21531 (goto-char pos))
21532 ;; Drawers
21533 ((and (looking-at "[ \t]*:END:")
21534 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21535 (save-excursion
21536 (goto-char (1- (match-beginning 1)))
21537 (setq column (current-column))))
21538 ;; Special blocks
21539 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21540 (save-excursion
21541 (re-search-backward
21542 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21543 (setq column (org-get-indentation (match-string 0))))
21544 ((and (not (looking-at "[ \t]*#\\+begin_"))
21545 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21546 (save-excursion
21547 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21548 (setq column
21549 (cond ((equal (downcase (match-string 1)) "src")
21550 ;; src blocks: let `org-edit-src-exit' handle them
21551 (org-get-indentation))
21552 ((equal (downcase (match-string 1)) "example")
21553 (max (org-get-indentation)
21554 (org-get-indentation (match-string 0))))
21556 (org-get-indentation (match-string 0))))))
21557 ;; This line has nothing special, look at the previous relevant
21558 ;; line to compute indentation
21560 (beginning-of-line 0)
21561 (while (and (not (bobp))
21562 (not (looking-at org-table-line-regexp))
21563 (not (looking-at org-drawer-regexp))
21564 ;; When point started in an inline task, do not move
21565 ;; above task starting line.
21566 (not (and inline-task-p (looking-at inline-re)))
21567 ;; Skip drawers, blocks, empty lines, verbatim,
21568 ;; comments, tables, footnotes definitions, lists,
21569 ;; inline tasks.
21570 (or (and (looking-at "[ \t]*:END:")
21571 (re-search-backward org-drawer-regexp nil t))
21572 (and (looking-at "[ \t]*#\\+end_")
21573 (re-search-backward "[ \t]*#\\+begin_"nil t))
21574 (looking-at "[ \t]*[\n:#|]")
21575 (looking-at org-footnote-definition-re)
21576 (and (ignore-errors (goto-char (org-in-item-p)))
21577 (goto-char
21578 (org-list-get-top-point (org-list-struct))))
21579 (and (not inline-task-p)
21580 (featurep 'org-inlinetask)
21581 (org-inlinetask-in-task-p)
21582 (or (org-inlinetask-goto-beginning) t))))
21583 (beginning-of-line 0))
21584 (cond
21585 ;; There was an heading above.
21586 ((looking-at "\\*+[ \t]+")
21587 (if (not org-adapt-indentation)
21588 (setq column 0)
21589 (goto-char (match-end 0))
21590 (setq column (current-column))))
21591 ;; A drawer had started and is unfinished
21592 ((looking-at org-drawer-regexp)
21593 (goto-char (1- (match-beginning 1)))
21594 (setq column (current-column)))
21595 ;; Else, nothing noticeable found: get indentation and go on.
21596 (t (setq column (org-get-indentation))))))
21597 ;; Now apply indentation and move cursor accordingly
21598 (goto-char pos)
21599 (if (<= (current-column) (current-indentation))
21600 (org-indent-line-to column)
21601 (save-excursion (org-indent-line-to column)))
21602 ;; Special polishing for properties, see `org-property-format'
21603 (setq column (current-column))
21604 (beginning-of-line 1)
21605 (if (looking-at
21606 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21607 (replace-match (concat (match-string 1)
21608 (format org-property-format
21609 (match-string 2) (match-string 3)))
21610 t t))
21611 (org-move-to-column column))))
21613 (defun org-indent-drawer ()
21614 "Indent the drawer at point."
21615 (interactive)
21616 (let ((p (point))
21617 (e (and (save-excursion (re-search-forward ":END:" nil t))
21618 (match-end 0)))
21619 (folded
21620 (save-excursion
21621 (end-of-line)
21622 (when (overlays-at (point))
21623 (member 'invisible (overlay-properties
21624 (car (overlays-at (point)))))))))
21625 (when folded (org-cycle))
21626 (indent-for-tab-command)
21627 (while (and (move-beginning-of-line 2) (< (point) e))
21628 (indent-for-tab-command))
21629 (goto-char p)
21630 (when folded (org-cycle)))
21631 (message "Drawer at point indented"))
21633 (defun org-indent-block ()
21634 "Indent the block at point."
21635 (interactive)
21636 (let ((p (point))
21637 (case-fold-search t)
21638 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21639 (match-end 0)))
21640 (folded
21641 (save-excursion
21642 (end-of-line)
21643 (when (overlays-at (point))
21644 (member 'invisible (overlay-properties
21645 (car (overlays-at (point)))))))))
21646 (when folded (org-cycle))
21647 (indent-for-tab-command)
21648 (while (and (move-beginning-of-line 2) (< (point) e))
21649 (indent-for-tab-command))
21650 (goto-char p)
21651 (when folded (org-cycle)))
21652 (message "Block at point indented"))
21654 (defun org-indent-region (start end)
21655 "Indent region."
21656 (interactive "r")
21657 (save-excursion
21658 (let ((line-end (org-current-line end)))
21659 (goto-char start)
21660 (while (< (org-current-line) line-end)
21661 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21662 (t (call-interactively 'org-indent-line)))
21663 (move-beginning-of-line 2)))))
21666 ;;; Filling
21668 ;; We use our own fill-paragraph and auto-fill functions.
21670 ;; `org-fill-paragraph' relies on adaptive filling and context
21671 ;; checking. Appropriate `fill-prefix' is computed with
21672 ;; `org-adaptive-fill-function'.
21674 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21675 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21676 ;; `org-adaptive-fill-function' value. Internally,
21677 ;; `org-comment-line-break-function' breaks the line.
21679 ;; `org-setup-filling' installs filling and auto-filling related
21680 ;; variables during `org-mode' initialization.
21682 (defun org-setup-filling ()
21683 (interactive)
21684 ;; Prevent auto-fill from inserting unwanted new items.
21685 (when (boundp 'fill-nobreak-predicate)
21686 (org-set-local
21687 'fill-nobreak-predicate
21688 (org-uniquify
21689 (append fill-nobreak-predicate
21690 '(org-fill-paragraph-separate-nobreak-p
21691 org-fill-line-break-nobreak-p
21692 org-fill-paragraph-with-timestamp-nobreak-p)))))
21693 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21694 (org-set-local 'auto-fill-inhibit-regexp nil)
21695 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21696 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21697 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21699 (defvar org-element-paragraph-separate) ; org-element.el
21700 (defun org-fill-paragraph-separate-nobreak-p ()
21701 "Non-nil when a line break at point would insert a new item."
21702 (looking-at (substring org-element-paragraph-separate 1)))
21704 (defun org-fill-line-break-nobreak-p ()
21705 "Non-nil when a line break at point would create an Org line break."
21706 (save-excursion
21707 (skip-chars-backward "[ \t]")
21708 (skip-chars-backward "\\\\")
21709 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21711 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21712 "Non-nil when a line break at point would insert a new item."
21713 (and (org-at-timestamp-p t)
21714 (not (looking-at org-ts-regexp-both))))
21716 (declare-function message-in-body-p "message" ())
21717 (defvar orgtbl-line-start-regexp) ; From org-table.el
21718 (defun org-adaptive-fill-function ()
21719 "Compute a fill prefix for the current line.
21720 Return fill prefix, as a string, or nil if current line isn't
21721 meant to be filled."
21722 (let (prefix)
21723 (catch 'exit
21724 (when (derived-mode-p 'message-mode)
21725 (save-excursion
21726 (beginning-of-line)
21727 (cond ((or (not (message-in-body-p))
21728 (looking-at orgtbl-line-start-regexp))
21729 (throw 'exit nil))
21730 ((looking-at message-cite-prefix-regexp)
21731 (throw 'exit (match-string-no-properties 0)))
21732 ((looking-at org-outline-regexp)
21733 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21734 (org-with-wide-buffer
21735 (let* ((p (line-beginning-position))
21736 (element (save-excursion (beginning-of-line)
21737 (org-element-at-point)))
21738 (type (org-element-type element))
21739 (post-affiliated (org-element-property :post-affiliated element)))
21740 (unless (and post-affiliated (< p post-affiliated))
21741 (case type
21742 (comment (looking-at "[ \t]*# ?") (match-string 0))
21743 (footnote-definition "")
21744 ((item plain-list)
21745 (make-string (org-list-item-body-column
21746 (or post-affiliated
21747 (org-element-property :begin element)))
21748 ? ))
21749 (paragraph
21750 ;; Fill prefix is usually the same as the current line,
21751 ;; except if the paragraph is at the beginning of an item.
21752 (let ((parent (org-element-property :parent element)))
21753 (cond ((eq (org-element-type parent) 'item)
21754 (make-string (org-list-item-body-column
21755 (org-element-property :begin parent))
21756 ? ))
21757 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21758 (match-string 0))
21759 (t ""))))
21760 (comment-block
21761 ;; Only fill contents if P is within block boundaries.
21762 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21763 (forward-line)
21764 (point)))
21765 (cend (save-excursion
21766 (goto-char (org-element-property :end element))
21767 (skip-chars-backward " \r\t\n")
21768 (line-beginning-position))))
21769 (when (and (>= p cbeg) (< p cend))
21770 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21771 (match-string 0)
21772 "")))))))))))
21774 (declare-function message-goto-body "message" ())
21775 (defvar message-cite-prefix-regexp) ; From message.el
21776 (defun org-fill-paragraph (&optional justify)
21777 "Fill element at point, when applicable.
21779 This function only applies to comment blocks, comments, example
21780 blocks and paragraphs. Also, as a special case, re-align table
21781 when point is at one.
21783 If JUSTIFY is non-nil (interactively, with prefix argument),
21784 justify as well. If `sentence-end-double-space' is non-nil, then
21785 period followed by one space does not end a sentence, so don't
21786 break a line there. The variable `fill-column' controls the
21787 width for filling.
21789 For convenience, when point is at a plain list, an item or
21790 a footnote definition, try to fill the first paragraph within."
21791 (interactive)
21792 (if (and (derived-mode-p 'message-mode)
21793 (or (not (message-in-body-p))
21794 (save-excursion (move-beginning-of-line 1)
21795 (looking-at message-cite-prefix-regexp))))
21796 ;; First ensure filling is correct in message-mode.
21797 (let ((fill-paragraph-function
21798 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21799 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21800 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21801 (paragraph-separate
21802 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21803 (fill-paragraph nil))
21804 (with-syntax-table org-mode-transpose-word-syntax-table
21805 ;; Move to end of line in order to get the first paragraph
21806 ;; within a plain list or a footnote definition.
21807 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21808 ;; First check if point is in a blank line at the beginning of
21809 ;; the buffer. In that case, ignore filling.
21810 (case (org-element-type element)
21811 ;; Use major mode filling function is src blocks.
21812 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21813 ;; Align Org tables, leave table.el tables as-is.
21814 (table-row (org-table-align) t)
21815 (table
21816 (when (eq (org-element-property :type element) 'org)
21817 (org-table-align))
21819 (paragraph
21820 ;; Paragraphs may contain `line-break' type objects.
21821 (let ((beg (max (point-min)
21822 (org-element-property :contents-begin element)))
21823 (end (min (point-max)
21824 (org-element-property :contents-end element))))
21825 ;; Do nothing if point is at an affiliated keyword.
21826 (if (< (line-end-position) beg) t
21827 (when (derived-mode-p 'message-mode)
21828 ;; In `message-mode', do not fill following citation
21829 ;; in current paragraph nor text before message body.
21830 (let ((body-start (save-excursion (message-goto-body))))
21831 (when body-start (setq beg (max body-start beg))))
21832 (when (save-excursion
21833 (re-search-forward
21834 (concat "^" message-cite-prefix-regexp) end t))
21835 (setq end (match-beginning 0))))
21836 ;; Fill paragraph, taking line breaks into account.
21837 ;; For that, slice the paragraph using line breaks as
21838 ;; separators, and fill the parts in reverse order to
21839 ;; avoid messing with markers.
21840 (save-excursion
21841 (goto-char end)
21842 (mapc
21843 (lambda (pos)
21844 (fill-region-as-paragraph pos (point) justify)
21845 (goto-char pos))
21846 ;; Find the list of ending positions for line breaks
21847 ;; in the current paragraph. Add paragraph
21848 ;; beginning to include first slice.
21849 (nreverse
21850 (cons beg
21851 (org-element-map
21852 (org-element--parse-objects
21853 beg end nil (org-element-restriction 'paragraph))
21854 'line-break
21855 (lambda (lb) (org-element-property :end lb)))))))
21856 t)))
21857 ;; Contents of `comment-block' type elements should be
21858 ;; filled as plain text, but only if point is within block
21859 ;; markers.
21860 (comment-block
21861 (let* ((case-fold-search t)
21862 (beg (save-excursion
21863 (goto-char (org-element-property :begin element))
21864 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21865 (forward-line)
21866 (point)))
21867 (end (save-excursion
21868 (goto-char (org-element-property :end element))
21869 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21870 (line-beginning-position))))
21871 (when (and (>= (point) beg) (< (point) end))
21872 (fill-region-as-paragraph
21873 (save-excursion
21874 (end-of-line)
21875 (re-search-backward "^[ \t]*$" beg 'move)
21876 (line-beginning-position))
21877 (save-excursion
21878 (beginning-of-line)
21879 (re-search-forward "^[ \t]*$" end 'move)
21880 (line-beginning-position))
21881 justify)))
21883 ;; Fill comments.
21884 (comment (fill-comment-paragraph justify))
21885 ;; Ignore every other element.
21886 (otherwise t))))))
21888 (defun org-auto-fill-function ()
21889 "Auto-fill function."
21890 ;; Check if auto-filling is meaningful.
21891 (let ((fc (current-fill-column)))
21892 (when (and fc (> (current-column) fc))
21893 (let* ((fill-prefix (org-adaptive-fill-function))
21894 ;; Enforce empty fill prefix, if required. Otherwise, it
21895 ;; will be computed again.
21896 (adaptive-fill-mode (not (equal fill-prefix ""))))
21897 (when fill-prefix (do-auto-fill))))))
21899 (defun org-comment-line-break-function (&optional soft)
21900 "Break line at point and indent, continuing comment if within one.
21901 The inserted newline is marked hard if variable
21902 `use-hard-newlines' is true, unless optional argument SOFT is
21903 non-nil."
21904 (if soft (insert-and-inherit ?\n) (newline 1))
21905 (save-excursion (forward-char -1) (delete-horizontal-space))
21906 (delete-horizontal-space)
21907 (indent-to-left-margin)
21908 (insert-before-markers-and-inherit fill-prefix))
21911 ;;; Comments
21913 ;; Org comments syntax is quite complex. It requires the entire line
21914 ;; to be just a comment. Also, even with the right syntax at the
21915 ;; beginning of line, some some elements (i.e. verse-block or
21916 ;; example-block) don't accept comments. Usual Emacs comment commands
21917 ;; cannot cope with those requirements. Therefore, Org replaces them.
21919 ;; Org still relies on `comment-dwim', but cannot trust
21920 ;; `comment-only-p'. So, `comment-region-function' and
21921 ;; `uncomment-region-function' both point
21922 ;; to`org-comment-or-uncomment-region'. Eventually,
21923 ;; `org-insert-comment' takes care of insertion of comments at the
21924 ;; beginning of line.
21926 ;; `org-setup-comments-handling' install comments related variables
21927 ;; during `org-mode' initialization.
21929 (defun org-setup-comments-handling ()
21930 (interactive)
21931 (org-set-local 'comment-use-syntax nil)
21932 (org-set-local 'comment-start "# ")
21933 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21934 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21935 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21936 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21938 (defun org-insert-comment ()
21939 "Insert an empty comment above current line.
21940 If the line is empty, insert comment at its beginning."
21941 (beginning-of-line)
21942 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21943 (org-indent-line)
21944 (insert "# "))
21946 (defvar comment-empty-lines) ; From newcomment.el.
21947 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21948 "Comment or uncomment each non-blank line in the region.
21949 Uncomment each non-blank line between BEG and END if it only
21950 contains commented lines. Otherwise, comment them."
21951 (save-restriction
21952 ;; Restrict region
21953 (narrow-to-region (save-excursion (goto-char beg)
21954 (skip-chars-forward " \r\t\n" end)
21955 (line-beginning-position))
21956 (save-excursion (goto-char end)
21957 (skip-chars-backward " \r\t\n" beg)
21958 (line-end-position)))
21959 (let ((uncommentp
21960 ;; UNCOMMENTP is non-nil when every non blank line between
21961 ;; BEG and END is a comment.
21962 (save-excursion
21963 (goto-char (point-min))
21964 (while (and (not (eobp))
21965 (let ((element (org-element-at-point)))
21966 (and (eq (org-element-type element) 'comment)
21967 (goto-char (min (point-max)
21968 (org-element-property
21969 :end element)))))))
21970 (eobp))))
21971 (if uncommentp
21972 ;; Only blank lines and comments in region: uncomment it.
21973 (save-excursion
21974 (goto-char (point-min))
21975 (while (not (eobp))
21976 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21977 (replace-match "" nil nil nil 1))
21978 (forward-line)))
21979 ;; Comment each line in region.
21980 (let ((min-indent (point-max)))
21981 ;; First find the minimum indentation across all lines.
21982 (save-excursion
21983 (goto-char (point-min))
21984 (while (and (not (eobp)) (not (zerop min-indent)))
21985 (unless (looking-at "[ \t]*$")
21986 (setq min-indent (min min-indent (current-indentation))))
21987 (forward-line)))
21988 ;; Then loop over all lines.
21989 (save-excursion
21990 (goto-char (point-min))
21991 (while (not (eobp))
21992 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21993 (org-move-to-column min-indent t)
21994 (insert comment-start))
21995 (forward-line))))))))
21998 ;;; Planning
22000 ;; This section contains tools to operate on timestamp objects, as
22001 ;; returned by, e.g. `org-element-context'.
22003 (defun org-timestamp-has-time-p (timestamp)
22004 "Non-nil when TIMESTAMP has a time specified."
22005 (org-element-property :hour-start timestamp))
22007 (defun org-timestamp-format (timestamp format &optional end utc)
22008 "Format a TIMESTAMP element into a string.
22010 FORMAT is a format specifier to be passed to
22011 `format-time-string'.
22013 When optional argument END is non-nil, use end of date-range or
22014 time-range, if possible.
22016 When optional argument UTC is non-nil, time will be expressed as
22017 Universal Time."
22018 (format-time-string
22019 format
22020 (apply 'encode-time
22021 (cons 0
22022 (mapcar
22023 (lambda (prop) (or (org-element-property prop timestamp) 0))
22024 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22025 '(:minute-start :hour-start :day-start :month-start
22026 :year-start)))))
22027 utc))
22029 (defun org-timestamp-split-range (timestamp &optional end)
22030 "Extract a timestamp object from a date or time range.
22032 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22033 the end of the range. Otherwise, extract its start.
22035 Return a new timestamp object sharing the same parent as
22036 TIMESTAMP."
22037 (let ((type (org-element-property :type timestamp)))
22038 (if (memq type '(active inactive diary)) timestamp
22039 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22040 ;; Set new type.
22041 (org-element-put-property
22042 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22043 ;; Copy start properties over end properties if END is
22044 ;; non-nil. Otherwise, copy end properties over `start' ones.
22045 (let ((p-alist '((:minute-start . :minute-end)
22046 (:hour-start . :hour-end)
22047 (:day-start . :day-end)
22048 (:month-start . :month-end)
22049 (:year-start . :year-end))))
22050 (dolist (p-cell p-alist)
22051 (org-element-put-property
22052 split-ts
22053 (funcall (if end 'car 'cdr) p-cell)
22054 (org-element-property
22055 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22056 ;; Eventually refresh `:raw-value'.
22057 (org-element-put-property split-ts :raw-value nil)
22058 (org-element-put-property
22059 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22061 (defun org-timestamp-translate (timestamp &optional boundary)
22062 "Apply `org-translate-time' on a TIMESTAMP object.
22063 When optional argument BOUNDARY is non-nil, it is either the
22064 symbol `start' or `end'. In this case, only translate the
22065 starting or ending part of TIMESTAMP if it is a date or time
22066 range. Otherwise, translate both parts."
22067 (if (and (not boundary)
22068 (memq (org-element-property :type timestamp)
22069 '(active-range inactive-range)))
22070 (concat
22071 (org-translate-time
22072 (org-element-property :raw-value
22073 (org-timestamp-split-range timestamp)))
22074 "--"
22075 (org-translate-time
22076 (org-element-property :raw-value
22077 (org-timestamp-split-range timestamp t))))
22078 (org-translate-time
22079 (org-element-property
22080 :raw-value
22081 (if (not boundary) timestamp
22082 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22086 ;;; Other stuff.
22088 (defun org-toggle-fixed-width-section (arg)
22089 "Toggle the fixed-width export.
22090 If there is no active region, the QUOTE keyword at the current headline is
22091 inserted or removed. When present, it causes the text between this headline
22092 and the next to be exported as fixed-width text, and unmodified.
22093 If there is an active region, this command adds or removes a colon as the
22094 first character of this line. If the first character of a line is a colon,
22095 this line is also exported in fixed-width font."
22096 (interactive "P")
22097 (let* ((cc 0)
22098 (regionp (org-region-active-p))
22099 (beg (if regionp (region-beginning) (point)))
22100 (end (if regionp (region-end)))
22101 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22102 (case-fold-search nil)
22103 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22104 off)
22105 (if regionp
22106 (save-excursion
22107 (goto-char beg)
22108 (setq cc (current-column))
22109 (beginning-of-line 1)
22110 (setq off (looking-at re))
22111 (while (> nlines 0)
22112 (setq nlines (1- nlines))
22113 (beginning-of-line 1)
22114 (cond
22115 (arg
22116 (org-move-to-column cc t)
22117 (insert ": \n")
22118 (forward-line -1))
22119 ((and off (looking-at re))
22120 (replace-match "" t t nil 1))
22121 ((not off) (org-move-to-column cc t) (insert ": ")))
22122 (forward-line 1)))
22123 (save-excursion
22124 (org-back-to-heading)
22125 (cond
22126 ((looking-at (format org-heading-keyword-regexp-format
22127 org-quote-string))
22128 (goto-char (match-end 1))
22129 (looking-at (concat " +" org-quote-string))
22130 (replace-match "" t t)
22131 (when (eolp) (insert " ")))
22132 ((looking-at org-outline-regexp)
22133 (goto-char (match-end 0))
22134 (insert org-quote-string " ")))))))
22136 (defun org-reftex-citation ()
22137 "Use reftex-citation to insert a citation into the buffer.
22138 This looks for a line like
22140 #+BIBLIOGRAPHY: foo plain option:-d
22142 and derives from it that foo.bib is the bibliography file relevant
22143 for this document. It then installs the necessary environment for RefTeX
22144 to work in this buffer and calls `reftex-citation' to insert a citation
22145 into the buffer.
22147 Export of such citations to both LaTeX and HTML is handled by the contributed
22148 package org-exp-bibtex by Taru Karttunen."
22149 (interactive)
22150 (let ((reftex-docstruct-symbol 'rds)
22151 (reftex-cite-format "\\cite{%l}")
22152 rds bib)
22153 (save-excursion
22154 (save-restriction
22155 (widen)
22156 (let ((case-fold-search t)
22157 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22158 (if (not (save-excursion
22159 (or (re-search-forward re nil t)
22160 (re-search-backward re nil t))))
22161 (error "No bibliography defined in file")
22162 (setq bib (concat (match-string 1) ".bib")
22163 rds (list (list 'bib bib)))))))
22164 (call-interactively 'reftex-citation)))
22166 ;;;; Functions extending outline functionality
22168 (defun org-beginning-of-line (&optional arg)
22169 "Go to the beginning of the current line. If that is invisible, continue
22170 to a visible line beginning. This makes the function of C-a more intuitive.
22171 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22172 first attempt, and only move to after the tags when the cursor is already
22173 beyond the end of the headline."
22174 (interactive "P")
22175 (let ((pos (point))
22176 (special (if (consp org-special-ctrl-a/e)
22177 (car org-special-ctrl-a/e)
22178 org-special-ctrl-a/e))
22179 refpos)
22180 (if (org-bound-and-true-p visual-line-mode)
22181 (beginning-of-visual-line 1)
22182 (beginning-of-line 1))
22183 (if (and arg (fboundp 'move-beginning-of-line))
22184 (call-interactively 'move-beginning-of-line)
22185 (if (bobp)
22187 (backward-char 1)
22188 (if (org-truely-invisible-p)
22189 (while (and (not (bobp)) (org-truely-invisible-p))
22190 (backward-char 1)
22191 (beginning-of-line 1))
22192 (forward-char 1))))
22193 (when special
22194 (cond
22195 ((and (looking-at org-complex-heading-regexp)
22196 (= (char-after (match-end 1)) ?\ ))
22197 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22198 (point-at-eol)))
22199 (goto-char
22200 (if (eq special t)
22201 (cond ((> pos refpos) refpos)
22202 ((= pos (point)) refpos)
22203 (t (point)))
22204 (cond ((> pos (point)) (point))
22205 ((not (eq last-command this-command)) (point))
22206 (t refpos)))))
22207 ((org-at-item-p)
22208 ;; Being at an item and not looking at an the item means point
22209 ;; was previously moved to beginning of a visual line, which
22210 ;; doesn't contain the item. Therefore, do nothing special,
22211 ;; just stay here.
22212 (when (looking-at org-list-full-item-re)
22213 ;; Set special position at first white space character after
22214 ;; bullet, and check-box, if any.
22215 (let ((after-bullet
22216 (let ((box (match-end 3)))
22217 (if (not box) (match-end 1)
22218 (let ((after (char-after box)))
22219 (if (and after (= after ? )) (1+ box) box))))))
22220 ;; Special case: Move point to special position when
22221 ;; currently after it or at beginning of line.
22222 (if (eq special t)
22223 (when (or (> pos after-bullet) (= (point) pos))
22224 (goto-char after-bullet))
22225 ;; Reversed case: Move point to special position when
22226 ;; point was already at beginning of line and command is
22227 ;; repeated.
22228 (when (and (= (point) pos) (eq last-command this-command))
22229 (goto-char after-bullet))))))))
22230 (org-no-warnings
22231 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22233 (defun org-end-of-line (&optional arg)
22234 "Go to the end of the line.
22235 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22236 tags on the first attempt, and only move to after the tags when
22237 the cursor is already beyond the end of the headline."
22238 (interactive "P")
22239 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22240 org-special-ctrl-a/e))
22241 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22242 'end-of-visual-line)
22243 ((fboundp 'move-end-of-line) 'move-end-of-line)
22244 (t 'end-of-line))))
22245 (if (or (not special) arg) (call-interactively move-fun)
22246 (let* ((element (save-excursion (beginning-of-line)
22247 (org-element-at-point)))
22248 (type (org-element-type element)))
22249 (cond
22250 ((memq type '(headline inlinetask))
22251 (let ((pos (point)))
22252 (beginning-of-line 1)
22253 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22254 (if (eq special t)
22255 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22256 (goto-char (match-beginning 1))
22257 (goto-char (match-end 0)))
22258 (if (or (< pos (match-end 0))
22259 (not (eq this-command last-command)))
22260 (goto-char (match-end 0))
22261 (goto-char (match-beginning 1))))
22262 (call-interactively move-fun))))
22263 ((org-element-property :hiddenp element)
22264 ;; If element is hidden, `move-end-of-line' would put point
22265 ;; after it. Use `end-of-line' to stay on current line.
22266 (call-interactively 'end-of-line))
22267 (t (call-interactively move-fun)))))
22268 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22270 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22271 (define-key org-mode-map "\C-e" 'org-end-of-line)
22273 (defun org-backward-sentence (&optional arg)
22274 "Go to beginning of sentence, or beginning of table field.
22275 This will call `backward-sentence' or `org-table-beginning-of-field',
22276 depending on context."
22277 (interactive "P")
22278 (cond
22279 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22280 (t (call-interactively 'backward-sentence))))
22282 (defun org-forward-sentence (&optional arg)
22283 "Go to end of sentence, or end of table field.
22284 This will call `forward-sentence' or `org-table-end-of-field',
22285 depending on context."
22286 (interactive "P")
22287 (cond
22288 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22289 (t (call-interactively 'forward-sentence))))
22291 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22292 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22294 (defun org-kill-line (&optional arg)
22295 "Kill line, to tags or end of line."
22296 (interactive "P")
22297 (cond
22298 ((or (not org-special-ctrl-k)
22299 (bolp)
22300 (not (org-at-heading-p)))
22301 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22302 org-ctrl-k-protect-subtree)
22303 (if (or (eq org-ctrl-k-protect-subtree 'error)
22304 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22305 (error "C-k aborted - would kill hidden subtree")))
22306 (call-interactively
22307 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22308 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22309 (kill-region (point) (match-beginning 1))
22310 (org-set-tags nil t))
22311 (t (kill-region (point) (point-at-eol)))))
22313 (define-key org-mode-map "\C-k" 'org-kill-line)
22315 (defun org-yank (&optional arg)
22316 "Yank. If the kill is a subtree, treat it specially.
22317 This command will look at the current kill and check if is a single
22318 subtree, or a series of subtrees[1]. If it passes the test, and if the
22319 cursor is at the beginning of a line or after the stars of a currently
22320 empty headline, then the yank is handled specially. How exactly depends
22321 on the value of the following variables, both set by default.
22323 org-yank-folded-subtrees
22324 When set, the subtree(s) will be folded after insertion, but only
22325 if doing so would now swallow text after the yanked text.
22327 org-yank-adjusted-subtrees
22328 When set, the subtree will be promoted or demoted in order to
22329 fit into the local outline tree structure, which means that the level
22330 will be adjusted so that it becomes the smaller one of the two
22331 *visible* surrounding headings.
22333 Any prefix to this command will cause `yank' to be called directly with
22334 no special treatment. In particular, a simple \\[universal-argument] prefix \
22335 will just
22336 plainly yank the text as it is.
22338 \[1] The test checks if the first non-white line is a heading
22339 and if there are no other headings with fewer stars."
22340 (interactive "P")
22341 (org-yank-generic 'yank arg))
22343 (defun org-yank-generic (command arg)
22344 "Perform some yank-like command.
22346 This function implements the behavior described in the `org-yank'
22347 documentation. However, it has been generalized to work for any
22348 interactive command with similar behavior."
22350 ;; pretend to be command COMMAND
22351 (setq this-command command)
22353 (if arg
22354 (call-interactively command)
22356 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22357 (and (org-kill-is-subtree-p)
22358 (or (bolp)
22359 (and (looking-at "[ \t]*$")
22360 (string-match
22361 "\\`\\*+\\'"
22362 (buffer-substring (point-at-bol) (point)))))))
22363 swallowp)
22364 (cond
22365 ((and subtreep org-yank-folded-subtrees)
22366 (let ((beg (point))
22367 end)
22368 (if (and subtreep org-yank-adjusted-subtrees)
22369 (org-paste-subtree nil nil 'for-yank)
22370 (call-interactively command))
22372 (setq end (point))
22373 (goto-char beg)
22374 (when (and (bolp) subtreep
22375 (not (setq swallowp
22376 (org-yank-folding-would-swallow-text beg end))))
22377 (org-with-limited-levels
22378 (or (looking-at org-outline-regexp)
22379 (re-search-forward org-outline-regexp-bol end t))
22380 (while (and (< (point) end) (looking-at org-outline-regexp))
22381 (hide-subtree)
22382 (org-cycle-show-empty-lines 'folded)
22383 (condition-case nil
22384 (outline-forward-same-level 1)
22385 (error (goto-char end))))))
22386 (when swallowp
22387 (message
22388 "Inserted text not folded because that would swallow text"))
22390 (goto-char end)
22391 (skip-chars-forward " \t\n\r")
22392 (beginning-of-line 1)
22393 (push-mark beg 'nomsg)))
22394 ((and subtreep org-yank-adjusted-subtrees)
22395 (let ((beg (point-at-bol)))
22396 (org-paste-subtree nil nil 'for-yank)
22397 (push-mark beg 'nomsg)))
22399 (call-interactively command))))))
22401 (defun org-yank-folding-would-swallow-text (beg end)
22402 "Would hide-subtree at BEG swallow any text after END?"
22403 (let (level)
22404 (org-with-limited-levels
22405 (save-excursion
22406 (goto-char beg)
22407 (when (or (looking-at org-outline-regexp)
22408 (re-search-forward org-outline-regexp-bol end t))
22409 (setq level (org-outline-level)))
22410 (goto-char end)
22411 (skip-chars-forward " \t\r\n\v\f")
22412 (if (or (eobp)
22413 (and (bolp) (looking-at org-outline-regexp)
22414 (<= (org-outline-level) level)))
22415 nil ; Nothing would be swallowed
22416 t))))) ; something would swallow
22418 (define-key org-mode-map "\C-y" 'org-yank)
22420 (defun org-truely-invisible-p ()
22421 "Check if point is at a character currently not visible.
22422 This version does not only check the character property, but also
22423 `visible-mode'."
22424 ;; Early versions of noutline don't have `outline-invisible-p'.
22425 (if (org-bound-and-true-p visible-mode)
22427 (outline-invisible-p)))
22429 (defun org-invisible-p2 ()
22430 "Check if point is at a character currently not visible."
22431 (save-excursion
22432 (if (and (eolp) (not (bobp))) (backward-char 1))
22433 ;; Early versions of noutline don't have `outline-invisible-p'.
22434 (outline-invisible-p)))
22436 (defun org-back-to-heading (&optional invisible-ok)
22437 "Call `outline-back-to-heading', but provide a better error message."
22438 (condition-case nil
22439 (outline-back-to-heading invisible-ok)
22440 (error (error "Before first headline at position %d in buffer %s"
22441 (point) (current-buffer)))))
22443 (defun org-before-first-heading-p ()
22444 "Before first heading?"
22445 (save-excursion
22446 (end-of-line)
22447 (null (re-search-backward org-outline-regexp-bol nil t))))
22449 (defun org-at-heading-p (&optional ignored)
22450 (outline-on-heading-p t))
22451 ;; Compatibility alias with Org versions < 7.8.03
22452 (defalias 'org-on-heading-p 'org-at-heading-p)
22454 (defun org-at-comment-p nil
22455 "Is cursor in a line starting with a # character?"
22456 (save-excursion
22457 (beginning-of-line)
22458 (looking-at "^#")))
22460 (defun org-at-drawer-p nil
22461 "Is cursor at a drawer keyword?"
22462 (save-excursion
22463 (move-beginning-of-line 1)
22464 (looking-at org-drawer-regexp)))
22466 (defun org-at-block-p nil
22467 "Is cursor at a block keyword?"
22468 (save-excursion
22469 (move-beginning-of-line 1)
22470 (looking-at org-block-regexp)))
22472 (defun org-point-at-end-of-empty-headline ()
22473 "If point is at the end of an empty headline, return t, else nil.
22474 If the heading only contains a TODO keyword, it is still still considered
22475 empty."
22476 (and (looking-at "[ \t]*$")
22477 (when org-todo-line-regexp
22478 (save-excursion
22479 (beginning-of-line 1)
22480 (let ((case-fold-search nil))
22481 (looking-at org-todo-line-regexp)
22482 (string= (match-string 3) ""))))))
22484 (defun org-at-heading-or-item-p ()
22485 (or (org-at-heading-p) (org-at-item-p)))
22487 (defun org-at-target-p ()
22488 (or (org-in-regexp org-radio-target-regexp)
22489 (org-in-regexp org-target-regexp)))
22490 ;; Compatibility alias with Org versions < 7.8.03
22491 (defalias 'org-on-target-p 'org-at-target-p)
22493 (defun org-up-heading-all (arg)
22494 "Move to the heading line of which the present line is a subheading.
22495 This function considers both visible and invisible heading lines.
22496 With argument, move up ARG levels."
22497 (if (fboundp 'outline-up-heading-all)
22498 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22499 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22501 (defun org-up-heading-safe ()
22502 "Move to the heading line of which the present line is a subheading.
22503 This version will not throw an error. It will return the level of the
22504 headline found, or nil if no higher level is found.
22506 Also, this function will be a lot faster than `outline-up-heading',
22507 because it relies on stars being the outline starters. This can really
22508 make a significant difference in outlines with very many siblings."
22509 (let (start-level re)
22510 (org-back-to-heading t)
22511 (setq start-level (funcall outline-level))
22512 (if (equal start-level 1)
22514 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22515 (if (re-search-backward re nil t)
22516 (funcall outline-level)))))
22518 (defun org-first-sibling-p ()
22519 "Is this heading the first child of its parents?"
22520 (interactive)
22521 (let ((re org-outline-regexp-bol)
22522 level l)
22523 (unless (org-at-heading-p t)
22524 (error "Not at a heading"))
22525 (setq level (funcall outline-level))
22526 (save-excursion
22527 (if (not (re-search-backward re nil t))
22529 (setq l (funcall outline-level))
22530 (< l level)))))
22532 (defun org-goto-sibling (&optional previous)
22533 "Goto the next sibling, even if it is invisible.
22534 When PREVIOUS is set, go to the previous sibling instead. Returns t
22535 when a sibling was found. When none is found, return nil and don't
22536 move point."
22537 (let ((fun (if previous 're-search-backward 're-search-forward))
22538 (pos (point))
22539 (re org-outline-regexp-bol)
22540 level l)
22541 (when (condition-case nil (org-back-to-heading t) (error nil))
22542 (setq level (funcall outline-level))
22543 (catch 'exit
22544 (or previous (forward-char 1))
22545 (while (funcall fun re nil t)
22546 (setq l (funcall outline-level))
22547 (when (< l level) (goto-char pos) (throw 'exit nil))
22548 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22549 (goto-char pos)
22550 nil))))
22552 (defun org-show-siblings ()
22553 "Show all siblings of the current headline."
22554 (save-excursion
22555 (while (org-goto-sibling) (org-flag-heading nil)))
22556 (save-excursion
22557 (while (org-goto-sibling 'previous)
22558 (org-flag-heading nil))))
22560 (defun org-goto-first-child ()
22561 "Goto the first child, even if it is invisible.
22562 Return t when a child was found. Otherwise don't move point and
22563 return nil."
22564 (let (level (pos (point)) (re org-outline-regexp-bol))
22565 (when (condition-case nil (org-back-to-heading t) (error nil))
22566 (setq level (outline-level))
22567 (forward-char 1)
22568 (if (and (re-search-forward re nil t) (> (outline-level) level))
22569 (progn (goto-char (match-beginning 0)) t)
22570 (goto-char pos) nil))))
22572 (defun org-show-hidden-entry ()
22573 "Show an entry where even the heading is hidden."
22574 (save-excursion
22575 (org-show-entry)))
22577 (defun org-flag-heading (flag &optional entry)
22578 "Flag the current heading. FLAG non-nil means make invisible.
22579 When ENTRY is non-nil, show the entire entry."
22580 (save-excursion
22581 (org-back-to-heading t)
22582 ;; Check if we should show the entire entry
22583 (if entry
22584 (progn
22585 (org-show-entry)
22586 (save-excursion
22587 (and (outline-next-heading)
22588 (org-flag-heading nil))))
22589 (outline-flag-region (max (point-min) (1- (point)))
22590 (save-excursion (outline-end-of-heading) (point))
22591 flag))))
22593 (defun org-get-next-sibling ()
22594 "Move to next heading of the same level, and return point.
22595 If there is no such heading, return nil.
22596 This is like outline-next-sibling, but invisible headings are ok."
22597 (let ((level (funcall outline-level)))
22598 (outline-next-heading)
22599 (while (and (not (eobp)) (> (funcall outline-level) level))
22600 (outline-next-heading))
22601 (if (or (eobp) (< (funcall outline-level) level))
22603 (point))))
22605 (defun org-get-last-sibling ()
22606 "Move to previous heading of the same level, and return point.
22607 If there is no such heading, return nil."
22608 (let ((opoint (point))
22609 (level (funcall outline-level)))
22610 (outline-previous-heading)
22611 (when (and (/= (point) opoint) (outline-on-heading-p t))
22612 (while (and (> (funcall outline-level) level)
22613 (not (bobp)))
22614 (outline-previous-heading))
22615 (if (< (funcall outline-level) level)
22617 (point)))))
22619 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22620 "Goto to the end of a subtree."
22621 ;; This contains an exact copy of the original function, but it uses
22622 ;; `org-back-to-heading', to make it work also in invisible
22623 ;; trees. And is uses an invisible-ok argument.
22624 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22625 ;; Furthermore, when used inside Org, finding the end of a large subtree
22626 ;; with many children and grandchildren etc, this can be much faster
22627 ;; than the outline version.
22628 (org-back-to-heading invisible-ok)
22629 (let ((first t)
22630 (level (funcall outline-level)))
22631 (if (and (derived-mode-p 'org-mode) (< level 1000))
22632 ;; A true heading (not a plain list item), in Org-mode
22633 ;; This means we can easily find the end by looking
22634 ;; only for the right number of stars. Using a regexp to do
22635 ;; this is so much faster than using a Lisp loop.
22636 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22637 (forward-char 1)
22638 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22639 ;; something else, do it the slow way
22640 (while (and (not (eobp))
22641 (or first (> (funcall outline-level) level)))
22642 (setq first nil)
22643 (outline-next-heading)))
22644 (unless to-heading
22645 (if (memq (preceding-char) '(?\n ?\^M))
22646 (progn
22647 ;; Go to end of line before heading
22648 (forward-char -1)
22649 (if (memq (preceding-char) '(?\n ?\^M))
22650 ;; leave blank line before heading
22651 (forward-char -1))))))
22652 (point))
22654 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22655 "Use Org version in org-mode, for dramatic speed-up."
22656 (if (derived-mode-p 'org-mode)
22657 (progn
22658 (org-end-of-subtree nil t)
22659 (unless (eobp) (backward-char 1)))
22660 ad-do-it))
22662 (defun org-end-of-meta-data-and-drawers ()
22663 "Jump to the first text after meta data and drawers in the current entry.
22664 This will move over empty lines, lines with planning time stamps,
22665 clocking lines, and drawers."
22666 (org-back-to-heading t)
22667 (let ((end (save-excursion (outline-next-heading) (point)))
22668 (re (concat "\\(" org-drawer-regexp "\\)"
22669 "\\|" "[ \t]*" org-keyword-time-regexp)))
22670 (forward-line 1)
22671 (while (re-search-forward re end t)
22672 (if (not (match-end 1))
22673 ;; empty or planning line
22674 (forward-line 1)
22675 ;; a drawer, find the end
22676 (re-search-forward "^[ \t]*:END:" end 'move)
22677 (forward-line 1)))
22678 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22679 (point)))
22681 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22682 "Move forward to the ARG'th subheading at same level as this one.
22683 Stop at the first and last subheadings of a superior heading.
22684 Normally this only looks at visible headings, but when INVISIBLE-OK is
22685 non-nil it will also look at invisible ones."
22686 (interactive "p")
22687 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22688 (if (and arg (< arg 0))
22689 (goto-char (point-min))
22690 (outline-next-heading))
22691 (org-at-heading-p)
22692 (let ((level (- (match-end 0) (match-beginning 0) 1))
22693 (f (if (and arg (< arg 0))
22694 're-search-backward
22695 're-search-forward))
22696 (count (if arg (abs arg) 1))
22697 (result (point)))
22698 (forward-char (if (and arg (< arg 0)) -1 1))
22699 (while (and (> count 0)
22700 (funcall f org-outline-regexp-bol nil 'move))
22701 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22702 (cond ((< l level) (setq count 0))
22703 ((and (= l level)
22704 (or invisible-ok
22705 (progn
22706 (goto-char (line-beginning-position))
22707 (not (outline-invisible-p)))))
22708 (setq count (1- count))
22709 (when (eq l level)
22710 (setq result (point)))))))
22711 (goto-char result))
22712 (beginning-of-line 1)))
22714 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22715 "Move backward to the ARG'th subheading at same level as this one.
22716 Stop at the first and last subheadings of a superior heading."
22717 (interactive "p")
22718 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22720 (defun org-next-block (arg &optional backward block-regexp)
22721 "Jump to the next block.
22722 With a prefix argument ARG, jump forward ARG many source blocks.
22723 When BACKWARD is non-nil, jump to the previous block.
22724 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22725 (interactive "p")
22726 (let ((re (or block-regexp org-block-regexp))
22727 (re-search-fn (or (and backward 're-search-backward)
22728 're-search-forward)))
22729 (if (looking-at re) (forward-char 1))
22730 (condition-case nil
22731 (funcall re-search-fn re nil nil arg)
22732 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22733 (goto-char (match-beginning 0)) (org-show-context)))
22735 (defun org-previous-block (arg &optional block-regexp)
22736 "Jump to the previous block.
22737 With a prefix argument ARG, jump backward ARG many source blocks.
22738 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22739 (interactive "p")
22740 (org-next-block arg t block-regexp))
22742 (defun org-forward-element ()
22743 "Move forward by one element.
22744 Move to the next element at the same level, when possible."
22745 (interactive)
22746 (cond ((eobp) (user-error "Cannot move further down"))
22747 ((org-with-limited-levels (org-at-heading-p))
22748 (let ((origin (point)))
22749 (goto-char (org-end-of-subtree nil t))
22750 (unless (org-with-limited-levels (org-at-heading-p))
22751 (goto-char origin)
22752 (user-error "Cannot move further down"))))
22754 (let* ((elem (org-element-at-point))
22755 (end (org-element-property :end elem))
22756 (parent (org-element-property :parent elem)))
22757 (if (and parent (= (org-element-property :contents-end parent) end))
22758 (goto-char (org-element-property :end parent))
22759 (goto-char end))))))
22761 (defun org-backward-element ()
22762 "Move backward by one element.
22763 Move to the previous element at the same level, when possible."
22764 (interactive)
22765 (cond ((bobp) (user-error "Cannot move further up"))
22766 ((org-with-limited-levels (org-at-heading-p))
22767 ;; At a headline, move to the previous one, if any, or stay
22768 ;; here.
22769 (let ((origin (point)))
22770 (org-with-limited-levels (org-backward-heading-same-level 1))
22771 ;; When current headline has no sibling above, move to its
22772 ;; parent.
22773 (when (= (point) origin)
22774 (or (org-with-limited-levels (org-up-heading-safe))
22775 (progn (goto-char origin)
22776 (user-error "Cannot move further up"))))))
22778 (let* ((trail (org-element-at-point 'keep-trail))
22779 (elem (car trail))
22780 (prev-elem (nth 1 trail))
22781 (beg (org-element-property :begin elem)))
22782 (cond
22783 ;; Move to beginning of current element if point isn't
22784 ;; there already.
22785 ((/= (point) beg) (goto-char beg))
22786 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22787 ((org-before-first-heading-p) (goto-char (point-min)))
22788 (t (org-back-to-heading)))))))
22790 (defun org-up-element ()
22791 "Move to upper element."
22792 (interactive)
22793 (if (org-with-limited-levels (org-at-heading-p))
22794 (unless (org-up-heading-safe) (error "No surrounding element"))
22795 (let* ((elem (org-element-at-point))
22796 (parent (org-element-property :parent elem)))
22797 (if parent (goto-char (org-element-property :begin parent))
22798 (if (org-with-limited-levels (org-before-first-heading-p))
22799 (error "No surrounding element")
22800 (org-with-limited-levels (org-back-to-heading)))))))
22802 (defvar org-element-greater-elements)
22803 (defun org-down-element ()
22804 "Move to inner element."
22805 (interactive)
22806 (let ((element (org-element-at-point)))
22807 (cond
22808 ((memq (org-element-type element) '(plain-list table))
22809 (goto-char (org-element-property :contents-begin element))
22810 (forward-char))
22811 ((memq (org-element-type element) org-element-greater-elements)
22812 ;; If contents are hidden, first disclose them.
22813 (when (org-element-property :hiddenp element) (org-cycle))
22814 (goto-char (or (org-element-property :contents-begin element)
22815 (error "No content for this element"))))
22816 (t (error "No inner element")))))
22818 (defun org-drag-element-backward ()
22819 "Move backward element at point."
22820 (interactive)
22821 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22822 (let* ((trail (org-element-at-point 'keep-trail))
22823 (elem (car trail))
22824 (prev-elem (nth 1 trail)))
22825 ;; Error out if no previous element or previous element is
22826 ;; a parent of the current one.
22827 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22828 (error "Cannot drag element backward")
22829 (let ((pos (point)))
22830 (org-element-swap-A-B prev-elem elem)
22831 (goto-char (+ (org-element-property :begin prev-elem)
22832 (- pos (org-element-property :begin elem)))))))))
22834 (defun org-drag-element-forward ()
22835 "Move forward element at point."
22836 (interactive)
22837 (let* ((pos (point))
22838 (elem (org-element-at-point)))
22839 (when (= (point-max) (org-element-property :end elem))
22840 (error "Cannot drag element forward"))
22841 (goto-char (org-element-property :end elem))
22842 (let ((next-elem (org-element-at-point)))
22843 (when (or (org-element-nested-p elem next-elem)
22844 (and (eq (org-element-type next-elem) 'headline)
22845 (not (eq (org-element-type elem) 'headline))))
22846 (goto-char pos)
22847 (error "Cannot drag element forward"))
22848 ;; Compute new position of point: it's shifted by NEXT-ELEM
22849 ;; body's length (without final blanks) and by the length of
22850 ;; blanks between ELEM and NEXT-ELEM.
22851 (let ((size-next (- (save-excursion
22852 (goto-char (org-element-property :end next-elem))
22853 (skip-chars-backward " \r\t\n")
22854 (forward-line)
22855 ;; Small correction if buffer doesn't end
22856 ;; with a newline character.
22857 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22858 (org-element-property :begin next-elem)))
22859 (size-blank (- (org-element-property :end elem)
22860 (save-excursion
22861 (goto-char (org-element-property :end elem))
22862 (skip-chars-backward " \r\t\n")
22863 (forward-line)
22864 (point)))))
22865 (org-element-swap-A-B elem next-elem)
22866 (goto-char (+ pos size-next size-blank))))))
22868 (defun org-drag-line-forward (arg)
22869 "Drag the line at point ARG lines forward."
22870 (interactive "p")
22871 (dotimes (n (abs arg))
22872 (let ((c (current-column)))
22873 (if (< 0 arg)
22874 (progn
22875 (beginning-of-line 2)
22876 (transpose-lines 1)
22877 (beginning-of-line 0))
22878 (transpose-lines 1)
22879 (beginning-of-line -1))
22880 (org-move-to-column c))))
22882 (defun org-drag-line-backward (arg)
22883 "Drag the line at point ARG lines backward."
22884 (interactive "p")
22885 (org-drag-line-forward (- arg)))
22887 (defun org-mark-element ()
22888 "Put point at beginning of this element, mark at end.
22890 Interactively, if this command is repeated or (in Transient Mark
22891 mode) if the mark is active, it marks the next element after the
22892 ones already marked."
22893 (interactive)
22894 (let (deactivate-mark)
22895 (if (and (org-called-interactively-p 'any)
22896 (or (and (eq last-command this-command) (mark t))
22897 (and transient-mark-mode mark-active)))
22898 (set-mark
22899 (save-excursion
22900 (goto-char (mark))
22901 (goto-char (org-element-property :end (org-element-at-point)))))
22902 (let ((element (org-element-at-point)))
22903 (end-of-line)
22904 (push-mark (org-element-property :end element) t t)
22905 (goto-char (org-element-property :begin element))))))
22907 (defun org-narrow-to-element ()
22908 "Narrow buffer to current element."
22909 (interactive)
22910 (let ((elem (org-element-at-point)))
22911 (cond
22912 ((eq (car elem) 'headline)
22913 (narrow-to-region
22914 (org-element-property :begin elem)
22915 (org-element-property :end elem)))
22916 ((memq (car elem) org-element-greater-elements)
22917 (narrow-to-region
22918 (org-element-property :contents-begin elem)
22919 (org-element-property :contents-end elem)))
22921 (narrow-to-region
22922 (org-element-property :begin elem)
22923 (org-element-property :end elem))))))
22925 (defun org-transpose-element ()
22926 "Transpose current and previous elements, keeping blank lines between.
22927 Point is moved after both elements."
22928 (interactive)
22929 (org-skip-whitespace)
22930 (let ((end (org-element-property :end (org-element-at-point))))
22931 (org-drag-element-backward)
22932 (goto-char end)))
22934 (defun org-unindent-buffer ()
22935 "Un-indent the visible part of the buffer.
22936 Relative indentation (between items, inside blocks, etc.) isn't
22937 modified."
22938 (interactive)
22939 (unless (eq major-mode 'org-mode)
22940 (error "Cannot un-indent a buffer not in Org mode"))
22941 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22942 unindent-tree ; For byte-compiler.
22943 (unindent-tree
22944 (function
22945 (lambda (contents)
22946 (mapc
22947 (lambda (element)
22948 (if (memq (org-element-type element) '(headline section))
22949 (funcall unindent-tree (org-element-contents element))
22950 (save-excursion
22951 (save-restriction
22952 (narrow-to-region
22953 (org-element-property :begin element)
22954 (org-element-property :end element))
22955 (org-do-remove-indentation)))))
22956 (reverse contents))))))
22957 (funcall unindent-tree (org-element-contents parse-tree))))
22959 (defun org-show-subtree ()
22960 "Show everything after this heading at deeper levels."
22961 (interactive)
22962 (outline-flag-region
22963 (point)
22964 (save-excursion
22965 (org-end-of-subtree t t))
22966 nil))
22968 (defun org-show-entry ()
22969 "Show the body directly following this heading.
22970 Show the heading too, if it is currently invisible."
22971 (interactive)
22972 (save-excursion
22973 (condition-case nil
22974 (progn
22975 (org-back-to-heading t)
22976 (outline-flag-region
22977 (max (point-min) (1- (point)))
22978 (save-excursion
22979 (if (re-search-forward
22980 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22981 (match-beginning 1)
22982 (point-max)))
22983 nil)
22984 (org-cycle-hide-drawers 'children))
22985 (error nil))))
22987 (defun org-make-options-regexp (kwds &optional extra)
22988 "Make a regular expression for keyword lines."
22989 (concat
22990 "^#\\+\\("
22991 (mapconcat 'regexp-quote kwds "\\|")
22992 (if extra (concat "\\|" extra))
22993 "\\):[ \t]*\\(.*\\)"))
22995 ;; Make isearch reveal the necessary context
22996 (defun org-isearch-end ()
22997 "Reveal context after isearch exits."
22998 (when isearch-success ; only if search was successful
22999 (if (featurep 'xemacs)
23000 ;; Under XEmacs, the hook is run in the correct place,
23001 ;; we directly show the context.
23002 (org-show-context 'isearch)
23003 ;; In Emacs the hook runs *before* restoring the overlays.
23004 ;; So we have to use a one-time post-command-hook to do this.
23005 ;; (Emacs 22 has a special variable, see function `org-mode')
23006 (unless (and (boundp 'isearch-mode-end-hook-quit)
23007 isearch-mode-end-hook-quit)
23008 ;; Only when the isearch was not quitted.
23009 (org-add-hook 'post-command-hook 'org-isearch-post-command
23010 'append 'local)))
23011 (org-fix-ellipsis-at-bol)))
23013 (defun org-isearch-post-command ()
23014 "Remove self from hook, and show context."
23015 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23016 (org-show-context 'isearch))
23019 ;;;; Integration with and fixes for other packages
23021 ;;; Imenu support
23023 (defvar org-imenu-markers nil
23024 "All markers currently used by Imenu.")
23025 (make-variable-buffer-local 'org-imenu-markers)
23027 (defun org-imenu-new-marker (&optional pos)
23028 "Return a new marker for use by Imenu, and remember the marker."
23029 (let ((m (make-marker)))
23030 (move-marker m (or pos (point)))
23031 (push m org-imenu-markers)
23034 (defun org-imenu-get-tree ()
23035 "Produce the index for Imenu."
23036 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23037 (setq org-imenu-markers nil)
23038 (let* ((n org-imenu-depth)
23039 (re (concat "^" (org-get-limited-outline-regexp)))
23040 (subs (make-vector (1+ n) nil))
23041 (last-level 0)
23042 m level head0 head)
23043 (save-excursion
23044 (save-restriction
23045 (widen)
23046 (goto-char (point-max))
23047 (while (re-search-backward re nil t)
23048 (setq level (org-reduced-level (funcall outline-level)))
23049 (when (and (<= level n)
23050 (looking-at org-complex-heading-regexp)
23051 (setq head0 (org-match-string-no-properties 4)))
23052 (setq head (org-link-display-format head0)
23053 m (org-imenu-new-marker))
23054 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23055 (if (>= level last-level)
23056 (push (cons head m) (aref subs level))
23057 (push (cons head (aref subs (1+ level))) (aref subs level))
23058 (loop for i from (1+ level) to n do (aset subs i nil)))
23059 (setq last-level level)))))
23060 (aref subs 1)))
23062 (eval-after-load "imenu"
23063 '(progn
23064 (add-hook 'imenu-after-jump-hook
23065 (lambda ()
23066 (if (derived-mode-p 'org-mode)
23067 (org-show-context 'org-goto))))))
23069 (defun org-link-display-format (link)
23070 "Replace a link with either the description, or the link target
23071 if no description is present"
23072 (save-match-data
23073 (if (string-match org-bracket-link-analytic-regexp link)
23074 (replace-match (if (match-end 5)
23075 (match-string 5 link)
23076 (concat (match-string 1 link)
23077 (match-string 3 link)))
23078 nil t link)
23079 link)))
23081 (defun org-toggle-link-display ()
23082 "Toggle the literal or descriptive display of links."
23083 (interactive)
23084 (if org-descriptive-links
23085 (progn (org-remove-from-invisibility-spec '(org-link))
23086 (org-restart-font-lock)
23087 (setq org-descriptive-links nil))
23088 (progn (add-to-invisibility-spec '(org-link))
23089 (org-restart-font-lock)
23090 (setq org-descriptive-links t))))
23092 ;; Speedbar support
23094 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23095 "Overlay marking the agenda restriction line in speedbar.")
23096 (overlay-put org-speedbar-restriction-lock-overlay
23097 'face 'org-agenda-restriction-lock)
23098 (overlay-put org-speedbar-restriction-lock-overlay
23099 'help-echo "Agendas are currently limited to this item.")
23100 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23102 (defun org-speedbar-set-agenda-restriction ()
23103 "Restrict future agenda commands to the location at point in speedbar.
23104 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23105 (interactive)
23106 (require 'org-agenda)
23107 (let (p m tp np dir txt)
23108 (cond
23109 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23110 'org-imenu t))
23111 (setq m (get-text-property p 'org-imenu-marker))
23112 (with-current-buffer (marker-buffer m)
23113 (goto-char m)
23114 (org-agenda-set-restriction-lock 'subtree)))
23115 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23116 'speedbar-function 'speedbar-find-file))
23117 (setq tp (previous-single-property-change
23118 (1+ p) 'speedbar-function)
23119 np (next-single-property-change
23120 tp 'speedbar-function)
23121 dir (speedbar-line-directory)
23122 txt (buffer-substring-no-properties (or tp (point-min))
23123 (or np (point-max))))
23124 (with-current-buffer (find-file-noselect
23125 (let ((default-directory dir))
23126 (expand-file-name txt)))
23127 (unless (derived-mode-p 'org-mode)
23128 (error "Cannot restrict to non-Org-mode file"))
23129 (org-agenda-set-restriction-lock 'file)))
23130 (t (error "Don't know how to restrict Org-mode's agenda")))
23131 (move-overlay org-speedbar-restriction-lock-overlay
23132 (point-at-bol) (point-at-eol))
23133 (setq current-prefix-arg nil)
23134 (org-agenda-maybe-redo)))
23136 (eval-after-load "speedbar"
23137 '(progn
23138 (speedbar-add-supported-extension ".org")
23139 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23140 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23141 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23142 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23143 (add-hook 'speedbar-visiting-tag-hook
23144 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23146 ;;; Fixes and Hacks for problems with other packages
23148 ;; Make flyspell not check words in links, to not mess up our keymap
23149 (defvar org-element-affiliated-keywords) ; From org-element.el
23150 (defvar org-element-block-name-alist) ; From org-element.el
23151 (defun org-mode-flyspell-verify ()
23152 "Don't let flyspell put overlays at active buttons, or on
23153 {todo,all-time,additional-option-like}-keywords."
23154 (let ((pos (max (1- (point)) (point-min)))
23155 (word (thing-at-point 'word)))
23156 (and (not (get-text-property pos 'keymap))
23157 (not (get-text-property pos 'org-no-flyspell))
23158 (not (member word org-todo-keywords-1))
23159 (not (member word org-all-time-keywords))
23160 (not (member word org-options-keywords))
23161 (not (member word (mapcar 'car org-startup-options)))
23162 (not (member-ignore-case word org-element-affiliated-keywords))
23163 (not (member-ignore-case word (org-get-export-keywords)))
23164 (not (member-ignore-case
23165 word (mapcar 'car org-element-block-name-alist)))
23166 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23168 (defun org-remove-flyspell-overlays-in (beg end)
23169 "Remove flyspell overlays in region."
23170 (and (org-bound-and-true-p flyspell-mode)
23171 (fboundp 'flyspell-delete-region-overlays)
23172 (flyspell-delete-region-overlays beg end))
23173 (add-text-properties beg end '(org-no-flyspell t)))
23175 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23176 (eval-after-load "bookmark"
23177 '(if (boundp 'bookmark-after-jump-hook)
23178 ;; We can use the hook
23179 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23180 ;; Hook not available, use advice
23181 (defadvice bookmark-jump (after org-make-visible activate)
23182 "Make the position visible."
23183 (org-bookmark-jump-unhide))))
23185 ;; Make sure saveplace shows the location if it was hidden
23186 (eval-after-load "saveplace"
23187 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23188 "Make the position visible."
23189 (org-bookmark-jump-unhide)))
23191 ;; Make sure ecb shows the location if it was hidden
23192 (eval-after-load "ecb"
23193 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23194 "Make hierarchy visible when jumping into location from ECB tree buffer."
23195 (if (derived-mode-p 'org-mode)
23196 (org-show-context))))
23198 (defun org-bookmark-jump-unhide ()
23199 "Unhide the current position, to show the bookmark location."
23200 (and (derived-mode-p 'org-mode)
23201 (or (outline-invisible-p)
23202 (save-excursion (goto-char (max (point-min) (1- (point))))
23203 (outline-invisible-p)))
23204 (org-show-context 'bookmark-jump)))
23206 ;; Make session.el ignore our circular variable
23207 (eval-after-load "session"
23208 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23210 ;;;; Experimental code
23212 (defun org-closed-in-range ()
23213 "Sparse tree of items closed in a certain time range.
23214 Still experimental, may disappear in the future."
23215 (interactive)
23216 ;; Get the time interval from the user.
23217 (let* ((time1 (org-float-time
23218 (org-read-date nil 'to-time nil "Starting date: ")))
23219 (time2 (org-float-time
23220 (org-read-date nil 'to-time nil "End date:")))
23221 ;; callback function
23222 (callback (lambda ()
23223 (let ((time
23224 (org-float-time
23225 (apply 'encode-time
23226 (org-parse-time-string
23227 (match-string 1))))))
23228 ;; check if time in interval
23229 (and (>= time time1) (<= time time2))))))
23230 ;; make tree, check each match with the callback
23231 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23233 ;;;; Finish up
23235 (provide 'org)
23237 (run-hooks 'org-load-hook)
23239 ;;; org.el ends here