org.el: Disable {pro,de}motion commands in orgstruct-mode if orgstruct-heading-prefix...
[org-mode/org-tableheadings.git] / lisp / org.el
blobb2be82bbe7c8a7594da4695445b880937c8caf9a
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro `org-with-limited-levels'.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches a headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function orgtbl-mode "org-table" (&optional arg))
126 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
127 (declare-function org-beamer-mode "ox-beamer" ())
128 (declare-function org-table-edit-field "org-table" (arg))
129 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :version "24.4"
351 :package-version '(Org . "8.0")
352 :type
353 '(set :greedy t
354 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
355 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
356 (const :tag " crypt: Encryption of subtrees" org-crypt)
357 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
358 (const :tag " docview: Links to doc-view buffers" org-docview)
359 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
360 (const :tag " id: Global IDs for identifying entries" org-id)
361 (const :tag " info: Links to Info nodes" org-info)
362 (const :tag " habit: Track your consistency with habits" org-habit)
363 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
364 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
365 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
366 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
367 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
368 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
369 (const :tag " mouse: Additional mouse support" org-mouse)
371 (const :tag "C vm: Links to VM folders/messages" org-vm)
372 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
373 (const :tag "C w3m: Special cut/paste from w3m to Org-mode." org-w3m)
374 (const :tag "C mew: Links to Mew folders/messages" org-mew)
375 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
376 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
377 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
378 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
379 (const :tag "C collector: Collect properties into tables" org-collector)
380 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
381 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
382 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
383 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
384 (const :tag "C eval: Include command output as text" org-eval)
385 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
386 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
387 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
388 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
389 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
391 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
393 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
394 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
395 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
396 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
397 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
398 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
399 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
400 (const :tag "C mtags: Support for muse-like tags" org-mtags)
401 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
402 (const :tag "C registry: A registry for Org-mode links" org-registry)
403 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
404 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
405 (const :tag "C secretary: Team management with org-mode" org-secretary)
406 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
407 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
408 (const :tag "C track: Keep up with Org-mode development" org-track)
409 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
410 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
411 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
413 (defvar org-export-registered-backends) ; From ox.el
414 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
415 (defcustom org-export-backends '(ascii html icalendar latex)
416 "List of export back-ends that should be always available.
418 If a description starts with <C>, the file is not part of Emacs
419 and loading it will require that you have downloaded and properly
420 installed the Org mode distribution.
422 Unlike to `org-modules', libraries in this list will not be
423 loaded along with Org, but only once the export framework is
424 needed.
426 This variable needs to be set before org.el is loaded. If you
427 need to make a change while Emacs is running, use the customize
428 interface or run the following code, where VALUE stands for the
429 new value of the variable, after updating it:
431 \(progn
432 \(setq org-export-registered-backends
433 \(org-remove-if-not
434 \(lambda (backend)
435 \(or (memq backend val)
436 \(catch 'parentp
437 \(mapc
438 \(lambda (b)
439 \(and (org-export-derived-backend-p b (car backend))
440 \(throw 'parentp t)))
441 val)
442 nil)))
443 org-export-registered-backends))
444 \(let ((new-list (mapcar 'car org-export-registered-backends)))
445 \(dolist (backend val)
446 \(cond
447 \((not (load (format \"ox-%s\" backend) t t))
448 \(message \"Problems while trying to load export back-end `%s'\"
449 backend))
450 \((not (memq backend new-list)) (push backend new-list))))
451 \(set-default var new-list)))
453 Adding a back-end to this list will also pull the back-end it
454 depends on, if any."
455 :group 'org
456 :group 'org-export
457 :version "24.4"
458 :package-version '(Org . "8.0")
459 :initialize 'custom-initialize-set
460 :set (lambda (var val)
461 (if (not (featurep 'ox)) (set-default var val)
462 ;; Any back-end not required anymore (not present in VAL and not
463 ;; a parent of any back-end in the new value) is removed from the
464 ;; list of registered back-ends.
465 (setq org-export-registered-backends
466 (org-remove-if-not
467 (lambda (backend)
468 (or (memq backend val)
469 (catch 'parentp
470 (mapc
471 (lambda (b)
472 (and (org-export-derived-backend-p b (car backend))
473 (throw 'parentp t)))
474 val)
475 nil)))
476 org-export-registered-backends))
477 ;; Now build NEW-LIST of both new back-ends and required
478 ;; parents.
479 (let ((new-list (mapcar 'car org-export-registered-backends)))
480 (dolist (backend val)
481 (cond
482 ((not (load (format "ox-%s" backend) t t))
483 (message "Problems while trying to load export back-end `%s'"
484 backend))
485 ((not (memq backend new-list)) (push backend new-list))))
486 ;; Set VAR to that list with fixed dependencies.
487 (set-default var new-list))))
488 :type '(set :greedy t
489 (const :tag " ascii Export buffer to ASCII format" ascii)
490 (const :tag " beamer Export buffer to Beamer presentation" beamer)
491 (const :tag " html Export buffer to HTML format" html)
492 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
493 (const :tag " latex Export buffer to LaTeX format" latex)
494 (const :tag " man Export buffer to MAN format" man)
495 (const :tag " md Export buffer to Markdown format" md)
496 (const :tag " odt Export buffer to ODT format" odt)
497 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
498 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
499 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
500 (const :tag "C groff Export buffer to Groff format" groff)
501 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
502 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
504 (eval-after-load 'ox
505 '(mapc
506 (lambda (backend)
507 (condition-case nil (require (intern (format "ox-%s" backend)))
508 (error (message "Problems while trying to load export back-end `%s'"
509 backend))))
510 org-export-backends))
512 (defcustom org-support-shift-select nil
513 "Non-nil means make shift-cursor commands select text when possible.
515 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
516 start selecting a region, or enlarge regions started in this way.
517 In Org-mode, in special contexts, these same keys are used for
518 other purposes, important enough to compete with shift selection.
519 Org tries to balance these needs by supporting `shift-select-mode'
520 outside these special contexts, under control of this variable.
522 The default of this variable is nil, to avoid confusing behavior. Shifted
523 cursor keys will then execute Org commands in the following contexts:
524 - on a headline, changing TODO state (left/right) and priority (up/down)
525 - on a time stamp, changing the time
526 - in a plain list item, changing the bullet type
527 - in a property definition line, switching between allowed values
528 - in the BEGIN line of a clock table (changing the time block).
529 Outside these contexts, the commands will throw an error.
531 When this variable is t and the cursor is not in a special
532 context, Org-mode will support shift-selection for making and
533 enlarging regions. To make this more effective, the bullet
534 cycling will no longer happen anywhere in an item line, but only
535 if the cursor is exactly on the bullet.
537 If you set this variable to the symbol `always', then the keys
538 will not be special in headlines, property lines, and item lines,
539 to make shift selection work there as well. If this is what you
540 want, you can use the following alternative commands: `C-c C-t'
541 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
542 can be used to switch TODO sets, `C-c -' to cycle item bullet
543 types, and properties can be edited by hand or in column view.
545 However, when the cursor is on a timestamp, shift-cursor commands
546 will still edit the time stamp - this is just too good to give up.
548 XEmacs user should have this variable set to nil, because
549 `shift-select-mode' is in Emacs 23 or later only."
550 :group 'org
551 :type '(choice
552 (const :tag "Never" nil)
553 (const :tag "When outside special context" t)
554 (const :tag "Everywhere except timestamps" always)))
556 (defcustom org-loop-over-headlines-in-active-region nil
557 "Shall some commands act upon headlines in the active region?
559 When set to `t', some commands will be performed in all headlines
560 within the active region.
562 When set to `start-level', some commands will be performed in all
563 headlines within the active region, provided that these headlines
564 are of the same level than the first one.
566 When set to a string, those commands will be performed on the
567 matching headlines within the active region. Such string must be
568 a tags/property/todo match as it is used in the agenda tags view.
570 The list of commands is: `org-schedule', `org-deadline',
571 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
572 `org-archive-to-archive-sibling'. The archiving commands skip
573 already archived entries."
574 :type '(choice (const :tag "Don't loop" nil)
575 (const :tag "All headlines in active region" t)
576 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
577 (string :tag "Tags/Property/Todo matcher"))
578 :version "24.1"
579 :group 'org-todo
580 :group 'org-archive)
582 (defgroup org-startup nil
583 "Options concerning startup of Org-mode."
584 :tag "Org Startup"
585 :group 'org)
587 (defcustom org-startup-folded t
588 "Non-nil means entering Org-mode will switch to OVERVIEW.
589 This can also be configured on a per-file basis by adding one of
590 the following lines anywhere in the buffer:
592 #+STARTUP: fold (or `overview', this is equivalent)
593 #+STARTUP: nofold (or `showall', this is equivalent)
594 #+STARTUP: content
595 #+STARTUP: showeverything
597 By default, this option is ignored when Org opens agenda files
598 for the first time. If you want the agenda to honor the startup
599 option, set `org-agenda-inhibit-startup' to nil."
600 :group 'org-startup
601 :type '(choice
602 (const :tag "nofold: show all" nil)
603 (const :tag "fold: overview" t)
604 (const :tag "content: all headlines" content)
605 (const :tag "show everything, even drawers" showeverything)))
607 (defcustom org-startup-truncated t
608 "Non-nil means entering Org-mode will set `truncate-lines'.
609 This is useful since some lines containing links can be very long and
610 uninteresting. Also tables look terrible when wrapped."
611 :group 'org-startup
612 :type 'boolean)
614 (defcustom org-startup-indented nil
615 "Non-nil means turn on `org-indent-mode' on startup.
616 This can also be configured on a per-file basis by adding one of
617 the following lines anywhere in the buffer:
619 #+STARTUP: indent
620 #+STARTUP: noindent"
621 :group 'org-structure
622 :type '(choice
623 (const :tag "Not" nil)
624 (const :tag "Globally (slow on startup in large files)" t)))
626 (defcustom org-use-sub-superscripts t
627 "Non-nil means interpret \"_\" and \"^\" for display.
628 When this option is turned on, you can use TeX-like syntax for sub- and
629 superscripts. Several characters after \"_\" or \"^\" will be
630 considered as a single item - so grouping with {} is normally not
631 needed. For example, the following things will be parsed as single
632 sub- or superscripts.
634 10^24 or 10^tau several digits will be considered 1 item.
635 10^-12 or 10^-tau a leading sign with digits or a word
636 x^2-y^3 will be read as x^2 - y^3, because items are
637 terminated by almost any nonword/nondigit char.
638 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
640 Still, ambiguity is possible - so when in doubt use {} to enclose
641 the sub/superscript. If you set this variable to the symbol
642 `{}', the braces are *required* in order to trigger
643 interpretations as sub/superscript. This can be helpful in
644 documents that need \"_\" frequently in plain text."
645 :group 'org-startup
646 :version "24.1"
647 :type '(choice
648 (const :tag "Always interpret" t)
649 (const :tag "Only with braces" {})
650 (const :tag "Never interpret" nil)))
652 (defcustom org-startup-with-beamer-mode nil
653 "Non-nil means turn on `org-beamer-mode' on startup.
654 This can also be configured on a per-file basis by adding one of
655 the following lines anywhere in the buffer:
657 #+STARTUP: beamer"
658 :group 'org-startup
659 :version "24.1"
660 :type 'boolean)
662 (defcustom org-startup-align-all-tables nil
663 "Non-nil means align all tables when visiting a file.
664 This is useful when the column width in tables is forced with <N> cookies
665 in table fields. Such tables will look correct only after the first re-align.
666 This can also be configured on a per-file basis by adding one of
667 the following lines anywhere in the buffer:
668 #+STARTUP: align
669 #+STARTUP: noalign"
670 :group 'org-startup
671 :type 'boolean)
673 (defcustom org-startup-with-inline-images nil
674 "Non-nil means show inline images when loading a new Org file.
675 This can also be configured on a per-file basis by adding one of
676 the following lines anywhere in the buffer:
677 #+STARTUP: inlineimages
678 #+STARTUP: noinlineimages"
679 :group 'org-startup
680 :version "24.1"
681 :type 'boolean)
683 (defcustom org-startup-with-latex-preview nil
684 "Non-nil means preview LaTeX fragments when loading a new Org file.
686 This can also be configured on a per-file basis by adding one of
687 the followinglines anywhere in the buffer:
688 #+STARTUP: latexpreview
689 #+STARTUP: nolatexpreview"
690 :group 'org-startup
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type 'boolean)
695 (defcustom org-insert-mode-line-in-empty-file nil
696 "Non-nil means insert the first line setting Org-mode in empty files.
697 When the function `org-mode' is called interactively in an empty file, this
698 normally means that the file name does not automatically trigger Org-mode.
699 To ensure that the file will always be in Org-mode in the future, a
700 line enforcing Org-mode will be inserted into the buffer, if this option
701 has been set."
702 :group 'org-startup
703 :type 'boolean)
705 (defcustom org-replace-disputed-keys nil
706 "Non-nil means use alternative key bindings for some keys.
707 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
708 These keys are also used by other packages like shift-selection-mode'
709 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
710 If you want to use Org-mode together with one of these other modes,
711 or more generally if you would like to move some Org-mode commands to
712 other keys, set this variable and configure the keys with the variable
713 `org-disputed-keys'.
715 This option is only relevant at load-time of Org-mode, and must be set
716 *before* org.el is loaded. Changing it requires a restart of Emacs to
717 become effective."
718 :group 'org-startup
719 :type 'boolean)
721 (defcustom org-use-extra-keys nil
722 "Non-nil means use extra key sequence definitions for certain commands.
723 This happens automatically if you run XEmacs or if `window-system'
724 is nil. This variable lets you do the same manually. You must
725 set it before loading org.
727 Example: on Carbon Emacs 22 running graphically, with an external
728 keyboard on a Powerbook, the default way of setting M-left might
729 not work for either Alt or ESC. Setting this variable will make
730 it work for ESC."
731 :group 'org-startup
732 :type 'boolean)
734 (if (fboundp 'defvaralias)
735 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
737 (defcustom org-disputed-keys
738 '(([(shift up)] . [(meta p)])
739 ([(shift down)] . [(meta n)])
740 ([(shift left)] . [(meta -)])
741 ([(shift right)] . [(meta +)])
742 ([(control shift right)] . [(meta shift +)])
743 ([(control shift left)] . [(meta shift -)]))
744 "Keys for which Org-mode and other modes compete.
745 This is an alist, cars are the default keys, second element specifies
746 the alternative to use when `org-replace-disputed-keys' is t.
748 Keys can be specified in any syntax supported by `define-key'.
749 The value of this option takes effect only at Org-mode's startup,
750 therefore you'll have to restart Emacs to apply it after changing."
751 :group 'org-startup
752 :type 'alist)
754 (defun org-key (key)
755 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
756 Or return the original if not disputed.
757 Also apply the translations defined in `org-xemacs-key-equivalents'."
758 (when org-replace-disputed-keys
759 (let* ((nkey (key-description key))
760 (x (org-find-if (lambda (x)
761 (equal (key-description (car x)) nkey))
762 org-disputed-keys)))
763 (setq key (if x (cdr x) key))))
764 (when (featurep 'xemacs)
765 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
766 key)
768 (defun org-find-if (predicate seq)
769 (catch 'exit
770 (while seq
771 (if (funcall predicate (car seq))
772 (throw 'exit (car seq))
773 (pop seq)))))
775 (defun org-defkey (keymap key def)
776 "Define a key, possibly translated, as returned by `org-key'."
777 (define-key keymap (org-key key) def))
779 (defcustom org-ellipsis nil
780 "The ellipsis to use in the Org-mode outline.
781 When nil, just use the standard three dots. When a string, use that instead,
782 When a face, use the standard 3 dots, but with the specified face.
783 The change affects only Org-mode (which will then use its own display table).
784 Changing this requires executing `M-x org-mode' in a buffer to become
785 effective."
786 :group 'org-startup
787 :type '(choice (const :tag "Default" nil)
788 (face :tag "Face" :value org-warning)
789 (string :tag "String" :value "...#")))
791 (defvar org-display-table nil
792 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
794 (defgroup org-keywords nil
795 "Keywords in Org-mode."
796 :tag "Org Keywords"
797 :group 'org)
799 (defcustom org-deadline-string "DEADLINE:"
800 "String to mark deadline entries.
801 A deadline is this string, followed by a time stamp. Should be a word,
802 terminated by a colon. You can insert a schedule keyword and
803 a timestamp with \\[org-deadline].
804 Changes become only effective after restarting Emacs."
805 :group 'org-keywords
806 :type 'string)
808 (defcustom org-scheduled-string "SCHEDULED:"
809 "String to mark scheduled TODO entries.
810 A schedule is this string, followed by a time stamp. Should be a word,
811 terminated by a colon. You can insert a schedule keyword and
812 a timestamp with \\[org-schedule].
813 Changes become only effective after restarting Emacs."
814 :group 'org-keywords
815 :type 'string)
817 (defcustom org-closed-string "CLOSED:"
818 "String used as the prefix for timestamps logging closing a TODO entry."
819 :group 'org-keywords
820 :type 'string)
822 (defcustom org-clock-string "CLOCK:"
823 "String used as prefix for timestamps clocking work hours on an item."
824 :group 'org-keywords
825 :type 'string)
827 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
828 org-scheduled-string "\\|"
829 org-deadline-string "\\|"
830 org-closed-string "\\|"
831 org-clock-string "\\)")
832 "Matches a line with planning or clock info.")
834 (defcustom org-comment-string "COMMENT"
835 "Entries starting with this keyword will never be exported.
836 An entry can be toggled between COMMENT and normal with
837 \\[org-toggle-comment].
838 Changes become only effective after restarting Emacs."
839 :group 'org-keywords
840 :type 'string)
842 (defcustom org-quote-string "QUOTE"
843 "Entries starting with this keyword will be exported in fixed-width font.
844 Quoting applies only to the text in the entry following the headline, and does
845 not extend beyond the next headline, even if that is lower level.
846 An entry can be toggled between QUOTE and normal with
847 \\[org-toggle-fixed-width-section]."
848 :group 'org-keywords
849 :type 'string)
851 (defconst org-repeat-re
852 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
853 "Regular expression for specifying repeated events.
854 After a match, group 1 contains the repeat expression.")
856 (defgroup org-structure nil
857 "Options concerning the general structure of Org-mode files."
858 :tag "Org Structure"
859 :group 'org)
861 (defgroup org-reveal-location nil
862 "Options about how to make context of a location visible."
863 :tag "Org Reveal Location"
864 :group 'org-structure)
866 (defconst org-context-choice
867 '(choice
868 (const :tag "Always" t)
869 (const :tag "Never" nil)
870 (repeat :greedy t :tag "Individual contexts"
871 (cons
872 (choice :tag "Context"
873 (const agenda)
874 (const org-goto)
875 (const occur-tree)
876 (const tags-tree)
877 (const link-search)
878 (const mark-goto)
879 (const bookmark-jump)
880 (const isearch)
881 (const default))
882 (boolean))))
883 "Contexts for the reveal options.")
885 (defcustom org-show-hierarchy-above '((default . t))
886 "Non-nil means show full hierarchy when revealing a location.
887 Org-mode often shows locations in an org-mode file which might have
888 been invisible before. When this is set, the hierarchy of headings
889 above the exposed location is shown.
890 Turning this off for example for sparse trees makes them very compact.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. Valid contexts are
893 agenda when exposing an entry from the agenda
894 org-goto when using the command `org-goto' on key C-c C-j
895 occur-tree when using the command `org-occur' on key C-c /
896 tags-tree when constructing a sparse tree based on tags matches
897 link-search when exposing search matches associated with a link
898 mark-goto when exposing the jump goal of a mark
899 bookmark-jump when exposing a bookmark location
900 isearch when exiting from an incremental search
901 default default for all contexts not set explicitly"
902 :group 'org-reveal-location
903 :type org-context-choice)
905 (defcustom org-show-following-heading '((default . nil))
906 "Non-nil means show following heading when revealing a location.
907 Org-mode often shows locations in an org-mode file which might have
908 been invisible before. When this is set, the heading following the
909 match is shown.
910 Turning this off for example for sparse trees makes them very compact,
911 but makes it harder to edit the location of the match. In such a case,
912 use the command \\[org-reveal] to show more context.
913 Instead of t, this can also be an alist specifying this option for different
914 contexts. See `org-show-hierarchy-above' for valid contexts."
915 :group 'org-reveal-location
916 :type org-context-choice)
918 (defcustom org-show-siblings '((default . nil) (isearch t))
919 "Non-nil means show all sibling heading when revealing a location.
920 Org-mode often shows locations in an org-mode file which might have
921 been invisible before. When this is set, the sibling of the current entry
922 heading are all made visible. If `org-show-hierarchy-above' is t,
923 the same happens on each level of the hierarchy above the current entry.
925 By default this is on for the isearch context, off for all other contexts.
926 Turning this off for example for sparse trees makes them very compact,
927 but makes it harder to edit the location of the match. In such a case,
928 use the command \\[org-reveal] to show more context.
929 Instead of t, this can also be an alist specifying this option for different
930 contexts. See `org-show-hierarchy-above' for valid contexts."
931 :group 'org-reveal-location
932 :type org-context-choice)
934 (defcustom org-show-entry-below '((default . nil))
935 "Non-nil means show the entry below a headline when revealing a location.
936 Org-mode often shows locations in an org-mode file which might have
937 been invisible before. When this is set, the text below the headline that is
938 exposed is also shown.
940 By default this is off for all contexts.
941 Instead of t, this can also be an alist specifying this option for different
942 contexts. See `org-show-hierarchy-above' for valid contexts."
943 :group 'org-reveal-location
944 :type org-context-choice)
946 (defcustom org-indirect-buffer-display 'other-window
947 "How should indirect tree buffers be displayed?
948 This applies to indirect buffers created with the commands
949 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
950 Valid values are:
951 current-window Display in the current window
952 other-window Just display in another window.
953 dedicated-frame Create one new frame, and re-use it each time.
954 new-frame Make a new frame each time. Note that in this case
955 previously-made indirect buffers are kept, and you need to
956 kill these buffers yourself."
957 :group 'org-structure
958 :group 'org-agenda-windows
959 :type '(choice
960 (const :tag "In current window" current-window)
961 (const :tag "In current frame, other window" other-window)
962 (const :tag "Each time a new frame" new-frame)
963 (const :tag "One dedicated frame" dedicated-frame)))
965 (defcustom org-use-speed-commands nil
966 "Non-nil means activate single letter commands at beginning of a headline.
967 This may also be a function to test for appropriate locations where speed
968 commands should be active."
969 :group 'org-structure
970 :type '(choice
971 (const :tag "Never" nil)
972 (const :tag "At beginning of headline stars" t)
973 (function)))
975 (defcustom org-speed-commands-user nil
976 "Alist of additional speed commands.
977 This list will be checked before `org-speed-commands-default'
978 when the variable `org-use-speed-commands' is non-nil
979 and when the cursor is at the beginning of a headline.
980 The car if each entry is a string with a single letter, which must
981 be assigned to `self-insert-command' in the global map.
982 The cdr is either a command to be called interactively, a function
983 to be called, or a form to be evaluated.
984 An entry that is just a list with a single string will be interpreted
985 as a descriptive headline that will be added when listing the speed
986 commands in the Help buffer using the `?' speed command."
987 :group 'org-structure
988 :type '(repeat :value ("k" . ignore)
989 (choice :value ("k" . ignore)
990 (list :tag "Descriptive Headline" (string :tag "Headline"))
991 (cons :tag "Letter and Command"
992 (string :tag "Command letter")
993 (choice
994 (function)
995 (sexp))))))
997 (defgroup org-cycle nil
998 "Options concerning visibility cycling in Org-mode."
999 :tag "Org Cycle"
1000 :group 'org-structure)
1002 (defcustom org-cycle-skip-children-state-if-no-children t
1003 "Non-nil means skip CHILDREN state in entries that don't have any."
1004 :group 'org-cycle
1005 :type 'boolean)
1007 (defcustom org-cycle-max-level nil
1008 "Maximum level which should still be subject to visibility cycling.
1009 Levels higher than this will, for cycling, be treated as text, not a headline.
1010 When `org-odd-levels-only' is set, a value of N in this variable actually
1011 means 2N-1 stars as the limiting headline.
1012 When nil, cycle all levels.
1013 Note that the limiting level of cycling is also influenced by
1014 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1015 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1016 than its value."
1017 :group 'org-cycle
1018 :type '(choice
1019 (const :tag "No limit" nil)
1020 (integer :tag "Maximum level")))
1022 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1023 "Names of drawers. Drawers are not opened by cycling on the headline above.
1024 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1025 this:
1026 :DRAWERNAME:
1027 .....
1028 :END:
1029 The drawer \"PROPERTIES\" is special for capturing properties through
1030 the property API.
1032 Drawers can be defined on the per-file basis with a line like:
1034 #+DRAWERS: HIDDEN STATE PROPERTIES"
1035 :group 'org-structure
1036 :group 'org-cycle
1037 :type '(repeat (string :tag "Drawer Name")))
1039 (defcustom org-hide-block-startup nil
1040 "Non-nil means entering Org-mode will fold all blocks.
1041 This can also be set in on a per-file basis with
1043 #+STARTUP: hideblocks
1044 #+STARTUP: showblocks"
1045 :group 'org-startup
1046 :group 'org-cycle
1047 :type 'boolean)
1049 (defcustom org-cycle-global-at-bob nil
1050 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1051 This makes it possible to do global cycling without having to use S-TAB or
1052 \\[universal-argument] TAB. For this special case to work, the first line
1053 of the buffer must not be a headline -- it may be empty or some other text.
1054 When used in this way, `org-cycle-hook' is disabled temporarily to make
1055 sure the cursor stays at the beginning of the buffer. When this option is
1056 nil, don't do anything special at the beginning of the buffer."
1057 :group 'org-cycle
1058 :type 'boolean)
1060 (defcustom org-cycle-level-after-item/entry-creation t
1061 "Non-nil means cycle entry level or item indentation in new empty entries.
1063 When the cursor is at the end of an empty headline, i.e., with only stars
1064 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1065 and then all possible ancestor states, before returning to the original state.
1066 This makes data entry extremely fast: M-RET to create a new headline,
1067 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1069 When the cursor is at the end of an empty plain list item, one TAB will
1070 make it a subitem, two or more tabs will back up to make this an item
1071 higher up in the item hierarchy."
1072 :group 'org-cycle
1073 :type 'boolean)
1075 (defcustom org-cycle-emulate-tab t
1076 "Where should `org-cycle' emulate TAB.
1077 nil Never
1078 white Only in completely white lines
1079 whitestart Only at the beginning of lines, before the first non-white char
1080 t Everywhere except in headlines
1081 exc-hl-bol Everywhere except at the start of a headline
1082 If TAB is used in a place where it does not emulate TAB, the current subtree
1083 visibility is cycled."
1084 :group 'org-cycle
1085 :type '(choice (const :tag "Never" nil)
1086 (const :tag "Only in completely white lines" white)
1087 (const :tag "Before first char in a line" whitestart)
1088 (const :tag "Everywhere except in headlines" t)
1089 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1092 (defcustom org-cycle-separator-lines 2
1093 "Number of empty lines needed to keep an empty line between collapsed trees.
1094 If you leave an empty line between the end of a subtree and the following
1095 headline, this empty line is hidden when the subtree is folded.
1096 Org-mode will leave (exactly) one empty line visible if the number of
1097 empty lines is equal or larger to the number given in this variable.
1098 So the default 2 means at least 2 empty lines after the end of a subtree
1099 are needed to produce free space between a collapsed subtree and the
1100 following headline.
1102 If the number is negative, and the number of empty lines is at least -N,
1103 all empty lines are shown.
1105 Special case: when 0, never leave empty lines in collapsed view."
1106 :group 'org-cycle
1107 :type 'integer)
1108 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1110 (defcustom org-pre-cycle-hook nil
1111 "Hook that is run before visibility cycling is happening.
1112 The function(s) in this hook must accept a single argument which indicates
1113 the new state that will be set right after running this hook. The
1114 argument is a symbol. Before a global state change, it can have the values
1115 `overview', `content', or `all'. Before a local state change, it can have
1116 the values `folded', `children', or `subtree'."
1117 :group 'org-cycle
1118 :type 'hook)
1120 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1121 org-cycle-hide-drawers
1122 org-cycle-hide-inline-tasks
1123 org-cycle-show-empty-lines
1124 org-optimize-window-after-visibility-change)
1125 "Hook that is run after `org-cycle' has changed the buffer visibility.
1126 The function(s) in this hook must accept a single argument which indicates
1127 the new state that was set by the most recent `org-cycle' command. The
1128 argument is a symbol. After a global state change, it can have the values
1129 `overview', `contents', or `all'. After a local state change, it can have
1130 the values `folded', `children', or `subtree'."
1131 :group 'org-cycle
1132 :type 'hook)
1134 (defgroup org-edit-structure nil
1135 "Options concerning structure editing in Org-mode."
1136 :tag "Org Edit Structure"
1137 :group 'org-structure)
1139 (defcustom org-odd-levels-only nil
1140 "Non-nil means skip even levels and only use odd levels for the outline.
1141 This has the effect that two stars are being added/taken away in
1142 promotion/demotion commands. It also influences how levels are
1143 handled by the exporters.
1144 Changing it requires restart of `font-lock-mode' to become effective
1145 for fontification also in regions already fontified.
1146 You may also set this on a per-file basis by adding one of the following
1147 lines to the buffer:
1149 #+STARTUP: odd
1150 #+STARTUP: oddeven"
1151 :group 'org-edit-structure
1152 :group 'org-appearance
1153 :type 'boolean)
1155 (defcustom org-adapt-indentation t
1156 "Non-nil means adapt indentation to outline node level.
1158 When this variable is set, Org assumes that you write outlines by
1159 indenting text in each node to align with the headline (after the stars).
1160 The following issues are influenced by this variable:
1162 - When this is set and the *entire* text in an entry is indented, the
1163 indentation is increased by one space in a demotion command, and
1164 decreased by one in a promotion command. If any line in the entry
1165 body starts with text at column 0, indentation is not changed at all.
1167 - Property drawers and planning information is inserted indented when
1168 this variable s set. When nil, they will not be indented.
1170 - TAB indents a line relative to context. The lines below a headline
1171 will be indented when this variable is set.
1173 Note that this is all about true indentation, by adding and removing
1174 space characters. See also `org-indent.el' which does level-dependent
1175 indentation in a virtual way, i.e. at display time in Emacs."
1176 :group 'org-edit-structure
1177 :type 'boolean)
1179 (defcustom org-special-ctrl-a/e nil
1180 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1182 When t, `C-a' will bring back the cursor to the beginning of the
1183 headline text, i.e. after the stars and after a possible TODO
1184 keyword. In an item, this will be the position after bullet and
1185 check-box, if any. When the cursor is already at that position,
1186 another `C-a' will bring it to the beginning of the line.
1188 `C-e' will jump to the end of the headline, ignoring the presence
1189 of tags in the headline. A second `C-e' will then jump to the
1190 true end of the line, after any tags. This also means that, when
1191 this variable is non-nil, `C-e' also will never jump beyond the
1192 end of the heading of a folded section, i.e. not after the
1193 ellipses.
1195 When set to the symbol `reversed', the first `C-a' or `C-e' works
1196 normally, going to the true line boundary first. Only a directly
1197 following, identical keypress will bring the cursor to the
1198 special positions.
1200 This may also be a cons cell where the behavior for `C-a' and
1201 `C-e' is set separately."
1202 :group 'org-edit-structure
1203 :type '(choice
1204 (const :tag "off" nil)
1205 (const :tag "on: after stars/bullet and before tags first" t)
1206 (const :tag "reversed: true line boundary first" reversed)
1207 (cons :tag "Set C-a and C-e separately"
1208 (choice :tag "Special C-a"
1209 (const :tag "off" nil)
1210 (const :tag "on: after stars/bullet first" t)
1211 (const :tag "reversed: before stars/bullet first" reversed))
1212 (choice :tag "Special C-e"
1213 (const :tag "off" nil)
1214 (const :tag "on: before tags first" t)
1215 (const :tag "reversed: after tags first" reversed)))))
1216 (if (fboundp 'defvaralias)
1217 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1219 (defcustom org-special-ctrl-k nil
1220 "Non-nil means `C-k' will behave specially in headlines.
1221 When nil, `C-k' will call the default `kill-line' command.
1222 When t, the following will happen while the cursor is in the headline:
1224 - When the cursor is at the beginning of a headline, kill the entire
1225 line and possible the folded subtree below the line.
1226 - When in the middle of the headline text, kill the headline up to the tags.
1227 - When after the headline text, kill the tags."
1228 :group 'org-edit-structure
1229 :type 'boolean)
1231 (defcustom org-ctrl-k-protect-subtree nil
1232 "Non-nil means, do not delete a hidden subtree with C-k.
1233 When set to the symbol `error', simply throw an error when C-k is
1234 used to kill (part-of) a headline that has hidden text behind it.
1235 Any other non-nil value will result in a query to the user, if it is
1236 OK to kill that hidden subtree. When nil, kill without remorse."
1237 :group 'org-edit-structure
1238 :version "24.1"
1239 :type '(choice
1240 (const :tag "Do not protect hidden subtrees" nil)
1241 (const :tag "Protect hidden subtrees with a security query" t)
1242 (const :tag "Never kill a hidden subtree with C-k" error)))
1244 (defcustom org-catch-invisible-edits nil
1245 "Check if in invisible region before inserting or deleting a character.
1246 Valid values are:
1248 nil Do not check, so just do invisible edits.
1249 error Throw an error and do nothing.
1250 show Make point visible, and do the requested edit.
1251 show-and-error Make point visible, then throw an error and abort the edit.
1252 smart Make point visible, and do insertion/deletion if it is
1253 adjacent to visible text and the change feels predictable.
1254 Never delete a previously invisible character or add in the
1255 middle or right after an invisible region. Basically, this
1256 allows insertion and backward-delete right before ellipses.
1257 FIXME: maybe in this case we should not even show?"
1258 :group 'org-edit-structure
1259 :version "24.1"
1260 :type '(choice
1261 (const :tag "Do not check" nil)
1262 (const :tag "Throw error when trying to edit" error)
1263 (const :tag "Unhide, but do not do the edit" show-and-error)
1264 (const :tag "Show invisible part and do the edit" show)
1265 (const :tag "Be smart and do the right thing" smart)))
1267 (defcustom org-yank-folded-subtrees t
1268 "Non-nil means when yanking subtrees, fold them.
1269 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1270 it starts with a heading and all other headings in it are either children
1271 or siblings, then fold all the subtrees. However, do this only if no
1272 text after the yank would be swallowed into a folded tree by this action."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-yank-adjusted-subtrees nil
1277 "Non-nil means when yanking subtrees, adjust the level.
1278 With this setting, `org-paste-subtree' is used to insert the subtree, see
1279 this function for details."
1280 :group 'org-edit-structure
1281 :type 'boolean)
1283 (defcustom org-M-RET-may-split-line '((default . t))
1284 "Non-nil means M-RET will split the line at the cursor position.
1285 When nil, it will go to the end of the line before making a
1286 new line.
1287 You may also set this option in a different way for different
1288 contexts. Valid contexts are:
1290 headline when creating a new headline
1291 item when creating a new item
1292 table in a table field
1293 default the value to be used for all contexts not explicitly
1294 customized"
1295 :group 'org-structure
1296 :group 'org-table
1297 :type '(choice
1298 (const :tag "Always" t)
1299 (const :tag "Never" nil)
1300 (repeat :greedy t :tag "Individual contexts"
1301 (cons
1302 (choice :tag "Context"
1303 (const headline)
1304 (const item)
1305 (const table)
1306 (const default))
1307 (boolean)))))
1310 (defcustom org-insert-heading-respect-content nil
1311 "Non-nil means insert new headings after the current subtree.
1312 When nil, the new heading is created directly after the current line.
1313 The commands \\[org-insert-heading-respect-content] and
1314 \\[org-insert-todo-heading-respect-content] turn this variable on
1315 for the duration of the command."
1316 :group 'org-structure
1317 :type 'boolean)
1319 (defcustom org-blank-before-new-entry '((heading . auto)
1320 (plain-list-item . auto))
1321 "Should `org-insert-heading' leave a blank line before new heading/item?
1322 The value is an alist, with `heading' and `plain-list-item' as CAR,
1323 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1324 which case Org will look at the surrounding headings/items and try to
1325 make an intelligent decision whether to insert a blank line or not.
1327 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1328 set, the setting here is ignored and no empty line is inserted, to avoid
1329 breaking the list structure."
1330 :group 'org-edit-structure
1331 :type '(list
1332 (cons (const heading)
1333 (choice (const :tag "Never" nil)
1334 (const :tag "Always" t)
1335 (const :tag "Auto" auto)))
1336 (cons (const plain-list-item)
1337 (choice (const :tag "Never" nil)
1338 (const :tag "Always" t)
1339 (const :tag "Auto" auto)))))
1341 (defcustom org-insert-heading-hook nil
1342 "Hook being run after inserting a new heading."
1343 :group 'org-edit-structure
1344 :type 'hook)
1346 (defcustom org-enable-fixed-width-editor t
1347 "Non-nil means lines starting with \":\" are treated as fixed-width.
1348 This currently only means they are never auto-wrapped.
1349 When nil, such lines will be treated like ordinary lines.
1350 See also the QUOTE keyword."
1351 :group 'org-edit-structure
1352 :type 'boolean)
1354 (defcustom org-goto-auto-isearch t
1355 "Non-nil means typing characters in `org-goto' starts incremental search.
1356 When nil, you can use these keybindings to navigate the buffer:
1358 q Quit the org-goto interface
1359 n Go to the next visible heading
1360 p Go to the previous visible heading
1361 f Go one heading forward on same level
1362 b Go one heading backward on same level
1363 u Go one heading up"
1364 :group 'org-edit-structure
1365 :type 'boolean)
1367 (defgroup org-sparse-trees nil
1368 "Options concerning sparse trees in Org-mode."
1369 :tag "Org Sparse Trees"
1370 :group 'org-structure)
1372 (defcustom org-highlight-sparse-tree-matches t
1373 "Non-nil means highlight all matches that define a sparse tree.
1374 The highlights will automatically disappear the next time the buffer is
1375 changed by an edit command."
1376 :group 'org-sparse-trees
1377 :type 'boolean)
1379 (defcustom org-remove-highlights-with-change t
1380 "Non-nil means any change to the buffer will remove temporary highlights.
1381 Such highlights are created by `org-occur' and `org-clock-display'.
1382 When nil, `C-c C-c needs to be used to get rid of the highlights.
1383 The highlights created by `org-preview-latex-fragment' always need
1384 `C-c C-c' to be removed."
1385 :group 'org-sparse-trees
1386 :group 'org-time
1387 :type 'boolean)
1390 (defcustom org-occur-hook '(org-first-headline-recenter)
1391 "Hook that is run after `org-occur' has constructed a sparse tree.
1392 This can be used to recenter the window to show as much of the structure
1393 as possible."
1394 :group 'org-sparse-trees
1395 :type 'hook)
1397 (defgroup org-imenu-and-speedbar nil
1398 "Options concerning imenu and speedbar in Org-mode."
1399 :tag "Org Imenu and Speedbar"
1400 :group 'org-structure)
1402 (defcustom org-imenu-depth 2
1403 "The maximum level for Imenu access to Org-mode headlines.
1404 This also applied for speedbar access."
1405 :group 'org-imenu-and-speedbar
1406 :type 'integer)
1408 (defgroup org-table nil
1409 "Options concerning tables in Org-mode."
1410 :tag "Org Table"
1411 :group 'org)
1413 (defcustom org-enable-table-editor 'optimized
1414 "Non-nil means lines starting with \"|\" are handled by the table editor.
1415 When nil, such lines will be treated like ordinary lines.
1417 When equal to the symbol `optimized', the table editor will be optimized to
1418 do the following:
1419 - Automatic overwrite mode in front of whitespace in table fields.
1420 This makes the structure of the table stay in tact as long as the edited
1421 field does not exceed the column width.
1422 - Minimize the number of realigns. Normally, the table is aligned each time
1423 TAB or RET are pressed to move to another field. With optimization this
1424 happens only if changes to a field might have changed the column width.
1425 Optimization requires replacing the functions `self-insert-command',
1426 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1427 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1428 very good at guessing when a re-align will be necessary, but you can always
1429 force one with \\[org-ctrl-c-ctrl-c].
1431 If you would like to use the optimized version in Org-mode, but the
1432 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1434 This variable can be used to turn on and off the table editor during a session,
1435 but in order to toggle optimization, a restart is required.
1437 See also the variable `org-table-auto-blank-field'."
1438 :group 'org-table
1439 :type '(choice
1440 (const :tag "off" nil)
1441 (const :tag "on" t)
1442 (const :tag "on, optimized" optimized)))
1444 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1445 (version<= emacs-version "24.1"))
1446 "Non-nil means cluster self-insert commands for undo when possible.
1447 If this is set, then, like in the Emacs command loop, 20 consecutive
1448 characters will be undone together.
1449 This is configurable, because there is some impact on typing performance."
1450 :group 'org-table
1451 :type 'boolean)
1453 (defcustom org-table-tab-recognizes-table.el t
1454 "Non-nil means TAB will automatically notice a table.el table.
1455 When it sees such a table, it moves point into it and - if necessary -
1456 calls `table-recognize-table'."
1457 :group 'org-table-editing
1458 :type 'boolean)
1460 (defgroup org-link nil
1461 "Options concerning links in Org-mode."
1462 :tag "Org Link"
1463 :group 'org)
1465 (defvar org-link-abbrev-alist-local nil
1466 "Buffer-local version of `org-link-abbrev-alist', which see.
1467 The value of this is taken from the #+LINK lines.")
1468 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1470 (defcustom org-link-abbrev-alist nil
1471 "Alist of link abbreviations.
1472 The car of each element is a string, to be replaced at the start of a link.
1473 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1474 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1476 [[linkkey:tag][description]]
1478 The 'linkkey' must be a word word, starting with a letter, followed
1479 by letters, numbers, '-' or '_'.
1481 If REPLACE is a string, the tag will simply be appended to create the link.
1482 If the string contains \"%s\", the tag will be inserted there. If the string
1483 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1484 at that point (see the function `url-hexify-string'). If the string contains
1485 the specifier \"%(my-function)\", then the custom function `my-function' will
1486 be invoked: this function takes the tag as its only argument and must return
1487 a string.
1489 REPLACE may also be a function that will be called with the tag as the
1490 only argument to create the link, which should be returned as a string.
1492 See the manual for examples."
1493 :group 'org-link
1494 :type '(repeat
1495 (cons
1496 (string :tag "Protocol")
1497 (choice
1498 (string :tag "Format")
1499 (function)))))
1501 (defcustom org-descriptive-links t
1502 "Non-nil means Org will display descriptive links.
1503 E.g. [[http://orgmode.org][Org website]] will be displayed as
1504 \"Org Website\", hiding the link itself and just displaying its
1505 description. When set to `nil', Org will display the full links
1506 literally.
1508 You can interactively set the value of this variable by calling
1509 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1510 :group 'org-link
1511 :type 'boolean)
1513 (defcustom org-link-file-path-type 'adaptive
1514 "How the path name in file links should be stored.
1515 Valid values are:
1517 relative Relative to the current directory, i.e. the directory of the file
1518 into which the link is being inserted.
1519 absolute Absolute path, if possible with ~ for home directory.
1520 noabbrev Absolute path, no abbreviation of home directory.
1521 adaptive Use relative path for files in the current directory and sub-
1522 directories of it. For other files, use an absolute path."
1523 :group 'org-link
1524 :type '(choice
1525 (const relative)
1526 (const absolute)
1527 (const noabbrev)
1528 (const adaptive)))
1530 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1531 "Types of links that should be activated in Org-mode files.
1532 This is a list of symbols, each leading to the activation of a certain link
1533 type. In principle, it does not hurt to turn on most link types - there may
1534 be a small gain when turning off unused link types. The types are:
1536 bracket The recommended [[link][description]] or [[link]] links with hiding.
1537 angle Links in angular brackets that may contain whitespace like
1538 <bbdb:Carsten Dominik>.
1539 plain Plain links in normal text, no whitespace, like http://google.com.
1540 radio Text that is matched by a radio target, see manual for details.
1541 tag Tag settings in a headline (link to tag search).
1542 date Time stamps (link to calendar).
1543 footnote Footnote labels.
1545 Changing this variable requires a restart of Emacs to become effective."
1546 :group 'org-link
1547 :type '(set :greedy t
1548 (const :tag "Double bracket links" bracket)
1549 (const :tag "Angular bracket links" angle)
1550 (const :tag "Plain text links" plain)
1551 (const :tag "Radio target matches" radio)
1552 (const :tag "Tags" tag)
1553 (const :tag "Timestamps" date)
1554 (const :tag "Footnotes" footnote)))
1556 (defcustom org-make-link-description-function nil
1557 "Function to use for generating link descriptions from links.
1558 When nil, the link location will be used. This function must take
1559 two parameters: the first one is the link, the second one is the
1560 description generated by `org-insert-link'. The function should
1561 return the description to use."
1562 :group 'org-link
1563 :type 'function)
1565 (defgroup org-link-store nil
1566 "Options concerning storing links in Org-mode."
1567 :tag "Org Store Link"
1568 :group 'org-link)
1570 (defcustom org-url-hexify-p t
1571 "When non-nil, hexify URL when creating a link."
1572 :type 'boolean
1573 :version "24.3"
1574 :group 'org-link-store)
1576 (defcustom org-email-link-description-format "Email %c: %.30s"
1577 "Format of the description part of a link to an email or usenet message.
1578 The following %-escapes will be replaced by corresponding information:
1580 %F full \"From\" field
1581 %f name, taken from \"From\" field, address if no name
1582 %T full \"To\" field
1583 %t first name in \"To\" field, address if no name
1584 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1585 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1586 %s subject
1587 %d date
1588 %m message-id.
1590 You may use normal field width specification between the % and the letter.
1591 This is for example useful to limit the length of the subject.
1593 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1594 :group 'org-link-store
1595 :type 'string)
1597 (defcustom org-from-is-user-regexp
1598 (let (r1 r2)
1599 (when (and user-mail-address (not (string= user-mail-address "")))
1600 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1601 (when (and user-full-name (not (string= user-full-name "")))
1602 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1603 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1604 "Regexp matched against the \"From:\" header of an email or usenet message.
1605 It should match if the message is from the user him/herself."
1606 :group 'org-link-store
1607 :type 'regexp)
1609 (defcustom org-context-in-file-links t
1610 "Non-nil means file links from `org-store-link' contain context.
1611 A search string will be added to the file name with :: as separator and
1612 used to find the context when the link is activated by the command
1613 `org-open-at-point'. When this option is t, the entire active region
1614 will be placed in the search string of the file link. If set to a
1615 positive integer, only the first n lines of context will be stored.
1617 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1618 negates this setting for the duration of the command."
1619 :group 'org-link-store
1620 :type '(choice boolean integer))
1622 (defcustom org-keep-stored-link-after-insertion nil
1623 "Non-nil means keep link in list for entire session.
1625 The command `org-store-link' adds a link pointing to the current
1626 location to an internal list. These links accumulate during a session.
1627 The command `org-insert-link' can be used to insert links into any
1628 Org-mode file (offering completion for all stored links). When this
1629 option is nil, every link which has been inserted once using \\[org-insert-link]
1630 will be removed from the list, to make completing the unused links
1631 more efficient."
1632 :group 'org-link-store
1633 :type 'boolean)
1635 (defgroup org-link-follow nil
1636 "Options concerning following links in Org-mode."
1637 :tag "Org Follow Link"
1638 :group 'org-link)
1640 (defcustom org-link-translation-function nil
1641 "Function to translate links with different syntax to Org syntax.
1642 This can be used to translate links created for example by the Planner
1643 or emacs-wiki packages to Org syntax.
1644 The function must accept two parameters, a TYPE containing the link
1645 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1646 which is everything after the link protocol. It should return a cons
1647 with possibly modified values of type and path.
1648 Org contains a function for this, so if you set this variable to
1649 `org-translate-link-from-planner', you should be able follow many
1650 links created by planner."
1651 :group 'org-link-follow
1652 :type 'function)
1654 (defcustom org-follow-link-hook nil
1655 "Hook that is run after a link has been followed."
1656 :group 'org-link-follow
1657 :type 'hook)
1659 (defcustom org-tab-follows-link nil
1660 "Non-nil means on links TAB will follow the link.
1661 Needs to be set before org.el is loaded.
1662 This really should not be used, it does not make sense, and the
1663 implementation is bad."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-return-follows-link nil
1668 "Non-nil means on links RET will follow the link.
1669 In tables, the special behavior of RET has precedence."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mouse-1-follows-link
1674 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1675 "Non-nil means mouse-1 on a link will follow the link.
1676 A longer mouse click will still set point. Does not work on XEmacs.
1677 Needs to be set before org.el is loaded."
1678 :group 'org-link-follow
1679 :type 'boolean)
1681 (defcustom org-mark-ring-length 4
1682 "Number of different positions to be recorded in the ring.
1683 Changing this requires a restart of Emacs to work correctly."
1684 :group 'org-link-follow
1685 :type 'integer)
1687 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1688 "Non-nil means internal links in Org files must exactly match a headline.
1689 When nil, the link search tries to match a phrase with all words
1690 in the search text."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type '(choice
1694 (const :tag "Use fuzzy text search" nil)
1695 (const :tag "Match only exact headline" t)
1696 (const :tag "Match exact headline or query to create it"
1697 query-to-create)))
1699 (defcustom org-link-frame-setup
1700 '((vm . vm-visit-folder-other-frame)
1701 (vm-imap . vm-visit-imap-folder-other-frame)
1702 (gnus . org-gnus-no-new-news)
1703 (file . find-file-other-window)
1704 (wl . wl-other-frame))
1705 "Setup the frame configuration for following links.
1706 When following a link with Emacs, it may often be useful to display
1707 this link in another window or frame. This variable can be used to
1708 set this up for the different types of links.
1709 For VM, use any of
1710 `vm-visit-folder'
1711 `vm-visit-folder-other-window'
1712 `vm-visit-folder-other-frame'
1713 For Gnus, use any of
1714 `gnus'
1715 `gnus-other-frame'
1716 `org-gnus-no-new-news'
1717 For FILE, use any of
1718 `find-file'
1719 `find-file-other-window'
1720 `find-file-other-frame'
1721 For Wanderlust use any of
1722 `wl'
1723 `wl-other-frame'
1724 For the calendar, use the variable `calendar-setup'.
1725 For BBDB, it is currently only possible to display the matches in
1726 another window."
1727 :group 'org-link-follow
1728 :type '(list
1729 (cons (const vm)
1730 (choice
1731 (const vm-visit-folder)
1732 (const vm-visit-folder-other-window)
1733 (const vm-visit-folder-other-frame)))
1734 (cons (const gnus)
1735 (choice
1736 (const gnus)
1737 (const gnus-other-frame)
1738 (const org-gnus-no-new-news)))
1739 (cons (const file)
1740 (choice
1741 (const find-file)
1742 (const find-file-other-window)
1743 (const find-file-other-frame)))
1744 (cons (const wl)
1745 (choice
1746 (const wl)
1747 (const wl-other-frame)))))
1749 (defcustom org-display-internal-link-with-indirect-buffer nil
1750 "Non-nil means use indirect buffer to display infile links.
1751 Activating internal links (from one location in a file to another location
1752 in the same file) normally just jumps to the location. When the link is
1753 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1754 is displayed in
1755 another window. When this option is set, the other window actually displays
1756 an indirect buffer clone of the current buffer, to avoid any visibility
1757 changes to the current buffer."
1758 :group 'org-link-follow
1759 :type 'boolean)
1761 (defcustom org-open-non-existing-files nil
1762 "Non-nil means `org-open-file' will open non-existing files.
1763 When nil, an error will be generated.
1764 This variable applies only to external applications because they
1765 might choke on non-existing files. If the link is to a file that
1766 will be opened in Emacs, the variable is ignored."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-open-directory-means-index-dot-org nil
1771 "Non-nil means a link to a directory really means to index.org.
1772 When nil, following a directory link will run dired or open a finder/explorer
1773 window on that directory."
1774 :group 'org-link-follow
1775 :type 'boolean)
1777 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1778 "Function and arguments to call for following mailto links.
1779 This is a list with the first element being a Lisp function, and the
1780 remaining elements being arguments to the function. In string arguments,
1781 %a will be replaced by the address, and %s will be replaced by the subject
1782 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1783 :group 'org-link-follow
1784 :type '(choice
1785 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1786 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1787 (const :tag "message-mail" (message-mail "%a" "%s"))
1788 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1790 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1791 "Non-nil means ask for confirmation before executing shell links.
1792 Shell links can be dangerous: just think about a link
1794 [[shell:rm -rf ~/*][Google Search]]
1796 This link would show up in your Org-mode document as \"Google Search\",
1797 but really it would remove your entire home directory.
1798 Therefore we advise against setting this variable to nil.
1799 Just change it to `y-or-n-p' if you want to confirm with a
1800 single keystroke rather than having to type \"yes\"."
1801 :group 'org-link-follow
1802 :type '(choice
1803 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1804 (const :tag "with y-or-n (faster)" y-or-n-p)
1805 (const :tag "no confirmation (dangerous)" nil)))
1806 (put 'org-confirm-shell-link-function
1807 'safe-local-variable
1808 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1810 (defcustom org-confirm-shell-link-not-regexp ""
1811 "A regexp to skip confirmation for shell links."
1812 :group 'org-link-follow
1813 :version "24.1"
1814 :type 'regexp)
1816 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1817 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1818 Elisp links can be dangerous: just think about a link
1820 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1822 This link would show up in your Org-mode document as \"Google Search\",
1823 but really it would remove your entire home directory.
1824 Therefore we advise against setting this variable to nil.
1825 Just change it to `y-or-n-p' if you want to confirm with a
1826 single keystroke rather than having to type \"yes\"."
1827 :group 'org-link-follow
1828 :type '(choice
1829 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1830 (const :tag "with y-or-n (faster)" y-or-n-p)
1831 (const :tag "no confirmation (dangerous)" nil)))
1832 (put 'org-confirm-shell-link-function
1833 'safe-local-variable
1834 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1836 (defcustom org-confirm-elisp-link-not-regexp ""
1837 "A regexp to skip confirmation for Elisp links."
1838 :group 'org-link-follow
1839 :version "24.1"
1840 :type 'regexp)
1842 (defconst org-file-apps-defaults-gnu
1843 '((remote . emacs)
1844 (system . mailcap)
1845 (t . mailcap))
1846 "Default file applications on a UNIX or GNU/Linux system.
1847 See `org-file-apps'.")
1849 (defconst org-file-apps-defaults-macosx
1850 '((remote . emacs)
1851 (t . "open %s")
1852 (system . "open %s")
1853 ("ps.gz" . "gv %s")
1854 ("eps.gz" . "gv %s")
1855 ("dvi" . "xdvi %s")
1856 ("fig" . "xfig %s"))
1857 "Default file applications on a MacOS X system.
1858 The system \"open\" is known as a default, but we use X11 applications
1859 for some files for which the OS does not have a good default.
1860 See `org-file-apps'.")
1862 (defconst org-file-apps-defaults-windowsnt
1863 (list
1864 '(remote . emacs)
1865 (cons t
1866 (list (if (featurep 'xemacs)
1867 'mswindows-shell-execute
1868 'w32-shell-execute)
1869 "open" 'file))
1870 (cons 'system
1871 (list (if (featurep 'xemacs)
1872 'mswindows-shell-execute
1873 'w32-shell-execute)
1874 "open" 'file)))
1875 "Default file applications on a Windows NT system.
1876 The system \"open\" is used for most files.
1877 See `org-file-apps'.")
1879 (defcustom org-file-apps
1881 (auto-mode . emacs)
1882 ("\\.mm\\'" . default)
1883 ("\\.x?html?\\'" . default)
1884 ("\\.pdf\\'" . default)
1886 "External applications for opening `file:path' items in a document.
1887 Org-mode uses system defaults for different file types, but
1888 you can use this variable to set the application for a given file
1889 extension. The entries in this list are cons cells where the car identifies
1890 files and the cdr the corresponding command. Possible values for the
1891 file identifier are
1892 \"string\" A string as a file identifier can be interpreted in different
1893 ways, depending on its contents:
1895 - Alphanumeric characters only:
1896 Match links with this file extension.
1897 Example: (\"pdf\" . \"evince %s\")
1898 to open PDFs with evince.
1900 - Regular expression: Match links where the
1901 filename matches the regexp. If you want to
1902 use groups here, use shy groups.
1904 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1905 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1906 to open *.html and *.xhtml with firefox.
1908 - Regular expression which contains (non-shy) groups:
1909 Match links where the whole link, including \"::\", and
1910 anything after that, matches the regexp.
1911 In a custom command string, %1, %2, etc. are replaced with
1912 the parts of the link that were matched by the groups.
1913 For backwards compatibility, if a command string is given
1914 that does not use any of the group matches, this case is
1915 handled identically to the second one (i.e. match against
1916 file name only).
1917 In a custom lisp form, you can access the group matches with
1918 (match-string n link).
1920 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1921 to open [[file:document.pdf::5]] with evince at page 5.
1923 `directory' Matches a directory
1924 `remote' Matches a remote file, accessible through tramp or efs.
1925 Remote files most likely should be visited through Emacs
1926 because external applications cannot handle such paths.
1927 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1928 so all files Emacs knows how to handle. Using this with
1929 command `emacs' will open most files in Emacs. Beware that this
1930 will also open html files inside Emacs, unless you add
1931 (\"html\" . default) to the list as well.
1932 t Default for files not matched by any of the other options.
1933 `system' The system command to open files, like `open' on Windows
1934 and Mac OS X, and mailcap under GNU/Linux. This is the command
1935 that will be selected if you call `C-c C-o' with a double
1936 \\[universal-argument] \\[universal-argument] prefix.
1938 Possible values for the command are:
1939 `emacs' The file will be visited by the current Emacs process.
1940 `default' Use the default application for this file type, which is the
1941 association for t in the list, most likely in the system-specific
1942 part.
1943 This can be used to overrule an unwanted setting in the
1944 system-specific variable.
1945 `system' Use the system command for opening files, like \"open\".
1946 This command is specified by the entry whose car is `system'.
1947 Most likely, the system-specific version of this variable
1948 does define this command, but you can overrule/replace it
1949 here.
1950 string A command to be executed by a shell; %s will be replaced
1951 by the path to the file.
1952 sexp A Lisp form which will be evaluated. The file path will
1953 be available in the Lisp variable `file'.
1954 For more examples, see the system specific constants
1955 `org-file-apps-defaults-macosx'
1956 `org-file-apps-defaults-windowsnt'
1957 `org-file-apps-defaults-gnu'."
1958 :group 'org-link-follow
1959 :type '(repeat
1960 (cons (choice :value ""
1961 (string :tag "Extension")
1962 (const :tag "System command to open files" system)
1963 (const :tag "Default for unrecognized files" t)
1964 (const :tag "Remote file" remote)
1965 (const :tag "Links to a directory" directory)
1966 (const :tag "Any files that have Emacs modes"
1967 auto-mode))
1968 (choice :value ""
1969 (const :tag "Visit with Emacs" emacs)
1970 (const :tag "Use default" default)
1971 (const :tag "Use the system command" system)
1972 (string :tag "Command")
1973 (sexp :tag "Lisp form")))))
1975 (defcustom org-doi-server-url "http://dx.doi.org/"
1976 "The URL of the DOI server."
1977 :type 'string
1978 :version "24.3"
1979 :group 'org-link-follow)
1981 (defgroup org-refile nil
1982 "Options concerning refiling entries in Org-mode."
1983 :tag "Org Refile"
1984 :group 'org)
1986 (defcustom org-directory "~/org"
1987 "Directory with org files.
1988 This is just a default location to look for Org files. There is no need
1989 at all to put your files into this directory. It is only used in the
1990 following situations:
1992 1. When a capture template specifies a target file that is not an
1993 absolute path. The path will then be interpreted relative to
1994 `org-directory'
1995 2. When a capture note is filed away in an interactive way (when exiting the
1996 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1997 with `org-directory' as the default path."
1998 :group 'org-refile
1999 :group 'org-remember
2000 :group 'org-capture
2001 :type 'directory)
2003 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2004 "Default target for storing notes.
2005 Used as a fall back file for org-remember.el and org-capture.el, for
2006 templates that do not specify a target file."
2007 :group 'org-refile
2008 :group 'org-remember
2009 :group 'org-capture
2010 :type '(choice
2011 (const :tag "Default from remember-data-file" nil)
2012 file))
2014 (defcustom org-goto-interface 'outline
2015 "The default interface to be used for `org-goto'.
2016 Allowed values are:
2017 outline The interface shows an outline of the relevant file
2018 and the correct heading is found by moving through
2019 the outline or by searching with incremental search.
2020 outline-path-completion Headlines in the current buffer are offered via
2021 completion. This is the interface also used by
2022 the refile command."
2023 :group 'org-refile
2024 :type '(choice
2025 (const :tag "Outline" outline)
2026 (const :tag "Outline-path-completion" outline-path-completion)))
2028 (defcustom org-goto-max-level 5
2029 "Maximum target level when running `org-goto' with refile interface."
2030 :group 'org-refile
2031 :type 'integer)
2033 (defcustom org-reverse-note-order nil
2034 "Non-nil means store new notes at the beginning of a file or entry.
2035 When nil, new notes will be filed to the end of a file or entry.
2036 This can also be a list with cons cells of regular expressions that
2037 are matched against file names, and values."
2038 :group 'org-remember
2039 :group 'org-capture
2040 :group 'org-refile
2041 :type '(choice
2042 (const :tag "Reverse always" t)
2043 (const :tag "Reverse never" nil)
2044 (repeat :tag "By file name regexp"
2045 (cons regexp boolean))))
2047 (defcustom org-log-refile nil
2048 "Information to record when a task is refiled.
2050 Possible values are:
2052 nil Don't add anything
2053 time Add a time stamp to the task
2054 note Prompt for a note and add it with template `org-log-note-headings'
2056 This option can also be set with on a per-file-basis with
2058 #+STARTUP: nologrefile
2059 #+STARTUP: logrefile
2060 #+STARTUP: lognoterefile
2062 You can have local logging settings for a subtree by setting the LOGGING
2063 property to one or more of these keywords.
2065 When bulk-refiling from the agenda, the value `note' is forbidden and
2066 will temporarily be changed to `time'."
2067 :group 'org-refile
2068 :group 'org-progress
2069 :version "24.1"
2070 :type '(choice
2071 (const :tag "No logging" nil)
2072 (const :tag "Record timestamp" time)
2073 (const :tag "Record timestamp with note." note)))
2075 (defcustom org-refile-targets nil
2076 "Targets for refiling entries with \\[org-refile].
2077 This is a list of cons cells. Each cell contains:
2078 - a specification of the files to be considered, either a list of files,
2079 or a symbol whose function or variable value will be used to retrieve
2080 a file name or a list of file names. If you use `org-agenda-files' for
2081 that, all agenda files will be scanned for targets. Nil means consider
2082 headings in the current buffer.
2083 - A specification of how to find candidate refile targets. This may be
2084 any of:
2085 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2086 This tag has to be present in all target headlines, inheritance will
2087 not be considered.
2088 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2089 todo keyword.
2090 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2091 headlines that are refiling targets.
2092 - a cons cell (:level . N). Any headline of level N is considered a target.
2093 Note that, when `org-odd-levels-only' is set, level corresponds to
2094 order in hierarchy, not to the number of stars.
2095 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2096 Note that, when `org-odd-levels-only' is set, level corresponds to
2097 order in hierarchy, not to the number of stars.
2099 Each element of this list generates a set of possible targets.
2100 The union of these sets is presented (with completion) to
2101 the user by `org-refile'.
2103 You can set the variable `org-refile-target-verify-function' to a function
2104 to verify each headline found by the simple criteria above.
2106 When this variable is nil, all top-level headlines in the current buffer
2107 are used, equivalent to the value `((nil . (:level . 1))'."
2108 :group 'org-refile
2109 :type '(repeat
2110 (cons
2111 (choice :value org-agenda-files
2112 (const :tag "All agenda files" org-agenda-files)
2113 (const :tag "Current buffer" nil)
2114 (function) (variable) (file))
2115 (choice :tag "Identify target headline by"
2116 (cons :tag "Specific tag" (const :value :tag) (string))
2117 (cons :tag "TODO keyword" (const :value :todo) (string))
2118 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2119 (cons :tag "Level number" (const :value :level) (integer))
2120 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2122 (defcustom org-refile-target-verify-function nil
2123 "Function to verify if the headline at point should be a refile target.
2124 The function will be called without arguments, with point at the
2125 beginning of the headline. It should return t and leave point
2126 where it is if the headline is a valid target for refiling.
2128 If the target should not be selected, the function must return nil.
2129 In addition to this, it may move point to a place from where the search
2130 should be continued. For example, the function may decide that the entire
2131 subtree of the current entry should be excluded and move point to the end
2132 of the subtree."
2133 :group 'org-refile
2134 :type 'function)
2136 (defcustom org-refile-use-cache nil
2137 "Non-nil means cache refile targets to speed up the process.
2138 The cache for a particular file will be updated automatically when
2139 the buffer has been killed, or when any of the marker used for flagging
2140 refile targets no longer points at a live buffer.
2141 If you have added new entries to a buffer that might themselves be targets,
2142 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2143 find that easier, `C-u C-u C-u C-c C-w'."
2144 :group 'org-refile
2145 :version "24.1"
2146 :type 'boolean)
2148 (defcustom org-refile-use-outline-path nil
2149 "Non-nil means provide refile targets as paths.
2150 So a level 3 headline will be available as level1/level2/level3.
2152 When the value is `file', also include the file name (without directory)
2153 into the path. In this case, you can also stop the completion after
2154 the file name, to get entries inserted as top level in the file.
2156 When `full-file-path', include the full file path."
2157 :group 'org-refile
2158 :type '(choice
2159 (const :tag "Not" nil)
2160 (const :tag "Yes" t)
2161 (const :tag "Start with file name" file)
2162 (const :tag "Start with full file path" full-file-path)))
2164 (defcustom org-outline-path-complete-in-steps t
2165 "Non-nil means complete the outline path in hierarchical steps.
2166 When Org-mode uses the refile interface to select an outline path
2167 \(see variable `org-refile-use-outline-path'), the completion of
2168 the path can be done is a single go, or if can be done in steps down
2169 the headline hierarchy. Going in steps is probably the best if you
2170 do not use a special completion package like `ido' or `icicles'.
2171 However, when using these packages, going in one step can be very
2172 fast, while still showing the whole path to the entry."
2173 :group 'org-refile
2174 :type 'boolean)
2176 (defcustom org-refile-allow-creating-parent-nodes nil
2177 "Non-nil means allow to create new nodes as refile targets.
2178 New nodes are then created by adding \"/new node name\" to the completion
2179 of an existing node. When the value of this variable is `confirm',
2180 new node creation must be confirmed by the user (recommended)
2181 When nil, the completion must match an existing entry.
2183 Note that, if the new heading is not seen by the criteria
2184 listed in `org-refile-targets', multiple instances of the same
2185 heading would be created by trying again to file under the new
2186 heading."
2187 :group 'org-refile
2188 :type '(choice
2189 (const :tag "Never" nil)
2190 (const :tag "Always" t)
2191 (const :tag "Prompt for confirmation" confirm)))
2193 (defcustom org-refile-active-region-within-subtree nil
2194 "Non-nil means also refile active region within a subtree.
2196 By default `org-refile' doesn't allow refiling regions if they
2197 don't contain a set of subtrees, but it might be convenient to
2198 do so sometimes: in that case, the first line of the region is
2199 converted to a headline before refiling."
2200 :group 'org-refile
2201 :version "24.1"
2202 :type 'boolean)
2204 (defgroup org-todo nil
2205 "Options concerning TODO items in Org-mode."
2206 :tag "Org TODO"
2207 :group 'org)
2209 (defgroup org-progress nil
2210 "Options concerning Progress logging in Org-mode."
2211 :tag "Org Progress"
2212 :group 'org-time)
2214 (defvar org-todo-interpretation-widgets
2215 '((:tag "Sequence (cycling hits every state)" sequence)
2216 (:tag "Type (cycling directly to DONE)" type))
2217 "The available interpretation symbols for customizing `org-todo-keywords'.
2218 Interested libraries should add to this list.")
2220 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2221 "List of TODO entry keyword sequences and their interpretation.
2222 \\<org-mode-map>This is a list of sequences.
2224 Each sequence starts with a symbol, either `sequence' or `type',
2225 indicating if the keywords should be interpreted as a sequence of
2226 action steps, or as different types of TODO items. The first
2227 keywords are states requiring action - these states will select a headline
2228 for inclusion into the global TODO list Org-mode produces. If one of
2229 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2230 signify that no further action is necessary. If \"|\" is not found,
2231 the last keyword is treated as the only DONE state of the sequence.
2233 The command \\[org-todo] cycles an entry through these states, and one
2234 additional state where no keyword is present. For details about this
2235 cycling, see the manual.
2237 TODO keywords and interpretation can also be set on a per-file basis with
2238 the special #+SEQ_TODO and #+TYP_TODO lines.
2240 Each keyword can optionally specify a character for fast state selection
2241 \(in combination with the variable `org-use-fast-todo-selection')
2242 and specifiers for state change logging, using the same syntax that
2243 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2244 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2245 indicates to record a time stamp each time this state is selected.
2247 Each keyword may also specify if a timestamp or a note should be
2248 recorded when entering or leaving the state, by adding additional
2249 characters in the parenthesis after the keyword. This looks like this:
2250 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2251 record only the time of the state change. With X and Y being either
2252 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2253 Y when leaving the state if and only if the *target* state does not
2254 define X. You may omit any of the fast-selection key or X or /Y,
2255 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2257 For backward compatibility, this variable may also be just a list
2258 of keywords. In this case the interpretation (sequence or type) will be
2259 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2260 :group 'org-todo
2261 :group 'org-keywords
2262 :type '(choice
2263 (repeat :tag "Old syntax, just keywords"
2264 (string :tag "Keyword"))
2265 (repeat :tag "New syntax"
2266 (cons
2267 (choice
2268 :tag "Interpretation"
2269 ;;Quick and dirty way to see
2270 ;;`org-todo-interpretations'. This takes the
2271 ;;place of item arguments
2272 :convert-widget
2273 (lambda (widget)
2274 (widget-put widget
2275 :args (mapcar
2276 #'(lambda (x)
2277 (widget-convert
2278 (cons 'const x)))
2279 org-todo-interpretation-widgets))
2280 widget))
2281 (repeat
2282 (string :tag "Keyword"))))))
2284 (defvar org-todo-keywords-1 nil
2285 "All TODO and DONE keywords active in a buffer.")
2286 (make-variable-buffer-local 'org-todo-keywords-1)
2287 (defvar org-todo-keywords-for-agenda nil)
2288 (defvar org-done-keywords-for-agenda nil)
2289 (defvar org-drawers-for-agenda nil)
2290 (defvar org-todo-keyword-alist-for-agenda nil)
2291 (defvar org-tag-alist-for-agenda nil)
2292 (defvar org-agenda-contributing-files nil)
2293 (defvar org-not-done-keywords nil)
2294 (make-variable-buffer-local 'org-not-done-keywords)
2295 (defvar org-done-keywords nil)
2296 (make-variable-buffer-local 'org-done-keywords)
2297 (defvar org-todo-heads nil)
2298 (make-variable-buffer-local 'org-todo-heads)
2299 (defvar org-todo-sets nil)
2300 (make-variable-buffer-local 'org-todo-sets)
2301 (defvar org-todo-log-states nil)
2302 (make-variable-buffer-local 'org-todo-log-states)
2303 (defvar org-todo-kwd-alist nil)
2304 (make-variable-buffer-local 'org-todo-kwd-alist)
2305 (defvar org-todo-key-alist nil)
2306 (make-variable-buffer-local 'org-todo-key-alist)
2307 (defvar org-todo-key-trigger nil)
2308 (make-variable-buffer-local 'org-todo-key-trigger)
2310 (defcustom org-todo-interpretation 'sequence
2311 "Controls how TODO keywords are interpreted.
2312 This variable is in principle obsolete and is only used for
2313 backward compatibility, if the interpretation of todo keywords is
2314 not given already in `org-todo-keywords'. See that variable for
2315 more information."
2316 :group 'org-todo
2317 :group 'org-keywords
2318 :type '(choice (const sequence)
2319 (const type)))
2321 (defcustom org-use-fast-todo-selection t
2322 "Non-nil means use the fast todo selection scheme with C-c C-t.
2323 This variable describes if and under what circumstances the cycling
2324 mechanism for TODO keywords will be replaced by a single-key, direct
2325 selection scheme.
2327 When nil, fast selection is never used.
2329 When the symbol `prefix', it will be used when `org-todo' is called
2330 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2331 `C-u t' in an agenda buffer.
2333 When t, fast selection is used by default. In this case, the prefix
2334 argument forces cycling instead.
2336 In all cases, the special interface is only used if access keys have
2337 actually been assigned by the user, i.e. if keywords in the configuration
2338 are followed by a letter in parenthesis, like TODO(t)."
2339 :group 'org-todo
2340 :type '(choice
2341 (const :tag "Never" nil)
2342 (const :tag "By default" t)
2343 (const :tag "Only with C-u C-c C-t" prefix)))
2345 (defcustom org-provide-todo-statistics t
2346 "Non-nil means update todo statistics after insert and toggle.
2347 ALL-HEADLINES means update todo statistics by including headlines
2348 with no TODO keyword as well, counting them as not done.
2349 A list of TODO keywords means the same, but skip keywords that are
2350 not in this list.
2352 When this is set, todo statistics is updated in the parent of the
2353 current entry each time a todo state is changed."
2354 :group 'org-todo
2355 :type '(choice
2356 (const :tag "Yes, only for TODO entries" t)
2357 (const :tag "Yes, including all entries" 'all-headlines)
2358 (repeat :tag "Yes, for TODOs in this list"
2359 (string :tag "TODO keyword"))
2360 (other :tag "No TODO statistics" nil)))
2362 (defcustom org-hierarchical-todo-statistics t
2363 "Non-nil means TODO statistics covers just direct children.
2364 When nil, all entries in the subtree are considered.
2365 This has only an effect if `org-provide-todo-statistics' is set.
2366 To set this to nil for only a single subtree, use a COOKIE_DATA
2367 property and include the word \"recursive\" into the value."
2368 :group 'org-todo
2369 :type 'boolean)
2371 (defcustom org-after-todo-state-change-hook nil
2372 "Hook which is run after the state of a TODO item was changed.
2373 The new state (a string with a TODO keyword, or nil) is available in the
2374 Lisp variable `org-state'."
2375 :group 'org-todo
2376 :type 'hook)
2378 (defvar org-blocker-hook nil
2379 "Hook for functions that are allowed to block a state change.
2381 Functions in this hook should not modify the buffer.
2382 Each function gets as its single argument a property list,
2383 see `org-trigger-hook' for more information about this list.
2385 If any of the functions in this hook returns nil, the state change
2386 is blocked.")
2388 (defvar org-trigger-hook nil
2389 "Hook for functions that are triggered by a state change.
2391 Each function gets as its single argument a property list with at
2392 least the following elements:
2394 (:type type-of-change :position pos-at-entry-start
2395 :from old-state :to new-state)
2397 Depending on the type, more properties may be present.
2399 This mechanism is currently implemented for:
2401 TODO state changes
2402 ------------------
2403 :type todo-state-change
2404 :from previous state (keyword as a string), or nil, or a symbol
2405 'todo' or 'done', to indicate the general type of state.
2406 :to new state, like in :from")
2408 (defcustom org-enforce-todo-dependencies nil
2409 "Non-nil means undone TODO entries will block switching the parent to DONE.
2410 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2411 be blocked if any prior sibling is not yet done.
2412 Finally, if the parent is blocked because of ordered siblings of its own,
2413 the child will also be blocked."
2414 :set (lambda (var val)
2415 (set var val)
2416 (if val
2417 (add-hook 'org-blocker-hook
2418 'org-block-todo-from-children-or-siblings-or-parent)
2419 (remove-hook 'org-blocker-hook
2420 'org-block-todo-from-children-or-siblings-or-parent)))
2421 :group 'org-todo
2422 :type 'boolean)
2424 (defcustom org-enforce-todo-checkbox-dependencies nil
2425 "Non-nil means unchecked boxes will block switching the parent to DONE.
2426 When this is nil, checkboxes have no influence on switching TODO states.
2427 When non-nil, you first need to check off all check boxes before the TODO
2428 entry can be switched to DONE.
2429 This variable needs to be set before org.el is loaded, and you need to
2430 restart Emacs after a change to make the change effective. The only way
2431 to change is while Emacs is running is through the customize interface."
2432 :set (lambda (var val)
2433 (set var val)
2434 (if val
2435 (add-hook 'org-blocker-hook
2436 'org-block-todo-from-checkboxes)
2437 (remove-hook 'org-blocker-hook
2438 'org-block-todo-from-checkboxes)))
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-insert-todo-heading-as-state-change nil
2443 "Non-nil means inserting a TODO heading is treated as state change.
2444 So when the command \\[org-insert-todo-heading] is used, state change
2445 logging will apply if appropriate. When nil, the new TODO item will
2446 be inserted directly, and no logging will take place."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2451 "Non-nil means switching TODO states with S-cursor counts as state change.
2452 This is the default behavior. However, setting this to nil allows a
2453 convenient way to select a TODO state and bypass any logging associated
2454 with that."
2455 :group 'org-todo
2456 :type 'boolean)
2458 (defcustom org-todo-state-tags-triggers nil
2459 "Tag changes that should be triggered by TODO state changes.
2460 This is a list. Each entry is
2462 (state-change (tag . flag) .......)
2464 State-change can be a string with a state, and empty string to indicate the
2465 state that has no TODO keyword, or it can be one of the symbols `todo'
2466 or `done', meaning any not-done or done state, respectively."
2467 :group 'org-todo
2468 :group 'org-tags
2469 :type '(repeat
2470 (cons (choice :tag "When changing to"
2471 (const :tag "Not-done state" todo)
2472 (const :tag "Done state" done)
2473 (string :tag "State"))
2474 (repeat
2475 (cons :tag "Tag action"
2476 (string :tag "Tag")
2477 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2479 (defcustom org-log-done nil
2480 "Information to record when a task moves to the DONE state.
2482 Possible values are:
2484 nil Don't add anything, just change the keyword
2485 time Add a time stamp to the task
2486 note Prompt for a note and add it with template `org-log-note-headings'
2488 This option can also be set with on a per-file-basis with
2490 #+STARTUP: nologdone
2491 #+STARTUP: logdone
2492 #+STARTUP: lognotedone
2494 You can have local logging settings for a subtree by setting the LOGGING
2495 property to one or more of these keywords."
2496 :group 'org-todo
2497 :group 'org-progress
2498 :type '(choice
2499 (const :tag "No logging" nil)
2500 (const :tag "Record CLOSED timestamp" time)
2501 (const :tag "Record CLOSED timestamp with note." note)))
2503 ;; Normalize old uses of org-log-done.
2504 (cond
2505 ((eq org-log-done t) (setq org-log-done 'time))
2506 ((and (listp org-log-done) (memq 'done org-log-done))
2507 (setq org-log-done 'note)))
2509 (defcustom org-log-reschedule nil
2510 "Information to record when the scheduling date of a tasks is modified.
2512 Possible values are:
2514 nil Don't add anything, just change the date
2515 time Add a time stamp to the task
2516 note Prompt for a note and add it with template `org-log-note-headings'
2518 This option can also be set with on a per-file-basis with
2520 #+STARTUP: nologreschedule
2521 #+STARTUP: logreschedule
2522 #+STARTUP: lognotereschedule"
2523 :group 'org-todo
2524 :group 'org-progress
2525 :type '(choice
2526 (const :tag "No logging" nil)
2527 (const :tag "Record timestamp" time)
2528 (const :tag "Record timestamp with note." note)))
2530 (defcustom org-log-redeadline nil
2531 "Information to record when the deadline date of a tasks is modified.
2533 Possible values are:
2535 nil Don't add anything, just change the date
2536 time Add a time stamp to the task
2537 note Prompt for a note and add it with template `org-log-note-headings'
2539 This option can also be set with on a per-file-basis with
2541 #+STARTUP: nologredeadline
2542 #+STARTUP: logredeadline
2543 #+STARTUP: lognoteredeadline
2545 You can have local logging settings for a subtree by setting the LOGGING
2546 property to one or more of these keywords."
2547 :group 'org-todo
2548 :group 'org-progress
2549 :type '(choice
2550 (const :tag "No logging" nil)
2551 (const :tag "Record timestamp" time)
2552 (const :tag "Record timestamp with note." note)))
2554 (defcustom org-log-note-clock-out nil
2555 "Non-nil means record a note when clocking out of an item.
2556 This can also be configured on a per-file basis by adding one of
2557 the following lines anywhere in the buffer:
2559 #+STARTUP: lognoteclock-out
2560 #+STARTUP: nolognoteclock-out"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-done-with-time t
2566 "Non-nil means the CLOSED time stamp will contain date and time.
2567 When nil, only the date will be recorded."
2568 :group 'org-progress
2569 :type 'boolean)
2571 (defcustom org-log-note-headings
2572 '((done . "CLOSING NOTE %t")
2573 (state . "State %-12s from %-12S %t")
2574 (note . "Note taken on %t")
2575 (reschedule . "Rescheduled from %S on %t")
2576 (delschedule . "Not scheduled, was %S on %t")
2577 (redeadline . "New deadline from %S on %t")
2578 (deldeadline . "Removed deadline, was %S on %t")
2579 (refile . "Refiled on %t")
2580 (clock-out . ""))
2581 "Headings for notes added to entries.
2582 The value is an alist, with the car being a symbol indicating the note
2583 context, and the cdr is the heading to be used. The heading may also be the
2584 empty string.
2585 %t in the heading will be replaced by a time stamp.
2586 %T will be an active time stamp instead the default inactive one
2587 %d will be replaced by a short-format time stamp.
2588 %D will be replaced by an active short-format time stamp.
2589 %s will be replaced by the new TODO state, in double quotes.
2590 %S will be replaced by the old TODO state, in double quotes.
2591 %u will be replaced by the user name.
2592 %U will be replaced by the full user name.
2594 In fact, it is not a good idea to change the `state' entry, because
2595 agenda log mode depends on the format of these entries."
2596 :group 'org-todo
2597 :group 'org-progress
2598 :type '(list :greedy t
2599 (cons (const :tag "Heading when closing an item" done) string)
2600 (cons (const :tag
2601 "Heading when changing todo state (todo sequence only)"
2602 state) string)
2603 (cons (const :tag "Heading when just taking a note" note) string)
2604 (cons (const :tag "Heading when clocking out" clock-out) string)
2605 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2606 (cons (const :tag "Heading when rescheduling" reschedule) string)
2607 (cons (const :tag "Heading when changing deadline" redeadline) string)
2608 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2609 (cons (const :tag "Heading when refiling" refile) string)))
2611 (unless (assq 'note org-log-note-headings)
2612 (push '(note . "%t") org-log-note-headings))
2614 (defcustom org-log-into-drawer nil
2615 "Non-nil means insert state change notes and time stamps into a drawer.
2616 When nil, state changes notes will be inserted after the headline and
2617 any scheduling and clock lines, but not inside a drawer.
2619 The value of this variable should be the name of the drawer to use.
2620 LOGBOOK is proposed as the default drawer for this purpose, you can
2621 also set this to a string to define the drawer of your choice.
2623 A value of t is also allowed, representing \"LOGBOOK\".
2625 A value of t or nil can also be set with on a per-file-basis with
2627 #+STARTUP: logdrawer
2628 #+STARTUP: nologdrawer
2630 If this variable is set, `org-log-state-notes-insert-after-drawers'
2631 will be ignored.
2633 You can set the property LOG_INTO_DRAWER to overrule this setting for
2634 a subtree."
2635 :group 'org-todo
2636 :group 'org-progress
2637 :type '(choice
2638 (const :tag "Not into a drawer" nil)
2639 (const :tag "LOGBOOK" t)
2640 (string :tag "Other")))
2642 (if (fboundp 'defvaralias)
2643 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2645 (defun org-log-into-drawer ()
2646 "Return the value of `org-log-into-drawer', but let properties overrule.
2647 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2648 used instead of the default value."
2649 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2650 (cond
2651 ((not p) org-log-into-drawer)
2652 ((equal p "nil") nil)
2653 ((equal p "t") "LOGBOOK")
2654 (t p))))
2656 (defcustom org-log-state-notes-insert-after-drawers nil
2657 "Non-nil means insert state change notes after any drawers in entry.
2658 Only the drawers that *immediately* follow the headline and the
2659 deadline/scheduled line are skipped.
2660 When nil, insert notes right after the heading and perhaps the line
2661 with deadline/scheduling if present.
2663 This variable will have no effect if `org-log-into-drawer' is
2664 set."
2665 :group 'org-todo
2666 :group 'org-progress
2667 :type 'boolean)
2669 (defcustom org-log-states-order-reversed t
2670 "Non-nil means the latest state note will be directly after heading.
2671 When nil, the state change notes will be ordered according to time.
2673 This option can also be set with on a per-file-basis with
2675 #+STARTUP: logstatesreversed
2676 #+STARTUP: nologstatesreversed"
2677 :group 'org-todo
2678 :group 'org-progress
2679 :type 'boolean)
2681 (defcustom org-todo-repeat-to-state nil
2682 "The TODO state to which a repeater should return the repeating task.
2683 By default this is the first task in a TODO sequence, or the previous state
2684 in a TODO_TYP set. But you can specify another task here.
2685 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2686 :group 'org-todo
2687 :version "24.1"
2688 :type '(choice (const :tag "Head of sequence" nil)
2689 (string :tag "Specific state")))
2691 (defcustom org-log-repeat 'time
2692 "Non-nil means record moving through the DONE state when triggering repeat.
2693 An auto-repeating task is immediately switched back to TODO when
2694 marked DONE. If you are not logging state changes (by adding \"@\"
2695 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2696 record a closing note, there will be no record of the task moving
2697 through DONE. This variable forces taking a note anyway.
2699 nil Don't force a record
2700 time Record a time stamp
2701 note Prompt for a note and add it with template `org-log-note-headings'
2703 This option can also be set with on a per-file-basis with
2705 #+STARTUP: nologrepeat
2706 #+STARTUP: logrepeat
2707 #+STARTUP: lognoterepeat
2709 You can have local logging settings for a subtree by setting the LOGGING
2710 property to one or more of these keywords."
2711 :group 'org-todo
2712 :group 'org-progress
2713 :type '(choice
2714 (const :tag "Don't force a record" nil)
2715 (const :tag "Force recording the DONE state" time)
2716 (const :tag "Force recording a note with the DONE state" note)))
2719 (defgroup org-priorities nil
2720 "Priorities in Org-mode."
2721 :tag "Org Priorities"
2722 :group 'org-todo)
2724 (defcustom org-enable-priority-commands t
2725 "Non-nil means priority commands are active.
2726 When nil, these commands will be disabled, so that you never accidentally
2727 set a priority."
2728 :group 'org-priorities
2729 :type 'boolean)
2731 (defcustom org-highest-priority ?A
2732 "The highest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a smaller ASCII number than `org-lowest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-lowest-priority ?C
2738 "The lowest priority of TODO items. A character like ?A, ?B etc.
2739 Must have a larger ASCII number than `org-highest-priority'."
2740 :group 'org-priorities
2741 :type 'character)
2743 (defcustom org-default-priority ?B
2744 "The default priority of TODO items.
2745 This is the priority an item gets if no explicit priority is given.
2746 When starting to cycle on an empty priority the first step in the cycle
2747 depends on `org-priority-start-cycle-with-default'. The resulting first
2748 step priority must not exceed the range from `org-highest-priority' to
2749 `org-lowest-priority' which means that `org-default-priority' has to be
2750 in this range exclusive or inclusive the range boundaries. Else the
2751 first step refuses to set the default and the second will fall back
2752 to (depending on the command used) the highest or lowest priority."
2753 :group 'org-priorities
2754 :type 'character)
2756 (defcustom org-priority-start-cycle-with-default t
2757 "Non-nil means start with default priority when starting to cycle.
2758 When this is nil, the first step in the cycle will be (depending on the
2759 command used) one higher or lower than the default priority.
2760 See also `org-default-priority'."
2761 :group 'org-priorities
2762 :type 'boolean)
2764 (defcustom org-get-priority-function nil
2765 "Function to extract the priority from a string.
2766 The string is normally the headline. If this is nil Org computes the
2767 priority from the priority cookie like [#A] in the headline. It returns
2768 an integer, increasing by 1000 for each priority level.
2769 The user can set a different function here, which should take a string
2770 as an argument and return the numeric priority."
2771 :group 'org-priorities
2772 :version "24.1"
2773 :type 'function)
2775 (defgroup org-time nil
2776 "Options concerning time stamps and deadlines in Org-mode."
2777 :tag "Org Time"
2778 :group 'org)
2780 (defcustom org-insert-labeled-timestamps-at-point nil
2781 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2782 When nil, these labeled time stamps are forces into the second line of an
2783 entry, just after the headline. When scheduling from the global TODO list,
2784 the time stamp will always be forced into the second line."
2785 :group 'org-time
2786 :type 'boolean)
2788 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2789 "Formats for `format-time-string' which are used for time stamps.
2790 It is not recommended to change this constant.")
2792 (defcustom org-time-stamp-rounding-minutes '(0 5)
2793 "Number of minutes to round time stamps to.
2794 These are two values, the first applies when first creating a time stamp.
2795 The second applies when changing it with the commands `S-up' and `S-down'.
2796 When changing the time stamp, this means that it will change in steps
2797 of N minutes, as given by the second value.
2799 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2800 numbers should be factors of 60, so for example 5, 10, 15.
2802 When this is larger than 1, you can still force an exact time stamp by using
2803 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2804 and by using a prefix arg to `S-up/down' to specify the exact number
2805 of minutes to shift."
2806 :group 'org-time
2807 :get #'(lambda (var) ; Make sure both elements are there
2808 (if (integerp (default-value var))
2809 (list (default-value var) 5)
2810 (default-value var)))
2811 :type '(list
2812 (integer :tag "when inserting times")
2813 (integer :tag "when modifying times")))
2815 ;; Normalize old customizations of this variable.
2816 (when (integerp org-time-stamp-rounding-minutes)
2817 (setq org-time-stamp-rounding-minutes
2818 (list org-time-stamp-rounding-minutes
2819 org-time-stamp-rounding-minutes)))
2821 (defcustom org-display-custom-times nil
2822 "Non-nil means overlay custom formats over all time stamps.
2823 The formats are defined through the variable `org-time-stamp-custom-formats'.
2824 To turn this on on a per-file basis, insert anywhere in the file:
2825 #+STARTUP: customtime"
2826 :group 'org-time
2827 :set 'set-default
2828 :type 'sexp)
2829 (make-variable-buffer-local 'org-display-custom-times)
2831 (defcustom org-time-stamp-custom-formats
2832 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2833 "Custom formats for time stamps. See `format-time-string' for the syntax.
2834 These are overlaid over the default ISO format if the variable
2835 `org-display-custom-times' is set. Time like %H:%M should be at the
2836 end of the second format. The custom formats are also honored by export
2837 commands, if custom time display is turned on at the time of export."
2838 :group 'org-time
2839 :type 'sexp)
2841 (defun org-time-stamp-format (&optional long inactive)
2842 "Get the right format for a time string."
2843 (let ((f (if long (cdr org-time-stamp-formats)
2844 (car org-time-stamp-formats))))
2845 (if inactive
2846 (concat "[" (substring f 1 -1) "]")
2847 f)))
2849 (defcustom org-time-clocksum-format
2850 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2851 "The format string used when creating CLOCKSUM lines.
2852 This is also used when Org mode generates a time duration.
2854 The value can be a single format string containing two
2855 %-sequences, which will be filled with the number of hours and
2856 minutes in that order.
2858 Alternatively, the value can be a plist associating any of the
2859 keys :years, :months, :weeks, :days, :hours or :minutes with
2860 format strings. The time duration is formatted using only the
2861 time components that are needed and concatenating the results.
2862 If a time unit in absent, it falls back to the next smallest
2863 unit.
2865 The keys :require-years, :require-months, :require-days,
2866 :require-weeks, :require-hours, :require-minutes are also
2867 meaningful. A non-nil value for these keys indicates that the
2868 corresponding time component should always be included, even if
2869 its value is 0.
2872 For example,
2874 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2875 :require-minutes t)
2877 means durations longer than a day will be expressed in days,
2878 hours and minutes, and durations less than a day will always be
2879 expressed in hours and minutes (even for durations less than an
2880 hour).
2882 The value
2884 \(:days \"%dd\" :minutes \"%dm\")
2886 means durations longer than a day will be expressed in days and
2887 minutes, and durations less than a day will be expressed entirely
2888 in minutes (even for durations longer than an hour)."
2889 :group 'org-time
2890 :group 'org-clock
2891 :version "24.4"
2892 :package-version '(Org . "8.0")
2893 :type '(choice (string :tag "Format string")
2894 (set :tag "Plist"
2895 (group :inline t (const :tag "Years" :years)
2896 (string :tag "Format string"))
2897 (group :inline t
2898 (const :tag "Always show years" :require-years)
2899 (const t))
2900 (group :inline t (const :tag "Months" :months)
2901 (string :tag "Format string"))
2902 (group :inline t
2903 (const :tag "Always show months" :require-months)
2904 (const t))
2905 (group :inline t (const :tag "Weeks" :weeks)
2906 (string :tag "Format string"))
2907 (group :inline t
2908 (const :tag "Always show weeks" :require-weeks)
2909 (const t))
2910 (group :inline t (const :tag "Days" :days)
2911 (string :tag "Format string"))
2912 (group :inline t
2913 (const :tag "Always show days" :require-days)
2914 (const t))
2915 (group :inline t (const :tag "Hours" :hours)
2916 (string :tag "Format string"))
2917 (group :inline t
2918 (const :tag "Always show hours" :require-hours)
2919 (const t))
2920 (group :inline t (const :tag "Minutes" :minutes)
2921 (string :tag "Format string"))
2922 (group :inline t
2923 (const :tag "Always show minutes" :require-minutes)
2924 (const t)))))
2926 (defcustom org-time-clocksum-use-fractional nil
2927 "When non-nil, \\[org-clock-display] uses fractional times.
2928 See `org-time-clocksum-format' for more on time clock formats."
2929 :group 'org-time
2930 :group 'org-clock
2931 :version "24.3"
2932 :type 'boolean)
2934 (defcustom org-time-clocksum-use-effort-durations nil
2935 "When non-nil, \\[org-clock-display] uses effort durations.
2936 E.g. by default, one day is considered to be a 8 hours effort,
2937 so a task that has been clocked for 16 hours will be displayed
2938 as during 2 days in the clock display or in the clocktable.
2940 See `org-effort-durations' on how to set effort durations
2941 and `org-time-clocksum-format' for more on time clock formats."
2942 :group 'org-time
2943 :group 'org-clock
2944 :version "24.4"
2945 :package-version '(Org . "8.0")
2946 :type 'boolean)
2948 (defcustom org-time-clocksum-fractional-format "%.2f"
2949 "The format string used when creating CLOCKSUM lines,
2950 or when Org mode generates a time duration, if
2951 `org-time-clocksum-use-fractional' is enabled.
2953 The value can be a single format string containing one
2954 %-sequence, which will be filled with the number of hours as
2955 a float.
2957 Alternatively, the value can be a plist associating any of the
2958 keys :years, :months, :weeks, :days, :hours or :minutes with
2959 a format string. The time duration is formatted using the
2960 largest time unit which gives a non-zero integer part. If all
2961 specified formats have zero integer part, the smallest time unit
2962 is used."
2963 :group 'org-time
2964 :type '(choice (string :tag "Format string")
2965 (set (group :inline t (const :tag "Years" :years)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Months" :months)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Weeks" :weeks)
2970 (string :tag "Format string"))
2971 (group :inline t (const :tag "Days" :days)
2972 (string :tag "Format string"))
2973 (group :inline t (const :tag "Hours" :hours)
2974 (string :tag "Format string"))
2975 (group :inline t (const :tag "Minutes" :minutes)
2976 (string :tag "Format string")))))
2978 (defcustom org-deadline-warning-days 14
2979 "Number of days before expiration during which a deadline becomes active.
2980 This variable governs the display in sparse trees and in the agenda.
2981 When 0 or negative, it means use this number (the absolute value of it)
2982 even if a deadline has a different individual lead time specified.
2984 Custom commands can set this variable in the options section."
2985 :group 'org-time
2986 :group 'org-agenda-daily/weekly
2987 :type 'integer)
2989 (defcustom org-scheduled-delay-days 0
2990 "Number of days before a scheduled item becomes active.
2991 This variable governs the display in sparse trees and in the agenda.
2992 The default value (i.e. 0) means: don't delay scheduled item.
2993 When negative, it means use this number (the absolute value of it)
2994 even if a scheduled item has a different individual delay time
2995 specified.
2997 Custom commands can set this variable in the options section."
2998 :group 'org-time
2999 :group 'org-agenda-daily/weekly
3000 :version "24.4"
3001 :package-version '(Org . "8.0")
3002 :type 'integer)
3004 (defcustom org-read-date-prefer-future t
3005 "Non-nil means assume future for incomplete date input from user.
3006 This affects the following situations:
3007 1. The user gives a month but not a year.
3008 For example, if it is April and you enter \"feb 2\", this will be read
3009 as Feb 2, *next* year. \"May 5\", however, will be this year.
3010 2. The user gives a day, but no month.
3011 For example, if today is the 15th, and you enter \"3\", Org-mode will
3012 read this as the third of *next* month. However, if you enter \"17\",
3013 it will be considered as *this* month.
3015 If you set this variable to the symbol `time', then also the following
3016 will work:
3018 3. If the user gives a time.
3019 If the time is before now, it will be interpreted as tomorrow.
3021 Currently none of this works for ISO week specifications.
3023 When this option is nil, the current day, month and year will always be
3024 used as defaults.
3026 See also `org-agenda-jump-prefer-future'."
3027 :group 'org-time
3028 :type '(choice
3029 (const :tag "Never" nil)
3030 (const :tag "Check month and day" t)
3031 (const :tag "Check month, day, and time" time)))
3033 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3034 "Should the agenda jump command prefer the future for incomplete dates?
3035 The default is to do the same as configured in `org-read-date-prefer-future'.
3036 But you can also set a deviating value here.
3037 This may t or nil, or the symbol `org-read-date-prefer-future'."
3038 :group 'org-agenda
3039 :group 'org-time
3040 :version "24.1"
3041 :type '(choice
3042 (const :tag "Use org-read-date-prefer-future"
3043 org-read-date-prefer-future)
3044 (const :tag "Never" nil)
3045 (const :tag "Always" t)))
3047 (defcustom org-read-date-force-compatible-dates t
3048 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3050 Depending on the system Emacs is running on, certain dates cannot
3051 be represented with the type used internally to represent time.
3052 Dates between 1970-1-1 and 2038-1-1 can always be represented
3053 correctly. Some systems allow for earlier dates, some for later,
3054 some for both. One way to find out it to insert any date into an
3055 Org buffer, putting the cursor on the year and hitting S-up and
3056 S-down to test the range.
3058 When this variable is set to t, the date/time prompt will not let
3059 you specify dates outside the 1970-2037 range, so it is certain that
3060 these dates will work in whatever version of Emacs you are
3061 running, and also that you can move a file from one Emacs implementation
3062 to another. WHenever Org is forcing the year for you, it will display
3063 a message and beep.
3065 When this variable is nil, Org will check if the date is
3066 representable in the specific Emacs implementation you are using.
3067 If not, it will force a year, usually the current year, and beep
3068 to remind you. Currently this setting is not recommended because
3069 the likelihood that you will open your Org files in an Emacs that
3070 has limited date range is not negligible.
3072 A workaround for this problem is to use diary sexp dates for time
3073 stamps outside of this range."
3074 :group 'org-time
3075 :version "24.1"
3076 :type 'boolean)
3078 (defcustom org-read-date-display-live t
3079 "Non-nil means display current interpretation of date prompt live.
3080 This display will be in an overlay, in the minibuffer."
3081 :group 'org-time
3082 :type 'boolean)
3084 (defcustom org-read-date-popup-calendar t
3085 "Non-nil means pop up a calendar when prompting for a date.
3086 In the calendar, the date can be selected with mouse-1. However, the
3087 minibuffer will also be active, and you can simply enter the date as well.
3088 When nil, only the minibuffer will be available."
3089 :group 'org-time
3090 :type 'boolean)
3091 (if (fboundp 'defvaralias)
3092 (defvaralias 'org-popup-calendar-for-date-prompt
3093 'org-read-date-popup-calendar))
3095 (make-obsolete-variable
3096 'org-read-date-minibuffer-setup-hook
3097 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3098 (defcustom org-read-date-minibuffer-setup-hook nil
3099 "Hook to be used to set up keys for the date/time interface.
3100 Add key definitions to `minibuffer-local-map', which will be a
3101 temporary copy.
3103 WARNING: This option is obsolete, you should use
3104 `org-read-date-minibuffer-local-map' to set up keys."
3105 :group 'org-time
3106 :type 'hook)
3108 (defcustom org-extend-today-until 0
3109 "The hour when your day really ends. Must be an integer.
3110 This has influence for the following applications:
3111 - When switching the agenda to \"today\". It it is still earlier than
3112 the time given here, the day recognized as TODAY is actually yesterday.
3113 - When a date is read from the user and it is still before the time given
3114 here, the current date and time will be assumed to be yesterday, 23:59.
3115 Also, timestamps inserted in capture templates follow this rule.
3117 IMPORTANT: This is a feature whose implementation is and likely will
3118 remain incomplete. Really, it is only here because past midnight seems to
3119 be the favorite working time of John Wiegley :-)"
3120 :group 'org-time
3121 :type 'integer)
3123 (defcustom org-use-effective-time nil
3124 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3125 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3126 \"effective time\" of any timestamps between midnight and 8am will be
3127 23:59 of the previous day."
3128 :group 'org-time
3129 :version "24.1"
3130 :type 'boolean)
3132 (defcustom org-use-last-clock-out-time-as-effective-time nil
3133 "When non-nil, use the last clock out time for `org-todo'.
3134 Note that this option has precedence over the combined use of
3135 `org-use-effective-time' and `org-extend-today-until'."
3136 :group 'org-time
3137 :version "24.4"
3138 :package-version '(Org . "8.0")
3139 :type 'boolean)
3141 (defcustom org-edit-timestamp-down-means-later nil
3142 "Non-nil means S-down will increase the time in a time stamp.
3143 When nil, S-up will increase."
3144 :group 'org-time
3145 :type 'boolean)
3147 (defcustom org-calendar-follow-timestamp-change t
3148 "Non-nil means make the calendar window follow timestamp changes.
3149 When a timestamp is modified and the calendar window is visible, it will be
3150 moved to the new date."
3151 :group 'org-time
3152 :type 'boolean)
3154 (defgroup org-tags nil
3155 "Options concerning tags in Org-mode."
3156 :tag "Org Tags"
3157 :group 'org)
3159 (defcustom org-tag-alist nil
3160 "List of tags allowed in Org-mode files.
3161 When this list is nil, Org-mode will base TAG input on what is already in the
3162 buffer.
3163 The value of this variable is an alist, the car of each entry must be a
3164 keyword as a string, the cdr may be a character that is used to select
3165 that tag through the fast-tag-selection interface.
3166 See the manual for details."
3167 :group 'org-tags
3168 :type '(repeat
3169 (choice
3170 (cons (string :tag "Tag name")
3171 (character :tag "Access char"))
3172 (list :tag "Start radio group"
3173 (const :startgroup)
3174 (option (string :tag "Group description")))
3175 (list :tag "End radio group"
3176 (const :endgroup)
3177 (option (string :tag "Group description")))
3178 (const :tag "New line" (:newline)))))
3180 (defcustom org-tag-persistent-alist nil
3181 "List of tags that will always appear in all Org-mode files.
3182 This is in addition to any in buffer settings or customizations
3183 of `org-tag-alist'.
3184 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3185 The value of this variable is an alist, the car of each entry must be a
3186 keyword as a string, the cdr may be a character that is used to select
3187 that tag through the fast-tag-selection interface.
3188 See the manual for details.
3189 To disable these tags on a per-file basis, insert anywhere in the file:
3190 #+STARTUP: noptag"
3191 :group 'org-tags
3192 :type '(repeat
3193 (choice
3194 (cons (string :tag "Tag name")
3195 (character :tag "Access char"))
3196 (const :tag "Start radio group" (:startgroup))
3197 (const :tag "End radio group" (:endgroup))
3198 (const :tag "New line" (:newline)))))
3200 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3201 "If non-nil, always offer completion for all tags of all agenda files.
3202 Instead of customizing this variable directly, you might want to
3203 set it locally for capture buffers, because there no list of
3204 tags in that file can be created dynamically (there are none).
3206 (add-hook 'org-capture-mode-hook
3207 (lambda ()
3208 (set (make-local-variable
3209 'org-complete-tags-always-offer-all-agenda-tags)
3210 t)))"
3211 :group 'org-tags
3212 :version "24.1"
3213 :type 'boolean)
3215 (defvar org-file-tags nil
3216 "List of tags that can be inherited by all entries in the file.
3217 The tags will be inherited if the variable `org-use-tag-inheritance'
3218 says they should be.
3219 This variable is populated from #+FILETAGS lines.")
3221 (defcustom org-use-fast-tag-selection 'auto
3222 "Non-nil means use fast tag selection scheme.
3223 This is a special interface to select and deselect tags with single keys.
3224 When nil, fast selection is never used.
3225 When the symbol `auto', fast selection is used if and only if selection
3226 characters for tags have been configured, either through the variable
3227 `org-tag-alist' or through a #+TAGS line in the buffer.
3228 When t, fast selection is always used and selection keys are assigned
3229 automatically if necessary."
3230 :group 'org-tags
3231 :type '(choice
3232 (const :tag "Always" t)
3233 (const :tag "Never" nil)
3234 (const :tag "When selection characters are configured" 'auto)))
3236 (defcustom org-fast-tag-selection-single-key nil
3237 "Non-nil means fast tag selection exits after first change.
3238 When nil, you have to press RET to exit it.
3239 During fast tag selection, you can toggle this flag with `C-c'.
3240 This variable can also have the value `expert'. In this case, the window
3241 displaying the tags menu is not even shown, until you press C-c again."
3242 :group 'org-tags
3243 :type '(choice
3244 (const :tag "No" nil)
3245 (const :tag "Yes" t)
3246 (const :tag "Expert" expert)))
3248 (defvar org-fast-tag-selection-include-todo nil
3249 "Non-nil means fast tags selection interface will also offer TODO states.
3250 This is an undocumented feature, you should not rely on it.")
3252 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3253 "The column to which tags should be indented in a headline.
3254 If this number is positive, it specifies the column. If it is negative,
3255 it means that the tags should be flushright to that column. For example,
3256 -80 works well for a normal 80 character screen.
3257 When 0, place tags directly after headline text, with only one space in
3258 between."
3259 :group 'org-tags
3260 :type 'integer)
3262 (defcustom org-auto-align-tags t
3263 "Non-nil keeps tags aligned when modifying headlines.
3264 Some operations (i.e. demoting) change the length of a headline and
3265 therefore shift the tags around. With this option turned on, after
3266 each such operation the tags are again aligned to `org-tags-column'."
3267 :group 'org-tags
3268 :type 'boolean)
3270 (defcustom org-use-tag-inheritance t
3271 "Non-nil means tags in levels apply also for sublevels.
3272 When nil, only the tags directly given in a specific line apply there.
3273 This may also be a list of tags that should be inherited, or a regexp that
3274 matches tags that should be inherited. Additional control is possible
3275 with the variable `org-tags-exclude-from-inheritance' which gives an
3276 explicit list of tags to be excluded from inheritance, even if the value of
3277 `org-use-tag-inheritance' would select it for inheritance.
3279 If this option is t, a match early-on in a tree can lead to a large
3280 number of matches in the subtree when constructing the agenda or creating
3281 a sparse tree. If you only want to see the first match in a tree during
3282 a search, check out the variable `org-tags-match-list-sublevels'."
3283 :group 'org-tags
3284 :type '(choice
3285 (const :tag "Not" nil)
3286 (const :tag "Always" t)
3287 (repeat :tag "Specific tags" (string :tag "Tag"))
3288 (regexp :tag "Tags matched by regexp")))
3290 (defcustom org-tags-exclude-from-inheritance nil
3291 "List of tags that should never be inherited.
3292 This is a way to exclude a few tags from inheritance. For way to do
3293 the opposite, to actively allow inheritance for selected tags,
3294 see the variable `org-use-tag-inheritance'."
3295 :group 'org-tags
3296 :type '(repeat (string :tag "Tag")))
3298 (defun org-tag-inherit-p (tag)
3299 "Check if TAG is one that should be inherited."
3300 (cond
3301 ((member tag org-tags-exclude-from-inheritance) nil)
3302 ((eq org-use-tag-inheritance t) t)
3303 ((not org-use-tag-inheritance) nil)
3304 ((stringp org-use-tag-inheritance)
3305 (string-match org-use-tag-inheritance tag))
3306 ((listp org-use-tag-inheritance)
3307 (member tag org-use-tag-inheritance))
3308 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3310 (defcustom org-tags-match-list-sublevels t
3311 "Non-nil means list also sublevels of headlines matching a search.
3312 This variable applies to tags/property searches, and also to stuck
3313 projects because this search is based on a tags match as well.
3315 When set to the symbol `indented', sublevels are indented with
3316 leading dots.
3318 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3319 the sublevels of a headline matching a tag search often also match
3320 the same search. Listing all of them can create very long lists.
3321 Setting this variable to nil causes subtrees of a match to be skipped.
3323 This variable is semi-obsolete and probably should always be true. It
3324 is better to limit inheritance to certain tags using the variables
3325 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3326 :group 'org-tags
3327 :type '(choice
3328 (const :tag "No, don't list them" nil)
3329 (const :tag "Yes, do list them" t)
3330 (const :tag "List them, indented with leading dots" indented)))
3332 (defcustom org-tags-sort-function nil
3333 "When set, tags are sorted using this function as a comparator."
3334 :group 'org-tags
3335 :type '(choice
3336 (const :tag "No sorting" nil)
3337 (const :tag "Alphabetical" string<)
3338 (const :tag "Reverse alphabetical" string>)
3339 (function :tag "Custom function" nil)))
3341 (defvar org-tags-history nil
3342 "History of minibuffer reads for tags.")
3343 (defvar org-last-tags-completion-table nil
3344 "The last used completion table for tags.")
3345 (defvar org-after-tags-change-hook nil
3346 "Hook that is run after the tags in a line have changed.")
3348 (defgroup org-properties nil
3349 "Options concerning properties in Org-mode."
3350 :tag "Org Properties"
3351 :group 'org)
3353 (defcustom org-property-format "%-10s %s"
3354 "How property key/value pairs should be formatted by `indent-line'.
3355 When `indent-line' hits a property definition, it will format the line
3356 according to this format, mainly to make sure that the values are
3357 lined-up with respect to each other."
3358 :group 'org-properties
3359 :type 'string)
3361 (defcustom org-properties-postprocess-alist nil
3362 "Alist of properties and functions to adjust inserted values.
3363 Elements of this alist must be of the form
3365 ([string] [function])
3367 where [string] must be a property name and [function] must be a
3368 lambda expression: this lambda expression must take one argument,
3369 the value to adjust, and return the new value as a string.
3371 For example, this element will allow the property \"Remaining\"
3372 to be updated wrt the relation between the \"Effort\" property
3373 and the clock summary:
3375 ((\"Remaining\" (lambda(value)
3376 (let ((clocksum (org-clock-sum-current-item))
3377 (effort (org-duration-string-to-minutes
3378 (org-entry-get (point) \"Effort\"))))
3379 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3380 :group 'org-properties
3381 :version "24.1"
3382 :type '(alist :key-type (string :tag "Property")
3383 :value-type (function :tag "Function")))
3385 (defcustom org-use-property-inheritance nil
3386 "Non-nil means properties apply also for sublevels.
3388 This setting is chiefly used during property searches. Turning it on can
3389 cause significant overhead when doing a search, which is why it is not
3390 on by default.
3392 When nil, only the properties directly given in the current entry count.
3393 When t, every property is inherited. The value may also be a list of
3394 properties that should have inheritance, or a regular expression matching
3395 properties that should be inherited.
3397 However, note that some special properties use inheritance under special
3398 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3399 and the properties ending in \"_ALL\" when they are used as descriptor
3400 for valid values of a property.
3402 Note for programmers:
3403 When querying an entry with `org-entry-get', you can control if inheritance
3404 should be used. By default, `org-entry-get' looks only at the local
3405 properties. You can request inheritance by setting the inherit argument
3406 to t (to force inheritance) or to `selective' (to respect the setting
3407 in this variable)."
3408 :group 'org-properties
3409 :type '(choice
3410 (const :tag "Not" nil)
3411 (const :tag "Always" t)
3412 (repeat :tag "Specific properties" (string :tag "Property"))
3413 (regexp :tag "Properties matched by regexp")))
3415 (defun org-property-inherit-p (property)
3416 "Check if PROPERTY is one that should be inherited."
3417 (cond
3418 ((eq org-use-property-inheritance t) t)
3419 ((not org-use-property-inheritance) nil)
3420 ((stringp org-use-property-inheritance)
3421 (string-match org-use-property-inheritance property))
3422 ((listp org-use-property-inheritance)
3423 (member property org-use-property-inheritance))
3424 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3426 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3427 "The default column format, if no other format has been defined.
3428 This variable can be set on the per-file basis by inserting a line
3430 #+COLUMNS: %25ITEM ....."
3431 :group 'org-properties
3432 :type 'string)
3434 (defcustom org-columns-ellipses ".."
3435 "The ellipses to be used when a field in column view is truncated.
3436 When this is the empty string, as many characters as possible are shown,
3437 but then there will be no visual indication that the field has been truncated.
3438 When this is a string of length N, the last N characters of a truncated
3439 field are replaced by this string. If the column is narrower than the
3440 ellipses string, only part of the ellipses string will be shown."
3441 :group 'org-properties
3442 :type 'string)
3444 (defcustom org-columns-modify-value-for-display-function nil
3445 "Function that modifies values for display in column view.
3446 For example, it can be used to cut out a certain part from a time stamp.
3447 The function must take 2 arguments:
3449 column-title The title of the column (*not* the property name)
3450 value The value that should be modified.
3452 The function should return the value that should be displayed,
3453 or nil if the normal value should be used."
3454 :group 'org-properties
3455 :type 'function)
3457 (defcustom org-effort-property "Effort"
3458 "The property that is being used to keep track of effort estimates.
3459 Effort estimates given in this property need to have the format H:MM."
3460 :group 'org-properties
3461 :group 'org-progress
3462 :type '(string :tag "Property"))
3464 (defconst org-global-properties-fixed
3465 '(("VISIBILITY_ALL" . "folded children content all")
3466 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3467 "List of property/value pairs that can be inherited by any entry.
3469 These are fixed values, for the preset properties. The user variable
3470 that can be used to add to this list is `org-global-properties'.
3472 The entries in this list are cons cells where the car is a property
3473 name and cdr is a string with the value. If the value represents
3474 multiple items like an \"_ALL\" property, separate the items by
3475 spaces.")
3477 (defcustom org-global-properties nil
3478 "List of property/value pairs that can be inherited by any entry.
3480 This list will be combined with the constant `org-global-properties-fixed'.
3482 The entries in this list are cons cells where the car is a property
3483 name and cdr is a string with the value.
3485 You can set buffer-local values for the same purpose in the variable
3486 `org-file-properties' this by adding lines like
3488 #+PROPERTY: NAME VALUE"
3489 :group 'org-properties
3490 :type '(repeat
3491 (cons (string :tag "Property")
3492 (string :tag "Value"))))
3494 (defvar org-file-properties nil
3495 "List of property/value pairs that can be inherited by any entry.
3496 Valid for the current buffer.
3497 This variable is populated from #+PROPERTY lines.")
3498 (make-variable-buffer-local 'org-file-properties)
3500 (defgroup org-agenda nil
3501 "Options concerning agenda views in Org-mode."
3502 :tag "Org Agenda"
3503 :group 'org)
3505 (defvar org-category nil
3506 "Variable used by org files to set a category for agenda display.
3507 Such files should use a file variable to set it, for example
3509 # -*- mode: org; org-category: \"ELisp\"
3511 or contain a special line
3513 #+CATEGORY: ELisp
3515 If the file does not specify a category, then file's base name
3516 is used instead.")
3517 (make-variable-buffer-local 'org-category)
3518 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3520 (defcustom org-agenda-files nil
3521 "The files to be used for agenda display.
3522 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3523 \\[org-remove-file]. You can also use customize to edit the list.
3525 If an entry is a directory, all files in that directory that are matched by
3526 `org-agenda-file-regexp' will be part of the file list.
3528 If the value of the variable is not a list but a single file name, then
3529 the list of agenda files is actually stored and maintained in that file, one
3530 agenda file per line. In this file paths can be given relative to
3531 `org-directory'. Tilde expansion and environment variable substitution
3532 are also made."
3533 :group 'org-agenda
3534 :type '(choice
3535 (repeat :tag "List of files and directories" file)
3536 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3538 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3539 "Regular expression to match files for `org-agenda-files'.
3540 If any element in the list in that variable contains a directory instead
3541 of a normal file, all files in that directory that are matched by this
3542 regular expression will be included."
3543 :group 'org-agenda
3544 :type 'regexp)
3546 (defcustom org-agenda-text-search-extra-files nil
3547 "List of extra files to be searched by text search commands.
3548 These files will be search in addition to the agenda files by the
3549 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3550 Note that these files will only be searched for text search commands,
3551 not for the other agenda views like todo lists, tag searches or the weekly
3552 agenda. This variable is intended to list notes and possibly archive files
3553 that should also be searched by these two commands.
3554 In fact, if the first element in the list is the symbol `agenda-archives',
3555 than all archive files of all agenda files will be added to the search
3556 scope."
3557 :group 'org-agenda
3558 :type '(set :greedy t
3559 (const :tag "Agenda Archives" agenda-archives)
3560 (repeat :inline t (file))))
3562 (if (fboundp 'defvaralias)
3563 (defvaralias 'org-agenda-multi-occur-extra-files
3564 'org-agenda-text-search-extra-files))
3566 (defcustom org-agenda-skip-unavailable-files nil
3567 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3568 A nil value means to remove them, after a query, from the list."
3569 :group 'org-agenda
3570 :type 'boolean)
3572 (defcustom org-calendar-to-agenda-key [?c]
3573 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3574 The command `org-calendar-goto-agenda' will be bound to this key. The
3575 default is the character `c' because then `c' can be used to switch back and
3576 forth between agenda and calendar."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-calendar-insert-diary-entry-key [?i]
3581 "The key to be installed in `calendar-mode-map' for adding diary entries.
3582 This option is irrelevant until `org-agenda-diary-file' has been configured
3583 to point to an Org-mode file. When that is the case, the command
3584 `org-agenda-diary-entry' will be bound to the key given here, by default
3585 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3586 if you want to continue doing this, you need to change this to a different
3587 key."
3588 :group 'org-agenda
3589 :type 'sexp)
3591 (defcustom org-agenda-diary-file 'diary-file
3592 "File to which to add new entries with the `i' key in agenda and calendar.
3593 When this is the symbol `diary-file', the functionality in the Emacs
3594 calendar will be used to add entries to the `diary-file'. But when this
3595 points to a file, `org-agenda-diary-entry' will be used instead."
3596 :group 'org-agenda
3597 :type '(choice
3598 (const :tag "The standard Emacs diary file" diary-file)
3599 (file :tag "Special Org file diary entries")))
3601 (eval-after-load "calendar"
3602 '(progn
3603 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3604 'org-calendar-goto-agenda)
3605 (add-hook 'calendar-mode-hook
3606 (lambda ()
3607 (unless (eq org-agenda-diary-file 'diary-file)
3608 (define-key calendar-mode-map
3609 org-calendar-insert-diary-entry-key
3610 'org-agenda-diary-entry))))))
3612 (defgroup org-latex nil
3613 "Options for embedding LaTeX code into Org-mode."
3614 :tag "Org LaTeX"
3615 :group 'org)
3617 (defcustom org-format-latex-options
3618 '(:foreground default :background default :scale 1.0
3619 :html-foreground "Black" :html-background "Transparent"
3620 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3621 "Options for creating images from LaTeX fragments.
3622 This is a property list with the following properties:
3623 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3624 `default' means use the foreground of the default face.
3625 `auto' means use the foreground from the text face.
3626 :background the background color, or \"Transparent\".
3627 `default' means use the background of the default face.
3628 `auto' means use the background from the text face.
3629 :scale a scaling factor for the size of the images, to get more pixels
3630 :html-foreground, :html-background, :html-scale
3631 the same numbers for HTML export.
3632 :matchers a list indicating which matchers should be used to
3633 find LaTeX fragments. Valid members of this list are:
3634 \"begin\" find environments
3635 \"$1\" find single characters surrounded by $.$
3636 \"$\" find math expressions surrounded by $...$
3637 \"$$\" find math expressions surrounded by $$....$$
3638 \"\\(\" find math expressions surrounded by \\(...\\)
3639 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3640 :group 'org-latex
3641 :type 'plist)
3643 (defcustom org-format-latex-signal-error t
3644 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3645 When nil, just push out a message."
3646 :group 'org-latex
3647 :version "24.1"
3648 :type 'boolean)
3650 (defcustom org-latex-to-mathml-jar-file nil
3651 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3652 Use this to specify additional executable file say a jar file.
3654 When using MathToWeb as the converter, specify the full-path to
3655 your mathtoweb.jar file."
3656 :group 'org-latex
3657 :version "24.1"
3658 :type '(choice
3659 (const :tag "None" nil)
3660 (file :tag "JAR file" :must-match t)))
3662 (defcustom org-latex-to-mathml-convert-command nil
3663 "Command to convert LaTeX fragments to MathML.
3664 Replace format-specifiers in the command as noted below and use
3665 `shell-command' to convert LaTeX to MathML.
3666 %j: Executable file in fully expanded form as specified by
3667 `org-latex-to-mathml-jar-file'.
3668 %I: Input LaTeX file in fully expanded form
3669 %o: Output MathML file
3670 This command is used by `org-create-math-formula'.
3672 When using MathToWeb as the converter, set this to
3673 \"java -jar %j -unicode -force -df %o %I\"."
3674 :group 'org-latex
3675 :version "24.1"
3676 :type '(choice
3677 (const :tag "None" nil)
3678 (string :tag "\nShell command")))
3680 (defcustom org-latex-create-formula-image-program 'dvipng
3681 "Program to convert LaTeX fragments with.
3683 dvipng Process the LaTeX fragments to dvi file, then convert
3684 dvi files to png files using dvipng.
3685 This will also include processing of non-math environments.
3686 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3687 to convert pdf files to png files"
3688 :group 'org-latex
3689 :version "24.1"
3690 :type '(choice
3691 (const :tag "dvipng" dvipng)
3692 (const :tag "imagemagick" imagemagick)))
3694 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3695 "Path to store latex preview images.
3696 A relative path here creates many directories relative to the
3697 processed org files paths. An absolute path puts all preview
3698 images at the same place."
3699 :group 'org-latex
3700 :version "24.3"
3701 :type 'string)
3703 (defun org-format-latex-mathml-available-p ()
3704 "Return t if `org-latex-to-mathml-convert-command' is usable."
3705 (save-match-data
3706 (when (and (boundp 'org-latex-to-mathml-convert-command)
3707 org-latex-to-mathml-convert-command)
3708 (let ((executable (car (split-string
3709 org-latex-to-mathml-convert-command))))
3710 (when (executable-find executable)
3711 (if (string-match
3712 "%j" org-latex-to-mathml-convert-command)
3713 (file-readable-p org-latex-to-mathml-jar-file)
3714 t))))))
3716 (defcustom org-format-latex-header "\\documentclass{article}
3717 \\usepackage[usenames]{color}
3718 \\usepackage{amsmath}
3719 \\usepackage[mathscr]{eucal}
3720 \\pagestyle{empty} % do not remove
3721 \[PACKAGES]
3722 \[DEFAULT-PACKAGES]
3723 % The settings below are copied from fullpage.sty
3724 \\setlength{\\textwidth}{\\paperwidth}
3725 \\addtolength{\\textwidth}{-3cm}
3726 \\setlength{\\oddsidemargin}{1.5cm}
3727 \\addtolength{\\oddsidemargin}{-2.54cm}
3728 \\setlength{\\evensidemargin}{\\oddsidemargin}
3729 \\setlength{\\textheight}{\\paperheight}
3730 \\addtolength{\\textheight}{-\\headheight}
3731 \\addtolength{\\textheight}{-\\headsep}
3732 \\addtolength{\\textheight}{-\\footskip}
3733 \\addtolength{\\textheight}{-3cm}
3734 \\setlength{\\topmargin}{1.5cm}
3735 \\addtolength{\\topmargin}{-2.54cm}"
3736 "The document header used for processing LaTeX fragments.
3737 It is imperative that this header make sure that no page number
3738 appears on the page. The package defined in the variables
3739 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3740 will either replace the placeholder \"[PACKAGES]\" in this
3741 header, or they will be appended."
3742 :group 'org-latex
3743 :type 'string)
3745 (defun org-set-packages-alist (var val)
3746 "Set the packages alist and make sure it has 3 elements per entry."
3747 (set var (mapcar (lambda (x)
3748 (if (and (consp x) (= (length x) 2))
3749 (list (car x) (nth 1 x) t)
3751 val)))
3753 (defun org-get-packages-alist (var)
3754 "Get the packages alist and make sure it has 3 elements per entry."
3755 (mapcar (lambda (x)
3756 (if (and (consp x) (= (length x) 2))
3757 (list (car x) (nth 1 x) t)
3759 (default-value var)))
3761 (defcustom org-latex-default-packages-alist
3762 '(("AUTO" "inputenc" t)
3763 ("T1" "fontenc" t)
3764 ("" "fixltx2e" nil)
3765 ("" "graphicx" t)
3766 ("" "longtable" nil)
3767 ("" "float" nil)
3768 ("" "wrapfig" nil)
3769 ("" "soul" t)
3770 ("" "textcomp" t)
3771 ("" "marvosym" t)
3772 ("" "wasysym" t)
3773 ("" "latexsym" t)
3774 ("" "amssymb" t)
3775 ("" "hyperref" nil)
3776 "\\tolerance=1000")
3777 "Alist of default packages to be inserted in the header.
3779 Change this only if one of the packages here causes an
3780 incompatibility with another package you are using.
3782 The packages in this list are needed by one part or another of
3783 Org mode to function properly:
3785 - inputenc, fontenc: for basic font and character selection
3786 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3787 symbols used for interpreting the entities in `org-entities'.
3788 You can skip some of these packages if you don't use any of the
3789 symbols in it.
3790 - graphicx: for including images
3791 - float, wrapfig: for figure placement
3792 - longtable: for long tables
3793 - hyperref: for cross references
3795 Therefore you should not modify this variable unless you know
3796 what you are doing. The one reason to change it anyway is that
3797 you might be loading some other package that conflicts with one
3798 of the default packages. Each cell is of the format
3799 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3800 the package also needs to be included when compiling LaTeX
3801 snippets into images for inclusion into non-LaTeX output."
3802 :group 'org-latex
3803 :group 'org-export-latex
3804 :set 'org-set-packages-alist
3805 :get 'org-get-packages-alist
3806 :version "24.1"
3807 :type '(repeat
3808 (choice
3809 (list :tag "options/package pair"
3810 (string :tag "options")
3811 (string :tag "package")
3812 (boolean :tag "Snippet"))
3813 (string :tag "A line of LaTeX"))))
3815 (defcustom org-latex-packages-alist nil
3816 "Alist of packages to be inserted in every LaTeX header.
3818 These will be inserted after `org-latex-default-packages-alist'.
3819 Each cell is of the format:
3821 \(\"options\" \"package\" snippet-flag)
3823 SNIPPET-FLAG, when t, indicates that this package is also needed
3824 when turning LaTeX snippets into images for inclusion into
3825 non-LaTeX output.
3827 Make sure that you only list packages here which:
3829 - you want in every file
3830 - do not conflict with the setup in `org-format-latex-header'.
3831 - do not conflict with the default packages in
3832 `org-latex-default-packages-alist'."
3833 :group 'org-latex
3834 :group 'org-export-latex
3835 :set 'org-set-packages-alist
3836 :get 'org-get-packages-alist
3837 :type '(repeat
3838 (choice
3839 (list :tag "options/package pair"
3840 (string :tag "options")
3841 (string :tag "package")
3842 (boolean :tag "Snippet"))
3843 (string :tag "A line of LaTeX"))))
3845 (defgroup org-appearance nil
3846 "Settings for Org-mode appearance."
3847 :tag "Org Appearance"
3848 :group 'org)
3850 (defcustom org-level-color-stars-only nil
3851 "Non-nil means fontify only the stars in each headline.
3852 When nil, the entire headline is fontified.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified."
3855 :group 'org-appearance
3856 :type 'boolean)
3858 (defcustom org-hide-leading-stars nil
3859 "Non-nil means hide the first N-1 stars in a headline.
3860 This works by using the face `org-hide' for these stars. This
3861 face is white for a light background, and black for a dark
3862 background. You may have to customize the face `org-hide' to
3863 make this work.
3864 Changing it requires restart of `font-lock-mode' to become effective
3865 also in regions already fontified.
3866 You may also set this on a per-file basis by adding one of the following
3867 lines to the buffer:
3869 #+STARTUP: hidestars
3870 #+STARTUP: showstars"
3871 :group 'org-appearance
3872 :type 'boolean)
3874 (defcustom org-hidden-keywords nil
3875 "List of symbols corresponding to keywords to be hidden the org buffer.
3876 For example, a value '(title) for this list will make the document's title
3877 appear in the buffer without the initial #+TITLE: keyword."
3878 :group 'org-appearance
3879 :version "24.1"
3880 :type '(set (const :tag "#+AUTHOR" author)
3881 (const :tag "#+DATE" date)
3882 (const :tag "#+EMAIL" email)
3883 (const :tag "#+TITLE" title)))
3885 (defcustom org-custom-properties nil
3886 "List of properties (as strings) with a special meaning.
3887 The default use of these custom properties is to let the user
3888 hide them with `org-toggle-custom-properties-visibility'."
3889 :group 'org-properties
3890 :group 'org-appearance
3891 :version "24.3"
3892 :type '(repeat (string :tag "Property Name")))
3894 (defcustom org-fontify-done-headline nil
3895 "Non-nil means change the face of a headline if it is marked DONE.
3896 Normally, only the TODO/DONE keyword indicates the state of a headline.
3897 When this is non-nil, the headline after the keyword is set to the
3898 `org-headline-done' as an additional indication."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-emphasized-text t
3903 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3904 Changing this variable requires a restart of Emacs to take effect."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-fontify-whole-heading-line nil
3909 "Non-nil means fontify the whole line for headings.
3910 This is useful when setting a background color for the
3911 org-level-* faces."
3912 :group 'org-appearance
3913 :type 'boolean)
3915 (defcustom org-highlight-latex-and-related nil
3916 "Non-nil means highlight LaTeX related syntax in the buffer.
3917 When non nil, the value should be a list containing any of the
3918 following symbols:
3919 `latex' Highlight LaTeX snippets and environments.
3920 `script' Highlight subscript and superscript.
3921 `entities' Highlight entities."
3922 :group 'org-appearance
3923 :version "24.4"
3924 :package-version '(Org . "8.0")
3925 :type '(choice
3926 (const :tag "No highlighting" nil)
3927 (set :greedy t :tag "Highlight"
3928 (const :tag "LaTeX snippets and environments" latex)
3929 (const :tag "Subscript and superscript" script)
3930 (const :tag "Entities" entities))))
3932 (defcustom org-hide-emphasis-markers nil
3933 "Non-nil mean font-lock should hide the emphasis marker characters."
3934 :group 'org-appearance
3935 :type 'boolean)
3937 (defcustom org-pretty-entities nil
3938 "Non-nil means show entities as UTF8 characters.
3939 When nil, the \\name form remains in the buffer."
3940 :group 'org-appearance
3941 :version "24.1"
3942 :type 'boolean)
3944 (defcustom org-pretty-entities-include-sub-superscripts t
3945 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3946 :group 'org-appearance
3947 :version "24.1"
3948 :type 'boolean)
3950 (defvar org-emph-re nil
3951 "Regular expression for matching emphasis.
3952 After a match, the match groups contain these elements:
3953 0 The match of the full regular expression, including the characters
3954 before and after the proper match
3955 1 The character before the proper match, or empty at beginning of line
3956 2 The proper match, including the leading and trailing markers
3957 3 The leading marker like * or /, indicating the type of highlighting
3958 4 The text between the emphasis markers, not including the markers
3959 5 The character after the match, empty at the end of a line")
3960 (defvar org-verbatim-re nil
3961 "Regular expression for matching verbatim text.")
3962 (defvar org-emphasis-regexp-components) ; defined just below
3963 (defvar org-emphasis-alist) ; defined just below
3964 (defun org-set-emph-re (var val)
3965 "Set variable and compute the emphasis regular expression."
3966 (set var val)
3967 (when (and (boundp 'org-emphasis-alist)
3968 (boundp 'org-emphasis-regexp-components)
3969 org-emphasis-alist org-emphasis-regexp-components)
3970 (let* ((e org-emphasis-regexp-components)
3971 (pre (car e))
3972 (post (nth 1 e))
3973 (border (nth 2 e))
3974 (body (nth 3 e))
3975 (nl (nth 4 e))
3976 (body1 (concat body "*?"))
3977 (markers (mapconcat 'car org-emphasis-alist ""))
3978 (vmarkers (mapconcat
3979 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3980 org-emphasis-alist "")))
3981 ;; make sure special characters appear at the right position in the class
3982 (if (string-match "\\^" markers)
3983 (setq markers (concat (replace-match "" t t markers) "^")))
3984 (if (string-match "-" markers)
3985 (setq markers (concat (replace-match "" t t markers) "-")))
3986 (if (string-match "\\^" vmarkers)
3987 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3988 (if (string-match "-" vmarkers)
3989 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3990 (if (> nl 0)
3991 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3992 (int-to-string nl) "\\}")))
3993 ;; Make the regexp
3994 (setq org-emph-re
3995 (concat "\\([" pre "]\\|^\\)"
3996 "\\("
3997 "\\([" markers "]\\)"
3998 "\\("
3999 "[^" border "]\\|"
4000 "[^" border "]"
4001 body1
4002 "[^" border "]"
4003 "\\)"
4004 "\\3\\)"
4005 "\\([" post "]\\|$\\)"))
4006 (setq org-verbatim-re
4007 (concat "\\([" pre "]\\|^\\)"
4008 "\\("
4009 "\\([" vmarkers "]\\)"
4010 "\\("
4011 "[^" border "]\\|"
4012 "[^" border "]"
4013 body1
4014 "[^" border "]"
4015 "\\)"
4016 "\\3\\)"
4017 "\\([" post "]\\|$\\)")))))
4019 (defcustom org-emphasis-regexp-components
4020 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4021 "Components used to build the regular expression for emphasis.
4022 This is a list with five entries. Terminology: In an emphasis string
4023 like \" *strong word* \", we call the initial space PREMATCH, the final
4024 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4025 and \"trong wor\" is the body. The different components in this variable
4026 specify what is allowed/forbidden in each part:
4028 pre Chars allowed as prematch. Beginning of line will be allowed too.
4029 post Chars allowed as postmatch. End of line will be allowed too.
4030 border The chars *forbidden* as border characters.
4031 body-regexp A regexp like \".\" to match a body character. Don't use
4032 non-shy groups here, and don't allow newline here.
4033 newline The maximum number of newlines allowed in an emphasis exp.
4035 Use customize to modify this, or restart Emacs after changing it."
4036 :group 'org-appearance
4037 :set 'org-set-emph-re
4038 :type '(list
4039 (sexp :tag "Allowed chars in pre ")
4040 (sexp :tag "Allowed chars in post ")
4041 (sexp :tag "Forbidden chars in border ")
4042 (sexp :tag "Regexp for body ")
4043 (integer :tag "number of newlines allowed")
4044 (option (boolean :tag "Please ignore this button"))))
4046 (defcustom org-emphasis-alist
4047 `(("*" bold "<b>" "</b>")
4048 ("/" italic "<i>" "</i>")
4049 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4050 ("=" org-code "<code>" "</code>" verbatim)
4051 ("~" org-verbatim "<code>" "</code>" verbatim)
4052 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4053 "<del>" "</del>")
4055 "Special syntax for emphasized text.
4056 Text starting and ending with a special character will be emphasized, for
4057 example *bold*, _underlined_ and /italic/. This variable sets the marker
4058 characters, the face to be used by font-lock for highlighting in Org-mode
4059 Emacs buffers, and the HTML tags to be used for this.
4060 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4061 Use customize to modify this, or restart Emacs after changing it."
4062 :group 'org-appearance
4063 :set 'org-set-emph-re
4064 :type '(repeat
4065 (list
4066 (string :tag "Marker character")
4067 (choice
4068 (face :tag "Font-lock-face")
4069 (plist :tag "Face property list"))
4070 (string :tag "HTML start tag")
4071 (string :tag "HTML end tag")
4072 (option (const verbatim)))))
4074 (defvar org-protecting-blocks
4075 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4076 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4077 This is needed for font-lock setup.")
4079 ;;; Miscellaneous options
4081 (defgroup org-completion nil
4082 "Completion in Org-mode."
4083 :tag "Org Completion"
4084 :group 'org)
4086 (defcustom org-completion-use-ido nil
4087 "Non-nil means use ido completion wherever possible.
4088 Note that `ido-mode' must be active for this variable to be relevant.
4089 If you decide to turn this variable on, you might well want to turn off
4090 `org-outline-path-complete-in-steps'.
4091 See also `org-completion-use-iswitchb'."
4092 :group 'org-completion
4093 :type 'boolean)
4095 (defcustom org-completion-use-iswitchb nil
4096 "Non-nil means use iswitchb completion wherever possible.
4097 Note that `iswitchb-mode' must be active for this variable to be relevant.
4098 If you decide to turn this variable on, you might well want to turn off
4099 `org-outline-path-complete-in-steps'.
4100 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4101 :group 'org-completion
4102 :type 'boolean)
4104 (defcustom org-completion-fallback-command 'hippie-expand
4105 "The expansion command called by \\[pcomplete] in normal context.
4106 Normal means, no org-mode-specific context."
4107 :group 'org-completion
4108 :type 'function)
4110 ;;; Functions and variables from their packages
4111 ;; Declared here to avoid compiler warnings
4113 ;; XEmacs only
4114 (defvar outline-mode-menu-heading)
4115 (defvar outline-mode-menu-show)
4116 (defvar outline-mode-menu-hide)
4117 (defvar zmacs-regions) ; XEmacs regions
4119 ;; Emacs only
4120 (defvar mark-active)
4122 ;; Various packages
4123 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4124 (declare-function calendar-forward-day "cal-move" (arg))
4125 (declare-function calendar-goto-date "cal-move" (date))
4126 (declare-function calendar-goto-today "cal-move" ())
4127 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4128 (defvar calc-embedded-close-formula)
4129 (defvar calc-embedded-open-formula)
4130 (declare-function cdlatex-tab "ext:cdlatex" ())
4131 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4132 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4133 (defvar font-lock-unfontify-region-function)
4134 (declare-function iswitchb-read-buffer "iswitchb"
4135 (prompt &optional default require-match start matches-set))
4136 (defvar iswitchb-temp-buflist)
4137 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4138 (defvar org-agenda-tags-todo-honor-ignore-options)
4139 (declare-function org-agenda-skip "org-agenda" ())
4140 (declare-function
4141 org-agenda-format-item "org-agenda"
4142 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4143 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4144 (declare-function org-agenda-change-all-lines "org-agenda"
4145 (newhead hdmarker &optional fixface just-this))
4146 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4147 (declare-function org-agenda-maybe-redo "org-agenda" ())
4148 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4149 (beg end))
4150 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4151 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4152 "org-agenda" (&optional end))
4153 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4154 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4155 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4156 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4157 (declare-function org-indent-mode "org-indent" (&optional arg))
4158 (declare-function parse-time-string "parse-time" (string))
4159 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4160 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4161 (defvar remember-data-file)
4162 (defvar texmathp-why)
4163 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4164 (declare-function table--at-cell-p "table" (position &optional object at-column))
4166 (defvar org-latex-regexps)
4168 ;;; Autoload and prepare some org modules
4170 ;; Some table stuff that needs to be defined here, because it is used
4171 ;; by the functions setting up org-mode or checking for table context.
4173 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4174 "Detect an org-type or table-type table.")
4175 (defconst org-table-line-regexp "^[ \t]*|"
4176 "Detect an org-type table line.")
4177 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4178 "Detect an org-type table line.")
4179 (defconst org-table-hline-regexp "^[ \t]*|-"
4180 "Detect an org-type table hline.")
4181 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4182 "Detect a table-type table hline.")
4183 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4184 "Detect the first line outside a table when searching from within it.
4185 This works for both table types.")
4187 ;; Autoload the functions in org-table.el that are needed by functions here.
4189 (eval-and-compile
4190 (org-autoload "org-table"
4191 '(org-table-begin org-table-blank-field org-table-end)))
4193 ;;;###autoload
4194 (defun turn-on-orgtbl ()
4195 "Unconditionally turn on `orgtbl-mode'."
4196 (require 'org-table)
4197 (orgtbl-mode 1))
4199 (defun org-at-table-p (&optional table-type)
4200 "Return t if the cursor is inside an org-type table.
4201 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4202 (if org-enable-table-editor
4203 (save-excursion
4204 (beginning-of-line 1)
4205 (looking-at (if table-type org-table-any-line-regexp
4206 org-table-line-regexp)))
4207 nil))
4208 (defsubst org-table-p () (org-at-table-p))
4210 (defun org-at-table.el-p ()
4211 "Return t if and only if we are at a table.el table."
4212 (and (org-at-table-p 'any)
4213 (save-excursion
4214 (goto-char (org-table-begin 'any))
4215 (looking-at org-table1-hline-regexp))))
4217 (defun org-table-recognize-table.el ()
4218 "If there is a table.el table nearby, recognize it and move into it."
4219 (if org-table-tab-recognizes-table.el
4220 (if (org-at-table.el-p)
4221 (progn
4222 (beginning-of-line 1)
4223 (if (looking-at org-table-dataline-regexp)
4225 (if (looking-at org-table1-hline-regexp)
4226 (progn
4227 (beginning-of-line 2)
4228 (if (looking-at org-table-any-border-regexp)
4229 (beginning-of-line -1)))))
4230 (if (re-search-forward "|" (org-table-end t) t)
4231 (progn
4232 (require 'table)
4233 (if (table--at-cell-p (point))
4235 (message "recognizing table.el table...")
4236 (table-recognize-table)
4237 (message "recognizing table.el table...done")))
4238 (error "This should not happen"))
4240 nil)
4241 nil))
4243 (defun org-at-table-hline-p ()
4244 "Return t if the cursor is inside a hline in a table."
4245 (if org-enable-table-editor
4246 (save-excursion
4247 (beginning-of-line 1)
4248 (looking-at org-table-hline-regexp))
4249 nil))
4251 (defvar org-table-clean-did-remove-column nil)
4252 (defun org-table-map-tables (function &optional quietly)
4253 "Apply FUNCTION to the start of all tables in the buffer."
4254 (save-excursion
4255 (save-restriction
4256 (widen)
4257 (goto-char (point-min))
4258 (while (re-search-forward org-table-any-line-regexp nil t)
4259 (unless quietly
4260 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4261 (beginning-of-line 1)
4262 (when (and (looking-at org-table-line-regexp)
4263 ;; Exclude tables in src/example/verbatim/clocktable blocks
4264 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4265 (save-excursion (funcall function))
4266 (or (looking-at org-table-line-regexp)
4267 (forward-char 1)))
4268 (re-search-forward org-table-any-border-regexp nil 1))))
4269 (unless quietly (message "Mapping tables: done")))
4271 ;; Declare and autoload functions from ox.el and al.
4273 (declare-function org-export-get-environment "ox"
4274 (&optional backend subtreep ext-plist))
4275 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4277 ;; Declare and autoload functions from org-agenda.el
4279 (eval-and-compile
4280 (org-autoload "org-agenda"
4281 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4283 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4284 (declare-function org-clock-update-mode-line "org-clock" ())
4285 (declare-function org-resolve-clocks "org-clock"
4286 (&optional also-non-dangling-p prompt last-valid))
4287 (defvar org-clock-start-time)
4288 (defvar org-clock-marker (make-marker)
4289 "Marker recording the last clock-in.")
4290 (defvar org-clock-hd-marker (make-marker)
4291 "Marker recording the last clock-in, but the headline position.")
4292 (defvar org-clock-heading ""
4293 "The heading of the current clock entry.")
4294 (defun org-clock-is-active ()
4295 "Return non-nil if clock is currently running.
4296 The return value is actually the clock marker."
4297 (marker-buffer org-clock-marker))
4299 (eval-and-compile
4300 (org-autoload "org-clock" '(org-clock-remove-overlays
4301 org-clock-update-time-maybe
4302 org-clocktable-shift)))
4304 (defun org-check-running-clock ()
4305 "Check if the current buffer contains the running clock.
4306 If yes, offer to stop it and to save the buffer with the changes."
4307 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4308 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4309 (buffer-name))))
4310 (org-clock-out)
4311 (when (y-or-n-p "Save changed buffer?")
4312 (save-buffer))))
4314 (defun org-clocktable-try-shift (dir n)
4315 "Check if this line starts a clock table, if yes, shift the time block."
4316 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4317 (org-clocktable-shift dir n)))
4319 ;;;###autoload
4320 (defun org-clock-persistence-insinuate ()
4321 "Set up hooks for clock persistence."
4322 (require 'org-clock)
4323 (add-hook 'org-mode-hook 'org-clock-load)
4324 (add-hook 'kill-emacs-hook 'org-clock-save))
4326 ;; Define the variable already here, to make sure we have it.
4327 (defvar org-indent-mode nil
4328 "Non-nil if Org-Indent mode is enabled.
4329 Use the command `org-indent-mode' to change this variable.")
4331 ;; Autoload archiving code
4332 ;; The stuff that is needed for cycling and tags has to be defined here.
4334 (defgroup org-archive nil
4335 "Options concerning archiving in Org-mode."
4336 :tag "Org Archive"
4337 :group 'org-structure)
4339 (defcustom org-archive-location "%s_archive::"
4340 "The location where subtrees should be archived.
4342 The value of this variable is a string, consisting of two parts,
4343 separated by a double-colon. The first part is a filename and
4344 the second part is a headline.
4346 When the filename is omitted, archiving happens in the same file.
4347 %s in the filename will be replaced by the current file
4348 name (without the directory part). Archiving to a different file
4349 is useful to keep archived entries from contributing to the
4350 Org-mode Agenda.
4352 The archived entries will be filed as subtrees of the specified
4353 headline. When the headline is omitted, the subtrees are simply
4354 filed away at the end of the file, as top-level entries. Also in
4355 the heading you can use %s to represent the file name, this can be
4356 useful when using the same archive for a number of different files.
4358 Here are a few examples:
4359 \"%s_archive::\"
4360 If the current file is Projects.org, archive in file
4361 Projects.org_archive, as top-level trees. This is the default.
4363 \"::* Archived Tasks\"
4364 Archive in the current file, under the top-level headline
4365 \"* Archived Tasks\".
4367 \"~/org/archive.org::\"
4368 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4370 \"~/org/archive.org::* From %s\"
4371 Archive in file ~/org/archive.org (absolute path), under headlines
4372 \"From FILENAME\" where file name is the current file name.
4374 \"~/org/datetree.org::datetree/* Finished Tasks\"
4375 The \"datetree/\" string is special, signifying to archive
4376 items to the datetree. Items are placed in either the CLOSED
4377 date of the item, or the current date if there is no CLOSED date.
4378 The heading will be a subentry to the current date. There doesn't
4379 need to be a heading, but there always needs to be a slash after
4380 datetree. For example, to store archived items directly in the
4381 datetree, use \"~/org/datetree.org::datetree/\".
4383 \"basement::** Finished Tasks\"
4384 Archive in file ./basement (relative path), as level 3 trees
4385 below the level 2 heading \"** Finished Tasks\".
4387 You may set this option on a per-file basis by adding to the buffer a
4388 line like
4390 #+ARCHIVE: basement::** Finished Tasks
4392 You may also define it locally for a subtree by setting an ARCHIVE property
4393 in the entry. If such a property is found in an entry, or anywhere up
4394 the hierarchy, it will be used."
4395 :group 'org-archive
4396 :type 'string)
4398 (defcustom org-archive-tag "ARCHIVE"
4399 "The tag that marks a subtree as archived.
4400 An archived subtree does not open during visibility cycling, and does
4401 not contribute to the agenda listings.
4402 After changing this, font-lock must be restarted in the relevant buffers to
4403 get the proper fontification."
4404 :group 'org-archive
4405 :group 'org-keywords
4406 :type 'string)
4408 (defcustom org-agenda-skip-archived-trees t
4409 "Non-nil means the agenda will skip any items located in archived trees.
4410 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4411 variable is no longer recommended, you should leave it at the value t.
4412 Instead, use the key `v' to cycle the archives-mode in the agenda."
4413 :group 'org-archive
4414 :group 'org-agenda-skip
4415 :type 'boolean)
4417 (defcustom org-columns-skip-archived-trees t
4418 "Non-nil means ignore archived trees when creating column view."
4419 :group 'org-archive
4420 :group 'org-properties
4421 :type 'boolean)
4423 (defcustom org-cycle-open-archived-trees nil
4424 "Non-nil means `org-cycle' will open archived trees.
4425 An archived tree is a tree marked with the tag ARCHIVE.
4426 When nil, archived trees will stay folded. You can still open them with
4427 normal outline commands like `show-all', but not with the cycling commands."
4428 :group 'org-archive
4429 :group 'org-cycle
4430 :type 'boolean)
4432 (defcustom org-sparse-tree-open-archived-trees nil
4433 "Non-nil means sparse tree construction shows matches in archived trees.
4434 When nil, matches in these trees are highlighted, but the trees are kept in
4435 collapsed state."
4436 :group 'org-archive
4437 :group 'org-sparse-trees
4438 :type 'boolean)
4440 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4441 "The default date type when building a sparse tree.
4442 When this is nil, a date is a scheduled or a deadline timestamp.
4443 Otherwise, these types are allowed:
4445 all: all timestamps
4446 active: only active timestamps (<...>)
4447 inactive: only inactive timestamps (<...)
4448 scheduled: only scheduled timestamps
4449 deadline: only deadline timestamps"
4450 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4451 (const :tag "All timestamps" all)
4452 (const :tag "Only active timestamps" active)
4453 (const :tag "Only inactive timestamps" inactive)
4454 (const :tag "Only scheduled timestamps" scheduled)
4455 (const :tag "Only deadline timestamps" deadline))
4456 :version "24.3"
4457 :group 'org-sparse-trees)
4459 (defun org-cycle-hide-archived-subtrees (state)
4460 "Re-hide all archived subtrees after a visibility state change."
4461 (when (and (not org-cycle-open-archived-trees)
4462 (not (memq state '(overview folded))))
4463 (save-excursion
4464 (let* ((globalp (memq state '(contents all)))
4465 (beg (if globalp (point-min) (point)))
4466 (end (if globalp (point-max) (org-end-of-subtree t))))
4467 (org-hide-archived-subtrees beg end)
4468 (goto-char beg)
4469 (if (looking-at (concat ".*:" org-archive-tag ":"))
4470 (message "%s" (substitute-command-keys
4471 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4473 (defun org-force-cycle-archived ()
4474 "Cycle subtree even if it is archived."
4475 (interactive)
4476 (setq this-command 'org-cycle)
4477 (let ((org-cycle-open-archived-trees t))
4478 (call-interactively 'org-cycle)))
4480 (defun org-hide-archived-subtrees (beg end)
4481 "Re-hide all archived subtrees after a visibility state change."
4482 (save-excursion
4483 (let* ((re (concat ":" org-archive-tag ":")))
4484 (goto-char beg)
4485 (while (re-search-forward re end t)
4486 (when (org-at-heading-p)
4487 (org-flag-subtree t)
4488 (org-end-of-subtree t))))))
4490 (declare-function outline-end-of-heading "outline" ())
4491 (declare-function outline-flag-region "outline" (from to flag))
4492 (defun org-flag-subtree (flag)
4493 (save-excursion
4494 (org-back-to-heading t)
4495 (outline-end-of-heading)
4496 (outline-flag-region (point)
4497 (progn (org-end-of-subtree t) (point))
4498 flag)))
4500 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4502 (eval-and-compile
4503 (org-autoload "org-archive"
4504 '(org-add-archive-files)))
4506 ;; Autoload Column View Code
4508 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4509 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4510 (declare-function org-columns-compute "org-colview" (property))
4512 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4513 '(org-columns-number-to-string
4514 org-columns-get-format-and-top-level
4515 org-columns-compute
4516 org-columns-remove-overlays))
4518 ;; Autoload ID code
4520 (declare-function org-id-store-link "org-id")
4521 (declare-function org-id-locations-load "org-id")
4522 (declare-function org-id-locations-save "org-id")
4523 (defvar org-id-track-globally)
4524 (org-autoload "org-id"
4525 '(org-id-new
4526 org-id-copy
4527 org-id-get-with-outline-path-completion
4528 org-id-get-with-outline-drilling))
4530 ;;; Variables for pre-computed regular expressions, all buffer local
4532 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4533 "Matches first line of a hidden block.")
4534 (make-variable-buffer-local 'org-drawer-regexp)
4535 (defvar org-todo-regexp nil
4536 "Matches any of the TODO state keywords.")
4537 (make-variable-buffer-local 'org-todo-regexp)
4538 (defvar org-not-done-regexp nil
4539 "Matches any of the TODO state keywords except the last one.")
4540 (make-variable-buffer-local 'org-not-done-regexp)
4541 (defvar org-not-done-heading-regexp nil
4542 "Matches a TODO headline that is not done.")
4543 (make-variable-buffer-local 'org-not-done-regexp)
4544 (defvar org-todo-line-regexp nil
4545 "Matches a headline and puts TODO state into group 2 if present.")
4546 (make-variable-buffer-local 'org-todo-line-regexp)
4547 (defvar org-complex-heading-regexp nil
4548 "Matches a headline and puts everything into groups:
4549 group 1: the stars
4550 group 2: The todo keyword, maybe
4551 group 3: Priority cookie
4552 group 4: True headline
4553 group 5: Tags")
4554 (make-variable-buffer-local 'org-complex-heading-regexp)
4555 (defvar org-complex-heading-regexp-format nil
4556 "Printf format to make regexp to match an exact headline.
4557 This regexp will match the headline of any node which has the
4558 exact headline text that is put into the format, but may have any
4559 TODO state, priority and tags.")
4560 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4561 (defvar org-todo-line-tags-regexp nil
4562 "Matches a headline and puts TODO state into group 2 if present.
4563 Also put tags into group 4 if tags are present.")
4564 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4565 (defvar org-ds-keyword-length 12
4566 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4567 (make-variable-buffer-local 'org-ds-keyword-length)
4568 (defvar org-deadline-regexp nil
4569 "Matches the DEADLINE keyword.")
4570 (make-variable-buffer-local 'org-deadline-regexp)
4571 (defvar org-deadline-time-regexp nil
4572 "Matches the DEADLINE keyword together with a time stamp.")
4573 (make-variable-buffer-local 'org-deadline-time-regexp)
4574 (defvar org-deadline-line-regexp nil
4575 "Matches the DEADLINE keyword and the rest of the line.")
4576 (make-variable-buffer-local 'org-deadline-line-regexp)
4577 (defvar org-scheduled-regexp nil
4578 "Matches the SCHEDULED keyword.")
4579 (make-variable-buffer-local 'org-scheduled-regexp)
4580 (defvar org-scheduled-time-regexp nil
4581 "Matches the SCHEDULED keyword together with a time stamp.")
4582 (make-variable-buffer-local 'org-scheduled-time-regexp)
4583 (defvar org-closed-time-regexp nil
4584 "Matches the CLOSED keyword together with a time stamp.")
4585 (make-variable-buffer-local 'org-closed-time-regexp)
4587 (defvar org-keyword-time-regexp nil
4588 "Matches any of the 4 keywords, together with the time stamp.")
4589 (make-variable-buffer-local 'org-keyword-time-regexp)
4590 (defvar org-keyword-time-not-clock-regexp nil
4591 "Matches any of the 3 keywords, together with the time stamp.")
4592 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4593 (defvar org-maybe-keyword-time-regexp nil
4594 "Matches a timestamp, possibly preceded by a keyword.")
4595 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4596 (defvar org-all-time-keywords nil
4597 "List of time keywords.")
4598 (make-variable-buffer-local 'org-all-time-keywords)
4600 (defconst org-plain-time-of-day-regexp
4601 (concat
4602 "\\(\\<[012]?[0-9]"
4603 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4604 "\\(--?"
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\)?")
4608 "Regular expression to match a plain time or time range.
4609 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4610 groups carry important information:
4611 0 the full match
4612 1 the first time, range or not
4613 8 the second time, if it is a range.")
4615 (defconst org-plain-time-extension-regexp
4616 (concat
4617 "\\(\\<[012]?[0-9]"
4618 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4619 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4620 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4621 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4622 groups carry important information:
4623 0 the full match
4624 7 hours of duration
4625 9 minutes of duration")
4627 (defconst org-stamp-time-of-day-regexp
4628 (concat
4629 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4630 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4631 "\\(--?"
4632 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4633 "Regular expression to match a timestamp time or time range.
4634 After a match, the following groups carry important information:
4635 0 the full match
4636 1 date plus weekday, for back referencing to make sure both times are on the same day
4637 2 the first time, range or not
4638 4 the second time, if it is a range.")
4640 (defconst org-startup-options
4641 '(("fold" org-startup-folded t)
4642 ("overview" org-startup-folded t)
4643 ("nofold" org-startup-folded nil)
4644 ("showall" org-startup-folded nil)
4645 ("showeverything" org-startup-folded showeverything)
4646 ("content" org-startup-folded content)
4647 ("indent" org-startup-indented t)
4648 ("noindent" org-startup-indented nil)
4649 ("hidestars" org-hide-leading-stars t)
4650 ("showstars" org-hide-leading-stars nil)
4651 ("odd" org-odd-levels-only t)
4652 ("oddeven" org-odd-levels-only nil)
4653 ("align" org-startup-align-all-tables t)
4654 ("noalign" org-startup-align-all-tables nil)
4655 ("inlineimages" org-startup-with-inline-images t)
4656 ("noinlineimages" org-startup-with-inline-images nil)
4657 ("latexpreview" org-startup-with-latex-preview t)
4658 ("nolatexpreview" org-startup-with-latex-preview nil)
4659 ("customtime" org-display-custom-times t)
4660 ("logdone" org-log-done time)
4661 ("lognotedone" org-log-done note)
4662 ("nologdone" org-log-done nil)
4663 ("lognoteclock-out" org-log-note-clock-out t)
4664 ("nolognoteclock-out" org-log-note-clock-out nil)
4665 ("logrepeat" org-log-repeat state)
4666 ("lognoterepeat" org-log-repeat note)
4667 ("logdrawer" org-log-into-drawer t)
4668 ("nologdrawer" org-log-into-drawer nil)
4669 ("logstatesreversed" org-log-states-order-reversed t)
4670 ("nologstatesreversed" org-log-states-order-reversed nil)
4671 ("nologrepeat" org-log-repeat nil)
4672 ("logreschedule" org-log-reschedule time)
4673 ("lognotereschedule" org-log-reschedule note)
4674 ("nologreschedule" org-log-reschedule nil)
4675 ("logredeadline" org-log-redeadline time)
4676 ("lognoteredeadline" org-log-redeadline note)
4677 ("nologredeadline" org-log-redeadline nil)
4678 ("logrefile" org-log-refile time)
4679 ("lognoterefile" org-log-refile note)
4680 ("nologrefile" org-log-refile nil)
4681 ("fninline" org-footnote-define-inline t)
4682 ("nofninline" org-footnote-define-inline nil)
4683 ("fnlocal" org-footnote-section nil)
4684 ("fnauto" org-footnote-auto-label t)
4685 ("fnprompt" org-footnote-auto-label nil)
4686 ("fnconfirm" org-footnote-auto-label confirm)
4687 ("fnplain" org-footnote-auto-label plain)
4688 ("fnadjust" org-footnote-auto-adjust t)
4689 ("nofnadjust" org-footnote-auto-adjust nil)
4690 ("constcgs" constants-unit-system cgs)
4691 ("constSI" constants-unit-system SI)
4692 ("noptag" org-tag-persistent-alist nil)
4693 ("hideblocks" org-hide-block-startup t)
4694 ("nohideblocks" org-hide-block-startup nil)
4695 ("beamer" org-startup-with-beamer-mode t)
4696 ("entitiespretty" org-pretty-entities t)
4697 ("entitiesplain" org-pretty-entities nil))
4698 "Variable associated with STARTUP options for org-mode.
4699 Each element is a list of three items: the startup options (as written
4700 in the #+STARTUP line), the corresponding variable, and the value to set
4701 this variable to if the option is found. An optional forth element PUSH
4702 means to push this value onto the list in the variable.")
4704 (defun org-update-property-plist (key val props)
4705 "Update PROPS with KEY and VAL."
4706 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4707 (key (if appending (substring key 0 (- (length key) 1)) key))
4708 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4709 (previous (cdr (assoc key props))))
4710 (if appending
4711 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4712 (cons (cons key val) remainder))))
4714 (defconst org-block-regexp
4715 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4716 "Regular expression for hiding blocks.")
4717 (defconst org-heading-keyword-regexp-format
4718 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4719 "Printf format for a regexp matching a headline with some keyword.
4720 This regexp will match the headline of any node which has the
4721 exact keyword that is put into the format. The keyword isn't in
4722 any group by default, but the stars and the body are.")
4723 (defconst org-heading-keyword-maybe-regexp-format
4724 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4725 "Printf format for a regexp matching a headline, possibly with some keyword.
4726 This regexp can match any headline with the specified keyword, or
4727 without a keyword. The keyword isn't in any group by default,
4728 but the stars and the body are.")
4730 (defun org-set-regexps-and-options ()
4731 "Precompute regular expressions for current buffer."
4732 (when (derived-mode-p 'org-mode)
4733 (org-set-local 'org-todo-kwd-alist nil)
4734 (org-set-local 'org-todo-key-alist nil)
4735 (org-set-local 'org-todo-key-trigger nil)
4736 (org-set-local 'org-todo-keywords-1 nil)
4737 (org-set-local 'org-done-keywords nil)
4738 (org-set-local 'org-todo-heads nil)
4739 (org-set-local 'org-todo-sets nil)
4740 (org-set-local 'org-todo-log-states nil)
4741 (org-set-local 'org-file-properties nil)
4742 (org-set-local 'org-file-tags nil)
4743 (let ((re (org-make-options-regexp
4744 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4745 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4746 "SETUPFILE" "OPTIONS")
4747 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4748 (splitre "[ \t]+")
4749 (scripts org-use-sub-superscripts)
4750 kwds kws0 kwsa key log value cat arch tags const links hw dws
4751 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4752 (start 0))
4753 (save-excursion
4754 (save-restriction
4755 (widen)
4756 (goto-char (point-min))
4757 (while (or (and ext-setup-or-nil
4758 (string-match re ext-setup-or-nil start)
4759 (setq start (match-end 0)))
4760 (and (setq ext-setup-or-nil nil start 0)
4761 (re-search-forward re nil t)))
4762 (setq key (upcase (match-string 1 ext-setup-or-nil))
4763 value (org-match-string-no-properties 2 ext-setup-or-nil))
4764 (if (stringp value) (setq value (org-trim value)))
4765 (cond
4766 ((equal key "CATEGORY")
4767 (setq cat value))
4768 ((member key '("SEQ_TODO" "TODO"))
4769 (push (cons 'sequence (org-split-string value splitre)) kwds))
4770 ((equal key "TYP_TODO")
4771 (push (cons 'type (org-split-string value splitre)) kwds))
4772 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4773 ;; general TODO-like setup
4774 (push (cons (intern (downcase (match-string 1 key)))
4775 (org-split-string value splitre)) kwds))
4776 ((equal key "TAGS")
4777 (setq tags (append tags (if tags '("\\n") nil)
4778 (org-split-string value splitre))))
4779 ((equal key "COLUMNS")
4780 (org-set-local 'org-columns-default-format value))
4781 ((equal key "LINK")
4782 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4783 (push (cons (match-string 1 value)
4784 (org-trim (match-string 2 value)))
4785 links)))
4786 ((equal key "PRIORITIES")
4787 (setq prio (org-split-string value " +")))
4788 ((equal key "PROPERTY")
4789 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4790 (setq props (org-update-property-plist (match-string 1 value)
4791 (match-string 2 value)
4792 props))))
4793 ((equal key "FILETAGS")
4794 (when (string-match "\\S-" value)
4795 (setq ftags
4796 (append
4797 ftags
4798 (apply 'append
4799 (mapcar (lambda (x) (org-split-string x ":"))
4800 (org-split-string value)))))))
4801 ((equal key "DRAWERS")
4802 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4803 ((equal key "CONSTANTS")
4804 (setq const (append const (org-split-string value splitre))))
4805 ((equal key "STARTUP")
4806 (let ((opts (org-split-string value splitre))
4807 l var val)
4808 (while (setq l (pop opts))
4809 (when (setq l (assoc l org-startup-options))
4810 (setq var (nth 1 l) val (nth 2 l))
4811 (if (not (nth 3 l))
4812 (set (make-local-variable var) val)
4813 (if (not (listp (symbol-value var)))
4814 (set (make-local-variable var) nil))
4815 (set (make-local-variable var) (symbol-value var))
4816 (add-to-list var val))))))
4817 ((equal key "ARCHIVE")
4818 (setq arch value)
4819 (remove-text-properties 0 (length arch)
4820 '(face t fontified t) arch))
4821 ((equal key "OPTIONS")
4822 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4823 (setq scripts (read (match-string 2 value)))))
4824 ((equal key "SETUPFILE")
4825 (setq setup-contents (org-file-contents
4826 (expand-file-name
4827 (org-remove-double-quotes value))
4828 'noerror))
4829 (if (not ext-setup-or-nil)
4830 (setq ext-setup-or-nil setup-contents start 0)
4831 (setq ext-setup-or-nil
4832 (concat (substring ext-setup-or-nil 0 start)
4833 "\n" setup-contents "\n"
4834 (substring ext-setup-or-nil start)))))))
4835 ;; search for property blocks
4836 (goto-char (point-min))
4837 (while (re-search-forward org-block-regexp nil t)
4838 (when (equal "PROPERTY" (upcase (match-string 1)))
4839 (setq value (replace-regexp-in-string
4840 "[\n\r]" " " (match-string 4)))
4841 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4842 (setq props (org-update-property-plist (match-string 1 value)
4843 (match-string 2 value)
4844 props)))))))
4845 (org-set-local 'org-use-sub-superscripts scripts)
4846 (when cat
4847 (org-set-local 'org-category (intern cat))
4848 (push (cons "CATEGORY" cat) props))
4849 (when prio
4850 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4851 (setq prio (mapcar 'string-to-char prio))
4852 (org-set-local 'org-highest-priority (nth 0 prio))
4853 (org-set-local 'org-lowest-priority (nth 1 prio))
4854 (org-set-local 'org-default-priority (nth 2 prio)))
4855 (and props (org-set-local 'org-file-properties (nreverse props)))
4856 (and ftags (org-set-local 'org-file-tags
4857 (mapcar 'org-add-prop-inherited ftags)))
4858 (and drawers (org-set-local 'org-drawers drawers))
4859 (and arch (org-set-local 'org-archive-location arch))
4860 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4861 ;; Process the TODO keywords
4862 (unless kwds
4863 ;; Use the global values as if they had been given locally.
4864 (setq kwds (default-value 'org-todo-keywords))
4865 (if (stringp (car kwds))
4866 (setq kwds (list (cons org-todo-interpretation
4867 (default-value 'org-todo-keywords)))))
4868 (setq kwds (reverse kwds)))
4869 (setq kwds (nreverse kwds))
4870 (let (inter kws kw)
4871 (while (setq kws (pop kwds))
4872 (let ((kws (or
4873 (run-hook-with-args-until-success
4874 'org-todo-setup-filter-hook kws)
4875 kws)))
4876 (setq inter (pop kws) sep (member "|" kws)
4877 kws0 (delete "|" (copy-sequence kws))
4878 kwsa nil
4879 kws1 (mapcar
4880 (lambda (x)
4881 ;; 1 2
4882 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4883 (progn
4884 (setq kw (match-string 1 x)
4885 key (and (match-end 2) (match-string 2 x))
4886 log (org-extract-log-state-settings x))
4887 (push (cons kw (and key (string-to-char key))) kwsa)
4888 (and log (push log org-todo-log-states))
4890 (error "Invalid TODO keyword %s" x)))
4891 kws0)
4892 kwsa (if kwsa (append '((:startgroup))
4893 (nreverse kwsa)
4894 '((:endgroup))))
4895 hw (car kws1)
4896 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4897 tail (list inter hw (car dws) (org-last dws))))
4898 (add-to-list 'org-todo-heads hw 'append)
4899 (push kws1 org-todo-sets)
4900 (setq org-done-keywords (append org-done-keywords dws nil))
4901 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4902 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4903 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4904 (setq org-todo-sets (nreverse org-todo-sets)
4905 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4906 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4907 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4908 ;; Process the constants
4909 (when const
4910 (let (e cst)
4911 (while (setq e (pop const))
4912 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4913 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4914 (setq org-table-formula-constants-local cst)))
4916 ;; Process the tags.
4917 (when tags
4918 (let (e tgs)
4919 (while (setq e (pop tags))
4920 (cond
4921 ((equal e "{") (push '(:startgroup) tgs))
4922 ((equal e "}") (push '(:endgroup) tgs))
4923 ((equal e "\\n") (push '(:newline) tgs))
4924 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4925 (push (cons (match-string 1 e)
4926 (string-to-char (match-string 2 e)))
4927 tgs))
4928 (t (push (list e) tgs))))
4929 (org-set-local 'org-tag-alist nil)
4930 (while (setq e (pop tgs))
4931 (or (and (stringp (car e))
4932 (assoc (car e) org-tag-alist))
4933 (push e org-tag-alist)))))
4935 ;; Compute the regular expressions and other local variables.
4936 ;; Using `org-outline-regexp-bol' would complicate them much,
4937 ;; because of the fixed white space at the end of that string.
4938 (if (not org-done-keywords)
4939 (setq org-done-keywords (and org-todo-keywords-1
4940 (list (org-last org-todo-keywords-1)))))
4941 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4942 (length org-scheduled-string)
4943 (length org-clock-string)
4944 (length org-closed-string)))
4945 org-drawer-regexp
4946 (concat "^[ \t]*:\\("
4947 (mapconcat 'regexp-quote org-drawers "\\|")
4948 "\\):[ \t]*$")
4949 org-not-done-keywords
4950 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4951 org-todo-regexp
4952 (concat "\\("
4953 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4954 "\\)")
4955 org-not-done-regexp
4956 (concat "\\("
4957 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4958 "\\)")
4959 org-not-done-heading-regexp
4960 (format org-heading-keyword-regexp-format org-not-done-regexp)
4961 org-todo-line-regexp
4962 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4963 org-complex-heading-regexp
4964 (concat "^\\(\\*+\\)"
4965 "\\(?: +" org-todo-regexp "\\)?"
4966 "\\(?: +\\(\\[#.\\]\\)\\)?"
4967 "\\(?: +\\(.*?\\)\\)??"
4968 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4969 "[ \t]*$")
4970 org-complex-heading-regexp-format
4971 (concat "^\\(\\*+\\)"
4972 "\\(?: +" org-todo-regexp "\\)?"
4973 "\\(?: +\\(\\[#.\\]\\)\\)?"
4974 "\\(?: +"
4975 ;; Stats cookies can be stuck to body.
4976 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4977 "\\(%s\\)"
4978 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4979 "\\)"
4980 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4981 "[ \t]*$")
4982 org-todo-line-tags-regexp
4983 (concat "^\\(\\*+\\)"
4984 "\\(?: +" org-todo-regexp "\\)?"
4985 "\\(?: +\\(.*?\\)\\)??"
4986 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4987 "[ \t]*$")
4988 org-deadline-regexp (concat "\\<" org-deadline-string)
4989 org-deadline-time-regexp
4990 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4991 org-deadline-line-regexp
4992 (concat "\\<\\(" org-deadline-string "\\).*")
4993 org-scheduled-regexp
4994 (concat "\\<" org-scheduled-string)
4995 org-scheduled-time-regexp
4996 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4997 org-closed-time-regexp
4998 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4999 org-keyword-time-regexp
5000 (concat "\\<\\(" org-scheduled-string
5001 "\\|" org-deadline-string
5002 "\\|" org-closed-string
5003 "\\|" org-clock-string "\\)"
5004 " *[[<]\\([^]>]+\\)[]>]")
5005 org-keyword-time-not-clock-regexp
5006 (concat "\\<\\(" org-scheduled-string
5007 "\\|" org-deadline-string
5008 "\\|" org-closed-string
5009 "\\)"
5010 " *[[<]\\([^]>]+\\)[]>]")
5011 org-maybe-keyword-time-regexp
5012 (concat "\\(\\<\\(" org-scheduled-string
5013 "\\|" org-deadline-string
5014 "\\|" org-closed-string
5015 "\\|" org-clock-string "\\)\\)?"
5016 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5017 org-all-time-keywords
5018 (mapcar (lambda (w) (substring w 0 -1))
5019 (list org-scheduled-string org-deadline-string
5020 org-clock-string org-closed-string)))
5021 (org-compute-latex-and-related-regexp)
5022 (org-set-font-lock-defaults))))
5024 (defun org-file-contents (file &optional noerror)
5025 "Return the contents of FILE, as a string."
5026 (if (or (not file)
5027 (not (file-readable-p file)))
5028 (if noerror
5029 (progn
5030 (message "Cannot read file \"%s\"" file)
5031 (ding) (sit-for 2)
5033 (error "Cannot read file \"%s\"" file))
5034 (with-temp-buffer
5035 (insert-file-contents file)
5036 (buffer-string))))
5038 (defun org-extract-log-state-settings (x)
5039 "Extract the log state setting from a TODO keyword string.
5040 This will extract info from a string like \"WAIT(w@/!)\"."
5041 (let (kw key log1 log2)
5042 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5043 (setq kw (match-string 1 x)
5044 key (and (match-end 2) (match-string 2 x))
5045 log1 (and (match-end 3) (match-string 3 x))
5046 log2 (and (match-end 4) (match-string 4 x)))
5047 (and (or log1 log2)
5048 (list kw
5049 (and log1 (if (equal log1 "!") 'time 'note))
5050 (and log2 (if (equal log2 "!") 'time 'note)))))))
5052 (defun org-remove-keyword-keys (list)
5053 "Remove a pair of parenthesis at the end of each string in LIST."
5054 (mapcar (lambda (x)
5055 (if (string-match "(.*)$" x)
5056 (substring x 0 (match-beginning 0))
5058 list))
5060 (defun org-assign-fast-keys (alist)
5061 "Assign fast keys to a keyword-key alist.
5062 Respect keys that are already there."
5063 (let (new e (alt ?0))
5064 (while (setq e (pop alist))
5065 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5066 (cdr e)) ;; Key already assigned.
5067 (push e new)
5068 (let ((clist (string-to-list (downcase (car e))))
5069 (used (append new alist)))
5070 (when (= (car clist) ?@)
5071 (pop clist))
5072 (while (and clist (rassoc (car clist) used))
5073 (pop clist))
5074 (unless clist
5075 (while (rassoc alt used)
5076 (incf alt)))
5077 (push (cons (car e) (or (car clist) alt)) new))))
5078 (nreverse new)))
5080 ;;; Some variables used in various places
5082 (defvar org-window-configuration nil
5083 "Used in various places to store a window configuration.")
5084 (defvar org-selected-window nil
5085 "Used in various places to store a window configuration.")
5086 (defvar org-finish-function nil
5087 "Function to be called when `C-c C-c' is used.
5088 This is for getting out of special buffers like capture.")
5091 ;; FIXME: Occasionally check by commenting these, to make sure
5092 ;; no other functions uses these, forgetting to let-bind them.
5093 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5094 (defvar org-last-state)
5095 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5097 ;; Defined somewhere in this file, but used before definition.
5098 (defvar org-entities) ;; defined in org-entities.el
5099 (defvar org-struct-menu)
5100 (defvar org-org-menu)
5101 (defvar org-tbl-menu)
5103 ;;;; Define the Org-mode
5105 ;; We use a before-change function to check if a table might need
5106 ;; an update.
5107 (defvar org-table-may-need-update t
5108 "Indicates that a table might need an update.
5109 This variable is set by `org-before-change-function'.
5110 `org-table-align' sets it back to nil.")
5111 (defun org-before-change-function (beg end)
5112 "Every change indicates that a table might need an update."
5113 (setq org-table-may-need-update t))
5114 (defvar org-mode-map)
5115 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5116 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5117 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5118 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5119 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5120 (defvar org-table-buffer-is-an nil)
5122 (defvar bidi-paragraph-direction)
5123 (defvar buffer-face-mode-face)
5125 (require 'outline)
5126 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5127 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5128 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5130 ;; Other stuff we need.
5131 (require 'time-date)
5132 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5133 (require 'easymenu)
5134 (require 'overlay)
5136 ;; (require 'org-macs) moved higher up in the file before it is first used
5137 (require 'org-entities)
5138 ;; (require 'org-compat) moved higher up in the file before it is first used
5139 (require 'org-faces)
5140 (require 'org-list)
5141 (require 'org-pcomplete)
5142 (require 'org-src)
5143 (require 'org-footnote)
5144 (require 'org-macro)
5146 ;; babel
5147 (require 'ob)
5149 ;;;###autoload
5150 (define-derived-mode org-mode outline-mode "Org"
5151 "Outline-based notes management and organizer, alias
5152 \"Carsten's outline-mode for keeping track of everything.\"
5154 Org-mode develops organizational tasks around a NOTES file which
5155 contains information about projects as plain text. Org-mode is
5156 implemented on top of outline-mode, which is ideal to keep the content
5157 of large files well structured. It supports ToDo items, deadlines and
5158 time stamps, which magically appear in the diary listing of the Emacs
5159 calendar. Tables are easily created with a built-in table editor.
5160 Plain text URL-like links connect to websites, emails (VM), Usenet
5161 messages (Gnus), BBDB entries, and any files related to the project.
5162 For printing and sharing of notes, an Org-mode file (or a part of it)
5163 can be exported as a structured ASCII or HTML file.
5165 The following commands are available:
5167 \\{org-mode-map}"
5169 ;; Get rid of Outline menus, they are not needed
5170 ;; Need to do this here because define-derived-mode sets up
5171 ;; the keymap so late. Still, it is a waste to call this each time
5172 ;; we switch another buffer into org-mode.
5173 (if (featurep 'xemacs)
5174 (when (boundp 'outline-mode-menu-heading)
5175 ;; Assume this is Greg's port, it uses easymenu
5176 (easy-menu-remove outline-mode-menu-heading)
5177 (easy-menu-remove outline-mode-menu-show)
5178 (easy-menu-remove outline-mode-menu-hide))
5179 (define-key org-mode-map [menu-bar headings] 'undefined)
5180 (define-key org-mode-map [menu-bar hide] 'undefined)
5181 (define-key org-mode-map [menu-bar show] 'undefined))
5183 (org-load-modules-maybe)
5184 (easy-menu-add org-org-menu)
5185 (easy-menu-add org-tbl-menu)
5186 (org-install-agenda-files-menu)
5187 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5188 (add-to-invisibility-spec '(org-cwidth))
5189 (add-to-invisibility-spec '(org-hide-block . t))
5190 (when (featurep 'xemacs)
5191 (org-set-local 'line-move-ignore-invisible t))
5192 (org-set-local 'outline-regexp org-outline-regexp)
5193 (org-set-local 'outline-level 'org-outline-level)
5194 (setq bidi-paragraph-direction 'left-to-right)
5195 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5196 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5197 (when (and org-ellipsis
5198 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5199 (fboundp 'make-glyph-code))
5200 (unless org-display-table
5201 (setq org-display-table (make-display-table)))
5202 (set-display-table-slot
5203 org-display-table 4
5204 (vconcat (mapcar
5205 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5206 org-ellipsis)))
5207 (if (stringp org-ellipsis) org-ellipsis "..."))))
5208 (setq buffer-display-table org-display-table))
5209 (org-set-regexps-and-options)
5210 (when (and org-tag-faces (not org-tags-special-faces-re))
5211 ;; tag faces set outside customize.... force initialization.
5212 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5213 ;; Calc embedded
5214 (org-set-local 'calc-embedded-open-mode "# ")
5215 ;; Modify a few syntax entries
5216 (modify-syntax-entry ?@ "w")
5217 (modify-syntax-entry ?\" "\"")
5218 (if org-startup-truncated (setq truncate-lines t))
5219 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5220 (org-set-local 'font-lock-unfontify-region-function
5221 'org-unfontify-region)
5222 ;; Activate before-change-function
5223 (org-set-local 'org-table-may-need-update t)
5224 (org-add-hook 'before-change-functions 'org-before-change-function nil
5225 'local)
5226 ;; Check for running clock before killing a buffer
5227 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5228 ;; Initialize macros templates.
5229 (org-macro-initialize-templates)
5230 ;; Initialize radio targets.
5231 (org-update-radio-target-regexp)
5232 ;; Indentation.
5233 (org-set-local 'indent-line-function 'org-indent-line)
5234 (org-set-local 'indent-region-function 'org-indent-region)
5235 ;; Filling and auto-filling.
5236 (org-setup-filling)
5237 ;; Comments.
5238 (org-setup-comments-handling)
5239 ;; Beginning/end of defun
5240 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5241 (org-set-local 'end-of-defun-function 'org-forward-element)
5242 ;; Next error for sparse trees
5243 (org-set-local 'next-error-function 'org-occur-next-match)
5244 ;; Make sure dependence stuff works reliably, even for users who set it
5245 ;; too late :-(
5246 (if org-enforce-todo-dependencies
5247 (add-hook 'org-blocker-hook
5248 'org-block-todo-from-children-or-siblings-or-parent)
5249 (remove-hook 'org-blocker-hook
5250 'org-block-todo-from-children-or-siblings-or-parent))
5251 (if org-enforce-todo-checkbox-dependencies
5252 (add-hook 'org-blocker-hook
5253 'org-block-todo-from-checkboxes)
5254 (remove-hook 'org-blocker-hook
5255 'org-block-todo-from-checkboxes))
5257 ;; Align options lines
5258 (org-set-local
5259 'align-mode-rules-list
5260 '((org-in-buffer-settings
5261 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5262 (modes . '(org-mode)))))
5264 ;; Imenu
5265 (org-set-local 'imenu-create-index-function
5266 'org-imenu-get-tree)
5268 ;; Make isearch reveal context
5269 (if (or (featurep 'xemacs)
5270 (not (boundp 'outline-isearch-open-invisible-function)))
5271 ;; Emacs 21 and XEmacs make use of the hook
5272 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5273 ;; Emacs 22 deals with this through a special variable
5274 (org-set-local 'outline-isearch-open-invisible-function
5275 (lambda (&rest ignore) (org-show-context 'isearch)))
5276 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5278 ;; Setup the pcomplete hooks
5279 (set (make-local-variable 'pcomplete-command-completion-function)
5280 'org-pcomplete-initial)
5281 (set (make-local-variable 'pcomplete-command-name-function)
5282 'org-command-at-point)
5283 (set (make-local-variable 'pcomplete-default-completion-function)
5284 'ignore)
5285 (set (make-local-variable 'pcomplete-parse-arguments-function)
5286 'org-parse-arguments)
5287 (set (make-local-variable 'pcomplete-termination-string) "")
5288 (when (>= emacs-major-version 23)
5289 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5291 ;; If empty file that did not turn on org-mode automatically, make it to.
5292 (if (and org-insert-mode-line-in-empty-file
5293 (org-called-interactively-p 'any)
5294 (= (point-min) (point-max)))
5295 (insert "# -*- mode: org -*-\n\n"))
5296 (unless org-inhibit-startup
5297 (org-unmodified
5298 (and org-startup-with-beamer-mode (org-beamer-mode))
5299 (when org-startup-align-all-tables
5300 (org-table-map-tables 'org-table-align 'quietly))
5301 (when org-startup-with-inline-images
5302 (org-display-inline-images))
5303 (when org-startup-with-latex-preview
5304 (org-preview-latex-fragment))
5305 (unless org-inhibit-startup-visibility-stuff
5306 (org-set-startup-visibility))))
5307 ;; Try to set org-hide correctly
5308 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5310 ;; Update `customize-package-emacs-version-alist'
5311 (add-to-list 'customize-package-emacs-version-alist
5312 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5313 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5314 ("8.0" . "24.4")))
5316 (defvar org-mode-transpose-word-syntax-table
5317 (let ((st (make-syntax-table)))
5318 (mapc (lambda(c) (modify-syntax-entry
5319 (string-to-char (car c)) "w p" st))
5320 org-emphasis-alist)
5321 st))
5323 (when (fboundp 'abbrev-table-put)
5324 (abbrev-table-put org-mode-abbrev-table
5325 :parents (list text-mode-abbrev-table)))
5327 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5329 (defsubst org-fix-ellipsis-at-bol ()
5330 (save-excursion (goto-char (window-start)) (recenter 0)))
5332 (defun org-find-invisible-foreground ()
5333 (let ((candidates (remove
5334 "unspecified-bg"
5335 (nconc
5336 (list (face-background 'default)
5337 (face-background 'org-default))
5338 (mapcar
5339 (lambda (alist)
5340 (when (boundp alist)
5341 (cdr (assoc 'background-color (symbol-value alist)))))
5342 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5343 (list (face-foreground 'org-hide))))))
5344 (car (remove nil candidates))))
5346 (defun org-current-time (&optional rounding-minutes past)
5347 "Current time, possibly rounded to ROUNDING-MINUTES.
5348 When ROUNDING-MINUTES is not an integer, fall back on the car of
5349 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5350 the rounding returns a past time."
5351 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5352 (car org-time-stamp-rounding-minutes)))
5353 (time (decode-time)) res)
5354 (if (< r 1)
5355 (current-time)
5356 (setq res
5357 (apply 'encode-time
5358 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5359 (nthcdr 2 time))))
5360 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5361 (seconds-to-time (- (org-float-time res) (* r 60)))
5362 res))))
5364 (defun org-today ()
5365 "Return today date, considering `org-extend-today-until'."
5366 (time-to-days
5367 (time-subtract (current-time)
5368 (list 0 (* 3600 org-extend-today-until) 0))))
5370 ;;;; Font-Lock stuff, including the activators
5372 (defvar org-mouse-map (make-sparse-keymap))
5373 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5374 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5375 (when org-mouse-1-follows-link
5376 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5377 (when org-tab-follows-link
5378 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5379 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5381 (require 'font-lock)
5383 (defconst org-non-link-chars "]\t\n\r<>")
5384 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5385 "shell" "elisp" "doi" "message"))
5386 (defvar org-link-types-re nil
5387 "Matches a link that has a url-like prefix like \"http:\"")
5388 (defvar org-link-re-with-space nil
5389 "Matches a link with spaces, optional angular brackets around it.")
5390 (defvar org-link-re-with-space2 nil
5391 "Matches a link with spaces, optional angular brackets around it.")
5392 (defvar org-link-re-with-space3 nil
5393 "Matches a link with spaces, only for internal part in bracket links.")
5394 (defvar org-angle-link-re nil
5395 "Matches link with angular brackets, spaces are allowed.")
5396 (defvar org-plain-link-re nil
5397 "Matches plain link, without spaces.")
5398 (defvar org-bracket-link-regexp nil
5399 "Matches a link in double brackets.")
5400 (defvar org-bracket-link-analytic-regexp nil
5401 "Regular expression used to analyze links.
5402 Here is what the match groups contain after a match:
5403 1: http:
5404 2: http
5405 3: path
5406 4: [desc]
5407 5: desc")
5408 (defvar org-bracket-link-analytic-regexp++ nil
5409 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5410 (defvar org-any-link-re nil
5411 "Regular expression matching any link.")
5413 (defconst org-match-sexp-depth 3
5414 "Number of stacked braces for sub/superscript matching.")
5416 (defun org-create-multibrace-regexp (left right n)
5417 "Create a regular expression which will match a balanced sexp.
5418 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5419 as single character strings.
5420 The regexp returned will match the entire expression including the
5421 delimiters. It will also define a single group which contains the
5422 match except for the outermost delimiters. The maximum depth of
5423 stacked delimiters is N. Escaping delimiters is not possible."
5424 (let* ((nothing (concat "[^" left right "]*?"))
5425 (or "\\|")
5426 (re nothing)
5427 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5428 (while (> n 1)
5429 (setq n (1- n)
5430 re (concat re or next)
5431 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5432 (concat left "\\(" re "\\)" right)))
5434 (defvar org-match-substring-regexp
5435 (concat
5436 "\\(\\S-\\)\\([_^]\\)\\("
5437 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5438 "\\|"
5439 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5440 "\\|"
5441 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5442 "The regular expression matching a sub- or superscript.")
5444 (defvar org-match-substring-with-braces-regexp
5445 (concat
5446 "\\(\\S-\\)\\([_^]\\)\\("
5447 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5448 "\\)")
5449 "The regular expression matching a sub- or superscript, forcing braces.")
5451 (defun org-make-link-regexps ()
5452 "Update the link regular expressions.
5453 This should be called after the variable `org-link-types' has changed."
5454 (setq org-link-types-re
5455 (concat
5456 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5457 org-link-re-with-space
5458 (concat
5459 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5460 "\\([^" org-non-link-chars " ]"
5461 "[^" org-non-link-chars "]*"
5462 "[^" org-non-link-chars " ]\\)>?")
5463 org-link-re-with-space2
5464 (concat
5465 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5466 "\\([^" org-non-link-chars " ]"
5467 "[^\t\n\r]*"
5468 "[^" org-non-link-chars " ]\\)>?")
5469 org-link-re-with-space3
5470 (concat
5471 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5472 "\\([^" org-non-link-chars " ]"
5473 "[^\t\n\r]*\\)")
5474 org-angle-link-re
5475 (concat
5476 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5477 "\\([^" org-non-link-chars " ]"
5478 "[^" org-non-link-chars "]*"
5479 "\\)>")
5480 org-plain-link-re
5481 (concat
5482 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5483 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5484 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5485 org-bracket-link-regexp
5486 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5487 org-bracket-link-analytic-regexp
5488 (concat
5489 "\\[\\["
5490 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5491 "\\([^]]+\\)"
5492 "\\]"
5493 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5494 "\\]")
5495 org-bracket-link-analytic-regexp++
5496 (concat
5497 "\\[\\["
5498 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5499 "\\([^]]+\\)"
5500 "\\]"
5501 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5502 "\\]")
5503 org-any-link-re
5504 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5505 org-angle-link-re "\\)\\|\\("
5506 org-plain-link-re "\\)")))
5508 (org-make-link-regexps)
5510 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5511 "Regular expression for fast time stamp matching.")
5512 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5513 "Regular expression for fast time stamp matching.")
5514 (defconst org-ts-regexp0
5515 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5516 "Regular expression matching time strings for analysis.
5517 This one does not require the space after the date, so it can be used
5518 on a string that terminates immediately after the date.")
5519 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5520 "Regular expression matching time strings for analysis.")
5521 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5522 "Regular expression matching time stamps, with groups.")
5523 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5524 "Regular expression matching time stamps (also [..]), with groups.")
5525 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5526 "Regular expression matching a time stamp range.")
5527 (defconst org-tr-regexp-both
5528 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5529 "Regular expression matching a time stamp range.")
5530 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5531 org-ts-regexp "\\)?")
5532 "Regular expression matching a time stamp or time stamp range.")
5533 (defconst org-tsr-regexp-both
5534 (concat org-ts-regexp-both "\\(--?-?"
5535 org-ts-regexp-both "\\)?")
5536 "Regular expression matching a time stamp or time stamp range.
5537 The time stamps may be either active or inactive.")
5539 (defvar org-emph-face nil)
5541 (defun org-do-emphasis-faces (limit)
5542 "Run through the buffer and add overlays to emphasized strings."
5543 (let (rtn a)
5544 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5545 (if (not (= (char-after (match-beginning 3))
5546 (char-after (match-beginning 4))))
5547 (progn
5548 (setq rtn t)
5549 (setq a (assoc (match-string 3) org-emphasis-alist))
5550 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5551 'face
5552 (nth 1 a))
5553 (and (nth 4 a)
5554 (org-remove-flyspell-overlays-in
5555 (match-beginning 0) (match-end 0)))
5556 (add-text-properties (match-beginning 2) (match-end 2)
5557 '(font-lock-multiline t org-emphasis t))
5558 (when org-hide-emphasis-markers
5559 (add-text-properties (match-end 4) (match-beginning 5)
5560 '(invisible org-link))
5561 (add-text-properties (match-beginning 3) (match-end 3)
5562 '(invisible org-link)))))
5563 (backward-char 1))
5564 rtn))
5566 (defun org-emphasize (&optional char)
5567 "Insert or change an emphasis, i.e. a font like bold or italic.
5568 If there is an active region, change that region to a new emphasis.
5569 If there is no region, just insert the marker characters and position
5570 the cursor between them.
5571 CHAR should be either the marker character, or the first character of the
5572 HTML tag associated with that emphasis. If CHAR is a space, the means
5573 to remove the emphasis of the selected region.
5574 If char is not given (for example in an interactive call) it
5575 will be prompted for."
5576 (interactive)
5577 (let ((eal org-emphasis-alist) e det
5578 (erc org-emphasis-regexp-components)
5579 (prompt "")
5580 (string "") beg end move tag c s)
5581 (if (org-region-active-p)
5582 (setq beg (region-beginning) end (region-end)
5583 string (buffer-substring beg end))
5584 (setq move t))
5586 (while (setq e (pop eal))
5587 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5588 c (aref tag 0))
5589 (push (cons c (string-to-char (car e))) det)
5590 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5591 (substring tag 1)))))
5592 (setq det (nreverse det))
5593 (unless char
5594 (message "%s" (concat "Emphasis marker or tag:" prompt))
5595 (setq char (read-char-exclusive)))
5596 (setq char (or (cdr (assoc char det)) char))
5597 (if (equal char ?\ )
5598 (setq s "" move nil)
5599 (unless (assoc (char-to-string char) org-emphasis-alist)
5600 (error "No such emphasis marker: \"%c\"" char))
5601 (setq s (char-to-string char)))
5602 (while (and (> (length string) 1)
5603 (equal (substring string 0 1) (substring string -1))
5604 (assoc (substring string 0 1) org-emphasis-alist))
5605 (setq string (substring string 1 -1)))
5606 (setq string (concat s string s))
5607 (if beg (delete-region beg end))
5608 (unless (or (bolp)
5609 (string-match (concat "[" (nth 0 erc) "\n]")
5610 (char-to-string (char-before (point)))))
5611 (insert " "))
5612 (unless (or (eobp)
5613 (string-match (concat "[" (nth 1 erc) "\n]")
5614 (char-to-string (char-after (point)))))
5615 (insert " ") (backward-char 1))
5616 (insert string)
5617 (and move (backward-char 1))))
5619 (defconst org-nonsticky-props
5620 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5622 (defsubst org-rear-nonsticky-at (pos)
5623 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5625 (defun org-activate-plain-links (limit)
5626 "Run through the buffer and add overlays to links."
5627 (let (f hl)
5628 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5629 (not (org-in-src-block-p)))
5630 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5631 (setq f (get-text-property (match-beginning 0) 'face))
5632 (setq hl (org-match-string-no-properties 0))
5633 (if (or (eq f 'org-tag)
5634 (and (listp f) (memq 'org-tag f)))
5636 (add-text-properties (match-beginning 0) (match-end 0)
5637 (list 'mouse-face 'highlight
5638 'face 'org-link
5639 'htmlize-link `(:uri ,hl)
5640 'keymap org-mouse-map))
5641 (org-rear-nonsticky-at (match-end 0)))
5642 t)))
5644 (defun org-activate-code (limit)
5645 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5646 (progn
5647 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5648 (remove-text-properties (match-beginning 0) (match-end 0)
5649 '(display t invisible t intangible t))
5650 t)))
5652 (defcustom org-src-fontify-natively nil
5653 "When non-nil, fontify code in code blocks."
5654 :type 'boolean
5655 :version "24.1"
5656 :group 'org-appearance
5657 :group 'org-babel)
5659 (defcustom org-allow-promoting-top-level-subtree nil
5660 "When non-nil, allow promoting a top level subtree.
5661 The leading star of the top level headline will be replaced
5662 by a #."
5663 :type 'boolean
5664 :version "24.1"
5665 :group 'org-appearance)
5667 (defun org-fontify-meta-lines-and-blocks (limit)
5668 (condition-case nil
5669 (org-fontify-meta-lines-and-blocks-1 limit)
5670 (error (message "org-mode fontification error"))))
5672 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5673 "Fontify #+ lines and blocks, in the correct ways."
5674 (let ((case-fold-search t))
5675 (if (re-search-forward
5676 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5677 limit t)
5678 (let ((beg (match-beginning 0))
5679 (block-start (match-end 0))
5680 (block-end nil)
5681 (lang (match-string 7))
5682 (beg1 (line-beginning-position 2))
5683 (dc1 (downcase (match-string 2)))
5684 (dc3 (downcase (match-string 3)))
5685 end end1 quoting block-type ovl)
5686 (cond
5687 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5688 ;; a single line of backend-specific content
5689 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5690 (remove-text-properties (match-beginning 0) (match-end 0)
5691 '(display t invisible t intangible t))
5692 (add-text-properties (match-beginning 1) (match-end 3)
5693 '(font-lock-fontified t face org-meta-line))
5694 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5695 '(font-lock-fontified t face org-block))
5696 ; for backend-specific code
5698 ((and (match-end 4) (equal dc3 "+begin"))
5699 ;; Truly a block
5700 (setq block-type (downcase (match-string 5))
5701 quoting (member block-type org-protecting-blocks))
5702 (when (re-search-forward
5703 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5704 nil t) ;; on purpose, we look further than LIMIT
5705 (setq end (min (point-max) (match-end 0))
5706 end1 (min (point-max) (1- (match-beginning 0))))
5707 (setq block-end (match-beginning 0))
5708 (when quoting
5709 (remove-text-properties beg end
5710 '(display t invisible t intangible t)))
5711 (add-text-properties
5712 beg end
5713 '(font-lock-fontified t font-lock-multiline t))
5714 (add-text-properties beg beg1 '(face org-meta-line))
5715 (add-text-properties end1 (min (point-max) (1+ end))
5716 '(face org-meta-line)) ; for end_src
5717 (cond
5718 ((and lang (not (string= lang "")) org-src-fontify-natively)
5719 (org-src-font-lock-fontify-block lang block-start block-end)
5720 ;; remove old background overlays
5721 (mapc (lambda (ov)
5722 (if (eq (overlay-get ov 'face) 'org-block-background)
5723 (delete-overlay ov)))
5724 (overlays-at (/ (+ beg1 block-end) 2)))
5725 ;; add a background overlay
5726 (setq ovl (make-overlay beg1 block-end))
5727 (overlay-put ovl 'face 'org-block-background)
5728 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5729 (quoting
5730 (add-text-properties beg1 (min (point-max) (1+ end1))
5731 '(face org-block))) ; end of source block
5732 ((not org-fontify-quote-and-verse-blocks))
5733 ((string= block-type "quote")
5734 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5735 ((string= block-type "verse")
5736 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5737 (add-text-properties beg beg1 '(face org-block-begin-line))
5738 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5739 '(face org-block-end-line))
5741 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5742 (add-text-properties
5743 beg (match-end 3)
5744 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5745 '(font-lock-fontified t invisible t)
5746 '(font-lock-fontified t face org-document-info-keyword)))
5747 (add-text-properties
5748 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5749 (if (string-equal dc1 "+title:")
5750 '(font-lock-fontified t face org-document-title)
5751 '(font-lock-fontified t face org-document-info))))
5752 ((or (equal dc1 "+results")
5753 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5754 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5755 "+call:" "+header:" "+headers:" "+name:"))
5756 (and (match-end 4) (equal dc3 "+attr")))
5757 (add-text-properties
5758 beg (match-end 0)
5759 '(font-lock-fontified t face org-meta-line))
5761 ((member dc3 '(" " ""))
5762 (add-text-properties
5763 beg (match-end 0)
5764 '(font-lock-fontified t face font-lock-comment-face)))
5765 ((not (member (char-after beg) '(?\ ?\t)))
5766 ;; just any other in-buffer setting, but not indented
5767 (add-text-properties
5768 beg (match-end 0)
5769 '(font-lock-fontified t face org-meta-line))
5771 (t nil))))))
5773 (defun org-activate-angle-links (limit)
5774 "Run through the buffer and add overlays to links."
5775 (if (and (re-search-forward org-angle-link-re limit t)
5776 (not (org-in-src-block-p)))
5777 (progn
5778 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5779 (add-text-properties (match-beginning 0) (match-end 0)
5780 (list 'mouse-face 'highlight
5781 'keymap org-mouse-map))
5782 (org-rear-nonsticky-at (match-end 0))
5783 t)))
5785 (defun org-activate-footnote-links (limit)
5786 "Run through the buffer and add overlays to footnotes."
5787 (let ((fn (org-footnote-next-reference-or-definition limit)))
5788 (when fn
5789 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5790 (org-remove-flyspell-overlays-in beg end)
5791 (add-text-properties beg end
5792 (list 'mouse-face 'highlight
5793 'keymap org-mouse-map
5794 'help-echo
5795 (if (= (point-at-bol) beg)
5796 "Footnote definition"
5797 "Footnote reference")
5798 'font-lock-fontified t
5799 'font-lock-multiline t
5800 'face 'org-footnote))))))
5802 (defun org-activate-bracket-links (limit)
5803 "Run through the buffer and add overlays to bracketed links."
5804 (if (and (re-search-forward org-bracket-link-regexp limit t)
5805 (not (org-in-src-block-p)))
5806 (let* ((hl (org-match-string-no-properties 1))
5807 (help (concat "LINK: " hl))
5808 ;; FIXME: Above we should remove the escapes. But that
5809 ;; requires another match, protecting match data, a lot
5810 ;; of overhead for font-lock.
5811 (ip (org-maybe-intangible
5812 (list 'invisible 'org-link
5813 'keymap org-mouse-map 'mouse-face 'highlight
5814 'font-lock-multiline t 'help-echo help
5815 'htmlize-link `(:uri ,hl))))
5816 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5817 'font-lock-multiline t 'help-echo help
5818 'htmlize-link `(:uri ,hl))))
5819 ;; We need to remove the invisible property here. Table narrowing
5820 ;; may have made some of this invisible.
5821 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5822 (remove-text-properties (match-beginning 0) (match-end 0)
5823 '(invisible nil))
5824 (if (match-end 3)
5825 (progn
5826 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5827 (org-rear-nonsticky-at (match-beginning 3))
5828 (add-text-properties (match-beginning 3) (match-end 3) vp)
5829 (org-rear-nonsticky-at (match-end 3))
5830 (add-text-properties (match-end 3) (match-end 0) ip)
5831 (org-rear-nonsticky-at (match-end 0)))
5832 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5833 (org-rear-nonsticky-at (match-beginning 1))
5834 (add-text-properties (match-beginning 1) (match-end 1) vp)
5835 (org-rear-nonsticky-at (match-end 1))
5836 (add-text-properties (match-end 1) (match-end 0) ip)
5837 (org-rear-nonsticky-at (match-end 0)))
5838 t)))
5840 (defun org-activate-dates (limit)
5841 "Run through the buffer and add overlays to dates."
5842 (if (and (re-search-forward org-tsr-regexp-both limit t)
5843 (not (equal (char-before (match-beginning 0)) 91)))
5844 (progn
5845 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5846 (add-text-properties (match-beginning 0) (match-end 0)
5847 (list 'mouse-face 'highlight
5848 'keymap org-mouse-map))
5849 (org-rear-nonsticky-at (match-end 0))
5850 (when org-display-custom-times
5851 (if (match-end 3)
5852 (org-display-custom-time (match-beginning 3) (match-end 3)))
5853 (org-display-custom-time (match-beginning 1) (match-end 1)))
5854 t)))
5856 (defvar org-target-link-regexp nil
5857 "Regular expression matching radio targets in plain text.")
5858 (make-variable-buffer-local 'org-target-link-regexp)
5859 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5860 "Regular expression matching a link target.")
5861 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5862 "Regular expression matching a radio target.")
5863 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5864 "Regular expression matching any target.")
5866 (defun org-activate-target-links (limit)
5867 "Run through the buffer and add overlays to target matches."
5868 (when org-target-link-regexp
5869 (let ((case-fold-search t))
5870 (if (re-search-forward org-target-link-regexp limit t)
5871 (progn
5872 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5873 (add-text-properties (match-beginning 0) (match-end 0)
5874 (list 'mouse-face 'highlight
5875 'keymap org-mouse-map
5876 'help-echo "Radio target link"
5877 'org-linked-text t))
5878 (org-rear-nonsticky-at (match-end 0))
5879 t)))))
5881 (defun org-update-radio-target-regexp ()
5882 "Find all radio targets in this file and update the regular expression."
5883 (interactive)
5884 (when (memq 'radio org-activate-links)
5885 (setq org-target-link-regexp
5886 (org-make-target-link-regexp (org-all-targets 'radio)))
5887 (org-restart-font-lock)))
5889 (defun org-hide-wide-columns (limit)
5890 (let (s e)
5891 (setq s (text-property-any (point) (or limit (point-max))
5892 'org-cwidth t))
5893 (when s
5894 (setq e (next-single-property-change s 'org-cwidth))
5895 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5896 (goto-char e)
5897 t)))
5899 (defvar org-latex-and-related-regexp nil
5900 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5901 (defvar org-match-substring-regexp)
5902 (defvar org-match-substring-with-braces-regexp)
5904 (defun org-compute-latex-and-related-regexp ()
5905 "Compute regular expression for LaTeX, entities and sub/superscript.
5906 Result depends on variable `org-highlight-latex-and-related'."
5907 (org-set-local
5908 'org-latex-and-related-regexp
5909 (let* ((re-sub
5910 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5911 ((eq org-use-sub-superscripts '{})
5912 (list org-match-substring-with-braces-regexp))
5913 (org-use-sub-superscripts (list org-match-substring-regexp))))
5914 (re-latex
5915 (when (memq 'latex org-highlight-latex-and-related)
5916 (let ((matchers (plist-get org-format-latex-options :matchers)))
5917 (delq nil
5918 (mapcar (lambda (x)
5919 (and (member (car x) matchers) (nth 1 x)))
5920 org-latex-regexps)))))
5921 (re-entities
5922 (when (memq 'entities org-highlight-latex-and-related)
5923 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5924 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5926 (defun org-do-latex-and-related (limit)
5927 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5928 LIMIT bounds the search for syntax to highlight. Stop at first
5929 highlighted object, if any. Return t if some highlighting was
5930 done, nil otherwise."
5931 (when (org-string-nw-p org-latex-and-related-regexp)
5932 (catch 'found
5933 (while (re-search-forward org-latex-and-related-regexp limit t)
5934 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5935 'face))
5936 '(org-code org-verbatim underline))
5937 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5938 '(?_ ?^))
5940 0)))
5941 (font-lock-prepend-text-property
5942 (+ offset (match-beginning 0)) (match-end 0)
5943 'face 'org-latex-and-related)
5944 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5945 '(font-lock-multiline t)))
5946 (throw 'found t)))
5947 nil)))
5949 (defun org-restart-font-lock ()
5950 "Restart `font-lock-mode', to force refontification."
5951 (when (and (boundp 'font-lock-mode) font-lock-mode)
5952 (font-lock-mode -1)
5953 (font-lock-mode 1)))
5955 (defun org-all-targets (&optional radio)
5956 "Return a list of all targets in this file.
5957 When optional argument RADIO is non-nil, only find radio
5958 targets."
5959 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5960 (save-excursion
5961 (goto-char (point-min))
5962 (while (re-search-forward re nil t)
5963 ;; Make sure point is really within the object.
5964 (backward-char)
5965 (let ((obj (org-element-context)))
5966 (when (memq (org-element-type obj) '(radio-target target))
5967 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5968 rtn)))
5970 (defun org-make-target-link-regexp (targets)
5971 "Make regular expression matching all strings in TARGETS.
5972 The regular expression finds the targets also if there is a line break
5973 between words."
5974 (and targets
5975 (concat
5976 "\\<\\("
5977 (mapconcat
5978 (lambda (x)
5979 (setq x (regexp-quote x))
5980 (while (string-match " +" x)
5981 (setq x (replace-match "\\s-+" t t x)))
5983 targets
5984 "\\|")
5985 "\\)\\>")))
5987 (defun org-activate-tags (limit)
5988 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5989 (progn
5990 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5991 (add-text-properties (match-beginning 1) (match-end 1)
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map))
5994 (org-rear-nonsticky-at (match-end 1))
5995 t)))
5997 (defun org-outline-level ()
5998 "Compute the outline level of the heading at point.
5999 If this is called at a normal headline, the level is the number of stars.
6000 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6001 (save-excursion
6002 (if (not (condition-case nil
6003 (org-back-to-heading t)
6004 (error nil)))
6006 (looking-at org-outline-regexp)
6007 (1- (- (match-end 0) (match-beginning 0))))))
6009 (defvar org-font-lock-keywords nil)
6011 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6012 "Regular expression matching a property line.")
6014 (defvar org-font-lock-hook nil
6015 "Functions to be called for special font lock stuff.")
6017 (defvar org-font-lock-set-keywords-hook nil
6018 "Functions that can manipulate `org-font-lock-extra-keywords'.
6019 This is called after `org-font-lock-extra-keywords' is defined, but before
6020 it is installed to be used by font lock. This can be useful if something
6021 needs to be inserted at a specific position in the font-lock sequence.")
6023 (defun org-font-lock-hook (limit)
6024 "Run `org-font-lock-hook' within LIMIT."
6025 (run-hook-with-args 'org-font-lock-hook limit))
6027 (defun org-set-font-lock-defaults ()
6028 "Set font lock defaults for the current buffer."
6029 (let* ((em org-fontify-emphasized-text)
6030 (lk org-activate-links)
6031 (org-font-lock-extra-keywords
6032 (list
6033 ;; Call the hook
6034 '(org-font-lock-hook)
6035 ;; Headlines
6036 `(,(if org-fontify-whole-heading-line
6037 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6038 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6039 (1 (org-get-level-face 1))
6040 (2 (org-get-level-face 2))
6041 (3 (org-get-level-face 3)))
6042 ;; Table lines
6043 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6044 (1 'org-table t))
6045 ;; Table internals
6046 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6047 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6048 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6049 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6050 ;; Drawers
6051 (list org-drawer-regexp '(0 'org-special-keyword t))
6052 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6053 ;; Properties
6054 (list org-property-re
6055 '(1 'org-special-keyword t)
6056 '(3 'org-property-value t))
6057 ;; Links
6058 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6059 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6060 (if (memq 'plain lk) '(org-activate-plain-links))
6061 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6062 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6063 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6064 (if (memq 'footnote lk) '(org-activate-footnote-links))
6065 ;; Targets.
6066 (list org-any-target-regexp '(0 'org-target t))
6067 ;; Diary sexps.
6068 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6069 '(org-hide-wide-columns (0 nil append))
6070 ;; TODO keyword
6071 (list (format org-heading-keyword-regexp-format
6072 org-todo-regexp)
6073 '(2 (org-get-todo-face 2) t))
6074 ;; DONE
6075 (if org-fontify-done-headline
6076 (list (format org-heading-keyword-regexp-format
6077 (concat
6078 "\\(?:"
6079 (mapconcat 'regexp-quote org-done-keywords "\\|")
6080 "\\)"))
6081 '(2 'org-headline-done t))
6082 nil)
6083 ;; Priorities
6084 '(org-font-lock-add-priority-faces)
6085 ;; Tags
6086 '(org-font-lock-add-tag-faces)
6087 ;; Special keywords
6088 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6089 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6090 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6091 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6092 ;; Emphasis
6093 (if em
6094 (if (featurep 'xemacs)
6095 '(org-do-emphasis-faces (0 nil append))
6096 '(org-do-emphasis-faces)))
6097 ;; Checkboxes
6098 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6099 1 'org-checkbox prepend)
6100 (if (cdr (assq 'checkbox org-list-automatic-rules))
6101 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6102 (0 (org-get-checkbox-statistics-face) t)))
6103 ;; Description list items
6104 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6105 1 'org-list-dt prepend)
6106 ;; ARCHIVEd headings
6107 (list (concat
6108 org-outline-regexp-bol
6109 "\\(.*:" org-archive-tag ":.*\\)")
6110 '(1 'org-archived prepend))
6111 ;; Specials
6112 '(org-do-latex-and-related)
6113 '(org-fontify-entities)
6114 '(org-raise-scripts)
6115 ;; Code
6116 '(org-activate-code (1 'org-code t))
6117 ;; COMMENT
6118 (list (format org-heading-keyword-regexp-format
6119 (concat "\\("
6120 org-comment-string "\\|" org-quote-string
6121 "\\)"))
6122 '(2 'org-special-keyword t))
6123 ;; Blocks and meta lines
6124 '(org-fontify-meta-lines-and-blocks)
6126 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6127 (run-hooks 'org-font-lock-set-keywords-hook)
6128 ;; Now set the full font-lock-keywords
6129 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6130 (org-set-local 'font-lock-defaults
6131 '(org-font-lock-keywords t nil nil backward-paragraph))
6132 (kill-local-variable 'font-lock-keywords) nil))
6134 (defun org-toggle-pretty-entities ()
6135 "Toggle the composition display of entities as UTF8 characters."
6136 (interactive)
6137 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6138 (org-restart-font-lock)
6139 (if org-pretty-entities
6140 (message "Entities are displayed as UTF8 characters")
6141 (save-restriction
6142 (widen)
6143 (org-decompose-region (point-min) (point-max))
6144 (message "Entities are displayed plain"))))
6146 (defvar org-custom-properties-overlays nil
6147 "List of overlays used for custom properties.")
6148 (make-variable-buffer-local 'org-custom-properties-overlays)
6150 (defun org-toggle-custom-properties-visibility ()
6151 "Display or hide properties in `org-custom-properties'."
6152 (interactive)
6153 (if org-custom-properties-overlays
6154 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6155 (setq org-custom-properties-overlays nil))
6156 (unless (not org-custom-properties)
6157 (save-excursion
6158 (save-restriction
6159 (widen)
6160 (goto-char (point-min))
6161 (while (re-search-forward org-property-re nil t)
6162 (mapc (lambda(p)
6163 (when (equal p (substring (match-string 1) 1 -1))
6164 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6165 (overlay-put o 'invisible t)
6166 (overlay-put o 'org-custom-property t)
6167 (push o org-custom-properties-overlays))))
6168 org-custom-properties)))))))
6170 (defun org-fontify-entities (limit)
6171 "Find an entity to fontify."
6172 (let (ee)
6173 (when org-pretty-entities
6174 (catch 'match
6175 (while (re-search-forward
6176 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6177 limit t)
6178 (if (and (not (org-in-indented-comment-line))
6179 (setq ee (org-entity-get (match-string 1)))
6180 (= (length (nth 6 ee)) 1))
6181 (let*
6182 ((end (if (equal (match-string 2) "{}")
6183 (match-end 2)
6184 (match-end 1))))
6185 (add-text-properties
6186 (match-beginning 0) end
6187 (list 'font-lock-fontified t))
6188 (compose-region (match-beginning 0) end
6189 (nth 6 ee) nil)
6190 (backward-char 1)
6191 (throw 'match t))))
6192 nil))))
6194 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6195 "Fontify string S like in Org-mode."
6196 (with-temp-buffer
6197 (insert s)
6198 (let ((org-odd-levels-only odd-levels))
6199 (org-mode)
6200 (font-lock-fontify-buffer)
6201 (buffer-string))))
6203 (defvar org-m nil)
6204 (defvar org-l nil)
6205 (defvar org-f nil)
6206 (defun org-get-level-face (n)
6207 "Get the right face for match N in font-lock matching of headlines."
6208 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6209 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6210 (if org-cycle-level-faces
6211 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6212 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6213 (cond
6214 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6215 ((eq n 2) org-f)
6216 (t (if org-level-color-stars-only nil org-f))))
6219 (defun org-get-todo-face (kwd)
6220 "Get the right face for a TODO keyword KWD.
6221 If KWD is a number, get the corresponding match group."
6222 (if (numberp kwd) (setq kwd (match-string kwd)))
6223 (or (org-face-from-face-or-color
6224 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6225 (and (member kwd org-done-keywords) 'org-done)
6226 'org-todo))
6228 (defun org-face-from-face-or-color (context inherit face-or-color)
6229 "Create a face list that inherits INHERIT, but sets the foreground color.
6230 When FACE-OR-COLOR is not a string, just return it."
6231 (if (stringp face-or-color)
6232 (list :inherit inherit
6233 (cdr (assoc context org-faces-easy-properties))
6234 face-or-color)
6235 face-or-color))
6237 (defun org-font-lock-add-tag-faces (limit)
6238 "Add the special tag faces."
6239 (when (and org-tag-faces org-tags-special-faces-re)
6240 (while (re-search-forward org-tags-special-faces-re limit t)
6241 (add-text-properties (match-beginning 1) (match-end 1)
6242 (list 'face (org-get-tag-face 1)
6243 'font-lock-fontified t))
6244 (backward-char 1))))
6246 (defun org-font-lock-add-priority-faces (limit)
6247 "Add the special priority faces."
6248 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6249 (when (save-match-data (org-at-heading-p))
6250 (add-text-properties
6251 (match-beginning 0) (match-end 0)
6252 (list 'face (or (org-face-from-face-or-color
6253 'priority 'org-priority
6254 (cdr (assoc (char-after (match-beginning 1))
6255 org-priority-faces)))
6256 'org-priority)
6257 'font-lock-fontified t)))))
6259 (defun org-get-tag-face (kwd)
6260 "Get the right face for a TODO keyword KWD.
6261 If KWD is a number, get the corresponding match group."
6262 (if (numberp kwd) (setq kwd (match-string kwd)))
6263 (or (org-face-from-face-or-color
6264 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6265 'org-tag))
6267 (defun org-unfontify-region (beg end &optional maybe_loudly)
6268 "Remove fontification and activation overlays from links."
6269 (font-lock-default-unfontify-region beg end)
6270 (let* ((buffer-undo-list t)
6271 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6272 (inhibit-modification-hooks t)
6273 deactivate-mark buffer-file-name buffer-file-truename)
6274 (org-decompose-region beg end)
6275 (remove-text-properties beg end
6276 '(mouse-face t keymap t org-linked-text t
6277 invisible t intangible t
6278 org-no-flyspell t org-emphasis t))
6279 (org-remove-font-lock-display-properties beg end)))
6281 (defconst org-script-display '(((raise -0.3) (height 0.7))
6282 ((raise 0.3) (height 0.7))
6283 ((raise -0.5))
6284 ((raise 0.5)))
6285 "Display properties for showing superscripts and subscripts.")
6287 (defun org-remove-font-lock-display-properties (beg end)
6288 "Remove specific display properties that have been added by font lock.
6289 The will remove the raise properties that are used to show superscripts
6290 and subscripts."
6291 (let (next prop)
6292 (while (< beg end)
6293 (setq next (next-single-property-change beg 'display nil end)
6294 prop (get-text-property beg 'display))
6295 (if (member prop org-script-display)
6296 (put-text-property beg next 'display nil))
6297 (setq beg next))))
6299 (defun org-raise-scripts (limit)
6300 "Add raise properties to sub/superscripts."
6301 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6302 (if (re-search-forward
6303 (if (eq org-use-sub-superscripts t)
6304 org-match-substring-regexp
6305 org-match-substring-with-braces-regexp)
6306 limit t)
6307 (let* ((pos (point)) table-p comment-p
6308 (mpos (match-beginning 3))
6309 (emph-p (get-text-property mpos 'org-emphasis))
6310 (link-p (get-text-property mpos 'mouse-face))
6311 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6312 (goto-char (point-at-bol))
6313 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6314 comment-p (org-looking-at-p "[ \t]*#"))
6315 (goto-char pos)
6316 ;; FIXME: Should we go back one character here, for a_b^c
6317 ;; (goto-char (1- pos)) ;????????????????????
6318 (if (or comment-p emph-p link-p keyw-p)
6320 (put-text-property (match-beginning 3) (match-end 0)
6321 'display
6322 (if (equal (char-after (match-beginning 2)) ?^)
6323 (nth (if table-p 3 1) org-script-display)
6324 (nth (if table-p 2 0) org-script-display)))
6325 (add-text-properties (match-beginning 2) (match-end 2)
6326 (list 'invisible t
6327 'org-dwidth t 'org-dwidth-n 1))
6328 (if (and (eq (char-after (match-beginning 3)) ?{)
6329 (eq (char-before (match-end 3)) ?}))
6330 (progn
6331 (add-text-properties
6332 (match-beginning 3) (1+ (match-beginning 3))
6333 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6334 (add-text-properties
6335 (1- (match-end 3)) (match-end 3)
6336 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6337 t)))))
6339 ;;;; Visibility cycling, including org-goto and indirect buffer
6341 ;;; Cycling
6343 (defvar org-cycle-global-status nil)
6344 (make-variable-buffer-local 'org-cycle-global-status)
6345 (put 'org-cycle-global-status 'org-state t)
6346 (defvar org-cycle-subtree-status nil)
6347 (make-variable-buffer-local 'org-cycle-subtree-status)
6348 (put 'org-cycle-subtree-status 'org-state t)
6350 (defvar org-inlinetask-min-level)
6352 ;;;###autoload
6353 (defun org-cycle (&optional arg)
6354 "TAB-action and visibility cycling for Org-mode.
6356 This is the command invoked in Org-mode by the TAB key. Its main purpose
6357 is outline visibility cycling, but it also invokes other actions
6358 in special contexts.
6360 - When this function is called with a prefix argument, rotate the entire
6361 buffer through 3 states (global cycling)
6362 1. OVERVIEW: Show only top-level headlines.
6363 2. CONTENTS: Show all headlines of all levels, but no body text.
6364 3. SHOW ALL: Show everything.
6365 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6366 determined by the variable `org-startup-folded', and by any VISIBILITY
6367 properties in the buffer.
6368 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6369 including any drawers.
6371 - When inside a table, re-align the table and move to the next field.
6373 - When point is at the beginning of a headline, rotate the subtree started
6374 by this line through 3 different states (local cycling)
6375 1. FOLDED: Only the main headline is shown.
6376 2. CHILDREN: The main headline and the direct children are shown.
6377 From this state, you can move to one of the children
6378 and zoom in further.
6379 3. SUBTREE: Show the entire subtree, including body text.
6380 If there is no subtree, switch directly from CHILDREN to FOLDED.
6382 - When point is at the beginning of an empty headline and the variable
6383 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6384 of the headline by demoting and promoting it to likely levels. This
6385 speeds up creation document structure by pressing TAB once or several
6386 times right after creating a new headline.
6388 - When there is a numeric prefix, go up to a heading with level ARG, do
6389 a `show-subtree' and return to the previous cursor position. If ARG
6390 is negative, go up that many levels.
6392 - When point is not at the beginning of a headline, execute the global
6393 binding for TAB, which is re-indenting the line. See the option
6394 `org-cycle-emulate-tab' for details.
6396 - Special case: if point is at the beginning of the buffer and there is
6397 no headline in line 1, this function will act as if called with prefix arg
6398 (C-u TAB, same as S-TAB) also when called without prefix arg.
6399 But only if also the variable `org-cycle-global-at-bob' is t."
6400 (interactive "P")
6401 (org-load-modules-maybe)
6402 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6403 (and org-cycle-level-after-item/entry-creation
6404 (or (org-cycle-level)
6405 (org-cycle-item-indentation))))
6406 (let* (message-log-max ; Don't populate the *Messages* buffer
6407 (limit-level
6408 (or org-cycle-max-level
6409 (and (boundp 'org-inlinetask-min-level)
6410 org-inlinetask-min-level
6411 (1- org-inlinetask-min-level))))
6412 (nstars (and limit-level
6413 (if org-odd-levels-only
6414 (and limit-level (1- (* limit-level 2)))
6415 limit-level)))
6416 (org-outline-regexp
6417 (if (not (derived-mode-p 'org-mode))
6418 outline-regexp
6419 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6420 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6421 (not (looking-at org-outline-regexp))))
6422 (org-cycle-hook
6423 (if bob-special
6424 (delq 'org-optimize-window-after-visibility-change
6425 (copy-sequence org-cycle-hook))
6426 org-cycle-hook))
6427 (pos (point)))
6429 (if (or bob-special (equal arg '(4)))
6430 ;; special case: use global cycling
6431 (setq arg t))
6433 (cond
6435 ((equal arg '(16))
6436 (setq last-command 'dummy)
6437 (org-set-startup-visibility)
6438 (message "Startup visibility, plus VISIBILITY properties"))
6440 ((equal arg '(64))
6441 (show-all)
6442 (message "Entire buffer visible, including drawers"))
6444 ;; Table: enter it or move to the next field.
6445 ((org-at-table-p 'any)
6446 (if (org-at-table.el-p)
6447 (message "Use C-c ' to edit table.el tables")
6448 (if arg (org-table-edit-field t)
6449 (org-table-justify-field-maybe)
6450 (call-interactively 'org-table-next-field))))
6452 ((run-hook-with-args-until-success
6453 'org-tab-after-check-for-table-hook))
6455 ;; Global cycling: delegate to `org-cycle-internal-global'.
6456 ((eq arg t) (org-cycle-internal-global))
6458 ;; Drawers: delegate to `org-flag-drawer'.
6459 ((and org-drawers org-drawer-regexp
6460 (save-excursion
6461 (beginning-of-line 1)
6462 (looking-at org-drawer-regexp)))
6463 (org-flag-drawer ; toggle block visibility
6464 (not (get-char-property (match-end 0) 'invisible))))
6466 ;; Show-subtree, ARG levels up from here.
6467 ((integerp arg)
6468 (save-excursion
6469 (org-back-to-heading)
6470 (outline-up-heading (if (< arg 0) (- arg)
6471 (- (funcall outline-level) arg)))
6472 (org-show-subtree)))
6474 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6475 ((and (featurep 'org-inlinetask)
6476 (org-inlinetask-at-task-p)
6477 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6478 (org-inlinetask-toggle-visibility))
6480 ((org-try-cdlatex-tab))
6482 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6483 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6484 (save-excursion (beginning-of-line 1)
6485 (looking-at org-outline-regexp)))
6486 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6487 (org-cycle-internal-local))
6489 ;; From there: TAB emulation and template completion.
6490 (buffer-read-only (org-back-to-heading))
6492 ((run-hook-with-args-until-success
6493 'org-tab-after-check-for-cycling-hook))
6495 ((org-try-structure-completion))
6497 ((run-hook-with-args-until-success
6498 'org-tab-before-tab-emulation-hook))
6500 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6501 (or (not (bolp))
6502 (not (looking-at org-outline-regexp))))
6503 (call-interactively (global-key-binding "\t")))
6505 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6506 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6507 (or (and (eq org-cycle-emulate-tab 'white)
6508 (= (match-end 0) (point-at-eol)))
6509 (and (eq org-cycle-emulate-tab 'whitestart)
6510 (>= (match-end 0) pos))))
6512 (eq org-cycle-emulate-tab t))
6513 (call-interactively (global-key-binding "\t")))
6515 (t (save-excursion
6516 (org-back-to-heading)
6517 (org-cycle)))))))
6519 (defun org-cycle-internal-global ()
6520 "Do the global cycling action."
6521 ;; Hack to avoid display of messages for .org attachments in Gnus
6522 (let (message-log-max ; Don't populate the *Messages* buffer
6523 (ga (string-match "\\*fontification" (buffer-name))))
6524 (cond
6525 ((and (eq last-command this-command)
6526 (eq org-cycle-global-status 'overview))
6527 ;; We just created the overview - now do table of contents
6528 ;; This can be slow in very large buffers, so indicate action
6529 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6530 (unless ga (message "CONTENTS..."))
6531 (org-content)
6532 (unless ga (message "CONTENTS...done"))
6533 (setq org-cycle-global-status 'contents)
6534 (run-hook-with-args 'org-cycle-hook 'contents))
6536 ((and (eq last-command this-command)
6537 (eq org-cycle-global-status 'contents))
6538 ;; We just showed the table of contents - now show everything
6539 (run-hook-with-args 'org-pre-cycle-hook 'all)
6540 (show-all)
6541 (unless ga (message "SHOW ALL"))
6542 (setq org-cycle-global-status 'all)
6543 (run-hook-with-args 'org-cycle-hook 'all))
6546 ;; Default action: go to overview
6547 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6548 (org-overview)
6549 (unless ga (message "OVERVIEW"))
6550 (setq org-cycle-global-status 'overview)
6551 (run-hook-with-args 'org-cycle-hook 'overview)))))
6553 (defun org-cycle-internal-local ()
6554 "Do the local cycling action."
6555 (let (message-log-max ; Don't populate the *Messages* buffer
6556 (goal-column 0) eoh eol eos has-children children-skipped struct)
6557 ;; First, determine end of headline (EOH), end of subtree or item
6558 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6559 (save-excursion
6560 (if (org-at-item-p)
6561 (progn
6562 (beginning-of-line)
6563 (setq struct (org-list-struct))
6564 (setq eoh (point-at-eol))
6565 (setq eos (org-list-get-item-end-before-blank (point) struct))
6566 (setq has-children (org-list-has-child-p (point) struct)))
6567 (org-back-to-heading)
6568 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6569 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6570 (setq has-children
6571 (or (save-excursion
6572 (let ((level (funcall outline-level)))
6573 (outline-next-heading)
6574 (and (org-at-heading-p t)
6575 (> (funcall outline-level) level))))
6576 (save-excursion
6577 (org-list-search-forward (org-item-beginning-re) eos t)))))
6578 ;; Determine end invisible part of buffer (EOL)
6579 (beginning-of-line 2)
6580 ;; XEmacs doesn't have `next-single-char-property-change'
6581 (if (featurep 'xemacs)
6582 (while (and (not (eobp)) ;; this is like `next-line'
6583 (get-char-property (1- (point)) 'invisible))
6584 (beginning-of-line 2))
6585 (while (and (not (eobp)) ;; this is like `next-line'
6586 (get-char-property (1- (point)) 'invisible))
6587 (goto-char (next-single-char-property-change (point) 'invisible))
6588 (and (eolp) (beginning-of-line 2))))
6589 (setq eol (point)))
6590 ;; Find out what to do next and set `this-command'
6591 (cond
6592 ((= eos eoh)
6593 ;; Nothing is hidden behind this heading
6594 (unless (org-before-first-heading-p)
6595 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6596 (message "EMPTY ENTRY")
6597 (setq org-cycle-subtree-status nil)
6598 (save-excursion
6599 (goto-char eos)
6600 (outline-next-heading)
6601 (if (outline-invisible-p) (org-flag-heading nil))))
6602 ((and (or (>= eol eos)
6603 (not (string-match "\\S-" (buffer-substring eol eos))))
6604 (or has-children
6605 (not (setq children-skipped
6606 org-cycle-skip-children-state-if-no-children))))
6607 ;; Entire subtree is hidden in one line: children view
6608 (unless (org-before-first-heading-p)
6609 (run-hook-with-args 'org-pre-cycle-hook 'children))
6610 (if (org-at-item-p)
6611 (org-list-set-item-visibility (point-at-bol) struct 'children)
6612 (org-show-entry)
6613 (org-with-limited-levels (show-children))
6614 ;; FIXME: This slows down the func way too much.
6615 ;; How keep drawers hidden in subtree anyway?
6616 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6617 ;; (org-cycle-hide-drawers 'subtree))
6619 ;; Fold every list in subtree to top-level items.
6620 (when (eq org-cycle-include-plain-lists 'integrate)
6621 (save-excursion
6622 (org-back-to-heading)
6623 (while (org-list-search-forward (org-item-beginning-re) eos t)
6624 (beginning-of-line 1)
6625 (let* ((struct (org-list-struct))
6626 (prevs (org-list-prevs-alist struct))
6627 (end (org-list-get-bottom-point struct)))
6628 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6629 (org-list-get-all-items (point) struct prevs))
6630 (goto-char end))))))
6631 (message "CHILDREN")
6632 (save-excursion
6633 (goto-char eos)
6634 (outline-next-heading)
6635 (if (outline-invisible-p) (org-flag-heading nil)))
6636 (setq org-cycle-subtree-status 'children)
6637 (unless (org-before-first-heading-p)
6638 (run-hook-with-args 'org-cycle-hook 'children)))
6639 ((or children-skipped
6640 (and (eq last-command this-command)
6641 (eq org-cycle-subtree-status 'children)))
6642 ;; We just showed the children, or no children are there,
6643 ;; now show everything.
6644 (unless (org-before-first-heading-p)
6645 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6646 (outline-flag-region eoh eos nil)
6647 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6648 (setq org-cycle-subtree-status 'subtree)
6649 (unless (org-before-first-heading-p)
6650 (run-hook-with-args 'org-cycle-hook 'subtree)))
6652 ;; Default action: hide the subtree.
6653 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6654 (outline-flag-region eoh eos t)
6655 (message "FOLDED")
6656 (setq org-cycle-subtree-status 'folded)
6657 (unless (org-before-first-heading-p)
6658 (run-hook-with-args 'org-cycle-hook 'folded))))))
6660 ;;;###autoload
6661 (defun org-global-cycle (&optional arg)
6662 "Cycle the global visibility. For details see `org-cycle'.
6663 With \\[universal-argument] prefix arg, switch to startup visibility.
6664 With a numeric prefix, show all headlines up to that level."
6665 (interactive "P")
6666 (let ((org-cycle-include-plain-lists
6667 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6668 (cond
6669 ((integerp arg)
6670 (show-all)
6671 (hide-sublevels arg)
6672 (setq org-cycle-global-status 'contents))
6673 ((equal arg '(4))
6674 (org-set-startup-visibility)
6675 (message "Startup visibility, plus VISIBILITY properties."))
6677 (org-cycle '(4))))))
6679 (defun org-set-startup-visibility ()
6680 "Set the visibility required by startup options and properties."
6681 (cond
6682 ((eq org-startup-folded t)
6683 (org-cycle '(4)))
6684 ((eq org-startup-folded 'content)
6685 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6686 (org-cycle '(4)) (org-cycle '(4)))))
6687 (unless (eq org-startup-folded 'showeverything)
6688 (if org-hide-block-startup (org-hide-block-all))
6689 (org-set-visibility-according-to-property 'no-cleanup)
6690 (org-cycle-hide-archived-subtrees 'all)
6691 (org-cycle-hide-drawers 'all)
6692 (org-cycle-show-empty-lines t)))
6694 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6695 "Switch subtree visibilities according to :VISIBILITY: property."
6696 (interactive)
6697 (let (org-show-entry-below state)
6698 (save-excursion
6699 (goto-char (point-min))
6700 (while (re-search-forward
6701 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6702 nil t)
6703 (setq state (match-string 1))
6704 (save-excursion
6705 (org-back-to-heading t)
6706 (hide-subtree)
6707 (org-reveal)
6708 (cond
6709 ((equal state '("fold" "folded"))
6710 (hide-subtree))
6711 ((equal state "children")
6712 (org-show-hidden-entry)
6713 (show-children))
6714 ((equal state "content")
6715 (save-excursion
6716 (save-restriction
6717 (org-narrow-to-subtree)
6718 (org-content))))
6719 ((member state '("all" "showall"))
6720 (show-subtree)))))
6721 (unless no-cleanup
6722 (org-cycle-hide-archived-subtrees 'all)
6723 (org-cycle-hide-drawers 'all)
6724 (org-cycle-show-empty-lines 'all)))))
6726 ;; This function uses outline-regexp instead of the more fundamental
6727 ;; org-outline-regexp so that org-cycle-global works outside of Org
6728 ;; buffers, where outline-regexp is needed.
6729 (defun org-overview ()
6730 "Switch to overview mode, showing only top-level headlines.
6731 Really, this shows all headlines with level equal or greater than the level
6732 of the first headline in the buffer. This is important, because if the
6733 first headline is not level one, then (hide-sublevels 1) gives confusing
6734 results."
6735 (interactive)
6736 (let ((l (org-current-line))
6737 (level (save-excursion
6738 (goto-char (point-min))
6739 (if (re-search-forward (concat "^" outline-regexp) nil t)
6740 (progn
6741 (goto-char (match-beginning 0))
6742 (funcall outline-level))))))
6743 (and level (hide-sublevels level))
6744 (recenter '(4))
6745 (org-goto-line l)))
6747 (defun org-content (&optional arg)
6748 "Show all headlines in the buffer, like a table of contents.
6749 With numerical argument N, show content up to level N."
6750 (interactive "P")
6751 (save-excursion
6752 ;; Visit all headings and show their offspring
6753 (and (integerp arg) (org-overview))
6754 (goto-char (point-max))
6755 (catch 'exit
6756 (while (and (progn (condition-case nil
6757 (outline-previous-visible-heading 1)
6758 (error (goto-char (point-min))))
6760 (looking-at org-outline-regexp))
6761 (if (integerp arg)
6762 (show-children (1- arg))
6763 (show-branches))
6764 (if (bobp) (throw 'exit nil))))))
6767 (defun org-optimize-window-after-visibility-change (state)
6768 "Adjust the window after a change in outline visibility.
6769 This function is the default value of the hook `org-cycle-hook'."
6770 (when (get-buffer-window (current-buffer))
6771 (cond
6772 ((eq state 'content) nil)
6773 ((eq state 'all) nil)
6774 ((eq state 'folded) nil)
6775 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6776 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6778 (defun org-remove-empty-overlays-at (pos)
6779 "Remove outline overlays that do not contain non-white stuff."
6780 (mapc
6781 (lambda (o)
6782 (and (eq 'outline (overlay-get o 'invisible))
6783 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6784 (overlay-end o))))
6785 (delete-overlay o)))
6786 (overlays-at pos)))
6788 (defun org-clean-visibility-after-subtree-move ()
6789 "Fix visibility issues after moving a subtree."
6790 ;; First, find a reasonable region to look at:
6791 ;; Start two siblings above, end three below
6792 (let* ((beg (save-excursion
6793 (and (org-get-last-sibling)
6794 (org-get-last-sibling))
6795 (point)))
6796 (end (save-excursion
6797 (and (org-get-next-sibling)
6798 (org-get-next-sibling)
6799 (org-get-next-sibling))
6800 (if (org-at-heading-p)
6801 (point-at-eol)
6802 (point))))
6803 (level (looking-at "\\*+"))
6804 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6805 (save-excursion
6806 (save-restriction
6807 (narrow-to-region beg end)
6808 (when re
6809 ;; Properly fold already folded siblings
6810 (goto-char (point-min))
6811 (while (re-search-forward re nil t)
6812 (if (and (not (outline-invisible-p))
6813 (save-excursion
6814 (goto-char (point-at-eol)) (outline-invisible-p)))
6815 (hide-entry))))
6816 (org-cycle-show-empty-lines 'overview)
6817 (org-cycle-hide-drawers 'overview)))))
6819 (defun org-cycle-show-empty-lines (state)
6820 "Show empty lines above all visible headlines.
6821 The region to be covered depends on STATE when called through
6822 `org-cycle-hook'. Lisp program can use t for STATE to get the
6823 entire buffer covered. Note that an empty line is only shown if there
6824 are at least `org-cycle-separator-lines' empty lines before the headline."
6825 (when (not (= org-cycle-separator-lines 0))
6826 (save-excursion
6827 (let* ((n (abs org-cycle-separator-lines))
6828 (re (cond
6829 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6830 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6831 (t (let ((ns (number-to-string (- n 2))))
6832 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6833 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6834 beg end b e)
6835 (cond
6836 ((memq state '(overview contents t))
6837 (setq beg (point-min) end (point-max)))
6838 ((memq state '(children folded))
6839 (setq beg (point) end (progn (org-end-of-subtree t t)
6840 (beginning-of-line 2)
6841 (point)))))
6842 (when beg
6843 (goto-char beg)
6844 (while (re-search-forward re end t)
6845 (unless (get-char-property (match-end 1) 'invisible)
6846 (setq e (match-end 1))
6847 (if (< org-cycle-separator-lines 0)
6848 (setq b (save-excursion
6849 (goto-char (match-beginning 0))
6850 (org-back-over-empty-lines)
6851 (if (save-excursion
6852 (goto-char (max (point-min) (1- (point))))
6853 (org-at-heading-p))
6854 (1- (point))
6855 (point))))
6856 (setq b (match-beginning 1)))
6857 (outline-flag-region b e nil)))))))
6858 ;; Never hide empty lines at the end of the file.
6859 (save-excursion
6860 (goto-char (point-max))
6861 (outline-previous-heading)
6862 (outline-end-of-heading)
6863 (if (and (looking-at "[ \t\n]+")
6864 (= (match-end 0) (point-max)))
6865 (outline-flag-region (point) (match-end 0) nil))))
6867 (defun org-show-empty-lines-in-parent ()
6868 "Move to the parent and re-show empty lines before visible headlines."
6869 (save-excursion
6870 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6871 (org-cycle-show-empty-lines context))))
6873 (defun org-files-list ()
6874 "Return `org-agenda-files' list, plus all open org-mode files.
6875 This is useful for operations that need to scan all of a user's
6876 open and agenda-wise Org files."
6877 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6878 (dolist (buf (buffer-list))
6879 (with-current-buffer buf
6880 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6881 (let ((file (expand-file-name (buffer-file-name))))
6882 (unless (member file files)
6883 (push file files))))))
6884 files))
6886 (defsubst org-entry-beginning-position ()
6887 "Return the beginning position of the current entry."
6888 (save-excursion (outline-back-to-heading t) (point)))
6890 (defsubst org-entry-end-position ()
6891 "Return the end position of the current entry."
6892 (save-excursion (outline-next-heading) (point)))
6894 (defun org-cycle-hide-drawers (state)
6895 "Re-hide all drawers after a visibility state change."
6896 (when (and (derived-mode-p 'org-mode)
6897 (not (memq state '(overview folded contents))))
6898 (save-excursion
6899 (let* ((globalp (memq state '(contents all)))
6900 (beg (if globalp (point-min) (point)))
6901 (end (if globalp (point-max)
6902 (if (eq state 'children)
6903 (save-excursion (outline-next-heading) (point))
6904 (org-end-of-subtree t)))))
6905 (goto-char beg)
6906 (while (re-search-forward org-drawer-regexp end t)
6907 (org-flag-drawer t))))))
6909 (defun org-cycle-hide-inline-tasks (state)
6910 "Re-hide inline task when switching to 'contents visibility state."
6911 (when (and (eq state 'contents)
6912 (boundp 'org-inlinetask-min-level)
6913 org-inlinetask-min-level)
6914 (hide-sublevels (1- org-inlinetask-min-level))))
6916 (defun org-flag-drawer (flag)
6917 "When FLAG is non-nil, hide the drawer we are within.
6918 Otherwise make it visible."
6919 (save-excursion
6920 (beginning-of-line 1)
6921 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6922 (let ((b (match-end 0)))
6923 (if (re-search-forward
6924 "^[ \t]*:END:"
6925 (save-excursion (outline-next-heading) (point)) t)
6926 (outline-flag-region b (point-at-eol) flag)
6927 (error ":END: line missing at position %s" b))))))
6929 (defun org-subtree-end-visible-p ()
6930 "Is the end of the current subtree visible?"
6931 (pos-visible-in-window-p
6932 (save-excursion (org-end-of-subtree t) (point))))
6934 (defun org-first-headline-recenter (&optional N)
6935 "Move cursor to the first headline and recenter the headline.
6936 Optional argument N means put the headline into the Nth line of the window."
6937 (goto-char (point-min))
6938 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6939 (beginning-of-line)
6940 (recenter (prefix-numeric-value N))))
6942 ;;; Saving and restoring visibility
6944 (defun org-outline-overlay-data (&optional use-markers)
6945 "Return a list of the locations of all outline overlays.
6946 These are overlays with the `invisible' property value `outline'.
6947 The return value is a list of cons cells, with start and stop
6948 positions for each overlay.
6949 If USE-MARKERS is set, return the positions as markers."
6950 (let (beg end)
6951 (save-excursion
6952 (save-restriction
6953 (widen)
6954 (delq nil
6955 (mapcar (lambda (o)
6956 (when (eq (overlay-get o 'invisible) 'outline)
6957 (setq beg (overlay-start o)
6958 end (overlay-end o))
6959 (and beg end (> end beg)
6960 (if use-markers
6961 (cons (move-marker (make-marker) beg)
6962 (move-marker (make-marker) end))
6963 (cons beg end)))))
6964 (overlays-in (point-min) (point-max))))))))
6966 (defun org-set-outline-overlay-data (data)
6967 "Create visibility overlays for all positions in DATA.
6968 DATA should have been made by `org-outline-overlay-data'."
6969 (let (o)
6970 (save-excursion
6971 (save-restriction
6972 (widen)
6973 (show-all)
6974 (mapc (lambda (c)
6975 (outline-flag-region (car c) (cdr c) t))
6976 data)))))
6978 ;;; Folding of blocks
6980 (defvar org-hide-block-overlays nil
6981 "Overlays hiding blocks.")
6982 (make-variable-buffer-local 'org-hide-block-overlays)
6984 (defun org-block-map (function &optional start end)
6985 "Call FUNCTION at the head of all source blocks in the current buffer.
6986 Optional arguments START and END can be used to limit the range."
6987 (let ((start (or start (point-min)))
6988 (end (or end (point-max))))
6989 (save-excursion
6990 (goto-char start)
6991 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6992 (save-excursion
6993 (save-match-data
6994 (goto-char (match-beginning 0))
6995 (funcall function)))))))
6997 (defun org-hide-block-toggle-all ()
6998 "Toggle the visibility of all blocks in the current buffer."
6999 (org-block-map #'org-hide-block-toggle))
7001 (defun org-hide-block-all ()
7002 "Fold all blocks in the current buffer."
7003 (interactive)
7004 (org-show-block-all)
7005 (org-block-map #'org-hide-block-toggle-maybe))
7007 (defun org-show-block-all ()
7008 "Unfold all blocks in the current buffer."
7009 (interactive)
7010 (mapc 'delete-overlay org-hide-block-overlays)
7011 (setq org-hide-block-overlays nil))
7013 (defun org-hide-block-toggle-maybe ()
7014 "Toggle visibility of block at point."
7015 (interactive)
7016 (let ((case-fold-search t))
7017 (if (save-excursion
7018 (beginning-of-line 1)
7019 (looking-at org-block-regexp))
7020 (progn (org-hide-block-toggle)
7021 t) ;; to signal that we took action
7022 nil))) ;; to signal that we did not
7024 (defun org-hide-block-toggle (&optional force)
7025 "Toggle the visibility of the current block."
7026 (interactive)
7027 (save-excursion
7028 (beginning-of-line)
7029 (if (re-search-forward org-block-regexp nil t)
7030 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7031 (end (match-end 0)) ;; end of entire body
7033 (if (memq t (mapcar (lambda (overlay)
7034 (eq (overlay-get overlay 'invisible)
7035 'org-hide-block))
7036 (overlays-at start)))
7037 (if (or (not force) (eq force 'off))
7038 (mapc (lambda (ov)
7039 (when (member ov org-hide-block-overlays)
7040 (setq org-hide-block-overlays
7041 (delq ov org-hide-block-overlays)))
7042 (when (eq (overlay-get ov 'invisible)
7043 'org-hide-block)
7044 (delete-overlay ov)))
7045 (overlays-at start)))
7046 (setq ov (make-overlay start end))
7047 (overlay-put ov 'invisible 'org-hide-block)
7048 ;; make the block accessible to isearch
7049 (overlay-put
7050 ov 'isearch-open-invisible
7051 (lambda (ov)
7052 (when (member ov org-hide-block-overlays)
7053 (setq org-hide-block-overlays
7054 (delq ov org-hide-block-overlays)))
7055 (when (eq (overlay-get ov 'invisible)
7056 'org-hide-block)
7057 (delete-overlay ov))))
7058 (push ov org-hide-block-overlays)))
7059 (error "Not looking at a source block"))))
7061 ;; org-tab-after-check-for-cycling-hook
7062 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7063 ;; Remove overlays when changing major mode
7064 (add-hook 'org-mode-hook
7065 (lambda () (org-add-hook 'change-major-mode-hook
7066 'org-show-block-all 'append 'local)))
7068 ;;; Org-goto
7070 (defvar org-goto-window-configuration nil)
7071 (defvar org-goto-marker nil)
7072 (defvar org-goto-map)
7073 (defun org-goto-map ()
7074 "Set the keymap `org-goto'."
7075 (setq org-goto-map
7076 (let ((map (make-sparse-keymap)))
7077 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7078 mouse-drag-region universal-argument org-occur))
7079 cmd)
7080 (while (setq cmd (pop cmds))
7081 (substitute-key-definition cmd cmd map global-map)))
7082 (suppress-keymap map)
7083 (org-defkey map "\C-m" 'org-goto-ret)
7084 (org-defkey map [(return)] 'org-goto-ret)
7085 (org-defkey map [(left)] 'org-goto-left)
7086 (org-defkey map [(right)] 'org-goto-right)
7087 (org-defkey map [(control ?g)] 'org-goto-quit)
7088 (org-defkey map "\C-i" 'org-cycle)
7089 (org-defkey map [(tab)] 'org-cycle)
7090 (org-defkey map [(down)] 'outline-next-visible-heading)
7091 (org-defkey map [(up)] 'outline-previous-visible-heading)
7092 (if org-goto-auto-isearch
7093 (if (fboundp 'define-key-after)
7094 (define-key-after map [t] 'org-goto-local-auto-isearch)
7095 nil)
7096 (org-defkey map "q" 'org-goto-quit)
7097 (org-defkey map "n" 'outline-next-visible-heading)
7098 (org-defkey map "p" 'outline-previous-visible-heading)
7099 (org-defkey map "f" 'outline-forward-same-level)
7100 (org-defkey map "b" 'outline-backward-same-level)
7101 (org-defkey map "u" 'outline-up-heading))
7102 (org-defkey map "/" 'org-occur)
7103 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7104 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7105 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7106 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7107 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7108 map)))
7110 (defconst org-goto-help
7111 "Browse buffer copy, to find location or copy text.%s
7112 RET=jump to location C-g=quit and return to previous location
7113 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7115 (defvar org-goto-start-pos) ; dynamically scoped parameter
7117 ;; FIXME: Docstring does not mention both interfaces
7118 (defun org-goto (&optional alternative-interface)
7119 "Look up a different location in the current file, keeping current visibility.
7121 When you want look-up or go to a different location in a
7122 document, the fastest way is often to fold the entire buffer and
7123 then dive into the tree. This method has the disadvantage, that
7124 the previous location will be folded, which may not be what you
7125 want.
7127 This command works around this by showing a copy of the current
7128 buffer in an indirect buffer, in overview mode. You can dive
7129 into the tree in that copy, use org-occur and incremental search
7130 to find a location. When pressing RET or `Q', the command
7131 returns to the original buffer in which the visibility is still
7132 unchanged. After RET it will also jump to the location selected
7133 in the indirect buffer and expose the headline hierarchy above.
7135 With a prefix argument, use the alternative interface: e.g. if
7136 `org-goto-interface' is 'outline use 'outline-path-completion."
7137 (interactive "P")
7138 (org-goto-map)
7139 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7140 (org-refile-use-outline-path t)
7141 (org-refile-target-verify-function nil)
7142 (interface
7143 (if (not alternative-interface)
7144 org-goto-interface
7145 (if (eq org-goto-interface 'outline)
7146 'outline-path-completion
7147 'outline)))
7148 (org-goto-start-pos (point))
7149 (selected-point
7150 (if (eq interface 'outline)
7151 (car (org-get-location (current-buffer) org-goto-help))
7152 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7153 (org-refile-check-position pa)
7154 (nth 3 pa)))))
7155 (if selected-point
7156 (progn
7157 (org-mark-ring-push org-goto-start-pos)
7158 (goto-char selected-point)
7159 (if (or (outline-invisible-p) (org-invisible-p2))
7160 (org-show-context 'org-goto)))
7161 (message "Quit"))))
7163 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7164 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7165 (defvar org-goto-local-auto-isearch-map) ; defined below
7167 (defun org-get-location (buf help)
7168 "Let the user select a location in the Org-mode buffer BUF.
7169 This function uses a recursive edit. It returns the selected position
7170 or nil."
7171 (org-no-popups
7172 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7173 (isearch-hide-immediately nil)
7174 (isearch-search-fun-function
7175 (lambda () 'org-goto-local-search-headings))
7176 (org-goto-selected-point org-goto-exit-command))
7177 (save-excursion
7178 (save-window-excursion
7179 (delete-other-windows)
7180 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7181 (org-pop-to-buffer-same-window
7182 (condition-case nil
7183 (make-indirect-buffer (current-buffer) "*org-goto*")
7184 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7185 (with-output-to-temp-buffer "*Org Help*"
7186 (princ (format help (if org-goto-auto-isearch
7187 " Just type for auto-isearch."
7188 " n/p/f/b/u to navigate, q to quit."))))
7189 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7190 (setq buffer-read-only nil)
7191 (let ((org-startup-truncated t)
7192 (org-startup-folded nil)
7193 (org-startup-align-all-tables nil))
7194 (org-mode)
7195 (org-overview))
7196 (setq buffer-read-only t)
7197 (if (and (boundp 'org-goto-start-pos)
7198 (integer-or-marker-p org-goto-start-pos))
7199 (let ((org-show-hierarchy-above t)
7200 (org-show-siblings t)
7201 (org-show-following-heading t))
7202 (goto-char org-goto-start-pos)
7203 (and (outline-invisible-p) (org-show-context)))
7204 (goto-char (point-min)))
7205 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7206 (message "Select location and press RET")
7207 (use-local-map org-goto-map)
7208 (recursive-edit)))
7209 (kill-buffer "*org-goto*")
7210 (cons org-goto-selected-point org-goto-exit-command))))
7212 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7213 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7214 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7215 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7217 (defun org-goto-local-search-headings (string bound noerror)
7218 "Search and make sure that any matches are in headlines."
7219 (catch 'return
7220 (while (if isearch-forward
7221 (search-forward string bound noerror)
7222 (search-backward string bound noerror))
7223 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7224 (and (member :headline context)
7225 (not (member :tags context))))
7226 (throw 'return (point))))))
7228 (defun org-goto-local-auto-isearch ()
7229 "Start isearch."
7230 (interactive)
7231 (goto-char (point-min))
7232 (let ((keys (this-command-keys)))
7233 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7234 (isearch-mode t)
7235 (isearch-process-search-char (string-to-char keys)))))
7237 (defun org-goto-ret (&optional arg)
7238 "Finish `org-goto' by going to the new location."
7239 (interactive "P")
7240 (setq org-goto-selected-point (point)
7241 org-goto-exit-command 'return)
7242 (throw 'exit nil))
7244 (defun org-goto-left ()
7245 "Finish `org-goto' by going to the new location."
7246 (interactive)
7247 (if (org-at-heading-p)
7248 (progn
7249 (beginning-of-line 1)
7250 (setq org-goto-selected-point (point)
7251 org-goto-exit-command 'left)
7252 (throw 'exit nil))
7253 (error "Not on a heading")))
7255 (defun org-goto-right ()
7256 "Finish `org-goto' by going to the new location."
7257 (interactive)
7258 (if (org-at-heading-p)
7259 (progn
7260 (setq org-goto-selected-point (point)
7261 org-goto-exit-command 'right)
7262 (throw 'exit nil))
7263 (error "Not on a heading")))
7265 (defun org-goto-quit ()
7266 "Finish `org-goto' without cursor motion."
7267 (interactive)
7268 (setq org-goto-selected-point nil)
7269 (setq org-goto-exit-command 'quit)
7270 (throw 'exit nil))
7272 ;;; Indirect buffer display of subtrees
7274 (defvar org-indirect-dedicated-frame nil
7275 "This is the frame being used for indirect tree display.")
7276 (defvar org-last-indirect-buffer nil)
7278 (defun org-tree-to-indirect-buffer (&optional arg)
7279 "Create indirect buffer and narrow it to current subtree.
7280 With a numerical prefix ARG, go up to this level and then take that tree.
7281 If ARG is negative, go up that many levels.
7283 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7284 indirect buffer previously made with this command, to avoid proliferation of
7285 indirect buffers. However, when you call the command with a \
7286 \\[universal-argument] prefix, or
7287 when `org-indirect-buffer-display' is `new-frame', the last buffer
7288 is kept so that you can work with several indirect buffers at the same time.
7289 If `org-indirect-buffer-display' is `dedicated-frame', the \
7290 \\[universal-argument] prefix also
7291 requests that a new frame be made for the new buffer, so that the dedicated
7292 frame is not changed."
7293 (interactive "P")
7294 (let ((cbuf (current-buffer))
7295 (cwin (selected-window))
7296 (pos (point))
7297 beg end level heading ibuf)
7298 (save-excursion
7299 (org-back-to-heading t)
7300 (when (numberp arg)
7301 (setq level (org-outline-level))
7302 (if (< arg 0) (setq arg (+ level arg)))
7303 (while (> (setq level (org-outline-level)) arg)
7304 (org-up-heading-safe)))
7305 (setq beg (point)
7306 heading (org-get-heading))
7307 (org-end-of-subtree t t)
7308 (if (org-at-heading-p) (backward-char 1))
7309 (setq end (point)))
7310 (if (and (buffer-live-p org-last-indirect-buffer)
7311 (not (eq org-indirect-buffer-display 'new-frame))
7312 (not arg))
7313 (kill-buffer org-last-indirect-buffer))
7314 (setq ibuf (org-get-indirect-buffer cbuf)
7315 org-last-indirect-buffer ibuf)
7316 (cond
7317 ((or (eq org-indirect-buffer-display 'new-frame)
7318 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7319 (select-frame (make-frame))
7320 (delete-other-windows)
7321 (org-pop-to-buffer-same-window ibuf)
7322 (org-set-frame-title heading))
7323 ((eq org-indirect-buffer-display 'dedicated-frame)
7324 (raise-frame
7325 (select-frame (or (and org-indirect-dedicated-frame
7326 (frame-live-p org-indirect-dedicated-frame)
7327 org-indirect-dedicated-frame)
7328 (setq org-indirect-dedicated-frame (make-frame)))))
7329 (delete-other-windows)
7330 (org-pop-to-buffer-same-window ibuf)
7331 (org-set-frame-title (concat "Indirect: " heading)))
7332 ((eq org-indirect-buffer-display 'current-window)
7333 (org-pop-to-buffer-same-window ibuf))
7334 ((eq org-indirect-buffer-display 'other-window)
7335 (pop-to-buffer ibuf))
7336 (t (error "Invalid value")))
7337 (if (featurep 'xemacs)
7338 (save-excursion (org-mode) (turn-on-font-lock)))
7339 (narrow-to-region beg end)
7340 (show-all)
7341 (goto-char pos)
7342 (run-hook-with-args 'org-cycle-hook 'all)
7343 (and (window-live-p cwin) (select-window cwin))))
7345 (defun org-get-indirect-buffer (&optional buffer)
7346 (setq buffer (or buffer (current-buffer)))
7347 (let ((n 1) (base (buffer-name buffer)) bname)
7348 (while (buffer-live-p
7349 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7350 (setq n (1+ n)))
7351 (condition-case nil
7352 (make-indirect-buffer buffer bname 'clone)
7353 (error (make-indirect-buffer buffer bname)))))
7355 (defun org-set-frame-title (title)
7356 "Set the title of the current frame to the string TITLE."
7357 ;; FIXME: how to name a single frame in XEmacs???
7358 (unless (featurep 'xemacs)
7359 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7361 ;;;; Structure editing
7363 ;;; Inserting headlines
7365 (defun org-previous-line-empty-p (&optional next)
7366 "Is the previous line a blank line?
7367 When NEXT is non-nil, check the next line instead."
7368 (save-excursion
7369 (and (not (bobp))
7370 (or (beginning-of-line (if next 2 0)) t)
7371 (save-match-data
7372 (looking-at "[ \t]*$")))))
7374 (defun org-insert-heading (&optional arg invisible-ok)
7375 "Insert a new heading or item with same depth at point.
7376 If point is in a plain list and ARG is nil, create a new list item.
7377 With one universal prefix argument, insert a heading even in lists.
7378 With two universal prefix arguments, insert the heading at the end
7379 of the parent subtree.
7381 If point is at the beginning of a headline, insert a sibling before
7382 the current headline. If point is not at the beginning, split the line
7383 and create a new headline with the text in the current line after point
7384 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7386 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7387 This is important for non-interactive uses of the command."
7388 (interactive "P")
7389 (if (or (= (buffer-size) 0)
7390 (and (not (save-excursion
7391 (and (ignore-errors (org-back-to-heading invisible-ok))
7392 (org-at-heading-p))))
7393 (or arg (not (org-in-item-p)))))
7394 (progn
7395 (insert
7396 (if (org-previous-line-empty-p) "" "\n")
7397 (if (org-in-src-block-p) ",* " "* "))
7398 (run-hooks 'org-insert-heading-hook))
7399 (when (or arg
7400 (not (org-insert-item
7401 (save-excursion
7402 (beginning-of-line)
7403 (looking-at org-list-full-item-re)
7404 (match-string 3)))))
7405 (let* ((empty-line-p nil)
7406 (eops (equal arg '(16))) ; insert at end of parent subtree
7407 (org-insert-heading-respect-content
7408 (or (not (null arg)) org-insert-heading-respect-content))
7409 (level nil)
7410 (on-heading (org-at-heading-p))
7411 (head (save-excursion
7412 (condition-case nil
7413 (progn
7414 (org-back-to-heading invisible-ok)
7415 (when (and (not on-heading)
7416 (featurep 'org-inlinetask)
7417 (integerp org-inlinetask-min-level)
7418 (>= (length (match-string 0))
7419 org-inlinetask-min-level))
7420 ;; Find a heading level before the inline task
7421 (while (and (setq level (org-up-heading-safe))
7422 (>= level org-inlinetask-min-level)))
7423 (if (org-at-heading-p)
7424 (org-back-to-heading invisible-ok)
7425 (error "This should not happen")))
7426 (unless (and (save-excursion
7427 (save-match-data
7428 (org-backward-heading-same-level 1 invisible-ok))
7429 (= (point) (match-beginning 0)))
7430 (not (org-previous-line-empty-p t)))
7431 (setq empty-line-p (org-previous-line-empty-p)))
7432 (match-string 0))
7433 (error "* "))))
7434 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7435 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7436 pos hide-previous previous-pos)
7437 (cond
7438 ;; At the beginning of a heading, open a new line for insertiong
7439 ((and (bolp) (org-at-heading-p)
7440 (not eops)
7441 (or (bobp)
7442 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7443 (open-line (if blank 2 1)))
7445 (save-excursion
7446 (setq previous-pos (point-at-bol))
7447 (end-of-line)
7448 (setq hide-previous (outline-invisible-p)))
7449 (and org-insert-heading-respect-content
7450 (save-excursion
7451 (while (outline-invisible-p)
7452 (org-show-subtree)
7453 (org-up-heading-safe))))
7454 (let ((split
7455 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7456 (save-excursion
7457 (let ((p (point)))
7458 (goto-char (point-at-bol))
7459 (and (looking-at org-complex-heading-regexp)
7460 (match-beginning 4)
7461 (> p (match-beginning 4)))))))
7462 tags pos)
7463 (cond
7464 ;; Insert a new line, possibly at end of parent subtree
7465 (org-insert-heading-respect-content
7466 (if (not eops)
7467 (progn
7468 (org-end-of-subtree nil t)
7469 (and (looking-at "^\\*") (backward-char 1))
7470 (while (and (not (bobp))
7471 ;; Don't delete spaces in empty headlines
7472 (not (looking-back org-outline-regexp))
7473 (member (char-before) '(?\ ?\t ?\n)))
7474 (backward-delete-char 1)))
7475 (let ((p (point)))
7476 (org-up-heading-safe)
7477 (if (= p (point))
7478 (goto-char (point-max))
7479 (org-end-of-subtree nil t))))
7480 (when (featurep 'org-inlinetask)
7481 (while (and (not (eobp))
7482 (looking-at "\\(\\*+\\)[ \t]+")
7483 (>= (length (match-string 1))
7484 org-inlinetask-min-level))
7485 (org-end-of-subtree nil t)))
7486 (or (bolp) (newline))
7487 (or (org-previous-line-empty-p)
7488 (and blank (newline)))
7489 (if (or empty-line-p eops) (open-line 1)))
7490 ;; Insert a headling containing text after point
7491 ((org-at-heading-p)
7492 (when hide-previous
7493 (show-children)
7494 (org-show-entry))
7495 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7496 (setq tags (and (match-end 2) (match-string 2)))
7497 (and (match-end 1)
7498 (delete-region (match-beginning 1) (match-end 1)))
7499 (setq pos (point-at-bol))
7500 (or split (end-of-line 1))
7501 (delete-horizontal-space)
7502 (if (string-match "\\`\\*+\\'"
7503 (buffer-substring (point-at-bol) (point)))
7504 (insert " "))
7505 (newline (if blank 2 1))
7506 (when tags
7507 (save-excursion
7508 (goto-char pos)
7509 (end-of-line 1)
7510 (insert " " tags)
7511 (org-set-tags nil 'align))))
7513 (or split (end-of-line 1))
7514 (newline (if blank 2 1)))))))
7515 (insert head) (just-one-space)
7516 (setq pos (point))
7517 (end-of-line 1)
7518 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7519 (when (and org-insert-heading-respect-content hide-previous)
7520 (save-excursion
7521 (goto-char previous-pos)
7522 (hide-subtree)))
7523 (run-hooks 'org-insert-heading-hook)))))
7525 (defun org-get-heading (&optional no-tags no-todo)
7526 "Return the heading of the current entry, without the stars.
7527 When NO-TAGS is non-nil, don't include tags.
7528 When NO-TODO is non-nil, don't include TODO keywords."
7529 (save-excursion
7530 (org-back-to-heading t)
7531 (cond
7532 ((and no-tags no-todo)
7533 (looking-at org-complex-heading-regexp)
7534 (match-string 4))
7535 (no-tags
7536 (looking-at (concat org-outline-regexp
7537 "\\(.*?\\)"
7538 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7539 (match-string 1))
7540 (no-todo
7541 (looking-at org-todo-line-regexp)
7542 (match-string 3))
7543 (t (looking-at org-heading-regexp)
7544 (match-string 2)))))
7546 (defvar orgstruct-mode) ; defined below
7548 (defun org-heading-components ()
7549 "Return the components of the current heading.
7550 This is a list with the following elements:
7551 - the level as an integer
7552 - the reduced level, different if `org-odd-levels-only' is set.
7553 - the TODO keyword, or nil
7554 - the priority character, like ?A, or nil if no priority is given
7555 - the headline text itself, or the tags string if no headline text
7556 - the tags string, or nil."
7557 (save-excursion
7558 (org-back-to-heading t)
7559 (if (let (case-fold-search)
7560 (looking-at
7561 (if orgstruct-mode
7562 org-heading-regexp
7563 org-complex-heading-regexp)))
7564 (if orgstruct-mode
7565 (list (length (match-string 1))
7566 (org-reduced-level (length (match-string 1)))
7569 (match-string 2)
7570 nil)
7571 (list (length (match-string 1))
7572 (org-reduced-level (length (match-string 1)))
7573 (org-match-string-no-properties 2)
7574 (and (match-end 3) (aref (match-string 3) 2))
7575 (org-match-string-no-properties 4)
7576 (org-match-string-no-properties 5))))))
7578 (defun org-get-entry ()
7579 "Get the entry text, after heading, entire subtree."
7580 (save-excursion
7581 (org-back-to-heading t)
7582 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7584 (defun org-insert-heading-after-current ()
7585 "Insert a new heading with same level as current, after current subtree."
7586 (interactive)
7587 (org-back-to-heading)
7588 (org-insert-heading)
7589 (org-move-subtree-down)
7590 (end-of-line 1))
7592 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7593 "Insert heading with `org-insert-heading-respect-content' set to t."
7594 (interactive "P")
7595 (let ((org-insert-heading-respect-content t))
7596 (org-insert-heading arg invisible-ok)))
7598 (defun org-insert-todo-heading-respect-content (&optional force-state)
7599 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7600 (interactive "P")
7601 (let ((org-insert-heading-respect-content t))
7602 (org-insert-todo-heading force-state t)))
7604 (defun org-insert-todo-heading (arg &optional force-heading)
7605 "Insert a new heading with the same level and TODO state as current heading.
7606 If the heading has no TODO state, or if the state is DONE, use the first
7607 state (TODO by default). Also one prefix arg, force first state. With two
7608 prefix args, force inserting at the end of the parent subtree."
7609 (interactive "P")
7610 (when (or force-heading (not (org-insert-item 'checkbox)))
7611 (org-insert-heading (or (and (equal arg '(16)) '(16))
7612 force-heading))
7613 (save-excursion
7614 (org-back-to-heading)
7615 (outline-previous-heading)
7616 (looking-at org-todo-line-regexp))
7617 (let*
7618 ((new-mark-x
7619 (if (or arg
7620 (not (match-beginning 2))
7621 (member (match-string 2) org-done-keywords))
7622 (car org-todo-keywords-1)
7623 (match-string 2)))
7624 (new-mark
7626 (run-hook-with-args-until-success
7627 'org-todo-get-default-hook new-mark-x nil)
7628 new-mark-x)))
7629 (beginning-of-line 1)
7630 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7631 (if org-treat-insert-todo-heading-as-state-change
7632 (org-todo new-mark)
7633 (insert new-mark " "))))
7634 (when org-provide-todo-statistics
7635 (org-update-parent-todo-statistics))))
7637 (defun org-insert-subheading (arg)
7638 "Insert a new subheading and demote it.
7639 Works for outline headings and for plain lists alike."
7640 (interactive "P")
7641 (org-insert-heading arg)
7642 (cond
7643 ((org-at-heading-p) (org-do-demote))
7644 ((org-at-item-p) (org-indent-item))))
7646 (defun org-insert-todo-subheading (arg)
7647 "Insert a new subheading with TODO keyword or checkbox and demote it.
7648 Works for outline headings and for plain lists alike."
7649 (interactive "P")
7650 (org-insert-todo-heading arg)
7651 (cond
7652 ((org-at-heading-p) (org-do-demote))
7653 ((org-at-item-p) (org-indent-item))))
7655 ;;; Promotion and Demotion
7657 (defvar org-after-demote-entry-hook nil
7658 "Hook run after an entry has been demoted.
7659 The cursor will be at the beginning of the entry.
7660 When a subtree is being demoted, the hook will be called for each node.")
7662 (defvar org-after-promote-entry-hook nil
7663 "Hook run after an entry has been promoted.
7664 The cursor will be at the beginning of the entry.
7665 When a subtree is being promoted, the hook will be called for each node.")
7667 (defun org-promote-subtree ()
7668 "Promote the entire subtree.
7669 See also `org-promote'."
7670 (interactive)
7671 (save-excursion
7672 (org-with-limited-levels (org-map-tree 'org-promote)))
7673 (org-fix-position-after-promote))
7675 (defun org-demote-subtree ()
7676 "Demote the entire subtree. See `org-demote'.
7677 See also `org-promote'."
7678 (interactive)
7679 (save-excursion
7680 (org-with-limited-levels (org-map-tree 'org-demote)))
7681 (org-fix-position-after-promote))
7684 (defun org-do-promote ()
7685 "Promote the current heading higher up the tree.
7686 If the region is active in `transient-mark-mode', promote all headings
7687 in the region."
7688 (interactive)
7689 (save-excursion
7690 (if (org-region-active-p)
7691 (org-map-region 'org-promote (region-beginning) (region-end))
7692 (org-promote)))
7693 (org-fix-position-after-promote))
7695 (defun org-do-demote ()
7696 "Demote the current heading lower down the tree.
7697 If the region is active in `transient-mark-mode', demote all headings
7698 in the region."
7699 (interactive)
7700 (save-excursion
7701 (if (org-region-active-p)
7702 (org-map-region 'org-demote (region-beginning) (region-end))
7703 (org-demote)))
7704 (org-fix-position-after-promote))
7706 (defun org-fix-position-after-promote ()
7707 "Make sure that after pro/demotion cursor position is right."
7708 (let ((pos (point)))
7709 (when (save-excursion
7710 (beginning-of-line 1)
7711 (looking-at org-todo-line-regexp)
7712 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7713 (cond ((eobp) (insert " "))
7714 ((eolp) (insert " "))
7715 ((equal (char-after) ?\ ) (forward-char 1))))))
7717 (defun org-current-level ()
7718 "Return the level of the current entry, or nil if before the first headline.
7719 The level is the number of stars at the beginning of the headline."
7720 (save-excursion
7721 (org-with-limited-levels
7722 (if (ignore-errors (org-back-to-heading t))
7723 (funcall outline-level)))))
7725 (defun org-get-previous-line-level ()
7726 "Return the outline depth of the last headline before the current line.
7727 Returns 0 for the first headline in the buffer, and nil if before the
7728 first headline."
7729 (let ((current-level (org-current-level))
7730 (prev-level (when (> (line-number-at-pos) 1)
7731 (save-excursion
7732 (beginning-of-line 0)
7733 (org-current-level)))))
7734 (cond ((null current-level) nil) ; Before first headline
7735 ((null prev-level) 0) ; At first headline
7736 (prev-level))))
7738 (defun org-reduced-level (l)
7739 "Compute the effective level of a heading.
7740 This takes into account the setting of `org-odd-levels-only'."
7741 (cond
7742 ((zerop l) 0)
7743 (org-odd-levels-only (1+ (floor (/ l 2))))
7744 (t l)))
7746 (defun org-level-increment ()
7747 "Return the number of stars that will be added or removed at a
7748 time to headlines when structure editing, based on the value of
7749 `org-odd-levels-only'."
7750 (if org-odd-levels-only 2 1))
7752 (defun org-get-valid-level (level &optional change)
7753 "Rectify a level change under the influence of `org-odd-levels-only'
7754 LEVEL is a current level, CHANGE is by how much the level should be
7755 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7756 even level numbers will become the next higher odd number."
7757 (if org-odd-levels-only
7758 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7759 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7760 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7761 (max 1 (+ level (or change 0)))))
7763 (if (boundp 'define-obsolete-function-alias)
7764 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7765 (define-obsolete-function-alias 'org-get-legal-level
7766 'org-get-valid-level)
7767 (define-obsolete-function-alias 'org-get-legal-level
7768 'org-get-valid-level "23.1")))
7770 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7771 ;; ̀org-with-limited-levels'
7772 (defun org-promote ()
7773 "Promote the current heading higher up the tree.
7774 If the region is active in `transient-mark-mode', promote all headings
7775 in the region."
7776 (org-back-to-heading t)
7777 (let* ((level (save-match-data (funcall outline-level)))
7778 (after-change-functions (remove 'flyspell-after-change-function
7779 after-change-functions))
7780 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7781 (diff (abs (- level (length up-head) -1))))
7782 (cond ((and (= level 1) org-called-with-limited-levels
7783 org-allow-promoting-top-level-subtree)
7784 (replace-match "# " nil t))
7785 ((= level 1)
7786 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7787 (t (replace-match up-head nil t)))
7788 ;; Fixup tag positioning
7789 (unless (= level 1)
7790 (and org-auto-align-tags (org-set-tags nil t))
7791 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7792 (run-hooks 'org-after-promote-entry-hook)))
7794 (defun org-demote ()
7795 "Demote the current heading lower down the tree.
7796 If the region is active in `transient-mark-mode', demote all headings
7797 in the region."
7798 (org-back-to-heading t)
7799 (let* ((level (save-match-data (funcall outline-level)))
7800 (after-change-functions (remove 'flyspell-after-change-function
7801 after-change-functions))
7802 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7803 (diff (abs (- level (length down-head) -1))))
7804 (replace-match down-head nil t)
7805 ;; Fixup tag positioning
7806 (and org-auto-align-tags (org-set-tags nil t))
7807 (if org-adapt-indentation (org-fixup-indentation diff))
7808 (run-hooks 'org-after-demote-entry-hook)))
7810 (defun org-cycle-level ()
7811 "Cycle the level of an empty headline through possible states.
7812 This goes first to child, then to parent, level, then up the hierarchy.
7813 After top level, it switches back to sibling level."
7814 (interactive)
7815 (let ((org-adapt-indentation nil))
7816 (when (org-point-at-end-of-empty-headline)
7817 (setq this-command 'org-cycle-level) ; Only needed for caching
7818 (let ((cur-level (org-current-level))
7819 (prev-level (org-get-previous-line-level)))
7820 (cond
7821 ;; If first headline in file, promote to top-level.
7822 ((= prev-level 0)
7823 (loop repeat (/ (- cur-level 1) (org-level-increment))
7824 do (org-do-promote)))
7825 ;; If same level as prev, demote one.
7826 ((= prev-level cur-level)
7827 (org-do-demote))
7828 ;; If parent is top-level, promote to top level if not already.
7829 ((= prev-level 1)
7830 (loop repeat (/ (- cur-level 1) (org-level-increment))
7831 do (org-do-promote)))
7832 ;; If top-level, return to prev-level.
7833 ((= cur-level 1)
7834 (loop repeat (/ (- prev-level 1) (org-level-increment))
7835 do (org-do-demote)))
7836 ;; If less than prev-level, promote one.
7837 ((< cur-level prev-level)
7838 (org-do-promote))
7839 ;; If deeper than prev-level, promote until higher than
7840 ;; prev-level.
7841 ((> cur-level prev-level)
7842 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7843 do (org-do-promote))))
7844 t))))
7846 (defun org-map-tree (fun)
7847 "Call FUN for every heading underneath the current one."
7848 (org-back-to-heading)
7849 (let ((level (funcall outline-level)))
7850 (save-excursion
7851 (funcall fun)
7852 (while (and (progn
7853 (outline-next-heading)
7854 (> (funcall outline-level) level))
7855 (not (eobp)))
7856 (funcall fun)))))
7858 (defun org-map-region (fun beg end)
7859 "Call FUN for every heading between BEG and END."
7860 (let ((org-ignore-region t))
7861 (save-excursion
7862 (setq end (copy-marker end))
7863 (goto-char beg)
7864 (if (and (re-search-forward org-outline-regexp-bol nil t)
7865 (< (point) end))
7866 (funcall fun))
7867 (while (and (progn
7868 (outline-next-heading)
7869 (< (point) end))
7870 (not (eobp)))
7871 (funcall fun)))))
7873 (defvar org-property-end-re) ; silence byte-compiler
7874 (defun org-fixup-indentation (diff)
7875 "Change the indentation in the current entry by DIFF.
7876 However, if any line in the current entry has no indentation, or if it
7877 would end up with no indentation after the change, nothing at all is done."
7878 (save-excursion
7879 (let ((end (save-excursion (outline-next-heading)
7880 (point-marker)))
7881 (prohibit (if (> diff 0)
7882 "^\\S-"
7883 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7884 col)
7885 (unless (save-excursion (end-of-line 1)
7886 (re-search-forward prohibit end t))
7887 (while (and (< (point) end)
7888 (re-search-forward "^[ \t]+" end t))
7889 (goto-char (match-end 0))
7890 (setq col (current-column))
7891 (if (< diff 0) (replace-match ""))
7892 (org-indent-to-column (+ diff col))))
7893 (move-marker end nil))))
7895 (defun org-convert-to-odd-levels ()
7896 "Convert an org-mode file with all levels allowed to one with odd levels.
7897 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7898 level 5 etc."
7899 (interactive)
7900 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7901 (let ((outline-level 'org-outline-level)
7902 (org-odd-levels-only nil) n)
7903 (save-excursion
7904 (goto-char (point-min))
7905 (while (re-search-forward "^\\*\\*+ " nil t)
7906 (setq n (- (length (match-string 0)) 2))
7907 (while (>= (setq n (1- n)) 0)
7908 (org-demote))
7909 (end-of-line 1))))))
7911 (defun org-convert-to-oddeven-levels ()
7912 "Convert an org-mode file with only odd levels to one with odd/even levels.
7913 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7914 file contains a section with an even level, conversion would
7915 destroy the structure of the file. An error is signaled in this
7916 case."
7917 (interactive)
7918 (goto-char (point-min))
7919 ;; First check if there are no even levels
7920 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7921 (org-show-context t)
7922 (error "Not all levels are odd in this file. Conversion not possible"))
7923 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7924 (let ((outline-regexp org-outline-regexp)
7925 (outline-level 'org-outline-level)
7926 (org-odd-levels-only nil) n)
7927 (save-excursion
7928 (goto-char (point-min))
7929 (while (re-search-forward "^\\*\\*+ " nil t)
7930 (setq n (/ (1- (length (match-string 0))) 2))
7931 (while (>= (setq n (1- n)) 0)
7932 (org-promote))
7933 (end-of-line 1))))))
7935 (defun org-tr-level (n)
7936 "Make N odd if required."
7937 (if org-odd-levels-only (1+ (/ n 2)) n))
7939 ;;; Vertical tree motion, cutting and pasting of subtrees
7941 (defun org-move-subtree-up (&optional arg)
7942 "Move the current subtree up past ARG headlines of the same level."
7943 (interactive "p")
7944 (org-move-subtree-down (- (prefix-numeric-value arg))))
7946 (defun org-move-subtree-down (&optional arg)
7947 "Move the current subtree down past ARG headlines of the same level."
7948 (interactive "p")
7949 (setq arg (prefix-numeric-value arg))
7950 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7951 'org-get-last-sibling))
7952 (ins-point (make-marker))
7953 (cnt (abs arg))
7954 (col (current-column))
7955 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7956 ;; Select the tree
7957 (org-back-to-heading)
7958 (setq beg0 (point))
7959 (save-excursion
7960 (setq ne-beg (org-back-over-empty-lines))
7961 (setq beg (point)))
7962 (save-match-data
7963 (save-excursion (outline-end-of-heading)
7964 (setq folded (outline-invisible-p)))
7965 (outline-end-of-subtree))
7966 (outline-next-heading)
7967 (setq ne-end (org-back-over-empty-lines))
7968 (setq end (point))
7969 (goto-char beg0)
7970 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7971 ;; include less whitespace
7972 (save-excursion
7973 (goto-char beg)
7974 (forward-line (- ne-beg ne-end))
7975 (setq beg (point))))
7976 ;; Find insertion point, with error handling
7977 (while (> cnt 0)
7978 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7979 (progn (goto-char beg0)
7980 (user-error "Cannot move past superior level or buffer limit")))
7981 (setq cnt (1- cnt)))
7982 (if (> arg 0)
7983 ;; Moving forward - still need to move over subtree
7984 (progn (org-end-of-subtree t t)
7985 (save-excursion
7986 (org-back-over-empty-lines)
7987 (or (bolp) (newline)))))
7988 (setq ne-ins (org-back-over-empty-lines))
7989 (move-marker ins-point (point))
7990 (setq txt (buffer-substring beg end))
7991 (org-save-markers-in-region beg end)
7992 (delete-region beg end)
7993 (org-remove-empty-overlays-at beg)
7994 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7995 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7996 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7997 (let ((bbb (point)))
7998 (insert-before-markers txt)
7999 (org-reinstall-markers-in-region bbb)
8000 (move-marker ins-point bbb))
8001 (or (bolp) (insert "\n"))
8002 (setq ins-end (point))
8003 (goto-char ins-point)
8004 (org-skip-whitespace)
8005 (when (and (< arg 0)
8006 (org-first-sibling-p)
8007 (> ne-ins ne-beg))
8008 ;; Move whitespace back to beginning
8009 (save-excursion
8010 (goto-char ins-end)
8011 (let ((kill-whole-line t))
8012 (kill-line (- ne-ins ne-beg)) (point)))
8013 (insert (make-string (- ne-ins ne-beg) ?\n)))
8014 (move-marker ins-point nil)
8015 (if folded
8016 (hide-subtree)
8017 (org-show-entry)
8018 (show-children)
8019 (org-cycle-hide-drawers 'children))
8020 (org-clean-visibility-after-subtree-move)
8021 ;; move back to the initial column we were at
8022 (move-to-column col)))
8024 (defvar org-subtree-clip ""
8025 "Clipboard for cut and paste of subtrees.
8026 This is actually only a copy of the kill, because we use the normal kill
8027 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8029 (defvar org-subtree-clip-folded nil
8030 "Was the last copied subtree folded?
8031 This is used to fold the tree back after pasting.")
8033 (defun org-cut-subtree (&optional n)
8034 "Cut the current subtree into the clipboard.
8035 With prefix arg N, cut this many sequential subtrees.
8036 This is a short-hand for marking the subtree and then cutting it."
8037 (interactive "p")
8038 (org-copy-subtree n 'cut))
8040 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8041 "Cut the current subtree into the clipboard.
8042 With prefix arg N, cut this many sequential subtrees.
8043 This is a short-hand for marking the subtree and then copying it.
8044 If CUT is non-nil, actually cut the subtree.
8045 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8046 of some markers in the region, even if CUT is non-nil. This is
8047 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8048 (interactive "p")
8049 (let (beg end folded (beg0 (point)))
8050 (if (org-called-interactively-p 'any)
8051 (org-back-to-heading nil) ; take what looks like a subtree
8052 (org-back-to-heading t)) ; take what is really there
8053 (setq beg (point))
8054 (skip-chars-forward " \t\r\n")
8055 (save-match-data
8056 (if nosubtrees
8057 (outline-next-heading)
8058 (save-excursion (outline-end-of-heading)
8059 (setq folded (outline-invisible-p)))
8060 (condition-case nil
8061 (org-forward-heading-same-level (1- n) t)
8062 (error nil))
8063 (org-end-of-subtree t t)))
8064 (setq end (point))
8065 (goto-char beg0)
8066 (when (> end beg)
8067 (setq org-subtree-clip-folded folded)
8068 (when (or cut force-store-markers)
8069 (org-save-markers-in-region beg end))
8070 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8071 (setq org-subtree-clip (current-kill 0))
8072 (message "%s: Subtree(s) with %d characters"
8073 (if cut "Cut" "Copied")
8074 (length org-subtree-clip)))))
8076 (defun org-paste-subtree (&optional level tree for-yank)
8077 "Paste the clipboard as a subtree, with modification of headline level.
8078 The entire subtree is promoted or demoted in order to match a new headline
8079 level.
8081 If the cursor is at the beginning of a headline, the same level as
8082 that headline is used to paste the tree.
8084 If not, the new level is derived from the *visible* headings
8085 before and after the insertion point, and taken to be the inferior headline
8086 level of the two. So if the previous visible heading is level 3 and the
8087 next is level 4 (or vice versa), level 4 will be used for insertion.
8088 This makes sure that the subtree remains an independent subtree and does
8089 not swallow low level entries.
8091 You can also force a different level, either by using a numeric prefix
8092 argument, or by inserting the heading marker by hand. For example, if the
8093 cursor is after \"*****\", then the tree will be shifted to level 5.
8095 If optional TREE is given, use this text instead of the kill ring.
8097 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8098 move back over whitespace before inserting, and move point to the end of
8099 the inserted text when done."
8100 (interactive "P")
8101 (setq tree (or tree (and kill-ring (current-kill 0))))
8102 (unless (org-kill-is-subtree-p tree)
8103 (error "%s"
8104 (substitute-command-keys
8105 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8106 (org-with-limited-levels
8107 (let* ((visp (not (outline-invisible-p)))
8108 (txt tree)
8109 (^re_ "\\(\\*+\\)[ \t]*")
8110 (old-level (if (string-match org-outline-regexp-bol txt)
8111 (- (match-end 0) (match-beginning 0) 1)
8112 -1))
8113 (force-level (cond (level (prefix-numeric-value level))
8114 ((and (looking-at "[ \t]*$")
8115 (string-match
8116 "^\\*+$" (buffer-substring
8117 (point-at-bol) (point))))
8118 (- (match-end 1) (match-beginning 1)))
8119 ((and (bolp)
8120 (looking-at org-outline-regexp))
8121 (- (match-end 0) (point) 1))))
8122 (previous-level (save-excursion
8123 (condition-case nil
8124 (progn
8125 (outline-previous-visible-heading 1)
8126 (if (looking-at ^re_)
8127 (- (match-end 0) (match-beginning 0) 1)
8129 (error 1))))
8130 (next-level (save-excursion
8131 (condition-case nil
8132 (progn
8133 (or (looking-at org-outline-regexp)
8134 (outline-next-visible-heading 1))
8135 (if (looking-at ^re_)
8136 (- (match-end 0) (match-beginning 0) 1)
8138 (error 1))))
8139 (new-level (or force-level (max previous-level next-level)))
8140 (shift (if (or (= old-level -1)
8141 (= new-level -1)
8142 (= old-level new-level))
8144 (- new-level old-level)))
8145 (delta (if (> shift 0) -1 1))
8146 (func (if (> shift 0) 'org-demote 'org-promote))
8147 (org-odd-levels-only nil)
8148 beg end newend)
8149 ;; Remove the forced level indicator
8150 (if force-level
8151 (delete-region (point-at-bol) (point)))
8152 ;; Paste
8153 (beginning-of-line (if (bolp) 1 2))
8154 (setq beg (point))
8155 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8156 (insert-before-markers txt)
8157 (unless (string-match "\n\\'" txt) (insert "\n"))
8158 (setq newend (point))
8159 (org-reinstall-markers-in-region beg)
8160 (setq end (point))
8161 (goto-char beg)
8162 (skip-chars-forward " \t\n\r")
8163 (setq beg (point))
8164 (if (and (outline-invisible-p) visp)
8165 (save-excursion (outline-show-heading)))
8166 ;; Shift if necessary
8167 (unless (= shift 0)
8168 (save-restriction
8169 (narrow-to-region beg end)
8170 (while (not (= shift 0))
8171 (org-map-region func (point-min) (point-max))
8172 (setq shift (+ delta shift)))
8173 (goto-char (point-min))
8174 (setq newend (point-max))))
8175 (when (or (org-called-interactively-p 'interactive) for-yank)
8176 (message "Clipboard pasted as level %d subtree" new-level))
8177 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8178 kill-ring
8179 (eq org-subtree-clip (current-kill 0))
8180 org-subtree-clip-folded)
8181 ;; The tree was folded before it was killed/copied
8182 (hide-subtree))
8183 (and for-yank (goto-char newend)))))
8185 (defun org-kill-is-subtree-p (&optional txt)
8186 "Check if the current kill is an outline subtree, or a set of trees.
8187 Returns nil if kill does not start with a headline, or if the first
8188 headline level is not the largest headline level in the tree.
8189 So this will actually accept several entries of equal levels as well,
8190 which is OK for `org-paste-subtree'.
8191 If optional TXT is given, check this string instead of the current kill."
8192 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8193 (re (org-get-limited-outline-regexp))
8194 (^re (concat "^" re))
8195 (start-level (and kill
8196 (string-match
8197 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8198 kill)
8199 (- (match-end 2) (match-beginning 2) 1)))
8200 (start (1+ (or (match-beginning 2) -1))))
8201 (if (not start-level)
8202 (progn
8203 nil) ;; does not even start with a heading
8204 (catch 'exit
8205 (while (setq start (string-match ^re kill (1+ start)))
8206 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8207 (throw 'exit nil)))
8208 t))))
8210 (defvar org-markers-to-move nil
8211 "Markers that should be moved with a cut-and-paste operation.
8212 Those markers are stored together with their positions relative to
8213 the start of the region.")
8215 (defun org-save-markers-in-region (beg end)
8216 "Check markers in region.
8217 If these markers are between BEG and END, record their position relative
8218 to BEG, so that after moving the block of text, we can put the markers back
8219 into place.
8220 This function gets called just before an entry or tree gets cut from the
8221 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8222 called immediately, to move the markers with the entries."
8223 (setq org-markers-to-move nil)
8224 (when (featurep 'org-clock)
8225 (org-clock-save-markers-for-cut-and-paste beg end))
8226 (when (featurep 'org-agenda)
8227 (org-agenda-save-markers-for-cut-and-paste beg end)))
8229 (defun org-check-and-save-marker (marker beg end)
8230 "Check if MARKER is between BEG and END.
8231 If yes, remember the marker and the distance to BEG."
8232 (when (and (marker-buffer marker)
8233 (equal (marker-buffer marker) (current-buffer)))
8234 (if (and (>= marker beg) (< marker end))
8235 (push (cons marker (- marker beg)) org-markers-to-move))))
8237 (defun org-reinstall-markers-in-region (beg)
8238 "Move all remembered markers to their position relative to BEG."
8239 (mapc (lambda (x)
8240 (move-marker (car x) (+ beg (cdr x))))
8241 org-markers-to-move)
8242 (setq org-markers-to-move nil))
8244 (defun org-narrow-to-subtree ()
8245 "Narrow buffer to the current subtree."
8246 (interactive)
8247 (save-excursion
8248 (save-match-data
8249 (org-with-limited-levels
8250 (narrow-to-region
8251 (progn (org-back-to-heading t) (point))
8252 (progn (org-end-of-subtree t t)
8253 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8254 (point)))))))
8256 (defun org-narrow-to-block ()
8257 "Narrow buffer to the current block."
8258 (interactive)
8259 (let* ((case-fold-search t)
8260 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8261 "^[ \t]*#\\+end_.*")))
8262 (if blockp
8263 (narrow-to-region (car blockp) (cdr blockp))
8264 (error "Not in a block"))))
8266 (eval-when-compile
8267 (defvar org-property-drawer-re))
8269 (defvar org-property-start-re) ;; defined below
8270 (defun org-clone-subtree-with-time-shift (n &optional shift)
8271 "Clone the task (subtree) at point N times.
8272 The clones will be inserted as siblings.
8274 In interactive use, the user will be prompted for the number of
8275 clones to be produced, and for a time SHIFT, which may be a
8276 repeater as used in time stamps, for example `+3d'.
8278 When a valid repeater is given and the entry contains any time
8279 stamps, the clones will become a sequence in time, with time
8280 stamps in the subtree shifted for each clone produced. If SHIFT
8281 is nil or the empty string, time stamps will be left alone. The
8282 ID property of the original subtree is removed.
8284 If the original subtree did contain time stamps with a repeater,
8285 the following will happen:
8286 - the repeater will be removed in each clone
8287 - an additional clone will be produced, with the current, unshifted
8288 date(s) in the entry.
8289 - the original entry will be placed *after* all the clones, with
8290 repeater intact.
8291 - the start days in the repeater in the original entry will be shifted
8292 to past the last clone.
8293 In this way you can spell out a number of instances of a repeating task,
8294 and still retain the repeater to cover future instances of the task."
8295 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8296 (let (beg end template task idprop
8297 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8298 (drawer-re org-drawer-regexp))
8299 (if (not (and (integerp n) (> n 0)))
8300 (error "Invalid number of replications %s" n))
8301 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8302 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8303 shift)))
8304 (error "Invalid shift specification %s" shift))
8305 (when doshift
8306 (setq shift-n (string-to-number (match-string 1 shift))
8307 shift-what (cdr (assoc (match-string 2 shift)
8308 '(("d" . day) ("w" . week)
8309 ("m" . month) ("y" . year))))))
8310 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8311 (setq nmin 1 nmax n)
8312 (org-back-to-heading t)
8313 (setq beg (point))
8314 (setq idprop (org-entry-get nil "ID"))
8315 (org-end-of-subtree t t)
8316 (or (bolp) (insert "\n"))
8317 (setq end (point))
8318 (setq template (buffer-substring beg end))
8319 (when (and doshift
8320 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8321 (delete-region beg end)
8322 (setq end beg)
8323 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8324 (goto-char end)
8325 (loop for n from nmin to nmax do
8326 ;; prepare clone
8327 (with-temp-buffer
8328 (insert template)
8329 (org-mode)
8330 (goto-char (point-min))
8331 (org-show-subtree)
8332 (and idprop (if org-clone-delete-id
8333 (org-entry-delete nil "ID")
8334 (org-id-get-create t)))
8335 (unless (= n 0)
8336 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8337 (kill-whole-line))
8338 (goto-char (point-min))
8339 (while (re-search-forward drawer-re nil t)
8340 (mapc (lambda (d)
8341 (org-remove-empty-drawer-at d (point))) org-drawers)))
8342 (goto-char (point-min))
8343 (when doshift
8344 (while (re-search-forward org-ts-regexp-both nil t)
8345 (org-timestamp-change (* n shift-n) shift-what))
8346 (unless (= n n-no-remove)
8347 (goto-char (point-min))
8348 (while (re-search-forward org-ts-regexp nil t)
8349 (save-excursion
8350 (goto-char (match-beginning 0))
8351 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8352 (delete-region (match-beginning 1) (match-end 1)))))))
8353 (setq task (buffer-string)))
8354 (insert task))
8355 (goto-char beg)))
8357 ;;; Outline Sorting
8359 (defun org-sort (with-case)
8360 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8361 Optional argument WITH-CASE means sort case-sensitively."
8362 (interactive "P")
8363 (cond
8364 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8365 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8367 (org-call-with-arg 'org-sort-entries with-case))))
8369 (defun org-sort-remove-invisible (s)
8370 "Remove invisible links from string S."
8371 (remove-text-properties 0 (length s) org-rm-props s)
8372 (while (string-match org-bracket-link-regexp s)
8373 (setq s (replace-match (if (match-end 2)
8374 (match-string 3 s)
8375 (match-string 1 s)) t t s)))
8376 (let ((st (format " %s " s)))
8377 (while (string-match org-emph-re st)
8378 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8379 (setq s (substring st 1 -1)))
8382 (defvar org-priority-regexp) ; defined later in the file
8384 (defvar org-after-sorting-entries-or-items-hook nil
8385 "Hook that is run after a bunch of entries or items have been sorted.
8386 When children are sorted, the cursor is in the parent line when this
8387 hook gets called. When a region or a plain list is sorted, the cursor
8388 will be in the first entry of the sorted region/list.")
8390 (defun org-sort-entries
8391 (&optional with-case sorting-type getkey-func compare-func property)
8392 "Sort entries on a certain level of an outline tree.
8393 If there is an active region, the entries in the region are sorted.
8394 Else, if the cursor is before the first entry, sort the top-level items.
8395 Else, the children of the entry at point are sorted.
8397 Sorting can be alphabetically, numerically, by date/time as given by
8398 a time stamp, by a property, by priority order, or by a custom function.
8400 The command prompts for the sorting type unless it has been given to the
8401 function through the SORTING-TYPE argument, which needs to be a character,
8402 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8403 precise meaning of each character:
8405 n Numerically, by converting the beginning of the entry/item to a number.
8406 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8407 o By order of TODO keywords.
8408 t By date/time, either the first active time stamp in the entry, or, if
8409 none exist, by the first inactive one.
8410 s By the scheduled date/time.
8411 d By deadline date/time.
8412 c By creation time, which is assumed to be the first inactive time stamp
8413 at the beginning of a line.
8414 p By priority according to the cookie.
8415 r By the value of a property.
8417 Capital letters will reverse the sort order.
8419 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8420 called with point at the beginning of the record. It must return either
8421 a string or a number that should serve as the sorting key for that record.
8423 Comparing entries ignores case by default. However, with an optional argument
8424 WITH-CASE, the sorting considers case as well.
8426 Sorting is done against the visible part of the headlines, it ignores hidden
8427 links."
8428 (interactive "P")
8429 (let ((case-func (if with-case 'identity 'downcase))
8430 (cmstr
8431 ;; The clock marker is lost when using `sort-subr', let's
8432 ;; store the clocking string.
8433 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8434 (save-excursion
8435 (goto-char org-clock-marker)
8436 (looking-back "^.*") (match-string-no-properties 0))))
8437 start beg end stars re re2
8438 txt what tmp)
8439 ;; Find beginning and end of region to sort
8440 (cond
8441 ((org-region-active-p)
8442 ;; we will sort the region
8443 (setq end (region-end)
8444 what "region")
8445 (goto-char (region-beginning))
8446 (if (not (org-at-heading-p)) (outline-next-heading))
8447 (setq start (point)))
8448 ((or (org-at-heading-p)
8449 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8450 ;; we will sort the children of the current headline
8451 (org-back-to-heading)
8452 (setq start (point)
8453 end (progn (org-end-of-subtree t t)
8454 (or (bolp) (insert "\n"))
8455 (org-back-over-empty-lines)
8456 (point))
8457 what "children")
8458 (goto-char start)
8459 (show-subtree)
8460 (outline-next-heading))
8462 ;; we will sort the top-level entries in this file
8463 (goto-char (point-min))
8464 (or (org-at-heading-p) (outline-next-heading))
8465 (setq start (point))
8466 (goto-char (point-max))
8467 (beginning-of-line 1)
8468 (when (looking-at ".*?\\S-")
8469 ;; File ends in a non-white line
8470 (end-of-line 1)
8471 (insert "\n"))
8472 (setq end (point-max))
8473 (setq what "top-level")
8474 (goto-char start)
8475 (show-all)))
8477 (setq beg (point))
8478 (if (>= beg end) (error "Nothing to sort"))
8480 (looking-at "\\(\\*+\\)")
8481 (setq stars (match-string 1)
8482 re (concat "^" (regexp-quote stars) " +")
8483 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8484 txt (buffer-substring beg end))
8485 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8486 (if (and (not (equal stars "*")) (string-match re2 txt))
8487 (error "Region to sort contains a level above the first entry"))
8489 (unless sorting-type
8490 (message
8491 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8492 [t]ime [s]cheduled [d]eadline [c]reated
8493 A/N/P/R/O/F/T/S/D/C means reversed:"
8494 what)
8495 (setq sorting-type (read-char-exclusive))
8497 (unless getkey-func
8498 (and (= (downcase sorting-type) ?f)
8499 (setq getkey-func
8500 (org-icompleting-read "Sort using function: "
8501 obarray 'fboundp t nil nil))
8502 (setq getkey-func (intern getkey-func))))
8504 (and (= (downcase sorting-type) ?r)
8505 (not property)
8506 (setq property
8507 (org-icompleting-read "Property: "
8508 (mapcar 'list (org-buffer-property-keys t))
8509 nil t))))
8511 (message "Sorting entries...")
8513 (save-restriction
8514 (narrow-to-region start end)
8515 (let ((dcst (downcase sorting-type))
8516 (case-fold-search nil)
8517 (now (current-time)))
8518 (sort-subr
8519 (/= dcst sorting-type)
8520 ;; This function moves to the beginning character of the "record" to
8521 ;; be sorted.
8522 (lambda nil
8523 (if (re-search-forward re nil t)
8524 (goto-char (match-beginning 0))
8525 (goto-char (point-max))))
8526 ;; This function moves to the last character of the "record" being
8527 ;; sorted.
8528 (lambda nil
8529 (save-match-data
8530 (condition-case nil
8531 (outline-forward-same-level 1)
8532 (error
8533 (goto-char (point-max))))))
8534 ;; This function returns the value that gets sorted against.
8535 (lambda nil
8536 (cond
8537 ((= dcst ?n)
8538 (if (looking-at org-complex-heading-regexp)
8539 (string-to-number (org-sort-remove-invisible (match-string 4)))
8540 nil))
8541 ((= dcst ?a)
8542 (if (looking-at org-complex-heading-regexp)
8543 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8544 nil))
8545 ((= dcst ?t)
8546 (let ((end (save-excursion (outline-next-heading) (point))))
8547 (if (or (re-search-forward org-ts-regexp end t)
8548 (re-search-forward org-ts-regexp-both end t))
8549 (org-time-string-to-seconds (match-string 0))
8550 (org-float-time now))))
8551 ((= dcst ?c)
8552 (let ((end (save-excursion (outline-next-heading) (point))))
8553 (if (re-search-forward
8554 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8555 end t)
8556 (org-time-string-to-seconds (match-string 0))
8557 (org-float-time now))))
8558 ((= dcst ?s)
8559 (let ((end (save-excursion (outline-next-heading) (point))))
8560 (if (re-search-forward org-scheduled-time-regexp end t)
8561 (org-time-string-to-seconds (match-string 1))
8562 (org-float-time now))))
8563 ((= dcst ?d)
8564 (let ((end (save-excursion (outline-next-heading) (point))))
8565 (if (re-search-forward org-deadline-time-regexp end t)
8566 (org-time-string-to-seconds (match-string 1))
8567 (org-float-time now))))
8568 ((= dcst ?p)
8569 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8570 (string-to-char (match-string 2))
8571 org-default-priority))
8572 ((= dcst ?r)
8573 (or (org-entry-get nil property) ""))
8574 ((= dcst ?o)
8575 (if (looking-at org-complex-heading-regexp)
8576 (- 9999 (length (member (match-string 2)
8577 org-todo-keywords-1)))))
8578 ((= dcst ?f)
8579 (if getkey-func
8580 (progn
8581 (setq tmp (funcall getkey-func))
8582 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8583 tmp)
8584 (error "Invalid key function `%s'" getkey-func)))
8585 (t (error "Invalid sorting type `%c'" sorting-type))))
8587 (cond
8588 ((= dcst ?a) 'string<)
8589 ((= dcst ?f) compare-func)
8590 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8591 (run-hooks 'org-after-sorting-entries-or-items-hook)
8592 ;; Reset the clock marker if needed
8593 (when cmstr
8594 (save-excursion
8595 (goto-char start)
8596 (search-forward cmstr nil t)
8597 (move-marker org-clock-marker (point))))
8598 (message "Sorting entries...done")))
8600 (defun org-do-sort (table what &optional with-case sorting-type)
8601 "Sort TABLE of WHAT according to SORTING-TYPE.
8602 The user will be prompted for the SORTING-TYPE if the call to this
8603 function does not specify it. WHAT is only for the prompt, to indicate
8604 what is being sorted. The sorting key will be extracted from
8605 the car of the elements of the table.
8606 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8607 (unless sorting-type
8608 (message
8609 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8610 what)
8611 (setq sorting-type (read-char-exclusive)))
8612 (let ((dcst (downcase sorting-type))
8613 extractfun comparefun)
8614 ;; Define the appropriate functions
8615 (cond
8616 ((= dcst ?n)
8617 (setq extractfun 'string-to-number
8618 comparefun (if (= dcst sorting-type) '< '>)))
8619 ((= dcst ?a)
8620 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8621 (lambda(x) (downcase (org-sort-remove-invisible x))))
8622 comparefun (if (= dcst sorting-type)
8623 'string<
8624 (lambda (a b) (and (not (string< a b))
8625 (not (string= a b)))))))
8626 ((= dcst ?t)
8627 (setq extractfun
8628 (lambda (x)
8629 (if (or (string-match org-ts-regexp x)
8630 (string-match org-ts-regexp-both x))
8631 (org-float-time
8632 (org-time-string-to-time (match-string 0 x)))
8634 comparefun (if (= dcst sorting-type) '< '>)))
8635 (t (error "Invalid sorting type `%c'" sorting-type)))
8637 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8638 table)
8639 (lambda (a b) (funcall comparefun (car a) (car b))))))
8642 ;;; The orgstruct minor mode
8644 ;; Define a minor mode which can be used in other modes in order to
8645 ;; integrate the org-mode structure editing commands.
8647 ;; This is really a hack, because the org-mode structure commands use
8648 ;; keys which normally belong to the major mode. Here is how it
8649 ;; works: The minor mode defines all the keys necessary to operate the
8650 ;; structure commands, but wraps the commands into a function which
8651 ;; tests if the cursor is currently at a headline or a plain list
8652 ;; item. If that is the case, the structure command is used,
8653 ;; temporarily setting many Org-mode variables like regular
8654 ;; expressions for filling etc. However, when any of those keys is
8655 ;; used at a different location, function uses `key-binding' to look
8656 ;; up if the key has an associated command in another currently active
8657 ;; keymap (minor modes, major mode, global), and executes that
8658 ;; command. There might be problems if any of the keys is otherwise
8659 ;; used as a prefix key.
8661 (defcustom orgstruct-heading-prefix-regexp nil
8662 "Regexp that matches the custom prefix of Org headlines in
8663 orgstruct(++)-mode."
8664 :group 'org
8665 :version "24.4"
8666 :package-version '(Org . "8.0")
8667 :type 'string)
8668 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8670 (defcustom orgstruct-setup-hook nil
8671 "Hook run after orgstruct-mode-map is filled."
8672 :group 'org
8673 :version "24.4"
8674 :package-version '(Org . "8.0")
8675 :type 'hook)
8677 (defvar orgstruct-initialized nil)
8679 (defvar org-local-vars nil
8680 "List of local variables, for use by `orgstruct-mode'.")
8682 ;;;###autoload
8683 (define-minor-mode orgstruct-mode
8684 "Toggle the minor mode `orgstruct-mode'.
8685 This mode is for using Org-mode structure commands in other
8686 modes. The following keys behave as if Org-mode were active, if
8687 the cursor is on a headline, or on a plain list item (both as
8688 defined by Org-mode)."
8689 nil " OrgStruct" (make-sparse-keymap)
8690 (when orgstruct-mode
8691 (org-load-modules-maybe)
8692 (unless orgstruct-initialized
8693 (orgstruct-setup)
8694 (setq orgstruct-initialized t))))
8696 ;;;###autoload
8697 (defun turn-on-orgstruct ()
8698 "Unconditionally turn on `orgstruct-mode'."
8699 (orgstruct-mode 1))
8701 (defvar org-fb-vars nil)
8702 (make-variable-buffer-local 'org-fb-vars)
8703 (defun orgstruct++-mode (&optional arg)
8704 "Toggle `orgstruct-mode', the enhanced version of it.
8705 In addition to setting orgstruct-mode, this also exports all
8706 indentation and autofilling variables from org-mode into the
8707 buffer. It will also recognize item context in multiline items."
8708 (interactive "P")
8709 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8710 (if (< arg 1)
8711 (progn (orgstruct-mode -1)
8712 (mapc (lambda(v)
8713 (org-set-local (car v)
8714 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8715 org-fb-vars))
8716 (orgstruct-mode 1)
8717 (setq org-fb-vars nil)
8718 (let (var val)
8719 (mapc
8720 (lambda (x)
8721 (when (string-match
8722 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8723 (symbol-name (car x)))
8724 (setq var (car x) val (nth 1 x))
8725 (push (list var `(quote ,(eval var))) org-fb-vars)
8726 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8727 org-local-vars)
8728 (org-set-local 'orgstruct-is-++ t))))
8730 (defvar orgstruct-is-++ nil
8731 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8732 (make-variable-buffer-local 'orgstruct-is-++)
8734 ;;;###autoload
8735 (defun turn-on-orgstruct++ ()
8736 "Unconditionally turn on `orgstruct++-mode'."
8737 (orgstruct++-mode 1))
8739 (defun orgstruct-error ()
8740 "Error when there is no default binding for a structure key."
8741 (interactive)
8742 (funcall (if (fboundp 'user-error)
8743 'user-error
8744 'error)
8745 "This key has no function outside structure elements"))
8747 (defun orgstruct-setup ()
8748 "Setup orgstruct keymap."
8749 (dolist (cell '((org-demote . t)
8750 (org-metaleft . t)
8751 (org-metaright . t)
8752 (org-promote . t)
8753 (org-shiftmetaleft . t)
8754 (org-shiftmetaright . t)
8755 org-backward-element
8756 org-backward-heading-same-level
8757 org-ctrl-c-ret
8758 org-ctrl-c-minus
8759 org-ctrl-c-star
8760 org-cycle
8761 org-forward-heading-same-level
8762 org-insert-heading
8763 org-insert-heading-respect-content
8764 org-kill-note-or-show-branches
8765 org-mark-subtree
8766 org-meta-return
8767 org-metadown
8768 org-metaup
8769 org-narrow-to-subtree
8770 org-promote-subtree
8771 org-reveal
8772 org-shiftdown
8773 org-shiftleft
8774 org-shiftmetadown
8775 org-shiftmetaup
8776 org-shiftright
8777 org-shifttab
8778 org-shifttab
8779 org-shiftup
8780 org-show-subtree
8781 org-sort
8782 org-up-element
8783 outline-demote
8784 outline-next-visible-heading
8785 outline-previous-visible-heading
8786 outline-promote
8787 outline-up-heading
8788 show-children))
8789 (let ((f (or (car-safe cell) cell))
8790 (disable-when-heading-prefix (cdr-safe cell)))
8791 (when (fboundp f)
8792 (dolist (binding (nconc (where-is-internal f org-mode-map)
8793 (where-is-internal f outline-mode-map)))
8794 ;; TODO use local-function-key-map
8795 (dolist (rep '(("<tab>" . "TAB")
8796 ("<return>" . "RET")
8797 ("<escape>" . "ESC")
8798 ("<delete>" . "DEL")))
8799 (setq binding (read-kbd-macro (replace-regexp-in-string
8800 (regexp-quote (car rep))
8801 (cdr rep)
8802 (key-description binding)))))
8803 (let ((key (lookup-key orgstruct-mode-map binding)))
8804 (when (or (not key) (numberp key))
8805 (condition-case nil
8806 (org-defkey orgstruct-mode-map
8807 binding
8808 (orgstruct-make-binding f binding disable-when-heading-prefix))
8809 (error nil))))))))
8810 (run-hooks 'orgstruct-setup-hook))
8812 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8813 "Create a function for binding in the structure minor mode.
8814 FUN is the command to call inside a table. KEY is the key that
8815 should be checked in for a command to execute outside of tables.
8816 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8817 if `orgstruct-heading-prefix-regexp' is non-nil."
8818 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8819 (let ((nname name)
8820 (i 0))
8821 (while (fboundp (intern nname))
8822 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8823 (setq name (intern nname)))
8824 (eval
8825 (let ((bindings '((org-heading-regexp
8826 (concat "^"
8827 orgstruct-heading-prefix-regexp
8828 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8829 (org-outline-regexp
8830 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8831 (org-outline-regexp-bol
8832 (concat "^" org-outline-regexp))
8833 (outline-regexp org-outline-regexp)
8834 (outline-heading-end-regexp "\n")
8835 (outline-level 'org-outline-level)
8836 (outline-heading-alist))))
8837 `(defun ,name (arg)
8838 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8839 "Outside of structure, run the binding of `"
8840 (key-description key) "'."
8841 (when disable-when-heading-prefix
8842 (concat
8843 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8844 "back to the default binding due to limitations of Org's implementation of\n"
8845 "`" (symbol-name fun) "'.")))
8846 (interactive "p")
8847 (let* ((disable
8848 ,(when disable-when-heading-prefix
8849 '(and orgstruct-heading-prefix-regexp
8850 (not (string= orgstruct-heading-prefix-regexp "")))))
8851 (fallback
8852 (or disable
8853 (not
8854 (let* ,bindings
8855 (org-context-p 'headline 'item
8856 ,(when (memq fun '(org-insert-heading))
8857 '(when orgstruct-is-++
8858 'item-body))))))))
8859 (if fallback
8860 (let* ((orgstruct-mode)
8861 (binding (key-binding ,key)))
8862 (if (keymapp binding)
8863 (set-temporary-overlay-map binding)
8864 (let ((func (or binding
8865 (unless disable
8866 'orgstruct-error))))
8867 (when func
8868 (call-interactively func)))))
8869 (org-run-like-in-org-mode
8870 (lambda ()
8871 (interactive)
8872 (let* ,bindings
8873 (call-interactively ',fun)))))))))
8874 name))
8876 (defun org-contextualize-keys (alist contexts)
8877 "Return valid elements in ALIST depending on CONTEXTS.
8879 `org-agenda-custom-commands' or `org-capture-templates' are the
8880 values used for ALIST, and `org-agenda-custom-commands-contexts'
8881 or `org-capture-templates-contexts' are the associated contexts
8882 definitions."
8883 (let ((contexts
8884 ;; normalize contexts
8885 (mapcar
8886 (lambda(c) (cond ((listp (cadr c))
8887 (list (car c) (car c) (cadr c)))
8888 ((string= "" (cadr c))
8889 (list (car c) (car c) (caddr c)))
8890 (t c))) contexts))
8891 (a alist) c r s)
8892 ;; loop over all commands or templates
8893 (while (setq c (pop a))
8894 (let (vrules repl)
8895 (cond
8896 ((not (assoc (car c) contexts))
8897 (push c r))
8898 ((and (assoc (car c) contexts)
8899 (setq vrules (org-contextualize-validate-key
8900 (car c) contexts)))
8901 (mapc (lambda (vr)
8902 (when (not (equal (car vr) (cadr vr)))
8903 (setq repl vr))) vrules)
8904 (if (not repl) (push c r)
8905 (push (cadr repl) s)
8906 (push
8907 (cons (car c)
8908 (cdr (or (assoc (cadr repl) alist)
8909 (error "Undefined key `%s' as contextual replacement for `%s'"
8910 (cadr repl) (car c)))))
8911 r))))))
8912 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8913 (delq
8915 (delete-dups
8916 (mapcar (lambda (x)
8917 (let ((tpl (car x)))
8918 (when (not (delq
8920 (mapcar (lambda(y)
8921 (equal y tpl)) s))) x)))
8922 (reverse r))))))
8924 (defun org-contextualize-validate-key (key contexts)
8925 "Check CONTEXTS for agenda or capture KEY."
8926 (let (r rr res)
8927 (while (setq r (pop contexts))
8928 (mapc
8929 (lambda (rr)
8930 (when
8931 (and (equal key (car r))
8932 (if (functionp rr) (funcall rr)
8933 (or (and (eq (car rr) 'in-file)
8934 (buffer-file-name)
8935 (string-match (cdr rr) (buffer-file-name)))
8936 (and (eq (car rr) 'in-mode)
8937 (string-match (cdr rr) (symbol-name major-mode)))
8938 (and (eq (car rr) 'in-buffer)
8939 (string-match (cdr rr) (buffer-name)))
8940 (when (and (eq (car rr) 'not-in-file)
8941 (buffer-file-name))
8942 (not (string-match (cdr rr) (buffer-file-name))))
8943 (when (eq (car rr) 'not-in-mode)
8944 (not (string-match (cdr rr) (symbol-name major-mode))))
8945 (when (eq (car rr) 'not-in-buffer)
8946 (not (string-match (cdr rr) (buffer-name)))))))
8947 (push r res)))
8948 (car (last r))))
8949 (delete-dups (delq nil res))))
8951 (defun org-context-p (&rest contexts)
8952 "Check if local context is any of CONTEXTS.
8953 Possible values in the list of contexts are `table', `headline', and `item'."
8954 (let ((pos (point)))
8955 (goto-char (point-at-bol))
8956 (prog1 (or (and (memq 'table contexts)
8957 (looking-at "[ \t]*|"))
8958 (and (memq 'headline contexts)
8959 (looking-at org-outline-regexp))
8960 (and (memq 'item contexts)
8961 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8962 (and (memq 'item-body contexts)
8963 (org-in-item-p)))
8964 (goto-char pos))))
8966 (defun org-get-local-variables ()
8967 "Return a list of all local variables in an Org mode buffer."
8968 (let (varlist)
8969 (with-current-buffer (get-buffer-create "*Org tmp*")
8970 (erase-buffer)
8971 (org-mode)
8972 (setq varlist (buffer-local-variables)))
8973 (kill-buffer "*Org tmp*")
8974 (delq nil
8975 (mapcar
8976 (lambda (x)
8977 (setq x
8978 (if (symbolp x)
8979 (list x)
8980 (list (car x) (cdr x))))
8981 (if (and (not (get (car x) 'org-state))
8982 (string-match
8983 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8984 (symbol-name (car x))))
8985 x nil))
8986 varlist))))
8988 (defun org-clone-local-variables (from-buffer &optional regexp)
8989 "Clone local variables from FROM-BUFFER.
8990 Optional argument REGEXP selects variables to clone."
8991 (mapc
8992 (lambda (pair)
8993 (and (symbolp (car pair))
8994 (or (null regexp)
8995 (string-match regexp (symbol-name (car pair))))
8996 (set (make-local-variable (car pair))
8997 (cdr pair))))
8998 (buffer-local-variables from-buffer)))
9000 ;;;###autoload
9001 (defun org-run-like-in-org-mode (cmd)
9002 "Run a command, pretending that the current buffer is in Org-mode.
9003 This will temporarily bind local variables that are typically bound in
9004 Org-mode to the values they have in Org-mode, and then interactively
9005 call CMD."
9006 (org-load-modules-maybe)
9007 (unless org-local-vars
9008 (setq org-local-vars (org-get-local-variables)))
9009 (let (binds)
9010 (dolist (var org-local-vars)
9011 (when (or (not (boundp (car var)))
9012 (eq (symbol-value (car var))
9013 (default-value (car var))))
9014 (push (list (car var) `(quote ,(cadr var))) binds)))
9015 (eval `(let ,binds
9016 (call-interactively (quote ,cmd))))))
9018 ;;;; Archiving
9020 (defun org-get-category (&optional pos force-refresh)
9021 "Get the category applying to position POS."
9022 (save-match-data
9023 (if force-refresh (org-refresh-category-properties))
9024 (let ((pos (or pos (point))))
9025 (or (get-text-property pos 'org-category)
9026 (progn (org-refresh-category-properties)
9027 (get-text-property pos 'org-category))))))
9029 (defun org-refresh-category-properties ()
9030 "Refresh category text properties in the buffer."
9031 (let ((case-fold-search t)
9032 (inhibit-read-only t)
9033 (def-cat (cond
9034 ((null org-category)
9035 (if buffer-file-name
9036 (file-name-sans-extension
9037 (file-name-nondirectory buffer-file-name))
9038 "???"))
9039 ((symbolp org-category) (symbol-name org-category))
9040 (t org-category)))
9041 beg end cat pos optionp)
9042 (org-with-silent-modifications
9043 (save-excursion
9044 (save-restriction
9045 (widen)
9046 (goto-char (point-min))
9047 (put-text-property (point) (point-max) 'org-category def-cat)
9048 (while (re-search-forward
9049 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9050 (setq pos (match-end 0)
9051 optionp (equal (char-after (match-beginning 0)) ?#)
9052 cat (org-trim (match-string 2)))
9053 (if optionp
9054 (setq beg (point-at-bol) end (point-max))
9055 (org-back-to-heading t)
9056 (setq beg (point) end (org-end-of-subtree t t)))
9057 (put-text-property beg end 'org-category cat)
9058 (put-text-property beg end 'org-category-position beg)
9059 (goto-char pos)))))))
9061 (defun org-refresh-properties (dprop tprop)
9062 "Refresh buffer text properties.
9063 DPROP is the drawer property and TPROP is the corresponding text
9064 property to set."
9065 (let ((case-fold-search t)
9066 (inhibit-read-only t) p)
9067 (org-with-silent-modifications
9068 (save-excursion
9069 (save-restriction
9070 (widen)
9071 (goto-char (point-min))
9072 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9073 (setq p (org-match-string-no-properties 1))
9074 (save-excursion
9075 (org-back-to-heading t)
9076 (put-text-property
9077 (point-at-bol) (point-at-eol) tprop p))))))))
9080 ;;;; Link Stuff
9082 ;;; Link abbreviations
9084 (defun org-link-expand-abbrev (link)
9085 "Apply replacements as defined in `org-link-abbrev-alist'."
9086 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9087 (let* ((key (match-string 1 link))
9088 (as (or (assoc key org-link-abbrev-alist-local)
9089 (assoc key org-link-abbrev-alist)))
9090 (tag (and (match-end 2) (match-string 3 link)))
9091 rpl)
9092 (if (not as)
9093 link
9094 (setq rpl (cdr as))
9095 (cond
9096 ((symbolp rpl) (funcall rpl tag))
9097 ((string-match "%(\\([^)]+\\))" rpl)
9098 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9099 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9100 ((string-match "%h" rpl)
9101 (replace-match (url-hexify-string (or tag "")) t t rpl))
9102 (t (concat rpl tag)))))
9103 link))
9105 ;;; Storing and inserting links
9107 (defvar org-insert-link-history nil
9108 "Minibuffer history for links inserted with `org-insert-link'.")
9110 (defvar org-stored-links nil
9111 "Contains the links stored with `org-store-link'.")
9113 (defvar org-store-link-plist nil
9114 "Plist with info about the most recently link created with `org-store-link'.")
9116 (defvar org-link-protocols nil
9117 "Link protocols added to Org-mode using `org-add-link-type'.")
9119 (defvar org-store-link-functions nil
9120 "List of functions that are called to create and store a link.
9121 Each function will be called in turn until one returns a non-nil
9122 value. Each function should check if it is responsible for creating
9123 this link (for example by looking at the major mode).
9124 If not, it must exit and return nil.
9125 If yes, it should return a non-nil value after a calling
9126 `org-store-link-props' with a list of properties and values.
9127 Special properties are:
9129 :type The link prefix, like \"http\". This must be given.
9130 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9131 This is obligatory as well.
9132 :description Optional default description for the second pair
9133 of brackets in an Org-mode link. The user can still change
9134 this when inserting this link into an Org-mode buffer.
9136 In addition to these, any additional properties can be specified
9137 and then used in capture templates.")
9139 (defun org-add-link-type (type &optional follow export)
9140 "Add TYPE to the list of `org-link-types'.
9141 Re-compute all regular expressions depending on `org-link-types'
9143 FOLLOW and EXPORT are two functions.
9145 FOLLOW should take the link path as the single argument and do whatever
9146 is necessary to follow the link, for example find a file or display
9147 a mail message.
9149 EXPORT should format the link path for export to one of the export formats.
9150 It should be a function accepting three arguments:
9152 path the path of the link, the text after the prefix (like \"http:\")
9153 desc the description of the link, if any, or a description added by
9154 org-export-normalize-links if there is none
9155 format the export format, a symbol like `html' or `latex' or `ascii'..
9157 The function may use the FORMAT information to return different values
9158 depending on the format. The return value will be put literally into
9159 the exported file. If the return value is nil, this means Org should
9160 do what it normally does with links which do not have EXPORT defined.
9162 Org-mode has a built-in default for exporting links. If you are happy with
9163 this default, there is no need to define an export function for the link
9164 type. For a simple example of an export function, see `org-bbdb.el'."
9165 (add-to-list 'org-link-types type t)
9166 (org-make-link-regexps)
9167 (if (assoc type org-link-protocols)
9168 (setcdr (assoc type org-link-protocols) (list follow export))
9169 (push (list type follow export) org-link-protocols)))
9171 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9172 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9174 ;;;###autoload
9175 (defun org-store-link (arg)
9176 "\\<org-mode-map>Store an org-link to the current location.
9177 This link is added to `org-stored-links' and can later be inserted
9178 into an org-buffer with \\[org-insert-link].
9180 For some link types, a prefix arg is interpreted.
9181 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9182 For file links, arg negates `org-context-in-file-links'.
9184 A double prefix arg force skipping storing functions that are not
9185 part of Org's core."
9186 (interactive "P")
9187 (org-load-modules-maybe)
9188 (setq org-store-link-plist nil) ; reset
9189 (org-with-limited-levels
9190 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9191 (cond
9192 ((and (not (equal arg '(16)))
9193 (setq sfuns
9194 (delq
9195 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9196 org-store-link-functions))
9197 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9198 (or (and (cdr sfuns)
9199 (funcall (intern
9200 (completing-read "Which function for creating the link? "
9201 sfunsn t (car sfunsn)))))
9202 (funcall (caar sfuns)))
9203 (setq link (plist-get org-store-link-plist :link)
9204 desc (or (plist-get org-store-link-plist :description) link))))
9205 ((org-src-edit-buffer-p)
9206 (let (label gc)
9207 (while (or (not label)
9208 (save-excursion
9209 (save-restriction
9210 (widen)
9211 (goto-char (point-min))
9212 (re-search-forward
9213 (regexp-quote (format org-coderef-label-format label))
9214 nil t))))
9215 (when label (message "Label exists already") (sit-for 2))
9216 (setq label (read-string "Code line label: " label)))
9217 (end-of-line 1)
9218 (setq link (format org-coderef-label-format label))
9219 (setq gc (- 79 (length link)))
9220 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9221 (insert link)
9222 (setq link (concat "(" label ")") desc nil)))
9224 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9225 ;; We are in the agenda, link to referenced location
9226 (let ((m (or (get-text-property (point) 'org-hd-marker)
9227 (get-text-property (point) 'org-marker))))
9228 (when m
9229 (org-with-point-at m
9230 (setq agenda-link
9231 (if (org-called-interactively-p 'any)
9232 (call-interactively 'org-store-link)
9233 (org-store-link nil)))))))
9235 ((eq major-mode 'calendar-mode)
9236 (let ((cd (calendar-cursor-to-date)))
9237 (setq link
9238 (format-time-string
9239 (car org-time-stamp-formats)
9240 (apply 'encode-time
9241 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9242 nil nil nil))))
9243 (org-store-link-props :type "calendar" :date cd)))
9245 ((eq major-mode 'help-mode)
9246 (setq link (concat "help:" (save-excursion
9247 (goto-char (point-min))
9248 (looking-at "^[^ ]+")
9249 (match-string 0))))
9250 (org-store-link-props :type "help"))
9252 ((eq major-mode 'w3-mode)
9253 (setq cpltxt (if (and (buffer-name)
9254 (not (string-match "Untitled" (buffer-name))))
9255 (buffer-name)
9256 (url-view-url t))
9257 link (url-view-url t))
9258 (org-store-link-props :type "w3" :url (url-view-url t)))
9260 ((setq search (run-hook-with-args-until-success
9261 'org-create-file-search-functions))
9262 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9263 "::" search))
9264 (setq cpltxt (or description link)))
9266 ((eq major-mode 'image-mode)
9267 (setq cpltxt (concat "file:"
9268 (abbreviate-file-name buffer-file-name))
9269 link cpltxt)
9270 (org-store-link-props :type "image" :file buffer-file-name))
9272 ((eq major-mode 'dired-mode)
9273 ;; link to the file in the current line
9274 (let ((file (dired-get-filename nil t)))
9275 (setq file (if file
9276 (abbreviate-file-name
9277 (expand-file-name (dired-get-filename nil t)))
9278 ;; otherwise, no file so use current directory.
9279 default-directory))
9280 (setq cpltxt (concat "file:" file)
9281 link cpltxt)))
9283 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9284 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9285 (cond
9286 ((org-in-regexp "<<\\(.*?\\)>>")
9287 (setq cpltxt
9288 (concat "file:"
9289 (abbreviate-file-name
9290 (buffer-file-name (buffer-base-buffer)))
9291 "::" (match-string 1))
9292 link cpltxt))
9293 ((and (featurep 'org-id)
9294 (or (eq org-id-link-to-org-use-id t)
9295 (and (org-called-interactively-p 'any)
9296 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9297 (and (eq org-id-link-to-org-use-id
9298 'create-if-interactive-and-no-custom-id)
9299 (not custom-id))))
9300 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9301 ;; We can make a link using the ID.
9302 (setq link (condition-case nil
9303 (prog1 (org-id-store-link)
9304 (setq desc (plist-get org-store-link-plist :description)))
9305 (error
9306 ;; probably before first headline, link to file only
9307 (concat "file:"
9308 (abbreviate-file-name
9309 (buffer-file-name (buffer-base-buffer))))))))
9311 ;; Just link to current headline
9312 (setq cpltxt (concat "file:"
9313 (abbreviate-file-name
9314 (buffer-file-name (buffer-base-buffer)))))
9315 ;; Add a context search string
9316 (when (org-xor org-context-in-file-links arg)
9317 (let* ((ee (org-element-at-point))
9318 (et (org-element-type ee))
9319 (ev (plist-get (cadr ee) :value)))
9320 (setq txt (cond
9321 ((org-at-heading-p) nil)
9322 ((eq et 'keyword) ev)
9323 ((org-region-active-p)
9324 (buffer-substring (region-beginning) (region-end)))))
9325 (when (or (null txt) (string-match "\\S-" txt))
9326 (setq cpltxt
9327 (concat cpltxt "::"
9328 (condition-case nil
9329 (org-make-org-heading-search-string txt)
9330 (error "")))
9331 desc (or (and (eq et 'keyword) ev)
9332 (nth 4 (ignore-errors (org-heading-components)))
9333 "NONE")))))
9334 (if (string-match "::\\'" cpltxt)
9335 (setq cpltxt (substring cpltxt 0 -2)))
9336 (setq link cpltxt))))
9338 ((buffer-file-name (buffer-base-buffer))
9339 ;; Just link to this file here.
9340 (setq cpltxt (concat "file:"
9341 (abbreviate-file-name
9342 (buffer-file-name (buffer-base-buffer)))))
9343 ;; Add a context string
9344 (when (org-xor org-context-in-file-links arg)
9345 (setq txt (if (org-region-active-p)
9346 (buffer-substring (region-beginning) (region-end))
9347 (buffer-substring (point-at-bol) (point-at-eol))))
9348 ;; Only use search option if there is some text.
9349 (when (string-match "\\S-" txt)
9350 (setq cpltxt
9351 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9352 desc "NONE")))
9353 (setq link cpltxt))
9355 ((org-called-interactively-p 'interactive)
9356 (user-error "No method for storing a link from this buffer"))
9358 (t (setq link nil)))
9360 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9361 (setq link (or link cpltxt)
9362 desc (or desc cpltxt))
9363 (cond ((equal desc "NONE") (setq desc nil))
9364 ((string-match org-bracket-link-regexp desc)
9365 (setq desc (replace-regexp-in-string
9366 org-bracket-link-regexp
9367 (concat "\\3" (if (equal (length (match-string 0 desc))
9368 (length desc)) "*" "")) desc))))
9370 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9371 (progn
9372 (setq org-stored-links
9373 (cons (list link desc) org-stored-links))
9374 (message "Stored: %s" (or desc link))
9375 (when custom-id
9376 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9377 "::#" custom-id))
9378 (setq org-stored-links
9379 (cons (list link desc) org-stored-links))))
9380 (or agenda-link (and link (org-make-link-string link desc)))))))
9382 (defun org-store-link-props (&rest plist)
9383 "Store link properties, extract names and addresses."
9384 (let (x adr)
9385 (when (setq x (plist-get plist :from))
9386 (setq adr (mail-extract-address-components x))
9387 (setq plist (plist-put plist :fromname (car adr)))
9388 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9389 (when (setq x (plist-get plist :to))
9390 (setq adr (mail-extract-address-components x))
9391 (setq plist (plist-put plist :toname (car adr)))
9392 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9393 (let ((from (plist-get plist :from))
9394 (to (plist-get plist :to)))
9395 (when (and from to org-from-is-user-regexp)
9396 (setq plist
9397 (plist-put plist :fromto
9398 (if (string-match org-from-is-user-regexp from)
9399 (concat "to %t")
9400 (concat "from %f"))))))
9401 (setq org-store-link-plist plist))
9403 (defun org-add-link-props (&rest plist)
9404 "Add these properties to the link property list."
9405 (let (key value)
9406 (while plist
9407 (setq key (pop plist) value (pop plist))
9408 (setq org-store-link-plist
9409 (plist-put org-store-link-plist key value)))))
9411 (defun org-email-link-description (&optional fmt)
9412 "Return the description part of an email link.
9413 This takes information from `org-store-link-plist' and formats it
9414 according to FMT (default from `org-email-link-description-format')."
9415 (setq fmt (or fmt org-email-link-description-format))
9416 (let* ((p org-store-link-plist)
9417 (to (plist-get p :toaddress))
9418 (from (plist-get p :fromaddress))
9419 (table
9420 (list
9421 (cons "%c" (plist-get p :fromto))
9422 (cons "%F" (plist-get p :from))
9423 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9424 (cons "%T" (plist-get p :to))
9425 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9426 (cons "%s" (plist-get p :subject))
9427 (cons "%d" (plist-get p :date))
9428 (cons "%m" (plist-get p :message-id)))))
9429 (when (string-match "%c" fmt)
9430 ;; Check if the user wrote this message
9431 (if (and org-from-is-user-regexp from to
9432 (save-match-data (string-match org-from-is-user-regexp from)))
9433 (setq fmt (replace-match "to %t" t t fmt))
9434 (setq fmt (replace-match "from %f" t t fmt))))
9435 (org-replace-escapes fmt table)))
9437 (defun org-make-org-heading-search-string (&optional string)
9438 "Make search string for the current headline or STRING."
9439 (let ((s (or string
9440 (and (derived-mode-p 'org-mode)
9441 (save-excursion
9442 (org-back-to-heading t)
9443 (org-element-property :raw-value (org-element-at-point))))))
9444 (lines org-context-in-file-links))
9445 (or string (setq s (concat "*" s))) ; Add * for headlines
9446 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9447 (when (and string (integerp lines) (> lines 0))
9448 (let ((slines (org-split-string s "\n")))
9449 (when (< lines (length slines))
9450 (setq s (mapconcat
9451 'identity
9452 (reverse (nthcdr (- (length slines) lines)
9453 (reverse slines))) "\n")))))
9454 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9456 (defun org-make-link-string (link &optional description)
9457 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9458 (unless (string-match "\\S-" link)
9459 (error "Empty link"))
9460 (when (and description
9461 (stringp description)
9462 (not (string-match "\\S-" description)))
9463 (setq description nil))
9464 (when (stringp description)
9465 ;; Remove brackets from the description, they are fatal.
9466 (while (string-match "\\[" description)
9467 (setq description (replace-match "{" t t description)))
9468 (while (string-match "\\]" description)
9469 (setq description (replace-match "}" t t description))))
9470 (when (equal link description)
9471 ;; No description needed, it is identical
9472 (setq description nil))
9473 (when (and (not description)
9474 (not (string-match (org-image-file-name-regexp) link))
9475 (not (equal link (org-link-escape link))))
9476 (setq description (org-extract-attributes link)))
9477 (setq link
9478 (cond ((string-match (org-image-file-name-regexp) link) link)
9479 ((string-match org-link-types-re link)
9480 (concat (match-string 1 link)
9481 (org-link-escape (substring link (match-end 1)))))
9482 (t (org-link-escape link))))
9483 (concat "[[" link "]"
9484 (if description (concat "[" description "]") "")
9485 "]"))
9487 (defconst org-link-escape-chars
9488 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9489 "List of characters that should be escaped in link.
9490 This is the list that is used for internal purposes.")
9492 (defconst org-link-escape-chars-browser
9493 '(?\ )
9494 "List of escapes for characters that are problematic in links.
9495 This is the list that is used before handing over to the browser.")
9497 (defun org-link-escape (text &optional table merge)
9498 "Return percent escaped representation of TEXT.
9499 TEXT is a string with the text to escape.
9500 Optional argument TABLE is a list with characters that should be
9501 escaped. When nil, `org-link-escape-chars' is used.
9502 If optional argument MERGE is set, merge TABLE into
9503 `org-link-escape-chars'."
9504 (cond
9505 ((and table merge)
9506 (mapc (lambda (defchr)
9507 (unless (member defchr table)
9508 (setq table (cons defchr table)))) org-link-escape-chars))
9509 ((null table)
9510 (setq table org-link-escape-chars)))
9511 (mapconcat
9512 (lambda (char)
9513 (if (or (member char table)
9514 (and (or (< char 32) (= char 37) (> char 126))
9515 org-url-hexify-p))
9516 (mapconcat (lambda (sequence-element)
9517 (format "%%%.2X" sequence-element))
9518 (or (encode-coding-char char 'utf-8)
9519 (error "Unable to percent escape character: %s"
9520 (char-to-string char))) "")
9521 (char-to-string char))) text ""))
9523 (defun org-link-unescape (str)
9524 "Unhex hexified Unicode strings as returned from the JavaScript function
9525 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9526 (unless (and (null str) (string= "" str))
9527 (let ((pos 0) (case-fold-search t) unhexed)
9528 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9529 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9530 (setq str (replace-match unhexed t t str))
9531 (setq pos (+ pos (length unhexed))))))
9532 str)
9534 (defun org-link-unescape-compound (hex)
9535 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9536 Note: this function also decodes single byte encodings like
9537 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9538 (save-match-data
9539 (let* ((bytes (cdr (split-string hex "%")))
9540 (ret "")
9541 (eat 0)
9542 (sum 0))
9543 (while bytes
9544 (let* ((val (string-to-number (pop bytes) 16))
9545 (shift-xor
9546 (if (= 0 eat)
9547 (cond
9548 ((>= val 252) (cons 6 252))
9549 ((>= val 248) (cons 5 248))
9550 ((>= val 240) (cons 4 240))
9551 ((>= val 224) (cons 3 224))
9552 ((>= val 192) (cons 2 192))
9553 (t (cons 0 0)))
9554 (cons 6 128))))
9555 (if (>= val 192) (setq eat (car shift-xor)))
9556 (setq val (logxor val (cdr shift-xor)))
9557 (setq sum (+ (lsh sum (car shift-xor)) val))
9558 (if (> eat 0) (setq eat (- eat 1)))
9559 (cond
9560 ((= 0 eat) ;multi byte
9561 (setq ret (concat ret (org-char-to-string sum)))
9562 (setq sum 0))
9563 ((not bytes) ; single byte(s)
9564 (setq ret (org-link-unescape-single-byte-sequence hex))))
9565 )) ;; end (while bytes
9566 ret )))
9568 (defun org-link-unescape-single-byte-sequence (hex)
9569 "Unhexify hex-encoded single byte character sequences."
9570 (mapconcat (lambda (byte)
9571 (char-to-string (string-to-number byte 16)))
9572 (cdr (split-string hex "%")) ""))
9574 (defun org-xor (a b)
9575 "Exclusive or."
9576 (if a (not b) b))
9578 (defun org-fixup-message-id-for-http (s)
9579 "Replace special characters in a message id, so it can be used in an http query."
9580 (when (string-match "%" s)
9581 (setq s (mapconcat (lambda (c)
9582 (if (eq c ?%)
9583 "%25"
9584 (char-to-string c)))
9585 s "")))
9586 (while (string-match "<" s)
9587 (setq s (replace-match "%3C" t t s)))
9588 (while (string-match ">" s)
9589 (setq s (replace-match "%3E" t t s)))
9590 (while (string-match "@" s)
9591 (setq s (replace-match "%40" t t s)))
9594 (defun org-link-prettify (link)
9595 "Return a human-readable representation of LINK.
9596 The car of LINK must be a raw link the cdr of LINK must be either
9597 a link description or nil."
9598 (let ((desc (or (cadr link) "<no description>")))
9599 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9600 "<" (car link) ">")))
9602 ;;;###autoload
9603 (defun org-insert-link-global ()
9604 "Insert a link like Org-mode does.
9605 This command can be called in any mode to insert a link in Org-mode syntax."
9606 (interactive)
9607 (org-load-modules-maybe)
9608 (org-run-like-in-org-mode 'org-insert-link))
9610 (defun org-insert-all-links (&optional keep)
9611 "Insert all links in `org-stored-links'."
9612 (interactive "P")
9613 (let ((links (copy-sequence org-stored-links)) l)
9614 (while (setq l (if keep (pop links) (pop org-stored-links)))
9615 (insert "- ")
9616 (org-insert-link nil (car l) (cadr l))
9617 (insert "\n"))))
9619 (defun org-link-fontify-links-to-this-file ()
9620 "Fontify links to the current file in `org-stored-links'."
9621 (let ((f (buffer-file-name)) a b)
9622 (setq a (mapcar (lambda(l)
9623 (let ((ll (car l)))
9624 (when (and (string-match "^file:\\(.+\\)::" ll)
9625 (equal f (expand-file-name (match-string 1 ll))))
9626 ll)))
9627 org-stored-links))
9628 (when (featurep 'org-id)
9629 (setq b (mapcar (lambda(l)
9630 (let ((ll (car l)))
9631 (when (and (string-match "^id:\\(.+\\)$" ll)
9632 (equal f (expand-file-name
9633 (or (org-id-find-id-file
9634 (match-string 1 ll)) ""))))
9635 ll)))
9636 org-stored-links)))
9637 (mapcar (lambda(l)
9638 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9639 (delq nil (append a b)))))
9641 (defvar org-link-links-in-this-file nil)
9642 (defun org-insert-link (&optional complete-file link-location default-description)
9643 "Insert a link. At the prompt, enter the link.
9645 Completion can be used to insert any of the link protocol prefixes like
9646 http or ftp in use.
9648 The history can be used to select a link previously stored with
9649 `org-store-link'. When the empty string is entered (i.e. if you just
9650 press RET at the prompt), the link defaults to the most recently
9651 stored link. As SPC triggers completion in the minibuffer, you need to
9652 use M-SPC or C-q SPC to force the insertion of a space character.
9654 You will also be prompted for a description, and if one is given, it will
9655 be displayed in the buffer instead of the link.
9657 If there is already a link at point, this command will allow you to edit link
9658 and description parts.
9660 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9661 be selected using completion. The path to the file will be relative to the
9662 current directory if the file is in the current directory or a subdirectory.
9663 Otherwise, the link will be the absolute path as completed in the minibuffer
9664 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9665 option `org-link-file-path-type'.
9667 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9668 the current directory or below.
9670 With three \\[universal-argument] prefixes, negate the meaning of
9671 `org-keep-stored-link-after-insertion'.
9673 If `org-make-link-description-function' is non-nil, this function will be
9674 called with the link target, and the result will be the default
9675 link description.
9677 If the LINK-LOCATION parameter is non-nil, this value will be
9678 used as the link location instead of reading one interactively.
9680 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9681 be used as the default description."
9682 (interactive "P")
9683 (let* ((wcf (current-window-configuration))
9684 (origbuf (current-buffer))
9685 (region (if (org-region-active-p)
9686 (buffer-substring (region-beginning) (region-end))))
9687 (remove (and region (list (region-beginning) (region-end))))
9688 (desc region)
9689 tmphist ; byte-compile incorrectly complains about this
9690 (link link-location)
9691 (abbrevs org-link-abbrev-alist-local)
9692 entry file all-prefixes auto-desc)
9693 (cond
9694 (link-location) ; specified by arg, just use it.
9695 ((org-in-regexp org-bracket-link-regexp 1)
9696 ;; We do have a link at point, and we are going to edit it.
9697 (setq remove (list (match-beginning 0) (match-end 0)))
9698 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9699 (setq link (read-string "Link: "
9700 (org-link-unescape
9701 (org-match-string-no-properties 1)))))
9702 ((or (org-in-regexp org-angle-link-re)
9703 (org-in-regexp org-plain-link-re))
9704 ;; Convert to bracket link
9705 (setq remove (list (match-beginning 0) (match-end 0))
9706 link (read-string "Link: "
9707 (org-remove-angle-brackets (match-string 0)))))
9708 ((member complete-file '((4) (16)))
9709 ;; Completing read for file names.
9710 (setq link (org-file-complete-link complete-file)))
9712 ;; Read link, with completion for stored links.
9713 (org-link-fontify-links-to-this-file)
9714 (org-switch-to-buffer-other-window "*Org Links*")
9715 (with-current-buffer "*Org Links*"
9716 (erase-buffer)
9717 (insert "Insert a link.
9718 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9719 (when org-stored-links
9720 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9721 (insert (mapconcat 'org-link-prettify
9722 (reverse org-stored-links) "\n")))
9723 (goto-char (point-min)))
9724 (let ((cw (selected-window)))
9725 (select-window (get-buffer-window "*Org Links*" 'visible))
9726 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9727 (unless (pos-visible-in-window-p (point-max))
9728 (org-fit-window-to-buffer))
9729 (and (window-live-p cw) (select-window cw)))
9730 ;; Fake a link history, containing the stored links.
9731 (setq tmphist (append (mapcar 'car org-stored-links)
9732 org-insert-link-history))
9733 (setq all-prefixes (append (mapcar 'car abbrevs)
9734 (mapcar 'car org-link-abbrev-alist)
9735 org-link-types))
9736 (unwind-protect
9737 (progn
9738 (setq link
9739 (org-completing-read
9740 "Link: "
9741 (append
9742 (mapcar (lambda (x) (concat x ":"))
9743 all-prefixes)
9744 (mapcar 'car org-stored-links))
9745 nil nil nil
9746 'tmphist
9747 (caar org-stored-links)))
9748 (if (not (string-match "\\S-" link))
9749 (error "No link selected"))
9750 (mapc (lambda(l)
9751 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9752 org-stored-links)
9753 (if (or (member link all-prefixes)
9754 (and (equal ":" (substring link -1))
9755 (member (substring link 0 -1) all-prefixes)
9756 (setq link (substring link 0 -1))))
9757 (setq link (with-current-buffer origbuf
9758 (org-link-try-special-completion link)))))
9759 (set-window-configuration wcf)
9760 (kill-buffer "*Org Links*"))
9761 (setq entry (assoc link org-stored-links))
9762 (or entry (push link org-insert-link-history))
9763 (setq desc (or desc (nth 1 entry)))))
9765 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9766 (not org-keep-stored-link-after-insertion))
9767 (setq org-stored-links (delq (assoc link org-stored-links)
9768 org-stored-links)))
9770 (if (string-match org-plain-link-re link)
9771 ;; URL-like link, normalize the use of angular brackets.
9772 (setq link (org-remove-angle-brackets link)))
9774 ;; Check if we are linking to the current file with a search
9775 ;; option If yes, simplify the link by using only the search
9776 ;; option.
9777 (when (and buffer-file-name
9778 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9779 (let* ((path (match-string 1 link))
9780 (case-fold-search nil)
9781 (search (match-string 2 link)))
9782 (save-match-data
9783 (if (equal (file-truename buffer-file-name) (file-truename path))
9784 ;; We are linking to this same file, with a search option
9785 (setq link search)))))
9787 ;; Check if we can/should use a relative path. If yes, simplify the link
9788 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9789 (let* ((type (match-string 1 link))
9790 (path (match-string 2 link))
9791 (origpath path)
9792 (case-fold-search nil))
9793 (cond
9794 ((or (eq org-link-file-path-type 'absolute)
9795 (equal complete-file '(16)))
9796 (setq path (abbreviate-file-name (expand-file-name path))))
9797 ((eq org-link-file-path-type 'noabbrev)
9798 (setq path (expand-file-name path)))
9799 ((eq org-link-file-path-type 'relative)
9800 (setq path (file-relative-name path)))
9802 (save-match-data
9803 (if (string-match (concat "^" (regexp-quote
9804 (expand-file-name
9805 (file-name-as-directory
9806 default-directory))))
9807 (expand-file-name path))
9808 ;; We are linking a file with relative path name.
9809 (setq path (substring (expand-file-name path)
9810 (match-end 0)))
9811 (setq path (abbreviate-file-name (expand-file-name path)))))))
9812 (setq link (concat type path))
9813 (if (equal desc origpath)
9814 (setq desc path))))
9816 (if org-make-link-description-function
9817 (setq desc
9818 (or (condition-case nil
9819 (funcall org-make-link-description-function link desc)
9820 (error (progn (message "Can't get link description from `%s'"
9821 (symbol-name org-make-link-description-function))
9822 (sit-for 2) nil)))
9823 (read-string "Description: " default-description)))
9824 (if default-description (setq desc default-description)
9825 (setq desc (or (and auto-desc desc)
9826 (read-string "Description: " desc)))))
9828 (unless (string-match "\\S-" desc) (setq desc nil))
9829 (if remove (apply 'delete-region remove))
9830 (insert (org-make-link-string link desc))))
9832 (defun org-link-try-special-completion (type)
9833 "If there is completion support for link type TYPE, offer it."
9834 (let ((fun (intern (concat "org-" type "-complete-link"))))
9835 (if (functionp fun)
9836 (funcall fun)
9837 (read-string "Link (no completion support): " (concat type ":")))))
9839 (defun org-file-complete-link (&optional arg)
9840 "Create a file link using completion."
9841 (let (file link)
9842 (setq file (org-iread-file-name "File: "))
9843 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9844 (pwd1 (file-name-as-directory (abbreviate-file-name
9845 (expand-file-name ".")))))
9846 (cond
9847 ((equal arg '(16))
9848 (setq link (concat
9849 "file:"
9850 (abbreviate-file-name (expand-file-name file)))))
9851 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9852 (setq link (concat "file:" (match-string 1 file))))
9853 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9854 (expand-file-name file))
9855 (setq link (concat
9856 "file:" (match-string 1 (expand-file-name file)))))
9857 (t (setq link (concat "file:" file)))))
9858 link))
9860 (defun org-iread-file-name (&rest args)
9861 "Read-file-name using `ido-mode' speedup if available.
9862 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9863 See `read-file-name' for a description of parameters."
9864 (org-without-partial-completion
9865 (if (and org-completion-use-ido
9866 (fboundp 'ido-read-file-name)
9867 (boundp 'ido-mode) ido-mode
9868 (listp (second args)))
9869 (let ((ido-enter-matching-directory nil))
9870 (apply 'ido-read-file-name args))
9871 (apply 'read-file-name args))))
9873 (defun org-completing-read (&rest args)
9874 "Completing-read with SPACE being a normal character."
9875 (let ((enable-recursive-minibuffers t)
9876 (minibuffer-local-completion-map
9877 (copy-keymap minibuffer-local-completion-map)))
9878 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9879 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9880 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9881 (apply 'org-icompleting-read args)))
9883 (defun org-completing-read-no-i (&rest args)
9884 (let (org-completion-use-ido org-completion-use-iswitchb)
9885 (apply 'org-completing-read args)))
9887 (defun org-iswitchb-completing-read (prompt choices &rest args)
9888 "Use iswitch as a completing-read replacement to choose from choices.
9889 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9890 from."
9891 (let* ((iswitchb-use-virtual-buffers nil)
9892 (iswitchb-make-buflist-hook
9893 (lambda ()
9894 (setq iswitchb-temp-buflist choices))))
9895 (iswitchb-read-buffer prompt)))
9897 (defun org-icompleting-read (&rest args)
9898 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9899 (org-without-partial-completion
9900 (if (and org-completion-use-ido
9901 (fboundp 'ido-completing-read)
9902 (boundp 'ido-mode) ido-mode
9903 (listp (second args)))
9904 (let ((ido-enter-matching-directory nil))
9905 (apply 'ido-completing-read (concat (car args))
9906 (if (consp (car (nth 1 args)))
9907 (mapcar 'car (nth 1 args))
9908 (nth 1 args))
9909 (cddr args)))
9910 (if (and org-completion-use-iswitchb
9911 (boundp 'iswitchb-mode) iswitchb-mode
9912 (listp (second args)))
9913 (apply 'org-iswitchb-completing-read (concat (car args))
9914 (if (consp (car (nth 1 args)))
9915 (mapcar 'car (nth 1 args))
9916 (nth 1 args))
9917 (cddr args))
9918 (apply 'completing-read args)))))
9920 (defun org-extract-attributes (s)
9921 "Extract the attributes cookie from a string and set as text property."
9922 (let (a attr (start 0) key value)
9923 (save-match-data
9924 (when (string-match "{{\\([^}]+\\)}}$" s)
9925 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9926 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9927 (setq key (match-string 1 a) value (match-string 2 a)
9928 start (match-end 0)
9929 attr (plist-put attr (intern key) value))))
9930 (org-add-props s nil 'org-attr attr))
9933 (defun org-extract-attributes-from-string (tag)
9934 (let (key value attr)
9935 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9936 (setq key (match-string 1 tag) value (match-string 2 tag)
9937 tag (replace-match "" t t tag)
9938 attr (plist-put attr (intern key) value)))
9939 (cons tag attr)))
9941 (defun org-attributes-to-string (plist)
9942 "Format a property list into an HTML attribute list."
9943 (let ((s "") key value)
9944 (while plist
9945 (setq key (pop plist) value (pop plist))
9946 (and value
9947 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9950 ;;; Opening/following a link
9952 (defvar org-link-search-failed nil)
9954 (defvar org-open-link-functions nil
9955 "Hook for functions finding a plain text link.
9956 These functions must take a single argument, the link content.
9957 They will be called for links that look like [[link text][description]]
9958 when LINK TEXT does not have a protocol like \"http:\" and does not look
9959 like a filename (e.g. \"./blue.png\").
9961 These functions will be called *before* Org attempts to resolve the
9962 link by doing text searches in the current buffer - so if you want a
9963 link \"[[target]]\" to still find \"<<target>>\", your function should
9964 handle this as a special case.
9966 When the function does handle the link, it must return a non-nil value.
9967 If it decides that it is not responsible for this link, it must return
9968 nil to indicate that that Org-mode can continue with other options
9969 like exact and fuzzy text search.")
9971 (defun org-next-link (&optional search-backward)
9972 "Move forward to the next link.
9973 If the link is in hidden text, expose it."
9974 (interactive "P")
9975 (when (and org-link-search-failed (eq this-command last-command))
9976 (goto-char (point-min))
9977 (message "Link search wrapped back to beginning of buffer"))
9978 (setq org-link-search-failed nil)
9979 (let* ((pos (point))
9980 (ct (org-context))
9981 (a (assoc :link ct))
9982 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9983 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9984 ((looking-at org-any-link-re)
9985 ;; Don't stay stuck at link without an org-link face
9986 (forward-char (if search-backward -1 1))))
9987 (if (funcall srch-fun org-any-link-re nil t)
9988 (progn
9989 (goto-char (match-beginning 0))
9990 (if (outline-invisible-p) (org-show-context)))
9991 (goto-char pos)
9992 (setq org-link-search-failed t)
9993 (message "No further link found"))))
9995 (defun org-previous-link ()
9996 "Move backward to the previous link.
9997 If the link is in hidden text, expose it."
9998 (interactive)
9999 (funcall 'org-next-link t))
10001 (defun org-translate-link (s)
10002 "Translate a link string if a translation function has been defined."
10003 (if (and org-link-translation-function
10004 (fboundp org-link-translation-function)
10005 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10006 (progn
10007 (setq s (funcall org-link-translation-function
10008 (match-string 1 s) (match-string 2 s)))
10009 (concat (car s) ":" (cdr s)))
10012 (defun org-translate-link-from-planner (type path)
10013 "Translate a link from Emacs Planner syntax so that Org can follow it.
10014 This is still an experimental function, your mileage may vary."
10015 (cond
10016 ((member type '("http" "https" "news" "ftp"))
10017 ;; standard Internet links are the same.
10018 nil)
10019 ((and (equal type "irc") (string-match "^//" path))
10020 ;; Planner has two / at the beginning of an irc link, we have 1.
10021 ;; We should have zero, actually....
10022 (setq path (substring path 1)))
10023 ((and (equal type "lisp") (string-match "^/" path))
10024 ;; Planner has a slash, we do not.
10025 (setq type "elisp" path (substring path 1)))
10026 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10027 ;; A typical message link. Planner has the id after the final slash,
10028 ;; we separate it with a hash mark
10029 (setq path (concat (match-string 1 path) "#"
10030 (org-remove-angle-brackets (match-string 2 path)))))
10032 (cons type path))
10034 (defun org-find-file-at-mouse (ev)
10035 "Open file link or URL at mouse."
10036 (interactive "e")
10037 (mouse-set-point ev)
10038 (org-open-at-point 'in-emacs))
10040 (defun org-open-at-mouse (ev)
10041 "Open file link or URL at mouse.
10042 See the docstring of `org-open-file' for details."
10043 (interactive "e")
10044 (mouse-set-point ev)
10045 (if (eq major-mode 'org-agenda-mode)
10046 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10047 (org-open-at-point))
10049 (defvar org-window-config-before-follow-link nil
10050 "The window configuration before following a link.
10051 This is saved in case the need arises to restore it.")
10053 (defvar org-open-link-marker (make-marker)
10054 "Marker pointing to the location where `org-open-at-point; was called.")
10056 ;;;###autoload
10057 (defun org-open-at-point-global ()
10058 "Follow a link like Org-mode does.
10059 This command can be called in any mode to follow a link that has
10060 Org-mode syntax."
10061 (interactive)
10062 (org-run-like-in-org-mode 'org-open-at-point))
10064 ;;;###autoload
10065 (defun org-open-link-from-string (s &optional arg reference-buffer)
10066 "Open a link in the string S, as if it was in Org-mode."
10067 (interactive "sLink: \nP")
10068 (let ((reference-buffer (or reference-buffer (current-buffer))))
10069 (with-temp-buffer
10070 (let ((org-inhibit-startup (not reference-buffer)))
10071 (org-mode)
10072 (insert s)
10073 (goto-char (point-min))
10074 (when reference-buffer
10075 (setq org-link-abbrev-alist-local
10076 (with-current-buffer reference-buffer
10077 org-link-abbrev-alist-local)))
10078 (org-open-at-point arg reference-buffer)))))
10080 (defvar org-open-at-point-functions nil
10081 "Hook that is run when following a link at point.
10083 Functions in this hook must return t if they identify and follow
10084 a link at point. If they don't find anything interesting at point,
10085 they must return nil.")
10087 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10088 (defun org-open-at-point (&optional arg reference-buffer)
10089 "Open link at or after point.
10090 If there is no link at point, this function will search forward up to
10091 the end of the current line.
10092 Normally, files will be opened by an appropriate application. If the
10093 optional prefix argument ARG is non-nil, Emacs will visit the file.
10094 With a double prefix argument, try to open outside of Emacs, in the
10095 application the system uses for this file type."
10096 (interactive "P")
10097 ;; if in a code block, then open the block's results
10098 (unless (call-interactively #'org-babel-open-src-block-result)
10099 (org-load-modules-maybe)
10100 (move-marker org-open-link-marker (point))
10101 (setq org-window-config-before-follow-link (current-window-configuration))
10102 (org-remove-occur-highlights nil nil t)
10103 (cond
10104 ((and (org-at-heading-p)
10105 (not (org-at-timestamp-p t))
10106 (not (org-in-regexp
10107 (concat org-plain-link-re "\\|"
10108 org-bracket-link-regexp "\\|"
10109 org-angle-link-re "\\|"
10110 "[ \t]:[^ \t\n]+:[ \t]*$")))
10111 (not (get-text-property (point) 'org-linked-text)))
10112 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10113 (lk0 (car lkall))
10114 (lk (if (stringp lk0) (list lk0) lk0))
10115 (lkend (cdr lkall)))
10116 (mapcar (lambda(l)
10117 (search-forward l nil lkend)
10118 (goto-char (match-beginning 0))
10119 (org-open-at-point))
10120 lk))
10121 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10122 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10123 ((and (org-at-timestamp-p t)
10124 (not (org-in-regexp org-bracket-link-regexp)))
10125 (org-follow-timestamp-link))
10126 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10127 (not (org-in-regexp org-any-link-re)))
10128 (org-footnote-action))
10130 (let (type path link line search (pos (point)))
10131 (catch 'match
10132 (save-excursion
10133 (skip-chars-forward "^]\n\r")
10134 (when (org-in-regexp org-bracket-link-regexp 1)
10135 (setq link (org-extract-attributes
10136 (org-link-unescape (org-match-string-no-properties 1))))
10137 (while (string-match " *\n *" link)
10138 (setq link (replace-match " " t t link)))
10139 (setq link (org-link-expand-abbrev link))
10140 (cond
10141 ((or (file-name-absolute-p link)
10142 (string-match "^\\.\\.?/" link))
10143 (setq type "file" path link))
10144 ((string-match org-link-re-with-space3 link)
10145 (setq type (match-string 1 link) path (match-string 2 link)))
10146 ((string-match "^help:+\\(.+\\)" link)
10147 (setq type "help" path (match-string 1 link)))
10148 (t (setq type "thisfile" path link)))
10149 (throw 'match t)))
10151 (when (get-text-property (point) 'org-linked-text)
10152 (setq type "thisfile"
10153 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10154 (1+ (point)) (point))
10155 path (buffer-substring
10156 (or (previous-single-property-change pos 'org-linked-text)
10157 (point-min))
10158 (or (next-single-property-change pos 'org-linked-text)
10159 (point-max))))
10160 (throw 'match t))
10162 (save-excursion
10163 (when (or (org-in-regexp org-angle-link-re)
10164 (let ((match (org-in-regexp org-plain-link-re)))
10165 ;; Check a plain link is not within a bracket link
10166 (and match
10167 (save-excursion
10168 (progn
10169 (goto-char (car match))
10170 (not (org-in-regexp org-bracket-link-regexp))))))
10171 (let ((line_ending (save-excursion (end-of-line) (point))))
10172 ;; We are in a line before a plain or bracket link
10173 (or (re-search-forward org-plain-link-re line_ending t)
10174 (re-search-forward org-bracket-link-regexp line_ending t))))
10175 (setq type (match-string 1)
10176 path (org-link-unescape (match-string 2)))
10177 (throw 'match t)))
10178 (save-excursion
10179 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10180 (setq type "tags"
10181 path (match-string 1))
10182 (while (string-match ":" path)
10183 (setq path (replace-match "+" t t path)))
10184 (throw 'match t)))
10185 (when (org-in-regexp "<\\([^><\n]+\\)>")
10186 (setq type "tree-match"
10187 path (match-string 1))
10188 (throw 'match t)))
10189 (unless path
10190 (user-error "No link found"))
10192 ;; switch back to reference buffer
10193 ;; needed when if called in a temporary buffer through
10194 ;; org-open-link-from-string
10195 (with-current-buffer (or reference-buffer (current-buffer))
10197 ;; Remove any trailing spaces in path
10198 (if (string-match " +\\'" path)
10199 (setq path (replace-match "" t t path)))
10200 (if (and org-link-translation-function
10201 (fboundp org-link-translation-function))
10202 ;; Check if we need to translate the link
10203 (let ((tmp (funcall org-link-translation-function type path)))
10204 (setq type (car tmp) path (cdr tmp))))
10206 (cond
10208 ((assoc type org-link-protocols)
10209 (funcall (nth 1 (assoc type org-link-protocols)) path))
10211 ((equal type "help")
10212 (let ((f-or-v (intern path)))
10213 (cond ((fboundp f-or-v)
10214 (describe-function f-or-v))
10215 ((boundp f-or-v)
10216 (describe-variable f-or-v))
10217 (t (error "Not a known function or variable")))))
10219 ((equal type "mailto")
10220 (let ((cmd (car org-link-mailto-program))
10221 (args (cdr org-link-mailto-program)) args1
10222 (address path) (subject "") a)
10223 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10224 (setq address (match-string 1 path)
10225 subject (org-link-escape (match-string 2 path))))
10226 (while args
10227 (cond
10228 ((not (stringp (car args))) (push (pop args) args1))
10229 (t (setq a (pop args))
10230 (if (string-match "%a" a)
10231 (setq a (replace-match address t t a)))
10232 (if (string-match "%s" a)
10233 (setq a (replace-match subject t t a)))
10234 (push a args1))))
10235 (apply cmd (nreverse args1))))
10237 ((member type '("http" "https" "ftp" "news"))
10238 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10239 (org-link-escape
10240 path org-link-escape-chars-browser)
10241 path))))
10243 ((string= type "doi")
10244 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10245 (org-link-escape
10246 path org-link-escape-chars-browser)
10247 path))))
10249 ((member type '("message"))
10250 (browse-url (concat type ":" path)))
10252 ((string= type "tags")
10253 (org-tags-view arg path))
10255 ((string= type "tree-match")
10256 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10258 ((string= type "file")
10259 (if (string-match "::\\([0-9]+\\)\\'" path)
10260 (setq line (string-to-number (match-string 1 path))
10261 path (substring path 0 (match-beginning 0)))
10262 (if (string-match "::\\(.+\\)\\'" path)
10263 (setq search (match-string 1 path)
10264 path (substring path 0 (match-beginning 0)))))
10265 (if (string-match "[*?{]" (file-name-nondirectory path))
10266 (dired path)
10267 (org-open-file path arg line search)))
10269 ((string= type "shell")
10270 (let ((buf (generate-new-buffer "*Org Shell Output"))
10271 (cmd path))
10272 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10273 (string-match org-confirm-shell-link-not-regexp cmd))
10274 (not org-confirm-shell-link-function)
10275 (funcall org-confirm-shell-link-function
10276 (format "Execute \"%s\" in shell? "
10277 (org-add-props cmd nil
10278 'face 'org-warning))))
10279 (progn
10280 (message "Executing %s" cmd)
10281 (shell-command cmd buf)
10282 (if (featurep 'midnight)
10283 (setq clean-buffer-list-kill-buffer-names
10284 (cons buf clean-buffer-list-kill-buffer-names))))
10285 (error "Abort"))))
10287 ((string= type "elisp")
10288 (let ((cmd path))
10289 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10290 (string-match org-confirm-elisp-link-not-regexp cmd))
10291 (not org-confirm-elisp-link-function)
10292 (funcall org-confirm-elisp-link-function
10293 (format "Execute \"%s\" as elisp? "
10294 (org-add-props cmd nil
10295 'face 'org-warning))))
10296 (message "%s => %s" cmd
10297 (if (equal (string-to-char cmd) ?\()
10298 (eval (read cmd))
10299 (call-interactively (read cmd))))
10300 (error "Abort"))))
10302 ((and (string= type "thisfile")
10303 (run-hook-with-args-until-success
10304 'org-open-link-functions path)))
10306 ((string= type "thisfile")
10307 (if arg
10308 (switch-to-buffer-other-window
10309 (org-get-buffer-for-internal-link (current-buffer)))
10310 (org-mark-ring-push))
10311 (let ((cmd `(org-link-search
10312 ,path
10313 ,(cond ((equal arg '(4)) ''occur)
10314 ((equal arg '(16)) ''org-occur))
10315 ,pos)))
10316 (condition-case nil (let ((org-link-search-inhibit-query t))
10317 (eval cmd))
10318 (error (progn (widen) (eval cmd))))))
10320 (t (browse-url-at-point)))))))
10321 (move-marker org-open-link-marker nil)
10322 (run-hook-with-args 'org-follow-link-hook)))
10324 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10325 "Offer links in the current entry and return the selected link.
10326 If there is only one link, return it.
10327 If NTH is an integer, return the NTH link found.
10328 If ZERO is a string, check also this string for a link, and if
10329 there is one, return it."
10330 (with-current-buffer buffer
10331 (save-excursion
10332 (save-restriction
10333 (widen)
10334 (goto-char marker)
10335 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10336 "\\(" org-angle-link-re "\\)\\|"
10337 "\\(" org-plain-link-re "\\)"))
10338 (cnt ?0)
10339 (in-emacs (if (integerp nth) nil nth))
10340 have-zero end links link c)
10341 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10342 (push (match-string 0 zero) links)
10343 (setq cnt (1- cnt) have-zero t))
10344 (save-excursion
10345 (org-back-to-heading t)
10346 (setq end (save-excursion (outline-next-heading) (point)))
10347 (while (re-search-forward re end t)
10348 (push (match-string 0) links))
10349 (setq links (org-uniquify (reverse links))))
10350 (cond
10351 ((null links)
10352 (message "No links"))
10353 ((equal (length links) 1)
10354 (setq link (car links)))
10355 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10356 (setq link (nth (if have-zero nth (1- nth)) links)))
10357 (t ; we have to select a link
10358 (save-excursion
10359 (save-window-excursion
10360 (delete-other-windows)
10361 (with-output-to-temp-buffer "*Select Link*"
10362 (mapc (lambda (l)
10363 (if (not (string-match org-bracket-link-regexp l))
10364 (princ (format "[%c] %s\n" (incf cnt)
10365 (org-remove-angle-brackets l)))
10366 (if (match-end 3)
10367 (princ (format "[%c] %s (%s)\n" (incf cnt)
10368 (match-string 3 l) (match-string 1 l)))
10369 (princ (format "[%c] %s\n" (incf cnt)
10370 (match-string 1 l))))))
10371 links))
10372 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10373 (message "Select link to open, RET to open all:")
10374 (setq c (read-char-exclusive))
10375 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10376 (when (equal c ?q) (error "Abort"))
10377 (if (equal c ?\C-m)
10378 (setq link links)
10379 (setq nth (- c ?0))
10380 (if have-zero (setq nth (1+ nth)))
10381 (unless (and (integerp nth) (>= (length links) nth))
10382 (error "Invalid link selection"))
10383 (setq link (nth (1- nth) links)))))
10384 (cons link end))))))
10386 ;; Add special file links that specify the way of opening
10388 (org-add-link-type "file+sys" 'org-open-file-with-system)
10389 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10390 (defun org-open-file-with-system (path)
10391 "Open file at PATH using the system way of opening it."
10392 (org-open-file path 'system))
10393 (defun org-open-file-with-emacs (path)
10394 "Open file at PATH in Emacs."
10395 (org-open-file path 'emacs))
10398 ;;; File search
10400 (defvar org-create-file-search-functions nil
10401 "List of functions to construct the right search string for a file link.
10402 These functions are called in turn with point at the location to
10403 which the link should point.
10405 A function in the hook should first test if it would like to
10406 handle this file type, for example by checking the `major-mode'
10407 or the file extension. If it decides not to handle this file, it
10408 should just return nil to give other functions a chance. If it
10409 does handle the file, it must return the search string to be used
10410 when following the link. The search string will be part of the
10411 file link, given after a double colon, and `org-open-at-point'
10412 will automatically search for it. If special measures must be
10413 taken to make the search successful, another function should be
10414 added to the companion hook `org-execute-file-search-functions',
10415 which see.
10417 A function in this hook may also use `setq' to set the variable
10418 `description' to provide a suggestion for the descriptive text to
10419 be used for this link when it gets inserted into an Org-mode
10420 buffer with \\[org-insert-link].")
10422 (defvar org-execute-file-search-functions nil
10423 "List of functions to execute a file search triggered by a link.
10425 Functions added to this hook must accept a single argument, the
10426 search string that was part of the file link, the part after the
10427 double colon. The function must first check if it would like to
10428 handle this search, for example by checking the `major-mode' or
10429 the file extension. If it decides not to handle this search, it
10430 should just return nil to give other functions a chance. If it
10431 does handle the search, it must return a non-nil value to keep
10432 other functions from trying.
10434 Each function can access the current prefix argument through the
10435 variable `current-prefix-argument'. Note that a single prefix is
10436 used to force opening a link in Emacs, so it may be good to only
10437 use a numeric or double prefix to guide the search function.
10439 In case this is needed, a function in this hook can also restore
10440 the window configuration before `org-open-at-point' was called using:
10442 (set-window-configuration org-window-config-before-follow-link)")
10444 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10445 (defun org-link-search (s &optional type avoid-pos stealth)
10446 "Search for a link search option.
10447 If S is surrounded by forward slashes, it is interpreted as a
10448 regular expression. In org-mode files, this will create an `org-occur'
10449 sparse tree. In ordinary files, `occur' will be used to list matches.
10450 If the current buffer is in `dired-mode', grep will be used to search
10451 in all files. If AVOID-POS is given, ignore matches near that position.
10453 When optional argument STEALTH is non-nil, do not modify
10454 visibility around point, thus ignoring
10455 `org-show-hierarchy-above', `org-show-following-heading' and
10456 `org-show-siblings' variables."
10457 (let ((case-fold-search t)
10458 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10459 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10460 (append '(("") (" ") ("\t") ("\n"))
10461 org-emphasis-alist)
10462 "\\|") "\\)"))
10463 (pos (point))
10464 (pre nil) (post nil)
10465 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10466 (cond
10467 ;; First check if there are any special search functions
10468 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10469 ;; Now try the builtin stuff
10470 ((and (equal (string-to-char s0) ?#)
10471 (> (length s0) 1)
10472 (save-excursion
10473 (goto-char (point-min))
10474 (and
10475 (re-search-forward
10476 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10477 (setq type 'dedicated
10478 pos (match-beginning 0))))
10479 ;; There is an exact target for this
10480 (goto-char pos)
10481 (org-back-to-heading t)))
10482 ((save-excursion
10483 (goto-char (point-min))
10484 (and
10485 (re-search-forward
10486 (concat "<<" (regexp-quote s0) ">>") nil t)
10487 (setq type 'dedicated
10488 pos (match-beginning 0))))
10489 ;; There is an exact target for this
10490 (goto-char pos))
10491 ((save-excursion
10492 (goto-char (point-min))
10493 (and
10494 (re-search-forward
10495 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10496 (setq type 'dedicated pos (match-beginning 0))))
10497 ;; Found an invisible target.
10498 (goto-char pos))
10499 ((save-excursion
10500 (goto-char (point-min))
10501 (and
10502 (re-search-forward
10503 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10504 (setq type 'dedicated pos (match-beginning 0))))
10505 ;; Found an element with a matching #+name affiliated keyword.
10506 (goto-char pos))
10507 ((and (string-match "^(\\(.*\\))$" s0)
10508 (save-excursion
10509 (goto-char (point-min))
10510 (and
10511 (re-search-forward
10512 (concat "[^[]" (regexp-quote
10513 (format org-coderef-label-format
10514 (match-string 1 s0))))
10515 nil t)
10516 (setq type 'dedicated
10517 pos (1+ (match-beginning 0))))))
10518 ;; There is a coderef target for this
10519 (goto-char pos))
10520 ((string-match "^/\\(.*\\)/$" s)
10521 ;; A regular expression
10522 (cond
10523 ((derived-mode-p 'org-mode)
10524 (org-occur (match-string 1 s)))
10525 (t (org-do-occur (match-string 1 s)))))
10526 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10527 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10528 (goto-char (point-min))
10529 (cond
10530 ((let (case-fold-search)
10531 (re-search-forward (format org-complex-heading-regexp-format
10532 (regexp-quote s))
10533 nil t))
10534 ;; OK, found a match
10535 (setq type 'dedicated)
10536 (goto-char (match-beginning 0)))
10537 ((and (not org-link-search-inhibit-query)
10538 (eq org-link-search-must-match-exact-headline 'query-to-create)
10539 (y-or-n-p "No match - create this as a new heading? "))
10540 (goto-char (point-max))
10541 (or (bolp) (newline))
10542 (insert "* " s "\n")
10543 (beginning-of-line 0))
10545 (goto-char pos)
10546 (error "No match"))))
10548 ;; A normal search string
10549 (when (equal (string-to-char s) ?*)
10550 ;; Anchor on headlines, post may include tags.
10551 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10552 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10553 s (substring s 1)))
10554 (remove-text-properties
10555 0 (length s)
10556 '(face nil mouse-face nil keymap nil fontified nil) s)
10557 ;; Make a series of regular expressions to find a match
10558 (setq words (org-split-string s "[ \n\r\t]+")
10560 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10561 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10562 "\\)" markers)
10563 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10564 re2a (concat "[ \t\r\n]" re2a_)
10565 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10566 re4 (concat "[^a-zA-Z_]" re4_)
10568 re1 (concat pre re2 post)
10569 re3 (concat pre (if pre re4_ re4) post)
10570 re5 (concat pre ".*" re4)
10571 re2 (concat pre re2)
10572 re2a (concat pre (if pre re2a_ re2a))
10573 re4 (concat pre (if pre re4_ re4))
10574 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10575 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10576 re5 "\\)"
10578 (cond
10579 ((eq type 'org-occur) (org-occur reall))
10580 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10581 (t (goto-char (point-min))
10582 (setq type 'fuzzy)
10583 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10584 (org-search-not-self 1 re1 nil t)
10585 (org-search-not-self 1 re2 nil t)
10586 (org-search-not-self 1 re2a nil t)
10587 (org-search-not-self 1 re3 nil t)
10588 (org-search-not-self 1 re4 nil t)
10589 (org-search-not-self 1 re5 nil t)
10591 (goto-char (match-beginning 1))
10592 (goto-char pos)
10593 (error "No match"))))))
10594 (and (derived-mode-p 'org-mode)
10595 (not stealth)
10596 (org-show-context 'link-search))
10597 type))
10599 (defun org-search-not-self (group &rest args)
10600 "Execute `re-search-forward', but only accept matches that do not
10601 enclose the position of `org-open-link-marker'."
10602 (let ((m org-open-link-marker))
10603 (catch 'exit
10604 (while (apply 're-search-forward args)
10605 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10606 (goto-char (match-end group))
10607 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10608 (> (match-beginning 0) (marker-position m))
10609 (< (match-end 0) (marker-position m)))
10610 (save-match-data
10611 (or (not (org-in-regexp
10612 org-bracket-link-analytic-regexp 1))
10613 (not (match-end 4)) ; no description
10614 (and (<= (match-beginning 4) (point))
10615 (>= (match-end 4) (point))))))
10616 (throw 'exit (point))))))))
10618 (defun org-get-buffer-for-internal-link (buffer)
10619 "Return a buffer to be used for displaying the link target of internal links."
10620 (cond
10621 ((not org-display-internal-link-with-indirect-buffer)
10622 buffer)
10623 ((string-match "(Clone)$" (buffer-name buffer))
10624 (message "Buffer is already a clone, not making another one")
10625 ;; we also do not modify visibility in this case
10626 buffer)
10627 (t ; make a new indirect buffer for displaying the link
10628 (let* ((bn (buffer-name buffer))
10629 (ibn (concat bn "(Clone)"))
10630 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10631 (with-current-buffer ib (org-overview))
10632 ib))))
10634 (defun org-do-occur (regexp &optional cleanup)
10635 "Call the Emacs command `occur'.
10636 If CLEANUP is non-nil, remove the printout of the regular expression
10637 in the *Occur* buffer. This is useful if the regex is long and not useful
10638 to read."
10639 (occur regexp)
10640 (when cleanup
10641 (let ((cwin (selected-window)) win beg end)
10642 (when (setq win (get-buffer-window "*Occur*"))
10643 (select-window win))
10644 (goto-char (point-min))
10645 (when (re-search-forward "match[a-z]+" nil t)
10646 (setq beg (match-end 0))
10647 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10648 (setq end (1- (match-beginning 0)))))
10649 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10650 (goto-char (point-min))
10651 (select-window cwin))))
10653 ;;; The mark ring for links jumps
10655 (defvar org-mark-ring nil
10656 "Mark ring for positions before jumps in Org-mode.")
10657 (defvar org-mark-ring-last-goto nil
10658 "Last position in the mark ring used to go back.")
10659 ;; Fill and close the ring
10660 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10661 (loop for i from 1 to org-mark-ring-length do
10662 (push (make-marker) org-mark-ring))
10663 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10664 org-mark-ring)
10666 (defun org-mark-ring-push (&optional pos buffer)
10667 "Put the current position or POS into the mark ring and rotate it."
10668 (interactive)
10669 (setq pos (or pos (point)))
10670 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10671 (move-marker (car org-mark-ring)
10672 (or pos (point))
10673 (or buffer (current-buffer)))
10674 (message "%s"
10675 (substitute-command-keys
10676 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10678 (defun org-mark-ring-goto (&optional n)
10679 "Jump to the previous position in the mark ring.
10680 With prefix arg N, jump back that many stored positions. When
10681 called several times in succession, walk through the entire ring.
10682 Org-mode commands jumping to a different position in the current file,
10683 or to another Org-mode file, automatically push the old position
10684 onto the ring."
10685 (interactive "p")
10686 (let (p m)
10687 (if (eq last-command this-command)
10688 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10689 (setq p org-mark-ring))
10690 (setq org-mark-ring-last-goto p)
10691 (setq m (car p))
10692 (org-pop-to-buffer-same-window (marker-buffer m))
10693 (goto-char m)
10694 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10696 (defun org-remove-angle-brackets (s)
10697 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10698 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10700 (defun org-add-angle-brackets (s)
10701 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10702 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10704 (defun org-remove-double-quotes (s)
10705 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10706 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10709 ;;; Following specific links
10711 (defun org-follow-timestamp-link ()
10712 "Open an agenda view for the time-stamp date/range at point."
10713 (cond
10714 ((org-at-date-range-p t)
10715 (let ((org-agenda-start-on-weekday)
10716 (t1 (match-string 1))
10717 (t2 (match-string 2)) tt1 tt2)
10718 (setq tt1 (time-to-days (org-time-string-to-time t1))
10719 tt2 (time-to-days (org-time-string-to-time t2)))
10720 (let ((org-agenda-buffer-tmp-name
10721 (format "*Org Agenda(a:%s)"
10722 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10723 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10724 ((org-at-timestamp-p t)
10725 (let ((org-agenda-buffer-tmp-name
10726 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10727 (org-agenda-list nil (time-to-days (org-time-string-to-time
10728 (substring (match-string 1) 0 10)))
10729 1)))
10730 (t (error "This should not happen"))))
10733 ;;; Following file links
10734 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10735 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10736 (declare-function mailcap-mime-info
10737 "mailcap" (string &optional request no-decode))
10738 (defvar org-wait nil)
10739 (defun org-open-file (path &optional in-emacs line search)
10740 "Open the file at PATH.
10741 First, this expands any special file name abbreviations. Then the
10742 configuration variable `org-file-apps' is checked if it contains an
10743 entry for this file type, and if yes, the corresponding command is launched.
10745 If no application is found, Emacs simply visits the file.
10747 With optional prefix argument IN-EMACS, Emacs will visit the file.
10748 With a double \\[universal-argument] \\[universal-argument] \
10749 prefix arg, Org tries to avoid opening in Emacs
10750 and to use an external application to visit the file.
10752 Optional LINE specifies a line to go to, optional SEARCH a string
10753 to search for. If LINE or SEARCH is given, the file will be
10754 opened in Emacs, unless an entry from org-file-apps that makes
10755 use of groups in a regexp matches.
10757 If you want to change the way frames are used when following a
10758 link, please customize `org-link-frame-setup'.
10760 If the file does not exist, an error is thrown."
10761 (let* ((file (if (equal path "")
10762 buffer-file-name
10763 (substitute-in-file-name (expand-file-name path))))
10764 (file-apps (append org-file-apps (org-default-apps)))
10765 (apps (org-remove-if
10766 'org-file-apps-entry-match-against-dlink-p file-apps))
10767 (apps-dlink (org-remove-if-not
10768 'org-file-apps-entry-match-against-dlink-p file-apps))
10769 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10770 (dirp (if remp nil (file-directory-p file)))
10771 (file (if (and dirp org-open-directory-means-index-dot-org)
10772 (concat (file-name-as-directory file) "index.org")
10773 file))
10774 (a-m-a-p (assq 'auto-mode apps))
10775 (dfile (downcase file))
10776 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10777 (link (cond ((and (eq line nil)
10778 (eq search nil))
10779 file)
10780 (line
10781 (concat file "::" (number-to-string line)))
10782 (search
10783 (concat file "::" search))))
10784 (dlink (downcase link))
10785 (old-buffer (current-buffer))
10786 (old-pos (point))
10787 (old-mode major-mode)
10788 ext cmd link-match-data)
10789 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10790 (setq ext (match-string 1 dfile))
10791 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10792 (setq ext (match-string 1 dfile))))
10793 (cond
10794 ((member in-emacs '((16) system))
10795 (setq cmd (cdr (assoc 'system apps))))
10796 (in-emacs (setq cmd 'emacs))
10798 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10799 (and dirp (cdr (assoc 'directory apps)))
10800 ; first, try matching against apps-dlink
10801 ; if we get a match here, store the match data for later
10802 (let ((match (assoc-default dlink apps-dlink
10803 'string-match)))
10804 (if match
10805 (progn (setq link-match-data (match-data))
10806 match)
10807 (progn (setq in-emacs (or in-emacs line search))
10808 nil))) ; if we have no match in apps-dlink,
10809 ; always open the file in emacs if line or search
10810 ; is given (for backwards compatibility)
10811 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10812 'string-match)
10813 (cdr (assoc ext apps))
10814 (cdr (assoc t apps))))))
10815 (when (eq cmd 'system)
10816 (setq cmd (cdr (assoc 'system apps))))
10817 (when (eq cmd 'default)
10818 (setq cmd (cdr (assoc t apps))))
10819 (when (eq cmd 'mailcap)
10820 (require 'mailcap)
10821 (mailcap-parse-mailcaps)
10822 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10823 (command (mailcap-mime-info mime-type)))
10824 (if (stringp command)
10825 (setq cmd command)
10826 (setq cmd 'emacs))))
10827 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10828 (not (file-exists-p file))
10829 (not org-open-non-existing-files))
10830 (error "No such file: %s" file))
10831 (cond
10832 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10833 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10834 (while (string-match "['\"]%s['\"]" cmd)
10835 (setq cmd (replace-match "%s" t t cmd)))
10836 (while (string-match "%s" cmd)
10837 (setq cmd (replace-match
10838 (save-match-data
10839 (shell-quote-argument
10840 (convert-standard-filename file)))
10841 t t cmd)))
10843 ;; Replace "%1", "%2" etc. in command with group matches from regex
10844 (save-match-data
10845 (let ((match-index 1)
10846 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10847 (set-match-data link-match-data)
10848 (while (<= match-index number-of-groups)
10849 (let ((regex (concat "%" (number-to-string match-index)))
10850 (replace-with (match-string match-index dlink)))
10851 (while (string-match regex cmd)
10852 (setq cmd (replace-match replace-with t t cmd))))
10853 (setq match-index (+ match-index 1)))))
10855 (save-window-excursion
10856 (message "Running %s...done" cmd)
10857 (start-process-shell-command cmd nil cmd)
10858 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10859 ((or (stringp cmd)
10860 (eq cmd 'emacs))
10861 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10862 (widen)
10863 (if line (org-goto-line line)
10864 (if search (org-link-search search))))
10865 ((consp cmd)
10866 (let ((file (convert-standard-filename file)))
10867 (save-match-data
10868 (set-match-data link-match-data)
10869 (eval cmd))))
10870 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10871 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10872 (or (not (equal old-buffer (current-buffer)))
10873 (not (equal old-pos (point))))
10874 (org-mark-ring-push old-pos old-buffer))))
10876 (defun org-file-apps-entry-match-against-dlink-p (entry)
10877 "This function returns non-nil if `entry' uses a regular
10878 expression which should be matched against the whole link by
10879 org-open-file.
10881 It assumes that is the case when the entry uses a regular
10882 expression which has at least one grouping construct and the
10883 action is either a lisp form or a command string containing
10884 '%1', i.e. using at least one subexpression match as a
10885 parameter."
10886 (let ((selector (car entry))
10887 (action (cdr entry)))
10888 (if (stringp selector)
10889 (and (> (regexp-opt-depth selector) 0)
10890 (or (and (stringp action)
10891 (string-match "%[0-9]" action))
10892 (consp action)))
10893 nil)))
10895 (defun org-default-apps ()
10896 "Return the default applications for this operating system."
10897 (cond
10898 ((eq system-type 'darwin)
10899 org-file-apps-defaults-macosx)
10900 ((eq system-type 'windows-nt)
10901 org-file-apps-defaults-windowsnt)
10902 (t org-file-apps-defaults-gnu)))
10904 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10905 "Convert extensions to regular expressions in the cars of LIST.
10906 Also, weed out any non-string entries, because the return value is used
10907 only for regexp matching.
10908 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10909 point to the symbol `emacs', indicating that the file should
10910 be opened in Emacs."
10911 (append
10912 (delq nil
10913 (mapcar (lambda (x)
10914 (if (not (stringp (car x)))
10916 (if (string-match "\\W" (car x))
10918 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10919 list))
10920 (if add-auto-mode
10921 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10923 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10924 (defun org-file-remote-p (file)
10925 "Test whether FILE specifies a location on a remote system.
10926 Return non-nil if the location is indeed remote.
10928 For example, the filename \"/user@host:/foo\" specifies a location
10929 on the system \"/user@host:\"."
10930 (cond ((fboundp 'file-remote-p)
10931 (file-remote-p file))
10932 ((fboundp 'tramp-handle-file-remote-p)
10933 (tramp-handle-file-remote-p file))
10934 ((and (boundp 'ange-ftp-name-format)
10935 (string-match (car ange-ftp-name-format) file))
10936 t)))
10939 ;;;; Refiling
10941 (defun org-get-org-file ()
10942 "Read a filename, with default directory `org-directory'."
10943 (let ((default (or org-default-notes-file remember-data-file)))
10944 (read-file-name (format "File name [%s]: " default)
10945 (file-name-as-directory org-directory)
10946 default)))
10948 (defun org-notes-order-reversed-p ()
10949 "Check if the current file should receive notes in reversed order."
10950 (cond
10951 ((not org-reverse-note-order) nil)
10952 ((eq t org-reverse-note-order) t)
10953 ((not (listp org-reverse-note-order)) nil)
10954 (t (catch 'exit
10955 (let ((all org-reverse-note-order)
10956 entry)
10957 (while (setq entry (pop all))
10958 (if (string-match (car entry) buffer-file-name)
10959 (throw 'exit (cdr entry))))
10960 nil)))))
10962 (defvar org-refile-target-table nil
10963 "The list of refile targets, created by `org-refile'.")
10965 (defvar org-agenda-new-buffers nil
10966 "Buffers created to visit agenda files.")
10968 (defvar org-refile-cache nil
10969 "Cache for refile targets.")
10971 (defvar org-refile-markers nil
10972 "All the markers used for caching refile locations.")
10974 (defun org-refile-marker (pos)
10975 "Get a new refile marker, but only if caching is in use."
10976 (if (not org-refile-use-cache)
10978 (let ((m (make-marker)))
10979 (move-marker m pos)
10980 (push m org-refile-markers)
10981 m)))
10983 (defun org-refile-cache-clear ()
10984 "Clear the refile cache and disable all the markers."
10985 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10986 (setq org-refile-markers nil)
10987 (setq org-refile-cache nil)
10988 (message "Refile cache has been cleared"))
10990 (defun org-refile-cache-check-set (set)
10991 "Check if all the markers in the cache still have live buffers."
10992 (let (marker)
10993 (catch 'exit
10994 (while (and set (setq marker (nth 3 (pop set))))
10995 ;; if org-refile-use-outline-path is 'file, marker may be nil
10996 (when (and marker (null (marker-buffer marker)))
10997 (message "not found") (sit-for 3)
10998 (throw 'exit nil)))
10999 t)))
11001 (defun org-refile-cache-put (set &rest identifiers)
11002 "Push the refile targets SET into the cache, under IDENTIFIERS."
11003 (let* ((key (sha1 (prin1-to-string identifiers)))
11004 (entry (assoc key org-refile-cache)))
11005 (if entry
11006 (setcdr entry set)
11007 (push (cons key set) org-refile-cache))))
11009 (defun org-refile-cache-get (&rest identifiers)
11010 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11011 (cond
11012 ((not org-refile-cache) nil)
11013 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11015 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11016 org-refile-cache))))
11017 (and set (org-refile-cache-check-set set) set)))))
11019 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11020 "Produce a table with refile targets."
11021 (let ((case-fold-search nil)
11022 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11023 (entries (or org-refile-targets '((nil . (:level . 1)))))
11024 targets tgs txt re files f desc descre fast-path-p level pos0)
11025 (message "Getting targets...")
11026 (with-current-buffer (or default-buffer (current-buffer))
11027 (while (setq entry (pop entries))
11028 (setq files (car entry) desc (cdr entry))
11029 (setq fast-path-p nil)
11030 (cond
11031 ((null files) (setq files (list (current-buffer))))
11032 ((eq files 'org-agenda-files)
11033 (setq files (org-agenda-files 'unrestricted)))
11034 ((and (symbolp files) (fboundp files))
11035 (setq files (funcall files)))
11036 ((and (symbolp files) (boundp files))
11037 (setq files (symbol-value files))))
11038 (if (stringp files) (setq files (list files)))
11039 (cond
11040 ((eq (car desc) :tag)
11041 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11042 ((eq (car desc) :todo)
11043 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11044 ((eq (car desc) :regexp)
11045 (setq descre (cdr desc)))
11046 ((eq (car desc) :level)
11047 (setq descre (concat "^\\*\\{" (number-to-string
11048 (if org-odd-levels-only
11049 (1- (* 2 (cdr desc)))
11050 (cdr desc)))
11051 "\\}[ \t]")))
11052 ((eq (car desc) :maxlevel)
11053 (setq fast-path-p t)
11054 (setq descre (concat "^\\*\\{1," (number-to-string
11055 (if org-odd-levels-only
11056 (1- (* 2 (cdr desc)))
11057 (cdr desc)))
11058 "\\}[ \t]")))
11059 (t (error "Bad refiling target description %s" desc)))
11060 (while (setq f (pop files))
11061 (with-current-buffer
11062 (if (bufferp f) f (org-get-agenda-file-buffer f))
11064 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11065 (progn
11066 (if (bufferp f) (setq f (buffer-file-name
11067 (buffer-base-buffer f))))
11068 (setq f (and f (expand-file-name f)))
11069 (if (eq org-refile-use-outline-path 'file)
11070 (push (list (file-name-nondirectory f) f nil nil) tgs))
11071 (save-excursion
11072 (save-restriction
11073 (widen)
11074 (goto-char (point-min))
11075 (while (re-search-forward descre nil t)
11076 (goto-char (setq pos0 (point-at-bol)))
11077 (catch 'next
11078 (when org-refile-target-verify-function
11079 (save-match-data
11080 (or (funcall org-refile-target-verify-function)
11081 (throw 'next t))))
11082 (when (and (looking-at org-complex-heading-regexp)
11083 (not (member (match-string 4) excluded-entries))
11084 (match-string 4))
11085 (setq level (org-reduced-level
11086 (- (match-end 1) (match-beginning 1)))
11087 txt (org-link-display-format (match-string 4))
11088 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11089 re (format org-complex-heading-regexp-format
11090 (regexp-quote (match-string 4))))
11091 (when org-refile-use-outline-path
11092 (setq txt (mapconcat
11093 'org-protect-slash
11094 (append
11095 (if (eq org-refile-use-outline-path
11096 'file)
11097 (list (file-name-nondirectory
11098 (buffer-file-name
11099 (buffer-base-buffer))))
11100 (if (eq org-refile-use-outline-path
11101 'full-file-path)
11102 (list (buffer-file-name
11103 (buffer-base-buffer)))))
11104 (org-get-outline-path fast-path-p
11105 level txt)
11106 (list txt))
11107 "/")))
11108 (push (list txt f re (org-refile-marker (point)))
11109 tgs)))
11110 (when (= (point) pos0)
11111 ;; verification function has not moved point
11112 (goto-char (point-at-eol))))))))
11113 (when org-refile-use-cache
11114 (org-refile-cache-put tgs (buffer-file-name) descre))
11115 (setq targets (append tgs targets))
11116 ))))
11117 (message "Getting targets...done")
11118 (nreverse targets)))
11120 (defun org-protect-slash (s)
11121 (while (string-match "/" s)
11122 (setq s (replace-match "\\" t t s)))
11125 (defvar org-olpa (make-vector 20 nil))
11127 (defun org-get-outline-path (&optional fastp level heading)
11128 "Return the outline path to the current entry, as a list.
11130 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11131 routine which makes outline path derivations for an entire file,
11132 avoiding backtracing. Refile target collection makes use of that."
11133 (if fastp
11134 (progn
11135 (if (> level 19)
11136 (error "Outline path failure, more than 19 levels"))
11137 (loop for i from level upto 19 do
11138 (aset org-olpa i nil))
11139 (prog1
11140 (delq nil (append org-olpa nil))
11141 (aset org-olpa level heading)))
11142 (let (rtn case-fold-search)
11143 (save-excursion
11144 (save-restriction
11145 (widen)
11146 (while (org-up-heading-safe)
11147 (when (looking-at org-complex-heading-regexp)
11148 (push (org-match-string-no-properties 4) rtn)))
11149 rtn)))))
11151 (defun org-format-outline-path (path &optional width prefix separator)
11152 "Format the outline path PATH for display.
11153 WIDTH is the maximum number of characters that is available.
11154 PREFIX is a prefix to be included in the returned string,
11155 such as the file name.
11156 SEPARATOR is inserted between the different parts of the path,
11157 the default is \"/\"."
11158 (setq width (or width 79))
11159 (if prefix (setq width (- width (length prefix))))
11160 (if (not path)
11161 (or prefix "")
11162 (let* ((nsteps (length path))
11163 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11164 (maxwidth (if (<= total-width width)
11165 10000 ;; everything fits
11166 ;; we need to shorten the level headings
11167 (/ (- width nsteps) nsteps)))
11168 (org-odd-levels-only nil)
11169 (n 0)
11170 (total (1+ (length prefix))))
11171 (setq maxwidth (max maxwidth 10))
11172 (concat prefix
11173 (if prefix (or separator "/"))
11174 (mapconcat
11175 (lambda (h)
11176 (setq n (1+ n))
11177 (if (and (= n nsteps) (< maxwidth 10000))
11178 (setq maxwidth (- total-width total)))
11179 (if (< (length h) maxwidth)
11180 (progn (setq total (+ total (length h) 1)) h)
11181 (setq h (substring h 0 (- maxwidth 2))
11182 total (+ total maxwidth 1))
11183 (if (string-match "[ \t]+\\'" h)
11184 (setq h (substring h 0 (match-beginning 0))))
11185 (setq h (concat h "..")))
11186 (org-add-props h nil 'face
11187 (nth (% (1- n) org-n-level-faces)
11188 org-level-faces))
11190 path (or separator "/"))))))
11192 (defun org-display-outline-path (&optional file current separator just-return-string)
11193 "Display the current outline path in the echo area.
11195 If FILE is non-nil, prepend the output with the file name.
11196 If CURRENT is non-nil, append the current heading to the output.
11197 SEPARATOR is passed through to `org-format-outline-path'. It separates
11198 the different parts of the path and defaults to \"/\".
11199 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11200 (interactive "P")
11201 (let* (case-fold-search
11202 message-log-max ; Don't populate the *Messages* buffer
11203 (bfn (buffer-file-name (buffer-base-buffer)))
11204 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11205 res)
11206 (if current (setq path (append path
11207 (save-excursion
11208 (org-back-to-heading t)
11209 (if (looking-at org-complex-heading-regexp)
11210 (list (match-string 4)))))))
11211 (setq res
11212 (org-format-outline-path
11213 path
11214 (1- (frame-width))
11215 (and file bfn (concat (file-name-nondirectory bfn) separator))
11216 separator))
11217 (if just-return-string
11218 (org-no-properties res)
11219 (message "%s" res))))
11221 (defvar org-refile-history nil
11222 "History for refiling operations.")
11224 (defvar org-after-refile-insert-hook nil
11225 "Hook run after `org-refile' has inserted its stuff at the new location.
11226 Note that this is still *before* the stuff will be removed from
11227 the *old* location.")
11229 (defvar org-capture-last-stored-marker)
11230 (defvar org-refile-keep nil
11231 "Non-nil means `org-refile' will copy instead of refile.")
11233 (defun org-copy ()
11234 "Like `org-refile', but copy."
11235 (interactive)
11236 (let ((org-refile-keep t))
11237 (funcall 'org-refile nil nil nil "Copy")))
11239 (defun org-refile (&optional goto default-buffer rfloc msg)
11240 "Move the entry or entries at point to another heading.
11241 The list of target headings is compiled using the information in
11242 `org-refile-targets', which see.
11244 At the target location, the entry is filed as a subitem of the target
11245 heading. Depending on `org-reverse-note-order', the new subitem will
11246 either be the first or the last subitem.
11248 If there is an active region, all entries in that region will be moved.
11249 However, the region must fulfill the requirement that the first heading
11250 is the first one sets the top-level of the moved text - at most siblings
11251 below it are allowed.
11253 With prefix arg GOTO, the command will only visit the target location
11254 and not actually move anything.
11256 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11257 go to the location where the last refiling operation has put the subtree.
11258 With a prefix argument of `2', refile to the running clock.
11260 RFLOC can be a refile location obtained in a different way.
11262 MSG is a string to replace \"Refile\" in the default prompt with
11263 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11265 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11267 If you are using target caching (see `org-refile-use-cache'),
11268 you have to clear the target cache in order to find new targets.
11269 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11270 prefix argument (`C-u C-u C-u C-c C-w')."
11272 (interactive "P")
11273 (if (member goto '(0 (64)))
11274 (org-refile-cache-clear)
11275 (let* ((actionmsg (or msg "Refile"))
11276 (cbuf (current-buffer))
11277 (regionp (org-region-active-p))
11278 (region-start (and regionp (region-beginning)))
11279 (region-end (and regionp (region-end)))
11280 (region-length (and regionp (- region-end region-start)))
11281 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11282 pos it nbuf file re level reversed)
11283 (setq last-command nil)
11284 (when regionp
11285 (goto-char region-start)
11286 (or (bolp) (goto-char (point-at-bol)))
11287 (setq region-start (point))
11288 (unless (or (org-kill-is-subtree-p
11289 (buffer-substring region-start region-end))
11290 (prog1 org-refile-active-region-within-subtree
11291 (org-toggle-heading)))
11292 (error "The region is not a (sequence of) subtree(s)")))
11293 (if (equal goto '(16))
11294 (org-refile-goto-last-stored)
11295 (when (or
11296 (and (equal goto 2)
11297 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11298 (prog1
11299 (setq it (list (or org-clock-heading "running clock")
11300 (buffer-file-name
11301 (marker-buffer org-clock-hd-marker))
11303 (marker-position org-clock-hd-marker)))
11304 (setq goto nil)))
11305 (setq it (or rfloc
11306 (let (heading-text)
11307 (save-excursion
11308 (unless goto
11309 (org-back-to-heading t)
11310 (setq heading-text
11311 (nth 4 (org-heading-components))))
11313 (org-refile-get-location
11314 (cond (goto "Goto")
11315 (regionp (concat actionmsg " region to"))
11316 (t (concat actionmsg " subtree \""
11317 heading-text "\" to")))
11318 default-buffer
11319 (and (not (equal '(4) goto))
11320 org-refile-allow-creating-parent-nodes)
11321 goto))))))
11322 (setq file (nth 1 it)
11323 re (nth 2 it)
11324 pos (nth 3 it))
11325 (if (and (not goto)
11327 (equal (buffer-file-name) file)
11328 (if regionp
11329 (and (>= pos region-start)
11330 (<= pos region-end))
11331 (and (>= pos (point))
11332 (< pos (save-excursion
11333 (org-end-of-subtree t t))))))
11334 (error "Cannot refile to position inside the tree or region"))
11336 (setq nbuf (or (find-buffer-visiting file)
11337 (find-file-noselect file)))
11338 (if goto
11339 (progn
11340 (org-pop-to-buffer-same-window nbuf)
11341 (goto-char pos)
11342 (org-show-context 'org-goto))
11343 (if regionp
11344 (progn
11345 (org-kill-new (buffer-substring region-start region-end))
11346 (org-save-markers-in-region region-start region-end))
11347 (org-copy-subtree 1 nil t))
11348 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11349 (find-file-noselect file)))
11350 (setq reversed (org-notes-order-reversed-p))
11351 (save-excursion
11352 (save-restriction
11353 (widen)
11354 (if pos
11355 (progn
11356 (goto-char pos)
11357 (looking-at org-outline-regexp)
11358 (setq level (org-get-valid-level (funcall outline-level) 1))
11359 (goto-char
11360 (if reversed
11361 (or (outline-next-heading) (point-max))
11362 (or (save-excursion (org-get-next-sibling))
11363 (org-end-of-subtree t t)
11364 (point-max)))))
11365 (setq level 1)
11366 (if (not reversed)
11367 (goto-char (point-max))
11368 (goto-char (point-min))
11369 (or (outline-next-heading) (goto-char (point-max)))))
11370 (if (not (bolp)) (newline))
11371 (org-paste-subtree level)
11372 (when org-log-refile
11373 (org-add-log-setup 'refile nil nil 'findpos
11374 org-log-refile)
11375 (unless (eq org-log-refile 'note)
11376 (save-excursion (org-add-log-note))))
11377 (and org-auto-align-tags
11378 (let ((org-loop-over-headlines-in-active-region nil))
11379 (org-set-tags nil t)))
11380 (with-demoted-errors
11381 (bookmark-set "org-refile-last-stored"))
11382 ;; If we are refiling for capture, make sure that the
11383 ;; last-capture pointers point here
11384 (when (org-bound-and-true-p org-refile-for-capture)
11385 (with-demoted-errors
11386 (bookmark-set "org-capture-last-stored-marker"))
11387 (move-marker org-capture-last-stored-marker (point)))
11388 (if (fboundp 'deactivate-mark) (deactivate-mark))
11389 (run-hooks 'org-after-refile-insert-hook))))
11390 (unless org-refile-keep
11391 (if regionp
11392 (delete-region (point) (+ (point) region-length))
11393 (org-cut-subtree)))
11394 (when (featurep 'org-inlinetask)
11395 (org-inlinetask-remove-END-maybe))
11396 (setq org-markers-to-move nil)
11397 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11399 (defun org-refile-goto-last-stored ()
11400 "Go to the location where the last refile was stored."
11401 (interactive)
11402 (bookmark-jump "org-refile-last-stored")
11403 (message "This is the location of the last refile"))
11405 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11406 no-exclude)
11407 "Prompt the user for a refile location, using PROMPT.
11408 PROMPT should not be suffixed with a colon and a space, because
11409 this function appends the default value from
11410 `org-refile-history' automatically, if that is not empty.
11411 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11412 this is used for the GOTO interface."
11413 (let ((org-refile-targets org-refile-targets)
11414 (org-refile-use-outline-path org-refile-use-outline-path)
11415 excluded-entries)
11416 (when (and (derived-mode-p 'org-mode)
11417 (not org-refile-use-cache)
11418 (not no-exclude))
11419 (org-map-tree
11420 (lambda()
11421 (setq excluded-entries
11422 (append excluded-entries (list (org-get-heading t t)))))))
11423 (setq org-refile-target-table
11424 (org-refile-get-targets default-buffer excluded-entries)))
11425 (unless org-refile-target-table
11426 (error "No refile targets"))
11427 (let* ((cbuf (current-buffer))
11428 (partial-completion-mode nil)
11429 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11430 (cfunc (if (and org-refile-use-outline-path
11431 org-outline-path-complete-in-steps)
11432 'org-olpath-completing-read
11433 'org-icompleting-read))
11434 (extra (if org-refile-use-outline-path "/" ""))
11435 (cbnex (concat (buffer-name) extra))
11436 (filename (and cfn (expand-file-name cfn)))
11437 (tbl (mapcar
11438 (lambda (x)
11439 (if (and (not (member org-refile-use-outline-path
11440 '(file full-file-path)))
11441 (not (equal filename (nth 1 x))))
11442 (cons (concat (car x) extra " ("
11443 (file-name-nondirectory (nth 1 x)) ")")
11444 (cdr x))
11445 (cons (concat (car x) extra) (cdr x))))
11446 org-refile-target-table))
11447 (completion-ignore-case t)
11448 cdef
11449 (prompt (concat prompt
11450 (or (and (car org-refile-history)
11451 (concat " (default " (car org-refile-history) ")"))
11452 (and (assoc cbnex tbl) (setq cdef cbnex)
11453 (concat " (default " cbnex ")"))) ": "))
11454 pa answ parent-target child parent old-hist)
11455 (setq old-hist org-refile-history)
11456 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11457 nil 'org-refile-history (or cdef (car org-refile-history))))
11458 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11459 (org-refile-check-position pa)
11460 (if pa
11461 (progn
11462 (when (or (not org-refile-history)
11463 (not (eq old-hist org-refile-history))
11464 (not (equal (car pa) (car org-refile-history))))
11465 (setq org-refile-history
11466 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11467 org-refile-history
11468 (cdr org-refile-history))))
11469 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11470 (pop org-refile-history)))
11472 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11473 (progn
11474 (setq parent (match-string 1 answ)
11475 child (match-string 2 answ))
11476 (setq parent-target (or (assoc parent tbl)
11477 (assoc (concat parent "/") tbl)))
11478 (when (and parent-target
11479 (or (eq new-nodes t)
11480 (and (eq new-nodes 'confirm)
11481 (y-or-n-p (format "Create new node \"%s\"? "
11482 child)))))
11483 (org-refile-new-child parent-target child)))
11484 (error "Invalid target location")))))
11486 (declare-function org-string-nw-p "org-macs" (s))
11487 (defun org-refile-check-position (refile-pointer)
11488 "Check if the refile pointer matches the headline to which it points."
11489 (let* ((file (nth 1 refile-pointer))
11490 (re (nth 2 refile-pointer))
11491 (pos (nth 3 refile-pointer))
11492 buffer)
11493 (if (and (not (markerp pos)) (not file))
11494 (error "Please save the buffer to a file before refiling")
11495 (when (org-string-nw-p re)
11496 (setq buffer (if (markerp pos)
11497 (marker-buffer pos)
11498 (or (find-buffer-visiting file)
11499 (find-file-noselect file))))
11500 (with-current-buffer buffer
11501 (save-excursion
11502 (save-restriction
11503 (widen)
11504 (goto-char pos)
11505 (beginning-of-line 1)
11506 (unless (org-looking-at-p re)
11507 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11509 (defun org-refile-new-child (parent-target child)
11510 "Use refile target PARENT-TARGET to add new CHILD below it."
11511 (unless parent-target
11512 (error "Cannot find parent for new node"))
11513 (let ((file (nth 1 parent-target))
11514 (pos (nth 3 parent-target))
11515 level)
11516 (with-current-buffer (or (find-buffer-visiting file)
11517 (find-file-noselect file))
11518 (save-excursion
11519 (save-restriction
11520 (widen)
11521 (if pos
11522 (goto-char pos)
11523 (goto-char (point-max))
11524 (if (not (bolp)) (newline)))
11525 (when (looking-at org-outline-regexp)
11526 (setq level (funcall outline-level))
11527 (org-end-of-subtree t t))
11528 (org-back-over-empty-lines)
11529 (insert "\n" (make-string
11530 (if pos (org-get-valid-level level 1) 1) ?*)
11531 " " child "\n")
11532 (beginning-of-line 0)
11533 (list (concat (car parent-target) "/" child) file "" (point)))))))
11535 (defun org-olpath-completing-read (prompt collection &rest args)
11536 "Read an outline path like a file name."
11537 (let ((thetable collection)
11538 (org-completion-use-ido nil) ; does not work with ido.
11539 (org-completion-use-iswitchb nil)) ; or iswitchb
11540 (apply
11541 'org-icompleting-read prompt
11542 (lambda (string predicate &optional flag)
11543 (let (rtn r f (l (length string)))
11544 (cond
11545 ((eq flag nil)
11546 ;; try completion
11547 (try-completion string thetable))
11548 ((eq flag t)
11549 ;; all-completions
11550 (setq rtn (all-completions string thetable predicate))
11551 (mapcar
11552 (lambda (x)
11553 (setq r (substring x l))
11554 (if (string-match " ([^)]*)$" x)
11555 (setq f (match-string 0 x))
11556 (setq f ""))
11557 (if (string-match "/" r)
11558 (concat string (substring r 0 (match-end 0)) f)
11560 rtn))
11561 ((eq flag 'lambda)
11562 ;; exact match?
11563 (assoc string thetable)))))
11564 args)))
11566 ;;;; Dynamic blocks
11568 (defun org-find-dblock (name)
11569 "Find the first dynamic block with name NAME in the buffer.
11570 If not found, stay at current position and return nil."
11571 (let ((case-fold-search t) pos)
11572 (save-excursion
11573 (goto-char (point-min))
11574 (setq pos (and (re-search-forward
11575 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11576 (match-beginning 0))))
11577 (if pos (goto-char pos))
11578 pos))
11580 (defconst org-dblock-start-re
11581 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11582 "Matches the start line of a dynamic block, with parameters.")
11584 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11585 "Matches the end of a dynamic block.")
11587 (defun org-create-dblock (plist)
11588 "Create a dynamic block section, with parameters taken from PLIST.
11589 PLIST must contain a :name entry which is used as name of the block."
11590 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11591 (end-of-line 1)
11592 (newline))
11593 (let ((col (current-column))
11594 (name (plist-get plist :name)))
11595 (insert "#+BEGIN: " name)
11596 (while plist
11597 (if (eq (car plist) :name)
11598 (setq plist (cddr plist))
11599 (insert " " (prin1-to-string (pop plist)))))
11600 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11601 (beginning-of-line -2)))
11603 (defun org-prepare-dblock ()
11604 "Prepare dynamic block for refresh.
11605 This empties the block, puts the cursor at the insert position and returns
11606 the property list including an extra property :name with the block name."
11607 (unless (looking-at org-dblock-start-re)
11608 (error "Not at a dynamic block"))
11609 (let* ((begdel (1+ (match-end 0)))
11610 (name (org-no-properties (match-string 1)))
11611 (params (append (list :name name)
11612 (read (concat "(" (match-string 3) ")")))))
11613 (save-excursion
11614 (beginning-of-line 1)
11615 (skip-chars-forward " \t")
11616 (setq params (plist-put params :indentation-column (current-column))))
11617 (unless (re-search-forward org-dblock-end-re nil t)
11618 (error "Dynamic block not terminated"))
11619 (setq params
11620 (append params
11621 (list :content (buffer-substring
11622 begdel (match-beginning 0)))))
11623 (delete-region begdel (match-beginning 0))
11624 (goto-char begdel)
11625 (open-line 1)
11626 params))
11628 (defun org-map-dblocks (&optional command)
11629 "Apply COMMAND to all dynamic blocks in the current buffer.
11630 If COMMAND is not given, use `org-update-dblock'."
11631 (let ((cmd (or command 'org-update-dblock)))
11632 (save-excursion
11633 (goto-char (point-min))
11634 (while (re-search-forward org-dblock-start-re nil t)
11635 (goto-char (match-beginning 0))
11636 (save-excursion
11637 (condition-case nil
11638 (funcall cmd)
11639 (error (message "Error during update of dynamic block"))))
11640 (unless (re-search-forward org-dblock-end-re nil t)
11641 (error "Dynamic block not terminated"))))))
11643 (defun org-dblock-update (&optional arg)
11644 "User command for updating dynamic blocks.
11645 Update the dynamic block at point. With prefix ARG, update all dynamic
11646 blocks in the buffer."
11647 (interactive "P")
11648 (if arg
11649 (org-update-all-dblocks)
11650 (or (looking-at org-dblock-start-re)
11651 (org-beginning-of-dblock))
11652 (org-update-dblock)))
11654 (defun org-update-dblock ()
11655 "Update the dynamic block at point.
11656 This means to empty the block, parse for parameters and then call
11657 the correct writing function."
11658 (interactive)
11659 (save-window-excursion
11660 (let* ((pos (point))
11661 (line (org-current-line))
11662 (params (org-prepare-dblock))
11663 (name (plist-get params :name))
11664 (indent (plist-get params :indentation-column))
11665 (cmd (intern (concat "org-dblock-write:" name))))
11666 (message "Updating dynamic block `%s' at line %d..." name line)
11667 (funcall cmd params)
11668 (message "Updating dynamic block `%s' at line %d...done" name line)
11669 (goto-char pos)
11670 (when (and indent (> indent 0))
11671 (setq indent (make-string indent ?\ ))
11672 (save-excursion
11673 (org-beginning-of-dblock)
11674 (forward-line 1)
11675 (while (not (looking-at org-dblock-end-re))
11676 (insert indent)
11677 (beginning-of-line 2))
11678 (when (looking-at org-dblock-end-re)
11679 (and (looking-at "[ \t]+")
11680 (replace-match ""))
11681 (insert indent)))))))
11683 (defun org-beginning-of-dblock ()
11684 "Find the beginning of the dynamic block at point.
11685 Error if there is no such block at point."
11686 (let ((pos (point))
11687 beg)
11688 (end-of-line 1)
11689 (if (and (re-search-backward org-dblock-start-re nil t)
11690 (setq beg (match-beginning 0))
11691 (re-search-forward org-dblock-end-re nil t)
11692 (> (match-end 0) pos))
11693 (goto-char beg)
11694 (goto-char pos)
11695 (error "Not in a dynamic block"))))
11697 (defun org-update-all-dblocks ()
11698 "Update all dynamic blocks in the buffer.
11699 This function can be used in a hook."
11700 (interactive)
11701 (when (derived-mode-p 'org-mode)
11702 (org-map-dblocks 'org-update-dblock)))
11705 ;;;; Completion
11707 (defun org-get-export-keywords ()
11708 "Return a list of all currently understood export keywords.
11709 Export keywords include options, block names, attributes and
11710 keywords relative to each registered export back-end."
11711 (delq nil
11712 (let (keywords)
11713 (mapc
11714 (lambda (back-end)
11715 (let ((props (cdr back-end)))
11716 ;; Back-end name (for keywords, like #+LATEX:)
11717 (push (upcase (symbol-name (car back-end))) keywords)
11718 ;; Back-end options.
11719 (mapc (lambda (option) (push (cadr option) keywords))
11720 (plist-get (cdr back-end) :options-alist))))
11721 (org-bound-and-true-p org-export-registered-backends))
11722 keywords)))
11724 (defconst org-options-keywords
11725 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11726 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11727 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11728 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11729 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11731 (defcustom org-structure-template-alist
11732 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11733 "<src lang=\"?\">\n\n</src>")
11734 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11735 "<example>\n?\n</example>")
11736 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11737 "<quote>\n?\n</quote>")
11738 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11739 "<verse>\n?\n</verse>")
11740 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11741 "<verbatim>\n?\n</verbatim>")
11742 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11743 "<center>\n?\n</center>")
11744 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11745 "<literal style=\"latex\">\n?\n</literal>")
11746 ("L" "#+LaTeX: "
11747 "<literal style=\"latex\">?</literal>")
11748 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11749 "<literal style=\"html\">\n?\n</literal>")
11750 ("H" "#+HTML: "
11751 "<literal style=\"html\">?</literal>")
11752 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11753 ("A" "#+ASCII: ")
11754 ("i" "#+INDEX: ?"
11755 "#+INDEX: ?")
11756 ("I" "#+INCLUDE: %file ?"
11757 "<include file=%file markup=\"?\">"))
11758 "Structure completion elements.
11759 This is a list of abbreviation keys and values. The value gets inserted
11760 if you type `<' followed by the key and then press the completion key,
11761 usually `M-TAB'. %file will be replaced by a file name after prompting
11762 for the file using completion. The cursor will be placed at the position
11763 of the `?` in the template.
11764 There are two templates for each key, the first uses the original Org syntax,
11765 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11766 the default when the /org-mtags.el/ module has been loaded. See also the
11767 variable `org-mtags-prefer-muse-templates'."
11768 :group 'org-completion
11769 :type '(repeat
11770 (string :tag "Key")
11771 (string :tag "Template")
11772 (string :tag "Muse Template")))
11774 (defun org-try-structure-completion ()
11775 "Try to complete a structure template before point.
11776 This looks for strings like \"<e\" on an otherwise empty line and
11777 expands them."
11778 (let ((l (buffer-substring (point-at-bol) (point)))
11780 (when (and (looking-at "[ \t]*$")
11781 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11782 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11783 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11784 (match-beginning 1)) a)
11785 t)))
11787 (defun org-complete-expand-structure-template (start cell)
11788 "Expand a structure template."
11789 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11790 (rpl (nth (if musep 2 1) cell))
11791 (ind ""))
11792 (delete-region start (point))
11793 (when (string-match "\\`#\\+" rpl)
11794 (cond
11795 ((bolp))
11796 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11797 (setq ind (buffer-substring (point-at-bol) (point))))
11798 (t (newline))))
11799 (setq start (point))
11800 (if (string-match "%file" rpl)
11801 (setq rpl (replace-match
11802 (concat
11803 "\""
11804 (save-match-data
11805 (abbreviate-file-name (read-file-name "Include file: ")))
11806 "\"")
11807 t t rpl)))
11808 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11809 (concat "\n" ind)))
11810 (insert rpl)
11811 (if (re-search-backward "\\?" start t) (delete-char 1))))
11813 ;;;; TODO, DEADLINE, Comments
11815 (defun org-toggle-comment ()
11816 "Change the COMMENT state of an entry."
11817 (interactive)
11818 (save-excursion
11819 (org-back-to-heading)
11820 (let (case-fold-search)
11821 (cond
11822 ((looking-at (format org-heading-keyword-regexp-format
11823 org-comment-string))
11824 (goto-char (match-end 1))
11825 (looking-at (concat " +" org-comment-string))
11826 (replace-match "" t t)
11827 (when (eolp) (insert " ")))
11828 ((looking-at org-outline-regexp)
11829 (goto-char (match-end 0))
11830 (insert org-comment-string " "))))))
11832 (defvar org-last-todo-state-is-todo nil
11833 "This is non-nil when the last TODO state change led to a TODO state.
11834 If the last change removed the TODO tag or switched to DONE, then
11835 this is nil.")
11837 (defvar org-setting-tags nil) ; dynamically skipped
11839 (defvar org-todo-setup-filter-hook nil
11840 "Hook for functions that pre-filter todo specs.
11841 Each function takes a todo spec and returns either nil or the spec
11842 transformed into canonical form." )
11844 (defvar org-todo-get-default-hook nil
11845 "Hook for functions that get a default item for todo.
11846 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11847 nil or a string to be used for the todo mark." )
11849 (defvar org-agenda-headline-snapshot-before-repeat)
11851 (defun org-current-effective-time ()
11852 "Return current time adjusted for `org-extend-today-until' variable."
11853 (let* ((ct (org-current-time))
11854 (dct (decode-time ct))
11855 (ct1
11856 (cond
11857 (org-use-last-clock-out-time-as-effective-time
11858 (or (org-clock-get-last-clock-out-time) ct))
11859 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11860 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11861 (t ct))))
11862 ct1))
11864 (defun org-todo-yesterday (&optional arg)
11865 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11866 (interactive "P")
11867 (if (eq major-mode 'org-agenda-mode)
11868 (apply 'org-agenda-todo-yesterday arg)
11869 (let* ((hour (third (decode-time
11870 (org-current-time))))
11871 (org-extend-today-until (1+ hour)))
11872 (org-todo arg))))
11874 (defvar org-block-entry-blocking ""
11875 "First entry preventing the TODO state change.")
11877 (defun org-todo (&optional arg)
11878 "Change the TODO state of an item.
11879 The state of an item is given by a keyword at the start of the heading,
11880 like
11881 *** TODO Write paper
11882 *** DONE Call mom
11884 The different keywords are specified in the variable `org-todo-keywords'.
11885 By default the available states are \"TODO\" and \"DONE\".
11886 So for this example: when the item starts with TODO, it is changed to DONE.
11887 When it starts with DONE, the DONE is removed. And when neither TODO nor
11888 DONE are present, add TODO at the beginning of the heading.
11890 With \\[universal-argument] prefix arg, use completion to determine the new \
11891 state.
11892 With numeric prefix arg, switch to that state.
11893 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11894 keywords (nextset).
11895 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11896 With a numeric prefix arg of 0, inhibit note taking for the change.
11898 For calling through lisp, arg is also interpreted in the following way:
11899 'none -> empty state
11900 \"\"(empty string) -> switch to empty state
11901 'done -> switch to DONE
11902 'nextset -> switch to the next set of keywords
11903 'previousset -> switch to the previous set of keywords
11904 \"WAITING\" -> switch to the specified keyword, but only if it
11905 really is a member of `org-todo-keywords'."
11906 (interactive "P")
11907 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11908 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11909 'region-start-level 'region))
11910 org-loop-over-headlines-in-active-region)
11911 (org-map-entries
11912 `(org-todo ,arg)
11913 org-loop-over-headlines-in-active-region
11914 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11915 (if (equal arg '(16)) (setq arg 'nextset))
11916 (let ((org-blocker-hook org-blocker-hook)
11917 commentp
11918 case-fold-search)
11919 (when (equal arg '(64))
11920 (setq arg nil org-blocker-hook nil))
11921 (when (and org-blocker-hook
11922 (or org-inhibit-blocking
11923 (org-entry-get nil "NOBLOCKING")))
11924 (setq org-blocker-hook nil))
11925 (save-excursion
11926 (catch 'exit
11927 (org-back-to-heading t)
11928 (when (looking-at (concat "^\\*+ " org-comment-string))
11929 (org-toggle-comment)
11930 (setq commentp t))
11931 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11932 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11933 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11934 (let* ((match-data (match-data))
11935 (startpos (point-at-bol))
11936 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11937 (org-log-done org-log-done)
11938 (org-log-repeat org-log-repeat)
11939 (org-todo-log-states org-todo-log-states)
11940 (org-inhibit-logging
11941 (if (equal arg 0)
11942 (progn (setq arg nil) 'note) org-inhibit-logging))
11943 (this (match-string 1))
11944 (hl-pos (match-beginning 0))
11945 (head (org-get-todo-sequence-head this))
11946 (ass (assoc head org-todo-kwd-alist))
11947 (interpret (nth 1 ass))
11948 (done-word (nth 3 ass))
11949 (final-done-word (nth 4 ass))
11950 (org-last-state (or this ""))
11951 (completion-ignore-case t)
11952 (member (member this org-todo-keywords-1))
11953 (tail (cdr member))
11954 (org-state (cond
11955 ((and org-todo-key-trigger
11956 (or (and (equal arg '(4))
11957 (eq org-use-fast-todo-selection 'prefix))
11958 (and (not arg) org-use-fast-todo-selection
11959 (not (eq org-use-fast-todo-selection
11960 'prefix)))))
11961 ;; Use fast selection
11962 (org-fast-todo-selection))
11963 ((and (equal arg '(4))
11964 (or (not org-use-fast-todo-selection)
11965 (not org-todo-key-trigger)))
11966 ;; Read a state with completion
11967 (org-icompleting-read
11968 "State: " (mapcar (lambda(x) (list x))
11969 org-todo-keywords-1)
11970 nil t))
11971 ((eq arg 'right)
11972 (if this
11973 (if tail (car tail) nil)
11974 (car org-todo-keywords-1)))
11975 ((eq arg 'left)
11976 (if (equal member org-todo-keywords-1)
11978 (if this
11979 (nth (- (length org-todo-keywords-1)
11980 (length tail) 2)
11981 org-todo-keywords-1)
11982 (org-last org-todo-keywords-1))))
11983 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11984 (setq arg nil))) ; hack to fall back to cycling
11985 (arg
11986 ;; user or caller requests a specific state
11987 (cond
11988 ((equal arg "") nil)
11989 ((eq arg 'none) nil)
11990 ((eq arg 'done) (or done-word (car org-done-keywords)))
11991 ((eq arg 'nextset)
11992 (or (car (cdr (member head org-todo-heads)))
11993 (car org-todo-heads)))
11994 ((eq arg 'previousset)
11995 (let ((org-todo-heads (reverse org-todo-heads)))
11996 (or (car (cdr (member head org-todo-heads)))
11997 (car org-todo-heads))))
11998 ((car (member arg org-todo-keywords-1)))
11999 ((stringp arg)
12000 (error "State `%s' not valid in this file" arg))
12001 ((nth (1- (prefix-numeric-value arg))
12002 org-todo-keywords-1))))
12003 ((null member) (or head (car org-todo-keywords-1)))
12004 ((equal this final-done-word) nil) ;; -> make empty
12005 ((null tail) nil) ;; -> first entry
12006 ((memq interpret '(type priority))
12007 (if (eq this-command last-command)
12008 (car tail)
12009 (if (> (length tail) 0)
12010 (or done-word (car org-done-keywords))
12011 nil)))
12013 (car tail))))
12014 (org-state (or
12015 (run-hook-with-args-until-success
12016 'org-todo-get-default-hook org-state org-last-state)
12017 org-state))
12018 (next (if org-state (concat " " org-state " ") " "))
12019 (change-plist (list :type 'todo-state-change :from this :to org-state
12020 :position startpos))
12021 dolog now-done-p)
12022 (when org-blocker-hook
12023 (setq org-last-todo-state-is-todo
12024 (not (member this org-done-keywords)))
12025 (unless (save-excursion
12026 (save-match-data
12027 (org-with-wide-buffer
12028 (run-hook-with-args-until-failure
12029 'org-blocker-hook change-plist))))
12030 (if (org-called-interactively-p 'interactive)
12031 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12032 this org-state org-block-entry-blocking)
12033 ;; fail silently
12034 (message "TODO state change from %s to %s blocked (by \"%s\")"
12035 this org-state org-block-entry-blocking)
12036 (throw 'exit nil))))
12037 (store-match-data match-data)
12038 (replace-match next t t)
12039 (unless (pos-visible-in-window-p hl-pos)
12040 (message "TODO state changed to %s" (org-trim next)))
12041 (unless head
12042 (setq head (org-get-todo-sequence-head org-state)
12043 ass (assoc head org-todo-kwd-alist)
12044 interpret (nth 1 ass)
12045 done-word (nth 3 ass)
12046 final-done-word (nth 4 ass)))
12047 (when (memq arg '(nextset previousset))
12048 (message "Keyword-Set %d/%d: %s"
12049 (- (length org-todo-sets) -1
12050 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12051 (length org-todo-sets)
12052 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12053 (setq org-last-todo-state-is-todo
12054 (not (member org-state org-done-keywords)))
12055 (setq now-done-p (and (member org-state org-done-keywords)
12056 (not (member this org-done-keywords))))
12057 (and logging (org-local-logging logging))
12058 (when (and (or org-todo-log-states org-log-done)
12059 (not (eq org-inhibit-logging t))
12060 (not (memq arg '(nextset previousset))))
12061 ;; we need to look at recording a time and note
12062 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12063 (nth 2 (assoc this org-todo-log-states))))
12064 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12065 (setq dolog 'time))
12066 (when (and org-state
12067 (member org-state org-not-done-keywords)
12068 (not (member this org-not-done-keywords)))
12069 ;; This is now a todo state and was not one before
12070 ;; If there was a CLOSED time stamp, get rid of it.
12071 (org-add-planning-info nil nil 'closed))
12072 (when (and now-done-p org-log-done)
12073 ;; It is now done, and it was not done before
12074 (org-add-planning-info 'closed (org-current-effective-time))
12075 (if (and (not dolog) (eq 'note org-log-done))
12076 (org-add-log-setup 'done org-state this 'findpos 'note)))
12077 (when (and org-state dolog)
12078 ;; This is a non-nil state, and we need to log it
12079 (org-add-log-setup 'state org-state this 'findpos dolog)))
12080 ;; Fixup tag positioning
12081 (org-todo-trigger-tag-changes org-state)
12082 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12083 (when org-provide-todo-statistics
12084 (org-update-parent-todo-statistics))
12085 (run-hooks 'org-after-todo-state-change-hook)
12086 (if (and arg (not (member org-state org-done-keywords)))
12087 (setq head (org-get-todo-sequence-head org-state)))
12088 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12089 ;; Do we need to trigger a repeat?
12090 (when now-done-p
12091 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12092 ;; This is for the agenda, take a snapshot of the headline.
12093 (save-match-data
12094 (setq org-agenda-headline-snapshot-before-repeat
12095 (org-get-heading))))
12096 (org-auto-repeat-maybe org-state))
12097 ;; Fixup cursor location if close to the keyword
12098 (if (and (outline-on-heading-p)
12099 (not (bolp))
12100 (save-excursion (beginning-of-line 1)
12101 (looking-at org-todo-line-regexp))
12102 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12103 (progn
12104 (goto-char (or (match-end 2) (match-end 1)))
12105 (and (looking-at " ") (just-one-space))))
12106 (when org-trigger-hook
12107 (save-excursion
12108 (run-hook-with-args 'org-trigger-hook change-plist)))
12109 (when commentp (org-toggle-comment))))))))
12111 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12112 "Block turning an entry into a TODO, using the hierarchy.
12113 This checks whether the current task should be blocked from state
12114 changes. Such blocking occurs when:
12116 1. The task has children which are not all in a completed state.
12118 2. A task has a parent with the property :ORDERED:, and there
12119 are siblings prior to the current task with incomplete
12120 status.
12122 3. The parent of the task is blocked because it has siblings that should
12123 be done first, or is child of a block grandparent TODO entry."
12125 (if (not org-enforce-todo-dependencies)
12126 t ; if locally turned off don't block
12127 (catch 'dont-block
12128 ;; If this is not a todo state change, or if this entry is already DONE,
12129 ;; do not block
12130 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12131 (member (plist-get change-plist :from)
12132 (cons 'done org-done-keywords))
12133 (member (plist-get change-plist :to)
12134 (cons 'todo org-not-done-keywords))
12135 (not (plist-get change-plist :to)))
12136 (throw 'dont-block t))
12137 ;; If this task has children, and any are undone, it's blocked
12138 (save-excursion
12139 (org-back-to-heading t)
12140 (let ((this-level (funcall outline-level)))
12141 (outline-next-heading)
12142 (let ((child-level (funcall outline-level)))
12143 (while (and (not (eobp))
12144 (> child-level this-level))
12145 ;; this todo has children, check whether they are all
12146 ;; completed
12147 (if (and (not (org-entry-is-done-p))
12148 (org-entry-is-todo-p))
12149 (progn (setq org-block-entry-blocking (org-get-heading))
12150 (throw 'dont-block nil)))
12151 (outline-next-heading)
12152 (setq child-level (funcall outline-level))))))
12153 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12154 ;; any previous siblings are undone, it's blocked
12155 (save-excursion
12156 (org-back-to-heading t)
12157 (let* ((pos (point))
12158 (parent-pos (and (org-up-heading-safe) (point))))
12159 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12160 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12161 (forward-line 1)
12162 (re-search-forward org-not-done-heading-regexp pos t))
12163 (setq org-block-entry-blocking (match-string 0))
12164 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12165 ;; Search further up the hierarchy, to see if an ancestor is blocked
12166 (while t
12167 (goto-char parent-pos)
12168 (if (not (looking-at org-not-done-heading-regexp))
12169 (throw 'dont-block t)) ; do not block, parent is not a TODO
12170 (setq pos (point))
12171 (setq parent-pos (and (org-up-heading-safe) (point)))
12172 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12173 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12174 (forward-line 1)
12175 (re-search-forward org-not-done-heading-regexp pos t)
12176 (setq org-block-entry-blocking (org-get-heading)))
12177 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12179 (defcustom org-track-ordered-property-with-tag nil
12180 "Should the ORDERED property also be shown as a tag?
12181 The ORDERED property decides if an entry should require subtasks to be
12182 completed in sequence. Since a property is not very visible, setting
12183 this option means that toggling the ORDERED property with the command
12184 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12185 not relevant for the behavior, but it makes things more visible.
12187 Note that toggling the tag with tags commands will not change the property
12188 and therefore not influence behavior!
12190 This can be t, meaning the tag ORDERED should be used, It can also be a
12191 string to select a different tag for this task."
12192 :group 'org-todo
12193 :type '(choice
12194 (const :tag "No tracking" nil)
12195 (const :tag "Track with ORDERED tag" t)
12196 (string :tag "Use other tag")))
12198 (defun org-toggle-ordered-property ()
12199 "Toggle the ORDERED property of the current entry.
12200 For better visibility, you can track the value of this property with a tag.
12201 See variable `org-track-ordered-property-with-tag'."
12202 (interactive)
12203 (let* ((t1 org-track-ordered-property-with-tag)
12204 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12205 (save-excursion
12206 (org-back-to-heading)
12207 (if (org-entry-get nil "ORDERED")
12208 (progn
12209 (org-delete-property "ORDERED" "PROPERTIES")
12210 (and tag (org-toggle-tag tag 'off))
12211 (message "Subtasks can be completed in arbitrary order"))
12212 (org-entry-put nil "ORDERED" "t")
12213 (and tag (org-toggle-tag tag 'on))
12214 (message "Subtasks must be completed in sequence")))))
12216 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12217 (defun org-block-todo-from-checkboxes (change-plist)
12218 "Block turning an entry into a TODO, using checkboxes.
12219 This checks whether the current task should be blocked from state
12220 changes because there are unchecked boxes in this entry."
12221 (if (not org-enforce-todo-checkbox-dependencies)
12222 t ; if locally turned off don't block
12223 (catch 'dont-block
12224 ;; If this is not a todo state change, or if this entry is already DONE,
12225 ;; do not block
12226 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12227 (member (plist-get change-plist :from)
12228 (cons 'done org-done-keywords))
12229 (member (plist-get change-plist :to)
12230 (cons 'todo org-not-done-keywords))
12231 (not (plist-get change-plist :to)))
12232 (throw 'dont-block t))
12233 ;; If this task has checkboxes that are not checked, it's blocked
12234 (save-excursion
12235 (org-back-to-heading t)
12236 (let ((beg (point)) end)
12237 (outline-next-heading)
12238 (setq end (point))
12239 (goto-char beg)
12240 (if (org-list-search-forward
12241 (concat (org-item-beginning-re)
12242 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12243 "\\[[- ]\\]")
12244 end t)
12245 (progn
12246 (if (boundp 'org-blocked-by-checkboxes)
12247 (setq org-blocked-by-checkboxes t))
12248 (throw 'dont-block nil)))))
12249 t))) ; do not block
12251 (defun org-entry-blocked-p ()
12252 "Is the current entry blocked?"
12253 (org-with-silent-modifications
12254 (if (org-entry-get nil "NOBLOCKING")
12255 nil ;; Never block this entry
12256 (not (run-hook-with-args-until-failure
12257 'org-blocker-hook
12258 (list :type 'todo-state-change
12259 :position (point)
12260 :from 'todo
12261 :to 'done))))))
12263 (defun org-update-statistics-cookies (all)
12264 "Update the statistics cookie, either from TODO or from checkboxes.
12265 This should be called with the cursor in a line with a statistics cookie."
12266 (interactive "P")
12267 (if all
12268 (progn
12269 (org-update-checkbox-count 'all)
12270 (org-map-entries 'org-update-parent-todo-statistics))
12271 (if (not (org-at-heading-p))
12272 (org-update-checkbox-count)
12273 (let ((pos (point-marker))
12274 end l1 l2)
12275 (ignore-errors (org-back-to-heading t))
12276 (if (not (org-at-heading-p))
12277 (org-update-checkbox-count)
12278 (setq l1 (org-outline-level))
12279 (setq end (save-excursion
12280 (outline-next-heading)
12281 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12282 (point)))
12283 (if (and (save-excursion
12284 (re-search-forward
12285 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12286 (not (save-excursion (re-search-forward
12287 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12288 (org-update-checkbox-count)
12289 (if (and l2 (> l2 l1))
12290 (progn
12291 (goto-char end)
12292 (org-update-parent-todo-statistics))
12293 (goto-char pos)
12294 (beginning-of-line 1)
12295 (while (re-search-forward
12296 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12297 (point-at-eol) t)
12298 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12299 (goto-char pos)
12300 (move-marker pos nil)))))
12302 (defvar org-entry-property-inherited-from) ;; defined below
12303 (defun org-update-parent-todo-statistics ()
12304 "Update any statistics cookie in the parent of the current headline.
12305 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12306 the entire subtree and this will travel up the hierarchy and update
12307 statistics everywhere."
12308 (let* ((prop (save-excursion (org-up-heading-safe)
12309 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12310 (recursive (or (not org-hierarchical-todo-statistics)
12311 (and prop (string-match "\\<recursive\\>" prop))))
12312 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12314 (first t)
12315 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12316 level ltoggle l1 new ndel
12317 (cnt-all 0) (cnt-done 0) is-percent kwd
12318 checkbox-beg ov ovs ove cookie-present)
12319 (catch 'exit
12320 (save-excursion
12321 (beginning-of-line 1)
12322 (setq ltoggle (funcall outline-level))
12323 ;; Three situations are to consider:
12325 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12326 ;; to the top-level ancestor on the headline;
12328 ;; 2. If parent has "recursive" property, repeat up to the
12329 ;; headline setting that property, taking inheritance into
12330 ;; account;
12332 ;; 3. Else, move up to direct parent and proceed only once.
12333 (while (and (setq level (org-up-heading-safe))
12334 (or recursive first)
12335 (>= (point) lim))
12336 (setq first nil cookie-present nil)
12337 (unless (and level
12338 (not (string-match
12339 "\\<checkbox\\>"
12340 (downcase (or (org-entry-get nil "COOKIE_DATA")
12341 "")))))
12342 (throw 'exit nil))
12343 (while (re-search-forward box-re (point-at-eol) t)
12344 (setq cnt-all 0 cnt-done 0 cookie-present t)
12345 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12346 (save-match-data
12347 (unless (outline-next-heading) (throw 'exit nil))
12348 (while (and (looking-at org-complex-heading-regexp)
12349 (> (setq l1 (length (match-string 1))) level))
12350 (setq kwd (and (or recursive (= l1 ltoggle))
12351 (match-string 2)))
12352 (if (or (eq org-provide-todo-statistics 'all-headlines)
12353 (and (listp org-provide-todo-statistics)
12354 (or (member kwd org-provide-todo-statistics)
12355 (member kwd org-done-keywords))))
12356 (setq cnt-all (1+ cnt-all))
12357 (if (eq org-provide-todo-statistics t)
12358 (and kwd (setq cnt-all (1+ cnt-all)))))
12359 (and (member kwd org-done-keywords)
12360 (setq cnt-done (1+ cnt-done)))
12361 (outline-next-heading)))
12362 (setq new
12363 (if is-percent
12364 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12365 (format "[%d/%d]" cnt-done cnt-all))
12366 ndel (- (match-end 0) checkbox-beg))
12367 ;; handle overlays when updating cookie from column view
12368 (when (setq ov (car (overlays-at checkbox-beg)))
12369 (setq ovs (overlay-start ov) ove (overlay-end ov))
12370 (delete-overlay ov))
12371 (goto-char checkbox-beg)
12372 (insert new)
12373 (delete-region (point) (+ (point) ndel))
12374 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12375 (when ov (move-overlay ov ovs ove)))
12376 (when cookie-present
12377 (run-hook-with-args 'org-after-todo-statistics-hook
12378 cnt-done (- cnt-all cnt-done))))))
12379 (run-hooks 'org-todo-statistics-hook)))
12381 (defvar org-after-todo-statistics-hook nil
12382 "Hook that is called after a TODO statistics cookie has been updated.
12383 Each function is called with two arguments: the number of not-done entries
12384 and the number of done entries.
12386 For example, the following function, when added to this hook, will switch
12387 an entry to DONE when all children are done, and back to TODO when new
12388 entries are set to a TODO status. Note that this hook is only called
12389 when there is a statistics cookie in the headline!
12391 (defun org-summary-todo (n-done n-not-done)
12392 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12393 (let (org-log-done org-log-states) ; turn off logging
12394 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12397 (defvar org-todo-statistics-hook nil
12398 "Hook that is run whenever Org thinks TODO statistics should be updated.
12399 This hook runs even if there is no statistics cookie present, in which case
12400 `org-after-todo-statistics-hook' would not run.")
12402 (defun org-todo-trigger-tag-changes (state)
12403 "Apply the changes defined in `org-todo-state-tags-triggers'."
12404 (let ((l org-todo-state-tags-triggers)
12405 changes)
12406 (when (or (not state) (equal state ""))
12407 (setq changes (append changes (cdr (assoc "" l)))))
12408 (when (and (stringp state) (> (length state) 0))
12409 (setq changes (append changes (cdr (assoc state l)))))
12410 (when (member state org-not-done-keywords)
12411 (setq changes (append changes (cdr (assoc 'todo l)))))
12412 (when (member state org-done-keywords)
12413 (setq changes (append changes (cdr (assoc 'done l)))))
12414 (dolist (c changes)
12415 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12417 (defun org-local-logging (value)
12418 "Get logging settings from a property VALUE."
12419 (let* (words w a)
12420 ;; directly set the variables, they are already local.
12421 (setq org-log-done nil
12422 org-log-repeat nil
12423 org-todo-log-states nil)
12424 (setq words (org-split-string value))
12425 (while (setq w (pop words))
12426 (cond
12427 ((setq a (assoc w org-startup-options))
12428 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12429 (set (nth 1 a) (nth 2 a))))
12430 ((setq a (org-extract-log-state-settings w))
12431 (and (member (car a) org-todo-keywords-1)
12432 (push a org-todo-log-states)))))))
12434 (defun org-get-todo-sequence-head (kwd)
12435 "Return the head of the TODO sequence to which KWD belongs.
12436 If KWD is not set, check if there is a text property remembering the
12437 right sequence."
12438 (let (p)
12439 (cond
12440 ((not kwd)
12441 (or (get-text-property (point-at-bol) 'org-todo-head)
12442 (progn
12443 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12444 nil (point-at-eol)))
12445 (get-text-property p 'org-todo-head))))
12446 ((not (member kwd org-todo-keywords-1))
12447 (car org-todo-keywords-1))
12448 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12450 (defun org-fast-todo-selection ()
12451 "Fast TODO keyword selection with single keys.
12452 Returns the new TODO keyword, or nil if no state change should occur."
12453 (let* ((fulltable org-todo-key-alist)
12454 (done-keywords org-done-keywords) ;; needed for the faces.
12455 (maxlen (apply 'max (mapcar
12456 (lambda (x)
12457 (if (stringp (car x)) (string-width (car x)) 0))
12458 fulltable)))
12459 (expert nil)
12460 (fwidth (+ maxlen 3 1 3))
12461 (ncol (/ (- (window-width) 4) fwidth))
12462 tg cnt e c tbl
12463 groups ingroup)
12464 (save-excursion
12465 (save-window-excursion
12466 (if expert
12467 (set-buffer (get-buffer-create " *Org todo*"))
12468 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12469 (erase-buffer)
12470 (org-set-local 'org-done-keywords done-keywords)
12471 (setq tbl fulltable cnt 0)
12472 (while (setq e (pop tbl))
12473 (cond
12474 ((equal e '(:startgroup))
12475 (push '() groups) (setq ingroup t)
12476 (when (not (= cnt 0))
12477 (setq cnt 0)
12478 (insert "\n"))
12479 (insert "{ "))
12480 ((equal e '(:endgroup))
12481 (setq ingroup nil cnt 0)
12482 (insert "}\n"))
12483 ((equal e '(:newline))
12484 (when (not (= cnt 0))
12485 (setq cnt 0)
12486 (insert "\n")
12487 (setq e (car tbl))
12488 (while (equal (car tbl) '(:newline))
12489 (insert "\n")
12490 (setq tbl (cdr tbl)))))
12492 (setq tg (car e) c (cdr e))
12493 (if ingroup (push tg (car groups)))
12494 (setq tg (org-add-props tg nil 'face
12495 (org-get-todo-face tg)))
12496 (if (and (= cnt 0) (not ingroup)) (insert " "))
12497 (insert "[" c "] " tg (make-string
12498 (- fwidth 4 (length tg)) ?\ ))
12499 (when (= (setq cnt (1+ cnt)) ncol)
12500 (insert "\n")
12501 (if ingroup (insert " "))
12502 (setq cnt 0)))))
12503 (insert "\n")
12504 (goto-char (point-min))
12505 (if (not expert) (org-fit-window-to-buffer))
12506 (message "[a-z..]:Set [SPC]:clear")
12507 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12508 (cond
12509 ((or (= c ?\C-g)
12510 (and (= c ?q) (not (rassoc c fulltable))))
12511 (setq quit-flag t))
12512 ((= c ?\ ) nil)
12513 ((setq e (rassoc c fulltable) tg (car e))
12515 (t (setq quit-flag t)))))))
12517 (defun org-entry-is-todo-p ()
12518 (member (org-get-todo-state) org-not-done-keywords))
12520 (defun org-entry-is-done-p ()
12521 (member (org-get-todo-state) org-done-keywords))
12523 (defun org-get-todo-state ()
12524 (save-excursion
12525 (org-back-to-heading t)
12526 (and (looking-at org-todo-line-regexp)
12527 (match-end 2)
12528 (match-string 2))))
12530 (defun org-at-date-range-p (&optional inactive-ok)
12531 "Is the cursor inside a date range?"
12532 (interactive)
12533 (save-excursion
12534 (catch 'exit
12535 (let ((pos (point)))
12536 (skip-chars-backward "^[<\r\n")
12537 (skip-chars-backward "<[")
12538 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12539 (>= (match-end 0) pos)
12540 (throw 'exit t))
12541 (skip-chars-backward "^<[\r\n")
12542 (skip-chars-backward "<[")
12543 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12544 (>= (match-end 0) pos)
12545 (throw 'exit t)))
12546 nil)))
12548 (defun org-get-repeat (&optional tagline)
12549 "Check if there is a deadline/schedule with repeater in this entry."
12550 (save-match-data
12551 (save-excursion
12552 (org-back-to-heading t)
12553 (and (re-search-forward (if tagline
12554 (concat tagline "\\s-*" org-repeat-re)
12555 org-repeat-re)
12556 (org-entry-end-position) t)
12557 (match-string-no-properties 1)))))
12559 (defvar org-last-changed-timestamp)
12560 (defvar org-last-inserted-timestamp)
12561 (defvar org-log-post-message)
12562 (defvar org-log-note-purpose)
12563 (defvar org-log-note-how)
12564 (defvar org-log-note-extra)
12565 (defun org-auto-repeat-maybe (done-word)
12566 "Check if the current headline contains a repeated deadline/schedule.
12567 If yes, set TODO state back to what it was and change the base date
12568 of repeating deadline/scheduled time stamps to new date.
12569 This function is run automatically after each state change to a DONE state."
12570 ;; last-state is dynamically scoped into this function
12571 (let* ((repeat (org-get-repeat))
12572 (aa (assoc org-last-state org-todo-kwd-alist))
12573 (interpret (nth 1 aa))
12574 (head (nth 2 aa))
12575 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12576 (msg "Entry repeats: ")
12577 (org-log-done nil)
12578 (org-todo-log-states nil)
12579 re type n what ts time to-state)
12580 (when repeat
12581 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12582 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12583 org-todo-repeat-to-state))
12584 (unless (and to-state (member to-state org-todo-keywords-1))
12585 (setq to-state (if (eq interpret 'type) org-last-state head)))
12586 (org-todo to-state)
12587 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12588 (org-entry-put nil "LAST_REPEAT" (format-time-string
12589 (org-time-stamp-format t t))))
12590 (when org-log-repeat
12591 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12592 (memq 'org-add-log-note post-command-hook))
12593 ;; OK, we are already setup for some record
12594 (if (eq org-log-repeat 'note)
12595 ;; make sure we take a note, not only a time stamp
12596 (setq org-log-note-how 'note))
12597 ;; Set up for taking a record
12598 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12599 org-last-state
12600 'findpos org-log-repeat)))
12601 (org-back-to-heading t)
12602 (org-add-planning-info nil nil 'closed)
12603 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12604 org-deadline-time-regexp "\\)\\|\\("
12605 org-ts-regexp "\\)"))
12606 (while (re-search-forward
12607 re (save-excursion (outline-next-heading) (point)) t)
12608 (setq type (if (match-end 1) org-scheduled-string
12609 (if (match-end 3) org-deadline-string "Plain:"))
12610 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12611 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12612 (setq n (string-to-number (match-string 2 ts))
12613 what (match-string 3 ts))
12614 (if (equal what "w") (setq n (* n 7) what "d"))
12615 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12616 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12617 ;; Preparation, see if we need to modify the start date for the change
12618 (when (match-end 1)
12619 (setq time (save-match-data (org-time-string-to-time ts)))
12620 (cond
12621 ((equal (match-string 1 ts) ".")
12622 ;; Shift starting date to today
12623 (org-timestamp-change
12624 (- (org-today) (time-to-days time))
12625 'day))
12626 ((equal (match-string 1 ts) "+")
12627 (let ((nshiftmax 10) (nshift 0))
12628 (while (or (= nshift 0)
12629 (<= (time-to-days time)
12630 (time-to-days (current-time))))
12631 (when (= (incf nshift) nshiftmax)
12632 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12633 (error "Abort")))
12634 (org-timestamp-change n (cdr (assoc what whata)))
12635 (org-at-timestamp-p t)
12636 (setq ts (match-string 1))
12637 (setq time (save-match-data (org-time-string-to-time ts)))))
12638 (org-timestamp-change (- n) (cdr (assoc what whata)))
12639 ;; rematch, so that we have everything in place for the real shift
12640 (org-at-timestamp-p t)
12641 (setq ts (match-string 1))
12642 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12643 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12644 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12645 (setq org-log-post-message msg)
12646 (message "%s" msg))))
12648 (defun org-show-todo-tree (arg)
12649 "Make a compact tree which shows all headlines marked with TODO.
12650 The tree will show the lines where the regexp matches, and all higher
12651 headlines above the match.
12652 With a \\[universal-argument] prefix, prompt for a regexp to match.
12653 With a numeric prefix N, construct a sparse tree for the Nth element
12654 of `org-todo-keywords-1'."
12655 (interactive "P")
12656 (let ((case-fold-search nil)
12657 (kwd-re
12658 (cond ((null arg) org-not-done-regexp)
12659 ((equal arg '(4))
12660 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12661 (mapcar 'list org-todo-keywords-1))))
12662 (concat "\\("
12663 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12664 "\\)\\>")))
12665 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12666 (regexp-quote (nth (1- (prefix-numeric-value arg))
12667 org-todo-keywords-1)))
12668 (t (error "Invalid prefix argument: %s" arg)))))
12669 (message "%d TODO entries found"
12670 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12672 (defun org-deadline (arg &optional time)
12673 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12674 With one universal prefix argument, remove any deadline from the item.
12675 With two universal prefix arguments, prompt for a warning delay.
12676 With argument TIME, set the deadline at the corresponding date. TIME
12677 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12678 (interactive "P")
12679 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12680 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12681 'region-start-level 'region))
12682 org-loop-over-headlines-in-active-region)
12683 (org-map-entries
12684 `(org-deadline ',arg ,time)
12685 org-loop-over-headlines-in-active-region
12686 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12687 (let* ((old-date (org-entry-get nil "DEADLINE"))
12688 (old-date-time (if old-date (org-time-string-to-time old-date)))
12689 (repeater (and old-date
12690 (string-match
12691 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12692 old-date)
12693 (match-string 1 old-date))))
12694 (cond
12695 ((equal arg '(4))
12696 (when (and old-date org-log-redeadline)
12697 (org-add-log-setup 'deldeadline nil old-date 'findpos
12698 org-log-redeadline))
12699 (org-remove-timestamp-with-keyword org-deadline-string)
12700 (message "Item no longer has a deadline."))
12701 ((equal arg '(16))
12702 (save-excursion
12703 (if (re-search-forward
12704 org-deadline-time-regexp
12705 (save-excursion (outline-next-heading) (point)) t)
12706 (let* ((rpl0 (match-string 1))
12707 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12708 (replace-match
12709 (concat org-deadline-string
12710 " <" rpl
12711 (format " -%dd"
12712 (abs
12713 (- (time-to-days
12714 (save-match-data
12715 (org-read-date nil t nil "Warn starting from" old-date-time)))
12716 (time-to-days old-date-time))))
12717 ">") t t))
12718 (user-error "No deadline information to update"))))
12720 (org-add-planning-info 'deadline time 'closed)
12721 (when (and old-date org-log-redeadline
12722 (not (equal old-date
12723 (substring org-last-inserted-timestamp 1 -1))))
12724 (org-add-log-setup 'redeadline nil old-date 'findpos
12725 org-log-redeadline))
12726 (when repeater
12727 (save-excursion
12728 (org-back-to-heading t)
12729 (when (re-search-forward (concat org-deadline-string " "
12730 org-last-inserted-timestamp)
12731 (save-excursion
12732 (outline-next-heading) (point)) t)
12733 (goto-char (1- (match-end 0)))
12734 (insert " " repeater)
12735 (setq org-last-inserted-timestamp
12736 (concat (substring org-last-inserted-timestamp 0 -1)
12737 " " repeater
12738 (substring org-last-inserted-timestamp -1))))))
12739 (message "Deadline on %s" org-last-inserted-timestamp))))))
12741 (defun org-schedule (arg &optional time)
12742 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12743 With one universal prefix argument, remove any scheduling date from the item.
12744 With two universal prefix arguments, prompt for a delay cookie.
12745 With argument TIME, scheduled at the corresponding date. TIME can
12746 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12747 (interactive "P")
12748 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12749 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12750 'region-start-level 'region))
12751 org-loop-over-headlines-in-active-region)
12752 (org-map-entries
12753 `(org-schedule ',arg ,time)
12754 org-loop-over-headlines-in-active-region
12755 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12756 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12757 (old-date-time (if old-date (org-time-string-to-time old-date)))
12758 (repeater (and old-date
12759 (string-match
12760 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12761 old-date)
12762 (match-string 1 old-date))))
12763 (cond
12764 ((equal arg '(4))
12765 (progn
12766 (when (and old-date org-log-reschedule)
12767 (org-add-log-setup 'delschedule nil old-date 'findpos
12768 org-log-reschedule))
12769 (org-remove-timestamp-with-keyword org-scheduled-string)
12770 (message "Item is no longer scheduled.")))
12771 ((equal arg '(16))
12772 (save-excursion
12773 (if (re-search-forward
12774 org-scheduled-time-regexp
12775 (save-excursion (outline-next-heading) (point)) t)
12776 (let* ((rpl0 (match-string 1))
12777 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12778 (replace-match
12779 (concat org-scheduled-string
12780 " <" rpl
12781 (format " -%dd"
12782 (abs
12783 (- (time-to-days
12784 (save-match-data
12785 (org-read-date nil t nil "Delay until" old-date-time)))
12786 (time-to-days old-date-time))))
12787 ">") t t))
12788 (user-error "No scheduled information to update"))))
12790 (org-add-planning-info 'scheduled time 'closed)
12791 (when (and old-date org-log-reschedule
12792 (not (equal old-date
12793 (substring org-last-inserted-timestamp 1 -1))))
12794 (org-add-log-setup 'reschedule nil old-date 'findpos
12795 org-log-reschedule))
12796 (when repeater
12797 (save-excursion
12798 (org-back-to-heading t)
12799 (when (re-search-forward (concat org-scheduled-string " "
12800 org-last-inserted-timestamp)
12801 (save-excursion
12802 (outline-next-heading) (point)) t)
12803 (goto-char (1- (match-end 0)))
12804 (insert " " repeater)
12805 (setq org-last-inserted-timestamp
12806 (concat (substring org-last-inserted-timestamp 0 -1)
12807 " " repeater
12808 (substring org-last-inserted-timestamp -1))))))
12809 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12811 (defun org-get-scheduled-time (pom &optional inherit)
12812 "Get the scheduled time as a time tuple, of a format suitable
12813 for calling org-schedule with, or if there is no scheduling,
12814 returns nil."
12815 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12816 (when time
12817 (apply 'encode-time (org-parse-time-string time)))))
12819 (defun org-get-deadline-time (pom &optional inherit)
12820 "Get the deadline as a time tuple, of a format suitable for
12821 calling org-deadline with, or if there is no scheduling, returns
12822 nil."
12823 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12824 (when time
12825 (apply 'encode-time (org-parse-time-string time)))))
12827 (defun org-remove-timestamp-with-keyword (keyword)
12828 "Remove all time stamps with KEYWORD in the current entry."
12829 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12830 beg)
12831 (save-excursion
12832 (org-back-to-heading t)
12833 (setq beg (point))
12834 (outline-next-heading)
12835 (while (re-search-backward re beg t)
12836 (replace-match "")
12837 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12838 (equal (char-before) ?\ ))
12839 (backward-delete-char 1)
12840 (if (string-match "^[ \t]*$" (buffer-substring
12841 (point-at-bol) (point-at-eol)))
12842 (delete-region (point-at-bol)
12843 (min (point-max) (1+ (point-at-eol))))))))))
12845 (defun org-add-planning-info (what &optional time &rest remove)
12846 "Insert new timestamp with keyword in the line directly after the headline.
12847 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12848 If non is given, the user is prompted for a date.
12849 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12850 be removed."
12851 (interactive)
12852 (let (org-time-was-given org-end-time-was-given ts
12853 end default-time default-input)
12855 (catch 'exit
12856 (when (and (memq what '(scheduled deadline))
12857 (or (not time)
12858 (and (stringp time)
12859 (string-match "^[-+]+[0-9]" time))))
12860 ;; Try to get a default date/time from existing timestamp
12861 (save-excursion
12862 (org-back-to-heading t)
12863 (setq end (save-excursion (outline-next-heading) (point)))
12864 (when (re-search-forward (if (eq what 'scheduled)
12865 org-scheduled-time-regexp
12866 org-deadline-time-regexp)
12867 end t)
12868 (setq ts (match-string 1)
12869 default-time
12870 (apply 'encode-time (org-parse-time-string ts))
12871 default-input (and ts (org-get-compact-tod ts))))))
12872 (when what
12873 (setq time
12874 (if (stringp time)
12875 ;; This is a string (relative or absolute), set proper date
12876 (apply 'encode-time
12877 (org-read-date-analyze
12878 time default-time (decode-time default-time)))
12879 ;; If necessary, get the time from the user
12880 (or time (org-read-date nil 'to-time nil nil
12881 default-time default-input)))))
12883 (when (and org-insert-labeled-timestamps-at-point
12884 (member what '(scheduled deadline)))
12885 (insert
12886 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12887 (org-insert-time-stamp time org-time-was-given
12888 nil nil nil (list org-end-time-was-given))
12889 (setq what nil))
12890 (save-excursion
12891 (save-restriction
12892 (let (col list elt ts buffer-invisibility-spec)
12893 (org-back-to-heading t)
12894 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12895 (goto-char (match-end 1))
12896 (setq col (current-column))
12897 (goto-char (match-end 0))
12898 (if (eobp) (insert "\n") (forward-char 1))
12899 (when (and (not what)
12900 (not (looking-at
12901 (concat "[ \t]*"
12902 org-keyword-time-not-clock-regexp))))
12903 ;; Nothing to add, nothing to remove...... :-)
12904 (throw 'exit nil))
12905 (if (and (not (looking-at org-outline-regexp))
12906 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12907 "[^\r\n]*"))
12908 (not (equal (match-string 1) org-clock-string)))
12909 (narrow-to-region (match-beginning 0) (match-end 0))
12910 (insert-before-markers "\n")
12911 (backward-char 1)
12912 (narrow-to-region (point) (point))
12913 (and org-adapt-indentation (org-indent-to-column col)))
12914 ;; Check if we have to remove something.
12915 (setq list (cons what remove))
12916 (while list
12917 (setq elt (pop list))
12918 (when (or (and (eq elt 'scheduled)
12919 (re-search-forward org-scheduled-time-regexp nil t))
12920 (and (eq elt 'deadline)
12921 (re-search-forward org-deadline-time-regexp nil t))
12922 (and (eq elt 'closed)
12923 (re-search-forward org-closed-time-regexp nil t)))
12924 (replace-match "")
12925 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12926 (and (looking-at "[ \t]+") (replace-match ""))
12927 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12928 (when what
12929 (insert
12930 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12931 (cond ((eq what 'scheduled) org-scheduled-string)
12932 ((eq what 'deadline) org-deadline-string)
12933 ((eq what 'closed) org-closed-string))
12934 " ")
12935 (setq ts (org-insert-time-stamp
12936 time
12937 (or org-time-was-given
12938 (and (eq what 'closed) org-log-done-with-time))
12939 (eq what 'closed)
12940 nil nil (list org-end-time-was-given)))
12941 (insert
12942 (if (not (or (bolp) (eq (char-before) ?\ )
12943 (memq (char-after) '(32 10))
12944 (eobp))) " " ""))
12945 (end-of-line 1))
12946 (goto-char (point-min))
12947 (widen)
12948 (if (and (looking-at "[ \t]*\n")
12949 (equal (char-before) ?\n))
12950 (delete-region (1- (point)) (point-at-eol)))
12951 ts))))))
12953 (defvar org-log-note-marker (make-marker))
12954 (defvar org-log-note-purpose nil)
12955 (defvar org-log-note-state nil)
12956 (defvar org-log-note-previous-state nil)
12957 (defvar org-log-note-how nil)
12958 (defvar org-log-note-extra nil)
12959 (defvar org-log-note-window-configuration nil)
12960 (defvar org-log-note-return-to (make-marker))
12961 (defvar org-log-note-effective-time nil
12962 "Remembered current time so that dynamically scoped
12963 `org-extend-today-until' affects tha timestamps in state change
12964 log")
12966 (defvar org-log-post-message nil
12967 "Message to be displayed after a log note has been stored.
12968 The auto-repeater uses this.")
12970 (defun org-add-note ()
12971 "Add a note to the current entry.
12972 This is done in the same way as adding a state change note."
12973 (interactive)
12974 (org-add-log-setup 'note nil nil 'findpos nil))
12976 (defvar org-property-end-re)
12977 (defun org-add-log-setup (&optional purpose state prev-state
12978 findpos how extra)
12979 "Set up the post command hook to take a note.
12980 If this is about to TODO state change, the new state is expected in STATE.
12981 When FINDPOS is non-nil, find the correct position for the note in
12982 the current entry. If not, assume that it can be inserted at point.
12983 HOW is an indicator what kind of note should be created.
12984 EXTRA is additional text that will be inserted into the notes buffer."
12985 (let* ((org-log-into-drawer (org-log-into-drawer))
12986 (drawer (cond ((stringp org-log-into-drawer)
12987 org-log-into-drawer)
12988 (org-log-into-drawer "LOGBOOK"))))
12989 (save-restriction
12990 (save-excursion
12991 (when findpos
12992 (org-back-to-heading t)
12993 (narrow-to-region (point) (save-excursion
12994 (outline-next-heading) (point)))
12995 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12996 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12997 "[^\r\n]*\\)?"))
12998 (goto-char (match-end 0))
12999 (cond
13000 (drawer
13001 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13002 nil t)
13003 (progn
13004 (goto-char (match-end 0))
13005 (or org-log-states-order-reversed
13006 (and (re-search-forward org-property-end-re nil t)
13007 (goto-char (1- (match-beginning 0))))))
13008 (insert "\n:" drawer ":\n:END:")
13009 (beginning-of-line 0)
13010 (org-indent-line)
13011 (beginning-of-line 2)
13012 (org-indent-line)
13013 (end-of-line 0)))
13014 ((and org-log-state-notes-insert-after-drawers
13015 (save-excursion
13016 (forward-line) (looking-at org-drawer-regexp)))
13017 (forward-line)
13018 (while (looking-at org-drawer-regexp)
13019 (goto-char (match-end 0))
13020 (re-search-forward org-property-end-re (point-max) t)
13021 (forward-line))
13022 (forward-line -1)))
13023 (unless org-log-states-order-reversed
13024 (and (= (char-after) ?\n) (forward-char 1))
13025 (org-skip-over-state-notes)
13026 (skip-chars-backward " \t\n\r")))
13027 (move-marker org-log-note-marker (point))
13028 (setq org-log-note-purpose purpose
13029 org-log-note-state state
13030 org-log-note-previous-state prev-state
13031 org-log-note-how how
13032 org-log-note-extra extra
13033 org-log-note-effective-time (org-current-effective-time))
13034 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13036 (defun org-skip-over-state-notes ()
13037 "Skip past the list of State notes in an entry."
13038 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13039 (when (ignore-errors (goto-char (org-in-item-p)))
13040 (let* ((struct (org-list-struct))
13041 (prevs (org-list-prevs-alist struct)))
13042 (while (looking-at "[ \t]*- State")
13043 (goto-char (or (org-list-get-next-item (point) struct prevs)
13044 (org-list-get-item-end (point) struct)))))))
13046 (defun org-add-log-note (&optional purpose)
13047 "Pop up a window for taking a note, and add this note later at point."
13048 (remove-hook 'post-command-hook 'org-add-log-note)
13049 (setq org-log-note-window-configuration (current-window-configuration))
13050 (delete-other-windows)
13051 (move-marker org-log-note-return-to (point))
13052 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13053 (goto-char org-log-note-marker)
13054 (org-switch-to-buffer-other-window "*Org Note*")
13055 (erase-buffer)
13056 (if (memq org-log-note-how '(time state))
13057 (let (current-prefix-arg) (org-store-log-note))
13058 (let ((org-inhibit-startup t)) (org-mode))
13059 (insert (format "# Insert note for %s.
13060 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13061 (cond
13062 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13063 ((eq org-log-note-purpose 'done) "closed todo item")
13064 ((eq org-log-note-purpose 'state)
13065 (format "state change from \"%s\" to \"%s\""
13066 (or org-log-note-previous-state "")
13067 (or org-log-note-state "")))
13068 ((eq org-log-note-purpose 'reschedule)
13069 "rescheduling")
13070 ((eq org-log-note-purpose 'delschedule)
13071 "no longer scheduled")
13072 ((eq org-log-note-purpose 'redeadline)
13073 "changing deadline")
13074 ((eq org-log-note-purpose 'deldeadline)
13075 "removing deadline")
13076 ((eq org-log-note-purpose 'refile)
13077 "refiling")
13078 ((eq org-log-note-purpose 'note)
13079 "this entry")
13080 (t (error "This should not happen")))))
13081 (if org-log-note-extra (insert org-log-note-extra))
13082 (org-set-local 'org-finish-function 'org-store-log-note)
13083 (run-hooks 'org-log-buffer-setup-hook)))
13085 (defvar org-note-abort nil) ; dynamically scoped
13086 (defun org-store-log-note ()
13087 "Finish taking a log note, and insert it to where it belongs."
13088 (let ((txt (buffer-string)))
13089 (kill-buffer (current-buffer))
13090 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13091 lines ind bul)
13092 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13093 (setq txt (replace-match "" t t txt)))
13094 (if (string-match "\\s-+\\'" txt)
13095 (setq txt (replace-match "" t t txt)))
13096 (setq lines (org-split-string txt "\n"))
13097 (when (and note (string-match "\\S-" note))
13098 (setq note
13099 (org-replace-escapes
13100 note
13101 (list (cons "%u" (user-login-name))
13102 (cons "%U" user-full-name)
13103 (cons "%t" (format-time-string
13104 (org-time-stamp-format 'long 'inactive)
13105 org-log-note-effective-time))
13106 (cons "%T" (format-time-string
13107 (org-time-stamp-format 'long nil)
13108 org-log-note-effective-time))
13109 (cons "%d" (format-time-string
13110 (org-time-stamp-format nil 'inactive)
13111 org-log-note-effective-time))
13112 (cons "%D" (format-time-string
13113 (org-time-stamp-format nil nil)
13114 org-log-note-effective-time))
13115 (cons "%s" (if org-log-note-state
13116 (concat "\"" org-log-note-state "\"")
13117 ""))
13118 (cons "%S" (if org-log-note-previous-state
13119 (concat "\"" org-log-note-previous-state "\"")
13120 "\"\"")))))
13121 (if lines (setq note (concat note " \\\\")))
13122 (push note lines))
13123 (when (or current-prefix-arg org-note-abort)
13124 (when org-log-into-drawer
13125 (org-remove-empty-drawer-at
13126 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13127 org-log-note-marker))
13128 (setq lines nil))
13129 (when lines
13130 (with-current-buffer (marker-buffer org-log-note-marker)
13131 (save-excursion
13132 (goto-char org-log-note-marker)
13133 (move-marker org-log-note-marker nil)
13134 (end-of-line 1)
13135 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13136 (setq ind (save-excursion
13137 (if (ignore-errors (goto-char (org-in-item-p)))
13138 (let ((struct (org-list-struct)))
13139 (org-list-get-ind
13140 (org-list-get-top-point struct) struct))
13141 (skip-chars-backward " \r\t\n")
13142 (cond
13143 ((and (org-at-heading-p)
13144 org-adapt-indentation)
13145 (1+ (org-current-level)))
13146 ((org-at-heading-p) 0)
13147 (t (org-get-indentation))))))
13148 (setq bul (org-list-bullet-string "-"))
13149 (org-indent-line-to ind)
13150 (insert bul (pop lines))
13151 (let ((ind-body (+ (length bul) ind)))
13152 (while lines
13153 (insert "\n")
13154 (org-indent-line-to ind-body)
13155 (insert (pop lines))))
13156 (message "Note stored")
13157 (org-back-to-heading t)
13158 (org-cycle-hide-drawers 'children))))))
13159 (set-window-configuration org-log-note-window-configuration)
13160 (with-current-buffer (marker-buffer org-log-note-return-to)
13161 (goto-char org-log-note-return-to))
13162 (move-marker org-log-note-return-to nil)
13163 (and org-log-post-message (message "%s" org-log-post-message)))
13165 (defun org-remove-empty-drawer-at (drawer pos)
13166 "Remove an empty drawer DRAWER at position POS.
13167 POS may also be a marker."
13168 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13169 (save-excursion
13170 (save-restriction
13171 (widen)
13172 (goto-char pos)
13173 (if (org-in-regexp
13174 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13175 (replace-match ""))))))
13177 (defvar org-ts-type nil)
13178 (defun org-sparse-tree (&optional arg type)
13179 "Create a sparse tree, prompt for the details.
13180 This command can create sparse trees. You first need to select the type
13181 of match used to create the tree:
13183 t Show all TODO entries.
13184 T Show entries with a specific TODO keyword.
13185 m Show entries selected by a tags/property match.
13186 p Enter a property name and its value (both with completion on existing
13187 names/values) and show entries with that property.
13188 r Show entries matching a regular expression (`/' can be used as well).
13189 b Show deadlines and scheduled items before a date.
13190 a Show deadlines and scheduled items after a date.
13191 d Show deadlines due within `org-deadline-warning-days'.
13192 D Show deadlines and scheduled items between a date range."
13193 (interactive "P")
13194 (let (ans kwd value ts-type)
13195 (setq type (or type org-sparse-tree-default-date-type))
13196 (setq org-ts-type type)
13197 (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"
13198 (cond ((eq type 'all) "all timestamps")
13199 ((eq type 'scheduled) "only scheduled")
13200 ((eq type 'deadline) "only deadline")
13201 ((eq type 'active) "only active timestamps")
13202 ((eq type 'inactive) "only inactive timestamps")
13203 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13204 (t "scheduled/deadline")))
13205 (setq ans (read-char-exclusive))
13206 (cond
13207 ((equal ans ?c)
13208 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13209 ((equal ans ?d)
13210 (call-interactively 'org-check-deadlines))
13211 ((equal ans ?b)
13212 (call-interactively 'org-check-before-date))
13213 ((equal ans ?a)
13214 (call-interactively 'org-check-after-date))
13215 ((equal ans ?D)
13216 (call-interactively 'org-check-dates-range))
13217 ((equal ans ?t)
13218 (call-interactively 'org-show-todo-tree))
13219 ((equal ans ?T)
13220 (org-show-todo-tree '(4)))
13221 ((member ans '(?T ?m))
13222 (call-interactively 'org-match-sparse-tree))
13223 ((member ans '(?p ?P))
13224 (setq kwd (org-icompleting-read "Property: "
13225 (mapcar 'list (org-buffer-property-keys))))
13226 (setq value (org-icompleting-read "Value: "
13227 (mapcar 'list (org-property-values kwd))))
13228 (unless (string-match "\\`{.*}\\'" value)
13229 (setq value (concat "\"" value "\"")))
13230 (org-match-sparse-tree arg (concat kwd "=" value)))
13231 ((member ans '(?r ?R ?/))
13232 (call-interactively 'org-occur))
13233 (t (error "No such sparse tree command \"%c\"" ans)))))
13235 (defvar org-occur-highlights nil
13236 "List of overlays used for occur matches.")
13237 (make-variable-buffer-local 'org-occur-highlights)
13238 (defvar org-occur-parameters nil
13239 "Parameters of the active org-occur calls.
13240 This is a list, each call to org-occur pushes as cons cell,
13241 containing the regular expression and the callback, onto the list.
13242 The list can contain several entries if `org-occur' has been called
13243 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13244 will only contain one set of parameters. When the highlights are
13245 removed (for example with `C-c C-c', or with the next edit (depending
13246 on `org-remove-highlights-with-change'), this variable is emptied
13247 as well.")
13248 (make-variable-buffer-local 'org-occur-parameters)
13250 (defun org-occur (regexp &optional keep-previous callback)
13251 "Make a compact tree which shows all matches of REGEXP.
13252 The tree will show the lines where the regexp matches, and all higher
13253 headlines above the match. It will also show the heading after the match,
13254 to make sure editing the matching entry is easy.
13255 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13256 call to `org-occur' will be kept, to allow stacking of calls to this
13257 command.
13258 If CALLBACK is non-nil, it is a function which is called to confirm
13259 that the match should indeed be shown."
13260 (interactive "sRegexp: \nP")
13261 (when (equal regexp "")
13262 (error "Regexp cannot be empty"))
13263 (unless keep-previous
13264 (org-remove-occur-highlights nil nil t))
13265 (push (cons regexp callback) org-occur-parameters)
13266 (let ((cnt 0))
13267 (save-excursion
13268 (goto-char (point-min))
13269 (if (or (not keep-previous) ; do not want to keep
13270 (not org-occur-highlights)) ; no previous matches
13271 ;; hide everything
13272 (org-overview))
13273 (while (re-search-forward regexp nil t)
13274 (when (or (not callback)
13275 (save-match-data (funcall callback)))
13276 (setq cnt (1+ cnt))
13277 (when org-highlight-sparse-tree-matches
13278 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13279 (org-show-context 'occur-tree))))
13280 (when org-remove-highlights-with-change
13281 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13282 nil 'local))
13283 (unless org-sparse-tree-open-archived-trees
13284 (org-hide-archived-subtrees (point-min) (point-max)))
13285 (run-hooks 'org-occur-hook)
13286 (if (org-called-interactively-p 'interactive)
13287 (message "%d match(es) for regexp %s" cnt regexp))
13288 cnt))
13290 (defun org-occur-next-match (&optional n reset)
13291 "Function for `next-error-function' to find sparse tree matches.
13292 N is the number of matches to move, when negative move backwards.
13293 RESET is entirely ignored - this function always goes back to the
13294 starting point when no match is found."
13295 (let* ((limit (if (< n 0) (point-min) (point-max)))
13296 (search-func (if (< n 0)
13297 'previous-single-char-property-change
13298 'next-single-char-property-change))
13299 (n (abs n))
13300 (pos (point))
13302 (catch 'exit
13303 (while (setq p1 (funcall search-func (point) 'org-type))
13304 (when (equal p1 limit)
13305 (goto-char pos)
13306 (error "No more matches"))
13307 (when (equal (get-char-property p1 'org-type) 'org-occur)
13308 (setq n (1- n))
13309 (when (= n 0)
13310 (goto-char p1)
13311 (throw 'exit (point))))
13312 (goto-char p1))
13313 (goto-char p1)
13314 (error "No more matches"))))
13316 (defun org-show-context (&optional key)
13317 "Make sure point and context are visible.
13318 How much context is shown depends upon the variables
13319 `org-show-hierarchy-above', `org-show-following-heading',
13320 `org-show-entry-below' and `org-show-siblings'."
13321 (let ((heading-p (org-at-heading-p t))
13322 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13323 (following-p (org-get-alist-option org-show-following-heading key))
13324 (entry-p (org-get-alist-option org-show-entry-below key))
13325 (siblings-p (org-get-alist-option org-show-siblings key)))
13326 ;; Show heading or entry text
13327 (if (and heading-p (not entry-p))
13328 (org-flag-heading nil) ; only show the heading
13329 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13330 (org-show-hidden-entry))) ; show entire entry
13331 (when following-p
13332 ;; Show next sibling, or heading below text
13333 (save-excursion
13334 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13335 (org-flag-heading nil))))
13336 (when siblings-p (org-show-siblings))
13337 (when hierarchy-p
13338 ;; show all higher headings, possibly with siblings
13339 (save-excursion
13340 (while (and (condition-case nil
13341 (progn (org-up-heading-all 1) t)
13342 (error nil))
13343 (not (bobp)))
13344 (org-flag-heading nil)
13345 (when siblings-p (org-show-siblings)))))
13346 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13348 (defvar org-reveal-start-hook nil
13349 "Hook run before revealing a location.")
13351 (defun org-reveal (&optional siblings)
13352 "Show current entry, hierarchy above it, and the following headline.
13353 This can be used to show a consistent set of context around locations
13354 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13355 not t for the search context.
13357 With optional argument SIBLINGS, on each level of the hierarchy all
13358 siblings are shown. This repairs the tree structure to what it would
13359 look like when opened with hierarchical calls to `org-cycle'.
13360 With double optional argument \\[universal-argument] \\[universal-argument], \
13361 go to the parent and show the
13362 entire tree."
13363 (interactive "P")
13364 (run-hooks 'org-reveal-start-hook)
13365 (let ((org-show-hierarchy-above t)
13366 (org-show-following-heading t)
13367 (org-show-siblings (if siblings t org-show-siblings)))
13368 (org-show-context nil))
13369 (when (equal siblings '(16))
13370 (save-excursion
13371 (when (org-up-heading-safe)
13372 (org-show-subtree)
13373 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13375 (defun org-highlight-new-match (beg end)
13376 "Highlight from BEG to END and mark the highlight is an occur headline."
13377 (let ((ov (make-overlay beg end)))
13378 (overlay-put ov 'face 'secondary-selection)
13379 (overlay-put ov 'org-type 'org-occur)
13380 (push ov org-occur-highlights)))
13382 (defun org-remove-occur-highlights (&optional beg end noremove)
13383 "Remove the occur highlights from the buffer.
13384 BEG and END are ignored. If NOREMOVE is nil, remove this function
13385 from the `before-change-functions' in the current buffer."
13386 (interactive)
13387 (unless org-inhibit-highlight-removal
13388 (mapc 'delete-overlay org-occur-highlights)
13389 (setq org-occur-highlights nil)
13390 (setq org-occur-parameters nil)
13391 (unless noremove
13392 (remove-hook 'before-change-functions
13393 'org-remove-occur-highlights 'local))))
13395 ;;;; Priorities
13397 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13398 "Regular expression matching the priority indicator.")
13400 (defvar org-remove-priority-next-time nil)
13402 (defun org-priority-up ()
13403 "Increase the priority of the current item."
13404 (interactive)
13405 (org-priority 'up))
13407 (defun org-priority-down ()
13408 "Decrease the priority of the current item."
13409 (interactive)
13410 (org-priority 'down))
13412 (defun org-priority (&optional action show)
13413 "Change the priority of an item.
13414 ACTION can be `set', `up', `down', or a character."
13415 (interactive "P")
13416 (if (equal action '(4))
13417 (org-show-priority)
13418 (unless org-enable-priority-commands
13419 (error "Priority commands are disabled"))
13420 (setq action (or action 'set))
13421 (let (current new news have remove)
13422 (save-excursion
13423 (org-back-to-heading t)
13424 (if (looking-at org-priority-regexp)
13425 (setq current (string-to-char (match-string 2))
13426 have t))
13427 (cond
13428 ((eq action 'remove)
13429 (setq remove t new ?\ ))
13430 ((or (eq action 'set)
13431 (if (featurep 'xemacs) (characterp action) (integerp action)))
13432 (if (not (eq action 'set))
13433 (setq new action)
13434 (message "Priority %c-%c, SPC to remove: "
13435 org-highest-priority org-lowest-priority)
13436 (save-match-data
13437 (setq new (read-char-exclusive))))
13438 (if (and (= (upcase org-highest-priority) org-highest-priority)
13439 (= (upcase org-lowest-priority) org-lowest-priority))
13440 (setq new (upcase new)))
13441 (cond ((equal new ?\ ) (setq remove t))
13442 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13443 (error "Priority must be between `%c' and `%c'"
13444 org-highest-priority org-lowest-priority))))
13445 ((eq action 'up)
13446 (setq new (if have
13447 (1- current) ; normal cycling
13448 ;; last priority was empty
13449 (if (eq last-command this-command)
13450 org-lowest-priority ; wrap around empty to lowest
13451 ;; default
13452 (if org-priority-start-cycle-with-default
13453 org-default-priority
13454 (1- org-default-priority))))))
13455 ((eq action 'down)
13456 (setq new (if have
13457 (1+ current) ; normal cycling
13458 ;; last priority was empty
13459 (if (eq last-command this-command)
13460 org-highest-priority ; wrap around empty to highest
13461 ;; default
13462 (if org-priority-start-cycle-with-default
13463 org-default-priority
13464 (1+ org-default-priority))))))
13465 (t (error "Invalid action")))
13466 (if (or (< (upcase new) org-highest-priority)
13467 (> (upcase new) org-lowest-priority))
13468 (if (and (memq action '(up down))
13469 (not have) (not (eq last-command this-command)))
13470 ;; `new' is from default priority
13471 (error
13472 "The default can not be set, see `org-default-priority' why")
13473 ;; normal cycling: `new' is beyond highest/lowest priority
13474 ;; and is wrapped around to the empty priority
13475 (setq remove t)))
13476 (setq news (format "%c" new))
13477 (if have
13478 (if remove
13479 (replace-match "" t t nil 1)
13480 (replace-match news t t nil 2))
13481 (if remove
13482 (error "No priority cookie found in line")
13483 (let ((case-fold-search nil))
13484 (looking-at org-todo-line-regexp))
13485 (if (match-end 2)
13486 (progn
13487 (goto-char (match-end 2))
13488 (insert " [#" news "]"))
13489 (goto-char (match-beginning 3))
13490 (insert "[#" news "] "))))
13491 (org-preserve-lc (org-set-tags nil 'align)))
13492 (if remove
13493 (message "Priority removed")
13494 (message "Priority of current item set to %s" news)))))
13496 (defun org-show-priority ()
13497 "Show the priority of the current item.
13498 This priority is composed of the main priority given with the [#A] cookies,
13499 and by additional input from the age of a schedules or deadline entry."
13500 (interactive)
13501 (let ((pri (if (eq major-mode 'org-agenda-mode)
13502 (org-get-at-bol 'priority)
13503 (save-excursion
13504 (save-match-data
13505 (beginning-of-line)
13506 (and (looking-at org-heading-regexp)
13507 (org-get-priority (match-string 0))))))))
13508 (message "Priority is %d" (if pri pri -1000))))
13510 (defun org-get-priority (s)
13511 "Find priority cookie and return priority."
13512 (save-match-data
13513 (if (functionp org-get-priority-function)
13514 (funcall org-get-priority-function)
13515 (if (not (string-match org-priority-regexp s))
13516 (* 1000 (- org-lowest-priority org-default-priority))
13517 (* 1000 (- org-lowest-priority
13518 (string-to-char (match-string 2 s))))))))
13520 ;;;; Tags
13522 (defvar org-agenda-archives-mode)
13523 (defvar org-map-continue-from nil
13524 "Position from where mapping should continue.
13525 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13527 (defvar org-scanner-tags nil
13528 "The current tag list while the tags scanner is running.")
13529 (defvar org-trust-scanner-tags nil
13530 "Should `org-get-tags-at' use the tags for the scanner.
13531 This is for internal dynamical scoping only.
13532 When this is non-nil, the function `org-get-tags-at' will return the value
13533 of `org-scanner-tags' instead of building the list by itself. This
13534 can lead to large speed-ups when the tags scanner is used in a file with
13535 many entries, and when the list of tags is retrieved, for example to
13536 obtain a list of properties. Building the tags list for each entry in such
13537 a file becomes an N^2 operation - but with this variable set, it scales
13538 as N.")
13540 (defun org-scan-tags (action matcher todo-only &optional start-level)
13541 "Sca headline tags with inheritance and produce output ACTION.
13543 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13544 or `agenda' to produce an entry list for an agenda view. It can also be
13545 a Lisp form or a function that should be called at each matched headline, in
13546 this case the return value is a list of all return values from these calls.
13548 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13549 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13550 only lines with a not-done TODO keyword are included in the output.
13551 This should be the same variable that was scoped into
13552 and set by `org-make-tags-matcher' when it constructed MATCHER.
13554 START-LEVEL can be a string with asterisks, reducing the scope to
13555 headlines matching this string."
13556 (require 'org-agenda)
13557 (let* ((re (concat "^"
13558 (if start-level
13559 ;; Get the correct level to match
13560 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13561 org-outline-regexp)
13562 " *\\(\\<\\("
13563 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13564 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13565 (props (list 'face 'default
13566 'done-face 'org-agenda-done
13567 'undone-face 'default
13568 'mouse-face 'highlight
13569 'org-not-done-regexp org-not-done-regexp
13570 'org-todo-regexp org-todo-regexp
13571 'org-complex-heading-regexp org-complex-heading-regexp
13572 'help-echo
13573 (format "mouse-2 or RET jump to org file %s"
13574 (abbreviate-file-name
13575 (or (buffer-file-name (buffer-base-buffer))
13576 (buffer-name (buffer-base-buffer)))))))
13577 (case-fold-search nil)
13578 (org-map-continue-from nil)
13579 lspos tags tags-list
13580 (tags-alist (list (cons 0 org-file-tags)))
13581 (llast 0) rtn rtn1 level category i txt
13582 todo marker entry priority)
13583 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13584 (setq action (list 'lambda nil action)))
13585 (save-excursion
13586 (goto-char (point-min))
13587 (when (eq action 'sparse-tree)
13588 (org-overview)
13589 (org-remove-occur-highlights))
13590 (while (re-search-forward re nil t)
13591 (setq org-map-continue-from nil)
13592 (catch :skip
13593 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13594 tags (if (match-end 4) (org-match-string-no-properties 4)))
13595 (goto-char (setq lspos (match-beginning 0)))
13596 (setq level (org-reduced-level (org-outline-level))
13597 category (org-get-category))
13598 (setq i llast llast level)
13599 ;; remove tag lists from same and sublevels
13600 (while (>= i level)
13601 (when (setq entry (assoc i tags-alist))
13602 (setq tags-alist (delete entry tags-alist)))
13603 (setq i (1- i)))
13604 ;; add the next tags
13605 (when tags
13606 (setq tags (org-split-string tags ":")
13607 tags-alist
13608 (cons (cons level tags) tags-alist)))
13609 ;; compile tags for current headline
13610 (setq tags-list
13611 (if org-use-tag-inheritance
13612 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13613 tags)
13614 org-scanner-tags tags-list)
13615 (when org-use-tag-inheritance
13616 (setcdr (car tags-alist)
13617 (mapcar (lambda (x)
13618 (setq x (copy-sequence x))
13619 (org-add-prop-inherited x))
13620 (cdar tags-alist))))
13621 (when (and tags org-use-tag-inheritance
13622 (or (not (eq t org-use-tag-inheritance))
13623 org-tags-exclude-from-inheritance))
13624 ;; selective inheritance, remove uninherited ones
13625 (setcdr (car tags-alist)
13626 (org-remove-uninherited-tags (cdar tags-alist))))
13627 (when (and
13629 ;; eval matcher only when the todo condition is OK
13630 (and (or (not todo-only) (member todo org-not-done-keywords))
13631 (let ((case-fold-search t) (org-trust-scanner-tags t))
13632 (eval matcher)))
13634 ;; Call the skipper, but return t if it does not skip,
13635 ;; so that the `and' form continues evaluating
13636 (progn
13637 (unless (eq action 'sparse-tree) (org-agenda-skip))
13640 ;; Check if timestamps are deselecting this entry
13641 (or (not todo-only)
13642 (and (member todo org-not-done-keywords)
13643 (or (not org-agenda-tags-todo-honor-ignore-options)
13644 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13646 ;; select this headline
13647 (cond
13648 ((eq action 'sparse-tree)
13649 (and org-highlight-sparse-tree-matches
13650 (org-get-heading) (match-end 0)
13651 (org-highlight-new-match
13652 (match-beginning 1) (match-end 1)))
13653 (org-show-context 'tags-tree))
13654 ((eq action 'agenda)
13655 (setq txt (org-agenda-format-item
13657 (concat
13658 (if (eq org-tags-match-list-sublevels 'indented)
13659 (make-string (1- level) ?.) "")
13660 (org-get-heading))
13661 level category
13662 tags-list)
13663 priority (org-get-priority txt))
13664 (goto-char lspos)
13665 (setq marker (org-agenda-new-marker))
13666 (org-add-props txt props
13667 'org-marker marker 'org-hd-marker marker 'org-category category
13668 'todo-state todo
13669 'priority priority 'type "tagsmatch")
13670 (push txt rtn))
13671 ((functionp action)
13672 (setq org-map-continue-from nil)
13673 (save-excursion
13674 (setq rtn1 (funcall action))
13675 (push rtn1 rtn)))
13676 (t (error "Invalid action")))
13678 ;; if we are to skip sublevels, jump to end of subtree
13679 (unless org-tags-match-list-sublevels
13680 (org-end-of-subtree t)
13681 (backward-char 1))))
13682 ;; Get the correct position from where to continue
13683 (if org-map-continue-from
13684 (goto-char org-map-continue-from)
13685 (and (= (point) lspos) (end-of-line 1)))))
13686 (when (and (eq action 'sparse-tree)
13687 (not org-sparse-tree-open-archived-trees))
13688 (org-hide-archived-subtrees (point-min) (point-max)))
13689 (nreverse rtn)))
13691 (defun org-remove-uninherited-tags (tags)
13692 "Remove all tags that are not inherited from the list TAGS."
13693 (cond
13694 ((eq org-use-tag-inheritance t)
13695 (if org-tags-exclude-from-inheritance
13696 (org-delete-all org-tags-exclude-from-inheritance tags)
13697 tags))
13698 ((not org-use-tag-inheritance) nil)
13699 ((stringp org-use-tag-inheritance)
13700 (delq nil (mapcar
13701 (lambda (x)
13702 (if (and (string-match org-use-tag-inheritance x)
13703 (not (member x org-tags-exclude-from-inheritance)))
13704 x nil))
13705 tags)))
13706 ((listp org-use-tag-inheritance)
13707 (delq nil (mapcar
13708 (lambda (x)
13709 (if (member x org-use-tag-inheritance) x nil))
13710 tags)))))
13712 (defun org-match-sparse-tree (&optional todo-only match)
13713 "Create a sparse tree according to tags string MATCH.
13714 MATCH can contain positive and negative selection of tags, like
13715 \"+WORK+URGENT-WITHBOSS\".
13716 If optional argument TODO-ONLY is non-nil, only select lines that are
13717 also TODO lines."
13718 (interactive "P")
13719 (org-agenda-prepare-buffers (list (current-buffer)))
13720 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13722 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13724 (defvar org-cached-props nil)
13725 (defun org-cached-entry-get (pom property)
13726 (if (or (eq t org-use-property-inheritance)
13727 (and (stringp org-use-property-inheritance)
13728 (string-match org-use-property-inheritance property))
13729 (and (listp org-use-property-inheritance)
13730 (member property org-use-property-inheritance)))
13731 ;; Caching is not possible, check it directly
13732 (org-entry-get pom property 'inherit)
13733 ;; Get all properties, so that we can do complicated checks easily
13734 (cdr (assoc property (or org-cached-props
13735 (setq org-cached-props
13736 (org-entry-properties pom)))))))
13738 (defun org-global-tags-completion-table (&optional files)
13739 "Return the list of all tags in all agenda buffer/files.
13740 Optional FILES argument is a list of files which can be used
13741 instead of the agenda files."
13742 (save-excursion
13743 (org-uniquify
13744 (delq nil
13745 (apply 'append
13746 (mapcar
13747 (lambda (file)
13748 (set-buffer (find-file-noselect file))
13749 (append (org-get-buffer-tags)
13750 (mapcar (lambda (x) (if (stringp (car-safe x))
13751 (list (car-safe x)) nil))
13752 org-tag-alist)))
13753 (if (and files (car files))
13754 files
13755 (org-agenda-files))))))))
13757 (defun org-make-tags-matcher (match)
13758 "Create the TAGS/TODO matcher form for the selection string MATCH.
13760 The variable `todo-only' is scoped dynamically into this function.
13761 It will be set to t if the matcher restricts matching to TODO entries,
13762 otherwise will not be touched.
13764 Returns a cons of the selection string MATCH and the constructed
13765 lisp form implementing the matcher. The matcher is to be evaluated
13766 at an Org entry, with point on the headline, and returns t if the
13767 entry matches the selection string MATCH. The returned lisp form
13768 references two variables with information about the entry, which
13769 must be bound around the form's evaluation: todo, the TODO keyword
13770 at the entry (or nil of none); and tags-list, the list of all tags
13771 at the entry including inherited ones. Additionally, the category
13772 of the entry (if any) must be specified as the text property
13773 'org-category on the headline.
13775 See also `org-scan-tags'.
13777 (declare (special todo-only))
13778 (unless (boundp 'todo-only)
13779 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13780 (unless match
13781 ;; Get a new match request, with completion
13782 (let ((org-last-tags-completion-table
13783 (org-global-tags-completion-table)))
13784 (setq match (org-completing-read-no-i
13785 "Match: " 'org-tags-completion-function nil nil nil
13786 'org-tags-history))))
13788 ;; Parse the string and create a lisp form
13789 (let ((match0 match)
13790 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13791 minus tag mm
13792 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13793 orterms term orlist re-p str-p level-p level-op time-p
13794 prop-p pn pv po gv rest)
13795 (if (string-match "/+" match)
13796 ;; match contains also a todo-matching request
13797 (progn
13798 (setq tagsmatch (substring match 0 (match-beginning 0))
13799 todomatch (substring match (match-end 0)))
13800 (if (string-match "^!" todomatch)
13801 (setq todo-only t todomatch (substring todomatch 1)))
13802 (if (string-match "^\\s-*$" todomatch)
13803 (setq todomatch nil)))
13804 ;; only matching tags
13805 (setq tagsmatch match todomatch nil))
13807 ;; Make the tags matcher
13808 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13809 (setq tagsmatcher t)
13810 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13811 (while (setq term (pop orterms))
13812 (while (and (equal (substring term -1) "\\") orterms)
13813 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13814 (while (string-match re term)
13815 (setq rest (substring term (match-end 0))
13816 minus (and (match-end 1)
13817 (equal (match-string 1 term) "-"))
13818 tag (save-match-data (replace-regexp-in-string
13819 "\\\\-" "-"
13820 (match-string 2 term)))
13821 re-p (equal (string-to-char tag) ?{)
13822 level-p (match-end 4)
13823 prop-p (match-end 5)
13824 mm (cond
13825 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13826 (level-p
13827 (setq level-op (org-op-to-function (match-string 3 term)))
13828 `(,level-op level ,(string-to-number
13829 (match-string 4 term))))
13830 (prop-p
13831 (setq pn (match-string 5 term)
13832 po (match-string 6 term)
13833 pv (match-string 7 term)
13834 re-p (equal (string-to-char pv) ?{)
13835 str-p (equal (string-to-char pv) ?\")
13836 time-p (save-match-data
13837 (string-match "^\"[[<].*[]>]\"$" pv))
13838 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13839 (if time-p (setq pv (org-matcher-time pv)))
13840 (setq po (org-op-to-function po (if time-p 'time str-p)))
13841 (cond
13842 ((equal pn "CATEGORY")
13843 (setq gv '(get-text-property (point) 'org-category)))
13844 ((equal pn "TODO")
13845 (setq gv 'todo))
13847 (setq gv `(org-cached-entry-get nil ,pn))))
13848 (if re-p
13849 (if (eq po 'org<>)
13850 `(not (string-match ,pv (or ,gv "")))
13851 `(string-match ,pv (or ,gv "")))
13852 (if str-p
13853 `(,po (or ,gv "") ,pv)
13854 `(,po (string-to-number (or ,gv ""))
13855 ,(string-to-number pv) ))))
13856 (t `(member ,tag tags-list)))
13857 mm (if minus (list 'not mm) mm)
13858 term rest)
13859 (push mm tagsmatcher))
13860 (push (if (> (length tagsmatcher) 1)
13861 (cons 'and tagsmatcher)
13862 (car tagsmatcher))
13863 orlist)
13864 (setq tagsmatcher nil))
13865 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13866 (setq tagsmatcher
13867 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13868 ;; Make the todo matcher
13869 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13870 (setq todomatcher t)
13871 (setq orterms (org-split-string todomatch "|") orlist nil)
13872 (while (setq term (pop orterms))
13873 (while (string-match re term)
13874 (setq minus (and (match-end 1)
13875 (equal (match-string 1 term) "-"))
13876 kwd (match-string 2 term)
13877 re-p (equal (string-to-char kwd) ?{)
13878 term (substring term (match-end 0))
13879 mm (if re-p
13880 `(string-match ,(substring kwd 1 -1) todo)
13881 (list 'equal 'todo kwd))
13882 mm (if minus (list 'not mm) mm))
13883 (push mm todomatcher))
13884 (push (if (> (length todomatcher) 1)
13885 (cons 'and todomatcher)
13886 (car todomatcher))
13887 orlist)
13888 (setq todomatcher nil))
13889 (setq todomatcher (if (> (length orlist) 1)
13890 (cons 'or orlist) (car orlist))))
13892 ;; Return the string and lisp forms of the matcher
13893 (setq matcher (if todomatcher
13894 (list 'and tagsmatcher todomatcher)
13895 tagsmatcher))
13896 (when todo-only
13897 (setq matcher (list 'and '(member todo org-not-done-keywords)
13898 matcher)))
13899 (cons match0 matcher)))
13901 (defun org-op-to-function (op &optional stringp)
13902 "Turn an operator into the appropriate function."
13903 (setq op
13904 (cond
13905 ((equal op "<" ) '(< string< org-time<))
13906 ((equal op ">" ) '(> org-string> org-time>))
13907 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13908 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13909 ((member op '("=" "==")) '(= string= org-time=))
13910 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13911 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13913 (defun org<> (a b) (not (= a b)))
13914 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13915 (defun org-string>= (a b) (not (string< a b)))
13916 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13917 (defun org-string<> (a b) (not (string= a b)))
13918 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13919 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13920 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13921 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13922 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13923 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13924 (defun org-2ft (s)
13925 "Convert S to a floating point time.
13926 If S is already a number, just return it. If it is a string, parse
13927 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13928 (cond
13929 ((numberp s) s)
13930 ((stringp s)
13931 (condition-case nil
13932 (float-time (apply 'encode-time (org-parse-time-string s)))
13933 (error 0.)))
13934 (t 0.)))
13936 (defun org-time-today ()
13937 "Time in seconds today at 0:00.
13938 Returns the float number of seconds since the beginning of the
13939 epoch to the beginning of today (00:00)."
13940 (float-time (apply 'encode-time
13941 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13943 (defun org-matcher-time (s)
13944 "Interpret a time comparison value."
13945 (save-match-data
13946 (cond
13947 ((string= s "<now>") (float-time))
13948 ((string= s "<today>") (org-time-today))
13949 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13950 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13951 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13952 (+ (org-time-today)
13953 (* (string-to-number (match-string 1 s))
13954 (cdr (assoc (match-string 2 s)
13955 '(("d" . 86400.0) ("w" . 604800.0)
13956 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13957 (t (org-2ft s)))))
13959 (defun org-match-any-p (re list)
13960 "Does re match any element of list?"
13961 (setq list (mapcar (lambda (x) (string-match re x)) list))
13962 (delq nil list))
13964 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13965 (defvar org-tags-overlay (make-overlay 1 1))
13966 (org-detach-overlay org-tags-overlay)
13968 (defun org-get-local-tags-at (&optional pos)
13969 "Get a list of tags defined in the current headline."
13970 (org-get-tags-at pos 'local))
13972 (defun org-get-local-tags ()
13973 "Get a list of tags defined in the current headline."
13974 (org-get-tags-at nil 'local))
13976 (defun org-get-tags-at (&optional pos local)
13977 "Get a list of all headline tags applicable at POS.
13978 POS defaults to point. If tags are inherited, the list contains
13979 the targets in the same sequence as the headlines appear, i.e.
13980 the tags of the current headline come last.
13981 When LOCAL is non-nil, only return tags from the current headline,
13982 ignore inherited ones."
13983 (interactive)
13984 (if (and org-trust-scanner-tags
13985 (or (not pos) (equal pos (point)))
13986 (not local))
13987 org-scanner-tags
13988 (let (tags ltags lastpos parent)
13989 (save-excursion
13990 (save-restriction
13991 (widen)
13992 (goto-char (or pos (point)))
13993 (save-match-data
13994 (catch 'done
13995 (condition-case nil
13996 (progn
13997 (org-back-to-heading t)
13998 (while (not (equal lastpos (point)))
13999 (setq lastpos (point))
14000 (when (looking-at
14001 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14002 (setq ltags (org-split-string
14003 (org-match-string-no-properties 1) ":"))
14004 (when parent
14005 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14006 (setq tags (append
14007 (if parent
14008 (org-remove-uninherited-tags ltags)
14009 ltags)
14010 tags)))
14011 (or org-use-tag-inheritance (throw 'done t))
14012 (if local (throw 'done t))
14013 (or (org-up-heading-safe) (error nil))
14014 (setq parent t)))
14015 (error nil)))))
14016 (if local
14017 tags
14018 (reverse (delete-dups
14019 (reverse (append
14020 (org-remove-uninherited-tags
14021 org-file-tags) tags)))))))))
14023 (defun org-add-prop-inherited (s)
14024 (add-text-properties 0 (length s) '(inherited t) s)
14027 (defun org-toggle-tag (tag &optional onoff)
14028 "Toggle the tag TAG for the current line.
14029 If ONOFF is `on' or `off', don't toggle but set to this state."
14030 (let (res current)
14031 (save-excursion
14032 (org-back-to-heading t)
14033 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14034 (point-at-eol) t)
14035 (progn
14036 (setq current (match-string 1))
14037 (replace-match ""))
14038 (setq current ""))
14039 (setq current (nreverse (org-split-string current ":")))
14040 (cond
14041 ((eq onoff 'on)
14042 (setq res t)
14043 (or (member tag current) (push tag current)))
14044 ((eq onoff 'off)
14045 (or (not (member tag current)) (setq current (delete tag current))))
14046 (t (if (member tag current)
14047 (setq current (delete tag current))
14048 (setq res t)
14049 (push tag current))))
14050 (end-of-line 1)
14051 (if current
14052 (progn
14053 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14054 (org-set-tags nil t))
14055 (delete-horizontal-space))
14056 (run-hooks 'org-after-tags-change-hook))
14057 res))
14059 (defun org-align-tags-here (to-col)
14060 ;; Assumes that this is a headline
14061 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14062 (beginning-of-line 1)
14063 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14064 (< pos (match-beginning 2)))
14065 (progn
14066 (setq tags-l (- (match-end 2) (match-beginning 2)))
14067 (goto-char (match-beginning 1))
14068 (insert " ")
14069 (delete-region (point) (1+ (match-beginning 2)))
14070 (setq ncol (max (current-column)
14071 (1+ col)
14072 (if (> to-col 0)
14073 to-col
14074 (- (abs to-col) tags-l))))
14075 (setq p (point))
14076 (insert (make-string (- ncol (current-column)) ?\ ))
14077 (setq ncol (current-column))
14078 (when indent-tabs-mode (tabify p (point-at-eol)))
14079 (org-move-to-column (min ncol col) t))
14080 (goto-char pos))))
14082 (defun org-set-tags-command (&optional arg just-align)
14083 "Call the set-tags command for the current entry."
14084 (interactive "P")
14085 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14086 (org-set-tags arg just-align)
14087 (save-excursion
14088 (unless (and (org-region-active-p)
14089 org-loop-over-headlines-in-active-region)
14090 (org-back-to-heading t))
14091 (org-set-tags arg just-align))))
14093 (defun org-set-tags-to (data)
14094 "Set the tags of the current entry to DATA, replacing the current tags.
14095 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14096 If DATA is nil or the empty string, any tags will be removed."
14097 (interactive "sTags: ")
14098 (setq data
14099 (cond
14100 ((eq data nil) "")
14101 ((equal data "") "")
14102 ((stringp data)
14103 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14104 ":"))
14105 ((listp data)
14106 (concat ":" (mapconcat 'identity data ":") ":"))))
14107 (when data
14108 (save-excursion
14109 (org-back-to-heading t)
14110 (when (looking-at org-complex-heading-regexp)
14111 (if (match-end 5)
14112 (progn
14113 (goto-char (match-beginning 5))
14114 (insert data)
14115 (delete-region (point) (point-at-eol))
14116 (org-set-tags nil 'align))
14117 (goto-char (point-at-eol))
14118 (insert " " data)
14119 (org-set-tags nil 'align)))
14120 (beginning-of-line 1)
14121 (if (looking-at ".*?\\([ \t]+\\)$")
14122 (delete-region (match-beginning 1) (match-end 1))))))
14124 (defun org-align-all-tags ()
14125 "Align the tags i all headings."
14126 (interactive)
14127 (save-excursion
14128 (or (ignore-errors (org-back-to-heading t))
14129 (outline-next-heading))
14130 (if (org-at-heading-p)
14131 (org-set-tags t)
14132 (message "No headings"))))
14134 (defvar org-indent-indentation-per-level)
14135 (defun org-set-tags (&optional arg just-align)
14136 "Set the tags for the current headline.
14137 With prefix ARG, realign all tags in headings in the current buffer."
14138 (interactive "P")
14139 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14140 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14141 'region-start-level 'region))
14142 org-loop-over-headlines-in-active-region)
14143 (org-map-entries
14144 ;; We don't use ARG and JUST-ALIGN here these args are not
14145 ;; useful when looping over headlines
14146 `(org-set-tags)
14147 org-loop-over-headlines-in-active-region
14148 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14149 (let* ((re org-outline-regexp-bol)
14150 (current (unless arg (org-get-tags-string)))
14151 (col (current-column))
14152 (org-setting-tags t)
14153 table current-tags inherited-tags ; computed below when needed
14154 tags p0 c0 c1 rpl di tc level)
14155 (if arg
14156 (save-excursion
14157 (goto-char (point-min))
14158 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14159 (while (re-search-forward re nil t)
14160 (org-set-tags nil t)
14161 (end-of-line 1)))
14162 (message "All tags realigned to column %d" org-tags-column))
14163 (if just-align
14164 (setq tags current)
14165 ;; Get a new set of tags from the user
14166 (save-excursion
14167 (setq table (append org-tag-persistent-alist
14168 (or org-tag-alist (org-get-buffer-tags))
14169 (and
14170 org-complete-tags-always-offer-all-agenda-tags
14171 (org-global-tags-completion-table
14172 (org-agenda-files))))
14173 org-last-tags-completion-table table
14174 current-tags (org-split-string current ":")
14175 inherited-tags (nreverse
14176 (nthcdr (length current-tags)
14177 (nreverse (org-get-tags-at))))
14178 tags
14179 (if (or (eq t org-use-fast-tag-selection)
14180 (and org-use-fast-tag-selection
14181 (delq nil (mapcar 'cdr table))))
14182 (org-fast-tag-selection
14183 current-tags inherited-tags table
14184 (if org-fast-tag-selection-include-todo
14185 org-todo-key-alist))
14186 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14187 (org-trim
14188 (org-icompleting-read "Tags: "
14189 'org-tags-completion-function
14190 nil nil current 'org-tags-history))))))
14191 (while (string-match "[-+&]+" tags)
14192 ;; No boolean logic, just a list
14193 (setq tags (replace-match ":" t t tags))))
14195 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14197 (if org-tags-sort-function
14198 (setq tags (mapconcat 'identity
14199 (sort (org-split-string
14200 tags (org-re "[^[:alnum:]_@#%]+"))
14201 org-tags-sort-function) ":")))
14203 (if (string-match "\\`[\t ]*\\'" tags)
14204 (setq tags "")
14205 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14206 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14208 ;; Insert new tags at the correct column
14209 (beginning-of-line 1)
14210 (setq level (or (and (looking-at org-outline-regexp)
14211 (- (match-end 0) (point) 1))
14213 (cond
14214 ((and (equal current "") (equal tags "")))
14215 ((re-search-forward
14216 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14217 (point-at-eol) t)
14218 (if (equal tags "")
14219 (setq rpl "")
14220 (goto-char (match-beginning 0))
14221 (setq c0 (current-column)
14222 ;; compute offset for the case of org-indent-mode active
14223 di (if org-indent-mode
14224 (* (1- org-indent-indentation-per-level) (1- level))
14226 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14227 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14228 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14229 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14230 (replace-match rpl t t)
14231 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14232 tags)
14233 (t (error "Tags alignment failed")))
14234 (org-move-to-column col)
14235 (unless just-align
14236 (run-hooks 'org-after-tags-change-hook))))))
14238 (defun org-change-tag-in-region (beg end tag off)
14239 "Add or remove TAG for each entry in the region.
14240 This works in the agenda, and also in an org-mode buffer."
14241 (interactive
14242 (list (region-beginning) (region-end)
14243 (let ((org-last-tags-completion-table
14244 (if (derived-mode-p 'org-mode)
14245 (org-get-buffer-tags)
14246 (org-global-tags-completion-table))))
14247 (org-icompleting-read
14248 "Tag: " 'org-tags-completion-function nil nil nil
14249 'org-tags-history))
14250 (progn
14251 (message "[s]et or [r]emove? ")
14252 (equal (read-char-exclusive) ?r))))
14253 (if (fboundp 'deactivate-mark) (deactivate-mark))
14254 (let ((agendap (equal major-mode 'org-agenda-mode))
14255 l1 l2 m buf pos newhead (cnt 0))
14256 (goto-char end)
14257 (setq l2 (1- (org-current-line)))
14258 (goto-char beg)
14259 (setq l1 (org-current-line))
14260 (loop for l from l1 to l2 do
14261 (org-goto-line l)
14262 (setq m (get-text-property (point) 'org-hd-marker))
14263 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14264 (and agendap m))
14265 (setq buf (if agendap (marker-buffer m) (current-buffer))
14266 pos (if agendap m (point)))
14267 (with-current-buffer buf
14268 (save-excursion
14269 (save-restriction
14270 (goto-char pos)
14271 (setq cnt (1+ cnt))
14272 (org-toggle-tag tag (if off 'off 'on))
14273 (setq newhead (org-get-heading)))))
14274 (and agendap (org-agenda-change-all-lines newhead m))))
14275 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14277 (defun org-tags-completion-function (string predicate &optional flag)
14278 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14279 (confirm (lambda (x) (stringp (car x)))))
14280 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14281 (setq s1 (match-string 1 string)
14282 s2 (match-string 2 string))
14283 (setq s1 "" s2 string))
14284 (cond
14285 ((eq flag nil)
14286 ;; try completion
14287 (setq rtn (try-completion s2 ctable confirm))
14288 (if (stringp rtn)
14289 (setq rtn
14290 (concat s1 s2 (substring rtn (length s2))
14291 (if (and org-add-colon-after-tag-completion
14292 (assoc rtn ctable))
14293 ":" ""))))
14294 rtn)
14295 ((eq flag t)
14296 ;; all-completions
14297 (all-completions s2 ctable confirm)
14299 ((eq flag 'lambda)
14300 ;; exact match?
14301 (assoc s2 ctable)))
14304 (defun org-fast-tag-insert (kwd tags face &optional end)
14305 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14306 (insert (format "%-12s" (concat kwd ":"))
14307 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14308 (or end "")))
14310 (defun org-fast-tag-show-exit (flag)
14311 (save-excursion
14312 (org-goto-line 3)
14313 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14314 (replace-match ""))
14315 (when flag
14316 (end-of-line 1)
14317 (org-move-to-column (- (window-width) 19) t)
14318 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14320 (defun org-set-current-tags-overlay (current prefix)
14321 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14322 (if (featurep 'xemacs)
14323 (org-overlay-display org-tags-overlay (concat prefix s)
14324 'secondary-selection)
14325 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14326 (org-overlay-display org-tags-overlay (concat prefix s)))))
14328 (defvar org-last-tag-selection-key nil)
14329 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14330 "Fast tag selection with single keys.
14331 CURRENT is the current list of tags in the headline, INHERITED is the
14332 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14333 possibly with grouping information. TODO-TABLE is a similar table with
14334 TODO keywords, should these have keys assigned to them.
14335 If the keys are nil, a-z are automatically assigned.
14336 Returns the new tags string, or nil to not change the current settings."
14337 (let* ((fulltable (append table todo-table))
14338 (maxlen (apply 'max (mapcar
14339 (lambda (x)
14340 (if (stringp (car x)) (string-width (car x)) 0))
14341 fulltable)))
14342 (buf (current-buffer))
14343 (expert (eq org-fast-tag-selection-single-key 'expert))
14344 (buffer-tags nil)
14345 (fwidth (+ maxlen 3 1 3))
14346 (ncol (/ (- (window-width) 4) fwidth))
14347 (i-face 'org-done)
14348 (c-face 'org-todo)
14349 tg cnt e c char c1 c2 ntable tbl rtn
14350 ov-start ov-end ov-prefix
14351 (exit-after-next org-fast-tag-selection-single-key)
14352 (done-keywords org-done-keywords)
14353 groups ingroup)
14354 (save-excursion
14355 (beginning-of-line 1)
14356 (if (looking-at
14357 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14358 (setq ov-start (match-beginning 1)
14359 ov-end (match-end 1)
14360 ov-prefix "")
14361 (setq ov-start (1- (point-at-eol))
14362 ov-end (1+ ov-start))
14363 (skip-chars-forward "^\n\r")
14364 (setq ov-prefix
14365 (concat
14366 (buffer-substring (1- (point)) (point))
14367 (if (> (current-column) org-tags-column)
14369 (make-string (- org-tags-column (current-column)) ?\ ))))))
14370 (move-overlay org-tags-overlay ov-start ov-end)
14371 (save-window-excursion
14372 (if expert
14373 (set-buffer (get-buffer-create " *Org tags*"))
14374 (delete-other-windows)
14375 (split-window-vertically)
14376 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14377 (erase-buffer)
14378 (org-set-local 'org-done-keywords done-keywords)
14379 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14380 (org-fast-tag-insert "Current" current c-face "\n\n")
14381 (org-fast-tag-show-exit exit-after-next)
14382 (org-set-current-tags-overlay current ov-prefix)
14383 (setq tbl fulltable char ?a cnt 0)
14384 (while (setq e (pop tbl))
14385 (cond
14386 ((equal (car e) :startgroup)
14387 (push '() groups) (setq ingroup t)
14388 (when (not (= cnt 0))
14389 (setq cnt 0)
14390 (insert "\n"))
14391 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14392 ((equal (car e) :endgroup)
14393 (setq ingroup nil cnt 0)
14394 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14395 ((equal e '(:newline))
14396 (when (not (= cnt 0))
14397 (setq cnt 0)
14398 (insert "\n")
14399 (setq e (car tbl))
14400 (while (equal (car tbl) '(:newline))
14401 (insert "\n")
14402 (setq tbl (cdr tbl)))))
14404 (setq tg (copy-sequence (car e)) c2 nil)
14405 (if (cdr e)
14406 (setq c (cdr e))
14407 ;; automatically assign a character.
14408 (setq c1 (string-to-char
14409 (downcase (substring
14410 tg (if (= (string-to-char tg) ?@) 1 0)))))
14411 (if (or (rassoc c1 ntable) (rassoc c1 table))
14412 (while (or (rassoc char ntable) (rassoc char table))
14413 (setq char (1+ char)))
14414 (setq c2 c1))
14415 (setq c (or c2 char)))
14416 (if ingroup (push tg (car groups)))
14417 (setq tg (org-add-props tg nil 'face
14418 (cond
14419 ((not (assoc tg table))
14420 (org-get-todo-face tg))
14421 ((member tg current) c-face)
14422 ((member tg inherited) i-face))))
14423 (if (and (= cnt 0) (not ingroup)) (insert " "))
14424 (insert "[" c "] " tg (make-string
14425 (- fwidth 4 (length tg)) ?\ ))
14426 (push (cons tg c) ntable)
14427 (when (= (setq cnt (1+ cnt)) ncol)
14428 (insert "\n")
14429 (if ingroup (insert " "))
14430 (setq cnt 0)))))
14431 (setq ntable (nreverse ntable))
14432 (insert "\n")
14433 (goto-char (point-min))
14434 (if (not expert) (org-fit-window-to-buffer))
14435 (setq rtn
14436 (catch 'exit
14437 (while t
14438 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14439 (if (not groups) "no " "")
14440 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14441 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14442 (setq org-last-tag-selection-key c)
14443 (cond
14444 ((= c ?\r) (throw 'exit t))
14445 ((= c ?!)
14446 (setq groups (not groups))
14447 (goto-char (point-min))
14448 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14449 ((= c ?\C-c)
14450 (if (not expert)
14451 (org-fast-tag-show-exit
14452 (setq exit-after-next (not exit-after-next)))
14453 (setq expert nil)
14454 (delete-other-windows)
14455 (set-window-buffer (split-window-vertically) " *Org tags*")
14456 (org-switch-to-buffer-other-window " *Org tags*")
14457 (org-fit-window-to-buffer)))
14458 ((or (= c ?\C-g)
14459 (and (= c ?q) (not (rassoc c ntable))))
14460 (org-detach-overlay org-tags-overlay)
14461 (setq quit-flag t))
14462 ((= c ?\ )
14463 (setq current nil)
14464 (if exit-after-next (setq exit-after-next 'now)))
14465 ((= c ?\t)
14466 (condition-case nil
14467 (setq tg (org-icompleting-read
14468 "Tag: "
14469 (or buffer-tags
14470 (with-current-buffer buf
14471 (org-get-buffer-tags)))))
14472 (quit (setq tg "")))
14473 (when (string-match "\\S-" tg)
14474 (add-to-list 'buffer-tags (list tg))
14475 (if (member tg current)
14476 (setq current (delete tg current))
14477 (push tg current)))
14478 (if exit-after-next (setq exit-after-next 'now)))
14479 ((setq e (rassoc c todo-table) tg (car e))
14480 (with-current-buffer buf
14481 (save-excursion (org-todo tg)))
14482 (if exit-after-next (setq exit-after-next 'now)))
14483 ((setq e (rassoc c ntable) tg (car e))
14484 (if (member tg current)
14485 (setq current (delete tg current))
14486 (loop for g in groups do
14487 (if (member tg g)
14488 (mapc (lambda (x)
14489 (setq current (delete x current)))
14490 g)))
14491 (push tg current))
14492 (if exit-after-next (setq exit-after-next 'now))))
14494 ;; Create a sorted list
14495 (setq current
14496 (sort current
14497 (lambda (a b)
14498 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14499 (if (eq exit-after-next 'now) (throw 'exit t))
14500 (goto-char (point-min))
14501 (beginning-of-line 2)
14502 (delete-region (point) (point-at-eol))
14503 (org-fast-tag-insert "Current" current c-face)
14504 (org-set-current-tags-overlay current ov-prefix)
14505 (while (re-search-forward
14506 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14507 (setq tg (match-string 1))
14508 (add-text-properties
14509 (match-beginning 1) (match-end 1)
14510 (list 'face
14511 (cond
14512 ((member tg current) c-face)
14513 ((member tg inherited) i-face)
14514 (t (get-text-property (match-beginning 1) 'face))))))
14515 (goto-char (point-min)))))
14516 (org-detach-overlay org-tags-overlay)
14517 (if rtn
14518 (mapconcat 'identity current ":")
14519 nil))))
14521 (defun org-get-tags-string ()
14522 "Get the TAGS string in the current headline."
14523 (unless (org-at-heading-p t)
14524 (error "Not on a heading"))
14525 (save-excursion
14526 (beginning-of-line 1)
14527 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14528 (org-match-string-no-properties 1)
14529 "")))
14531 (defun org-get-tags ()
14532 "Get the list of tags specified in the current headline."
14533 (org-split-string (org-get-tags-string) ":"))
14535 (defun org-get-buffer-tags ()
14536 "Get a table of all tags used in the buffer, for completion."
14537 (let (tags)
14538 (save-excursion
14539 (goto-char (point-min))
14540 (while (re-search-forward
14541 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14542 (when (equal (char-after (point-at-bol 0)) ?*)
14543 (mapc (lambda (x) (add-to-list 'tags x))
14544 (org-split-string (org-match-string-no-properties 1) ":")))))
14545 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14546 (mapcar 'list tags)))
14548 ;;;; The mapping API
14550 (defun org-map-entries (func &optional match scope &rest skip)
14551 "Call FUNC at each headline selected by MATCH in SCOPE.
14553 FUNC is a function or a lisp form. The function will be called without
14554 arguments, with the cursor positioned at the beginning of the headline.
14555 The return values of all calls to the function will be collected and
14556 returned as a list.
14558 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14559 does not need to preserve point. After evaluation, the cursor will be
14560 moved to the end of the line (presumably of the headline of the
14561 processed entry) and search continues from there. Under some
14562 circumstances, this may not produce the wanted results. For example,
14563 if you have removed (e.g. archived) the current (sub)tree it could
14564 mean that the next entry will be skipped entirely. In such cases, you
14565 can specify the position from where search should continue by making
14566 FUNC set the variable `org-map-continue-from' to the desired buffer
14567 position.
14569 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14570 Only headlines that are matched by this query will be considered during
14571 the iteration. When MATCH is nil or t, all headlines will be
14572 visited by the iteration.
14574 SCOPE determines the scope of this command. It can be any of:
14576 nil The current buffer, respecting the restriction if any
14577 tree The subtree started with the entry at point
14578 region The entries within the active region, if any
14579 region-start-level
14580 The entries within the active region, but only those at
14581 the same level than the first one.
14582 file The current buffer, without restriction
14583 file-with-archives
14584 The current buffer, and any archives associated with it
14585 agenda All agenda files
14586 agenda-with-archives
14587 All agenda files with any archive files associated with them
14588 \(file1 file2 ...)
14589 If this is a list, all files in the list will be scanned
14591 The remaining args are treated as settings for the skipping facilities of
14592 the scanner. The following items can be given here:
14594 archive skip trees with the archive tag
14595 comment skip trees with the COMMENT keyword
14596 function or Emacs Lisp form:
14597 will be used as value for `org-agenda-skip-function', so
14598 whenever the function returns a position, FUNC will not be
14599 called for that entry and search will continue from the
14600 position returned
14602 If your function needs to retrieve the tags including inherited tags
14603 at the *current* entry, you can use the value of the variable
14604 `org-scanner-tags' which will be much faster than getting the value
14605 with `org-get-tags-at'. If your function gets properties with
14606 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14607 to t around the call to `org-entry-properties' to get the same speedup.
14608 Note that if your function moves around to retrieve tags and properties at
14609 a *different* entry, you cannot use these techniques."
14610 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14611 (not (org-region-active-p)))
14612 (let* ((org-agenda-archives-mode nil) ; just to make sure
14613 (org-agenda-skip-archived-trees (memq 'archive skip))
14614 (org-agenda-skip-comment-trees (memq 'comment skip))
14615 (org-agenda-skip-function
14616 (car (org-delete-all '(comment archive) skip)))
14617 (org-tags-match-list-sublevels t)
14618 (start-level (eq scope 'region-start-level))
14619 matcher file res
14620 org-todo-keywords-for-agenda
14621 org-done-keywords-for-agenda
14622 org-todo-keyword-alist-for-agenda
14623 org-drawers-for-agenda
14624 org-tag-alist-for-agenda
14625 todo-only)
14627 (cond
14628 ((eq match t) (setq matcher t))
14629 ((eq match nil) (setq matcher t))
14630 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14632 (save-excursion
14633 (save-restriction
14634 (cond ((eq scope 'tree)
14635 (org-back-to-heading t)
14636 (org-narrow-to-subtree)
14637 (setq scope nil))
14638 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14639 (org-region-active-p))
14640 ;; If needed, set start-level to a string like "2"
14641 (when start-level
14642 (save-excursion
14643 (goto-char (region-beginning))
14644 (unless (org-at-heading-p) (outline-next-heading))
14645 (setq start-level (org-current-level))))
14646 (narrow-to-region (region-beginning)
14647 (save-excursion
14648 (goto-char (region-end))
14649 (unless (and (bolp) (org-at-heading-p))
14650 (outline-next-heading))
14651 (point)))
14652 (setq scope nil)))
14654 (if (not scope)
14655 (progn
14656 (org-agenda-prepare-buffers
14657 (list (buffer-file-name (current-buffer))))
14658 (setq res (org-scan-tags func matcher todo-only start-level)))
14659 ;; Get the right scope
14660 (cond
14661 ((and scope (listp scope) (symbolp (car scope)))
14662 (setq scope (eval scope)))
14663 ((eq scope 'agenda)
14664 (setq scope (org-agenda-files t)))
14665 ((eq scope 'agenda-with-archives)
14666 (setq scope (org-agenda-files t))
14667 (setq scope (org-add-archive-files scope)))
14668 ((eq scope 'file)
14669 (setq scope (list (buffer-file-name))))
14670 ((eq scope 'file-with-archives)
14671 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14672 (org-agenda-prepare-buffers scope)
14673 (while (setq file (pop scope))
14674 (with-current-buffer (org-find-base-buffer-visiting file)
14675 (save-excursion
14676 (save-restriction
14677 (widen)
14678 (goto-char (point-min))
14679 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14680 res)))
14682 ;;;; Properties
14684 ;;; Setting and retrieving properties
14686 (defconst org-special-properties
14687 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14688 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14689 "The special properties valid in Org-mode.
14691 These are properties that are not defined in the property drawer,
14692 but in some other way.")
14694 (defconst org-default-properties
14695 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14696 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14697 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14698 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14699 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14700 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14701 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14702 "Some properties that are used by Org-mode for various purposes.
14703 Being in this list makes sure that they are offered for completion.")
14705 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14706 "Regular expression matching the first line of a property drawer.")
14708 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14709 "Regular expression matching the last line of a property drawer.")
14711 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14712 "Regular expression matching the first line of a property drawer.")
14714 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14715 "Regular expression matching the first line of a property drawer.")
14717 (defconst org-property-drawer-re
14718 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14719 org-property-end-re "\\)\n?")
14720 "Matches an entire property drawer.")
14722 (defconst org-clock-drawer-re
14723 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14724 org-property-end-re "\\)\n?")
14725 "Matches an entire clock drawer.")
14727 (defsubst org-re-property (property)
14728 "Return a regexp matching a PROPERTY line.
14729 Match group 1 will be set to the value."
14730 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14732 (defsubst org-re-property-keyword (property)
14733 "Return a regexp matching a PROPERTY line, possibly with no
14734 value for the property."
14735 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14737 (defun org-property-action ()
14738 "Do an action on properties."
14739 (interactive)
14740 (let (c)
14741 (org-at-property-p)
14742 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14743 (setq c (read-char-exclusive))
14744 (cond
14745 ((equal c ?s)
14746 (call-interactively 'org-set-property))
14747 ((equal c ?d)
14748 (call-interactively 'org-delete-property))
14749 ((equal c ?D)
14750 (call-interactively 'org-delete-property-globally))
14751 ((equal c ?c)
14752 (call-interactively 'org-compute-property-at-point))
14753 (t (error "No such property action %c" c)))))
14755 (defun org-inc-effort ()
14756 "Increment the value of the effort property in the current entry."
14757 (interactive)
14758 (org-set-effort nil t))
14760 (defvar org-clock-effort) ;; Defined in org-clock.el
14761 (defvar org-clock-current-task) ;; Defined in org-clock.el
14762 (defun org-set-effort (&optional value increment)
14763 "Set the effort property of the current entry.
14764 With numerical prefix arg, use the nth allowed value, 0 stands for the
14765 10th allowed value.
14767 When INCREMENT is non-nil, set the property to the next allowed value."
14768 (interactive "P")
14769 (if (equal value 0) (setq value 10))
14770 (let* ((completion-ignore-case t)
14771 (prop org-effort-property)
14772 (cur (org-entry-get nil prop))
14773 (allowed (org-property-get-allowed-values nil prop 'table))
14774 (existing (mapcar 'list (org-property-values prop)))
14775 (heading (nth 4 (org-heading-components)))
14777 (val (cond
14778 ((stringp value) value)
14779 ((and allowed (integerp value))
14780 (or (car (nth (1- value) allowed))
14781 (car (org-last allowed))))
14782 ((and allowed increment)
14783 (or (caadr (member (list cur) allowed))
14784 (error "Allowed effort values are not set")))
14785 (allowed
14786 (message "Select 1-9,0, [RET%s]: %s"
14787 (if cur (concat "=" cur) "")
14788 (mapconcat 'car allowed " "))
14789 (setq rpl (read-char-exclusive))
14790 (if (equal rpl ?\r)
14792 (setq rpl (- rpl ?0))
14793 (if (equal rpl 0) (setq rpl 10))
14794 (if (and (> rpl 0) (<= rpl (length allowed)))
14795 (car (nth (1- rpl) allowed))
14796 (org-completing-read "Effort: " allowed nil))))
14798 (let (org-completion-use-ido org-completion-use-iswitchb)
14799 (org-completing-read
14800 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14801 (concat "[" cur "]") "")
14802 ": ")
14803 existing nil nil "" nil cur))))))
14804 (unless (equal (org-entry-get nil prop) val)
14805 (org-entry-put nil prop val))
14806 (save-excursion
14807 (org-back-to-heading t)
14808 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14809 (when (string= heading org-clock-current-task)
14810 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14811 (org-clock-update-mode-line))
14812 (message "%s is now %s" prop val)))
14814 (defun org-at-property-p ()
14815 "Is cursor inside a property drawer?"
14816 (save-excursion
14817 (beginning-of-line 1)
14818 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14819 (save-match-data ;; Used by calling procedures
14820 (let ((p (point))
14821 (range (unless (org-before-first-heading-p)
14822 (org-get-property-block))))
14823 (and range (<= (car range) p) (< p (cdr range))))))))
14825 (defun org-get-property-block (&optional beg end force)
14826 "Return the (beg . end) range of the body of the property drawer.
14827 BEG and END are the beginning and end of the current subtree, or of
14828 the part before the first headline. If they are not given, they will
14829 be found. If the drawer does not exist and FORCE is non-nil, create
14830 the drawer."
14831 (catch 'exit
14832 (save-excursion
14833 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14834 (progn (org-back-to-heading t) (point))))
14835 (end (or end (and (not (outline-next-heading)) (point-max))
14836 (point))))
14837 (goto-char beg)
14838 (if (re-search-forward org-property-start-re end t)
14839 (setq beg (1+ (match-end 0)))
14840 (if force
14841 (save-excursion
14842 (org-insert-property-drawer)
14843 (setq end (progn (outline-next-heading) (point))))
14844 (throw 'exit nil))
14845 (goto-char beg)
14846 (if (re-search-forward org-property-start-re end t)
14847 (setq beg (1+ (match-end 0)))))
14848 (if (re-search-forward org-property-end-re end t)
14849 (setq end (match-beginning 0))
14850 (or force (throw 'exit nil))
14851 (goto-char beg)
14852 (setq end beg)
14853 (org-indent-line)
14854 (insert ":END:\n"))
14855 (cons beg end)))))
14857 (defun org-entry-properties (&optional pom which specific)
14858 "Get all properties of the entry at point-or-marker POM.
14859 This includes the TODO keyword, the tags, time strings for deadline,
14860 scheduled, and clocking, and any additional properties defined in the
14861 entry. The return value is an alist, keys may occur multiple times
14862 if the property key was used several times.
14863 POM may also be nil, in which case the current entry is used.
14864 If WHICH is nil or `all', get all properties. If WHICH is
14865 `special' or `standard', only get that subclass. If WHICH
14866 is a string only get exactly this property. SPECIFIC can be a string, the
14867 specific property we are interested in. Specifying it can speed
14868 things up because then unnecessary parsing is avoided."
14869 (setq which (or which 'all))
14870 (org-with-point-at pom
14871 (let ((clockstr (substring org-clock-string 0 -1))
14872 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14873 (case-fold-search nil)
14874 beg end range props sum-props key key1 value string clocksum clocksumt)
14875 (save-excursion
14876 (when (condition-case nil
14877 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14878 (error nil))
14879 (setq beg (point))
14880 (setq sum-props (get-text-property (point) 'org-summaries))
14881 (setq clocksum (get-text-property (point) :org-clock-minutes)
14882 clocksumt (get-text-property (point) :org-clock-minutes-today))
14883 (outline-next-heading)
14884 (setq end (point))
14885 (when (memq which '(all special))
14886 ;; Get the special properties, like TODO and tags
14887 (goto-char beg)
14888 (when (and (or (not specific) (string= specific "TODO"))
14889 (looking-at org-todo-line-regexp) (match-end 2))
14890 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14891 (when (and (or (not specific) (string= specific "PRIORITY"))
14892 (looking-at org-priority-regexp))
14893 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14894 (when (or (not specific) (string= specific "FILE"))
14895 (push (cons "FILE" buffer-file-name) props))
14896 (when (and (or (not specific) (string= specific "TAGS"))
14897 (setq value (org-get-tags-string))
14898 (string-match "\\S-" value))
14899 (push (cons "TAGS" value) props))
14900 (when (and (or (not specific) (string= specific "ALLTAGS"))
14901 (setq value (org-get-tags-at)))
14902 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14903 ":"))
14904 props))
14905 (when (or (not specific) (string= specific "BLOCKED"))
14906 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14907 (when (or (not specific)
14908 (member specific
14909 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14910 "TIMESTAMP" "TIMESTAMP_IA")))
14911 (catch 'match
14912 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14913 (setq key (if (match-end 1)
14914 (substring (org-match-string-no-properties 1)
14915 0 -1))
14916 string (if (equal key clockstr)
14917 (org-trim
14918 (buffer-substring-no-properties
14919 (match-beginning 3) (goto-char
14920 (point-at-eol))))
14921 (substring (org-match-string-no-properties 3)
14922 1 -1)))
14923 ;; Get the correct property name from the key. This is
14924 ;; necessary if the user has configured time keywords.
14925 (setq key1 (concat key ":"))
14926 (cond
14927 ((not key)
14928 (setq key
14929 (if (= (char-after (match-beginning 3)) ?\[)
14930 "TIMESTAMP_IA" "TIMESTAMP")))
14931 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14932 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14933 ((equal key1 org-closed-string) (setq key "CLOSED"))
14934 ((equal key1 org-clock-string) (setq key "CLOCK")))
14935 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14936 (progn
14937 (push (cons key string) props)
14938 ;; no need to search further if match is found
14939 (throw 'match t))
14940 (when (or (equal key "CLOCK") (not (assoc key props)))
14941 (push (cons key string) props)))))))
14943 (when (memq which '(all standard))
14944 ;; Get the standard properties, like :PROP: ...
14945 (setq range (org-get-property-block beg end))
14946 (when range
14947 (goto-char (car range))
14948 (while (re-search-forward
14949 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14950 (cdr range) t)
14951 (setq key (org-match-string-no-properties 1)
14952 value (org-trim (or (org-match-string-no-properties 2) "")))
14953 (unless (member key excluded)
14954 (push (cons key (or value "")) props)))))
14955 (if clocksum
14956 (push (cons "CLOCKSUM"
14957 (org-columns-number-to-string (/ (float clocksum) 60.)
14958 'add_times))
14959 props))
14960 (if clocksumt
14961 (push (cons "CLOCKSUM_T"
14962 (org-columns-number-to-string (/ (float clocksumt) 60.)
14963 'add_times))
14964 props))
14965 (unless (assoc "CATEGORY" props)
14966 (push (cons "CATEGORY" (org-get-category)) props))
14967 (append sum-props (nreverse props)))))))
14969 (defun org-entry-get (pom property &optional inherit literal-nil)
14970 "Get value of PROPERTY for entry or content at point-or-marker POM.
14971 If INHERIT is non-nil and the entry does not have the property,
14972 then also check higher levels of the hierarchy.
14973 If INHERIT is the symbol `selective', use inheritance only if the setting
14974 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14975 If the property is present but empty, the return value is the empty string.
14976 If the property is not present at all, nil is returned.
14978 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14979 do not interpret it as the list atom nil. This is used for inheritance
14980 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14981 (org-with-point-at pom
14982 (if (and inherit (if (eq inherit 'selective)
14983 (org-property-inherit-p property)
14985 (org-entry-get-with-inheritance property literal-nil)
14986 (if (member property org-special-properties)
14987 ;; We need a special property. Use `org-entry-properties' to
14988 ;; retrieve it, but specify the wanted property
14989 (cdr (assoc property (org-entry-properties nil 'special property)))
14990 (let ((range (org-get-property-block)))
14991 (when (and range (not (eq (car range) (cdr range))))
14992 (let* ((props (list (or (assoc property org-file-properties)
14993 (assoc property org-global-properties)
14994 (assoc property org-global-properties-fixed))))
14995 (ap (lambda (key)
14996 (when (re-search-forward
14997 (org-re-property key) (cdr range) t)
14998 (setq props
14999 (org-update-property-plist
15001 (if (match-end 1)
15002 (org-match-string-no-properties 1) "")
15003 props)))))
15004 val)
15005 (goto-char (car range))
15006 (funcall ap property)
15007 (goto-char (car range))
15008 (while (funcall ap (concat property "+")))
15009 (setq val (cdr (assoc property props)))
15010 (when val (if literal-nil val (org-not-nil val))))))))))
15012 (defun org-property-or-variable-value (var &optional inherit)
15013 "Check if there is a property fixing the value of VAR.
15014 If yes, return this value. If not, return the current value of the variable."
15015 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15016 (if (and prop (stringp prop) (string-match "\\S-" prop))
15017 (read prop)
15018 (symbol-value var))))
15020 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15021 "Delete the property PROPERTY from entry at point-or-marker POM.
15022 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15023 an empty drawer to delete."
15024 (org-with-point-at pom
15025 (if (member property org-special-properties)
15026 nil ; cannot delete these properties.
15027 (let ((range (org-get-property-block)))
15028 (if (and range
15029 (goto-char (car range))
15030 (re-search-forward
15031 (org-re-property property)
15032 (cdr range) t))
15033 (progn
15034 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15035 (and delete-empty-drawer
15036 (org-remove-empty-drawer-at
15037 delete-empty-drawer (car range)))
15039 nil)))))
15041 ;; Multi-values properties are properties that contain multiple values
15042 ;; These values are assumed to be single words, separated by whitespace.
15043 (defun org-entry-add-to-multivalued-property (pom property value)
15044 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15045 (let* ((old (org-entry-get pom property))
15046 (values (and old (org-split-string old "[ \t]"))))
15047 (setq value (org-entry-protect-space value))
15048 (unless (member value values)
15049 (setq values (cons value values))
15050 (org-entry-put pom property
15051 (mapconcat 'identity values " ")))))
15053 (defun org-entry-remove-from-multivalued-property (pom property value)
15054 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15055 (let* ((old (org-entry-get pom property))
15056 (values (and old (org-split-string old "[ \t]"))))
15057 (setq value (org-entry-protect-space value))
15058 (when (member value values)
15059 (setq values (delete value values))
15060 (org-entry-put pom property
15061 (mapconcat 'identity values " ")))))
15063 (defun org-entry-member-in-multivalued-property (pom property value)
15064 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15065 (let* ((old (org-entry-get pom property))
15066 (values (and old (org-split-string old "[ \t]"))))
15067 (setq value (org-entry-protect-space value))
15068 (member value values)))
15070 (defun org-entry-get-multivalued-property (pom property)
15071 "Return a list of values in a multivalued property."
15072 (let* ((value (org-entry-get pom property))
15073 (values (and value (org-split-string value "[ \t]"))))
15074 (mapcar 'org-entry-restore-space values)))
15076 (defun org-entry-put-multivalued-property (pom property &rest values)
15077 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15078 VALUES should be a list of strings. Spaces will be protected."
15079 (org-entry-put pom property
15080 (mapconcat 'org-entry-protect-space values " "))
15081 (let* ((value (org-entry-get pom property))
15082 (values (and value (org-split-string value "[ \t]"))))
15083 (mapcar 'org-entry-restore-space values)))
15085 (defun org-entry-protect-space (s)
15086 "Protect spaces and newline in string S."
15087 (while (string-match " " s)
15088 (setq s (replace-match "%20" t t s)))
15089 (while (string-match "\n" s)
15090 (setq s (replace-match "%0A" t t s)))
15093 (defun org-entry-restore-space (s)
15094 "Restore spaces and newline in string S."
15095 (while (string-match "%20" s)
15096 (setq s (replace-match " " t t s)))
15097 (while (string-match "%0A" s)
15098 (setq s (replace-match "\n" t t s)))
15101 (defvar org-entry-property-inherited-from (make-marker)
15102 "Marker pointing to the entry from where a property was inherited.
15103 Each call to `org-entry-get-with-inheritance' will set this marker to the
15104 location of the entry where the inheritance search matched. If there was
15105 no match, the marker will point nowhere.
15106 Note that also `org-entry-get' calls this function, if the INHERIT flag
15107 is set.")
15109 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15110 "Get PROPERTY of entry or content at point, search higher levels if needed.
15111 The search will stop at the first ancestor which has the property defined.
15112 If the value found is \"nil\", return nil to show that the property
15113 should be considered as undefined (this is the meaning of nil here).
15114 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15115 (move-marker org-entry-property-inherited-from nil)
15116 (let (tmp)
15117 (save-excursion
15118 (save-restriction
15119 (widen)
15120 (catch 'ex
15121 (while t
15122 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15123 (or (ignore-errors (org-back-to-heading t))
15124 (goto-char (point-min)))
15125 (move-marker org-entry-property-inherited-from (point))
15126 (throw 'ex tmp))
15127 (or (ignore-errors (org-up-heading-safe))
15128 (throw 'ex nil))))))
15129 (setq tmp (or tmp
15130 (cdr (assoc property org-file-properties))
15131 (cdr (assoc property org-global-properties))
15132 (cdr (assoc property org-global-properties-fixed))))
15133 (if literal-nil tmp (org-not-nil tmp))))
15135 (defvar org-property-changed-functions nil
15136 "Hook called when the value of a property has changed.
15137 Each hook function should accept two arguments, the name of the property
15138 and the new value.")
15140 (defun org-entry-put (pom property value)
15141 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15142 (org-with-point-at pom
15143 (org-back-to-heading t)
15144 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15145 range)
15146 (cond
15147 ((equal property "TODO")
15148 (when (and (stringp value) (string-match "\\S-" value)
15149 (not (member value org-todo-keywords-1)))
15150 (error "\"%s\" is not a valid TODO state" value))
15151 (if (or (not value)
15152 (not (string-match "\\S-" value)))
15153 (setq value 'none))
15154 (org-todo value)
15155 (org-set-tags nil 'align))
15156 ((equal property "PRIORITY")
15157 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15158 (string-to-char value) ?\ ))
15159 (org-set-tags nil 'align))
15160 ((equal property "CLOCKSUM")
15161 (if (not (re-search-forward
15162 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15163 (error "Cannot find a clock log")
15164 (goto-char (- (match-end 1) 2))
15165 (cond
15166 ((eq value 'earlier) (org-timestamp-down))
15167 ((eq value 'later) (org-timestamp-up)))
15168 (org-clock-sum-current-item)))
15169 ((equal property "SCHEDULED")
15170 (if (re-search-forward org-scheduled-time-regexp end t)
15171 (cond
15172 ((eq value 'earlier) (org-timestamp-change -1 'day))
15173 ((eq value 'later) (org-timestamp-change 1 'day))
15174 (t (call-interactively 'org-schedule)))
15175 (call-interactively 'org-schedule)))
15176 ((equal property "DEADLINE")
15177 (if (re-search-forward org-deadline-time-regexp end t)
15178 (cond
15179 ((eq value 'earlier) (org-timestamp-change -1 'day))
15180 ((eq value 'later) (org-timestamp-change 1 'day))
15181 (t (call-interactively 'org-deadline)))
15182 (call-interactively 'org-deadline)))
15183 ((member property org-special-properties)
15184 (error "The %s property can not yet be set with `org-entry-put'"
15185 property))
15186 (t ; a non-special property
15187 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15188 (setq range (org-get-property-block beg end 'force))
15189 (goto-char (car range))
15190 (if (re-search-forward
15191 (org-re-property-keyword property) (cdr range) t)
15192 (progn
15193 (delete-region (match-beginning 0) (match-end 0))
15194 (goto-char (match-beginning 0)))
15195 (goto-char (cdr range))
15196 (insert "\n")
15197 (backward-char 1)
15198 (org-indent-line))
15199 (insert ":" property ":")
15200 (and value (insert " " value))
15201 (org-indent-line)))))
15202 (run-hook-with-args 'org-property-changed-functions property value)))
15204 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15205 "Get all property keys in the current buffer.
15206 With INCLUDE-SPECIALS, also list the special properties that reflect things
15207 like tags and TODO state.
15208 With INCLUDE-DEFAULTS, also include properties that has special meaning
15209 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15210 and others.
15211 With INCLUDE-COLUMNS, also include property names given in COLUMN
15212 formats in the current buffer."
15213 (let (rtn range cfmt s p)
15214 (save-excursion
15215 (save-restriction
15216 (widen)
15217 (goto-char (point-min))
15218 (while (re-search-forward org-property-start-re nil t)
15219 (setq range (org-get-property-block))
15220 (goto-char (car range))
15221 (while (re-search-forward
15222 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15223 (cdr range) t)
15224 (add-to-list 'rtn (org-match-string-no-properties 1)))
15225 (outline-next-heading))))
15227 (when include-specials
15228 (setq rtn (append org-special-properties rtn)))
15230 (when include-defaults
15231 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15232 (add-to-list 'rtn org-effort-property))
15234 (when include-columns
15235 (save-excursion
15236 (save-restriction
15237 (widen)
15238 (goto-char (point-min))
15239 (while (re-search-forward
15240 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15241 nil t)
15242 (setq cfmt (match-string 2) s 0)
15243 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15244 cfmt s)
15245 (setq s (match-end 0)
15246 p (match-string 1 cfmt))
15247 (unless (or (equal p "ITEM")
15248 (member p org-special-properties))
15249 (add-to-list 'rtn (match-string 1 cfmt))))))))
15251 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15253 (defun org-property-values (key)
15254 "Return a list of all values of property KEY in the current buffer."
15255 (save-excursion
15256 (save-restriction
15257 (widen)
15258 (goto-char (point-min))
15259 (let ((re (org-re-property key))
15260 values)
15261 (while (re-search-forward re nil t)
15262 (add-to-list 'values (org-trim (match-string 1))))
15263 (delete "" values)))))
15265 (defun org-insert-property-drawer ()
15266 "Insert a property drawer into the current entry."
15267 (org-back-to-heading t)
15268 (looking-at org-outline-regexp)
15269 (let ((indent (if org-adapt-indentation
15270 (- (match-end 0) (match-beginning 0))
15272 (beg (point))
15273 (re (concat "^[ \t]*" org-keyword-time-regexp))
15274 end hiddenp)
15275 (outline-next-heading)
15276 (setq end (point))
15277 (goto-char beg)
15278 (while (re-search-forward re end t))
15279 (setq hiddenp (outline-invisible-p))
15280 (end-of-line 1)
15281 (and (equal (char-after) ?\n) (forward-char 1))
15282 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15283 (if (member (match-string 1) '("CLOCK:" ":END:"))
15284 ;; just skip this line
15285 (beginning-of-line 2)
15286 ;; Drawer start, find the end
15287 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15288 (beginning-of-line 1)))
15289 (org-skip-over-state-notes)
15290 (skip-chars-backward " \t\n\r")
15291 (if (eq (char-before) ?*) (forward-char 1))
15292 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15293 (beginning-of-line 0)
15294 (org-indent-to-column indent)
15295 (beginning-of-line 2)
15296 (org-indent-to-column indent)
15297 (beginning-of-line 0)
15298 (if hiddenp
15299 (save-excursion
15300 (org-back-to-heading t)
15301 (hide-entry))
15302 (org-flag-drawer t))))
15304 (defun org-insert-drawer (&optional arg drawer)
15305 "Insert a drawer at point.
15307 Optional argument DRAWER, when non-nil, is a string representing
15308 drawer's name. Otherwise, the user is prompted for a name.
15310 If a region is active, insert the drawer around that region
15311 instead.
15313 Point is left between drawer's boundaries."
15314 (interactive "P")
15315 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15316 "LOGBOOK"))
15317 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15318 ;; internally by Org. They are meant to be inserted
15319 ;; automatically.
15320 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15321 ;; Remove system drawers from list. Note: For some reason,
15322 ;; `org-completing-read' ignores the predicate while
15323 ;; `completing-read' handles it fine.
15324 (drawer (if arg "PROPERTIES"
15325 (or drawer
15326 (completing-read
15327 "Drawer: " org-drawers
15328 (lambda (d) (not (member d system-drawers))))))))
15329 (cond
15330 ;; With C-u, fall back on `org-insert-property-drawer'
15331 (arg (org-insert-property-drawer))
15332 ;; With an active region, insert a drawer at point.
15333 ((not (org-region-active-p))
15334 (progn
15335 (unless (bolp) (insert "\n"))
15336 (insert (format ":%s:\n\n:END:\n" drawer))
15337 (forward-line -2)))
15338 ;; Otherwise, insert the drawer at point
15340 (let ((rbeg (region-beginning))
15341 (rend (copy-marker (region-end))))
15342 (unwind-protect
15343 (progn
15344 (goto-char rbeg)
15345 (beginning-of-line)
15346 (when (save-excursion
15347 (re-search-forward org-outline-regexp-bol rend t))
15348 (error "Drawers cannot contain headlines"))
15349 ;; Position point at the beginning of the first
15350 ;; non-blank line in region. Insert drawer's opening
15351 ;; there, then indent it.
15352 (org-skip-whitespace)
15353 (beginning-of-line)
15354 (insert ":" drawer ":\n")
15355 (forward-line -1)
15356 (indent-for-tab-command)
15357 ;; Move point to the beginning of the first blank line
15358 ;; after the last non-blank line in region. Insert
15359 ;; drawer's closing, then indent it.
15360 (goto-char rend)
15361 (skip-chars-backward " \r\t\n")
15362 (insert "\n:END:")
15363 (deactivate-mark t)
15364 (indent-for-tab-command)
15365 (unless (eolp) (insert "\n")))
15366 ;; Clear marker, whatever the outcome of insertion is.
15367 (set-marker rend nil)))))))
15369 (defvar org-property-set-functions-alist nil
15370 "Property set function alist.
15371 Each entry should have the following format:
15373 (PROPERTY . READ-FUNCTION)
15375 The read function will be called with the same argument as
15376 `org-completing-read'.")
15378 (defun org-set-property-function (property)
15379 "Get the function that should be used to set PROPERTY.
15380 This is computed according to `org-property-set-functions-alist'."
15381 (or (cdr (assoc property org-property-set-functions-alist))
15382 'org-completing-read))
15384 (defun org-read-property-value (property)
15385 "Read PROPERTY value from user."
15386 (let* ((completion-ignore-case t)
15387 (allowed (org-property-get-allowed-values nil property 'table))
15388 (cur (org-entry-get nil property))
15389 (prompt (concat property " value"
15390 (if (and cur (string-match "\\S-" cur))
15391 (concat " [" cur "]") "") ": "))
15392 (set-function (org-set-property-function property))
15393 (val (if allowed
15394 (funcall set-function prompt allowed nil
15395 (not (get-text-property 0 'org-unrestricted
15396 (caar allowed))))
15397 (let (org-completion-use-ido org-completion-use-iswitchb)
15398 (funcall set-function prompt
15399 (mapcar 'list (org-property-values property))
15400 nil nil "" nil cur)))))
15401 (if (equal val "")
15403 val)))
15405 (defvar org-last-set-property nil)
15406 (defvar org-last-set-property-value nil)
15407 (defun org-read-property-name ()
15408 "Read a property name."
15409 (let* ((completion-ignore-case t)
15410 (keys (org-buffer-property-keys nil t t))
15411 (default-prop (or (save-excursion
15412 (save-match-data
15413 (beginning-of-line)
15414 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15415 (null (string= (match-string 1) "END"))
15416 (match-string 1))))
15417 org-last-set-property))
15418 (property (org-icompleting-read
15419 (concat "Property"
15420 (if default-prop (concat " [" default-prop "]") "")
15421 ": ")
15422 (mapcar 'list keys)
15423 nil nil nil nil
15424 default-prop)))
15425 (if (member property keys)
15426 property
15427 (or (cdr (assoc (downcase property)
15428 (mapcar (lambda (x) (cons (downcase x) x))
15429 keys)))
15430 property))))
15432 (defun org-set-property-and-value (use-last)
15433 "Allow to set [PROPERTY]: [value] direction from prompt.
15434 When use-default, don't even ask, just use the last
15435 \"[PROPERTY]: [value]\" string from the history."
15436 (interactive "P")
15437 (let* ((completion-ignore-case t)
15438 (pv (or (and use-last org-last-set-property-value)
15439 (org-completing-read
15440 "Enter a \"[Property]: [value]\" pair: "
15441 nil nil nil nil nil
15442 org-last-set-property-value)))
15443 prop val)
15444 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15445 (setq prop (match-string 1 pv)
15446 val (match-string 2 pv))
15447 (org-set-property prop val))))
15449 (defun org-set-property (property value)
15450 "In the current entry, set PROPERTY to VALUE.
15451 When called interactively, this will prompt for a property name, offering
15452 completion on existing and default properties. And then it will prompt
15453 for a value, offering completion either on allowed values (via an inherited
15454 xxx_ALL property) or on existing values in other instances of this property
15455 in the current file."
15456 (interactive (list nil nil))
15457 (let* ((property (or property (org-read-property-name)))
15458 (value (or value (org-read-property-value property)))
15459 (fn (cdr (assoc property org-properties-postprocess-alist))))
15460 (setq org-last-set-property property)
15461 (setq org-last-set-property-value (concat property ": " value))
15462 ;; Possibly postprocess the inserted value:
15463 (when fn (setq value (funcall fn value)))
15464 (unless (equal (org-entry-get nil property) value)
15465 (org-entry-put nil property value))))
15467 (defun org-delete-property (property &optional delete-empty-drawer)
15468 "In the current entry, delete PROPERTY.
15469 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15470 an empty drawer to delete."
15471 (interactive
15472 (let* ((completion-ignore-case t)
15473 (prop (org-icompleting-read "Property: "
15474 (org-entry-properties nil 'standard))))
15475 (list prop)))
15476 (message "Property %s %s" property
15477 (if (org-entry-delete nil property delete-empty-drawer)
15478 "deleted"
15479 "was not present in the entry")))
15481 (defun org-delete-property-globally (property)
15482 "Remove PROPERTY globally, from all entries."
15483 (interactive
15484 (let* ((completion-ignore-case t)
15485 (prop (org-icompleting-read
15486 "Globally remove property: "
15487 (mapcar 'list (org-buffer-property-keys)))))
15488 (list prop)))
15489 (save-excursion
15490 (save-restriction
15491 (widen)
15492 (goto-char (point-min))
15493 (let ((cnt 0))
15494 (while (re-search-forward
15495 (org-re-property property)
15496 nil t)
15497 (setq cnt (1+ cnt))
15498 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15499 (message "Property \"%s\" removed from %d entries" property cnt)))))
15501 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15503 (defun org-compute-property-at-point ()
15504 "Compute the property at point.
15505 This looks for an enclosing column format, extracts the operator and
15506 then applies it to the property in the column format's scope."
15507 (interactive)
15508 (unless (org-at-property-p)
15509 (error "Not at a property"))
15510 (let ((prop (org-match-string-no-properties 2)))
15511 (org-columns-get-format-and-top-level)
15512 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15513 (error "No operator defined for property %s" prop))
15514 (org-columns-compute prop)))
15516 (defvar org-property-allowed-value-functions nil
15517 "Hook for functions supplying allowed values for a specific property.
15518 The functions must take a single argument, the name of the property, and
15519 return a flat list of allowed values. If \":ETC\" is one of
15520 the values, this means that these values are intended as defaults for
15521 completion, but that other values should be allowed too.
15522 The functions must return nil if they are not responsible for this
15523 property.")
15525 (defun org-property-get-allowed-values (pom property &optional table)
15526 "Get allowed values for the property PROPERTY.
15527 When TABLE is non-nil, return an alist that can directly be used for
15528 completion."
15529 (let (vals)
15530 (cond
15531 ((equal property "TODO")
15532 (setq vals (org-with-point-at pom
15533 (append org-todo-keywords-1 '("")))))
15534 ((equal property "PRIORITY")
15535 (let ((n org-lowest-priority))
15536 (while (>= n org-highest-priority)
15537 (push (char-to-string n) vals)
15538 (setq n (1- n)))))
15539 ((member property org-special-properties))
15540 ((setq vals (run-hook-with-args-until-success
15541 'org-property-allowed-value-functions property)))
15543 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15544 (when (and vals (string-match "\\S-" vals))
15545 (setq vals (car (read-from-string (concat "(" vals ")"))))
15546 (setq vals (mapcar (lambda (x)
15547 (cond ((stringp x) x)
15548 ((numberp x) (number-to-string x))
15549 ((symbolp x) (symbol-name x))
15550 (t "???")))
15551 vals)))))
15552 (when (member ":ETC" vals)
15553 (setq vals (remove ":ETC" vals))
15554 (org-add-props (car vals) '(org-unrestricted t)))
15555 (if table (mapcar 'list vals) vals)))
15557 (defun org-property-previous-allowed-value (&optional previous)
15558 "Switch to the next allowed value for this property."
15559 (interactive)
15560 (org-property-next-allowed-value t))
15562 (defun org-property-next-allowed-value (&optional previous)
15563 "Switch to the next allowed value for this property."
15564 (interactive)
15565 (unless (org-at-property-p)
15566 (error "Not at a property"))
15567 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15568 (key (match-string 2))
15569 (value (match-string 3))
15570 (allowed (or (org-property-get-allowed-values (point) key)
15571 (and (member value '("[ ]" "[-]" "[X]"))
15572 '("[ ]" "[X]"))))
15573 (heading (save-match-data (nth 4 (org-heading-components))))
15574 nval)
15575 (unless allowed
15576 (error "Allowed values for this property have not been defined"))
15577 (if previous (setq allowed (reverse allowed)))
15578 (if (member value allowed)
15579 (setq nval (car (cdr (member value allowed)))))
15580 (setq nval (or nval (car allowed)))
15581 (if (equal nval value)
15582 (error "Only one allowed value for this property"))
15583 (org-at-property-p)
15584 (replace-match (concat " :" key ": " nval) t t)
15585 (org-indent-line)
15586 (beginning-of-line 1)
15587 (skip-chars-forward " \t")
15588 (when (equal prop org-effort-property)
15589 (save-excursion
15590 (org-back-to-heading t)
15591 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15592 (when (string= org-clock-current-task heading)
15593 (setq org-clock-effort nval)
15594 (org-clock-update-mode-line)))
15595 (run-hook-with-args 'org-property-changed-functions key nval)))
15597 (defun org-find-olp (path &optional this-buffer)
15598 "Return a marker pointing to the entry at outline path OLP.
15599 If anything goes wrong, throw an error.
15600 You can wrap this call to catch the error like this:
15602 (condition-case msg
15603 (org-mobile-locate-entry (match-string 4))
15604 (error (nth 1 msg)))
15606 The return value will then be either a string with the error message,
15607 or a marker if everything is OK.
15609 If THIS-BUFFER is set, the outline path does not contain a file,
15610 only headings."
15611 (let* ((file (if this-buffer buffer-file-name (pop path)))
15612 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15613 (level 1)
15614 (lmin 1)
15615 (lmax 1)
15616 limit re end found pos heading cnt flevel)
15617 (unless buffer (error "File not found :%s" file))
15618 (with-current-buffer buffer
15619 (save-excursion
15620 (save-restriction
15621 (widen)
15622 (setq limit (point-max))
15623 (goto-char (point-min))
15624 (while (setq heading (pop path))
15625 (setq re (format org-complex-heading-regexp-format
15626 (regexp-quote heading)))
15627 (setq cnt 0 pos (point))
15628 (while (re-search-forward re end t)
15629 (setq level (- (match-end 1) (match-beginning 1)))
15630 (if (and (>= level lmin) (<= level lmax))
15631 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15632 (when (= cnt 0) (error "Heading not found on level %d: %s"
15633 lmax heading))
15634 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15635 lmax heading))
15636 (goto-char found)
15637 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15638 (setq end (save-excursion (org-end-of-subtree t t))))
15639 (when (org-at-heading-p)
15640 (point-marker)))))))
15642 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15643 "Find node HEADING in BUFFER.
15644 Return a marker to the heading if it was found, or nil if not.
15645 If POS-ONLY is set, return just the position instead of a marker.
15647 The heading text must match exact, but it may have a TODO keyword,
15648 a priority cookie and tags in the standard locations."
15649 (with-current-buffer (or buffer (current-buffer))
15650 (save-excursion
15651 (save-restriction
15652 (widen)
15653 (goto-char (point-min))
15654 (let (case-fold-search)
15655 (if (re-search-forward
15656 (format org-complex-heading-regexp-format
15657 (regexp-quote heading)) nil t)
15658 (if pos-only
15659 (match-beginning 0)
15660 (move-marker (make-marker) (match-beginning 0)))))))))
15662 (defun org-find-exact-heading-in-directory (heading &optional dir)
15663 "Find Org node headline HEADING in all .org files in directory DIR.
15664 When the target headline is found, return a marker to this location."
15665 (let ((files (directory-files (or dir default-directory)
15666 nil "\\`[^.#].*\\.org\\'"))
15667 file visiting m buffer)
15668 (catch 'found
15669 (while (setq file (pop files))
15670 (message "trying %s" file)
15671 (setq visiting (org-find-base-buffer-visiting file))
15672 (setq buffer (or visiting (find-file-noselect file)))
15673 (setq m (org-find-exact-headline-in-buffer
15674 heading buffer))
15675 (when (and (not m) (not visiting)) (kill-buffer buffer))
15676 (and m (throw 'found m))))))
15678 (defun org-find-entry-with-id (ident)
15679 "Locate the entry that contains the ID property with exact value IDENT.
15680 IDENT can be a string, a symbol or a number, this function will search for
15681 the string representation of it.
15682 Return the position where this entry starts, or nil if there is no such entry."
15683 (interactive "sID: ")
15684 (let ((id (cond
15685 ((stringp ident) ident)
15686 ((symbol-name ident) (symbol-name ident))
15687 ((numberp ident) (number-to-string ident))
15688 (t (error "IDENT %s must be a string, symbol or number" ident))))
15689 (case-fold-search nil))
15690 (save-excursion
15691 (save-restriction
15692 (widen)
15693 (goto-char (point-min))
15694 (when (re-search-forward
15695 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15696 nil t)
15697 (org-back-to-heading t)
15698 (point))))))
15700 ;;;; Timestamps
15702 (defvar org-last-changed-timestamp nil)
15703 (defvar org-last-inserted-timestamp nil
15704 "The last time stamp inserted with `org-insert-time-stamp'.")
15705 (defvar org-time-was-given) ; dynamically scoped parameter
15706 (defvar org-end-time-was-given) ; dynamically scoped parameter
15707 (defvar org-ts-what) ; dynamically scoped parameter
15709 (defun org-time-stamp (arg &optional inactive)
15710 "Prompt for a date/time and insert a time stamp.
15711 If the user specifies a time like HH:MM or if this command is
15712 called with at least one prefix argument, the time stamp contains
15713 the date and the time. Otherwise, only the date is be included.
15715 All parts of a date not specified by the user is filled in from
15716 the current date/time. So if you just press return without
15717 typing anything, the time stamp will represent the current
15718 date/time.
15720 If there is already a timestamp at the cursor, it will be
15721 modified.
15723 With two universal prefix arguments, insert an active timestamp
15724 with the current time without prompting the user."
15725 (interactive "P")
15726 (let* ((ts nil)
15727 (default-time
15728 ;; Default time is either today, or, when entering a range,
15729 ;; the range start.
15730 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15731 (save-excursion
15732 (re-search-backward
15733 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15734 (- (point) 20) t)))
15735 (apply 'encode-time (org-parse-time-string (match-string 1)))
15736 (current-time)))
15737 (default-input (and ts (org-get-compact-tod ts)))
15738 (repeater (save-excursion
15739 (save-match-data
15740 (beginning-of-line)
15741 (when (re-search-forward
15742 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15743 (save-excursion (progn (end-of-line) (point))) t)
15744 (match-string 0)))))
15745 org-time-was-given org-end-time-was-given time)
15746 (cond
15747 ((and (org-at-timestamp-p t)
15748 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15749 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15750 (insert "--")
15751 (setq time (let ((this-command this-command))
15752 (org-read-date arg 'totime nil nil
15753 default-time default-input inactive)))
15754 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15755 ((org-at-timestamp-p t)
15756 (setq time (let ((this-command this-command))
15757 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15758 (when (org-at-timestamp-p t) ; just to get the match data
15759 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15760 (replace-match "")
15761 (setq org-last-changed-timestamp
15762 (org-insert-time-stamp
15763 time (or org-time-was-given arg)
15764 inactive nil nil (list org-end-time-was-given)))
15765 (when repeater (goto-char (1- (point))) (insert " " repeater)
15766 (setq org-last-changed-timestamp
15767 (concat (substring org-last-inserted-timestamp 0 -1)
15768 " " repeater ">"))))
15769 (message "Timestamp updated"))
15770 ((equal arg '(16))
15771 (org-insert-time-stamp (current-time) t))
15773 (setq time (let ((this-command this-command))
15774 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15775 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15776 nil nil (list org-end-time-was-given))))))
15778 ;; FIXME: can we use this for something else, like computing time differences?
15779 (defun org-get-compact-tod (s)
15780 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15781 (let* ((t1 (match-string 1 s))
15782 (h1 (string-to-number (match-string 2 s)))
15783 (m1 (string-to-number (match-string 3 s)))
15784 (t2 (and (match-end 4) (match-string 5 s)))
15785 (h2 (and t2 (string-to-number (match-string 6 s))))
15786 (m2 (and t2 (string-to-number (match-string 7 s))))
15787 dh dm)
15788 (if (not t2)
15790 (setq dh (- h2 h1) dm (- m2 m1))
15791 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15792 (concat t1 "+" (number-to-string dh)
15793 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15795 (defun org-time-stamp-inactive (&optional arg)
15796 "Insert an inactive time stamp.
15797 An inactive time stamp is enclosed in square brackets instead of angle
15798 brackets. It is inactive in the sense that it does not trigger agenda entries,
15799 does not link to the calendar and cannot be changed with the S-cursor keys.
15800 So these are more for recording a certain time/date."
15801 (interactive "P")
15802 (org-time-stamp arg 'inactive))
15804 (defvar org-date-ovl (make-overlay 1 1))
15805 (overlay-put org-date-ovl 'face 'org-date-selected)
15806 (org-detach-overlay org-date-ovl)
15808 (defvar org-ans1) ; dynamically scoped parameter
15809 (defvar org-ans2) ; dynamically scoped parameter
15811 (defvar org-plain-time-of-day-regexp) ; defined below
15813 (defvar org-overriding-default-time nil) ; dynamically scoped
15814 (defvar org-read-date-overlay nil)
15815 (defvar org-dcst nil) ; dynamically scoped
15816 (defvar org-read-date-history nil)
15817 (defvar org-read-date-final-answer nil)
15818 (defvar org-read-date-analyze-futurep nil)
15819 (defvar org-read-date-analyze-forced-year nil)
15820 (defvar org-read-date-inactive)
15822 (defvar org-read-date-minibuffer-local-map
15823 (let ((map (make-sparse-keymap)))
15824 (set-keymap-parent map minibuffer-local-map)
15825 (org-defkey map (kbd ".")
15826 (lambda () (interactive)
15827 (org-eval-in-calendar '(calendar-goto-today))))
15828 (org-defkey map [(meta shift left)]
15829 (lambda () (interactive)
15830 (org-eval-in-calendar '(calendar-backward-month 1))))
15831 (org-defkey map [(meta shift right)]
15832 (lambda () (interactive)
15833 (org-eval-in-calendar '(calendar-forward-month 1))))
15834 (org-defkey map [(meta shift up)]
15835 (lambda () (interactive)
15836 (org-eval-in-calendar '(calendar-backward-year 1))))
15837 (org-defkey map [(meta shift down)]
15838 (lambda () (interactive)
15839 (org-eval-in-calendar '(calendar-forward-year 1))))
15840 (org-defkey map [?\e (shift left)]
15841 (lambda () (interactive)
15842 (org-eval-in-calendar '(calendar-backward-month 1))))
15843 (org-defkey map [?\e (shift right)]
15844 (lambda () (interactive)
15845 (org-eval-in-calendar '(calendar-forward-month 1))))
15846 (org-defkey map [?\e (shift up)]
15847 (lambda () (interactive)
15848 (org-eval-in-calendar '(calendar-backward-year 1))))
15849 (org-defkey map [?\e (shift down)]
15850 (lambda () (interactive)
15851 (org-eval-in-calendar '(calendar-forward-year 1))))
15852 (org-defkey map [(shift up)]
15853 (lambda () (interactive)
15854 (org-eval-in-calendar '(calendar-backward-week 1))))
15855 (org-defkey map [(shift down)]
15856 (lambda () (interactive)
15857 (org-eval-in-calendar '(calendar-forward-week 1))))
15858 (org-defkey map [(shift left)]
15859 (lambda () (interactive)
15860 (org-eval-in-calendar '(calendar-backward-day 1))))
15861 (org-defkey map [(shift right)]
15862 (lambda () (interactive)
15863 (org-eval-in-calendar '(calendar-forward-day 1))))
15864 (org-defkey map "!"
15865 (lambda () (interactive)
15866 (org-eval-in-calendar '(diary-view-entries))
15867 (message "")))
15868 (org-defkey map ">"
15869 (lambda () (interactive)
15870 (org-eval-in-calendar '(scroll-calendar-left 1))))
15871 (org-defkey map "<"
15872 (lambda () (interactive)
15873 (org-eval-in-calendar '(scroll-calendar-right 1))))
15874 (org-defkey map "\C-v"
15875 (lambda () (interactive)
15876 (org-eval-in-calendar
15877 '(calendar-scroll-left-three-months 1))))
15878 (org-defkey map "\M-v"
15879 (lambda () (interactive)
15880 (org-eval-in-calendar
15881 '(calendar-scroll-right-three-months 1))))
15882 map)
15883 "Keymap for minibuffer commands when using `org-read-date'.")
15885 (defun org-read-date (&optional org-with-time to-time from-string prompt
15886 default-time default-input inactive)
15887 "Read a date, possibly a time, and make things smooth for the user.
15888 The prompt will suggest to enter an ISO date, but you can also enter anything
15889 which will at least partially be understood by `parse-time-string'.
15890 Unrecognized parts of the date will default to the current day, month, year,
15891 hour and minute. If this command is called to replace a timestamp at point,
15892 or to enter the second timestamp of a range, the default time is taken
15893 from the existing stamp. Furthermore, the command prefers the future,
15894 so if you are giving a date where the year is not given, and the day-month
15895 combination is already past in the current year, it will assume you
15896 mean next year. For details, see the manual. A few examples:
15898 3-2-5 --> 2003-02-05
15899 feb 15 --> currentyear-02-15
15900 2/15 --> currentyear-02-15
15901 sep 12 9 --> 2009-09-12
15902 12:45 --> today 12:45
15903 22 sept 0:34 --> currentyear-09-22 0:34
15904 12 --> currentyear-currentmonth-12
15905 Fri --> nearest Friday (today or later)
15906 etc.
15908 Furthermore you can specify a relative date by giving, as the *first* thing
15909 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15910 change in days weeks, months, years.
15911 With a single plus or minus, the date is relative to today. With a double
15912 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15913 +4d --> four days from today
15914 +4 --> same as above
15915 +2w --> two weeks from today
15916 ++5 --> five days from default date
15918 The function understands only English month and weekday abbreviations.
15920 While prompting, a calendar is popped up - you can also select the
15921 date with the mouse (button 1). The calendar shows a period of three
15922 months. To scroll it to other months, use the keys `>' and `<'.
15923 If you don't like the calendar, turn it off with
15924 \(setq org-read-date-popup-calendar nil)
15926 With optional argument TO-TIME, the date will immediately be converted
15927 to an internal time.
15928 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15929 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15930 still enter a time, and this function will inform the calling routine
15931 about this change. The calling routine may then choose to change the
15932 format used to insert the time stamp into the buffer to include the time.
15933 With optional argument FROM-STRING, read from this string instead from
15934 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15935 the time/date that is used for everything that is not specified by the
15936 user."
15937 (require 'parse-time)
15938 (let* ((org-time-stamp-rounding-minutes
15939 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15940 (org-dcst org-display-custom-times)
15941 (ct (org-current-time))
15942 (org-def (or org-overriding-default-time default-time ct))
15943 (org-defdecode (decode-time org-def))
15944 (dummy (progn
15945 (when (< (nth 2 org-defdecode) org-extend-today-until)
15946 (setcar (nthcdr 2 org-defdecode) -1)
15947 (setcar (nthcdr 1 org-defdecode) 59)
15948 (setq org-def (apply 'encode-time org-defdecode)
15949 org-defdecode (decode-time org-def)))))
15950 (mouse-autoselect-window nil) ; Don't let the mouse jump
15951 (calendar-frame-setup nil)
15952 (calendar-setup nil)
15953 (calendar-move-hook nil)
15954 (calendar-view-diary-initially-flag nil)
15955 (calendar-view-holidays-initially-flag nil)
15956 (timestr (format-time-string
15957 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15958 (prompt (concat (if prompt (concat prompt " ") "")
15959 (format "Date+time [%s]: " timestr)))
15960 ans (org-ans0 "") org-ans1 org-ans2 final)
15962 (cond
15963 (from-string (setq ans from-string))
15964 (org-read-date-popup-calendar
15965 (save-excursion
15966 (save-window-excursion
15967 (calendar)
15968 (org-eval-in-calendar '(setq cursor-type nil) t)
15969 (unwind-protect
15970 (progn
15971 (calendar-forward-day (- (time-to-days org-def)
15972 (calendar-absolute-from-gregorian
15973 (calendar-current-date))))
15974 (org-eval-in-calendar nil t)
15975 (let* ((old-map (current-local-map))
15976 (map (copy-keymap calendar-mode-map))
15977 (minibuffer-local-map
15978 (copy-keymap org-read-date-minibuffer-local-map)))
15979 (org-defkey map (kbd "RET") 'org-calendar-select)
15980 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15981 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15982 (unwind-protect
15983 (progn
15984 (use-local-map map)
15985 (setq org-read-date-inactive inactive)
15986 (add-hook 'post-command-hook 'org-read-date-display)
15987 (setq org-ans0 (read-string prompt default-input
15988 'org-read-date-history nil))
15989 ;; org-ans0: from prompt
15990 ;; org-ans1: from mouse click
15991 ;; org-ans2: from calendar motion
15992 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15993 (remove-hook 'post-command-hook 'org-read-date-display)
15994 (use-local-map old-map)
15995 (when org-read-date-overlay
15996 (delete-overlay org-read-date-overlay)
15997 (setq org-read-date-overlay nil)))))
15998 (bury-buffer "*Calendar*")))))
16000 (t ; Naked prompt only
16001 (unwind-protect
16002 (setq ans (read-string prompt default-input
16003 'org-read-date-history timestr))
16004 (when org-read-date-overlay
16005 (delete-overlay org-read-date-overlay)
16006 (setq org-read-date-overlay nil)))))
16008 (setq final (org-read-date-analyze ans org-def org-defdecode))
16010 (when org-read-date-analyze-forced-year
16011 (message "Year was forced into %s"
16012 (if org-read-date-force-compatible-dates
16013 "compatible range (1970-2037)"
16014 "range representable on this machine"))
16015 (ding))
16017 ;; One round trip to get rid of 34th of August and stuff like that....
16018 (setq final (decode-time (apply 'encode-time final)))
16020 (setq org-read-date-final-answer ans)
16022 (if to-time
16023 (apply 'encode-time final)
16024 (if (and (boundp 'org-time-was-given) org-time-was-given)
16025 (format "%04d-%02d-%02d %02d:%02d"
16026 (nth 5 final) (nth 4 final) (nth 3 final)
16027 (nth 2 final) (nth 1 final))
16028 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16030 (defvar org-def)
16031 (defvar org-defdecode)
16032 (defvar org-with-time)
16033 (defun org-read-date-display ()
16034 "Display the current date prompt interpretation in the minibuffer."
16035 (when org-read-date-display-live
16036 (when org-read-date-overlay
16037 (delete-overlay org-read-date-overlay))
16038 (when (minibufferp (current-buffer))
16039 (save-excursion
16040 (end-of-line 1)
16041 (while (not (equal (buffer-substring
16042 (max (point-min) (- (point) 4)) (point))
16043 " "))
16044 (insert " ")))
16045 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16046 " " (or org-ans1 org-ans2)))
16047 (org-end-time-was-given nil)
16048 (f (org-read-date-analyze ans org-def org-defdecode))
16049 (fmts (if org-dcst
16050 org-time-stamp-custom-formats
16051 org-time-stamp-formats))
16052 (fmt (if (or org-with-time
16053 (and (boundp 'org-time-was-given) org-time-was-given))
16054 (cdr fmts)
16055 (car fmts)))
16056 (txt (format-time-string fmt (apply 'encode-time f)))
16057 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16058 (txt (concat "=> " txt)))
16059 (when (and org-end-time-was-given
16060 (string-match org-plain-time-of-day-regexp txt))
16061 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16062 org-end-time-was-given
16063 (substring txt (match-end 0)))))
16064 (when org-read-date-analyze-futurep
16065 (setq txt (concat txt " (=>F)")))
16066 (setq org-read-date-overlay
16067 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16068 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16070 (defun org-read-date-analyze (ans org-def org-defdecode)
16071 "Analyze the combined answer of the date prompt."
16072 ;; FIXME: cleanup and comment
16073 (let ((nowdecode (decode-time (current-time)))
16074 delta deltan deltaw deltadef year month day
16075 hour minute second wday pm h2 m2 tl wday1
16076 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16077 (setq org-read-date-analyze-futurep nil
16078 org-read-date-analyze-forced-year nil)
16079 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16080 (setq ans "+0"))
16082 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16083 (setq ans (replace-match "" t t ans)
16084 deltan (car delta)
16085 deltaw (nth 1 delta)
16086 deltadef (nth 2 delta)))
16088 ;; Check if there is an iso week date in there. If yes, store the
16089 ;; info and postpone interpreting it until the rest of the parsing
16090 ;; is done.
16091 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16092 (setq iso-year (if (match-end 1)
16093 (org-small-year-to-year
16094 (string-to-number (match-string 1 ans))))
16095 iso-weekday (if (match-end 3)
16096 (string-to-number (match-string 3 ans)))
16097 iso-week (string-to-number (match-string 2 ans)))
16098 (setq ans (replace-match "" t t ans)))
16100 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16101 (when (string-match
16102 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16103 (setq year (if (match-end 2)
16104 (string-to-number (match-string 2 ans))
16105 (progn (setq kill-year t)
16106 (string-to-number (format-time-string "%Y"))))
16107 month (string-to-number (match-string 3 ans))
16108 day (string-to-number (match-string 4 ans)))
16109 (if (< year 100) (setq year (+ 2000 year)))
16110 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16111 t nil ans)))
16113 ;; Help matching dotted european dates
16114 (when (string-match
16115 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16116 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16117 (setq kill-year t)
16118 (string-to-number (format-time-string "%Y")))
16119 day (string-to-number (match-string 1 ans))
16120 month (string-to-number (match-string 2 ans))
16121 ans (replace-match (format "%04d-%02d-%02d" year month day)
16122 t nil ans)))
16124 ;; Help matching american dates, like 5/30 or 5/30/7
16125 (when (string-match
16126 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16127 (setq year (if (match-end 4)
16128 (string-to-number (match-string 4 ans))
16129 (progn (setq kill-year t)
16130 (string-to-number (format-time-string "%Y"))))
16131 month (string-to-number (match-string 1 ans))
16132 day (string-to-number (match-string 2 ans)))
16133 (if (< year 100) (setq year (+ 2000 year)))
16134 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16135 t nil ans)))
16136 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16137 ;; If there is a time with am/pm, and *no* time without it, we convert
16138 ;; so that matching will be successful.
16139 (loop for i from 1 to 2 do ; twice, for end time as well
16140 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16141 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16142 (setq hour (string-to-number (match-string 1 ans))
16143 minute (if (match-end 3)
16144 (string-to-number (match-string 3 ans))
16146 pm (equal ?p
16147 (string-to-char (downcase (match-string 4 ans)))))
16148 (if (and (= hour 12) (not pm))
16149 (setq hour 0)
16150 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16151 (setq ans (replace-match (format "%02d:%02d" hour minute)
16152 t t ans))))
16154 ;; Check if a time range is given as a duration
16155 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16156 (setq hour (string-to-number (match-string 1 ans))
16157 h2 (+ hour (string-to-number (match-string 3 ans)))
16158 minute (string-to-number (match-string 2 ans))
16159 m2 (+ minute (if (match-end 5) (string-to-number
16160 (match-string 5 ans))0)))
16161 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16162 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16163 t t ans)))
16165 ;; Check if there is a time range
16166 (when (boundp 'org-end-time-was-given)
16167 (setq org-time-was-given nil)
16168 (when (and (string-match org-plain-time-of-day-regexp ans)
16169 (match-end 8))
16170 (setq org-end-time-was-given (match-string 8 ans))
16171 (setq ans (concat (substring ans 0 (match-beginning 7))
16172 (substring ans (match-end 7))))))
16174 (setq tl (parse-time-string ans)
16175 day (or (nth 3 tl) (nth 3 org-defdecode))
16176 month (or (nth 4 tl)
16177 (if (and org-read-date-prefer-future
16178 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16179 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16180 (nth 4 org-defdecode)))
16181 year (or (and (not kill-year) (nth 5 tl))
16182 (if (and org-read-date-prefer-future
16183 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16184 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16185 (nth 5 org-defdecode)))
16186 hour (or (nth 2 tl) (nth 2 org-defdecode))
16187 minute (or (nth 1 tl) (nth 1 org-defdecode))
16188 second (or (nth 0 tl) 0)
16189 wday (nth 6 tl))
16191 (when (and (eq org-read-date-prefer-future 'time)
16192 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16193 (equal day (nth 3 nowdecode))
16194 (equal month (nth 4 nowdecode))
16195 (equal year (nth 5 nowdecode))
16196 (nth 2 tl)
16197 (or (< (nth 2 tl) (nth 2 nowdecode))
16198 (and (= (nth 2 tl) (nth 2 nowdecode))
16199 (nth 1 tl)
16200 (< (nth 1 tl) (nth 1 nowdecode)))))
16201 (setq day (1+ day)
16202 futurep t))
16204 ;; Special date definitions below
16205 (cond
16206 (iso-week
16207 ;; There was an iso week
16208 (require 'cal-iso)
16209 (setq futurep nil)
16210 (setq year (or iso-year year)
16211 day (or iso-weekday wday 1)
16212 wday nil ; to make sure that the trigger below does not match
16213 iso-date (calendar-gregorian-from-absolute
16214 (calendar-absolute-from-iso
16215 (list iso-week day year))))
16216 ; FIXME: Should we also push ISO weeks into the future?
16217 ; (when (and org-read-date-prefer-future
16218 ; (not iso-year)
16219 ; (< (calendar-absolute-from-gregorian iso-date)
16220 ; (time-to-days (current-time))))
16221 ; (setq year (1+ year)
16222 ; iso-date (calendar-gregorian-from-absolute
16223 ; (calendar-absolute-from-iso
16224 ; (list iso-week day year)))))
16225 (setq month (car iso-date)
16226 year (nth 2 iso-date)
16227 day (nth 1 iso-date)))
16228 (deltan
16229 (setq futurep nil)
16230 (unless deltadef
16231 (let ((now (decode-time (current-time))))
16232 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16233 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16234 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16235 ((equal deltaw "m") (setq month (+ month deltan)))
16236 ((equal deltaw "y") (setq year (+ year deltan)))))
16237 ((and wday (not (nth 3 tl)))
16238 ;; Weekday was given, but no day, so pick that day in the week
16239 ;; on or after the derived date.
16240 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16241 (unless (equal wday wday1)
16242 (setq day (+ day (% (- wday wday1 -7) 7))))))
16243 (if (and (boundp 'org-time-was-given)
16244 (nth 2 tl))
16245 (setq org-time-was-given t))
16246 (if (< year 100) (setq year (+ 2000 year)))
16247 ;; Check of the date is representable
16248 (if org-read-date-force-compatible-dates
16249 (progn
16250 (if (< year 1970)
16251 (setq year 1970 org-read-date-analyze-forced-year t))
16252 (if (> year 2037)
16253 (setq year 2037 org-read-date-analyze-forced-year t)))
16254 (condition-case nil
16255 (ignore (encode-time second minute hour day month year))
16256 (error
16257 (setq year (nth 5 org-defdecode))
16258 (setq org-read-date-analyze-forced-year t))))
16259 (setq org-read-date-analyze-futurep futurep)
16260 (list second minute hour day month year)))
16262 (defvar parse-time-weekdays)
16263 (defun org-read-date-get-relative (s today default)
16264 "Check string S for special relative date string.
16265 TODAY and DEFAULT are internal times, for today and for a default.
16266 Return shift list (N what def-flag)
16267 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16268 N is the number of WHATs to shift.
16269 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16270 the DEFAULT date rather than TODAY."
16271 (require 'parse-time)
16272 (when (and
16273 (string-match
16274 (concat
16275 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16276 "\\([0-9]+\\)?"
16277 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16278 "\\([ \t]\\|$\\)") s)
16279 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16280 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16281 (string-to-char (substring (match-string 1 s) -1))
16282 ?+))
16283 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16284 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16285 (what (if (match-end 3) (match-string 3 s) "d"))
16286 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16287 (date (if rel default today))
16288 (wday (nth 6 (decode-time date)))
16289 delta)
16290 (if wday1
16291 (progn
16292 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16293 (if (= dir ?-) (setq delta (- delta 7)))
16294 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16295 (list delta "d" rel))
16296 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16298 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16299 "Turn a user-specified date into the internal representation.
16300 The internal representation needed by the calendar is (month day year).
16301 This is a wrapper to handle the brain-dead convention in calendar that
16302 user function argument order change dependent on argument order."
16303 (if (boundp 'calendar-date-style)
16304 (cond
16305 ((eq calendar-date-style 'american)
16306 (list arg1 arg2 arg3))
16307 ((eq calendar-date-style 'european)
16308 (list arg2 arg1 arg3))
16309 ((eq calendar-date-style 'iso)
16310 (list arg2 arg3 arg1)))
16311 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16312 (if (org-bound-and-true-p european-calendar-style)
16313 (list arg2 arg1 arg3)
16314 (list arg1 arg2 arg3)))))
16316 (defun org-eval-in-calendar (form &optional keepdate)
16317 "Eval FORM in the calendar window and return to current window.
16318 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16319 otherwise stick to the current value of `org-ans2'."
16320 (let ((sf (selected-frame))
16321 (sw (selected-window)))
16322 (select-window (get-buffer-window "*Calendar*" t))
16323 (eval form)
16324 (when (and (not keepdate) (calendar-cursor-to-date))
16325 (let* ((date (calendar-cursor-to-date))
16326 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16327 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16328 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16329 (select-window sw)
16330 (org-select-frame-set-input-focus sf)))
16332 (defun org-calendar-select ()
16333 "Return to `org-read-date' with the date currently selected.
16334 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16335 (interactive)
16336 (when (calendar-cursor-to-date)
16337 (let* ((date (calendar-cursor-to-date))
16338 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16339 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16340 (if (active-minibuffer-window) (exit-minibuffer))))
16342 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16343 "Insert a date stamp for the date given by the internal TIME.
16344 WITH-HM means use the stamp format that includes the time of the day.
16345 INACTIVE means use square brackets instead of angular ones, so that the
16346 stamp will not contribute to the agenda.
16347 PRE and POST are optional strings to be inserted before and after the
16348 stamp.
16349 The command returns the inserted time stamp."
16350 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16351 stamp)
16352 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16353 (insert-before-markers (or pre ""))
16354 (when (listp extra)
16355 (setq extra (car extra))
16356 (if (and (stringp extra)
16357 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16358 (setq extra (format "-%02d:%02d"
16359 (string-to-number (match-string 1 extra))
16360 (string-to-number (match-string 2 extra))))
16361 (setq extra nil)))
16362 (when extra
16363 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16364 (insert-before-markers (setq stamp (format-time-string fmt time)))
16365 (insert-before-markers (or post ""))
16366 (setq org-last-inserted-timestamp stamp)))
16368 (defun org-toggle-time-stamp-overlays ()
16369 "Toggle the use of custom time stamp formats."
16370 (interactive)
16371 (setq org-display-custom-times (not org-display-custom-times))
16372 (unless org-display-custom-times
16373 (let ((p (point-min)) (bmp (buffer-modified-p)))
16374 (while (setq p (next-single-property-change p 'display))
16375 (if (and (get-text-property p 'display)
16376 (eq (get-text-property p 'face) 'org-date))
16377 (remove-text-properties
16378 p (setq p (next-single-property-change p 'display))
16379 '(display t))))
16380 (set-buffer-modified-p bmp)))
16381 (if (featurep 'xemacs)
16382 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16383 (org-restart-font-lock)
16384 (setq org-table-may-need-update t)
16385 (if org-display-custom-times
16386 (message "Time stamps are overlaid with custom format")
16387 (message "Time stamp overlays removed")))
16389 (defun org-display-custom-time (beg end)
16390 "Overlay modified time stamp format over timestamp between BEG and END."
16391 (let* ((ts (buffer-substring beg end))
16392 t1 w1 with-hm tf time str w2 (off 0))
16393 (save-match-data
16394 (setq t1 (org-parse-time-string ts t))
16395 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16396 (setq off (- (match-end 0) (match-beginning 0)))))
16397 (setq end (- end off))
16398 (setq w1 (- end beg)
16399 with-hm (and (nth 1 t1) (nth 2 t1))
16400 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16401 time (org-fix-decoded-time t1)
16402 str (org-add-props
16403 (format-time-string
16404 (substring tf 1 -1) (apply 'encode-time time))
16405 nil 'mouse-face 'highlight)
16406 w2 (length str))
16407 (if (not (= w2 w1))
16408 (add-text-properties (1+ beg) (+ 2 beg)
16409 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16410 (if (featurep 'xemacs)
16411 (progn
16412 (put-text-property beg end 'invisible t)
16413 (put-text-property beg end 'end-glyph (make-glyph str)))
16414 (put-text-property beg end 'display str))))
16416 (defun org-translate-time (string)
16417 "Translate all timestamps in STRING to custom format.
16418 But do this only if the variable `org-display-custom-times' is set."
16419 (when org-display-custom-times
16420 (save-match-data
16421 (let* ((start 0)
16422 (re org-ts-regexp-both)
16423 t1 with-hm inactive tf time str beg end)
16424 (while (setq start (string-match re string start))
16425 (setq beg (match-beginning 0)
16426 end (match-end 0)
16427 t1 (save-match-data
16428 (org-parse-time-string (substring string beg end) t))
16429 with-hm (and (nth 1 t1) (nth 2 t1))
16430 inactive (equal (substring string beg (1+ beg)) "[")
16431 tf (funcall (if with-hm 'cdr 'car)
16432 org-time-stamp-custom-formats)
16433 time (org-fix-decoded-time t1)
16434 str (format-time-string
16435 (concat
16436 (if inactive "[" "<") (substring tf 1 -1)
16437 (if inactive "]" ">"))
16438 (apply 'encode-time time))
16439 string (replace-match str t t string)
16440 start (+ start (length str)))))))
16441 string)
16443 (defun org-fix-decoded-time (time)
16444 "Set 0 instead of nil for the first 6 elements of time.
16445 Don't touch the rest."
16446 (let ((n 0))
16447 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16449 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16451 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16452 "Difference between TIMESTAMP-STRING and now in days.
16453 If SECONDS is non-nil, return the difference in seconds."
16454 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16455 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16456 (funcall fdiff (current-time)))))
16458 (defun org-deadline-close (timestamp-string &optional ndays)
16459 "Is the time in TIMESTAMP-STRING close to the current date?"
16460 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16461 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16462 (not (org-entry-is-done-p))))
16464 (defun org-get-wdays (ts &optional delay zero-delay)
16465 "Get the deadline lead time appropriate for timestring TS.
16466 When DELAY is non-nil, get the delay time for scheduled items
16467 instead of the deadline lead time. When ZERO-DELAY is non-nil
16468 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16469 don't try to find the delay cookie in the scheduled timestamp."
16470 (let ((tv (if delay org-scheduled-delay-days
16471 org-deadline-warning-days)))
16472 (cond
16473 ((or (and delay (< tv 0))
16474 (and delay zero-delay (<= tv 0))
16475 (and (not delay) (<= tv 0)))
16476 ;; Enforce this value no matter what
16477 (- tv))
16478 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16479 ;; lead time is specified.
16480 (floor (* (string-to-number (match-string 1 ts))
16481 (cdr (assoc (match-string 2 ts)
16482 '(("d" . 1) ("w" . 7)
16483 ("m" . 30.4) ("y" . 365.25)
16484 ("h" . 0.041667)))))))
16485 ;; go for the default.
16486 (t tv))))
16488 (defun org-calendar-select-mouse (ev)
16489 "Return to `org-read-date' with the date currently selected.
16490 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16491 (interactive "e")
16492 (mouse-set-point ev)
16493 (when (calendar-cursor-to-date)
16494 (let* ((date (calendar-cursor-to-date))
16495 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16496 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16497 (if (active-minibuffer-window) (exit-minibuffer))))
16499 (defun org-check-deadlines (ndays)
16500 "Check if there are any deadlines due or past due.
16501 A deadline is considered due if it happens within `org-deadline-warning-days'
16502 days from today's date. If the deadline appears in an entry marked DONE,
16503 it is not shown. The prefix arg NDAYS can be used to test that many
16504 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16505 (interactive "P")
16506 (let* ((org-warn-days
16507 (cond
16508 ((equal ndays '(4)) 100000)
16509 (ndays (prefix-numeric-value ndays))
16510 (t (abs org-deadline-warning-days))))
16511 (case-fold-search nil)
16512 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16513 (callback
16514 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16516 (message "%d deadlines past-due or due within %d days"
16517 (org-occur regexp nil callback)
16518 org-warn-days)))
16520 (defsubst org-re-timestamp (type)
16521 "Return a regexp for timestamp TYPE.
16522 Allowed values for TYPE are:
16524 all: all timestamps
16525 active: only active timestamps (<...>)
16526 inactive: only inactive timestamps ([...])
16527 scheduled: only scheduled timestamps
16528 deadline: only deadline timestamps
16530 When TYPE is nil, fall back on returning a regexp that matches
16531 both scheduled and deadline timestamps."
16532 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16533 ((eq type 'active) org-ts-regexp)
16534 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16535 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16536 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16537 ((eq type 'scheduled-or-deadline)
16538 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16540 (defun org-check-before-date (date)
16541 "Check if there are deadlines or scheduled entries before DATE."
16542 (interactive (list (org-read-date)))
16543 (let ((case-fold-search nil)
16544 (regexp (org-re-timestamp org-ts-type))
16545 (callback
16546 (lambda () (time-less-p
16547 (org-time-string-to-time (match-string 1))
16548 (org-time-string-to-time date)))))
16549 (message "%d entries before %s"
16550 (org-occur regexp nil callback) date)))
16552 (defun org-check-after-date (date)
16553 "Check if there are deadlines or scheduled entries after DATE."
16554 (interactive (list (org-read-date)))
16555 (let ((case-fold-search nil)
16556 (regexp (org-re-timestamp org-ts-type))
16557 (callback
16558 (lambda () (not
16559 (time-less-p
16560 (org-time-string-to-time (match-string 1))
16561 (org-time-string-to-time date))))))
16562 (message "%d entries after %s"
16563 (org-occur regexp nil callback) date)))
16565 (defun org-check-dates-range (start-date end-date)
16566 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16567 (interactive (list (org-read-date nil nil nil "Range starts")
16568 (org-read-date nil nil nil "Range end")))
16569 (let ((case-fold-search nil)
16570 (regexp (org-re-timestamp org-ts-type))
16571 (callback
16572 (lambda ()
16573 (let ((match (match-string 1)))
16574 (and
16575 (not (time-less-p
16576 (org-time-string-to-time match)
16577 (org-time-string-to-time start-date)))
16578 (time-less-p
16579 (org-time-string-to-time match)
16580 (org-time-string-to-time end-date)))))))
16581 (message "%d entries between %s and %s"
16582 (org-occur regexp nil callback) start-date end-date)))
16584 (defun org-evaluate-time-range (&optional to-buffer)
16585 "Evaluate a time range by computing the difference between start and end.
16586 Normally the result is just printed in the echo area, but with prefix arg
16587 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16588 If the time range is actually in a table, the result is inserted into the
16589 next column.
16590 For time difference computation, a year is assumed to be exactly 365
16591 days in order to avoid rounding problems."
16592 (interactive "P")
16594 (org-clock-update-time-maybe)
16595 (save-excursion
16596 (unless (org-at-date-range-p t)
16597 (goto-char (point-at-bol))
16598 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16599 (if (not (org-at-date-range-p t))
16600 (error "Not at a time-stamp range, and none found in current line")))
16601 (let* ((ts1 (match-string 1))
16602 (ts2 (match-string 2))
16603 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16604 (match-end (match-end 0))
16605 (time1 (org-time-string-to-time ts1))
16606 (time2 (org-time-string-to-time ts2))
16607 (t1 (org-float-time time1))
16608 (t2 (org-float-time time2))
16609 (diff (abs (- t2 t1)))
16610 (negative (< (- t2 t1) 0))
16611 ;; (ys (floor (* 365 24 60 60)))
16612 (ds (* 24 60 60))
16613 (hs (* 60 60))
16614 (fy "%dy %dd %02d:%02d")
16615 (fy1 "%dy %dd")
16616 (fd "%dd %02d:%02d")
16617 (fd1 "%dd")
16618 (fh "%02d:%02d")
16619 y d h m align)
16620 (if havetime
16621 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16623 d (floor (/ diff ds)) diff (mod diff ds)
16624 h (floor (/ diff hs)) diff (mod diff hs)
16625 m (floor (/ diff 60)))
16626 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16628 d (floor (+ (/ diff ds) 0.5))
16629 h 0 m 0))
16630 (if (not to-buffer)
16631 (message "%s" (org-make-tdiff-string y d h m))
16632 (if (org-at-table-p)
16633 (progn
16634 (goto-char match-end)
16635 (setq align t)
16636 (and (looking-at " *|") (goto-char (match-end 0))))
16637 (goto-char match-end))
16638 (if (looking-at
16639 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16640 (replace-match ""))
16641 (if negative (insert " -"))
16642 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16643 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16644 (insert " " (format fh h m))))
16645 (if align (org-table-align))
16646 (message "Time difference inserted")))))
16648 (defun org-make-tdiff-string (y d h m)
16649 (let ((fmt "")
16650 (l nil))
16651 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16652 l (push y l)))
16653 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16654 l (push d l)))
16655 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16656 l (push h l)))
16657 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16658 l (push m l)))
16659 (apply 'format fmt (nreverse l))))
16661 (defun org-time-string-to-time (s &optional buffer pos)
16662 "Convert a timestamp string into internal time."
16663 (condition-case errdata
16664 (apply 'encode-time (org-parse-time-string s))
16665 (error (error "Bad timestamp `%s'%s\nError was: %s"
16666 s (if (not (and buffer pos))
16668 (format " at %d in buffer `%s'" pos buffer))
16669 (cdr errdata)))))
16671 (defun org-time-string-to-seconds (s)
16672 "Convert a timestamp string to a number of seconds."
16673 (org-float-time (org-time-string-to-time s)))
16675 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16676 "Convert a time stamp to an absolute day number.
16677 If there is a specifier for a cyclic time stamp, get the closest
16678 date to DAYNR.
16679 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16680 The variable date is bound by the calendar when this is called."
16681 (cond
16682 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16683 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16684 daynr
16685 (+ daynr 1000)))
16686 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16687 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16688 (time-to-days (current-time))) (match-string 0 s)
16689 prefer show-all))
16690 (t (time-to-days
16691 (condition-case errdata
16692 (apply 'encode-time (org-parse-time-string s))
16693 (error (error "Bad timestamp `%s'%s\nError was: %s"
16694 s (if (not (and buffer pos))
16696 (format " at %d in buffer `%s'" pos buffer))
16697 (cdr errdata))))))))
16699 (defun org-days-to-iso-week (days)
16700 "Return the iso week number."
16701 (require 'cal-iso)
16702 (car (calendar-iso-from-absolute days)))
16704 (defun org-small-year-to-year (year)
16705 "Convert 2-digit years into 4-digit years.
16706 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16707 The year 2000 cannot be abbreviated. Any year larger than 99
16708 is returned unchanged."
16709 (if (< year 38)
16710 (setq year (+ 2000 year))
16711 (if (< year 100)
16712 (setq year (+ 1900 year))))
16713 year)
16715 (defun org-time-from-absolute (d)
16716 "Return the time corresponding to date D.
16717 D may be an absolute day number, or a calendar-type list (month day year)."
16718 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16719 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16721 (defun org-calendar-holiday ()
16722 "List of holidays, for Diary display in Org-mode."
16723 (require 'holidays)
16724 (let ((hl (funcall
16725 (if (fboundp 'calendar-check-holidays)
16726 'calendar-check-holidays 'check-calendar-holidays) date)))
16727 (if hl (mapconcat 'identity hl "; "))))
16729 (defun org-diary-sexp-entry (sexp entry date)
16730 "Process a SEXP diary ENTRY for DATE."
16731 (require 'diary-lib)
16732 (let ((result (if calendar-debug-sexp
16733 (let ((stack-trace-on-error t))
16734 (eval (car (read-from-string sexp))))
16735 (condition-case nil
16736 (eval (car (read-from-string sexp)))
16737 (error
16738 (beep)
16739 (message "Bad sexp at line %d in %s: %s"
16740 (org-current-line)
16741 (buffer-file-name) sexp)
16742 (sleep-for 2))))))
16743 (cond ((stringp result) (split-string result "; "))
16744 ((and (consp result)
16745 (not (consp (cdr result)))
16746 (stringp (cdr result))) (cdr result))
16747 ((and (consp result)
16748 (stringp (car result))) result)
16749 (result entry))))
16751 (defun org-diary-to-ical-string (frombuf)
16752 "Get iCalendar entries from diary entries in buffer FROMBUF.
16753 This uses the icalendar.el library."
16754 (let* ((tmpdir (if (featurep 'xemacs)
16755 (temp-directory)
16756 temporary-file-directory))
16757 (tmpfile (make-temp-name
16758 (expand-file-name "orgics" tmpdir)))
16759 buf rtn b e)
16760 (with-current-buffer frombuf
16761 (icalendar-export-region (point-min) (point-max) tmpfile)
16762 (setq buf (find-buffer-visiting tmpfile))
16763 (set-buffer buf)
16764 (goto-char (point-min))
16765 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16766 (setq b (match-beginning 0)))
16767 (goto-char (point-max))
16768 (if (re-search-backward "^END:VEVENT" nil t)
16769 (setq e (match-end 0)))
16770 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16771 (kill-buffer buf)
16772 (delete-file tmpfile)
16773 rtn))
16775 (defun org-closest-date (start current change prefer show-all)
16776 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16777 When PREFER is `past', return a date that is either CURRENT or past.
16778 When PREFER is `future', return a date that is either CURRENT or future.
16779 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16780 ;; Make the proper lists from the dates
16781 (catch 'exit
16782 (let ((a1 '(("h" . hour)
16783 ("d" . day)
16784 ("w" . week)
16785 ("m" . month)
16786 ("y" . year)))
16787 (shour (nth 2 (org-parse-time-string start)))
16788 dn dw sday cday n1 n2 n0
16789 d m y y1 y2 date1 date2 nmonths nm ny m2)
16791 (setq start (org-date-to-gregorian start)
16792 current (org-date-to-gregorian
16793 (if show-all
16794 current
16795 (time-to-days (current-time))))
16796 sday (calendar-absolute-from-gregorian start)
16797 cday (calendar-absolute-from-gregorian current))
16799 (if (<= cday sday) (throw 'exit sday))
16801 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16802 (setq dn (string-to-number (match-string 1 change))
16803 dw (cdr (assoc (match-string 2 change) a1)))
16804 (error "Invalid change specifier: %s" change))
16805 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16806 (cond
16807 ((eq dw 'hour)
16808 (let ((missing-hours
16809 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16810 dn)))
16811 (setq n1 (if (zerop missing-hours) cday
16812 (- cday (1+ (floor (/ missing-hours 24)))))
16813 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16814 ((eq dw 'day)
16815 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16816 n2 (+ n1 dn)))
16817 ((eq dw 'year)
16818 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16819 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16820 (setq date1 (list m d y1)
16821 n1 (calendar-absolute-from-gregorian date1)
16822 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16823 n2 (calendar-absolute-from-gregorian date2)))
16824 ((eq dw 'month)
16825 ;; approx number of month between the two dates
16826 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16827 ;; How often does dn fit in there?
16828 (setq d (nth 1 start) m (car start) y (nth 2 start)
16829 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16830 m (+ m nm)
16831 ny (floor (/ m 12))
16832 y (+ y ny)
16833 m (- m (* ny 12)))
16834 (while (> m 12) (setq m (- m 12) y (1+ y)))
16835 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16836 (setq m2 (+ m dn) y2 y)
16837 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16838 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16839 (while (<= n2 cday)
16840 (setq n1 n2 m m2 y y2)
16841 (setq m2 (+ m dn) y2 y)
16842 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16843 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16844 ;; Make sure n1 is the earlier date
16845 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16846 (if show-all
16847 (cond
16848 ((eq prefer 'past) (if (= cday n2) n2 n1))
16849 ((eq prefer 'future) (if (= cday n1) n1 n2))
16850 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16851 (cond
16852 ((eq prefer 'past) (if (= cday n2) n2 n1))
16853 ((eq prefer 'future) (if (= cday n1) n1 n2))
16854 (t (if (= cday n1) n1 n2)))))))
16856 (defun org-date-to-gregorian (date)
16857 "Turn any specification of DATE into a Gregorian date for the calendar."
16858 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16859 ((and (listp date) (= (length date) 3)) date)
16860 ((stringp date)
16861 (setq date (org-parse-time-string date))
16862 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16863 ((listp date)
16864 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16866 (defun org-parse-time-string (s &optional nodefault)
16867 "Parse the standard Org-mode time string.
16868 This should be a lot faster than the normal `parse-time-string'.
16869 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16870 hour and minute fields will be nil if not given."
16871 (cond ((string-match org-ts-regexp0 s)
16872 (list 0
16873 (if (or (match-beginning 8) (not nodefault))
16874 (string-to-number (or (match-string 8 s) "0")))
16875 (if (or (match-beginning 7) (not nodefault))
16876 (string-to-number (or (match-string 7 s) "0")))
16877 (string-to-number (match-string 4 s))
16878 (string-to-number (match-string 3 s))
16879 (string-to-number (match-string 2 s))
16880 nil nil nil))
16881 ((string-match "^<[^>]+>$" s)
16882 (decode-time (seconds-to-time (org-matcher-time s))))
16883 (t (error "Not a standard Org-mode time string: %s" s))))
16885 (defun org-timestamp-up (&optional arg)
16886 "Increase the date item at the cursor by one.
16887 If the cursor is on the year, change the year. If it is on the month,
16888 the day or the time, change that.
16889 With prefix ARG, change by that many units."
16890 (interactive "p")
16891 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16893 (defun org-timestamp-down (&optional arg)
16894 "Decrease the date item at the cursor by one.
16895 If the cursor is on the year, change the year. If it is on the month,
16896 the day or the time, change that.
16897 With prefix ARG, change by that many units."
16898 (interactive "p")
16899 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16901 (defun org-timestamp-up-day (&optional arg)
16902 "Increase the date in the time stamp by one day.
16903 With prefix ARG, change that many days."
16904 (interactive "p")
16905 (if (and (not (org-at-timestamp-p t))
16906 (org-at-heading-p))
16907 (org-todo 'up)
16908 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16910 (defun org-timestamp-down-day (&optional arg)
16911 "Decrease the date in the time stamp by one day.
16912 With prefix ARG, change that many days."
16913 (interactive "p")
16914 (if (and (not (org-at-timestamp-p t))
16915 (org-at-heading-p))
16916 (org-todo 'down)
16917 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16919 (defun org-at-timestamp-p (&optional inactive-ok)
16920 "Determine if the cursor is in or at a timestamp."
16921 (interactive)
16922 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16923 (pos (point))
16924 (ans (or (looking-at tsr)
16925 (save-excursion
16926 (skip-chars-backward "^[<\n\r\t")
16927 (if (> (point) (point-min)) (backward-char 1))
16928 (and (looking-at tsr)
16929 (> (- (match-end 0) pos) -1))))))
16930 (and ans
16931 (boundp 'org-ts-what)
16932 (setq org-ts-what
16933 (cond
16934 ((= pos (match-beginning 0)) 'bracket)
16935 ;; Point is considered to be "on the bracket" whether
16936 ;; it's really on it or right after it.
16937 ((= pos (1- (match-end 0))) 'bracket)
16938 ((= pos (match-end 0)) 'after)
16939 ((org-pos-in-match-range pos 2) 'year)
16940 ((org-pos-in-match-range pos 3) 'month)
16941 ((org-pos-in-match-range pos 7) 'hour)
16942 ((org-pos-in-match-range pos 8) 'minute)
16943 ((or (org-pos-in-match-range pos 4)
16944 (org-pos-in-match-range pos 5)) 'day)
16945 ((and (> pos (or (match-end 8) (match-end 5)))
16946 (< pos (match-end 0)))
16947 (- pos (or (match-end 8) (match-end 5))))
16948 (t 'day))))
16949 ans))
16951 (defun org-toggle-timestamp-type ()
16952 "Toggle the type (<active> or [inactive]) of a time stamp."
16953 (interactive)
16954 (when (org-at-timestamp-p t)
16955 (let ((beg (match-beginning 0)) (end (match-end 0))
16956 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16957 (save-excursion
16958 (goto-char beg)
16959 (while (re-search-forward "[][<>]" end t)
16960 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16961 t t)))
16962 (message "Timestamp is now %sactive"
16963 (if (equal (char-after beg) ?<) "" "in")))))
16965 (defun org-at-clock-log-p nil
16966 "Is the cursor on the clock log line?"
16967 (save-excursion
16968 (move-beginning-of-line 1)
16969 (looking-at "^[ \t]*CLOCK:")))
16971 (defvar org-clock-history) ; defined in org-clock.el
16972 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16973 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16974 "Change the date in the time stamp at point.
16975 The date will be changed by N times WHAT. WHAT can be `day', `month',
16976 `year', `minute', `second'. If WHAT is not given, the cursor position
16977 in the timestamp determines what will be changed.
16978 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16979 (let ((origin (point)) origin-cat
16980 with-hm inactive
16981 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16982 org-ts-what
16983 extra rem
16984 ts time time0 fixnext clrgx)
16985 (if (not (org-at-timestamp-p t))
16986 (error "Not at a timestamp"))
16987 (if (and (not what) (eq org-ts-what 'bracket))
16988 (org-toggle-timestamp-type)
16989 ;; Point isn't on brackets. Remember the part of the time-stamp
16990 ;; the point was in. Indeed, size of time-stamps may change,
16991 ;; but point must be kept in the same category nonetheless.
16992 (setq origin-cat org-ts-what)
16993 (if (and (not what) (not (eq org-ts-what 'day))
16994 org-display-custom-times
16995 (get-text-property (point) 'display)
16996 (not (get-text-property (1- (point)) 'display)))
16997 (setq org-ts-what 'day))
16998 (setq org-ts-what (or what org-ts-what)
16999 inactive (= (char-after (match-beginning 0)) ?\[)
17000 ts (match-string 0))
17001 (replace-match "")
17002 (when (string-match
17003 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17005 (setq extra (match-string 1 ts))
17006 (if suppress-tmp-delay
17007 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17008 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17009 (setq with-hm t))
17010 (setq time0 (org-parse-time-string ts))
17011 (when (and updown
17012 (eq org-ts-what 'minute)
17013 (not current-prefix-arg))
17014 ;; This looks like s-up and s-down. Change by one rounding step.
17015 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17016 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17017 (setcar (cdr time0) (+ (nth 1 time0)
17018 (if (> n 0) (- rem) (- dm rem))))))
17019 (setq time
17020 (encode-time (or (car time0) 0)
17021 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17022 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17023 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17024 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17025 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17026 (nthcdr 6 time0)))
17027 (when (and (member org-ts-what '(hour minute))
17028 extra
17029 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17030 (setq extra (org-modify-ts-extra
17031 extra
17032 (if (eq org-ts-what 'hour) 2 5)
17033 n dm)))
17034 (when (integerp org-ts-what)
17035 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17036 (if (eq what 'calendar)
17037 (let ((cal-date (org-get-date-from-calendar)))
17038 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17039 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17040 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17041 (setcar time0 (or (car time0) 0))
17042 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17043 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17044 (setq time (apply 'encode-time time0))))
17045 ;; Insert the new time-stamp, and ensure point stays in the same
17046 ;; category as before (i.e. not after the last position in that
17047 ;; category).
17048 (let ((pos (point)))
17049 ;; Stay before inserted string. `save-excursion' is of no use.
17050 (setq org-last-changed-timestamp
17051 (org-insert-time-stamp time with-hm inactive nil nil extra))
17052 (goto-char pos))
17053 (save-match-data
17054 (looking-at org-ts-regexp3)
17055 (goto-char (cond
17056 ;; `day' category ends before `hour' if any, or at
17057 ;; the end of the day name.
17058 ((eq origin-cat 'day)
17059 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17060 ((eq origin-cat 'hour) (min (match-end 7) origin))
17061 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17062 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17063 ;; `year' and `month' have both fixed size: point
17064 ;; couldn't have moved into another part.
17065 (t origin))))
17066 ;; Update clock if on a CLOCK line.
17067 (org-clock-update-time-maybe)
17068 ;; Maybe adjust the closest clock in `org-clock-history'
17069 (when org-clock-adjust-closest
17070 (if (not (and (org-at-clock-log-p)
17071 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17072 org-clock-history))))))
17073 (message "No clock to adjust")
17074 (cond ((save-excursion ; fix previous clock?
17075 (re-search-backward org-ts-regexp0 nil t)
17076 (org-looking-back (concat org-clock-string " \\[")))
17077 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17078 ((save-excursion ; fix next clock?
17079 (re-search-backward org-ts-regexp0 nil t)
17080 (looking-at (concat org-ts-regexp0 "\\] =>")))
17081 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17082 (save-window-excursion
17083 ;; Find closest clock to point, adjust the previous/next one in history
17084 (let* ((p (save-excursion (org-back-to-heading t)))
17085 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17086 (clfixnth
17087 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17088 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17089 (if (not clfixpos)
17090 (message "No clock to adjust")
17091 (save-excursion
17092 (org-goto-marker-or-bmk clfixpos)
17093 (org-show-subtree)
17094 (when (re-search-forward clrgx nil t)
17095 (goto-char (match-beginning 1))
17096 (let (org-clock-adjust-closest)
17097 (org-timestamp-change n org-ts-what updown))
17098 (message "Clock adjusted in %s for heading: %s"
17099 (file-name-nondirectory (buffer-file-name))
17100 (org-get-heading t t)))))))))
17101 ;; Try to recenter the calendar window, if any.
17102 (if (and org-calendar-follow-timestamp-change
17103 (get-buffer-window "*Calendar*" t)
17104 (memq org-ts-what '(day month year)))
17105 (org-recenter-calendar (time-to-days time))))))
17107 (defun org-modify-ts-extra (s pos n dm)
17108 "Change the different parts of the lead-time and repeat fields in timestamp."
17109 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17110 ng h m new rem)
17111 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17112 (cond
17113 ((or (org-pos-in-match-range pos 2)
17114 (org-pos-in-match-range pos 3))
17115 (setq m (string-to-number (match-string 3 s))
17116 h (string-to-number (match-string 2 s)))
17117 (if (org-pos-in-match-range pos 2)
17118 (setq h (+ h n))
17119 (setq n (* dm (org-no-warnings (signum n))))
17120 (when (not (= 0 (setq rem (% m dm))))
17121 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17122 (setq m (+ m n)))
17123 (if (< m 0) (setq m (+ m 60) h (1- h)))
17124 (if (> m 59) (setq m (- m 60) h (1+ h)))
17125 (setq h (min 24 (max 0 h)))
17126 (setq ng 1 new (format "-%02d:%02d" h m)))
17127 ((org-pos-in-match-range pos 6)
17128 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17129 ((org-pos-in-match-range pos 5)
17130 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17132 ((org-pos-in-match-range pos 9)
17133 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17134 ((org-pos-in-match-range pos 8)
17135 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17137 (when ng
17138 (setq s (concat
17139 (substring s 0 (match-beginning ng))
17141 (substring s (match-end ng))))))
17144 (defun org-recenter-calendar (date)
17145 "If the calendar is visible, recenter it to DATE."
17146 (let ((cwin (get-buffer-window "*Calendar*" t)))
17147 (when cwin
17148 (let ((calendar-move-hook nil))
17149 (with-selected-window cwin
17150 (calendar-goto-date (if (listp date) date
17151 (calendar-gregorian-from-absolute date))))))))
17153 (defun org-goto-calendar (&optional arg)
17154 "Go to the Emacs calendar at the current date.
17155 If there is a time stamp in the current line, go to that date.
17156 A prefix ARG can be used to force the current date."
17157 (interactive "P")
17158 (let ((tsr org-ts-regexp) diff
17159 (calendar-move-hook nil)
17160 (calendar-view-holidays-initially-flag nil)
17161 (calendar-view-diary-initially-flag nil))
17162 (if (or (org-at-timestamp-p)
17163 (save-excursion
17164 (beginning-of-line 1)
17165 (looking-at (concat ".*" tsr))))
17166 (let ((d1 (time-to-days (current-time)))
17167 (d2 (time-to-days
17168 (org-time-string-to-time (match-string 1)))))
17169 (setq diff (- d2 d1))))
17170 (calendar)
17171 (calendar-goto-today)
17172 (if (and diff (not arg)) (calendar-forward-day diff))))
17174 (defun org-get-date-from-calendar ()
17175 "Return a list (month day year) of date at point in calendar."
17176 (with-current-buffer "*Calendar*"
17177 (save-match-data
17178 (calendar-cursor-to-date))))
17180 (defun org-date-from-calendar ()
17181 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17182 If there is already a time stamp at the cursor position, update it."
17183 (interactive)
17184 (if (org-at-timestamp-p t)
17185 (org-timestamp-change 0 'calendar)
17186 (let ((cal-date (org-get-date-from-calendar)))
17187 (org-insert-time-stamp
17188 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17190 (defcustom org-effort-durations
17191 `(("h" . 60)
17192 ("d" . ,(* 60 8))
17193 ("w" . ,(* 60 8 5))
17194 ("m" . ,(* 60 8 5 4))
17195 ("y" . ,(* 60 8 5 40)))
17196 "Conversion factor to minutes for an effort modifier.
17198 Each entry has the form (MODIFIER . MINUTES).
17200 In an effort string, a number followed by MODIFIER is multiplied
17201 by the specified number of MINUTES to obtain an effort in
17202 minutes.
17204 For example, if the value of this variable is ((\"hours\" . 60)), then an
17205 effort string \"2hours\" is equivalent to 120 minutes."
17206 :group 'org-agenda
17207 :version "24.1"
17208 :type '(alist :key-type (string :tag "Modifier")
17209 :value-type (number :tag "Minutes")))
17211 (defun org-minutes-to-clocksum-string (m)
17212 "Format number of minutes as a clocksum string.
17213 The format is determined by `org-time-clocksum-format',
17214 `org-time-clocksum-use-fractional' and
17215 `org-time-clocksum-fractional-format' and
17216 `org-time-clocksum-use-effort-durations'."
17217 (let ((clocksum "") h d w mo y fmt n)
17218 (setq h (if org-time-clocksum-use-effort-durations
17219 (cdr (assoc "h" org-effort-durations)) 60)
17220 d (if org-time-clocksum-use-effort-durations
17221 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17222 w (if org-time-clocksum-use-effort-durations
17223 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17224 mo (if org-time-clocksum-use-effort-durations
17225 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17226 y (if org-time-clocksum-use-effort-durations
17227 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17228 ;; fractional format
17229 (if org-time-clocksum-use-fractional
17230 (cond
17231 ;; single format string
17232 ((stringp org-time-clocksum-fractional-format)
17233 (format org-time-clocksum-fractional-format (/ m (float h))))
17234 ;; choice of fractional formats for different time units
17235 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17236 (> (/ (truncate m) (* y d h)) 0))
17237 (format fmt (/ m (* y d (float h)))))
17238 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17239 (> (/ (truncate m) (* mo d h)) 0))
17240 (format fmt (/ m (* mo d (float h)))))
17241 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17242 (> (/ (truncate m) (* w d h)) 0))
17243 (format fmt (/ m (* w d (float h)))))
17244 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17245 (> (/ (truncate m) (* d h)) 0))
17246 (format fmt (/ m (* d (float h)))))
17247 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17248 (> (/ (truncate m) h) 0))
17249 (format fmt (/ m (float h))))
17250 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17251 (format fmt m))
17252 ;; fall back to smallest time unit with a format
17253 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17254 (format fmt (/ m (float h))))
17255 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17256 (format fmt (/ m (* d (float h)))))
17257 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17258 (format fmt (/ m (* w d (float h)))))
17259 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17260 (format fmt (/ m (* mo d (float h)))))
17261 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17262 (format fmt (/ m (* y d (float h))))))
17263 ;; standard (non-fractional) format, with single format string
17264 (if (stringp org-time-clocksum-format)
17265 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17266 ;; separate formats components
17267 (and (setq fmt (plist-get org-time-clocksum-format :years))
17268 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17269 (plist-get org-time-clocksum-format :require-years))
17270 (setq clocksum (concat clocksum (format fmt n))
17271 m (- m (* n y d h))))
17272 (and (setq fmt (plist-get org-time-clocksum-format :months))
17273 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17274 (plist-get org-time-clocksum-format :require-months))
17275 (setq clocksum (concat clocksum (format fmt n))
17276 m (- m (* n mo d h))))
17277 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17278 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17279 (plist-get org-time-clocksum-format :require-weeks))
17280 (setq clocksum (concat clocksum (format fmt n))
17281 m (- m (* n w d h))))
17282 (and (setq fmt (plist-get org-time-clocksum-format :days))
17283 (or (> (setq n (/ (truncate m) (* d h))) 0)
17284 (plist-get org-time-clocksum-format :require-days))
17285 (setq clocksum (concat clocksum (format fmt n))
17286 m (- m (* n d h))))
17287 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17288 (or (> (setq n (/ (truncate m) h)) 0)
17289 (plist-get org-time-clocksum-format :require-hours))
17290 (setq clocksum (concat clocksum (format fmt n))
17291 m (- m (* n h))))
17292 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17293 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17294 (setq clocksum (concat clocksum (format fmt m))))
17295 ;; return formatted time duration
17296 clocksum))))
17298 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17299 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17300 "Org mode version 8.0")
17302 (defun org-hours-to-clocksum-string (n)
17303 (org-minutes-to-clocksum-string (* n 60)))
17305 (defun org-hh:mm-string-to-minutes (s)
17306 "Convert a string H:MM to a number of minutes.
17307 If the string is just a number, interpret it as minutes.
17308 In fact, the first hh:mm or number in the string will be taken,
17309 there can be extra stuff in the string.
17310 If no number is found, the return value is 0."
17311 (cond
17312 ((integerp s) s)
17313 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17314 (+ (* (string-to-number (match-string 1 s)) 60)
17315 (string-to-number (match-string 2 s))))
17316 ((string-match "\\([0-9]+\\)" s)
17317 (string-to-number (match-string 1 s)))
17318 (t 0)))
17320 (defcustom org-image-actual-width t
17321 "Should we use the actual width of images when inlining them?
17323 When set to `t', always use the image width.
17325 When set to a number, use imagemagick (when available) to set
17326 the image's width to this value.
17328 When set to a number in a list, try to get the width from the
17329 #+ATTR.* keyword if it matches a width specification like
17330 width=\"[0-9]+\", and fall back on that number if none is found.
17332 When set to nil, try to get the width from an #+ATTR.* keyword
17333 and fall back on the original width if none is found.
17335 This requires Emacs >= 24.1, build with imagemagick support."
17336 :group 'org-appearance
17337 :version "24.4"
17338 :package-version '(Org . "8.0")
17339 :type '(choice
17340 (const :tag "Use the image width" t)
17341 (integer :tag "Use a number of pixels")
17342 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17343 (const :tag "Use #+ATTR* or don't resize" nil)))
17345 (defcustom org-agenda-inhibit-startup nil
17346 "Inhibit startup when preparing agenda buffers.
17347 When this variable is `t' (the default), the initialization of
17348 the Org agenda buffers is inhibited: e.g. the visibility state
17349 is not set, the tables are not re-aligned, etc."
17350 :type 'boolean
17351 :version "24.3"
17352 :group 'org-agenda)
17354 (defun org-duration-string-to-minutes (s &optional output-to-string)
17355 "Convert a duration string S to minutes.
17357 A bare number is interpreted as minutes, modifiers can be set by
17358 customizing `org-effort-durations' (which see).
17360 Entries containing a colon are interpreted as H:MM by
17361 `org-hh:mm-string-to-minutes'."
17362 (let ((result 0)
17363 (re (concat "\\([0-9.]+\\) *\\("
17364 (regexp-opt (mapcar 'car org-effort-durations))
17365 "\\)")))
17366 (while (string-match re s)
17367 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17368 (string-to-number (match-string 1 s))))
17369 (setq s (replace-match "" nil t s)))
17370 (setq result (floor result))
17371 (incf result (org-hh:mm-string-to-minutes s))
17372 (if output-to-string (number-to-string result) result)))
17374 ;;;; Files
17376 (defun org-save-all-org-buffers ()
17377 "Save all Org-mode buffers without user confirmation."
17378 (interactive)
17379 (message "Saving all Org-mode buffers...")
17380 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17381 (when (featurep 'org-id) (org-id-locations-save))
17382 (message "Saving all Org-mode buffers... done"))
17384 (defun org-revert-all-org-buffers ()
17385 "Revert all Org-mode buffers.
17386 Prompt for confirmation when there are unsaved changes.
17387 Be sure you know what you are doing before letting this function
17388 overwrite your changes.
17390 This function is useful in a setup where one tracks org files
17391 with a version control system, to revert on one machine after pulling
17392 changes from another. I believe the procedure must be like this:
17394 1. M-x org-save-all-org-buffers
17395 2. Pull changes from the other machine, resolve conflicts
17396 3. M-x org-revert-all-org-buffers"
17397 (interactive)
17398 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17399 (error "Abort"))
17400 (save-excursion
17401 (save-window-excursion
17402 (mapc
17403 (lambda (b)
17404 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17405 (with-current-buffer b buffer-file-name))
17406 (org-pop-to-buffer-same-window b)
17407 (revert-buffer t 'no-confirm)))
17408 (buffer-list))
17409 (when (and (featurep 'org-id) org-id-track-globally)
17410 (org-id-locations-load)))))
17412 ;;;; Agenda files
17414 ;;;###autoload
17415 (defun org-switchb (&optional arg)
17416 "Switch between Org buffers.
17417 With one prefix argument, restrict available buffers to files.
17418 With two prefix arguments, restrict available buffers to agenda files.
17420 Defaults to `iswitchb' for buffer name completion.
17421 Set `org-completion-use-ido' to make it use ido instead."
17422 (interactive "P")
17423 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17424 ((equal arg '(16)) (org-buffer-list 'agenda))
17425 (t (org-buffer-list))))
17426 (org-completion-use-iswitchb org-completion-use-iswitchb)
17427 (org-completion-use-ido org-completion-use-ido))
17428 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17429 (setq org-completion-use-iswitchb t))
17430 (org-pop-to-buffer-same-window
17431 (org-icompleting-read "Org buffer: "
17432 (mapcar 'list (mapcar 'buffer-name blist))
17433 nil t))))
17435 ;;; Define some older names previously used for this functionality
17436 ;;;###autoload
17437 (defalias 'org-ido-switchb 'org-switchb)
17438 ;;;###autoload
17439 (defalias 'org-iswitchb 'org-switchb)
17441 (defun org-buffer-list (&optional predicate exclude-tmp)
17442 "Return a list of Org buffers.
17443 PREDICATE can be `export', `files' or `agenda'.
17445 export restrict the list to Export buffers.
17446 files restrict the list to buffers visiting Org files.
17447 agenda restrict the list to buffers visiting agenda files.
17449 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17450 (let* ((bfn nil)
17451 (agenda-files (and (eq predicate 'agenda)
17452 (mapcar 'file-truename (org-agenda-files t))))
17453 (filter
17454 (cond
17455 ((eq predicate 'files)
17456 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17457 ((eq predicate 'export)
17458 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17459 ((eq predicate 'agenda)
17460 (lambda (b)
17461 (with-current-buffer b
17462 (and (derived-mode-p 'org-mode)
17463 (setq bfn (buffer-file-name b))
17464 (member (file-truename bfn) agenda-files)))))
17465 (t (lambda (b) (with-current-buffer b
17466 (or (derived-mode-p 'org-mode)
17467 (string-match "\*Org .*Export"
17468 (buffer-name b)))))))))
17469 (delq nil
17470 (mapcar
17471 (lambda(b)
17472 (if (and (funcall filter b)
17473 (or (not exclude-tmp)
17474 (not (string-match "tmp" (buffer-name b)))))
17476 nil))
17477 (buffer-list)))))
17479 (defun org-agenda-files (&optional unrestricted archives)
17480 "Get the list of agenda files.
17481 Optional UNRESTRICTED means return the full list even if a restriction
17482 is currently in place.
17483 When ARCHIVES is t, include all archive files that are really being
17484 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17485 `org-agenda-archives-mode' is t."
17486 (let ((files
17487 (cond
17488 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17489 ((stringp org-agenda-files) (org-read-agenda-file-list))
17490 ((listp org-agenda-files) org-agenda-files)
17491 (t (error "Invalid value of `org-agenda-files'")))))
17492 (setq files (apply 'append
17493 (mapcar (lambda (f)
17494 (if (file-directory-p f)
17495 (directory-files
17496 f t org-agenda-file-regexp)
17497 (list f)))
17498 files)))
17499 (when org-agenda-skip-unavailable-files
17500 (setq files (delq nil
17501 (mapcar (function
17502 (lambda (file)
17503 (and (file-readable-p file) file)))
17504 files))))
17505 (when (or (eq archives t)
17506 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17507 (setq files (org-add-archive-files files)))
17508 files))
17510 (defun org-agenda-file-p (&optional file)
17511 "Return non-nil, if FILE is an agenda file.
17512 If FILE is omitted, use the file associated with the current
17513 buffer."
17514 (member (or file (buffer-file-name))
17515 (org-agenda-files t)))
17517 (defun org-edit-agenda-file-list ()
17518 "Edit the list of agenda files.
17519 Depending on setup, this either uses customize to edit the variable
17520 `org-agenda-files', or it visits the file that is holding the list. In the
17521 latter case, the buffer is set up in a way that saving it automatically kills
17522 the buffer and restores the previous window configuration."
17523 (interactive)
17524 (if (stringp org-agenda-files)
17525 (let ((cw (current-window-configuration)))
17526 (find-file org-agenda-files)
17527 (org-set-local 'org-window-configuration cw)
17528 (org-add-hook 'after-save-hook
17529 (lambda ()
17530 (set-window-configuration
17531 (prog1 org-window-configuration
17532 (kill-buffer (current-buffer))))
17533 (org-install-agenda-files-menu)
17534 (message "New agenda file list installed"))
17535 nil 'local)
17536 (message "%s" (substitute-command-keys
17537 "Edit list and finish with \\[save-buffer]")))
17538 (customize-variable 'org-agenda-files)))
17540 (defun org-store-new-agenda-file-list (list)
17541 "Set new value for the agenda file list and save it correctly."
17542 (if (stringp org-agenda-files)
17543 (let ((fe (org-read-agenda-file-list t)) b u)
17544 (while (setq b (find-buffer-visiting org-agenda-files))
17545 (kill-buffer b))
17546 (with-temp-file org-agenda-files
17547 (insert
17548 (mapconcat
17549 (lambda (f) ;; Keep un-expanded entries.
17550 (if (setq u (assoc f fe))
17551 (cdr u)
17553 list "\n")
17554 "\n")))
17555 (let ((org-mode-hook nil) (org-inhibit-startup t)
17556 (org-insert-mode-line-in-empty-file nil))
17557 (setq org-agenda-files list)
17558 (customize-save-variable 'org-agenda-files org-agenda-files))))
17560 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17561 "Read the list of agenda files from a file.
17562 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17563 filenames, used by `org-store-new-agenda-file-list' to write back
17564 un-expanded file names."
17565 (when (file-directory-p org-agenda-files)
17566 (error "`org-agenda-files' cannot be a single directory"))
17567 (when (stringp org-agenda-files)
17568 (with-temp-buffer
17569 (insert-file-contents org-agenda-files)
17570 (mapcar
17571 (lambda (f)
17572 (let ((e (expand-file-name (substitute-in-file-name f)
17573 org-directory)))
17574 (if pair-with-expansion
17575 (cons e f)
17576 e)))
17577 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17579 ;;;###autoload
17580 (defun org-cycle-agenda-files ()
17581 "Cycle through the files in `org-agenda-files'.
17582 If the current buffer visits an agenda file, find the next one in the list.
17583 If the current buffer does not, find the first agenda file."
17584 (interactive)
17585 (let* ((fs (org-agenda-files t))
17586 (files (append fs (list (car fs))))
17587 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17588 file)
17589 (unless files (error "No agenda files"))
17590 (catch 'exit
17591 (while (setq file (pop files))
17592 (if (equal (file-truename file) tcf)
17593 (when (car files)
17594 (find-file (car files))
17595 (throw 'exit t))))
17596 (find-file (car fs)))
17597 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17599 (defun org-agenda-file-to-front (&optional to-end)
17600 "Move/add the current file to the top of the agenda file list.
17601 If the file is not present in the list, it is added to the front. If it is
17602 present, it is moved there. With optional argument TO-END, add/move to the
17603 end of the list."
17604 (interactive "P")
17605 (let ((org-agenda-skip-unavailable-files nil)
17606 (file-alist (mapcar (lambda (x)
17607 (cons (file-truename x) x))
17608 (org-agenda-files t)))
17609 (ctf (file-truename
17610 (or buffer-file-name
17611 (error "Please save the current buffer to a file"))))
17612 x had)
17613 (setq x (assoc ctf file-alist) had x)
17615 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17616 (if to-end
17617 (setq file-alist (append (delq x file-alist) (list x)))
17618 (setq file-alist (cons x (delq x file-alist))))
17619 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17620 (org-install-agenda-files-menu)
17621 (message "File %s to %s of agenda file list"
17622 (if had "moved" "added") (if to-end "end" "front"))))
17624 (defun org-remove-file (&optional file)
17625 "Remove current file from the list of files in variable `org-agenda-files'.
17626 These are the files which are being checked for agenda entries.
17627 Optional argument FILE means use this file instead of the current."
17628 (interactive)
17629 (let* ((org-agenda-skip-unavailable-files nil)
17630 (file (or file buffer-file-name
17631 (error "Current buffer does not visit a file")))
17632 (true-file (file-truename file))
17633 (afile (abbreviate-file-name file))
17634 (files (delq nil (mapcar
17635 (lambda (x)
17636 (if (equal true-file
17637 (file-truename x))
17638 nil x))
17639 (org-agenda-files t)))))
17640 (if (not (= (length files) (length (org-agenda-files t))))
17641 (progn
17642 (org-store-new-agenda-file-list files)
17643 (org-install-agenda-files-menu)
17644 (message "Removed file: %s" afile))
17645 (message "File was not in list: %s (not removed)" afile))))
17647 (defun org-file-menu-entry (file)
17648 (vector file (list 'find-file file) t))
17650 (defun org-check-agenda-file (file)
17651 "Make sure FILE exists. If not, ask user what to do."
17652 (when (not (file-exists-p file))
17653 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17654 (abbreviate-file-name file))
17655 (let ((r (downcase (read-char-exclusive))))
17656 (cond
17657 ((equal r ?r)
17658 (org-remove-file file)
17659 (throw 'nextfile t))
17660 (t (error "Abort"))))))
17662 (defun org-get-agenda-file-buffer (file)
17663 "Get a buffer visiting FILE. If the buffer needs to be created, add
17664 it to the list of buffers which might be released later."
17665 (let ((buf (org-find-base-buffer-visiting file)))
17666 (if buf
17667 buf ; just return it
17668 ;; Make a new buffer and remember it
17669 (setq buf (find-file-noselect file))
17670 (if buf (push buf org-agenda-new-buffers))
17671 buf)))
17673 (defun org-release-buffers (blist)
17674 "Release all buffers in list, asking the user for confirmation when needed.
17675 When a buffer is unmodified, it is just killed. When modified, it is saved
17676 \(if the user agrees) and then killed."
17677 (let (buf file)
17678 (while (setq buf (pop blist))
17679 (setq file (buffer-file-name buf))
17680 (when (and (buffer-modified-p buf)
17681 file
17682 (y-or-n-p (format "Save file %s? " file)))
17683 (with-current-buffer buf (save-buffer)))
17684 (kill-buffer buf))))
17686 (defun org-agenda-prepare-buffers (files)
17687 "Create buffers for all agenda files, protect archived trees and comments."
17688 (interactive)
17689 (let ((pa '(:org-archived t))
17690 (pc '(:org-comment t))
17691 (pall '(:org-archived t :org-comment t))
17692 (inhibit-read-only t)
17693 (org-inhibit-startup org-agenda-inhibit-startup)
17694 (rea (concat ":" org-archive-tag ":"))
17695 file re)
17696 (save-excursion
17697 (save-restriction
17698 (while (setq file (pop files))
17699 (catch 'nextfile
17700 (if (bufferp file)
17701 (set-buffer file)
17702 (org-check-agenda-file file)
17703 (set-buffer (org-get-agenda-file-buffer file)))
17704 (widen)
17705 (org-refresh-category-properties)
17706 (org-refresh-properties org-effort-property 'org-effort)
17707 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17708 (setq org-todo-keywords-for-agenda
17709 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17710 (setq org-done-keywords-for-agenda
17711 (append org-done-keywords-for-agenda org-done-keywords))
17712 (setq org-todo-keyword-alist-for-agenda
17713 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17714 (setq org-drawers-for-agenda
17715 (append org-drawers-for-agenda org-drawers))
17716 (setq org-tag-alist-for-agenda
17717 (append org-tag-alist-for-agenda org-tag-alist))
17718 (org-with-silent-modifications
17719 (save-excursion
17720 (remove-text-properties (point-min) (point-max) pall)
17721 (when org-agenda-skip-archived-trees
17722 (goto-char (point-min))
17723 (while (re-search-forward rea nil t)
17724 (if (org-at-heading-p t)
17725 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17726 (goto-char (point-min))
17727 (setq re (format org-heading-keyword-regexp-format
17728 org-comment-string))
17729 (while (re-search-forward re nil t)
17730 (add-text-properties
17731 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17732 (setq org-todo-keywords-for-agenda
17733 (org-uniquify org-todo-keywords-for-agenda))
17734 (setq org-todo-keyword-alist-for-agenda
17735 (org-uniquify org-todo-keyword-alist-for-agenda)
17736 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17739 ;;;; CDLaTeX minor mode
17741 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17742 "Keymap for the minor `org-cdlatex-mode'.")
17744 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17745 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17746 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17747 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17748 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17750 (defvar org-cdlatex-texmathp-advice-is-done nil
17751 "Flag remembering if we have applied the advice to texmathp already.")
17753 (define-minor-mode org-cdlatex-mode
17754 "Toggle the minor `org-cdlatex-mode'.
17755 This mode supports entering LaTeX environment and math in LaTeX fragments
17756 in Org-mode.
17757 \\{org-cdlatex-mode-map}"
17758 nil " OCDL" nil
17759 (when org-cdlatex-mode
17760 (require 'cdlatex)
17761 (run-hooks 'cdlatex-mode-hook)
17762 (cdlatex-compute-tables))
17763 (unless org-cdlatex-texmathp-advice-is-done
17764 (setq org-cdlatex-texmathp-advice-is-done t)
17765 (defadvice texmathp (around org-math-always-on activate)
17766 "Always return t in org-mode buffers.
17767 This is because we want to insert math symbols without dollars even outside
17768 the LaTeX math segments. If Orgmode thinks that point is actually inside
17769 an embedded LaTeX fragment, let texmathp do its job.
17770 \\[org-cdlatex-mode-map]"
17771 (interactive)
17772 (let (p)
17773 (cond
17774 ((not (derived-mode-p 'org-mode)) ad-do-it)
17775 ((eq this-command 'cdlatex-math-symbol)
17776 (setq ad-return-value t
17777 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17779 (let ((p (org-inside-LaTeX-fragment-p)))
17780 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17781 (setq ad-return-value t
17782 texmathp-why '("Org-mode embedded math" . 0))
17783 (if p ad-do-it)))))))))
17785 (defun turn-on-org-cdlatex ()
17786 "Unconditionally turn on `org-cdlatex-mode'."
17787 (org-cdlatex-mode 1))
17789 (defun org-try-cdlatex-tab ()
17790 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17791 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17792 - inside a LaTeX fragment, or
17793 - after the first word in a line, where an abbreviation expansion could
17794 insert a LaTeX environment."
17795 (when org-cdlatex-mode
17796 (cond
17797 ;; Before any word on the line: No expansion possible.
17798 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17799 ;; Just after first word on the line: Expand it. Make sure it
17800 ;; cannot happen on headlines, though.
17801 ((save-excursion
17802 (skip-chars-backward "a-zA-Z0-9*")
17803 (skip-chars-backward " \t")
17804 (and (bolp) (not (org-at-heading-p))))
17805 (cdlatex-tab) t)
17806 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17808 (defun org-cdlatex-underscore-caret (&optional arg)
17809 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17810 Revert to the normal definition outside of these fragments."
17811 (interactive "P")
17812 (if (org-inside-LaTeX-fragment-p)
17813 (call-interactively 'cdlatex-sub-superscript)
17814 (let (org-cdlatex-mode)
17815 (call-interactively (key-binding (vector last-input-event))))))
17817 (defun org-cdlatex-math-modify (&optional arg)
17818 "Execute `cdlatex-math-modify' in LaTeX fragments.
17819 Revert to the normal definition outside of these fragments."
17820 (interactive "P")
17821 (if (org-inside-LaTeX-fragment-p)
17822 (call-interactively 'cdlatex-math-modify)
17823 (let (org-cdlatex-mode)
17824 (call-interactively (key-binding (vector last-input-event))))))
17828 ;;;; LaTeX fragments
17830 (defvar org-latex-regexps
17831 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17832 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17833 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17834 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17835 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17836 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17837 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17838 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17839 "Regular expressions for matching embedded LaTeX.")
17841 (defun org-inside-LaTeX-fragment-p ()
17842 "Test if point is inside a LaTeX fragment.
17843 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17844 sequence appearing also before point.
17845 Even though the matchers for math are configurable, this function assumes
17846 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17847 delimiters are skipped when they have been removed by customization.
17848 The return value is nil, or a cons cell with the delimiter and the
17849 position of this delimiter.
17851 This function does a reasonably good job, but can locally be fooled by
17852 for example currency specifications. For example it will assume being in
17853 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17854 fragments that are properly closed, but during editing, we have to live
17855 with the uncertainty caused by missing closing delimiters. This function
17856 looks only before point, not after."
17857 (catch 'exit
17858 (let ((pos (point))
17859 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17860 (lim (progn
17861 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17862 (point)))
17863 dd-on str (start 0) m re)
17864 (goto-char pos)
17865 (when dodollar
17866 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17867 re (nth 1 (assoc "$" org-latex-regexps)))
17868 (while (string-match re str start)
17869 (cond
17870 ((= (match-end 0) (length str))
17871 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17872 ((= (match-end 0) (- (length str) 5))
17873 (throw 'exit nil))
17874 (t (setq start (match-end 0))))))
17875 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17876 (goto-char pos)
17877 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17878 (and (match-beginning 2) (throw 'exit nil))
17879 ;; count $$
17880 (while (re-search-backward "\\$\\$" lim t)
17881 (setq dd-on (not dd-on)))
17882 (goto-char pos)
17883 (if dd-on (cons "$$" m))))))
17885 (defun org-inside-latex-macro-p ()
17886 "Is point inside a LaTeX macro or its arguments?"
17887 (save-match-data
17888 (org-in-regexp
17889 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17891 (defvar org-latex-fragment-image-overlays nil
17892 "List of overlays carrying the images of latex fragments.")
17893 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17895 (defun org-remove-latex-fragment-image-overlays ()
17896 "Remove all overlays with LaTeX fragment images in current buffer."
17897 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17898 (setq org-latex-fragment-image-overlays nil))
17900 (defun org-preview-latex-fragment (&optional subtree)
17901 "Preview the LaTeX fragment at point, or all locally or globally.
17902 If the cursor is in a LaTeX fragment, create the image and overlay
17903 it over the source code. If there is no fragment at point, display
17904 all fragments in the current text, from one headline to the next. With
17905 prefix SUBTREE, display all fragments in the current subtree. With a
17906 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17907 the cursor is before the first headline,
17908 display all fragments in the buffer.
17909 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17910 (interactive "P")
17911 (unless buffer-file-name
17912 (error "Can't preview LaTeX fragment in a non-file buffer"))
17913 (org-remove-latex-fragment-image-overlays)
17914 (save-excursion
17915 (save-restriction
17916 (let (beg end at msg)
17917 (cond
17918 ((or (equal subtree '(16))
17919 (not (save-excursion
17920 (re-search-backward org-outline-regexp-bol nil t))))
17921 (setq beg (point-min) end (point-max)
17922 msg "Creating images for buffer...%s"))
17923 ((equal subtree '(4))
17924 (org-back-to-heading)
17925 (setq beg (point) end (org-end-of-subtree t)
17926 msg "Creating images for subtree...%s"))
17928 (if (setq at (org-inside-LaTeX-fragment-p))
17929 (goto-char (max (point-min) (- (cdr at) 2)))
17930 (org-back-to-heading))
17931 (setq beg (point) end (progn (outline-next-heading) (point))
17932 msg (if at "Creating image...%s"
17933 "Creating images for entry...%s"))))
17934 (message msg "")
17935 (narrow-to-region beg end)
17936 (goto-char beg)
17937 (org-format-latex
17938 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17939 (file-name-nondirectory
17940 buffer-file-name)))
17941 default-directory 'overlays msg at 'forbuffer
17942 org-latex-create-formula-image-program)
17943 (message msg "done. Use `C-c C-c' to remove images.")))))
17945 (defun org-format-latex (prefix &optional dir overlays msg at
17946 forbuffer processing-type)
17947 "Replace LaTeX fragments with links to an image, and produce images.
17948 Some of the options can be changed using the variable
17949 `org-format-latex-options'."
17950 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17951 (let* ((prefixnodir (file-name-nondirectory prefix))
17952 (absprefix (expand-file-name prefix dir))
17953 (todir (file-name-directory absprefix))
17954 (opt org-format-latex-options)
17955 (optnew org-format-latex-options)
17956 (matchers (plist-get opt :matchers))
17957 (re-list org-latex-regexps)
17958 (cnt 0) txt hash link beg end re e checkdir
17959 string
17960 m n block-type block linkfile movefile ov)
17961 ;; Check the different regular expressions
17962 (while (setq e (pop re-list))
17963 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17964 block (if block-type "\n\n" ""))
17965 (when (member m matchers)
17966 (goto-char (point-min))
17967 (while (re-search-forward re nil t)
17968 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17969 (or (not overlays)
17970 (not (eq (get-char-property (match-beginning n)
17971 'org-overlay-type)
17972 'org-latex-overlay))))
17973 (cond
17974 ((eq processing-type 'verbatim))
17975 ((eq processing-type 'mathjax)
17976 ;; Prepare for MathJax processing.
17977 (setq string (match-string n))
17978 (when (member m '("$" "$1"))
17979 (save-excursion
17980 (delete-region (match-beginning n) (match-end n))
17981 (goto-char (match-beginning n))
17982 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17983 ((or (eq processing-type 'dvipng)
17984 (eq processing-type 'imagemagick))
17985 ;; Process to an image.
17986 (setq txt (match-string n)
17987 beg (match-beginning n) end (match-end n)
17988 cnt (1+ cnt))
17989 (let ((face (face-at-point))
17990 (fg (plist-get opt :foreground))
17991 (bg (plist-get opt :background))
17992 ;; Ensure full list is printed.
17993 print-length print-level)
17994 (when forbuffer
17995 ;; Get the colors from the face at point.
17996 (goto-char beg)
17997 (when (eq fg 'auto)
17998 (setq fg (face-attribute face :foreground nil 'default)))
17999 (when (eq bg 'auto)
18000 (setq bg (face-attribute face :background nil 'default)))
18001 (setq optnew (copy-sequence opt))
18002 (plist-put optnew :foreground fg)
18003 (plist-put optnew :background bg))
18004 (setq hash (sha1 (prin1-to-string
18005 (list org-format-latex-header
18006 org-latex-default-packages-alist
18007 org-latex-packages-alist
18008 org-format-latex-options
18009 forbuffer txt fg bg)))
18010 linkfile (format "%s_%s.png" prefix hash)
18011 movefile (format "%s_%s.png" absprefix hash)))
18012 (setq link (concat block "[[file:" linkfile "]]" block))
18013 (if msg (message msg cnt))
18014 (goto-char beg)
18015 (unless checkdir ; Ensure the directory exists.
18016 (setq checkdir t)
18017 (or (file-directory-p todir) (make-directory todir t)))
18018 (unless (file-exists-p movefile)
18019 (org-create-formula-image
18020 txt movefile optnew forbuffer processing-type))
18021 (if overlays
18022 (progn
18023 (mapc (lambda (o)
18024 (if (eq (overlay-get o 'org-overlay-type)
18025 'org-latex-overlay)
18026 (delete-overlay o)))
18027 (overlays-in beg end))
18028 (setq ov (make-overlay beg end))
18029 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18030 (if (featurep 'xemacs)
18031 (progn
18032 (overlay-put ov 'invisible t)
18033 (overlay-put
18034 ov 'end-glyph
18035 (make-glyph (vector 'png :file movefile))))
18036 (overlay-put
18037 ov 'display
18038 (list 'image :type 'png :file movefile :ascent 'center)))
18039 (push ov org-latex-fragment-image-overlays)
18040 (goto-char end))
18041 (delete-region beg end)
18042 (insert (org-add-props link
18043 (list 'org-latex-src
18044 (replace-regexp-in-string
18045 "\"" "" txt)
18046 'org-latex-src-embed-type
18047 (if block-type 'paragraph 'character))))))
18048 ((eq processing-type 'mathml)
18049 ;; Process to MathML
18050 (unless (save-match-data (org-format-latex-mathml-available-p))
18051 (error "LaTeX to MathML converter not configured"))
18052 (setq txt (match-string n)
18053 beg (match-beginning n) end (match-end n)
18054 cnt (1+ cnt))
18055 (if msg (message msg cnt))
18056 (goto-char beg)
18057 (delete-region beg end)
18058 (insert (org-format-latex-as-mathml
18059 txt block-type prefix dir)))
18061 (error "Unknown conversion type %s for latex fragments"
18062 processing-type)))))))))
18064 (defun org-create-math-formula (latex-frag &optional mathml-file)
18065 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18066 Use `org-latex-to-mathml-convert-command'. If the conversion is
18067 sucessful, return the portion between \"<math...> </math>\"
18068 elements otherwise return nil. When MATHML-FILE is specified,
18069 write the results in to that file. When invoked as an
18070 interactive command, prompt for LATEX-FRAG, with initial value
18071 set to the current active region and echo the results for user
18072 inspection."
18073 (interactive (list (let ((frag (when (org-region-active-p)
18074 (buffer-substring-no-properties
18075 (region-beginning) (region-end)))))
18076 (read-string "LaTeX Fragment: " frag nil frag))))
18077 (unless latex-frag (error "Invalid latex-frag"))
18078 (let* ((tmp-in-file (file-relative-name
18079 (make-temp-name (expand-file-name "ltxmathml-in"))))
18080 (ignore (write-region latex-frag nil tmp-in-file))
18081 (tmp-out-file (file-relative-name
18082 (make-temp-name (expand-file-name "ltxmathml-out"))))
18083 (cmd (format-spec
18084 org-latex-to-mathml-convert-command
18085 `((?j . ,(shell-quote-argument
18086 (expand-file-name org-latex-to-mathml-jar-file)))
18087 (?I . ,(shell-quote-argument tmp-in-file))
18088 (?o . ,(shell-quote-argument tmp-out-file)))))
18089 mathml shell-command-output)
18090 (when (org-called-interactively-p 'any)
18091 (unless (org-format-latex-mathml-available-p)
18092 (error "LaTeX to MathML converter not configured")))
18093 (message "Running %s" cmd)
18094 (setq shell-command-output (shell-command-to-string cmd))
18095 (setq mathml
18096 (when (file-readable-p tmp-out-file)
18097 (with-current-buffer (find-file-noselect tmp-out-file t)
18098 (goto-char (point-min))
18099 (when (re-search-forward
18100 (concat
18101 (regexp-quote
18102 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18103 "\\(.\\|\n\\)*"
18104 (regexp-quote "</math>")) nil t)
18105 (prog1 (match-string 0) (kill-buffer))))))
18106 (cond
18107 (mathml
18108 (setq mathml
18109 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18110 (when mathml-file
18111 (write-region mathml nil mathml-file))
18112 (when (org-called-interactively-p 'any)
18113 (message mathml)))
18114 ((message "LaTeX to MathML conversion failed")
18115 (message shell-command-output)))
18116 (delete-file tmp-in-file)
18117 (when (file-exists-p tmp-out-file)
18118 (delete-file tmp-out-file))
18119 mathml))
18121 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18122 prefix &optional dir)
18123 "Use `org-create-math-formula' but check local cache first."
18124 (let* ((absprefix (expand-file-name prefix dir))
18125 (print-length nil) (print-level nil)
18126 (formula-id (concat
18127 "formula-"
18128 (sha1
18129 (prin1-to-string
18130 (list latex-frag
18131 org-latex-to-mathml-convert-command)))))
18132 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18133 (formula-cache-dir (file-name-directory formula-cache)))
18135 (unless (file-directory-p formula-cache-dir)
18136 (make-directory formula-cache-dir t))
18138 (unless (file-exists-p formula-cache)
18139 (org-create-math-formula latex-frag formula-cache))
18141 (if (file-exists-p formula-cache)
18142 ;; Successful conversion. Return the link to MathML file.
18143 (org-add-props
18144 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18145 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18146 'org-latex-src-embed-type (if latex-frag-type
18147 'paragraph 'character)))
18148 ;; Failed conversion. Return the LaTeX fragment verbatim
18149 latex-frag)))
18151 (defun org-create-formula-image (string tofile options buffer &optional type)
18152 "Create an image from LaTeX source using dvipng or convert.
18153 This function calls either `org-create-formula-image-with-dvipng'
18154 or `org-create-formula-image-with-imagemagick' depending on the
18155 value of `org-latex-create-formula-image-program' or on the value
18156 of the optional TYPE variable.
18158 Note: ultimately these two function should be combined as they
18159 share a good deal of logic."
18160 (org-check-external-command
18161 "latex" "needed to convert LaTeX fragments to images")
18162 (funcall
18163 (case (or type org-latex-create-formula-image-program)
18164 ('dvipng
18165 (org-check-external-command
18166 "dvipng" "needed to convert LaTeX fragments to images")
18167 #'org-create-formula-image-with-dvipng)
18168 ('imagemagick
18169 (org-check-external-command
18170 "convert" "you need to install imagemagick")
18171 #'org-create-formula-image-with-imagemagick)
18172 (t (error
18173 "invalid value of `org-latex-create-formula-image-program'")))
18174 string tofile options buffer))
18176 (declare-function org-export--get-global-options "ox" (&optional backend))
18177 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18178 (defun org-create-formula--latex-header ()
18179 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18180 (org-latex-guess-inputenc
18181 (org-splice-latex-header
18182 org-format-latex-header
18183 org-latex-default-packages-alist
18184 org-latex-packages-alist t
18185 (plist-get
18186 (org-combine-plists
18187 (org-export--get-global-options 'latex)
18188 (org-export--get-inbuffer-options 'latex))
18189 :latex-header))))
18191 ;; This function borrows from Ganesh Swami's latex2png.el
18192 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18193 "This calls dvipng."
18194 (require 'ox-latex)
18195 (let* ((tmpdir (if (featurep 'xemacs)
18196 (temp-directory)
18197 temporary-file-directory))
18198 (texfilebase (make-temp-name
18199 (expand-file-name "orgtex" tmpdir)))
18200 (texfile (concat texfilebase ".tex"))
18201 (dvifile (concat texfilebase ".dvi"))
18202 (pngfile (concat texfilebase ".png"))
18203 (fnh (if (featurep 'xemacs)
18204 (font-height (face-font 'default))
18205 (face-attribute 'default :height nil)))
18206 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18207 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18208 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18209 "Black"))
18210 (bg (or (plist-get options (if buffer :background :html-background))
18211 "Transparent")))
18212 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18213 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18214 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18215 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18216 (let ((latex-header (org-create-formula--latex-header)))
18217 (with-temp-file texfile
18218 (insert latex-header)
18219 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18220 (let ((dir default-directory))
18221 (condition-case nil
18222 (progn
18223 (cd tmpdir)
18224 (call-process "latex" nil nil nil texfile))
18225 (error nil))
18226 (cd dir))
18227 (if (not (file-exists-p dvifile))
18228 (progn (message "Failed to create dvi file from %s" texfile) nil)
18229 (condition-case nil
18230 (if (featurep 'xemacs)
18231 (call-process "dvipng" nil nil nil
18232 "-fg" fg "-bg" bg
18233 "-T" "tight"
18234 "-o" pngfile
18235 dvifile)
18236 (call-process "dvipng" nil nil nil
18237 "-fg" fg "-bg" bg
18238 "-D" dpi
18239 ;;"-x" scale "-y" scale
18240 "-T" "tight"
18241 "-o" pngfile
18242 dvifile))
18243 (error nil))
18244 (if (not (file-exists-p pngfile))
18245 (if org-format-latex-signal-error
18246 (error "Failed to create png file from %s" texfile)
18247 (message "Failed to create png file from %s" texfile)
18248 nil)
18249 ;; Use the requested file name and clean up
18250 (copy-file pngfile tofile 'replace)
18251 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18252 (if (file-exists-p (concat texfilebase e))
18253 (delete-file (concat texfilebase e))))
18254 pngfile))))
18256 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18257 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18258 "This calls convert, which is included into imagemagick."
18259 (require 'ox-latex)
18260 (let* ((tmpdir (if (featurep 'xemacs)
18261 (temp-directory)
18262 temporary-file-directory))
18263 (texfilebase (make-temp-name
18264 (expand-file-name "orgtex" tmpdir)))
18265 (texfile (concat texfilebase ".tex"))
18266 (pdffile (concat texfilebase ".pdf"))
18267 (pngfile (concat texfilebase ".png"))
18268 (fnh (if (featurep 'xemacs)
18269 (font-height (face-font 'default))
18270 (face-attribute 'default :height nil)))
18271 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18272 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18273 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18274 "black"))
18275 (bg (or (plist-get options (if buffer :background :html-background))
18276 "white")))
18277 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18278 (setq fg (org-latex-color-format fg)))
18279 (if (eq bg 'default) (setq bg (org-latex-color :background))
18280 (setq bg (org-latex-color-format
18281 (if (string= bg "Transparent") "white" bg))))
18282 (let ((latex-header (org-create-formula--latex-header)))
18283 (with-temp-file texfile
18284 (insert latex-header)
18285 (insert "\n\\begin{document}\n"
18286 "\\definecolor{fg}{rgb}{" fg "}\n"
18287 "\\definecolor{bg}{rgb}{" bg "}\n"
18288 "\n\\pagecolor{bg}\n"
18289 "\n{\\color{fg}\n"
18290 string
18291 "\n}\n"
18292 "\n\\end{document}\n")))
18293 (org-latex-compile texfile t)
18294 (if (not (file-exists-p pdffile))
18295 (progn (message "Failed to create pdf file from %s" texfile) nil)
18296 (condition-case nil
18297 (if (featurep 'xemacs)
18298 (call-process "convert" nil nil nil
18299 "-density" "96"
18300 "-trim"
18301 "-antialias"
18302 pdffile
18303 "-quality" "100"
18304 ;; "-sharpen" "0x1.0"
18305 pngfile)
18306 (call-process "convert" nil nil nil
18307 "-density" dpi
18308 "-trim"
18309 "-antialias"
18310 pdffile
18311 "-quality" "100"
18312 ;; "-sharpen" "0x1.0"
18313 pngfile))
18314 (error nil))
18315 (if (not (file-exists-p pngfile))
18316 (if org-format-latex-signal-error
18317 (error "Failed to create png file from %s" texfile)
18318 (message "Failed to create png file from %s" texfile)
18319 nil)
18320 ;; Use the requested file name and clean up
18321 (copy-file pngfile tofile 'replace)
18322 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18323 (if (file-exists-p (concat texfilebase e))
18324 (delete-file (concat texfilebase e))))
18325 pngfile))))
18327 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18328 "Fill a LaTeX header template TPL.
18329 In the template, the following place holders will be recognized:
18331 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18332 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18333 [PACKAGES] \\usepackage statements for PKG
18334 [NO-PACKAGES] do not include PKG
18335 [EXTRA] the string EXTRA
18336 [NO-EXTRA] do not include EXTRA
18338 For backward compatibility, if both the positive and the negative place
18339 holder is missing, the positive one (without the \"NO-\") will be
18340 assumed to be present at the end of the template.
18341 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18342 EXTRA is a string.
18343 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18344 (let (rpl (end ""))
18345 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18346 (setq rpl (if (or (match-end 1) (not def-pkg))
18347 "" (org-latex-packages-to-string def-pkg snippets-p t))
18348 tpl (replace-match rpl t t tpl))
18349 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18351 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18352 (setq rpl (if (or (match-end 1) (not pkg))
18353 "" (org-latex-packages-to-string pkg snippets-p t))
18354 tpl (replace-match rpl t t tpl))
18355 (if pkg (setq end
18356 (concat end "\n"
18357 (org-latex-packages-to-string pkg snippets-p)))))
18359 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18360 (setq rpl (if (or (match-end 1) (not extra))
18361 "" (concat extra "\n"))
18362 tpl (replace-match rpl t t tpl))
18363 (if (and extra (string-match "\\S-" extra))
18364 (setq end (concat end "\n" extra))))
18366 (if (string-match "\\S-" end)
18367 (concat tpl "\n" end)
18368 tpl)))
18370 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18371 "Turn an alist of packages into a string with the \\usepackage macros."
18372 (setq pkg (mapconcat (lambda(p)
18373 (cond
18374 ((stringp p) p)
18375 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18376 (format "%% Package %s omitted" (cadr p)))
18377 ((equal "" (car p))
18378 (format "\\usepackage{%s}" (cadr p)))
18380 (format "\\usepackage[%s]{%s}"
18381 (car p) (cadr p)))))
18383 "\n"))
18384 (if newline (concat pkg "\n") pkg))
18386 (defun org-dvipng-color (attr)
18387 "Return a RGB color specification for dvipng."
18388 (apply 'format "rgb %s %s %s"
18389 (mapcar 'org-normalize-color
18390 (if (featurep 'xemacs)
18391 (color-rgb-components
18392 (face-property 'default
18393 (cond ((eq attr :foreground) 'foreground)
18394 ((eq attr :background) 'background))))
18395 (color-values (face-attribute 'default attr nil))))))
18397 (defun org-dvipng-color-format (color-name)
18398 "Convert COLOR-NAME to a RGB color value for dvipng."
18399 (apply 'format "rgb %s %s %s"
18400 (mapcar 'org-normalize-color
18401 (color-values color-name))))
18403 (defun org-latex-color (attr)
18404 "Return a RGB color for the LaTeX color package."
18405 (apply 'format "%s,%s,%s"
18406 (mapcar 'org-normalize-color
18407 (if (featurep 'xemacs)
18408 (color-rgb-components
18409 (face-property 'default
18410 (cond ((eq attr :foreground) 'foreground)
18411 ((eq attr :background) 'background))))
18412 (color-values (face-attribute 'default attr nil))))))
18414 (defun org-latex-color-format (color-name)
18415 "Convert COLOR-NAME to a RGB color value."
18416 (apply 'format "%s,%s,%s"
18417 (mapcar 'org-normalize-color
18418 (color-values color-name))))
18420 (defun org-normalize-color (value)
18421 "Return string to be used as color value for an RGB component."
18422 (format "%g" (/ value 65535.0)))
18426 ;; Image display
18428 (defvar org-inline-image-overlays nil)
18429 (make-variable-buffer-local 'org-inline-image-overlays)
18431 (defun org-toggle-inline-images (&optional include-linked)
18432 "Toggle the display of inline images.
18433 INCLUDE-LINKED is passed to `org-display-inline-images'."
18434 (interactive "P")
18435 (if org-inline-image-overlays
18436 (progn
18437 (org-remove-inline-images)
18438 (message "Inline image display turned off"))
18439 (org-display-inline-images include-linked)
18440 (if (and (org-called-interactively-p)
18441 org-inline-image-overlays)
18442 (message "%d images displayed inline"
18443 (length org-inline-image-overlays))
18444 (message "No images to display inline"))))
18446 (defun org-redisplay-inline-images ()
18447 "Refresh the display of inline images."
18448 (interactive)
18449 (if (not org-inline-image-overlays)
18450 (org-toggle-inline-images)
18451 (org-toggle-inline-images)
18452 (org-toggle-inline-images)))
18454 (defun org-display-inline-images (&optional include-linked refresh beg end)
18455 "Display inline images.
18456 Normally only links without a description part are inlined, because this
18457 is how it will work for export. When INCLUDE-LINKED is set, also links
18458 with a description part will be inlined. This can be nice for a quick
18459 look at those images, but it does not reflect what exported files will look
18460 like.
18461 When REFRESH is set, refresh existing images between BEG and END.
18462 This will create new image displays only if necessary.
18463 BEG and END default to the buffer boundaries."
18464 (interactive "P")
18465 (unless refresh
18466 (org-remove-inline-images)
18467 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18468 (save-excursion
18469 (save-restriction
18470 (widen)
18471 (setq beg (or beg (point-min)) end (or end (point-max)))
18472 (goto-char beg)
18473 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18474 (substring (org-image-file-name-regexp) 0 -2)
18475 "\\)\\]" (if include-linked "" "\\]")))
18476 old file ov img type attrwidth width)
18477 (while (re-search-forward re end t)
18478 (setq old (get-char-property-and-overlay (match-beginning 1)
18479 'org-image-overlay)
18480 file (expand-file-name
18481 (concat (or (match-string 3) "") (match-string 4))))
18482 (when (image-type-available-p 'imagemagick)
18483 (setq attrwidth (if (or (listp org-image-actual-width)
18484 (null org-image-actual-width))
18485 (save-excursion
18486 (save-match-data
18487 (when (re-search-backward
18488 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18489 (save-excursion
18490 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18491 (string-to-number (match-string 1))))))
18492 width (cond ((eq org-image-actual-width t) nil)
18493 ((null org-image-actual-width) attrwidth)
18494 ((numberp org-image-actual-width)
18495 org-image-actual-width)
18496 ((listp org-image-actual-width)
18497 (or attrwidth (car org-image-actual-width))))
18498 type (if width 'imagemagick)))
18499 (when (file-exists-p file)
18500 (if (and (car-safe old) refresh)
18501 (image-refresh (overlay-get (cdr old) 'display))
18502 (setq img (save-match-data (create-image file type nil :width width)))
18503 (when img
18504 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18505 (overlay-put ov 'display img)
18506 (overlay-put ov 'face 'default)
18507 (overlay-put ov 'org-image-overlay t)
18508 (overlay-put ov 'modification-hooks
18509 (list 'org-display-inline-remove-overlay))
18510 (push ov org-inline-image-overlays)))))))))
18512 (define-obsolete-function-alias
18513 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18515 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18516 "Remove inline-display overlay if a corresponding region is modified."
18517 (let ((inhibit-modification-hooks t))
18518 (when (and ov after)
18519 (delete ov org-inline-image-overlays)
18520 (delete-overlay ov))))
18522 (defun org-remove-inline-images ()
18523 "Remove inline display of images."
18524 (interactive)
18525 (mapc 'delete-overlay org-inline-image-overlays)
18526 (setq org-inline-image-overlays nil))
18528 ;;;; Key bindings
18530 ;; Outline functions from `outline-mode-prefix-map'
18531 ;; that can be remapped in Org:
18532 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18533 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18534 (define-key org-mode-map [remap outline-forward-same-level]
18535 'org-forward-heading-same-level)
18536 (define-key org-mode-map [remap outline-backward-same-level]
18537 'org-backward-heading-same-level)
18538 (define-key org-mode-map [remap show-branches]
18539 'org-kill-note-or-show-branches)
18540 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18541 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18542 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18544 ;; Outline functions from `outline-mode-prefix-map' that can not
18545 ;; be remapped in Org:
18547 ;; - the column "key binding" shows whether the Outline function is still
18548 ;; available in Org mode on the same key that it has been bound to in
18549 ;; Outline mode:
18550 ;; - "overridden": key used for a different functionality in Org mode
18551 ;; - else: key still bound to the same Outline function in Org mode
18553 ;; | Outline function | key binding | Org replacement |
18554 ;; |------------------------------------+-------------+-----------------------|
18555 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18556 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18557 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18558 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18559 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18560 ;; | `show-entry' | overridden | no replacement |
18561 ;; | `show-children' | `C-c C-i' | visibility cycling |
18562 ;; | `show-branches' | `C-c C-k' | still same function |
18563 ;; | `show-subtree' | overridden | visibility cycling |
18564 ;; | `show-all' | overridden | no replacement |
18565 ;; | `hide-subtree' | overridden | visibility cycling |
18566 ;; | `hide-body' | overridden | no replacement |
18567 ;; | `hide-entry' | overridden | visibility cycling |
18568 ;; | `hide-leaves' | overridden | no replacement |
18569 ;; | `hide-sublevels' | overridden | no replacement |
18570 ;; | `hide-other' | overridden | no replacement |
18572 ;; Make `C-c C-x' a prefix key
18573 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18575 ;; TAB key with modifiers
18576 (org-defkey org-mode-map "\C-i" 'org-cycle)
18577 (org-defkey org-mode-map [(tab)] 'org-cycle)
18578 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18579 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18580 ;; The following line is necessary under Suse GNU/Linux
18581 (unless (featurep 'xemacs)
18582 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18583 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18584 (define-key org-mode-map [backtab] 'org-shifttab)
18586 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18587 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18588 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18590 ;; Cursor keys with modifiers
18591 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18592 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18593 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18594 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18596 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18597 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18598 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18599 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18601 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18602 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18603 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18604 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18606 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18607 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18608 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18609 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18611 ;; Babel keys
18612 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18613 (mapc (lambda (pair)
18614 (define-key org-babel-map (car pair) (cdr pair)))
18615 org-babel-key-bindings)
18617 ;;; Extra keys for tty access.
18618 ;; We only set them when really needed because otherwise the
18619 ;; menus don't show the simple keys
18621 (when (or org-use-extra-keys
18622 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18623 (not window-system))
18624 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18625 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18626 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18627 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18628 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18629 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18630 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18631 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18632 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18633 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18634 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18635 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18636 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18637 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18638 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18639 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18640 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18641 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18642 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18643 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18644 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18645 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18646 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18647 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18648 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18649 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18650 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18651 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18653 ;; All the other keys
18655 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18656 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18657 (if (boundp 'narrow-map)
18658 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18659 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18660 (if (boundp 'narrow-map)
18661 (org-defkey narrow-map "b" 'org-narrow-to-block)
18662 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18663 (if (boundp 'narrow-map)
18664 (org-defkey narrow-map "e" 'org-narrow-to-element)
18665 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18666 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18667 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18668 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18669 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18670 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18671 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18672 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18673 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18674 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18675 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18676 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18677 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18678 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18679 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18680 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18681 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18682 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18683 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18684 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18685 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18686 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18687 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18688 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18689 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18690 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18691 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18692 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18693 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18694 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18695 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18696 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18697 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18698 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18699 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18700 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18701 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18702 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18703 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18704 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18705 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18706 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18707 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18708 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18709 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18710 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18711 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18712 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18713 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18714 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18715 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18716 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18717 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18718 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18719 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18720 (org-defkey org-mode-map "\C-c^" 'org-sort)
18721 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18722 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18723 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18724 (org-defkey org-mode-map "\C-m" 'org-return)
18725 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18726 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18727 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18728 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18729 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18730 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18731 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18732 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18733 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18734 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18735 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18736 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18737 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18738 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18739 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18740 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18741 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18742 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18743 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18744 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18745 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18746 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18747 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18749 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18750 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18751 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18753 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18754 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18755 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18756 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18757 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18758 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18759 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18760 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18761 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18762 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18763 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18764 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18765 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18766 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18767 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18768 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18769 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18770 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18771 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18772 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18773 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18774 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18775 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18777 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18778 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18779 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18780 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18781 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18783 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18785 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18787 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18788 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18790 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18793 (when (featurep 'xemacs)
18794 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18797 (defconst org-speed-commands-default
18799 ("Outline Navigation")
18800 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18801 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18802 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18803 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18804 ("F" . org-next-block)
18805 ("B" . org-previous-block)
18806 ("u" . (org-speed-move-safe 'outline-up-heading))
18807 ("j" . org-goto)
18808 ("g" . (org-refile t))
18809 ("Outline Visibility")
18810 ("c" . org-cycle)
18811 ("C" . org-shifttab)
18812 (" " . org-display-outline-path)
18813 ("=" . org-columns)
18814 ("Outline Structure Editing")
18815 ("U" . org-shiftmetaup)
18816 ("D" . org-shiftmetadown)
18817 ("r" . org-metaright)
18818 ("l" . org-metaleft)
18819 ("R" . org-shiftmetaright)
18820 ("L" . org-shiftmetaleft)
18821 ("i" . (progn (forward-char 1) (call-interactively
18822 'org-insert-heading-respect-content)))
18823 ("^" . org-sort)
18824 ("w" . org-refile)
18825 ("a" . org-archive-subtree-default-with-confirmation)
18826 ("@" . org-mark-subtree)
18827 ("#" . org-toggle-comment)
18828 ("Clock Commands")
18829 ("I" . org-clock-in)
18830 ("O" . org-clock-out)
18831 ("Meta Data Editing")
18832 ("t" . org-todo)
18833 ("," . (org-priority))
18834 ("0" . (org-priority ?\ ))
18835 ("1" . (org-priority ?A))
18836 ("2" . (org-priority ?B))
18837 ("3" . (org-priority ?C))
18838 (":" . org-set-tags-command)
18839 ("e" . org-set-effort)
18840 ("E" . org-inc-effort)
18841 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18842 (org-entry-put (point) "APPT_WARNTIME" m)))
18843 ("Agenda Views etc")
18844 ("v" . org-agenda)
18845 ("/" . org-sparse-tree)
18846 ("Misc")
18847 ("o" . org-open-at-point)
18848 ("?" . org-speed-command-help)
18849 ("<" . (org-agenda-set-restriction-lock 'subtree))
18850 (">" . (org-agenda-remove-restriction-lock))
18852 "The default speed commands.")
18854 (defun org-print-speed-command (e)
18855 (if (> (length (car e)) 1)
18856 (progn
18857 (princ "\n")
18858 (princ (car e))
18859 (princ "\n")
18860 (princ (make-string (length (car e)) ?-))
18861 (princ "\n"))
18862 (princ (car e))
18863 (princ " ")
18864 (if (symbolp (cdr e))
18865 (princ (symbol-name (cdr e)))
18866 (prin1 (cdr e)))
18867 (princ "\n")))
18869 (defun org-speed-command-help ()
18870 "Show the available speed commands."
18871 (interactive)
18872 (if (not org-use-speed-commands)
18873 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18874 (with-output-to-temp-buffer "*Help*"
18875 (princ "User-defined Speed commands\n===========================\n")
18876 (mapc 'org-print-speed-command org-speed-commands-user)
18877 (princ "\n")
18878 (princ "Built-in Speed commands\n=======================\n")
18879 (mapc 'org-print-speed-command org-speed-commands-default))
18880 (with-current-buffer "*Help*"
18881 (setq truncate-lines t))))
18883 (defun org-speed-move-safe (cmd)
18884 "Execute CMD, but make sure that the cursor always ends up in a headline.
18885 If not, return to the original position and throw an error."
18886 (interactive)
18887 (let ((pos (point)))
18888 (call-interactively cmd)
18889 (unless (and (bolp) (org-at-heading-p))
18890 (goto-char pos)
18891 (error "Boundary reached while executing %s" cmd))))
18893 (defvar org-self-insert-command-undo-counter 0)
18895 (defvar org-table-auto-blank-field) ; defined in org-table.el
18896 (defvar org-speed-command nil)
18898 (define-obsolete-function-alias
18899 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18901 (defun org-speed-command-activate (keys)
18902 "Hook for activating single-letter speed commands.
18903 `org-speed-commands-default' specifies a minimal command set.
18904 Use `org-speed-commands-user' for further customization."
18905 (when (or (and (bolp) (looking-at org-outline-regexp))
18906 (and (functionp org-use-speed-commands)
18907 (funcall org-use-speed-commands)))
18908 (cdr (assoc keys (append org-speed-commands-user
18909 org-speed-commands-default)))))
18911 (define-obsolete-function-alias
18912 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18914 (defun org-babel-speed-command-activate (keys)
18915 "Hook for activating single-letter code block commands."
18916 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18917 (cdr (assoc keys org-babel-key-bindings))))
18919 (defcustom org-speed-command-hook
18920 '(org-speed-command-default-hook org-babel-speed-command-hook)
18921 "Hook for activating speed commands at strategic locations.
18922 Hook functions are called in sequence until a valid handler is
18923 found.
18925 Each hook takes a single argument, a user-pressed command key
18926 which is also a `self-insert-command' from the global map.
18928 Within the hook, examine the cursor position and the command key
18929 and return nil or a valid handler as appropriate. Handler could
18930 be one of an interactive command, a function, or a form.
18932 Set `org-use-speed-commands' to non-nil value to enable this
18933 hook. The default setting is `org-speed-command-activate'."
18934 :group 'org-structure
18935 :version "24.1"
18936 :type 'hook)
18938 (defun org-self-insert-command (N)
18939 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18940 If the cursor is in a table looking at whitespace, the whitespace is
18941 overwritten, and the table is not marked as requiring realignment."
18942 (interactive "p")
18943 (org-check-before-invisible-edit 'insert)
18944 (cond
18945 ((and org-use-speed-commands
18946 (setq org-speed-command
18947 (run-hook-with-args-until-success
18948 'org-speed-command-hook (this-command-keys))))
18949 (cond
18950 ((commandp org-speed-command)
18951 (setq this-command org-speed-command)
18952 (call-interactively org-speed-command))
18953 ((functionp org-speed-command)
18954 (funcall org-speed-command))
18955 ((and org-speed-command (listp org-speed-command))
18956 (eval org-speed-command))
18957 (t (let (org-use-speed-commands)
18958 (call-interactively 'org-self-insert-command)))))
18959 ((and
18960 (org-table-p)
18961 (progn
18962 ;; check if we blank the field, and if that triggers align
18963 (and (featurep 'org-table) org-table-auto-blank-field
18964 (member last-command
18965 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18966 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18967 ;; got extra space, this field does not determine column width
18968 (let (org-table-may-need-update) (org-table-blank-field))
18969 ;; no extra space, this field may determine column width
18970 (org-table-blank-field)))
18972 (eq N 1)
18973 (looking-at "[^|\n]* |"))
18974 (let (org-table-may-need-update)
18975 (goto-char (1- (match-end 0)))
18976 (backward-delete-char 1)
18977 (goto-char (match-beginning 0))
18978 (self-insert-command N)))
18980 (setq org-table-may-need-update t)
18981 (self-insert-command N)
18982 (org-fix-tags-on-the-fly)
18983 (if org-self-insert-cluster-for-undo
18984 (if (not (eq last-command 'org-self-insert-command))
18985 (setq org-self-insert-command-undo-counter 1)
18986 (if (>= org-self-insert-command-undo-counter 20)
18987 (setq org-self-insert-command-undo-counter 1)
18988 (and (> org-self-insert-command-undo-counter 0)
18989 buffer-undo-list (listp buffer-undo-list)
18990 (not (cadr buffer-undo-list)) ; remove nil entry
18991 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18992 (setq org-self-insert-command-undo-counter
18993 (1+ org-self-insert-command-undo-counter))))))))
18995 (defun org-check-before-invisible-edit (kind)
18996 "Check is editing if kind KIND would be dangerous with invisible text around.
18997 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18998 ;; First, try to get out of here as quickly as possible, to reduce overhead
18999 (if (and org-catch-invisible-edits
19000 (or (not (boundp 'visible-mode)) (not visible-mode))
19001 (or (get-char-property (point) 'invisible)
19002 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19003 ;; OK, we need to take a closer look
19004 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19005 (invisible-before-point (if (bobp) nil (get-char-property
19006 (1- (point)) 'invisible)))
19007 (border-and-ok-direction
19009 ;; Check if we are acting predictably before invisible text
19010 (and invisible-at-point (not invisible-before-point)
19011 (memq kind '(insert delete-backward)))
19012 ;; Check if we are acting predictably after invisible text
19013 ;; This works not well, and I have turned it off. It seems
19014 ;; better to always show and stop after invisible text.
19015 ;; (and (not invisible-at-point) invisible-before-point
19016 ;; (memq kind '(insert delete)))
19018 (when (or (memq invisible-at-point '(outline org-hide-block t))
19019 (memq invisible-before-point '(outline org-hide-block t)))
19020 (if (eq org-catch-invisible-edits 'error)
19021 (error "Editing in invisible areas is prohibited - make visible first"))
19022 (if (and org-custom-properties-overlays
19023 (y-or-n-p "Display invisible properties in this buffer? "))
19024 (org-toggle-custom-properties-visibility)
19025 ;; Make the area visible
19026 (save-excursion
19027 (if invisible-before-point
19028 (goto-char (previous-single-char-property-change
19029 (point) 'invisible)))
19030 (org-cycle))
19031 (cond
19032 ((eq org-catch-invisible-edits 'show)
19033 ;; That's it, we do the edit after showing
19034 (message
19035 "Unfolding invisible region around point before editing")
19036 (sit-for 1))
19037 ((and (eq org-catch-invisible-edits 'smart)
19038 border-and-ok-direction)
19039 (message "Unfolding invisible region around point before editing"))
19041 ;; Don't do the edit, make the user repeat it in full visibility
19042 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19044 (defun org-fix-tags-on-the-fly ()
19045 (when (and (equal (char-after (point-at-bol)) ?*)
19046 (org-at-heading-p))
19047 (org-align-tags-here org-tags-column)))
19049 (defun org-delete-backward-char (N)
19050 "Like `delete-backward-char', insert whitespace at field end in tables.
19051 When deleting backwards, in tables this function will insert whitespace in
19052 front of the next \"|\" separator, to keep the table aligned. The table will
19053 still be marked for re-alignment if the field did fill the entire column,
19054 because, in this case the deletion might narrow the column."
19055 (interactive "p")
19056 (save-match-data
19057 (org-check-before-invisible-edit 'delete-backward)
19058 (if (and (org-table-p)
19059 (eq N 1)
19060 (string-match "|" (buffer-substring (point-at-bol) (point)))
19061 (looking-at ".*?|"))
19062 (let ((pos (point))
19063 (noalign (looking-at "[^|\n\r]* |"))
19064 (c org-table-may-need-update))
19065 (backward-delete-char N)
19066 (if (not overwrite-mode)
19067 (progn
19068 (skip-chars-forward "^|")
19069 (insert " ")
19070 (goto-char (1- pos))))
19071 ;; noalign: if there were two spaces at the end, this field
19072 ;; does not determine the width of the column.
19073 (if noalign (setq org-table-may-need-update c)))
19074 (backward-delete-char N)
19075 (org-fix-tags-on-the-fly))))
19077 (defun org-delete-char (N)
19078 "Like `delete-char', but insert whitespace at field end in tables.
19079 When deleting characters, in tables this function will insert whitespace in
19080 front of the next \"|\" separator, to keep the table aligned. The table will
19081 still be marked for re-alignment if the field did fill the entire column,
19082 because, in this case the deletion might narrow the column."
19083 (interactive "p")
19084 (save-match-data
19085 (org-check-before-invisible-edit 'delete)
19086 (if (and (org-table-p)
19087 (not (bolp))
19088 (not (= (char-after) ?|))
19089 (eq N 1))
19090 (if (looking-at ".*?|")
19091 (let ((pos (point))
19092 (noalign (looking-at "[^|\n\r]* |"))
19093 (c org-table-may-need-update))
19094 (replace-match (concat
19095 (substring (match-string 0) 1 -1)
19096 " |"))
19097 (goto-char pos)
19098 ;; noalign: if there were two spaces at the end, this field
19099 ;; does not determine the width of the column.
19100 (if noalign (setq org-table-may-need-update c)))
19101 (delete-char N))
19102 (delete-char N)
19103 (org-fix-tags-on-the-fly))))
19105 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19106 (put 'org-self-insert-command 'delete-selection t)
19107 (put 'orgtbl-self-insert-command 'delete-selection t)
19108 (put 'org-delete-char 'delete-selection 'supersede)
19109 (put 'org-delete-backward-char 'delete-selection 'supersede)
19110 (put 'org-yank 'delete-selection 'yank)
19112 ;; Make `flyspell-mode' delay after some commands
19113 (put 'org-self-insert-command 'flyspell-delayed t)
19114 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19115 (put 'org-delete-char 'flyspell-delayed t)
19116 (put 'org-delete-backward-char 'flyspell-delayed t)
19118 ;; Make pabbrev-mode expand after org-mode commands
19119 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19120 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19122 ;; How to do this: Measure non-white length of current string
19123 ;; If equal to column width, we should realign.
19125 (defun org-remap (map &rest commands)
19126 "In MAP, remap the functions given in COMMANDS.
19127 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19128 (let (new old)
19129 (while commands
19130 (setq old (pop commands) new (pop commands))
19131 (if (fboundp 'command-remapping)
19132 (org-defkey map (vector 'remap old) new)
19133 (substitute-key-definition old new map global-map)))))
19135 (defun org-transpose-words ()
19136 "Transpose words for Org.
19137 This uses the `org-mode-transpose-word-syntax-table' syntax
19138 table, which interprets characters in `org-emphasis-alist' as
19139 word constituants."
19140 (interactive)
19141 (with-syntax-table org-mode-transpose-word-syntax-table
19142 (call-interactively 'transpose-words)))
19143 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19145 (when (eq org-enable-table-editor 'optimized)
19146 ;; If the user wants maximum table support, we need to hijack
19147 ;; some standard editing functions
19148 (org-remap org-mode-map
19149 'self-insert-command 'org-self-insert-command
19150 'delete-char 'org-delete-char
19151 'delete-backward-char 'org-delete-backward-char)
19152 (org-defkey org-mode-map "|" 'org-force-self-insert))
19154 (defvar org-ctrl-c-ctrl-c-hook nil
19155 "Hook for functions attaching themselves to `C-c C-c'.
19157 This can be used to add additional functionality to the C-c C-c
19158 key which executes context-dependent commands. This hook is run
19159 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19160 run after the last test.
19162 Each function will be called with no arguments. The function
19163 must check if the context is appropriate for it to act. If yes,
19164 it should do its thing and then return a non-nil value. If the
19165 context is wrong, just do nothing and return nil.")
19167 (defvar org-ctrl-c-ctrl-c-final-hook nil
19168 "Hook for functions attaching themselves to `C-c C-c'.
19170 This can be used to add additional functionality to the C-c C-c
19171 key which executes context-dependent commands. This hook is run
19172 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19173 before the first test.
19175 Each function will be called with no arguments. The function
19176 must check if the context is appropriate for it to act. If yes,
19177 it should do its thing and then return a non-nil value. If the
19178 context is wrong, just do nothing and return nil.")
19180 (defvar org-tab-first-hook nil
19181 "Hook for functions to attach themselves to TAB.
19182 See `org-ctrl-c-ctrl-c-hook' for more information.
19183 This hook runs as the first action when TAB is pressed, even before
19184 `org-cycle' messes around with the `outline-regexp' to cater for
19185 inline tasks and plain list item folding.
19186 If any function in this hook returns t, any other actions that
19187 would have been caused by TAB (such as table field motion or visibility
19188 cycling) will not occur.")
19190 (defvar org-tab-after-check-for-table-hook nil
19191 "Hook for functions to attach themselves to TAB.
19192 See `org-ctrl-c-ctrl-c-hook' for more information.
19193 This hook runs after it has been established that the cursor is not in a
19194 table, but before checking if the cursor is in a headline or if global cycling
19195 should be done.
19196 If any function in this hook returns t, not other actions like visibility
19197 cycling will be done.")
19199 (defvar org-tab-after-check-for-cycling-hook nil
19200 "Hook for functions to attach themselves to TAB.
19201 See `org-ctrl-c-ctrl-c-hook' for more information.
19202 This hook runs after it has been established that not table field motion and
19203 not visibility should be done because of current context. This is probably
19204 the place where a package like yasnippets can hook in.")
19206 (defvar org-tab-before-tab-emulation-hook nil
19207 "Hook for functions to attach themselves to TAB.
19208 See `org-ctrl-c-ctrl-c-hook' for more information.
19209 This hook runs after every other options for TAB have been exhausted, but
19210 before indentation and \t insertion takes place.")
19212 (defvar org-metaleft-hook nil
19213 "Hook for functions attaching themselves to `M-left'.
19214 See `org-ctrl-c-ctrl-c-hook' for more information.")
19215 (defvar org-metaright-hook nil
19216 "Hook for functions attaching themselves to `M-right'.
19217 See `org-ctrl-c-ctrl-c-hook' for more information.")
19218 (defvar org-metaup-hook nil
19219 "Hook for functions attaching themselves to `M-up'.
19220 See `org-ctrl-c-ctrl-c-hook' for more information.")
19221 (defvar org-metadown-hook nil
19222 "Hook for functions attaching themselves to `M-down'.
19223 See `org-ctrl-c-ctrl-c-hook' for more information.")
19224 (defvar org-shiftmetaleft-hook nil
19225 "Hook for functions attaching themselves to `M-S-left'.
19226 See `org-ctrl-c-ctrl-c-hook' for more information.")
19227 (defvar org-shiftmetaright-hook nil
19228 "Hook for functions attaching themselves to `M-S-right'.
19229 See `org-ctrl-c-ctrl-c-hook' for more information.")
19230 (defvar org-shiftmetaup-hook nil
19231 "Hook for functions attaching themselves to `M-S-up'.
19232 See `org-ctrl-c-ctrl-c-hook' for more information.")
19233 (defvar org-shiftmetadown-hook nil
19234 "Hook for functions attaching themselves to `M-S-down'.
19235 See `org-ctrl-c-ctrl-c-hook' for more information.")
19236 (defvar org-metareturn-hook nil
19237 "Hook for functions attaching themselves to `M-RET'.
19238 See `org-ctrl-c-ctrl-c-hook' for more information.")
19239 (defvar org-shiftup-hook nil
19240 "Hook for functions attaching themselves to `S-up'.
19241 See `org-ctrl-c-ctrl-c-hook' for more information.")
19242 (defvar org-shiftup-final-hook nil
19243 "Hook for functions attaching themselves to `S-up'.
19244 This one runs after all other options except shift-select have been excluded.
19245 See `org-ctrl-c-ctrl-c-hook' for more information.")
19246 (defvar org-shiftdown-hook nil
19247 "Hook for functions attaching themselves to `S-down'.
19248 See `org-ctrl-c-ctrl-c-hook' for more information.")
19249 (defvar org-shiftdown-final-hook nil
19250 "Hook for functions attaching themselves to `S-down'.
19251 This one runs after all other options except shift-select have been excluded.
19252 See `org-ctrl-c-ctrl-c-hook' for more information.")
19253 (defvar org-shiftleft-hook nil
19254 "Hook for functions attaching themselves to `S-left'.
19255 See `org-ctrl-c-ctrl-c-hook' for more information.")
19256 (defvar org-shiftleft-final-hook nil
19257 "Hook for functions attaching themselves to `S-left'.
19258 This one runs after all other options except shift-select have been excluded.
19259 See `org-ctrl-c-ctrl-c-hook' for more information.")
19260 (defvar org-shiftright-hook nil
19261 "Hook for functions attaching themselves to `S-right'.
19262 See `org-ctrl-c-ctrl-c-hook' for more information.")
19263 (defvar org-shiftright-final-hook nil
19264 "Hook for functions attaching themselves to `S-right'.
19265 This one runs after all other options except shift-select have been excluded.
19266 See `org-ctrl-c-ctrl-c-hook' for more information.")
19268 (defun org-modifier-cursor-error ()
19269 "Throw an error, a modified cursor command was applied in wrong context."
19270 (error "This command is active in special context like tables, headlines or items"))
19272 (defun org-shiftselect-error ()
19273 "Throw an error because Shift-Cursor command was applied in wrong context."
19274 (if (and (boundp 'shift-select-mode) shift-select-mode)
19275 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19276 (error "This command works only in special context like headlines or timestamps")))
19278 (defun org-call-for-shift-select (cmd)
19279 (let ((this-command-keys-shift-translated t))
19280 (call-interactively cmd)))
19282 (defun org-shifttab (&optional arg)
19283 "Global visibility cycling or move to previous table field.
19284 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19285 on context.
19286 See the individual commands for more information."
19287 (interactive "P")
19288 (cond
19289 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19290 ((integerp arg)
19291 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19292 (message "Content view to level: %d" arg)
19293 (org-content (prefix-numeric-value arg2))
19294 (setq org-cycle-global-status 'overview)))
19295 (t (call-interactively 'org-global-cycle))))
19297 (defun org-shiftmetaleft ()
19298 "Promote subtree or delete table column.
19299 Calls `org-promote-subtree', `org-outdent-item-tree', or
19300 `org-table-delete-column', depending on context. See the
19301 individual commands for more information."
19302 (interactive)
19303 (cond
19304 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19305 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19306 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19307 ((if (not (org-region-active-p)) (org-at-item-p)
19308 (save-excursion (goto-char (region-beginning))
19309 (org-at-item-p)))
19310 (call-interactively 'org-outdent-item-tree))
19311 (t (org-modifier-cursor-error))))
19313 (defun org-shiftmetaright ()
19314 "Demote subtree or insert table column.
19315 Calls `org-demote-subtree', `org-indent-item-tree', or
19316 `org-table-insert-column', depending on context. See the
19317 individual commands for more information."
19318 (interactive)
19319 (cond
19320 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19321 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19322 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19323 ((if (not (org-region-active-p)) (org-at-item-p)
19324 (save-excursion (goto-char (region-beginning))
19325 (org-at-item-p)))
19326 (call-interactively 'org-indent-item-tree))
19327 (t (org-modifier-cursor-error))))
19329 (defun org-shiftmetaup (&optional arg)
19330 "Move subtree up or kill table row.
19331 Calls `org-move-subtree-up' or `org-table-kill-row' or
19332 `org-move-item-up' or `org-timestamp-up', depending on context.
19333 See the individual commands for more information."
19334 (interactive "P")
19335 (cond
19336 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19337 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19338 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19339 ((org-at-item-p) (call-interactively 'org-move-item-up))
19340 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19341 (call-interactively 'org-timestamp-up)))
19342 (t (call-interactively 'org-drag-line-backward))))
19344 (defun org-shiftmetadown (&optional arg)
19345 "Move subtree down or insert table row.
19346 Calls `org-move-subtree-down' or `org-table-insert-row' or
19347 `org-move-item-down' or `org-timestamp-up', depending on context.
19348 See the individual commands for more information."
19349 (interactive "P")
19350 (cond
19351 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19352 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19353 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19354 ((org-at-item-p) (call-interactively 'org-move-item-down))
19355 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19356 (call-interactively 'org-timestamp-down)))
19357 (t (call-interactively 'org-drag-line-forward))))
19359 (defsubst org-hidden-tree-error ()
19360 (error
19361 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19363 (defun org-metaleft (&optional arg)
19364 "Promote heading or move table column to left.
19365 Calls `org-do-promote' or `org-table-move-column', depending on context.
19366 With no specific context, calls the Emacs default `backward-word'.
19367 See the individual commands for more information."
19368 (interactive "P")
19369 (cond
19370 ((run-hook-with-args-until-success 'org-metaleft-hook))
19371 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19372 ((org-with-limited-levels
19373 (or (org-at-heading-p)
19374 (and (org-region-active-p)
19375 (save-excursion
19376 (goto-char (region-beginning))
19377 (org-at-heading-p)))))
19378 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19379 (call-interactively 'org-do-promote))
19380 ;; At an inline task.
19381 ((org-at-heading-p)
19382 (call-interactively 'org-inlinetask-promote))
19383 ((or (org-at-item-p)
19384 (and (org-region-active-p)
19385 (save-excursion
19386 (goto-char (region-beginning))
19387 (org-at-item-p))))
19388 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19389 (call-interactively 'org-outdent-item))
19390 (t (call-interactively 'backward-word))))
19392 (defun org-metaright (&optional arg)
19393 "Demote a subtree, a list item or move table column to right.
19394 In front of a drawer or a block keyword, indent it correctly.
19395 With no specific context, calls the Emacs default `forward-word'.
19396 See the individual commands for more information."
19397 (interactive "P")
19398 (cond
19399 ((run-hook-with-args-until-success 'org-metaright-hook))
19400 ((org-at-table-p) (call-interactively 'org-table-move-column))
19401 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19402 ((org-at-block-p) (call-interactively 'org-indent-block))
19403 ((org-with-limited-levels
19404 (or (org-at-heading-p)
19405 (and (org-region-active-p)
19406 (save-excursion
19407 (goto-char (region-beginning))
19408 (org-at-heading-p)))))
19409 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19410 (call-interactively 'org-do-demote))
19411 ;; At an inline task.
19412 ((org-at-heading-p)
19413 (call-interactively 'org-inlinetask-demote))
19414 ((or (org-at-item-p)
19415 (and (org-region-active-p)
19416 (save-excursion
19417 (goto-char (region-beginning))
19418 (org-at-item-p))))
19419 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19420 (call-interactively 'org-indent-item))
19421 (t (call-interactively 'forward-word))))
19423 (defun org-check-for-hidden (what)
19424 "Check if there are hidden headlines/items in the current visual line.
19425 WHAT can be either `headlines' or `items'. If the current line is
19426 an outline or item heading and it has a folded subtree below it,
19427 this function returns t, nil otherwise."
19428 (let ((re (cond
19429 ((eq what 'headlines) org-outline-regexp-bol)
19430 ((eq what 'items) (org-item-beginning-re))
19431 (t (error "This should not happen"))))
19432 beg end)
19433 (save-excursion
19434 (catch 'exit
19435 (unless (org-region-active-p)
19436 (setq beg (point-at-bol))
19437 (beginning-of-line 2)
19438 (while (and (not (eobp)) ;; this is like `next-line'
19439 (get-char-property (1- (point)) 'invisible))
19440 (beginning-of-line 2))
19441 (setq end (point))
19442 (goto-char beg)
19443 (goto-char (point-at-eol))
19444 (setq end (max end (point)))
19445 (while (re-search-forward re end t)
19446 (if (get-char-property (match-beginning 0) 'invisible)
19447 (throw 'exit t))))
19448 nil))))
19450 (defun org-metaup (&optional arg)
19451 "Move subtree up or move table row up.
19452 Calls `org-move-subtree-up' or `org-table-move-row' or
19453 `org-move-item-up', depending on context. See the individual commands
19454 for more information."
19455 (interactive "P")
19456 (cond
19457 ((run-hook-with-args-until-success 'org-metaup-hook))
19458 ((org-region-active-p)
19459 (let* ((a (min (region-beginning) (region-end)))
19460 (b (1- (max (region-beginning) (region-end))))
19461 (c (save-excursion (goto-char a)
19462 (move-beginning-of-line 0)))
19463 (d (save-excursion (goto-char a)
19464 (move-end-of-line 0) (point))))
19465 (transpose-regions a b c d)
19466 (goto-char c)))
19467 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19468 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19469 ((org-at-item-p) (call-interactively 'org-move-item-up))
19470 (t (org-drag-element-backward))))
19472 (defun org-metadown (&optional arg)
19473 "Move subtree down or move table row down.
19474 Calls `org-move-subtree-down' or `org-table-move-row' or
19475 `org-move-item-down', depending on context. See the individual
19476 commands for more information."
19477 (interactive "P")
19478 (cond
19479 ((run-hook-with-args-until-success 'org-metadown-hook))
19480 ((org-region-active-p)
19481 (let* ((a (min (region-beginning) (region-end)))
19482 (b (max (region-beginning) (region-end)))
19483 (c (save-excursion (goto-char b)
19484 (move-beginning-of-line 1)))
19485 (d (save-excursion (goto-char b)
19486 (move-end-of-line 1) (1+ (point)))))
19487 (transpose-regions a b c d)
19488 (goto-char d)))
19489 ((org-at-table-p) (call-interactively 'org-table-move-row))
19490 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19491 ((org-at-item-p) (call-interactively 'org-move-item-down))
19492 (t (org-drag-element-forward))))
19494 (defun org-shiftup (&optional arg)
19495 "Increase item in timestamp or increase priority of current headline.
19496 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19497 depending on context. See the individual commands for more information."
19498 (interactive "P")
19499 (cond
19500 ((run-hook-with-args-until-success 'org-shiftup-hook))
19501 ((and org-support-shift-select (org-region-active-p))
19502 (org-call-for-shift-select 'previous-line))
19503 ((org-at-timestamp-p t)
19504 (call-interactively (if org-edit-timestamp-down-means-later
19505 'org-timestamp-down 'org-timestamp-up)))
19506 ((and (not (eq org-support-shift-select 'always))
19507 org-enable-priority-commands
19508 (org-at-heading-p))
19509 (call-interactively 'org-priority-up))
19510 ((and (not org-support-shift-select) (org-at-item-p))
19511 (call-interactively 'org-previous-item))
19512 ((org-clocktable-try-shift 'up arg))
19513 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19514 (org-support-shift-select
19515 (org-call-for-shift-select 'previous-line))
19516 (t (org-shiftselect-error))))
19518 (defun org-shiftdown (&optional arg)
19519 "Decrease item in timestamp or decrease priority of current headline.
19520 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19521 depending on context. See the individual commands for more information."
19522 (interactive "P")
19523 (cond
19524 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19525 ((and org-support-shift-select (org-region-active-p))
19526 (org-call-for-shift-select 'next-line))
19527 ((org-at-timestamp-p t)
19528 (call-interactively (if org-edit-timestamp-down-means-later
19529 'org-timestamp-up 'org-timestamp-down)))
19530 ((and (not (eq org-support-shift-select 'always))
19531 org-enable-priority-commands
19532 (org-at-heading-p))
19533 (call-interactively 'org-priority-down))
19534 ((and (not org-support-shift-select) (org-at-item-p))
19535 (call-interactively 'org-next-item))
19536 ((org-clocktable-try-shift 'down arg))
19537 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19538 (org-support-shift-select
19539 (org-call-for-shift-select 'next-line))
19540 (t (org-shiftselect-error))))
19542 (defun org-shiftright (&optional arg)
19543 "Cycle the thing at point or in the current line, depending on context.
19544 Depending on context, this does one of the following:
19546 - switch a timestamp at point one day into the future
19547 - on a headline, switch to the next TODO keyword.
19548 - on an item, switch entire list to the next bullet type
19549 - on a property line, switch to the next allowed value
19550 - on a clocktable definition line, move time block into the future"
19551 (interactive "P")
19552 (cond
19553 ((run-hook-with-args-until-success 'org-shiftright-hook))
19554 ((and org-support-shift-select (org-region-active-p))
19555 (org-call-for-shift-select 'forward-char))
19556 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19557 ((and (not (eq org-support-shift-select 'always))
19558 (org-at-heading-p))
19559 (let ((org-inhibit-logging
19560 (not org-treat-S-cursor-todo-selection-as-state-change))
19561 (org-inhibit-blocking
19562 (not org-treat-S-cursor-todo-selection-as-state-change)))
19563 (org-call-with-arg 'org-todo 'right)))
19564 ((or (and org-support-shift-select
19565 (not (eq org-support-shift-select 'always))
19566 (org-at-item-bullet-p))
19567 (and (not org-support-shift-select) (org-at-item-p)))
19568 (org-call-with-arg 'org-cycle-list-bullet nil))
19569 ((and (not (eq org-support-shift-select 'always))
19570 (org-at-property-p))
19571 (call-interactively 'org-property-next-allowed-value))
19572 ((org-clocktable-try-shift 'right arg))
19573 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19574 (org-support-shift-select
19575 (org-call-for-shift-select 'forward-char))
19576 (t (org-shiftselect-error))))
19578 (defun org-shiftleft (&optional arg)
19579 "Cycle the thing at point or in the current line, depending on context.
19580 Depending on context, this does one of the following:
19582 - switch a timestamp at point one day into the past
19583 - on a headline, switch to the previous TODO keyword.
19584 - on an item, switch entire list to the previous bullet type
19585 - on a property line, switch to the previous allowed value
19586 - on a clocktable definition line, move time block into the past"
19587 (interactive "P")
19588 (cond
19589 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19590 ((and org-support-shift-select (org-region-active-p))
19591 (org-call-for-shift-select 'backward-char))
19592 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19593 ((and (not (eq org-support-shift-select 'always))
19594 (org-at-heading-p))
19595 (let ((org-inhibit-logging
19596 (not org-treat-S-cursor-todo-selection-as-state-change))
19597 (org-inhibit-blocking
19598 (not org-treat-S-cursor-todo-selection-as-state-change)))
19599 (org-call-with-arg 'org-todo 'left)))
19600 ((or (and org-support-shift-select
19601 (not (eq org-support-shift-select 'always))
19602 (org-at-item-bullet-p))
19603 (and (not org-support-shift-select) (org-at-item-p)))
19604 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19605 ((and (not (eq org-support-shift-select 'always))
19606 (org-at-property-p))
19607 (call-interactively 'org-property-previous-allowed-value))
19608 ((org-clocktable-try-shift 'left arg))
19609 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19610 (org-support-shift-select
19611 (org-call-for-shift-select 'backward-char))
19612 (t (org-shiftselect-error))))
19614 (defun org-shiftcontrolright ()
19615 "Switch to next TODO set."
19616 (interactive)
19617 (cond
19618 ((and org-support-shift-select (org-region-active-p))
19619 (org-call-for-shift-select 'forward-word))
19620 ((and (not (eq org-support-shift-select 'always))
19621 (org-at-heading-p))
19622 (org-call-with-arg 'org-todo 'nextset))
19623 (org-support-shift-select
19624 (org-call-for-shift-select 'forward-word))
19625 (t (org-shiftselect-error))))
19627 (defun org-shiftcontrolleft ()
19628 "Switch to previous TODO set."
19629 (interactive)
19630 (cond
19631 ((and org-support-shift-select (org-region-active-p))
19632 (org-call-for-shift-select 'backward-word))
19633 ((and (not (eq org-support-shift-select 'always))
19634 (org-at-heading-p))
19635 (org-call-with-arg 'org-todo 'previousset))
19636 (org-support-shift-select
19637 (org-call-for-shift-select 'backward-word))
19638 (t (org-shiftselect-error))))
19640 (defun org-shiftcontrolup (&optional n)
19641 "Change timestamps synchronously up in CLOCK log lines.
19642 Optional argument N tells to change by that many units."
19643 (interactive "P")
19644 (cond ((and (not org-support-shift-select)
19645 (org-at-clock-log-p)
19646 (org-at-timestamp-p t))
19647 (org-clock-timestamps-up n))
19648 (t (org-shiftselect-error))))
19650 (defun org-shiftcontroldown (&optional n)
19651 "Change timestamps synchronously down in CLOCK log lines.
19652 Optional argument N tells to change by that many units."
19653 (interactive "P")
19654 (cond ((and (not org-support-shift-select)
19655 (org-at-clock-log-p)
19656 (org-at-timestamp-p t))
19657 (org-clock-timestamps-down n))
19658 (t (org-shiftselect-error))))
19660 (defun org-ctrl-c-ret ()
19661 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19662 (interactive)
19663 (cond
19664 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19665 (t (call-interactively 'org-insert-heading))))
19667 (defun org-find-visible ()
19668 (let ((s (point)))
19669 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19670 (get-char-property s 'invisible)))
19672 (defun org-find-invisible ()
19673 (let ((s (point)))
19674 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19675 (not (get-char-property s 'invisible))))
19678 (defun org-copy-visible (beg end)
19679 "Copy the visible parts of the region."
19680 (interactive "r")
19681 (let (snippets s)
19682 (save-excursion
19683 (save-restriction
19684 (narrow-to-region beg end)
19685 (setq s (goto-char (point-min)))
19686 (while (not (= (point) (point-max)))
19687 (goto-char (org-find-invisible))
19688 (push (buffer-substring s (point)) snippets)
19689 (setq s (goto-char (org-find-visible))))))
19690 (kill-new (apply 'concat (nreverse snippets)))))
19692 (defun org-copy-special ()
19693 "Copy region in table or copy current subtree.
19694 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19695 See the individual commands for more information."
19696 (interactive)
19697 (call-interactively
19698 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19700 (defun org-cut-special ()
19701 "Cut region in table or cut current subtree.
19702 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19703 See the individual commands for more information."
19704 (interactive)
19705 (call-interactively
19706 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19708 (defun org-paste-special (arg)
19709 "Paste rectangular region into table, or past subtree relative to level.
19710 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19711 See the individual commands for more information."
19712 (interactive "P")
19713 (if (org-at-table-p)
19714 (org-table-paste-rectangle)
19715 (org-paste-subtree arg)))
19717 (defsubst org-in-fixed-width-region-p ()
19718 "Is point in a fixed-width region?"
19719 (save-match-data
19720 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19722 (defun org-edit-special (&optional arg)
19723 "Call a special editor for the element at point.
19724 When at a table, call the formula editor with `org-table-edit-formulas'.
19725 When in a source code block, call `org-edit-src-code'.
19726 When in a fixed-width region, call `org-edit-fixed-width-region'.
19727 When at an #+INCLUDE keyword, visit the included file.
19728 On a link, call `ffap' to visit the link at point.
19729 Otherwise, return a user error."
19730 (interactive)
19731 (let ((element (org-element-at-point)))
19732 (assert (not buffer-read-only) nil
19733 "Buffer is read-only: %s" (buffer-name))
19734 (case (org-element-type element)
19735 (src-block
19736 (if (not arg) (org-edit-src-code)
19737 (let* ((info (org-babel-get-src-block-info))
19738 (lang (nth 0 info))
19739 (params (nth 2 info))
19740 (session (cdr (assq :session params))))
19741 (if (not session) (org-edit-src-code)
19742 ;; At a src-block with a session and function called with
19743 ;; an ARG: switch to the buffer related to the inferior
19744 ;; process.
19745 (funcall (intern (concat "org-babel-prep-session:" lang))
19746 session params)))))
19747 (keyword
19748 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19749 (find-file
19750 (org-remove-double-quotes
19751 (car (org-split-string (org-element-property :value element)))))
19752 (user-error "No special environment to edit here")))
19753 (table
19754 (if (eq (org-element-property :type element) 'table.el)
19755 (org-edit-src-code)
19756 (call-interactively 'org-table-edit-formulas)))
19757 ;; Only Org tables contain `table-row' type elements.
19758 (table-row (call-interactively 'org-table-edit-formulas))
19759 ((example-block export-block) (org-edit-src-code))
19760 (fixed-width (org-edit-fixed-width-region))
19761 (otherwise
19762 ;; No notable element at point. Though, we may be at a link,
19763 ;; which is an object. Thus, scan deeper.
19764 (if (eq (org-element-type (org-element-context element)) 'link)
19765 (call-interactively 'ffap)
19766 (user-error "No special environment to edit here"))))))
19768 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19769 (defun org-ctrl-c-ctrl-c (&optional arg)
19770 "Set tags in headline, or update according to changed information at point.
19772 This command does many different things, depending on context:
19774 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19775 this is what we do.
19777 - If the cursor is on a statistics cookie, update it.
19779 - If the cursor is in a headline, prompt for tags and insert them
19780 into the current line, aligned to `org-tags-column'. When called
19781 with prefix arg, realign all tags in the current buffer.
19783 - If the cursor is in one of the special #+KEYWORD lines, this
19784 triggers scanning the buffer for these lines and updating the
19785 information.
19787 - If the cursor is inside a table, realign the table. This command
19788 works even if the automatic table editor has been turned off.
19790 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19791 the entire table.
19793 - If the cursor is at a footnote reference or definition, jump to
19794 the corresponding definition or references, respectively.
19796 - If the cursor is a the beginning of a dynamic block, update it.
19798 - If the current buffer is a capture buffer, close note and file it.
19800 - If the cursor is on a <<<target>>>, update radio targets and
19801 corresponding links in this buffer.
19803 - If the cursor is on a numbered item in a plain list, renumber the
19804 ordered list.
19806 - If the cursor is on a checkbox, toggle it.
19808 - If the cursor is on a code block, evaluate it. The variable
19809 `org-confirm-babel-evaluate' can be used to control prompting
19810 before code block evaluation, by default every code block
19811 evaluation requires confirmation. Code block evaluation can be
19812 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19813 (interactive "P")
19814 (cond
19815 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19816 org-occur-highlights
19817 org-latex-fragment-image-overlays)
19818 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19819 (org-remove-occur-highlights)
19820 (org-remove-latex-fragment-image-overlays)
19821 (message "Temporary highlights/overlays removed from current buffer"))
19822 ((and (local-variable-p 'org-finish-function (current-buffer))
19823 (fboundp org-finish-function))
19824 (funcall org-finish-function))
19825 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19827 (let* ((context (org-element-context)) (type (org-element-type context)))
19828 ;; Test if point is within a blank line.
19829 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19830 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19831 (user-error "C-c C-c can do nothing useful at this location"))
19832 ;; For convenience: at the first line of a paragraph on the
19833 ;; same line as an item, apply function on that item instead.
19834 (when (eq type 'paragraph)
19835 (let ((parent (org-element-property :parent context)))
19836 (when (and (eq (org-element-type parent) 'item)
19837 (= (point-at-bol) (org-element-property :begin parent)))
19838 (setq context parent type 'item))))
19839 ;; Act according to type of element or object at point.
19840 (case type
19841 (clock (org-clock-update-time-maybe))
19842 (dynamic-block
19843 (save-excursion
19844 (goto-char (org-element-property :post-affiliated context))
19845 (org-update-dblock)))
19846 (footnote-definition
19847 (goto-char (org-element-property :post-affiliated context))
19848 (call-interactively 'org-footnote-action))
19849 (footnote-reference (call-interactively 'org-footnote-action))
19850 ((headline inlinetask)
19851 (save-excursion (goto-char (org-element-property :begin context))
19852 (call-interactively 'org-set-tags)))
19853 (item
19854 ;; At an item: a double C-u set checkbox to "[-]"
19855 ;; unconditionally, whereas a single one will toggle its
19856 ;; presence. Without an universal argument, if the item
19857 ;; has a checkbox, toggle it. Otherwise repair the list.
19858 (let* ((box (org-element-property :checkbox context))
19859 (struct (org-element-property :structure context))
19860 (old-struct (copy-tree struct))
19861 (parents (org-list-parents-alist struct))
19862 (prevs (org-list-prevs-alist struct))
19863 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19864 (org-list-set-checkbox
19865 (org-element-property :begin context) struct
19866 (cond ((equal arg '(16)) "[-]")
19867 ((and (not box) (equal arg '(4))) "[ ]")
19868 ((or (not box) (equal arg '(4))) nil)
19869 ((eq box 'on) "[ ]")
19870 (t "[X]")))
19871 ;; Mimic `org-list-write-struct' but with grabbing
19872 ;; a return value from `org-list-struct-fix-box'.
19873 (org-list-struct-fix-ind struct parents 2)
19874 (org-list-struct-fix-item-end struct)
19875 (org-list-struct-fix-bul struct prevs)
19876 (org-list-struct-fix-ind struct parents)
19877 (let ((block-item
19878 (org-list-struct-fix-box struct parents prevs orderedp)))
19879 (if (and box (equal struct old-struct))
19880 (if (equal arg '(16))
19881 (message "Checkboxes already reset")
19882 (user-error "Cannot toggle this checkbox: %s"
19883 (if (eq box 'on)
19884 "all subitems checked"
19885 "unchecked subitems")))
19886 (org-list-struct-apply-struct struct old-struct)
19887 (org-update-checkbox-count-maybe))
19888 (when block-item
19889 (message "Checkboxes were removed due to empty box at line %d"
19890 (org-current-line block-item))))))
19891 (keyword
19892 (let ((org-inhibit-startup-visibility-stuff t)
19893 (org-startup-align-all-tables nil))
19894 (when (boundp 'org-table-coordinate-overlays)
19895 (mapc 'delete-overlay org-table-coordinate-overlays)
19896 (setq org-table-coordinate-overlays nil))
19897 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19898 (message "Local setup has been refreshed"))
19899 (plain-list
19900 ;; At a plain list, with a double C-u argument, set
19901 ;; checkboxes of each item to "[-]", whereas a single one
19902 ;; will toggle their presence according to the state of the
19903 ;; first item in the list. Without an argument, repair the
19904 ;; list.
19905 (let* ((begin (org-element-property :contents-begin context))
19906 (struct (org-element-property :structure context))
19907 (old-struct (copy-tree struct))
19908 (first-box (save-excursion
19909 (goto-char begin)
19910 (looking-at org-list-full-item-re)
19911 (match-string-no-properties 3)))
19912 (new-box (cond ((equal arg '(16)) "[-]")
19913 ((equal arg '(4)) (unless first-box "[ ]"))
19914 ((equal first-box "[X]") "[ ]")
19915 (t "[X]"))))
19916 (cond
19917 (arg
19918 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19919 (org-list-get-all-items
19920 begin struct (org-list-prevs-alist struct))))
19921 ((and first-box (eq (point) begin))
19922 ;; For convenience, when point is at bol on the first
19923 ;; item of the list and no argument is provided, simply
19924 ;; toggle checkbox of that item, if any.
19925 (org-list-set-checkbox begin struct new-box)))
19926 (org-list-write-struct
19927 struct (org-list-parents-alist struct) old-struct)
19928 (org-update-checkbox-count-maybe)
19929 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19930 ((property-drawer node-property)
19931 (call-interactively 'org-property-action))
19932 ((radio-target target)
19933 (call-interactively 'org-update-radio-target-regexp))
19934 (statistics-cookie
19935 (call-interactively 'org-update-statistics-cookies))
19936 ((table table-cell table-row)
19937 ;; At a table, recalculate every field and align it. Also
19938 ;; send the table if necessary. If the table has
19939 ;; a `table.el' type, just give up. At a table row or
19940 ;; cell, maybe recalculate line but always align table.
19941 (if (eq (org-element-property :type context) 'table.el)
19942 (message "Use C-c ' to edit table.el tables")
19943 (let ((org-enable-table-editor t))
19944 (if (or (eq type 'table)
19945 ;; Check if point is at a TBLFM line.
19946 (and (eq type 'table-row)
19947 (= (point) (org-element-property :end context))))
19948 (save-excursion
19949 (goto-char (org-element-property :contents-begin context))
19950 (org-call-with-arg 'org-table-recalculate (or arg t))
19951 (orgtbl-send-table 'maybe))
19952 (org-table-maybe-eval-formula)
19953 (cond (arg (call-interactively 'org-table-recalculate))
19954 ((org-table-maybe-recalculate-line))
19955 (t (org-table-align)))))))
19956 (timestamp (org-timestamp-change 0 'day))
19957 (otherwise
19958 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19959 (user-error
19960 "C-c C-c can do nothing useful at this location")))))))))
19962 (defun org-mode-restart ()
19963 "Restart Org-mode, to scan again for special lines.
19964 Also updates the keyword regular expressions."
19965 (interactive)
19966 (org-mode)
19967 (message "Org-mode restarted"))
19969 (defun org-kill-note-or-show-branches ()
19970 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19971 (interactive)
19972 (if (not org-finish-function)
19973 (progn
19974 (hide-subtree)
19975 (call-interactively 'show-branches))
19976 (let ((org-note-abort t))
19977 (funcall org-finish-function))))
19979 (defun org-return (&optional indent)
19980 "Goto next table row or insert a newline.
19981 Calls `org-table-next-row' or `newline', depending on context.
19982 See the individual commands for more information."
19983 (interactive)
19984 (let (org-ts-what)
19985 (cond
19986 ((or (bobp) (org-in-src-block-p))
19987 (if indent (newline-and-indent) (newline)))
19988 ((org-at-table-p)
19989 (org-table-justify-field-maybe)
19990 (call-interactively 'org-table-next-row))
19991 ;; when `newline-and-indent' is called within a list, make sure
19992 ;; text moved stays inside the item.
19993 ((and (org-in-item-p) indent)
19994 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19995 (progn
19996 (save-match-data (newline))
19997 (org-indent-line-to (length (match-string 0))))
19998 (let ((ind (org-get-indentation)))
19999 (newline)
20000 (if (org-looking-back org-list-end-re)
20001 (org-indent-line)
20002 (org-indent-line-to ind)))))
20003 ((and org-return-follows-link
20004 (org-at-timestamp-p t)
20005 (not (eq org-ts-what 'after)))
20006 (org-follow-timestamp-link))
20007 ((and org-return-follows-link
20008 (let ((tprop (get-text-property (point) 'face)))
20009 (or (eq tprop 'org-link)
20010 (and (listp tprop) (memq 'org-link tprop)))))
20011 (call-interactively 'org-open-at-point))
20012 ((and (org-at-heading-p)
20013 (looking-at
20014 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20015 (org-show-entry)
20016 (end-of-line 1)
20017 (newline))
20018 (t (if indent (newline-and-indent) (newline))))))
20020 (defun org-return-indent ()
20021 "Goto next table row or insert a newline and indent.
20022 Calls `org-table-next-row' or `newline-and-indent', depending on
20023 context. See the individual commands for more information."
20024 (interactive)
20025 (org-return t))
20027 (defun org-ctrl-c-star ()
20028 "Compute table, or change heading status of lines.
20029 Calls `org-table-recalculate' or `org-toggle-heading',
20030 depending on context."
20031 (interactive)
20032 (cond
20033 ((org-at-table-p)
20034 (call-interactively 'org-table-recalculate))
20036 ;; Convert all lines in region to list items
20037 (call-interactively 'org-toggle-heading))))
20039 (defun org-ctrl-c-minus ()
20040 "Insert separator line in table or modify bullet status of line.
20041 Also turns a plain line or a region of lines into list items.
20042 Calls `org-table-insert-hline', `org-toggle-item', or
20043 `org-cycle-list-bullet', depending on context."
20044 (interactive)
20045 (cond
20046 ((org-at-table-p)
20047 (call-interactively 'org-table-insert-hline))
20048 ((org-region-active-p)
20049 (call-interactively 'org-toggle-item))
20050 ((org-in-item-p)
20051 (call-interactively 'org-cycle-list-bullet))
20053 (call-interactively 'org-toggle-item))))
20055 (defun org-toggle-item (arg)
20056 "Convert headings or normal lines to items, items to normal lines.
20057 If there is no active region, only the current line is considered.
20059 If the first non blank line in the region is a headline, convert
20060 all headlines to items, shifting text accordingly.
20062 If it is an item, convert all items to normal lines.
20064 If it is normal text, change region into a list of items.
20065 With a prefix argument ARG, change the region in a single item."
20066 (interactive "P")
20067 (let ((shift-text
20068 (function
20069 ;; Shift text in current section to IND, from point to END.
20070 ;; The function leaves point to END line.
20071 (lambda (ind end)
20072 (let ((min-i 1000) (end (copy-marker end)))
20073 ;; First determine the minimum indentation (MIN-I) of
20074 ;; the text.
20075 (save-excursion
20076 (catch 'exit
20077 (while (< (point) end)
20078 (let ((i (org-get-indentation)))
20079 (cond
20080 ;; Skip blank lines and inline tasks.
20081 ((looking-at "^[ \t]*$"))
20082 ((looking-at org-outline-regexp-bol))
20083 ;; We can't find less than 0 indentation.
20084 ((zerop i) (throw 'exit (setq min-i 0)))
20085 ((< i min-i) (setq min-i i))))
20086 (forward-line))))
20087 ;; Then indent each line so that a line indented to
20088 ;; MIN-I becomes indented to IND. Ignore blank lines
20089 ;; and inline tasks in the process.
20090 (let ((delta (- ind min-i)))
20091 (while (< (point) end)
20092 (unless (or (looking-at "^[ \t]*$")
20093 (looking-at org-outline-regexp-bol))
20094 (org-indent-line-to (+ (org-get-indentation) delta)))
20095 (forward-line)))))))
20096 (skip-blanks
20097 (function
20098 ;; Return beginning of first non-blank line, starting from
20099 ;; line at POS.
20100 (lambda (pos)
20101 (save-excursion
20102 (goto-char pos)
20103 (skip-chars-forward " \r\t\n")
20104 (point-at-bol)))))
20105 beg end)
20106 ;; Determine boundaries of changes.
20107 (if (org-region-active-p)
20108 (setq beg (funcall skip-blanks (region-beginning))
20109 end (copy-marker (region-end)))
20110 (setq beg (funcall skip-blanks (point-at-bol))
20111 end (copy-marker (point-at-eol))))
20112 ;; Depending on the starting line, choose an action on the text
20113 ;; between BEG and END.
20114 (org-with-limited-levels
20115 (save-excursion
20116 (goto-char beg)
20117 (cond
20118 ;; Case 1. Start at an item: de-itemize. Note that it only
20119 ;; happens when a region is active: `org-ctrl-c-minus'
20120 ;; would call `org-cycle-list-bullet' otherwise.
20121 ((org-at-item-p)
20122 (while (< (point) end)
20123 (when (org-at-item-p)
20124 (skip-chars-forward " \t")
20125 (delete-region (point) (match-end 0)))
20126 (forward-line)))
20127 ;; Case 2. Start at an heading: convert to items.
20128 ((org-at-heading-p)
20129 (let* ((bul (org-list-bullet-string "-"))
20130 (bul-len (length bul))
20131 ;; Indentation of the first heading. It should be
20132 ;; relative to the indentation of its parent, if any.
20133 (start-ind (save-excursion
20134 (cond
20135 ((not org-adapt-indentation) 0)
20136 ((not (outline-previous-heading)) 0)
20137 (t (length (match-string 0))))))
20138 ;; Level of first heading. Further headings will be
20139 ;; compared to it to determine hierarchy in the list.
20140 (ref-level (org-reduced-level (org-outline-level))))
20141 (while (< (point) end)
20142 (let* ((level (org-reduced-level (org-outline-level)))
20143 (delta (max 0 (- level ref-level))))
20144 ;; If current headline is less indented than the first
20145 ;; one, set it as reference, in order to preserve
20146 ;; subtrees.
20147 (when (< level ref-level) (setq ref-level level))
20148 (replace-match bul t t)
20149 (org-indent-line-to (+ start-ind (* delta bul-len)))
20150 ;; Ensure all text down to END (or SECTION-END) belongs
20151 ;; to the newly created item.
20152 (let ((section-end (save-excursion
20153 (or (outline-next-heading) (point)))))
20154 (forward-line)
20155 (funcall shift-text
20156 (+ start-ind (* (1+ delta) bul-len))
20157 (min end section-end)))))))
20158 ;; Case 3. Normal line with ARG: make the first line of region
20159 ;; an item, and shift indentation of others lines to
20160 ;; set them as item's body.
20161 (arg (let* ((bul (org-list-bullet-string "-"))
20162 (bul-len (length bul))
20163 (ref-ind (org-get-indentation)))
20164 (skip-chars-forward " \t")
20165 (insert bul)
20166 (forward-line)
20167 (while (< (point) end)
20168 ;; Ensure that lines less indented than first one
20169 ;; still get included in item body.
20170 (funcall shift-text
20171 (+ ref-ind bul-len)
20172 (min end (save-excursion (or (outline-next-heading)
20173 (point)))))
20174 (forward-line))))
20175 ;; Case 4. Normal line without ARG: turn each non-item line
20176 ;; into an item.
20178 (while (< (point) end)
20179 (unless (or (org-at-heading-p) (org-at-item-p))
20180 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20181 (replace-match
20182 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20183 (forward-line))))))))
20185 (defun org-toggle-heading (&optional nstars)
20186 "Convert headings to normal text, or items or text to headings.
20187 If there is no active region, only convert the current line.
20189 With a \\[universal-argument] prefix, convert the whole list at
20190 point into heading.
20192 In a region:
20194 - If the first non blank line is a headline, remove the stars
20195 from all headlines in the region.
20197 - If it is a normal line, turn each and every normal line (i.e.,
20198 not an heading or an item) in the region into headings. If you
20199 want to convert only the first line of this region, use one
20200 universal prefix argument.
20202 - If it is a plain list item, turn all plain list items into headings.
20204 When converting a line into a heading, the number of stars is chosen
20205 such that the lines become children of the current entry. However,
20206 when a numeric prefix argument is given, its value determines the
20207 number of stars to add."
20208 (interactive "P")
20209 (let ((skip-blanks
20210 (function
20211 ;; Return beginning of first non-blank line, starting from
20212 ;; line at POS.
20213 (lambda (pos)
20214 (save-excursion
20215 (goto-char pos)
20216 (while (org-at-comment-p) (forward-line))
20217 (skip-chars-forward " \r\t\n")
20218 (point-at-bol)))))
20219 beg end toggled)
20220 ;; Determine boundaries of changes. If a universal prefix has
20221 ;; been given, put the list in a region. If region ends at a bol,
20222 ;; do not consider the last line to be in the region.
20224 (when (and current-prefix-arg (org-at-item-p))
20225 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20226 (org-mark-element))
20228 (if (org-region-active-p)
20229 (setq beg (funcall skip-blanks (region-beginning))
20230 end (copy-marker (save-excursion
20231 (goto-char (region-end))
20232 (if (bolp) (point) (point-at-eol)))))
20233 (setq beg (funcall skip-blanks (point-at-bol))
20234 end (copy-marker (point-at-eol))))
20235 ;; Ensure inline tasks don't count as headings.
20236 (org-with-limited-levels
20237 (save-excursion
20238 (goto-char beg)
20239 (cond
20240 ;; Case 1. Started at an heading: de-star headings.
20241 ((org-at-heading-p)
20242 (while (< (point) end)
20243 (when (org-at-heading-p t)
20244 (looking-at org-outline-regexp) (replace-match "")
20245 (setq toggled t))
20246 (forward-line)))
20247 ;; Case 2. Started at an item: change items into headlines.
20248 ;; One star will be added by `org-list-to-subtree'.
20249 ((org-at-item-p)
20250 (let* ((stars (make-string
20251 ;; subtract the star that will be added again by
20252 ;; `org-list-to-subtree'
20253 (if (numberp nstars) (1- nstars)
20254 (or (org-current-level) 0))
20255 ?*))
20256 (add-stars
20257 (cond (nstars "") ; stars from prefix only
20258 ((equal stars "") "") ; before first heading
20259 (org-odd-levels-only "*") ; inside heading, odd
20260 (t "")))) ; inside heading, oddeven
20261 (while (< (point) end)
20262 (when (org-at-item-p)
20263 ;; Pay attention to cases when region ends before list.
20264 (let* ((struct (org-list-struct))
20265 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20266 (save-restriction
20267 (narrow-to-region (point) list-end)
20268 (insert
20269 (org-list-to-subtree
20270 (org-list-parse-list t)
20271 '(:istart (concat stars add-stars (funcall get-stars depth))
20272 :icount (concat stars add-stars (funcall get-stars depth)))))))
20273 (setq toggled t))
20274 (forward-line))))
20275 ;; Case 3. Started at normal text: make every line an heading,
20276 ;; skipping headlines and items.
20277 (t (let* ((stars
20278 (make-string
20279 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20280 (add-stars
20281 (cond (nstars "") ; stars from prefix only
20282 ((equal stars "") "*") ; before first heading
20283 (org-odd-levels-only "**") ; inside heading, odd
20284 (t "*"))) ; inside heading, oddeven
20285 (rpl (concat stars add-stars " "))
20286 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20287 (while (< (point) (if (equal nstars '(4)) lend end))
20288 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20289 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20290 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20291 (forward-line)))))))
20292 (unless toggled (message "Cannot toggle heading from here"))))
20294 (defun org-meta-return (&optional arg)
20295 "Insert a new heading or wrap a region in a table.
20296 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20297 See the individual commands for more information."
20298 (interactive "P")
20299 (cond
20300 ((run-hook-with-args-until-success 'org-metareturn-hook))
20301 ((or (org-at-drawer-p) (org-at-property-p))
20302 (newline-and-indent))
20303 ((org-at-table-p)
20304 (call-interactively 'org-table-wrap-region))
20305 (t (call-interactively 'org-insert-heading))))
20307 ;;; Menu entries
20309 (defsubst org-in-subtree-not-table-p ()
20310 "Are we in a subtree and not in a table?"
20311 (and (not (org-before-first-heading-p))
20312 (not (org-at-table-p))))
20314 ;; Define the Org-mode menus
20315 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20316 '("Tbl"
20317 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20318 ["Next Field" org-cycle (org-at-table-p)]
20319 ["Previous Field" org-shifttab (org-at-table-p)]
20320 ["Next Row" org-return (org-at-table-p)]
20321 "--"
20322 ["Blank Field" org-table-blank-field (org-at-table-p)]
20323 ["Edit Field" org-table-edit-field (org-at-table-p)]
20324 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20325 "--"
20326 ("Column"
20327 ["Move Column Left" org-metaleft (org-at-table-p)]
20328 ["Move Column Right" org-metaright (org-at-table-p)]
20329 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20330 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20331 ("Row"
20332 ["Move Row Up" org-metaup (org-at-table-p)]
20333 ["Move Row Down" org-metadown (org-at-table-p)]
20334 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20335 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20336 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20337 "--"
20338 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20339 ("Rectangle"
20340 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20341 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20342 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20343 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20344 "--"
20345 ("Calculate"
20346 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20347 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20348 ["Edit Formulas" org-edit-special (org-at-table-p)]
20349 "--"
20350 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20351 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20352 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20353 "--"
20354 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20355 "--"
20356 ["Sum Column/Rectangle" org-table-sum
20357 (or (org-at-table-p) (org-region-active-p))]
20358 ["Which Column?" org-table-current-column (org-at-table-p)])
20359 ["Debug Formulas"
20360 org-table-toggle-formula-debugger
20361 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20362 ["Show Col/Row Numbers"
20363 org-table-toggle-coordinate-overlays
20364 :style toggle
20365 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20366 "--"
20367 ["Create" org-table-create (and (not (org-at-table-p))
20368 org-enable-table-editor)]
20369 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20370 ["Import from File" org-table-import (not (org-at-table-p))]
20371 ["Export to File" org-table-export (org-at-table-p)]
20372 "--"
20373 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20375 (easy-menu-define org-org-menu org-mode-map "Org menu"
20376 '("Org"
20377 ("Show/Hide"
20378 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20379 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20380 ["Sparse Tree..." org-sparse-tree t]
20381 ["Reveal Context" org-reveal t]
20382 ["Show All" show-all t]
20383 "--"
20384 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20385 "--"
20386 ["New Heading" org-insert-heading t]
20387 ("Navigate Headings"
20388 ["Up" outline-up-heading t]
20389 ["Next" outline-next-visible-heading t]
20390 ["Previous" outline-previous-visible-heading t]
20391 ["Next Same Level" outline-forward-same-level t]
20392 ["Previous Same Level" outline-backward-same-level t]
20393 "--"
20394 ["Jump" org-goto t])
20395 ("Edit Structure"
20396 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20397 "--"
20398 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20399 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20400 "--"
20401 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20402 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20403 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20404 "--"
20405 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20406 "--"
20407 ["Copy visible text" org-copy-visible t]
20408 "--"
20409 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20410 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20411 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20412 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20413 "--"
20414 ["Sort Region/Children" org-sort t]
20415 "--"
20416 ["Convert to odd levels" org-convert-to-odd-levels t]
20417 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20418 ("Editing"
20419 ["Emphasis..." org-emphasize t]
20420 ["Edit Source Example" org-edit-special t]
20421 "--"
20422 ["Footnote new/jump" org-footnote-action t]
20423 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20424 ("Archive"
20425 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20426 "--"
20427 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20428 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20429 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20431 "--"
20432 ("Hyperlinks"
20433 ["Store Link (Global)" org-store-link t]
20434 ["Find existing link to here" org-occur-link-in-agenda-files t]
20435 ["Insert Link" org-insert-link t]
20436 ["Follow Link" org-open-at-point t]
20437 "--"
20438 ["Next link" org-next-link t]
20439 ["Previous link" org-previous-link t]
20440 "--"
20441 ["Descriptive Links"
20442 org-toggle-link-display
20443 :style radio
20444 :selected org-descriptive-links
20446 ["Literal Links"
20447 org-toggle-link-display
20448 :style radio
20449 :selected (not org-descriptive-links)])
20450 "--"
20451 ("TODO Lists"
20452 ["TODO/DONE/-" org-todo t]
20453 ("Select keyword"
20454 ["Next keyword" org-shiftright (org-at-heading-p)]
20455 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20456 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20457 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20458 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20459 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20460 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20461 "--"
20462 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20463 :selected org-enforce-todo-dependencies :style toggle :active t]
20464 "Settings for tree at point"
20465 ["Do Children sequentially" org-toggle-ordered-property :style radio
20466 :selected (org-entry-get nil "ORDERED")
20467 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20468 ["Do Children parallel" org-toggle-ordered-property :style radio
20469 :selected (not (org-entry-get nil "ORDERED"))
20470 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20471 "--"
20472 ["Set Priority" org-priority t]
20473 ["Priority Up" org-shiftup t]
20474 ["Priority Down" org-shiftdown t]
20475 "--"
20476 ["Get news from all feeds" org-feed-update-all t]
20477 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20478 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20479 ("TAGS and Properties"
20480 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20481 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20482 "--"
20483 ["Set property" org-set-property (not (org-before-first-heading-p))]
20484 ["Column view of properties" org-columns t]
20485 ["Insert Column View DBlock" org-insert-columns-dblock t])
20486 ("Dates and Scheduling"
20487 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20488 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20489 ("Change Date"
20490 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20491 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20492 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20493 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20494 ["Compute Time Range" org-evaluate-time-range t]
20495 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20496 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20497 "--"
20498 ["Custom time format" org-toggle-time-stamp-overlays
20499 :style radio :selected org-display-custom-times]
20500 "--"
20501 ["Goto Calendar" org-goto-calendar t]
20502 ["Date from Calendar" org-date-from-calendar t]
20503 "--"
20504 ["Start/Restart Timer" org-timer-start t]
20505 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20506 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20507 ["Insert Timer String" org-timer t]
20508 ["Insert Timer Item" org-timer-item t])
20509 ("Logging work"
20510 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20511 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20512 ["Clock out" org-clock-out t]
20513 ["Clock cancel" org-clock-cancel t]
20514 "--"
20515 ["Mark as default task" org-clock-mark-default-task t]
20516 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20517 ["Goto running clock" org-clock-goto t]
20518 "--"
20519 ["Display times" org-clock-display t]
20520 ["Create clock table" org-clock-report t]
20521 "--"
20522 ["Record DONE time"
20523 (progn (setq org-log-done (not org-log-done))
20524 (message "Switching to %s will %s record a timestamp"
20525 (car org-done-keywords)
20526 (if org-log-done "automatically" "not")))
20527 :style toggle :selected org-log-done])
20528 "--"
20529 ["Agenda Command..." org-agenda t]
20530 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20531 ("File List for Agenda")
20532 ("Special views current file"
20533 ["TODO Tree" org-show-todo-tree t]
20534 ["Check Deadlines" org-check-deadlines t]
20535 ["Timeline" org-timeline t]
20536 ["Tags/Property tree" org-match-sparse-tree t])
20537 "--"
20538 ["Export/Publish..." org-export-dispatch t]
20539 ("LaTeX"
20540 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20541 :selected org-cdlatex-mode]
20542 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20543 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20544 ["Modify math symbol" org-cdlatex-math-modify
20545 (org-inside-LaTeX-fragment-p)]
20546 ["Insert citation" org-reftex-citation t]
20547 "--"
20548 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20549 "--"
20550 ("MobileOrg"
20551 ["Push Files and Views" org-mobile-push t]
20552 ["Get Captured and Flagged" org-mobile-pull t]
20553 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20554 "--"
20555 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20556 "--"
20557 ("Documentation"
20558 ["Show Version" org-version t]
20559 ["Info Documentation" org-info t])
20560 ("Customize"
20561 ["Browse Org Group" org-customize t]
20562 "--"
20563 ["Expand This Menu" org-create-customize-menu
20564 (fboundp 'customize-menu-create)])
20565 ["Send bug report" org-submit-bug-report t]
20566 "--"
20567 ("Refresh/Reload"
20568 ["Refresh setup current buffer" org-mode-restart t]
20569 ["Reload Org (after update)" org-reload t]
20570 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20573 (defun org-info (&optional node)
20574 "Read documentation for Org-mode in the info system.
20575 With optional NODE, go directly to that node."
20576 (interactive)
20577 (info (format "(org)%s" (or node ""))))
20579 ;;;###autoload
20580 (defun org-submit-bug-report ()
20581 "Submit a bug report on Org-mode via mail.
20583 Don't hesitate to report any problems or inaccurate documentation.
20585 If you don't have setup sending mail from (X)Emacs, please copy the
20586 output buffer into your mail program, as it gives us important
20587 information about your Org-mode version and configuration."
20588 (interactive)
20589 (require 'reporter)
20590 (org-load-modules-maybe)
20591 (org-require-autoloaded-modules)
20592 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20593 (reporter-submit-bug-report
20594 "emacs-orgmode@gnu.org"
20595 (org-version nil 'full)
20596 (let (list)
20597 (save-window-excursion
20598 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20599 (delete-other-windows)
20600 (erase-buffer)
20601 (insert "You are about to submit a bug report to the Org-mode mailing list.
20603 We would like to add your full Org-mode and Outline configuration to the
20604 bug report. This greatly simplifies the work of the maintainer and
20605 other experts on the mailing list.
20607 HOWEVER, some variables you have customized may contain private
20608 information. The names of customers, colleagues, or friends, might
20609 appear in the form of file names, tags, todo states, or search strings.
20610 If you answer yes to the prompt, you might want to check and remove
20611 such private information before sending the email.")
20612 (add-text-properties (point-min) (point-max) '(face org-warning))
20613 (when (yes-or-no-p "Include your Org-mode configuration ")
20614 (mapatoms
20615 (lambda (v)
20616 (and (boundp v)
20617 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20618 (or (and (symbol-value v)
20619 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20620 (and
20621 (get v 'custom-type) (get v 'standard-value)
20622 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20623 (push v list)))))
20624 (kill-buffer (get-buffer "*Warn about privacy*"))
20625 list))
20626 nil nil
20627 "Remember to cover the basics, that is, what you expected to happen and
20628 what in fact did happen. You don't know how to make a good report? See
20630 http://orgmode.org/manual/Feedback.html#Feedback
20632 Your bug report will be posted to the Org-mode mailing list.
20633 ------------------------------------------------------------------------")
20634 (save-excursion
20635 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20636 (replace-match "\\1Bug: \\3 [\\2]")))))
20639 (defun org-install-agenda-files-menu ()
20640 (let ((bl (buffer-list)))
20641 (save-excursion
20642 (while bl
20643 (set-buffer (pop bl))
20644 (if (derived-mode-p 'org-mode) (setq bl nil)))
20645 (when (derived-mode-p 'org-mode)
20646 (easy-menu-change
20647 '("Org") "File List for Agenda"
20648 (append
20649 (list
20650 ["Edit File List" (org-edit-agenda-file-list) t]
20651 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20652 ["Remove Current File from List" org-remove-file t]
20653 ["Cycle through agenda files" org-cycle-agenda-files t]
20654 ["Occur in all agenda files" org-occur-in-agenda-files t]
20655 "--")
20656 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20658 ;;;; Documentation
20660 (defun org-require-autoloaded-modules ()
20661 (interactive)
20662 (mapc 'require
20663 '(org-agenda org-archive org-attach org-clock org-colview org-id
20664 org-remember org-table org-timer)))
20666 ;;;###autoload
20667 (defun org-reload (&optional uncompiled)
20668 "Reload all org lisp files.
20669 With prefix arg UNCOMPILED, load the uncompiled versions."
20670 (interactive "P")
20671 (require 'loadhist)
20672 (let* ((org-dir (org-find-library-dir "org"))
20673 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20674 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20675 (remove-re (mapconcat 'identity
20676 (mapcar (lambda (f) (concat "^" f "$"))
20677 (list (if (featurep 'xemacs)
20678 "org-colview"
20679 "org-colview-xemacs")
20680 "org" "org-loaddefs" "org-version"))
20681 "\\|"))
20682 (feats (delete-dups
20683 (mapcar 'file-name-sans-extension
20684 (mapcar 'file-name-nondirectory
20685 (delq nil
20686 (mapcar 'feature-file
20687 features))))))
20688 (lfeat (append
20689 (sort
20690 (setq feats
20691 (delq nil (mapcar
20692 (lambda (f)
20693 (if (and (string-match feature-re f)
20694 (not (string-match remove-re f)))
20695 f nil))
20696 feats)))
20697 'string-lessp)
20698 (list "org-version" "org")))
20699 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20700 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20701 load-uncore load-misses)
20702 (setq load-misses
20703 (delq 't
20704 (mapcar (lambda (f)
20705 (or (org-load-noerror-mustsuffix (concat org-dir f))
20706 (and (string= org-dir contrib-dir)
20707 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20708 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20709 (add-to-list 'load-uncore f 'append)
20712 lfeat)))
20713 (if load-uncore
20714 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20715 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20716 (if load-misses
20717 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20718 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20719 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20721 ;;;###autoload
20722 (defun org-customize ()
20723 "Call the customize function with org as argument."
20724 (interactive)
20725 (org-load-modules-maybe)
20726 (org-require-autoloaded-modules)
20727 (customize-browse 'org))
20729 (defun org-create-customize-menu ()
20730 "Create a full customization menu for Org-mode, insert it into the menu."
20731 (interactive)
20732 (org-load-modules-maybe)
20733 (org-require-autoloaded-modules)
20734 (if (fboundp 'customize-menu-create)
20735 (progn
20736 (easy-menu-change
20737 '("Org") "Customize"
20738 `(["Browse Org group" org-customize t]
20739 "--"
20740 ,(customize-menu-create 'org)
20741 ["Set" Custom-set t]
20742 ["Save" Custom-save t]
20743 ["Reset to Current" Custom-reset-current t]
20744 ["Reset to Saved" Custom-reset-saved t]
20745 ["Reset to Standard Settings" Custom-reset-standard t]))
20746 (message "\"Org\"-menu now contains full customization menu"))
20747 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20749 ;;;; Miscellaneous stuff
20751 ;;; Generally useful functions
20753 (defun org-get-at-bol (property)
20754 "Get text property PROPERTY at beginning of line."
20755 (get-text-property (point-at-bol) property))
20757 (defun org-find-text-property-in-string (prop s)
20758 "Return the first non-nil value of property PROP in string S."
20759 (or (get-text-property 0 prop s)
20760 (get-text-property (or (next-single-property-change 0 prop s) 0)
20761 prop s)))
20763 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20764 "Display the given MESSAGE as a warning."
20765 (if (fboundp 'display-warning)
20766 (display-warning 'org message
20767 (if (featurep 'xemacs) 'warning :warning))
20768 (let ((buf (get-buffer-create "*Org warnings*")))
20769 (with-current-buffer buf
20770 (goto-char (point-max))
20771 (insert "Warning (Org): " message)
20772 (unless (bolp)
20773 (newline)))
20774 (display-buffer buf)
20775 (sit-for 0))))
20777 (defun org-eval (form)
20778 "Eval FORM and return result."
20779 (condition-case error
20780 (eval form)
20781 (error (format "%%![Error: %s]" error))))
20783 (defun org-in-clocktable-p ()
20784 "Check if the cursor is in a clocktable."
20785 (let ((pos (point)) start)
20786 (save-excursion
20787 (end-of-line 1)
20788 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20789 (setq start (match-beginning 0))
20790 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20791 (>= (match-end 0) pos)
20792 start))))
20794 (defun org-in-commented-line ()
20795 "Is point in a line starting with `#'?"
20796 (equal (char-after (point-at-bol)) ?#))
20798 (defun org-in-indented-comment-line ()
20799 "Is point in a line starting with `#' after some white space?"
20800 (save-excursion
20801 (save-match-data
20802 (goto-char (point-at-bol))
20803 (looking-at "[ \t]*#"))))
20805 (defun org-in-verbatim-emphasis ()
20806 (save-match-data
20807 (and (org-in-regexp org-emph-re 2)
20808 (>= (point) (match-beginning 3))
20809 (<= (point) (match-end 4))
20810 (member (match-string 3) '("=" "~")))))
20812 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20813 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20814 (if (and marker (marker-buffer marker)
20815 (buffer-live-p (marker-buffer marker)))
20816 (progn
20817 (org-pop-to-buffer-same-window (marker-buffer marker))
20818 (if (or (> marker (point-max)) (< marker (point-min)))
20819 (widen))
20820 (goto-char marker)
20821 (org-show-context 'org-goto))
20822 (if bookmark
20823 (bookmark-jump bookmark)
20824 (error "Cannot find location"))))
20826 (defun org-quote-csv-field (s)
20827 "Quote field for inclusion in CSV material."
20828 (if (string-match "[\",]" s)
20829 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20832 (defun org-force-self-insert (N)
20833 "Needed to enforce self-insert under remapping."
20834 (interactive "p")
20835 (self-insert-command N))
20837 (defun org-string-width (s)
20838 "Compute width of string, ignoring invisible characters.
20839 This ignores character with invisibility property `org-link', and also
20840 characters with property `org-cwidth', because these will become invisible
20841 upon the next fontification round."
20842 (let (b l)
20843 (when (or (eq t buffer-invisibility-spec)
20844 (assq 'org-link buffer-invisibility-spec))
20845 (while (setq b (text-property-any 0 (length s)
20846 'invisible 'org-link s))
20847 (setq s (concat (substring s 0 b)
20848 (substring s (or (next-single-property-change
20849 b 'invisible s) (length s)))))))
20850 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20851 (setq s (concat (substring s 0 b)
20852 (substring s (or (next-single-property-change
20853 b 'org-cwidth s) (length s))))))
20854 (setq l (string-width s) b -1)
20855 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20856 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20859 (defun org-shorten-string (s maxlength)
20860 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20861 If the string is shorter or has length MAXLENGTH, just return the
20862 original string. If it is longer, the functions finds a space in the
20863 string, breaks this string off at that locations and adds three dots
20864 as ellipsis. Including the ellipsis, the string will not be longer
20865 than MAXLENGTH. If finding a good breaking point in the string does
20866 not work, the string is just chopped off in the middle of a word
20867 if necessary."
20868 (if (<= (length s) maxlength)
20870 (let* ((n (max (- maxlength 4) 1))
20871 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20872 (if (string-match re s)
20873 (concat (match-string 1 s) "...")
20874 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20876 (defun org-get-indentation (&optional line)
20877 "Get the indentation of the current line, interpreting tabs.
20878 When LINE is given, assume it represents a line and compute its indentation."
20879 (if line
20880 (if (string-match "^ *" (org-remove-tabs line))
20881 (match-end 0))
20882 (save-excursion
20883 (beginning-of-line 1)
20884 (skip-chars-forward " \t")
20885 (current-column))))
20887 (defun org-get-string-indentation (s)
20888 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20889 (let ((n -1) (i 0) (w tab-width) c)
20890 (catch 'exit
20891 (while (< (setq n (1+ n)) (length s))
20892 (setq c (aref s n))
20893 (cond ((= c ?\ ) (setq i (1+ i)))
20894 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20895 (t (throw 'exit t)))))
20898 (defun org-remove-tabs (s &optional width)
20899 "Replace tabulators in S with spaces.
20900 Assumes that s is a single line, starting in column 0."
20901 (setq width (or width tab-width))
20902 (while (string-match "\t" s)
20903 (setq s (replace-match
20904 (make-string
20905 (- (* width (/ (+ (match-beginning 0) width) width))
20906 (match-beginning 0)) ?\ )
20907 t t s)))
20910 (defun org-fix-indentation (line ind)
20911 "Fix indentation in LINE.
20912 IND is a cons cell with target and minimum indentation.
20913 If the current indentation in LINE is smaller than the minimum,
20914 leave it alone. If it is larger than ind, set it to the target."
20915 (let* ((l (org-remove-tabs line))
20916 (i (org-get-indentation l))
20917 (i1 (car ind)) (i2 (cdr ind)))
20918 (if (>= i i2) (setq l (substring line i2)))
20919 (if (> i1 0)
20920 (concat (make-string i1 ?\ ) l)
20921 l)))
20923 (defun org-remove-indentation (code &optional n)
20924 "Remove the maximum common indentation from the lines in CODE.
20925 N may optionally be the number of spaces to remove."
20926 (with-temp-buffer
20927 (insert code)
20928 (org-do-remove-indentation n)
20929 (buffer-string)))
20931 (defun org-do-remove-indentation (&optional n)
20932 "Remove the maximum common indentation from the buffer."
20933 (untabify (point-min) (point-max))
20934 (let ((min 10000) re)
20935 (if n
20936 (setq min n)
20937 (goto-char (point-min))
20938 (while (re-search-forward "^ *[^ \n]" nil t)
20939 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20940 (unless (or (= min 0) (= min 10000))
20941 (setq re (format "^ \\{%d\\}" min))
20942 (goto-char (point-min))
20943 (while (re-search-forward re nil t)
20944 (replace-match "")
20945 (end-of-line 1))
20946 min)))
20948 (defun org-fill-template (template alist)
20949 "Find each %key of ALIST in TEMPLATE and replace it."
20950 (let ((case-fold-search nil)
20951 entry key value)
20952 (setq alist (sort (copy-sequence alist)
20953 (lambda (a b) (< (length (car a)) (length (car b))))))
20954 (while (setq entry (pop alist))
20955 (setq template
20956 (replace-regexp-in-string
20957 (concat "%" (regexp-quote (car entry)))
20958 (or (cdr entry) "") template t t)))
20959 template))
20961 (defun org-base-buffer (buffer)
20962 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20963 (if (not buffer)
20964 buffer
20965 (or (buffer-base-buffer buffer)
20966 buffer)))
20968 (defun org-trim (s)
20969 "Remove whitespace at beginning and end of string."
20970 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20971 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20974 (defun org-wrap (string &optional width lines)
20975 "Wrap string to either a number of lines, or a width in characters.
20976 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20977 that costs. If there is a word longer than WIDTH, the text is actually
20978 wrapped to the length of that word.
20979 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20980 many lines, whatever width that takes.
20981 The return value is a list of lines, without newlines at the end."
20982 (let* ((words (org-split-string string "[ \t\n]+"))
20983 (maxword (apply 'max (mapcar 'org-string-width words)))
20984 w ll)
20985 (cond (width
20986 (org-do-wrap words (max maxword width)))
20987 (lines
20988 (setq w maxword)
20989 (setq ll (org-do-wrap words maxword))
20990 (if (<= (length ll) lines)
20992 (setq ll words)
20993 (while (> (length ll) lines)
20994 (setq w (1+ w))
20995 (setq ll (org-do-wrap words w)))
20996 ll))
20997 (t (error "Cannot wrap this")))))
20999 (defun org-do-wrap (words width)
21000 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21001 (let (lines line)
21002 (while words
21003 (setq line (pop words))
21004 (while (and words (< (+ (length line) (length (car words))) width))
21005 (setq line (concat line " " (pop words))))
21006 (setq lines (push line lines)))
21007 (nreverse lines)))
21009 (defun org-split-string (string &optional separators)
21010 "Splits STRING into substrings at SEPARATORS.
21011 No empty strings are returned if there are matches at the beginning
21012 and end of string."
21013 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21014 (start 0)
21015 notfirst
21016 (list nil))
21017 (while (and (string-match rexp string
21018 (if (and notfirst
21019 (= start (match-beginning 0))
21020 (< start (length string)))
21021 (1+ start) start))
21022 (< (match-beginning 0) (length string)))
21023 (setq notfirst t)
21024 (or (eq (match-beginning 0) 0)
21025 (and (eq (match-beginning 0) (match-end 0))
21026 (eq (match-beginning 0) start))
21027 (setq list
21028 (cons (substring string start (match-beginning 0))
21029 list)))
21030 (setq start (match-end 0)))
21031 (or (eq start (length string))
21032 (setq list
21033 (cons (substring string start)
21034 list)))
21035 (nreverse list)))
21037 (defun org-quote-vert (s)
21038 "Replace \"|\" with \"\\vert\"."
21039 (while (string-match "|" s)
21040 (setq s (replace-match "\\vert" t t s)))
21043 (defun org-uuidgen-p (s)
21044 "Is S an ID created by UUIDGEN?"
21045 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21047 (defun org-in-src-block-p (&optional inside)
21048 "Whether point is in a code source block.
21049 When INSIDE is non-nil, don't consider we are within a src block
21050 when point is at #+BEGIN_SRC or #+END_SRC."
21051 (let ((case-fold-search t) ov)
21052 (or (and (setq ov (overlays-at (point)))
21053 (memq 'org-block-background
21054 (overlay-properties (car ov))))
21055 (and (not inside)
21056 (save-match-data
21057 (save-excursion
21058 (beginning-of-line)
21059 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21061 (defun org-context ()
21062 "Return a list of contexts of the current cursor position.
21063 If several contexts apply, all are returned.
21064 Each context entry is a list with a symbol naming the context, and
21065 two positions indicating start and end of the context. Possible
21066 contexts are:
21068 :headline anywhere in a headline
21069 :headline-stars on the leading stars in a headline
21070 :todo-keyword on a TODO keyword (including DONE) in a headline
21071 :tags on the TAGS in a headline
21072 :priority on the priority cookie in a headline
21073 :item on the first line of a plain list item
21074 :item-bullet on the bullet/number of a plain list item
21075 :checkbox on the checkbox in a plain list item
21076 :table in an org-mode table
21077 :table-special on a special filed in a table
21078 :table-table in a table.el table
21079 :clocktable in a clocktable
21080 :src-block in a source block
21081 :link on a hyperlink
21082 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21083 :target on a <<target>>
21084 :radio-target on a <<<radio-target>>>
21085 :latex-fragment on a LaTeX fragment
21086 :latex-preview on a LaTeX fragment with overlaid preview image
21088 This function expects the position to be visible because it uses font-lock
21089 faces as a help to recognize the following contexts: :table-special, :link,
21090 and :keyword."
21091 (let* ((f (get-text-property (point) 'face))
21092 (faces (if (listp f) f (list f)))
21093 (case-fold-search t)
21094 (p (point)) clist o)
21095 ;; First the large context
21096 (cond
21097 ((org-at-heading-p t)
21098 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21099 (when (progn
21100 (beginning-of-line 1)
21101 (looking-at org-todo-line-tags-regexp))
21102 (push (org-point-in-group p 1 :headline-stars) clist)
21103 (push (org-point-in-group p 2 :todo-keyword) clist)
21104 (push (org-point-in-group p 4 :tags) clist))
21105 (goto-char p)
21106 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21107 (if (looking-at "\\[#[A-Z0-9]\\]")
21108 (push (org-point-in-group p 0 :priority) clist)))
21110 ((org-at-item-p)
21111 (push (org-point-in-group p 2 :item-bullet) clist)
21112 (push (list :item (point-at-bol)
21113 (save-excursion (org-end-of-item) (point)))
21114 clist)
21115 (and (org-at-item-checkbox-p)
21116 (push (org-point-in-group p 0 :checkbox) clist)))
21118 ((org-at-table-p)
21119 (push (list :table (org-table-begin) (org-table-end)) clist)
21120 (if (memq 'org-formula faces)
21121 (push (list :table-special
21122 (previous-single-property-change p 'face)
21123 (next-single-property-change p 'face)) clist)))
21124 ((org-at-table-p 'any)
21125 (push (list :table-table) clist)))
21126 (goto-char p)
21128 (let ((case-fold-search t))
21129 ;; New the "medium" contexts: clocktables, source blocks
21130 (cond ((org-in-clocktable-p)
21131 (push (list :clocktable
21132 (and (or (looking-at "#\\+BEGIN: clocktable")
21133 (search-backward "#+BEGIN: clocktable" nil t))
21134 (match-beginning 0))
21135 (and (re-search-forward "#\\+END:?" nil t)
21136 (match-end 0))) clist))
21137 ((org-in-src-block-p)
21138 (push (list :src-block
21139 (and (or (looking-at "#\\+BEGIN_SRC")
21140 (search-backward "#+BEGIN_SRC" nil t))
21141 (match-beginning 0))
21142 (and (search-forward "#+END_SRC" nil t)
21143 (match-beginning 0))) clist))))
21144 (goto-char p)
21146 ;; Now the small context
21147 (cond
21148 ((org-at-timestamp-p)
21149 (push (org-point-in-group p 0 :timestamp) clist))
21150 ((memq 'org-link faces)
21151 (push (list :link
21152 (previous-single-property-change p 'face)
21153 (next-single-property-change p 'face)) clist))
21154 ((memq 'org-special-keyword faces)
21155 (push (list :keyword
21156 (previous-single-property-change p 'face)
21157 (next-single-property-change p 'face)) clist))
21158 ((org-at-target-p)
21159 (push (org-point-in-group p 0 :target) clist)
21160 (goto-char (1- (match-beginning 0)))
21161 (if (looking-at org-radio-target-regexp)
21162 (push (org-point-in-group p 0 :radio-target) clist))
21163 (goto-char p))
21164 ((setq o (car (delq nil
21165 (mapcar
21166 (lambda (x)
21167 (if (memq x org-latex-fragment-image-overlays) x))
21168 (overlays-at (point))))))
21169 (push (list :latex-fragment
21170 (overlay-start o) (overlay-end o)) clist)
21171 (push (list :latex-preview
21172 (overlay-start o) (overlay-end o)) clist))
21173 ((org-inside-LaTeX-fragment-p)
21174 ;; FIXME: positions wrong.
21175 (push (list :latex-fragment (point) (point)) clist)))
21177 (setq clist (nreverse (delq nil clist)))
21178 clist))
21180 ;; FIXME: Compare with at-regexp-p Do we need both?
21181 (defun org-in-regexp (re &optional nlines visually)
21182 "Check if point is inside a match of regexp.
21183 Normally only the current line is checked, but you can include NLINES extra
21184 lines both before and after point into the search.
21185 If VISUALLY is set, require that the cursor is not after the match but
21186 really on, so that the block visually is on the match."
21187 (catch 'exit
21188 (let ((pos (point))
21189 (eol (point-at-eol (+ 1 (or nlines 0))))
21190 (inc (if visually 1 0)))
21191 (save-excursion
21192 (beginning-of-line (- 1 (or nlines 0)))
21193 (while (re-search-forward re eol t)
21194 (if (and (<= (match-beginning 0) pos)
21195 (>= (+ inc (match-end 0)) pos))
21196 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21198 (defun org-at-regexp-p (regexp)
21199 "Is point inside a match of REGEXP in the current line?"
21200 (catch 'exit
21201 (save-excursion
21202 (let ((pos (point)) (end (point-at-eol)))
21203 (beginning-of-line 1)
21204 (while (re-search-forward regexp end t)
21205 (if (and (<= (match-beginning 0) pos)
21206 (>= (match-end 0) pos))
21207 (throw 'exit t)))
21208 nil))))
21210 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21211 "Non-nil when point is between matches of START-RE and END-RE.
21213 Also return a non-nil value when point is on one of the matches.
21215 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21216 buffer positions. Default values are the positions of headlines
21217 surrounding the point.
21219 The functions returns a cons cell whose car (resp. cdr) is the
21220 position before START-RE (resp. after END-RE)."
21221 (save-match-data
21222 (let ((pos (point))
21223 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21224 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21225 beg end)
21226 (save-excursion
21227 ;; Point is on a block when on START-RE or if START-RE can be
21228 ;; found before it...
21229 (and (or (org-at-regexp-p start-re)
21230 (re-search-backward start-re limit-up t))
21231 (setq beg (match-beginning 0))
21232 ;; ... and END-RE after it...
21233 (goto-char (match-end 0))
21234 (re-search-forward end-re limit-down t)
21235 (> (setq end (match-end 0)) pos)
21236 ;; ... without another START-RE in-between.
21237 (goto-char (match-beginning 0))
21238 (not (re-search-backward start-re (1+ beg) t))
21239 ;; Return value.
21240 (cons beg end))))))
21242 (defun org-in-block-p (names)
21243 "Non-nil when point belongs to a block whose name belongs to NAMES.
21245 NAMES is a list of strings containing names of blocks.
21247 Return first block name matched, or nil. Beware that in case of
21248 nested blocks, the returned name may not belong to the closest
21249 block from point."
21250 (save-match-data
21251 (catch 'exit
21252 (let ((case-fold-search t)
21253 (lim-up (save-excursion (outline-previous-heading)))
21254 (lim-down (save-excursion (outline-next-heading))))
21255 (mapc (lambda (name)
21256 (let ((n (regexp-quote name)))
21257 (when (org-between-regexps-p
21258 (concat "^[ \t]*#\\+begin_" n)
21259 (concat "^[ \t]*#\\+end_" n)
21260 lim-up lim-down)
21261 (throw 'exit n))))
21262 names))
21263 nil)))
21265 (defun org-occur-in-agenda-files (regexp &optional nlines)
21266 "Call `multi-occur' with buffers for all agenda files."
21267 (interactive "sOrg-files matching: \np")
21268 (let* ((files (org-agenda-files))
21269 (tnames (mapcar 'file-truename files))
21270 (extra org-agenda-text-search-extra-files)
21272 (when (eq (car extra) 'agenda-archives)
21273 (setq extra (cdr extra))
21274 (setq files (org-add-archive-files files)))
21275 (while (setq f (pop extra))
21276 (unless (member (file-truename f) tnames)
21277 (add-to-list 'files f 'append)
21278 (add-to-list 'tnames (file-truename f) 'append)))
21279 (multi-occur
21280 (mapcar (lambda (x)
21281 (with-current-buffer
21282 (or (get-file-buffer x) (find-file-noselect x))
21283 (widen)
21284 (current-buffer)))
21285 files)
21286 regexp)))
21288 (if (boundp 'occur-mode-find-occurrence-hook)
21289 ;; Emacs 23
21290 (add-hook 'occur-mode-find-occurrence-hook
21291 (lambda ()
21292 (when (derived-mode-p 'org-mode)
21293 (org-reveal))))
21294 ;; Emacs 22
21295 (defadvice occur-mode-goto-occurrence
21296 (after org-occur-reveal activate)
21297 (and (derived-mode-p 'org-mode) (org-reveal)))
21298 (defadvice occur-mode-goto-occurrence-other-window
21299 (after org-occur-reveal activate)
21300 (and (derived-mode-p 'org-mode) (org-reveal)))
21301 (defadvice occur-mode-display-occurrence
21302 (after org-occur-reveal activate)
21303 (when (derived-mode-p 'org-mode)
21304 (let ((pos (occur-mode-find-occurrence)))
21305 (with-current-buffer (marker-buffer pos)
21306 (save-excursion
21307 (goto-char pos)
21308 (org-reveal)))))))
21310 (defun org-occur-link-in-agenda-files ()
21311 "Create a link and search for it in the agendas.
21312 The link is not stored in `org-stored-links', it is just created
21313 for the search purpose."
21314 (interactive)
21315 (let ((link (condition-case nil
21316 (org-store-link nil)
21317 (error "Unable to create a link to here"))))
21318 (org-occur-in-agenda-files (regexp-quote link))))
21320 (defun org-reverse-string (string)
21321 "Return the reverse of STRING."
21322 (apply 'string (reverse (string-to-list string))))
21324 (defun org-uniquify (list)
21325 "Remove duplicate elements from LIST."
21326 (let (res)
21327 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21328 res))
21330 (defun org-delete-all (elts list)
21331 "Remove all elements in ELTS from LIST."
21332 (while elts
21333 (setq list (delete (pop elts) list)))
21334 list)
21336 (defun org-count (cl-item cl-seq)
21337 "Count the number of occurrences of ITEM in SEQ.
21338 Taken from `count' in cl-seq.el with all keyword arguments removed."
21339 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21340 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21341 (while (< cl-start cl-end)
21342 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21343 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21344 (setq cl-start (1+ cl-start)))
21345 cl-count))
21347 (defun org-remove-if (predicate seq)
21348 "Remove everything from SEQ that fulfills PREDICATE."
21349 (let (res e)
21350 (while seq
21351 (setq e (pop seq))
21352 (if (not (funcall predicate e)) (push e res)))
21353 (nreverse res)))
21355 (defun org-remove-if-not (predicate seq)
21356 "Remove everything from SEQ that does not fulfill PREDICATE."
21357 (let (res e)
21358 (while seq
21359 (setq e (pop seq))
21360 (if (funcall predicate e) (push e res)))
21361 (nreverse res)))
21363 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21364 "Reduce two-argument FUNCTION across SEQ.
21365 Taken from `reduce' in cl-seq.el with all keyword arguments but
21366 \":initial-value\" removed."
21367 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21368 (cadr (memq :initial-value cl-keys)))
21369 (cl-seq (pop cl-seq))
21370 (t (funcall cl-func)))))
21371 (while cl-seq
21372 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21373 cl-accum))
21375 (defun org-back-over-empty-lines ()
21376 "Move backwards over whitespace, to the beginning of the first empty line.
21377 Returns the number of empty lines passed."
21378 (let ((pos (point)))
21379 (if (cdr (assoc 'heading org-blank-before-new-entry))
21380 (skip-chars-backward " \t\n\r")
21381 (unless (eobp)
21382 (forward-line -1)))
21383 (beginning-of-line 2)
21384 (goto-char (min (point) pos))
21385 (count-lines (point) pos)))
21387 (defun org-skip-whitespace ()
21388 (skip-chars-forward " \t\n\r"))
21390 (defun org-point-in-group (point group &optional context)
21391 "Check if POINT is in match-group GROUP.
21392 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21393 match. If the match group does not exist or point is not inside it,
21394 return nil."
21395 (and (match-beginning group)
21396 (>= point (match-beginning group))
21397 (<= point (match-end group))
21398 (if context
21399 (list context (match-beginning group) (match-end group))
21400 t)))
21402 (defun org-switch-to-buffer-other-window (&rest args)
21403 "Switch to buffer in a second window on the current frame.
21404 In particular, do not allow pop-up frames.
21405 Returns the newly created buffer."
21406 (org-no-popups
21407 (apply 'switch-to-buffer-other-window args)))
21409 (defun org-combine-plists (&rest plists)
21410 "Create a single property list from all plists in PLISTS.
21411 The process starts by copying the first list, and then setting properties
21412 from the other lists. Settings in the last list are the most significant
21413 ones and overrule settings in the other lists."
21414 (let ((rtn (copy-sequence (pop plists)))
21415 p v ls)
21416 (while plists
21417 (setq ls (pop plists))
21418 (while ls
21419 (setq p (pop ls) v (pop ls))
21420 (setq rtn (plist-put rtn p v))))
21421 rtn))
21423 (defun org-replace-escapes (string table)
21424 "Replace %-escapes in STRING with values in TABLE.
21425 TABLE is an association list with keys like \"%a\" and string values.
21426 The sequences in STRING may contain normal field width and padding information,
21427 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21428 so values can contain further %-escapes if they are define later in TABLE."
21429 (let ((tbl (copy-alist table))
21430 (case-fold-search nil)
21431 (pchg 0)
21432 e re rpl)
21433 (while (setq e (pop tbl))
21434 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21435 (when (and (cdr e) (string-match re (cdr e)))
21436 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21437 (safe "SREF"))
21438 (add-text-properties 0 3 (list 'sref sref) safe)
21439 (setcdr e (replace-match safe t t (cdr e)))))
21440 (while (string-match re string)
21441 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21442 (cdr e)))
21443 (setq string (replace-match rpl t t string))))
21444 (while (setq pchg (next-property-change pchg string))
21445 (let ((sref (get-text-property pchg 'sref string)))
21446 (when (and sref (string-match "SREF" string pchg))
21447 (setq string (replace-match sref t t string)))))
21448 string))
21450 (defun org-sublist (list start end)
21451 "Return a section of LIST, from START to END.
21452 Counting starts at 1."
21453 (let (rtn (c start))
21454 (setq list (nthcdr (1- start) list))
21455 (while (and list (<= c end))
21456 (push (pop list) rtn)
21457 (setq c (1+ c)))
21458 (nreverse rtn)))
21460 (defun org-find-base-buffer-visiting (file)
21461 "Like `find-buffer-visiting' but always return the base buffer and
21462 not an indirect buffer."
21463 (let ((buf (or (get-file-buffer file)
21464 (find-buffer-visiting file))))
21465 (if buf
21466 (or (buffer-base-buffer buf) buf)
21467 nil)))
21469 (defun org-image-file-name-regexp (&optional extensions)
21470 "Return regexp matching the file names of images.
21471 If EXTENSIONS is given, only match these."
21472 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21473 (image-file-name-regexp)
21474 (let ((image-file-name-extensions
21475 (or extensions
21476 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21477 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21478 (concat "\\."
21479 (regexp-opt (nconc (mapcar 'upcase
21480 image-file-name-extensions)
21481 image-file-name-extensions)
21483 "\\'"))))
21485 (defun org-file-image-p (file &optional extensions)
21486 "Return non-nil if FILE is an image."
21487 (save-match-data
21488 (string-match (org-image-file-name-regexp extensions) file)))
21490 (defun org-get-cursor-date (&optional with-time)
21491 "Return the date at cursor in as a time.
21492 This works in the calendar and in the agenda, anywhere else it just
21493 returns the current time.
21494 If WITH-TIME is non-nil, returns the time of the event at point (in
21495 the agenda) or the current time of the day."
21496 (let (date day defd tp tm hod mod)
21497 (when with-time
21498 (setq tp (get-text-property (point) 'time))
21499 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21500 (setq hod (string-to-number (match-string 1 tp))
21501 mod (string-to-number (match-string 2 tp))))
21502 (or tp (setq hod (nth 2 (decode-time (current-time)))
21503 mod (nth 1 (decode-time (current-time))))))
21504 (cond
21505 ((eq major-mode 'calendar-mode)
21506 (setq date (calendar-cursor-to-date)
21507 defd (encode-time 0 (or mod 0) (or hod 0)
21508 (nth 1 date) (nth 0 date) (nth 2 date))))
21509 ((eq major-mode 'org-agenda-mode)
21510 (setq day (get-text-property (point) 'day))
21511 (if day
21512 (setq date (calendar-gregorian-from-absolute day)
21513 defd (encode-time 0 (or mod 0) (or hod 0)
21514 (nth 1 date) (nth 0 date) (nth 2 date))))))
21515 (or defd (current-time))))
21517 (defun org-mark-subtree (&optional up)
21518 "Mark the current subtree.
21519 This puts point at the start of the current subtree, and mark at
21520 the end. If a numeric prefix UP is given, move up into the
21521 hierarchy of headlines by UP levels before marking the subtree."
21522 (interactive "P")
21523 (org-with-limited-levels
21524 (cond ((org-at-heading-p) (beginning-of-line))
21525 ((org-before-first-heading-p) (error "Not in a subtree"))
21526 (t (outline-previous-visible-heading 1))))
21527 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21528 (if (org-called-interactively-p 'any)
21529 (call-interactively 'org-mark-element)
21530 (org-mark-element)))
21533 ;;; Indentation
21535 (defun org-indent-line ()
21536 "Indent line depending on context."
21537 (interactive)
21538 (let* ((pos (point))
21539 (itemp (org-at-item-p))
21540 (case-fold-search t)
21541 (org-drawer-regexp (or org-drawer-regexp "\000"))
21542 (inline-task-p (and (featurep 'org-inlinetask)
21543 (org-inlinetask-in-task-p)))
21544 (inline-re (and inline-task-p
21545 (org-inlinetask-outline-regexp)))
21546 column)
21547 (if (and orgstruct-is-++ (eq pos (point)))
21548 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21549 (indent-according-to-mode))
21550 (beginning-of-line 1)
21551 (cond
21552 ;; Headings
21553 ((looking-at org-outline-regexp) (setq column 0))
21554 ;; Footnote definition
21555 ((looking-at org-footnote-definition-re) (setq column 0))
21556 ;; Literal examples
21557 ((looking-at "[ \t]*:\\( \\|$\\)")
21558 (setq column (org-get-indentation))) ; do nothing
21559 ;; Lists
21560 ((ignore-errors (goto-char (org-in-item-p)))
21561 (setq column (if itemp
21562 (org-get-indentation)
21563 (org-list-item-body-column (point))))
21564 (goto-char pos))
21565 ;; Drawers
21566 ((and (looking-at "[ \t]*:END:")
21567 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21568 (save-excursion
21569 (goto-char (1- (match-beginning 1)))
21570 (setq column (current-column))))
21571 ;; Special blocks
21572 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21573 (save-excursion
21574 (re-search-backward
21575 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21576 (setq column (org-get-indentation (match-string 0))))
21577 ((and (not (looking-at "[ \t]*#\\+begin_"))
21578 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21579 (save-excursion
21580 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21581 (setq column
21582 (cond ((equal (downcase (match-string 1)) "src")
21583 ;; src blocks: let `org-edit-src-exit' handle them
21584 (org-get-indentation))
21585 ((equal (downcase (match-string 1)) "example")
21586 (max (org-get-indentation)
21587 (org-get-indentation (match-string 0))))
21589 (org-get-indentation (match-string 0))))))
21590 ;; This line has nothing special, look at the previous relevant
21591 ;; line to compute indentation
21593 (beginning-of-line 0)
21594 (while (and (not (bobp))
21595 (not (looking-at org-table-line-regexp))
21596 (not (looking-at org-drawer-regexp))
21597 ;; When point started in an inline task, do not move
21598 ;; above task starting line.
21599 (not (and inline-task-p (looking-at inline-re)))
21600 ;; Skip drawers, blocks, empty lines, verbatim,
21601 ;; comments, tables, footnotes definitions, lists,
21602 ;; inline tasks.
21603 (or (and (looking-at "[ \t]*:END:")
21604 (re-search-backward org-drawer-regexp nil t))
21605 (and (looking-at "[ \t]*#\\+end_")
21606 (re-search-backward "[ \t]*#\\+begin_"nil t))
21607 (looking-at "[ \t]*[\n:#|]")
21608 (looking-at org-footnote-definition-re)
21609 (and (ignore-errors (goto-char (org-in-item-p)))
21610 (goto-char
21611 (org-list-get-top-point (org-list-struct))))
21612 (and (not inline-task-p)
21613 (featurep 'org-inlinetask)
21614 (org-inlinetask-in-task-p)
21615 (or (org-inlinetask-goto-beginning) t))))
21616 (beginning-of-line 0))
21617 (cond
21618 ;; There was an heading above.
21619 ((looking-at "\\*+[ \t]+")
21620 (if (not org-adapt-indentation)
21621 (setq column 0)
21622 (goto-char (match-end 0))
21623 (setq column (current-column))))
21624 ;; A drawer had started and is unfinished
21625 ((looking-at org-drawer-regexp)
21626 (goto-char (1- (match-beginning 1)))
21627 (setq column (current-column)))
21628 ;; Else, nothing noticeable found: get indentation and go on.
21629 (t (setq column (org-get-indentation))))))
21630 ;; Now apply indentation and move cursor accordingly
21631 (goto-char pos)
21632 (if (<= (current-column) (current-indentation))
21633 (org-indent-line-to column)
21634 (save-excursion (org-indent-line-to column)))
21635 ;; Special polishing for properties, see `org-property-format'
21636 (setq column (current-column))
21637 (beginning-of-line 1)
21638 (if (looking-at
21639 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21640 (replace-match (concat (match-string 1)
21641 (format org-property-format
21642 (match-string 2) (match-string 3)))
21643 t t))
21644 (org-move-to-column column))))
21646 (defun org-indent-drawer ()
21647 "Indent the drawer at point."
21648 (interactive)
21649 (let ((p (point))
21650 (e (and (save-excursion (re-search-forward ":END:" nil t))
21651 (match-end 0)))
21652 (folded
21653 (save-excursion
21654 (end-of-line)
21655 (when (overlays-at (point))
21656 (member 'invisible (overlay-properties
21657 (car (overlays-at (point)))))))))
21658 (when folded (org-cycle))
21659 (indent-for-tab-command)
21660 (while (and (move-beginning-of-line 2) (< (point) e))
21661 (indent-for-tab-command))
21662 (goto-char p)
21663 (when folded (org-cycle)))
21664 (message "Drawer at point indented"))
21666 (defun org-indent-block ()
21667 "Indent the block at point."
21668 (interactive)
21669 (let ((p (point))
21670 (case-fold-search t)
21671 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21672 (match-end 0)))
21673 (folded
21674 (save-excursion
21675 (end-of-line)
21676 (when (overlays-at (point))
21677 (member 'invisible (overlay-properties
21678 (car (overlays-at (point)))))))))
21679 (when folded (org-cycle))
21680 (indent-for-tab-command)
21681 (while (and (move-beginning-of-line 2) (< (point) e))
21682 (indent-for-tab-command))
21683 (goto-char p)
21684 (when folded (org-cycle)))
21685 (message "Block at point indented"))
21687 (defun org-indent-region (start end)
21688 "Indent region."
21689 (interactive "r")
21690 (save-excursion
21691 (let ((line-end (org-current-line end)))
21692 (goto-char start)
21693 (while (< (org-current-line) line-end)
21694 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21695 (t (call-interactively 'org-indent-line)))
21696 (move-beginning-of-line 2)))))
21699 ;;; Filling
21701 ;; We use our own fill-paragraph and auto-fill functions.
21703 ;; `org-fill-paragraph' relies on adaptive filling and context
21704 ;; checking. Appropriate `fill-prefix' is computed with
21705 ;; `org-adaptive-fill-function'.
21707 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21708 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21709 ;; `org-adaptive-fill-function' value. Internally,
21710 ;; `org-comment-line-break-function' breaks the line.
21712 ;; `org-setup-filling' installs filling and auto-filling related
21713 ;; variables during `org-mode' initialization.
21715 (defun org-setup-filling ()
21716 (interactive)
21717 ;; Prevent auto-fill from inserting unwanted new items.
21718 (when (boundp 'fill-nobreak-predicate)
21719 (org-set-local
21720 'fill-nobreak-predicate
21721 (org-uniquify
21722 (append fill-nobreak-predicate
21723 '(org-fill-paragraph-separate-nobreak-p
21724 org-fill-line-break-nobreak-p
21725 org-fill-paragraph-with-timestamp-nobreak-p)))))
21726 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21727 (org-set-local 'auto-fill-inhibit-regexp nil)
21728 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21729 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21730 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21732 (defvar org-element-paragraph-separate) ; org-element.el
21733 (defun org-fill-paragraph-separate-nobreak-p ()
21734 "Non-nil when a line break at point would insert a new item."
21735 (looking-at (substring org-element-paragraph-separate 1)))
21737 (defun org-fill-line-break-nobreak-p ()
21738 "Non-nil when a line break at point would create an Org line break."
21739 (save-excursion
21740 (skip-chars-backward "[ \t]")
21741 (skip-chars-backward "\\\\")
21742 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21744 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21745 "Non-nil when a line break at point would insert a new item."
21746 (and (org-at-timestamp-p t)
21747 (not (looking-at org-ts-regexp-both))))
21749 (declare-function message-in-body-p "message" ())
21750 (defvar orgtbl-line-start-regexp) ; From org-table.el
21751 (defun org-adaptive-fill-function ()
21752 "Compute a fill prefix for the current line.
21753 Return fill prefix, as a string, or nil if current line isn't
21754 meant to be filled."
21755 (let (prefix)
21756 (catch 'exit
21757 (when (derived-mode-p 'message-mode)
21758 (save-excursion
21759 (beginning-of-line)
21760 (cond ((or (not (message-in-body-p))
21761 (looking-at orgtbl-line-start-regexp))
21762 (throw 'exit nil))
21763 ((looking-at message-cite-prefix-regexp)
21764 (throw 'exit (match-string-no-properties 0)))
21765 ((looking-at org-outline-regexp)
21766 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21767 (org-with-wide-buffer
21768 (let* ((p (line-beginning-position))
21769 (element (save-excursion (beginning-of-line)
21770 (org-element-at-point)))
21771 (type (org-element-type element))
21772 (post-affiliated (org-element-property :post-affiliated element)))
21773 (unless (and post-affiliated (< p post-affiliated))
21774 (case type
21775 (comment (looking-at "[ \t]*# ?") (match-string 0))
21776 (footnote-definition "")
21777 ((item plain-list)
21778 (make-string (org-list-item-body-column
21779 (or post-affiliated
21780 (org-element-property :begin element)))
21781 ? ))
21782 (paragraph
21783 ;; Fill prefix is usually the same as the current line,
21784 ;; except if the paragraph is at the beginning of an item.
21785 (let ((parent (org-element-property :parent element)))
21786 (cond ((eq (org-element-type parent) 'item)
21787 (make-string (org-list-item-body-column
21788 (org-element-property :begin parent))
21789 ? ))
21790 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21791 (match-string 0))
21792 (t ""))))
21793 (comment-block
21794 ;; Only fill contents if P is within block boundaries.
21795 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21796 (forward-line)
21797 (point)))
21798 (cend (save-excursion
21799 (goto-char (org-element-property :end element))
21800 (skip-chars-backward " \r\t\n")
21801 (line-beginning-position))))
21802 (when (and (>= p cbeg) (< p cend))
21803 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21804 (match-string 0)
21805 "")))))))))))
21807 (declare-function message-goto-body "message" ())
21808 (defvar message-cite-prefix-regexp) ; From message.el
21809 (defun org-fill-paragraph (&optional justify)
21810 "Fill element at point, when applicable.
21812 This function only applies to comment blocks, comments, example
21813 blocks and paragraphs. Also, as a special case, re-align table
21814 when point is at one.
21816 If JUSTIFY is non-nil (interactively, with prefix argument),
21817 justify as well. If `sentence-end-double-space' is non-nil, then
21818 period followed by one space does not end a sentence, so don't
21819 break a line there. The variable `fill-column' controls the
21820 width for filling.
21822 For convenience, when point is at a plain list, an item or
21823 a footnote definition, try to fill the first paragraph within."
21824 (interactive)
21825 (if (and (derived-mode-p 'message-mode)
21826 (or (not (message-in-body-p))
21827 (save-excursion (move-beginning-of-line 1)
21828 (looking-at message-cite-prefix-regexp))))
21829 ;; First ensure filling is correct in message-mode.
21830 (let ((fill-paragraph-function
21831 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21832 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21833 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21834 (paragraph-separate
21835 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21836 (fill-paragraph nil))
21837 (with-syntax-table org-mode-transpose-word-syntax-table
21838 ;; Move to end of line in order to get the first paragraph
21839 ;; within a plain list or a footnote definition.
21840 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21841 ;; First check if point is in a blank line at the beginning of
21842 ;; the buffer. In that case, ignore filling.
21843 (case (org-element-type element)
21844 ;; Use major mode filling function is src blocks.
21845 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21846 ;; Align Org tables, leave table.el tables as-is.
21847 (table-row (org-table-align) t)
21848 (table
21849 (when (eq (org-element-property :type element) 'org)
21850 (org-table-align))
21852 (paragraph
21853 ;; Paragraphs may contain `line-break' type objects.
21854 (let ((beg (max (point-min)
21855 (org-element-property :contents-begin element)))
21856 (end (min (point-max)
21857 (org-element-property :contents-end element))))
21858 ;; Do nothing if point is at an affiliated keyword.
21859 (if (< (line-end-position) beg) t
21860 (when (derived-mode-p 'message-mode)
21861 ;; In `message-mode', do not fill following citation
21862 ;; in current paragraph nor text before message body.
21863 (let ((body-start (save-excursion (message-goto-body))))
21864 (when body-start (setq beg (max body-start beg))))
21865 (when (save-excursion
21866 (re-search-forward
21867 (concat "^" message-cite-prefix-regexp) end t))
21868 (setq end (match-beginning 0))))
21869 ;; Fill paragraph, taking line breaks into account.
21870 ;; For that, slice the paragraph using line breaks as
21871 ;; separators, and fill the parts in reverse order to
21872 ;; avoid messing with markers.
21873 (save-excursion
21874 (goto-char end)
21875 (mapc
21876 (lambda (pos)
21877 (fill-region-as-paragraph pos (point) justify)
21878 (goto-char pos))
21879 ;; Find the list of ending positions for line breaks
21880 ;; in the current paragraph. Add paragraph
21881 ;; beginning to include first slice.
21882 (nreverse
21883 (cons beg
21884 (org-element-map
21885 (org-element--parse-objects
21886 beg end nil (org-element-restriction 'paragraph))
21887 'line-break
21888 (lambda (lb) (org-element-property :end lb)))))))
21889 t)))
21890 ;; Contents of `comment-block' type elements should be
21891 ;; filled as plain text, but only if point is within block
21892 ;; markers.
21893 (comment-block
21894 (let* ((case-fold-search t)
21895 (beg (save-excursion
21896 (goto-char (org-element-property :begin element))
21897 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21898 (forward-line)
21899 (point)))
21900 (end (save-excursion
21901 (goto-char (org-element-property :end element))
21902 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21903 (line-beginning-position))))
21904 (when (and (>= (point) beg) (< (point) end))
21905 (fill-region-as-paragraph
21906 (save-excursion
21907 (end-of-line)
21908 (re-search-backward "^[ \t]*$" beg 'move)
21909 (line-beginning-position))
21910 (save-excursion
21911 (beginning-of-line)
21912 (re-search-forward "^[ \t]*$" end 'move)
21913 (line-beginning-position))
21914 justify)))
21916 ;; Fill comments.
21917 (comment (fill-comment-paragraph justify))
21918 ;; Ignore every other element.
21919 (otherwise t))))))
21921 (defun org-auto-fill-function ()
21922 "Auto-fill function."
21923 ;; Check if auto-filling is meaningful.
21924 (let ((fc (current-fill-column)))
21925 (when (and fc (> (current-column) fc))
21926 (let* ((fill-prefix (org-adaptive-fill-function))
21927 ;; Enforce empty fill prefix, if required. Otherwise, it
21928 ;; will be computed again.
21929 (adaptive-fill-mode (not (equal fill-prefix ""))))
21930 (when fill-prefix (do-auto-fill))))))
21932 (defun org-comment-line-break-function (&optional soft)
21933 "Break line at point and indent, continuing comment if within one.
21934 The inserted newline is marked hard if variable
21935 `use-hard-newlines' is true, unless optional argument SOFT is
21936 non-nil."
21937 (if soft (insert-and-inherit ?\n) (newline 1))
21938 (save-excursion (forward-char -1) (delete-horizontal-space))
21939 (delete-horizontal-space)
21940 (indent-to-left-margin)
21941 (insert-before-markers-and-inherit fill-prefix))
21944 ;;; Comments
21946 ;; Org comments syntax is quite complex. It requires the entire line
21947 ;; to be just a comment. Also, even with the right syntax at the
21948 ;; beginning of line, some some elements (i.e. verse-block or
21949 ;; example-block) don't accept comments. Usual Emacs comment commands
21950 ;; cannot cope with those requirements. Therefore, Org replaces them.
21952 ;; Org still relies on `comment-dwim', but cannot trust
21953 ;; `comment-only-p'. So, `comment-region-function' and
21954 ;; `uncomment-region-function' both point
21955 ;; to`org-comment-or-uncomment-region'. Eventually,
21956 ;; `org-insert-comment' takes care of insertion of comments at the
21957 ;; beginning of line.
21959 ;; `org-setup-comments-handling' install comments related variables
21960 ;; during `org-mode' initialization.
21962 (defun org-setup-comments-handling ()
21963 (interactive)
21964 (org-set-local 'comment-use-syntax nil)
21965 (org-set-local 'comment-start "# ")
21966 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21967 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21968 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21969 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21971 (defun org-insert-comment ()
21972 "Insert an empty comment above current line.
21973 If the line is empty, insert comment at its beginning."
21974 (beginning-of-line)
21975 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21976 (org-indent-line)
21977 (insert "# "))
21979 (defvar comment-empty-lines) ; From newcomment.el.
21980 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21981 "Comment or uncomment each non-blank line in the region.
21982 Uncomment each non-blank line between BEG and END if it only
21983 contains commented lines. Otherwise, comment them."
21984 (save-restriction
21985 ;; Restrict region
21986 (narrow-to-region (save-excursion (goto-char beg)
21987 (skip-chars-forward " \r\t\n" end)
21988 (line-beginning-position))
21989 (save-excursion (goto-char end)
21990 (skip-chars-backward " \r\t\n" beg)
21991 (line-end-position)))
21992 (let ((uncommentp
21993 ;; UNCOMMENTP is non-nil when every non blank line between
21994 ;; BEG and END is a comment.
21995 (save-excursion
21996 (goto-char (point-min))
21997 (while (and (not (eobp))
21998 (let ((element (org-element-at-point)))
21999 (and (eq (org-element-type element) 'comment)
22000 (goto-char (min (point-max)
22001 (org-element-property
22002 :end element)))))))
22003 (eobp))))
22004 (if uncommentp
22005 ;; Only blank lines and comments in region: uncomment it.
22006 (save-excursion
22007 (goto-char (point-min))
22008 (while (not (eobp))
22009 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22010 (replace-match "" nil nil nil 1))
22011 (forward-line)))
22012 ;; Comment each line in region.
22013 (let ((min-indent (point-max)))
22014 ;; First find the minimum indentation across all lines.
22015 (save-excursion
22016 (goto-char (point-min))
22017 (while (and (not (eobp)) (not (zerop min-indent)))
22018 (unless (looking-at "[ \t]*$")
22019 (setq min-indent (min min-indent (current-indentation))))
22020 (forward-line)))
22021 ;; Then loop over all lines.
22022 (save-excursion
22023 (goto-char (point-min))
22024 (while (not (eobp))
22025 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22026 (org-move-to-column min-indent t)
22027 (insert comment-start))
22028 (forward-line))))))))
22031 ;;; Planning
22033 ;; This section contains tools to operate on timestamp objects, as
22034 ;; returned by, e.g. `org-element-context'.
22036 (defun org-timestamp-has-time-p (timestamp)
22037 "Non-nil when TIMESTAMP has a time specified."
22038 (org-element-property :hour-start timestamp))
22040 (defun org-timestamp-format (timestamp format &optional end utc)
22041 "Format a TIMESTAMP element into a string.
22043 FORMAT is a format specifier to be passed to
22044 `format-time-string'.
22046 When optional argument END is non-nil, use end of date-range or
22047 time-range, if possible.
22049 When optional argument UTC is non-nil, time will be expressed as
22050 Universal Time."
22051 (format-time-string
22052 format
22053 (apply 'encode-time
22054 (cons 0
22055 (mapcar
22056 (lambda (prop) (or (org-element-property prop timestamp) 0))
22057 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22058 '(:minute-start :hour-start :day-start :month-start
22059 :year-start)))))
22060 utc))
22062 (defun org-timestamp-split-range (timestamp &optional end)
22063 "Extract a timestamp object from a date or time range.
22065 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22066 the end of the range. Otherwise, extract its start.
22068 Return a new timestamp object sharing the same parent as
22069 TIMESTAMP."
22070 (let ((type (org-element-property :type timestamp)))
22071 (if (memq type '(active inactive diary)) timestamp
22072 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22073 ;; Set new type.
22074 (org-element-put-property
22075 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22076 ;; Copy start properties over end properties if END is
22077 ;; non-nil. Otherwise, copy end properties over `start' ones.
22078 (let ((p-alist '((:minute-start . :minute-end)
22079 (:hour-start . :hour-end)
22080 (:day-start . :day-end)
22081 (:month-start . :month-end)
22082 (:year-start . :year-end))))
22083 (dolist (p-cell p-alist)
22084 (org-element-put-property
22085 split-ts
22086 (funcall (if end 'car 'cdr) p-cell)
22087 (org-element-property
22088 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22089 ;; Eventually refresh `:raw-value'.
22090 (org-element-put-property split-ts :raw-value nil)
22091 (org-element-put-property
22092 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22094 (defun org-timestamp-translate (timestamp &optional boundary)
22095 "Apply `org-translate-time' on a TIMESTAMP object.
22096 When optional argument BOUNDARY is non-nil, it is either the
22097 symbol `start' or `end'. In this case, only translate the
22098 starting or ending part of TIMESTAMP if it is a date or time
22099 range. Otherwise, translate both parts."
22100 (if (and (not boundary)
22101 (memq (org-element-property :type timestamp)
22102 '(active-range inactive-range)))
22103 (concat
22104 (org-translate-time
22105 (org-element-property :raw-value
22106 (org-timestamp-split-range timestamp)))
22107 "--"
22108 (org-translate-time
22109 (org-element-property :raw-value
22110 (org-timestamp-split-range timestamp t))))
22111 (org-translate-time
22112 (org-element-property
22113 :raw-value
22114 (if (not boundary) timestamp
22115 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22119 ;;; Other stuff.
22121 (defun org-toggle-fixed-width-section (arg)
22122 "Toggle the fixed-width export.
22123 If there is no active region, the QUOTE keyword at the current headline is
22124 inserted or removed. When present, it causes the text between this headline
22125 and the next to be exported as fixed-width text, and unmodified.
22126 If there is an active region, this command adds or removes a colon as the
22127 first character of this line. If the first character of a line is a colon,
22128 this line is also exported in fixed-width font."
22129 (interactive "P")
22130 (let* ((cc 0)
22131 (regionp (org-region-active-p))
22132 (beg (if regionp (region-beginning) (point)))
22133 (end (if regionp (region-end)))
22134 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22135 (case-fold-search nil)
22136 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22137 off)
22138 (if regionp
22139 (save-excursion
22140 (goto-char beg)
22141 (setq cc (current-column))
22142 (beginning-of-line 1)
22143 (setq off (looking-at re))
22144 (while (> nlines 0)
22145 (setq nlines (1- nlines))
22146 (beginning-of-line 1)
22147 (cond
22148 (arg
22149 (org-move-to-column cc t)
22150 (insert ": \n")
22151 (forward-line -1))
22152 ((and off (looking-at re))
22153 (replace-match "" t t nil 1))
22154 ((not off) (org-move-to-column cc t) (insert ": ")))
22155 (forward-line 1)))
22156 (save-excursion
22157 (org-back-to-heading)
22158 (cond
22159 ((looking-at (format org-heading-keyword-regexp-format
22160 org-quote-string))
22161 (goto-char (match-end 1))
22162 (looking-at (concat " +" org-quote-string))
22163 (replace-match "" t t)
22164 (when (eolp) (insert " ")))
22165 ((looking-at org-outline-regexp)
22166 (goto-char (match-end 0))
22167 (insert org-quote-string " ")))))))
22169 (defun org-reftex-citation ()
22170 "Use reftex-citation to insert a citation into the buffer.
22171 This looks for a line like
22173 #+BIBLIOGRAPHY: foo plain option:-d
22175 and derives from it that foo.bib is the bibliography file relevant
22176 for this document. It then installs the necessary environment for RefTeX
22177 to work in this buffer and calls `reftex-citation' to insert a citation
22178 into the buffer.
22180 Export of such citations to both LaTeX and HTML is handled by the contributed
22181 package org-exp-bibtex by Taru Karttunen."
22182 (interactive)
22183 (let ((reftex-docstruct-symbol 'rds)
22184 (reftex-cite-format "\\cite{%l}")
22185 rds bib)
22186 (save-excursion
22187 (save-restriction
22188 (widen)
22189 (let ((case-fold-search t)
22190 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22191 (if (not (save-excursion
22192 (or (re-search-forward re nil t)
22193 (re-search-backward re nil t))))
22194 (error "No bibliography defined in file")
22195 (setq bib (concat (match-string 1) ".bib")
22196 rds (list (list 'bib bib)))))))
22197 (call-interactively 'reftex-citation)))
22199 ;;;; Functions extending outline functionality
22201 (defun org-beginning-of-line (&optional arg)
22202 "Go to the beginning of the current line. If that is invisible, continue
22203 to a visible line beginning. This makes the function of C-a more intuitive.
22204 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22205 first attempt, and only move to after the tags when the cursor is already
22206 beyond the end of the headline."
22207 (interactive "P")
22208 (let ((pos (point))
22209 (special (if (consp org-special-ctrl-a/e)
22210 (car org-special-ctrl-a/e)
22211 org-special-ctrl-a/e))
22212 refpos)
22213 (if (org-bound-and-true-p visual-line-mode)
22214 (beginning-of-visual-line 1)
22215 (beginning-of-line 1))
22216 (if (and arg (fboundp 'move-beginning-of-line))
22217 (call-interactively 'move-beginning-of-line)
22218 (if (bobp)
22220 (backward-char 1)
22221 (if (org-truely-invisible-p)
22222 (while (and (not (bobp)) (org-truely-invisible-p))
22223 (backward-char 1)
22224 (beginning-of-line 1))
22225 (forward-char 1))))
22226 (when special
22227 (cond
22228 ((and (looking-at org-complex-heading-regexp)
22229 (= (char-after (match-end 1)) ?\ ))
22230 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22231 (point-at-eol)))
22232 (goto-char
22233 (if (eq special t)
22234 (cond ((> pos refpos) refpos)
22235 ((= pos (point)) refpos)
22236 (t (point)))
22237 (cond ((> pos (point)) (point))
22238 ((not (eq last-command this-command)) (point))
22239 (t refpos)))))
22240 ((org-at-item-p)
22241 ;; Being at an item and not looking at an the item means point
22242 ;; was previously moved to beginning of a visual line, which
22243 ;; doesn't contain the item. Therefore, do nothing special,
22244 ;; just stay here.
22245 (when (looking-at org-list-full-item-re)
22246 ;; Set special position at first white space character after
22247 ;; bullet, and check-box, if any.
22248 (let ((after-bullet
22249 (let ((box (match-end 3)))
22250 (if (not box) (match-end 1)
22251 (let ((after (char-after box)))
22252 (if (and after (= after ? )) (1+ box) box))))))
22253 ;; Special case: Move point to special position when
22254 ;; currently after it or at beginning of line.
22255 (if (eq special t)
22256 (when (or (> pos after-bullet) (= (point) pos))
22257 (goto-char after-bullet))
22258 ;; Reversed case: Move point to special position when
22259 ;; point was already at beginning of line and command is
22260 ;; repeated.
22261 (when (and (= (point) pos) (eq last-command this-command))
22262 (goto-char after-bullet))))))))
22263 (org-no-warnings
22264 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22266 (defun org-end-of-line (&optional arg)
22267 "Go to the end of the line.
22268 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22269 tags on the first attempt, and only move to after the tags when
22270 the cursor is already beyond the end of the headline."
22271 (interactive "P")
22272 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22273 org-special-ctrl-a/e))
22274 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22275 'end-of-visual-line)
22276 ((fboundp 'move-end-of-line) 'move-end-of-line)
22277 (t 'end-of-line))))
22278 (if (or (not special) arg) (call-interactively move-fun)
22279 (let* ((element (save-excursion (beginning-of-line)
22280 (org-element-at-point)))
22281 (type (org-element-type element)))
22282 (cond
22283 ((memq type '(headline inlinetask))
22284 (let ((pos (point)))
22285 (beginning-of-line 1)
22286 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22287 (if (eq special t)
22288 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22289 (goto-char (match-beginning 1))
22290 (goto-char (match-end 0)))
22291 (if (or (< pos (match-end 0))
22292 (not (eq this-command last-command)))
22293 (goto-char (match-end 0))
22294 (goto-char (match-beginning 1))))
22295 (call-interactively move-fun))))
22296 ((org-element-property :hiddenp element)
22297 ;; If element is hidden, `move-end-of-line' would put point
22298 ;; after it. Use `end-of-line' to stay on current line.
22299 (call-interactively 'end-of-line))
22300 (t (call-interactively move-fun)))))
22301 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22303 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22304 (define-key org-mode-map "\C-e" 'org-end-of-line)
22306 (defun org-backward-sentence (&optional arg)
22307 "Go to beginning of sentence, or beginning of table field.
22308 This will call `backward-sentence' or `org-table-beginning-of-field',
22309 depending on context."
22310 (interactive "P")
22311 (cond
22312 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22313 (t (call-interactively 'backward-sentence))))
22315 (defun org-forward-sentence (&optional arg)
22316 "Go to end of sentence, or end of table field.
22317 This will call `forward-sentence' or `org-table-end-of-field',
22318 depending on context."
22319 (interactive "P")
22320 (cond
22321 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22322 (t (call-interactively 'forward-sentence))))
22324 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22325 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22327 (defun org-kill-line (&optional arg)
22328 "Kill line, to tags or end of line."
22329 (interactive "P")
22330 (cond
22331 ((or (not org-special-ctrl-k)
22332 (bolp)
22333 (not (org-at-heading-p)))
22334 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22335 org-ctrl-k-protect-subtree)
22336 (if (or (eq org-ctrl-k-protect-subtree 'error)
22337 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22338 (error "C-k aborted - would kill hidden subtree")))
22339 (call-interactively
22340 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22341 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22342 (kill-region (point) (match-beginning 1))
22343 (org-set-tags nil t))
22344 (t (kill-region (point) (point-at-eol)))))
22346 (define-key org-mode-map "\C-k" 'org-kill-line)
22348 (defun org-yank (&optional arg)
22349 "Yank. If the kill is a subtree, treat it specially.
22350 This command will look at the current kill and check if is a single
22351 subtree, or a series of subtrees[1]. If it passes the test, and if the
22352 cursor is at the beginning of a line or after the stars of a currently
22353 empty headline, then the yank is handled specially. How exactly depends
22354 on the value of the following variables, both set by default.
22356 org-yank-folded-subtrees
22357 When set, the subtree(s) will be folded after insertion, but only
22358 if doing so would now swallow text after the yanked text.
22360 org-yank-adjusted-subtrees
22361 When set, the subtree will be promoted or demoted in order to
22362 fit into the local outline tree structure, which means that the level
22363 will be adjusted so that it becomes the smaller one of the two
22364 *visible* surrounding headings.
22366 Any prefix to this command will cause `yank' to be called directly with
22367 no special treatment. In particular, a simple \\[universal-argument] prefix \
22368 will just
22369 plainly yank the text as it is.
22371 \[1] The test checks if the first non-white line is a heading
22372 and if there are no other headings with fewer stars."
22373 (interactive "P")
22374 (org-yank-generic 'yank arg))
22376 (defun org-yank-generic (command arg)
22377 "Perform some yank-like command.
22379 This function implements the behavior described in the `org-yank'
22380 documentation. However, it has been generalized to work for any
22381 interactive command with similar behavior."
22383 ;; pretend to be command COMMAND
22384 (setq this-command command)
22386 (if arg
22387 (call-interactively command)
22389 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22390 (and (org-kill-is-subtree-p)
22391 (or (bolp)
22392 (and (looking-at "[ \t]*$")
22393 (string-match
22394 "\\`\\*+\\'"
22395 (buffer-substring (point-at-bol) (point)))))))
22396 swallowp)
22397 (cond
22398 ((and subtreep org-yank-folded-subtrees)
22399 (let ((beg (point))
22400 end)
22401 (if (and subtreep org-yank-adjusted-subtrees)
22402 (org-paste-subtree nil nil 'for-yank)
22403 (call-interactively command))
22405 (setq end (point))
22406 (goto-char beg)
22407 (when (and (bolp) subtreep
22408 (not (setq swallowp
22409 (org-yank-folding-would-swallow-text beg end))))
22410 (org-with-limited-levels
22411 (or (looking-at org-outline-regexp)
22412 (re-search-forward org-outline-regexp-bol end t))
22413 (while (and (< (point) end) (looking-at org-outline-regexp))
22414 (hide-subtree)
22415 (org-cycle-show-empty-lines 'folded)
22416 (condition-case nil
22417 (outline-forward-same-level 1)
22418 (error (goto-char end))))))
22419 (when swallowp
22420 (message
22421 "Inserted text not folded because that would swallow text"))
22423 (goto-char end)
22424 (skip-chars-forward " \t\n\r")
22425 (beginning-of-line 1)
22426 (push-mark beg 'nomsg)))
22427 ((and subtreep org-yank-adjusted-subtrees)
22428 (let ((beg (point-at-bol)))
22429 (org-paste-subtree nil nil 'for-yank)
22430 (push-mark beg 'nomsg)))
22432 (call-interactively command))))))
22434 (defun org-yank-folding-would-swallow-text (beg end)
22435 "Would hide-subtree at BEG swallow any text after END?"
22436 (let (level)
22437 (org-with-limited-levels
22438 (save-excursion
22439 (goto-char beg)
22440 (when (or (looking-at org-outline-regexp)
22441 (re-search-forward org-outline-regexp-bol end t))
22442 (setq level (org-outline-level)))
22443 (goto-char end)
22444 (skip-chars-forward " \t\r\n\v\f")
22445 (if (or (eobp)
22446 (and (bolp) (looking-at org-outline-regexp)
22447 (<= (org-outline-level) level)))
22448 nil ; Nothing would be swallowed
22449 t))))) ; something would swallow
22451 (define-key org-mode-map "\C-y" 'org-yank)
22453 (defun org-truely-invisible-p ()
22454 "Check if point is at a character currently not visible.
22455 This version does not only check the character property, but also
22456 `visible-mode'."
22457 ;; Early versions of noutline don't have `outline-invisible-p'.
22458 (if (org-bound-and-true-p visible-mode)
22460 (outline-invisible-p)))
22462 (defun org-invisible-p2 ()
22463 "Check if point is at a character currently not visible."
22464 (save-excursion
22465 (if (and (eolp) (not (bobp))) (backward-char 1))
22466 ;; Early versions of noutline don't have `outline-invisible-p'.
22467 (outline-invisible-p)))
22469 (defun org-back-to-heading (&optional invisible-ok)
22470 "Call `outline-back-to-heading', but provide a better error message."
22471 (condition-case nil
22472 (outline-back-to-heading invisible-ok)
22473 (error (error "Before first headline at position %d in buffer %s"
22474 (point) (current-buffer)))))
22476 (defun org-before-first-heading-p ()
22477 "Before first heading?"
22478 (save-excursion
22479 (end-of-line)
22480 (null (re-search-backward org-outline-regexp-bol nil t))))
22482 (defun org-at-heading-p (&optional ignored)
22483 (outline-on-heading-p t))
22484 ;; Compatibility alias with Org versions < 7.8.03
22485 (defalias 'org-on-heading-p 'org-at-heading-p)
22487 (defun org-at-comment-p nil
22488 "Is cursor in a line starting with a # character?"
22489 (save-excursion
22490 (beginning-of-line)
22491 (looking-at "^#")))
22493 (defun org-at-drawer-p nil
22494 "Is cursor at a drawer keyword?"
22495 (save-excursion
22496 (move-beginning-of-line 1)
22497 (looking-at org-drawer-regexp)))
22499 (defun org-at-block-p nil
22500 "Is cursor at a block keyword?"
22501 (save-excursion
22502 (move-beginning-of-line 1)
22503 (looking-at org-block-regexp)))
22505 (defun org-point-at-end-of-empty-headline ()
22506 "If point is at the end of an empty headline, return t, else nil.
22507 If the heading only contains a TODO keyword, it is still still considered
22508 empty."
22509 (and (looking-at "[ \t]*$")
22510 (when org-todo-line-regexp
22511 (save-excursion
22512 (beginning-of-line 1)
22513 (let ((case-fold-search nil))
22514 (looking-at org-todo-line-regexp)
22515 (string= (match-string 3) ""))))))
22517 (defun org-at-heading-or-item-p ()
22518 (or (org-at-heading-p) (org-at-item-p)))
22520 (defun org-at-target-p ()
22521 (or (org-in-regexp org-radio-target-regexp)
22522 (org-in-regexp org-target-regexp)))
22523 ;; Compatibility alias with Org versions < 7.8.03
22524 (defalias 'org-on-target-p 'org-at-target-p)
22526 (defun org-up-heading-all (arg)
22527 "Move to the heading line of which the present line is a subheading.
22528 This function considers both visible and invisible heading lines.
22529 With argument, move up ARG levels."
22530 (if (fboundp 'outline-up-heading-all)
22531 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22532 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22534 (defun org-up-heading-safe ()
22535 "Move to the heading line of which the present line is a subheading.
22536 This version will not throw an error. It will return the level of the
22537 headline found, or nil if no higher level is found.
22539 Also, this function will be a lot faster than `outline-up-heading',
22540 because it relies on stars being the outline starters. This can really
22541 make a significant difference in outlines with very many siblings."
22542 (let (start-level re)
22543 (org-back-to-heading t)
22544 (setq start-level (funcall outline-level))
22545 (if (equal start-level 1)
22547 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22548 (if (re-search-backward re nil t)
22549 (funcall outline-level)))))
22551 (defun org-first-sibling-p ()
22552 "Is this heading the first child of its parents?"
22553 (interactive)
22554 (let ((re org-outline-regexp-bol)
22555 level l)
22556 (unless (org-at-heading-p t)
22557 (error "Not at a heading"))
22558 (setq level (funcall outline-level))
22559 (save-excursion
22560 (if (not (re-search-backward re nil t))
22562 (setq l (funcall outline-level))
22563 (< l level)))))
22565 (defun org-goto-sibling (&optional previous)
22566 "Goto the next sibling, even if it is invisible.
22567 When PREVIOUS is set, go to the previous sibling instead. Returns t
22568 when a sibling was found. When none is found, return nil and don't
22569 move point."
22570 (let ((fun (if previous 're-search-backward 're-search-forward))
22571 (pos (point))
22572 (re org-outline-regexp-bol)
22573 level l)
22574 (when (condition-case nil (org-back-to-heading t) (error nil))
22575 (setq level (funcall outline-level))
22576 (catch 'exit
22577 (or previous (forward-char 1))
22578 (while (funcall fun re nil t)
22579 (setq l (funcall outline-level))
22580 (when (< l level) (goto-char pos) (throw 'exit nil))
22581 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22582 (goto-char pos)
22583 nil))))
22585 (defun org-show-siblings ()
22586 "Show all siblings of the current headline."
22587 (save-excursion
22588 (while (org-goto-sibling) (org-flag-heading nil)))
22589 (save-excursion
22590 (while (org-goto-sibling 'previous)
22591 (org-flag-heading nil))))
22593 (defun org-goto-first-child ()
22594 "Goto the first child, even if it is invisible.
22595 Return t when a child was found. Otherwise don't move point and
22596 return nil."
22597 (let (level (pos (point)) (re org-outline-regexp-bol))
22598 (when (condition-case nil (org-back-to-heading t) (error nil))
22599 (setq level (outline-level))
22600 (forward-char 1)
22601 (if (and (re-search-forward re nil t) (> (outline-level) level))
22602 (progn (goto-char (match-beginning 0)) t)
22603 (goto-char pos) nil))))
22605 (defun org-show-hidden-entry ()
22606 "Show an entry where even the heading is hidden."
22607 (save-excursion
22608 (org-show-entry)))
22610 (defun org-flag-heading (flag &optional entry)
22611 "Flag the current heading. FLAG non-nil means make invisible.
22612 When ENTRY is non-nil, show the entire entry."
22613 (save-excursion
22614 (org-back-to-heading t)
22615 ;; Check if we should show the entire entry
22616 (if entry
22617 (progn
22618 (org-show-entry)
22619 (save-excursion
22620 (and (outline-next-heading)
22621 (org-flag-heading nil))))
22622 (outline-flag-region (max (point-min) (1- (point)))
22623 (save-excursion (outline-end-of-heading) (point))
22624 flag))))
22626 (defun org-get-next-sibling ()
22627 "Move to next heading of the same level, and return point.
22628 If there is no such heading, return nil.
22629 This is like outline-next-sibling, but invisible headings are ok."
22630 (let ((level (funcall outline-level)))
22631 (outline-next-heading)
22632 (while (and (not (eobp)) (> (funcall outline-level) level))
22633 (outline-next-heading))
22634 (if (or (eobp) (< (funcall outline-level) level))
22636 (point))))
22638 (defun org-get-last-sibling ()
22639 "Move to previous heading of the same level, and return point.
22640 If there is no such heading, return nil."
22641 (let ((opoint (point))
22642 (level (funcall outline-level)))
22643 (outline-previous-heading)
22644 (when (and (/= (point) opoint) (outline-on-heading-p t))
22645 (while (and (> (funcall outline-level) level)
22646 (not (bobp)))
22647 (outline-previous-heading))
22648 (if (< (funcall outline-level) level)
22650 (point)))))
22652 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22653 "Goto to the end of a subtree."
22654 ;; This contains an exact copy of the original function, but it uses
22655 ;; `org-back-to-heading', to make it work also in invisible
22656 ;; trees. And is uses an invisible-ok argument.
22657 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22658 ;; Furthermore, when used inside Org, finding the end of a large subtree
22659 ;; with many children and grandchildren etc, this can be much faster
22660 ;; than the outline version.
22661 (org-back-to-heading invisible-ok)
22662 (let ((first t)
22663 (level (funcall outline-level)))
22664 (if (and (derived-mode-p 'org-mode) (< level 1000))
22665 ;; A true heading (not a plain list item), in Org-mode
22666 ;; This means we can easily find the end by looking
22667 ;; only for the right number of stars. Using a regexp to do
22668 ;; this is so much faster than using a Lisp loop.
22669 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22670 (forward-char 1)
22671 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22672 ;; something else, do it the slow way
22673 (while (and (not (eobp))
22674 (or first (> (funcall outline-level) level)))
22675 (setq first nil)
22676 (outline-next-heading)))
22677 (unless to-heading
22678 (if (memq (preceding-char) '(?\n ?\^M))
22679 (progn
22680 ;; Go to end of line before heading
22681 (forward-char -1)
22682 (if (memq (preceding-char) '(?\n ?\^M))
22683 ;; leave blank line before heading
22684 (forward-char -1))))))
22685 (point))
22687 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22688 "Use Org version in org-mode, for dramatic speed-up."
22689 (if (derived-mode-p 'org-mode)
22690 (progn
22691 (org-end-of-subtree nil t)
22692 (unless (eobp) (backward-char 1)))
22693 ad-do-it))
22695 (defun org-end-of-meta-data-and-drawers ()
22696 "Jump to the first text after meta data and drawers in the current entry.
22697 This will move over empty lines, lines with planning time stamps,
22698 clocking lines, and drawers."
22699 (org-back-to-heading t)
22700 (let ((end (save-excursion (outline-next-heading) (point)))
22701 (re (concat "\\(" org-drawer-regexp "\\)"
22702 "\\|" "[ \t]*" org-keyword-time-regexp)))
22703 (forward-line 1)
22704 (while (re-search-forward re end t)
22705 (if (not (match-end 1))
22706 ;; empty or planning line
22707 (forward-line 1)
22708 ;; a drawer, find the end
22709 (re-search-forward "^[ \t]*:END:" end 'move)
22710 (forward-line 1)))
22711 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22712 (point)))
22714 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22715 "Move forward to the ARG'th subheading at same level as this one.
22716 Stop at the first and last subheadings of a superior heading.
22717 Normally this only looks at visible headings, but when INVISIBLE-OK is
22718 non-nil it will also look at invisible ones."
22719 (interactive "p")
22720 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22721 (if (and arg (< arg 0))
22722 (goto-char (point-min))
22723 (outline-next-heading))
22724 (org-at-heading-p)
22725 (let ((level (- (match-end 0) (match-beginning 0) 1))
22726 (f (if (and arg (< arg 0))
22727 're-search-backward
22728 're-search-forward))
22729 (count (if arg (abs arg) 1))
22730 (result (point)))
22731 (forward-char (if (and arg (< arg 0)) -1 1))
22732 (while (and (> count 0)
22733 (funcall f org-outline-regexp-bol nil 'move))
22734 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22735 (cond ((< l level) (setq count 0))
22736 ((and (= l level)
22737 (or invisible-ok
22738 (progn
22739 (goto-char (line-beginning-position))
22740 (not (outline-invisible-p)))))
22741 (setq count (1- count))
22742 (when (eq l level)
22743 (setq result (point)))))))
22744 (goto-char result))
22745 (beginning-of-line 1)))
22747 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22748 "Move backward to the ARG'th subheading at same level as this one.
22749 Stop at the first and last subheadings of a superior heading."
22750 (interactive "p")
22751 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22753 (defun org-next-block (arg &optional backward block-regexp)
22754 "Jump to the next block.
22755 With a prefix argument ARG, jump forward ARG many source blocks.
22756 When BACKWARD is non-nil, jump to the previous block.
22757 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22758 (interactive "p")
22759 (let ((re (or block-regexp org-block-regexp))
22760 (re-search-fn (or (and backward 're-search-backward)
22761 're-search-forward)))
22762 (if (looking-at re) (forward-char 1))
22763 (condition-case nil
22764 (funcall re-search-fn re nil nil arg)
22765 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22766 (goto-char (match-beginning 0)) (org-show-context)))
22768 (defun org-previous-block (arg &optional block-regexp)
22769 "Jump to the previous block.
22770 With a prefix argument ARG, jump backward ARG many source blocks.
22771 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22772 (interactive "p")
22773 (org-next-block arg t block-regexp))
22775 (defun org-forward-element ()
22776 "Move forward by one element.
22777 Move to the next element at the same level, when possible."
22778 (interactive)
22779 (cond ((eobp) (user-error "Cannot move further down"))
22780 ((org-with-limited-levels (org-at-heading-p))
22781 (let ((origin (point)))
22782 (goto-char (org-end-of-subtree nil t))
22783 (unless (org-with-limited-levels (org-at-heading-p))
22784 (goto-char origin)
22785 (user-error "Cannot move further down"))))
22787 (let* ((elem (org-element-at-point))
22788 (end (org-element-property :end elem))
22789 (parent (org-element-property :parent elem)))
22790 (if (and parent (= (org-element-property :contents-end parent) end))
22791 (goto-char (org-element-property :end parent))
22792 (goto-char end))))))
22794 (defun org-backward-element ()
22795 "Move backward by one element.
22796 Move to the previous element at the same level, when possible."
22797 (interactive)
22798 (cond ((bobp) (user-error "Cannot move further up"))
22799 ((org-with-limited-levels (org-at-heading-p))
22800 ;; At a headline, move to the previous one, if any, or stay
22801 ;; here.
22802 (let ((origin (point)))
22803 (org-with-limited-levels (org-backward-heading-same-level 1))
22804 ;; When current headline has no sibling above, move to its
22805 ;; parent.
22806 (when (= (point) origin)
22807 (or (org-with-limited-levels (org-up-heading-safe))
22808 (progn (goto-char origin)
22809 (user-error "Cannot move further up"))))))
22811 (let* ((trail (org-element-at-point 'keep-trail))
22812 (elem (car trail))
22813 (prev-elem (nth 1 trail))
22814 (beg (org-element-property :begin elem)))
22815 (cond
22816 ;; Move to beginning of current element if point isn't
22817 ;; there already.
22818 ((/= (point) beg) (goto-char beg))
22819 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22820 ((org-before-first-heading-p) (goto-char (point-min)))
22821 (t (org-back-to-heading)))))))
22823 (defun org-up-element ()
22824 "Move to upper element."
22825 (interactive)
22826 (if (org-with-limited-levels (org-at-heading-p))
22827 (unless (org-up-heading-safe) (error "No surrounding element"))
22828 (let* ((elem (org-element-at-point))
22829 (parent (org-element-property :parent elem)))
22830 (if parent (goto-char (org-element-property :begin parent))
22831 (if (org-with-limited-levels (org-before-first-heading-p))
22832 (error "No surrounding element")
22833 (org-with-limited-levels (org-back-to-heading)))))))
22835 (defvar org-element-greater-elements)
22836 (defun org-down-element ()
22837 "Move to inner element."
22838 (interactive)
22839 (let ((element (org-element-at-point)))
22840 (cond
22841 ((memq (org-element-type element) '(plain-list table))
22842 (goto-char (org-element-property :contents-begin element))
22843 (forward-char))
22844 ((memq (org-element-type element) org-element-greater-elements)
22845 ;; If contents are hidden, first disclose them.
22846 (when (org-element-property :hiddenp element) (org-cycle))
22847 (goto-char (or (org-element-property :contents-begin element)
22848 (error "No content for this element"))))
22849 (t (error "No inner element")))))
22851 (defun org-drag-element-backward ()
22852 "Move backward element at point."
22853 (interactive)
22854 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22855 (let* ((trail (org-element-at-point 'keep-trail))
22856 (elem (car trail))
22857 (prev-elem (nth 1 trail)))
22858 ;; Error out if no previous element or previous element is
22859 ;; a parent of the current one.
22860 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22861 (error "Cannot drag element backward")
22862 (let ((pos (point)))
22863 (org-element-swap-A-B prev-elem elem)
22864 (goto-char (+ (org-element-property :begin prev-elem)
22865 (- pos (org-element-property :begin elem)))))))))
22867 (defun org-drag-element-forward ()
22868 "Move forward element at point."
22869 (interactive)
22870 (let* ((pos (point))
22871 (elem (org-element-at-point)))
22872 (when (= (point-max) (org-element-property :end elem))
22873 (error "Cannot drag element forward"))
22874 (goto-char (org-element-property :end elem))
22875 (let ((next-elem (org-element-at-point)))
22876 (when (or (org-element-nested-p elem next-elem)
22877 (and (eq (org-element-type next-elem) 'headline)
22878 (not (eq (org-element-type elem) 'headline))))
22879 (goto-char pos)
22880 (error "Cannot drag element forward"))
22881 ;; Compute new position of point: it's shifted by NEXT-ELEM
22882 ;; body's length (without final blanks) and by the length of
22883 ;; blanks between ELEM and NEXT-ELEM.
22884 (let ((size-next (- (save-excursion
22885 (goto-char (org-element-property :end next-elem))
22886 (skip-chars-backward " \r\t\n")
22887 (forward-line)
22888 ;; Small correction if buffer doesn't end
22889 ;; with a newline character.
22890 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22891 (org-element-property :begin next-elem)))
22892 (size-blank (- (org-element-property :end elem)
22893 (save-excursion
22894 (goto-char (org-element-property :end elem))
22895 (skip-chars-backward " \r\t\n")
22896 (forward-line)
22897 (point)))))
22898 (org-element-swap-A-B elem next-elem)
22899 (goto-char (+ pos size-next size-blank))))))
22901 (defun org-drag-line-forward (arg)
22902 "Drag the line at point ARG lines forward."
22903 (interactive "p")
22904 (dotimes (n (abs arg))
22905 (let ((c (current-column)))
22906 (if (< 0 arg)
22907 (progn
22908 (beginning-of-line 2)
22909 (transpose-lines 1)
22910 (beginning-of-line 0))
22911 (transpose-lines 1)
22912 (beginning-of-line -1))
22913 (org-move-to-column c))))
22915 (defun org-drag-line-backward (arg)
22916 "Drag the line at point ARG lines backward."
22917 (interactive "p")
22918 (org-drag-line-forward (- arg)))
22920 (defun org-mark-element ()
22921 "Put point at beginning of this element, mark at end.
22923 Interactively, if this command is repeated or (in Transient Mark
22924 mode) if the mark is active, it marks the next element after the
22925 ones already marked."
22926 (interactive)
22927 (let (deactivate-mark)
22928 (if (and (org-called-interactively-p 'any)
22929 (or (and (eq last-command this-command) (mark t))
22930 (and transient-mark-mode mark-active)))
22931 (set-mark
22932 (save-excursion
22933 (goto-char (mark))
22934 (goto-char (org-element-property :end (org-element-at-point)))))
22935 (let ((element (org-element-at-point)))
22936 (end-of-line)
22937 (push-mark (org-element-property :end element) t t)
22938 (goto-char (org-element-property :begin element))))))
22940 (defun org-narrow-to-element ()
22941 "Narrow buffer to current element."
22942 (interactive)
22943 (let ((elem (org-element-at-point)))
22944 (cond
22945 ((eq (car elem) 'headline)
22946 (narrow-to-region
22947 (org-element-property :begin elem)
22948 (org-element-property :end elem)))
22949 ((memq (car elem) org-element-greater-elements)
22950 (narrow-to-region
22951 (org-element-property :contents-begin elem)
22952 (org-element-property :contents-end elem)))
22954 (narrow-to-region
22955 (org-element-property :begin elem)
22956 (org-element-property :end elem))))))
22958 (defun org-transpose-element ()
22959 "Transpose current and previous elements, keeping blank lines between.
22960 Point is moved after both elements."
22961 (interactive)
22962 (org-skip-whitespace)
22963 (let ((end (org-element-property :end (org-element-at-point))))
22964 (org-drag-element-backward)
22965 (goto-char end)))
22967 (defun org-unindent-buffer ()
22968 "Un-indent the visible part of the buffer.
22969 Relative indentation (between items, inside blocks, etc.) isn't
22970 modified."
22971 (interactive)
22972 (unless (eq major-mode 'org-mode)
22973 (error "Cannot un-indent a buffer not in Org mode"))
22974 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22975 unindent-tree ; For byte-compiler.
22976 (unindent-tree
22977 (function
22978 (lambda (contents)
22979 (mapc
22980 (lambda (element)
22981 (if (memq (org-element-type element) '(headline section))
22982 (funcall unindent-tree (org-element-contents element))
22983 (save-excursion
22984 (save-restriction
22985 (narrow-to-region
22986 (org-element-property :begin element)
22987 (org-element-property :end element))
22988 (org-do-remove-indentation)))))
22989 (reverse contents))))))
22990 (funcall unindent-tree (org-element-contents parse-tree))))
22992 (defun org-show-subtree ()
22993 "Show everything after this heading at deeper levels."
22994 (interactive)
22995 (outline-flag-region
22996 (point)
22997 (save-excursion
22998 (org-end-of-subtree t t))
22999 nil))
23001 (defun org-show-entry ()
23002 "Show the body directly following this heading.
23003 Show the heading too, if it is currently invisible."
23004 (interactive)
23005 (save-excursion
23006 (condition-case nil
23007 (progn
23008 (org-back-to-heading t)
23009 (outline-flag-region
23010 (max (point-min) (1- (point)))
23011 (save-excursion
23012 (if (re-search-forward
23013 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23014 (match-beginning 1)
23015 (point-max)))
23016 nil)
23017 (org-cycle-hide-drawers 'children))
23018 (error nil))))
23020 (defun org-make-options-regexp (kwds &optional extra)
23021 "Make a regular expression for keyword lines."
23022 (concat
23023 "^#\\+\\("
23024 (mapconcat 'regexp-quote kwds "\\|")
23025 (if extra (concat "\\|" extra))
23026 "\\):[ \t]*\\(.*\\)"))
23028 ;; Make isearch reveal the necessary context
23029 (defun org-isearch-end ()
23030 "Reveal context after isearch exits."
23031 (when isearch-success ; only if search was successful
23032 (if (featurep 'xemacs)
23033 ;; Under XEmacs, the hook is run in the correct place,
23034 ;; we directly show the context.
23035 (org-show-context 'isearch)
23036 ;; In Emacs the hook runs *before* restoring the overlays.
23037 ;; So we have to use a one-time post-command-hook to do this.
23038 ;; (Emacs 22 has a special variable, see function `org-mode')
23039 (unless (and (boundp 'isearch-mode-end-hook-quit)
23040 isearch-mode-end-hook-quit)
23041 ;; Only when the isearch was not quitted.
23042 (org-add-hook 'post-command-hook 'org-isearch-post-command
23043 'append 'local)))
23044 (org-fix-ellipsis-at-bol)))
23046 (defun org-isearch-post-command ()
23047 "Remove self from hook, and show context."
23048 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23049 (org-show-context 'isearch))
23052 ;;;; Integration with and fixes for other packages
23054 ;;; Imenu support
23056 (defvar org-imenu-markers nil
23057 "All markers currently used by Imenu.")
23058 (make-variable-buffer-local 'org-imenu-markers)
23060 (defun org-imenu-new-marker (&optional pos)
23061 "Return a new marker for use by Imenu, and remember the marker."
23062 (let ((m (make-marker)))
23063 (move-marker m (or pos (point)))
23064 (push m org-imenu-markers)
23067 (defun org-imenu-get-tree ()
23068 "Produce the index for Imenu."
23069 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23070 (setq org-imenu-markers nil)
23071 (let* ((n org-imenu-depth)
23072 (re (concat "^" (org-get-limited-outline-regexp)))
23073 (subs (make-vector (1+ n) nil))
23074 (last-level 0)
23075 m level head0 head)
23076 (save-excursion
23077 (save-restriction
23078 (widen)
23079 (goto-char (point-max))
23080 (while (re-search-backward re nil t)
23081 (setq level (org-reduced-level (funcall outline-level)))
23082 (when (and (<= level n)
23083 (looking-at org-complex-heading-regexp)
23084 (setq head0 (org-match-string-no-properties 4)))
23085 (setq head (org-link-display-format head0)
23086 m (org-imenu-new-marker))
23087 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23088 (if (>= level last-level)
23089 (push (cons head m) (aref subs level))
23090 (push (cons head (aref subs (1+ level))) (aref subs level))
23091 (loop for i from (1+ level) to n do (aset subs i nil)))
23092 (setq last-level level)))))
23093 (aref subs 1)))
23095 (eval-after-load "imenu"
23096 '(progn
23097 (add-hook 'imenu-after-jump-hook
23098 (lambda ()
23099 (if (derived-mode-p 'org-mode)
23100 (org-show-context 'org-goto))))))
23102 (defun org-link-display-format (link)
23103 "Replace a link with either the description, or the link target
23104 if no description is present"
23105 (save-match-data
23106 (if (string-match org-bracket-link-analytic-regexp link)
23107 (replace-match (if (match-end 5)
23108 (match-string 5 link)
23109 (concat (match-string 1 link)
23110 (match-string 3 link)))
23111 nil t link)
23112 link)))
23114 (defun org-toggle-link-display ()
23115 "Toggle the literal or descriptive display of links."
23116 (interactive)
23117 (if org-descriptive-links
23118 (progn (org-remove-from-invisibility-spec '(org-link))
23119 (org-restart-font-lock)
23120 (setq org-descriptive-links nil))
23121 (progn (add-to-invisibility-spec '(org-link))
23122 (org-restart-font-lock)
23123 (setq org-descriptive-links t))))
23125 ;; Speedbar support
23127 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23128 "Overlay marking the agenda restriction line in speedbar.")
23129 (overlay-put org-speedbar-restriction-lock-overlay
23130 'face 'org-agenda-restriction-lock)
23131 (overlay-put org-speedbar-restriction-lock-overlay
23132 'help-echo "Agendas are currently limited to this item.")
23133 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23135 (defun org-speedbar-set-agenda-restriction ()
23136 "Restrict future agenda commands to the location at point in speedbar.
23137 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23138 (interactive)
23139 (require 'org-agenda)
23140 (let (p m tp np dir txt)
23141 (cond
23142 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23143 'org-imenu t))
23144 (setq m (get-text-property p 'org-imenu-marker))
23145 (with-current-buffer (marker-buffer m)
23146 (goto-char m)
23147 (org-agenda-set-restriction-lock 'subtree)))
23148 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23149 'speedbar-function 'speedbar-find-file))
23150 (setq tp (previous-single-property-change
23151 (1+ p) 'speedbar-function)
23152 np (next-single-property-change
23153 tp 'speedbar-function)
23154 dir (speedbar-line-directory)
23155 txt (buffer-substring-no-properties (or tp (point-min))
23156 (or np (point-max))))
23157 (with-current-buffer (find-file-noselect
23158 (let ((default-directory dir))
23159 (expand-file-name txt)))
23160 (unless (derived-mode-p 'org-mode)
23161 (error "Cannot restrict to non-Org-mode file"))
23162 (org-agenda-set-restriction-lock 'file)))
23163 (t (error "Don't know how to restrict Org-mode's agenda")))
23164 (move-overlay org-speedbar-restriction-lock-overlay
23165 (point-at-bol) (point-at-eol))
23166 (setq current-prefix-arg nil)
23167 (org-agenda-maybe-redo)))
23169 (eval-after-load "speedbar"
23170 '(progn
23171 (speedbar-add-supported-extension ".org")
23172 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23173 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23174 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23175 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23176 (add-hook 'speedbar-visiting-tag-hook
23177 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23179 ;;; Fixes and Hacks for problems with other packages
23181 ;; Make flyspell not check words in links, to not mess up our keymap
23182 (defvar org-element-affiliated-keywords) ; From org-element.el
23183 (defvar org-element-block-name-alist) ; From org-element.el
23184 (defun org-mode-flyspell-verify ()
23185 "Don't let flyspell put overlays at active buttons, or on
23186 {todo,all-time,additional-option-like}-keywords."
23187 (let ((pos (max (1- (point)) (point-min)))
23188 (word (thing-at-point 'word)))
23189 (and (not (get-text-property pos 'keymap))
23190 (not (get-text-property pos 'org-no-flyspell))
23191 (not (member word org-todo-keywords-1))
23192 (not (member word org-all-time-keywords))
23193 (not (member word org-options-keywords))
23194 (not (member word (mapcar 'car org-startup-options)))
23195 (not (member-ignore-case word org-element-affiliated-keywords))
23196 (not (member-ignore-case word (org-get-export-keywords)))
23197 (not (member-ignore-case
23198 word (mapcar 'car org-element-block-name-alist)))
23199 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23201 (defun org-remove-flyspell-overlays-in (beg end)
23202 "Remove flyspell overlays in region."
23203 (and (org-bound-and-true-p flyspell-mode)
23204 (fboundp 'flyspell-delete-region-overlays)
23205 (flyspell-delete-region-overlays beg end))
23206 (add-text-properties beg end '(org-no-flyspell t)))
23208 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23209 (eval-after-load "bookmark"
23210 '(if (boundp 'bookmark-after-jump-hook)
23211 ;; We can use the hook
23212 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23213 ;; Hook not available, use advice
23214 (defadvice bookmark-jump (after org-make-visible activate)
23215 "Make the position visible."
23216 (org-bookmark-jump-unhide))))
23218 ;; Make sure saveplace shows the location if it was hidden
23219 (eval-after-load "saveplace"
23220 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23221 "Make the position visible."
23222 (org-bookmark-jump-unhide)))
23224 ;; Make sure ecb shows the location if it was hidden
23225 (eval-after-load "ecb"
23226 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23227 "Make hierarchy visible when jumping into location from ECB tree buffer."
23228 (if (derived-mode-p 'org-mode)
23229 (org-show-context))))
23231 (defun org-bookmark-jump-unhide ()
23232 "Unhide the current position, to show the bookmark location."
23233 (and (derived-mode-p 'org-mode)
23234 (or (outline-invisible-p)
23235 (save-excursion (goto-char (max (point-min) (1- (point))))
23236 (outline-invisible-p)))
23237 (org-show-context 'bookmark-jump)))
23239 ;; Make session.el ignore our circular variable
23240 (eval-after-load "session"
23241 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23243 ;;;; Experimental code
23245 (defun org-closed-in-range ()
23246 "Sparse tree of items closed in a certain time range.
23247 Still experimental, may disappear in the future."
23248 (interactive)
23249 ;; Get the time interval from the user.
23250 (let* ((time1 (org-float-time
23251 (org-read-date nil 'to-time nil "Starting date: ")))
23252 (time2 (org-float-time
23253 (org-read-date nil 'to-time nil "End date:")))
23254 ;; callback function
23255 (callback (lambda ()
23256 (let ((time
23257 (org-float-time
23258 (apply 'encode-time
23259 (org-parse-time-string
23260 (match-string 1))))))
23261 ;; check if time in interval
23262 (and (>= time time1) (<= time time2))))))
23263 ;; make tree, check each match with the callback
23264 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23266 ;;;; Finish up
23268 (provide 'org)
23270 (run-hooks 'org-load-hook)
23272 ;;; org.el ends here