org.el (org-toggle-ordered-property): Delete the drawer "PROPERTIES" if empty
[org-mode.git] / lisp / org.el
blob76c2dca202b9eae047a410a71bbbee2982ff98ee
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
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-mew org-mhe org-rmail org-vm org-w3m org-wl)
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 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything
591 By default, this option is ignored when Org opens agenda files
592 for the first time. If you want the agenda to honor the startup
593 option, set `org-agenda-inhibit-startup' to nil."
594 :group 'org-startup
595 :type '(choice
596 (const :tag "nofold: show all" nil)
597 (const :tag "fold: overview" t)
598 (const :tag "content: all headlines" content)
599 (const :tag "show everything, even drawers" showeverything)))
601 (defcustom org-startup-truncated t
602 "Non-nil means entering Org-mode will set `truncate-lines'.
603 This is useful since some lines containing links can be very long and
604 uninteresting. Also tables look terrible when wrapped."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-startup-indented nil
609 "Non-nil means turn on `org-indent-mode' on startup.
610 This can also be configured on a per-file basis by adding one of
611 the following lines anywhere in the buffer:
613 #+STARTUP: indent
614 #+STARTUP: noindent"
615 :group 'org-structure
616 :type '(choice
617 (const :tag "Not" nil)
618 (const :tag "Globally (slow on startup in large files)" t)))
620 (defcustom org-use-sub-superscripts t
621 "Non-nil means interpret \"_\" and \"^\" for display.
622 When this option is turned on, you can use TeX-like syntax for sub- and
623 superscripts. Several characters after \"_\" or \"^\" will be
624 considered as a single item - so grouping with {} is normally not
625 needed. For example, the following things will be parsed as single
626 sub- or superscripts.
628 10^24 or 10^tau several digits will be considered 1 item.
629 10^-12 or 10^-tau a leading sign with digits or a word
630 x^2-y^3 will be read as x^2 - y^3, because items are
631 terminated by almost any nonword/nondigit char.
632 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
634 Still, ambiguity is possible - so when in doubt use {} to enclose
635 the sub/superscript. If you set this variable to the symbol
636 `{}', the braces are *required* in order to trigger
637 interpretations as sub/superscript. This can be helpful in
638 documents that need \"_\" frequently in plain text."
639 :group 'org-startup
640 :version "24.1"
641 :type '(choice
642 (const :tag "Always interpret" t)
643 (const :tag "Only with braces" {})
644 (const :tag "Never interpret" nil)))
646 (defcustom org-startup-with-beamer-mode nil
647 "Non-nil means turn on `org-beamer-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: beamer"
652 :group 'org-startup
653 :version "24.1"
654 :type 'boolean)
656 (defcustom org-startup-align-all-tables nil
657 "Non-nil means align all tables when visiting a file.
658 This is useful when the column width in tables is forced with <N> cookies
659 in table fields. Such tables will look correct only after the first re-align.
660 This can also be configured on a per-file basis by adding one of
661 the following lines anywhere in the buffer:
662 #+STARTUP: align
663 #+STARTUP: noalign"
664 :group 'org-startup
665 :type 'boolean)
667 (defcustom org-startup-with-inline-images nil
668 "Non-nil means show inline images when loading a new Org file.
669 This can also be configured on a per-file basis by adding one of
670 the following lines anywhere in the buffer:
671 #+STARTUP: inlineimages
672 #+STARTUP: noinlineimages"
673 :group 'org-startup
674 :version "24.1"
675 :type 'boolean)
677 (defcustom org-startup-with-latex-preview nil
678 "Non-nil means preview LaTeX fragments when loading a new Org file.
680 This can also be configured on a per-file basis by adding one of
681 the followinglines anywhere in the buffer:
682 #+STARTUP: latexpreview
683 #+STARTUP: nolatexpreview"
684 :group 'org-startup
685 :version "24.3"
686 :type 'boolean)
688 (defcustom org-insert-mode-line-in-empty-file nil
689 "Non-nil means insert the first line setting Org-mode in empty files.
690 When the function `org-mode' is called interactively in an empty file, this
691 normally means that the file name does not automatically trigger Org-mode.
692 To ensure that the file will always be in Org-mode in the future, a
693 line enforcing Org-mode will be inserted into the buffer, if this option
694 has been set."
695 :group 'org-startup
696 :type 'boolean)
698 (defcustom org-replace-disputed-keys nil
699 "Non-nil means use alternative key bindings for some keys.
700 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
701 These keys are also used by other packages like shift-selection-mode'
702 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
703 If you want to use Org-mode together with one of these other modes,
704 or more generally if you would like to move some Org-mode commands to
705 other keys, set this variable and configure the keys with the variable
706 `org-disputed-keys'.
708 This option is only relevant at load-time of Org-mode, and must be set
709 *before* org.el is loaded. Changing it requires a restart of Emacs to
710 become effective."
711 :group 'org-startup
712 :type 'boolean)
714 (defcustom org-use-extra-keys nil
715 "Non-nil means use extra key sequence definitions for certain commands.
716 This happens automatically if you run XEmacs or if `window-system'
717 is nil. This variable lets you do the same manually. You must
718 set it before loading org.
720 Example: on Carbon Emacs 22 running graphically, with an external
721 keyboard on a Powerbook, the default way of setting M-left might
722 not work for either Alt or ESC. Setting this variable will make
723 it work for ESC."
724 :group 'org-startup
725 :type 'boolean)
727 (if (fboundp 'defvaralias)
728 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
730 (defcustom org-disputed-keys
731 '(([(shift up)] . [(meta p)])
732 ([(shift down)] . [(meta n)])
733 ([(shift left)] . [(meta -)])
734 ([(shift right)] . [(meta +)])
735 ([(control shift right)] . [(meta shift +)])
736 ([(control shift left)] . [(meta shift -)]))
737 "Keys for which Org-mode and other modes compete.
738 This is an alist, cars are the default keys, second element specifies
739 the alternative to use when `org-replace-disputed-keys' is t.
741 Keys can be specified in any syntax supported by `define-key'.
742 The value of this option takes effect only at Org-mode's startup,
743 therefore you'll have to restart Emacs to apply it after changing."
744 :group 'org-startup
745 :type 'alist)
747 (defun org-key (key)
748 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
749 Or return the original if not disputed.
750 Also apply the translations defined in `org-xemacs-key-equivalents'."
751 (when org-replace-disputed-keys
752 (let* ((nkey (key-description key))
753 (x (org-find-if (lambda (x)
754 (equal (key-description (car x)) nkey))
755 org-disputed-keys)))
756 (setq key (if x (cdr x) key))))
757 (when (featurep 'xemacs)
758 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
759 key)
761 (defun org-find-if (predicate seq)
762 (catch 'exit
763 (while seq
764 (if (funcall predicate (car seq))
765 (throw 'exit (car seq))
766 (pop seq)))))
768 (defun org-defkey (keymap key def)
769 "Define a key, possibly translated, as returned by `org-key'."
770 (define-key keymap (org-key key) def))
772 (defcustom org-ellipsis nil
773 "The ellipsis to use in the Org-mode outline.
774 When nil, just use the standard three dots. When a string, use that instead,
775 When a face, use the standard 3 dots, but with the specified face.
776 The change affects only Org-mode (which will then use its own display table).
777 Changing this requires executing `M-x org-mode' in a buffer to become
778 effective."
779 :group 'org-startup
780 :type '(choice (const :tag "Default" nil)
781 (face :tag "Face" :value org-warning)
782 (string :tag "String" :value "...#")))
784 (defvar org-display-table nil
785 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
787 (defgroup org-keywords nil
788 "Keywords in Org-mode."
789 :tag "Org Keywords"
790 :group 'org)
792 (defcustom org-deadline-string "DEADLINE:"
793 "String to mark deadline entries.
794 A deadline is this string, followed by a time stamp. Should be a word,
795 terminated by a colon. You can insert a schedule keyword and
796 a timestamp with \\[org-deadline].
797 Changes become only effective after restarting Emacs."
798 :group 'org-keywords
799 :type 'string)
801 (defcustom org-scheduled-string "SCHEDULED:"
802 "String to mark scheduled TODO entries.
803 A schedule is this string, followed by a time stamp. Should be a word,
804 terminated by a colon. You can insert a schedule keyword and
805 a timestamp with \\[org-schedule].
806 Changes become only effective after restarting Emacs."
807 :group 'org-keywords
808 :type 'string)
810 (defcustom org-closed-string "CLOSED:"
811 "String used as the prefix for timestamps logging closing a TODO entry."
812 :group 'org-keywords
813 :type 'string)
815 (defcustom org-clock-string "CLOCK:"
816 "String used as prefix for timestamps clocking work hours on an item."
817 :group 'org-keywords
818 :type 'string)
820 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
821 org-scheduled-string "\\|"
822 org-deadline-string "\\|"
823 org-closed-string "\\|"
824 org-clock-string "\\)")
825 "Matches a line with planning or clock info.")
827 (defcustom org-comment-string "COMMENT"
828 "Entries starting with this keyword will never be exported.
829 An entry can be toggled between COMMENT and normal with
830 \\[org-toggle-comment].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-quote-string "QUOTE"
836 "Entries starting with this keyword will be exported in fixed-width font.
837 Quoting applies only to the text in the entry following the headline, and does
838 not extend beyond the next headline, even if that is lower level.
839 An entry can be toggled between QUOTE and normal with
840 \\[org-toggle-fixed-width-section]."
841 :group 'org-keywords
842 :type 'string)
844 (defconst org-repeat-re
845 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
846 "Regular expression for specifying repeated events.
847 After a match, group 1 contains the repeat expression.")
849 (defgroup org-structure nil
850 "Options concerning the general structure of Org-mode files."
851 :tag "Org Structure"
852 :group 'org)
854 (defgroup org-reveal-location nil
855 "Options about how to make context of a location visible."
856 :tag "Org Reveal Location"
857 :group 'org-structure)
859 (defconst org-context-choice
860 '(choice
861 (const :tag "Always" t)
862 (const :tag "Never" nil)
863 (repeat :greedy t :tag "Individual contexts"
864 (cons
865 (choice :tag "Context"
866 (const agenda)
867 (const org-goto)
868 (const occur-tree)
869 (const tags-tree)
870 (const link-search)
871 (const mark-goto)
872 (const bookmark-jump)
873 (const isearch)
874 (const default))
875 (boolean))))
876 "Contexts for the reveal options.")
878 (defcustom org-show-hierarchy-above '((default . t))
879 "Non-nil means show full hierarchy when revealing a location.
880 Org-mode often shows locations in an org-mode file which might have
881 been invisible before. When this is set, the hierarchy of headings
882 above the exposed location is shown.
883 Turning this off for example for sparse trees makes them very compact.
884 Instead of t, this can also be an alist specifying this option for different
885 contexts. Valid contexts are
886 agenda when exposing an entry from the agenda
887 org-goto when using the command `org-goto' on key C-c C-j
888 occur-tree when using the command `org-occur' on key C-c /
889 tags-tree when constructing a sparse tree based on tags matches
890 link-search when exposing search matches associated with a link
891 mark-goto when exposing the jump goal of a mark
892 bookmark-jump when exposing a bookmark location
893 isearch when exiting from an incremental search
894 default default for all contexts not set explicitly"
895 :group 'org-reveal-location
896 :type org-context-choice)
898 (defcustom org-show-following-heading '((default . nil))
899 "Non-nil means show following heading when revealing a location.
900 Org-mode often shows locations in an org-mode file which might have
901 been invisible before. When this is set, the heading following the
902 match is shown.
903 Turning this off for example for sparse trees makes them very compact,
904 but makes it harder to edit the location of the match. In such a case,
905 use the command \\[org-reveal] to show more context.
906 Instead of t, this can also be an alist specifying this option for different
907 contexts. See `org-show-hierarchy-above' for valid contexts."
908 :group 'org-reveal-location
909 :type org-context-choice)
911 (defcustom org-show-siblings '((default . nil) (isearch t))
912 "Non-nil means show all sibling heading when revealing a location.
913 Org-mode often shows locations in an org-mode file which might have
914 been invisible before. When this is set, the sibling of the current entry
915 heading are all made visible. If `org-show-hierarchy-above' is t,
916 the same happens on each level of the hierarchy above the current entry.
918 By default this is on for the isearch context, off for all other contexts.
919 Turning this off for example for sparse trees makes them very compact,
920 but makes it harder to edit the location of the match. In such a case,
921 use the command \\[org-reveal] to show more context.
922 Instead of t, this can also be an alist specifying this option for different
923 contexts. See `org-show-hierarchy-above' for valid contexts."
924 :group 'org-reveal-location
925 :type org-context-choice)
927 (defcustom org-show-entry-below '((default . nil))
928 "Non-nil means show the entry below a headline when revealing a location.
929 Org-mode often shows locations in an org-mode file which might have
930 been invisible before. When this is set, the text below the headline that is
931 exposed is also shown.
933 By default this is off for all contexts.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. See `org-show-hierarchy-above' for valid contexts."
936 :group 'org-reveal-location
937 :type org-context-choice)
939 (defcustom org-indirect-buffer-display 'other-window
940 "How should indirect tree buffers be displayed?
941 This applies to indirect buffers created with the commands
942 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
943 Valid values are:
944 current-window Display in the current window
945 other-window Just display in another window.
946 dedicated-frame Create one new frame, and re-use it each time.
947 new-frame Make a new frame each time. Note that in this case
948 previously-made indirect buffers are kept, and you need to
949 kill these buffers yourself."
950 :group 'org-structure
951 :group 'org-agenda-windows
952 :type '(choice
953 (const :tag "In current window" current-window)
954 (const :tag "In current frame, other window" other-window)
955 (const :tag "Each time a new frame" new-frame)
956 (const :tag "One dedicated frame" dedicated-frame)))
958 (defcustom org-use-speed-commands nil
959 "Non-nil means activate single letter commands at beginning of a headline.
960 This may also be a function to test for appropriate locations where speed
961 commands should be active."
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Never" nil)
965 (const :tag "At beginning of headline stars" t)
966 (function)))
968 (defcustom org-speed-commands-user nil
969 "Alist of additional speed commands.
970 This list will be checked before `org-speed-commands-default'
971 when the variable `org-use-speed-commands' is non-nil
972 and when the cursor is at the beginning of a headline.
973 The car if each entry is a string with a single letter, which must
974 be assigned to `self-insert-command' in the global map.
975 The cdr is either a command to be called interactively, a function
976 to be called, or a form to be evaluated.
977 An entry that is just a list with a single string will be interpreted
978 as a descriptive headline that will be added when listing the speed
979 commands in the Help buffer using the `?' speed command."
980 :group 'org-structure
981 :type '(repeat :value ("k" . ignore)
982 (choice :value ("k" . ignore)
983 (list :tag "Descriptive Headline" (string :tag "Headline"))
984 (cons :tag "Letter and Command"
985 (string :tag "Command letter")
986 (choice
987 (function)
988 (sexp))))))
990 (defgroup org-cycle nil
991 "Options concerning visibility cycling in Org-mode."
992 :tag "Org Cycle"
993 :group 'org-structure)
995 (defcustom org-cycle-skip-children-state-if-no-children t
996 "Non-nil means skip CHILDREN state in entries that don't have any."
997 :group 'org-cycle
998 :type 'boolean)
1000 (defcustom org-cycle-max-level nil
1001 "Maximum level which should still be subject to visibility cycling.
1002 Levels higher than this will, for cycling, be treated as text, not a headline.
1003 When `org-odd-levels-only' is set, a value of N in this variable actually
1004 means 2N-1 stars as the limiting headline.
1005 When nil, cycle all levels.
1006 Note that the limiting level of cycling is also influenced by
1007 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1008 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1009 than its value."
1010 :group 'org-cycle
1011 :type '(choice
1012 (const :tag "No limit" nil)
1013 (integer :tag "Maximum level")))
1015 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1016 "Names of drawers. Drawers are not opened by cycling on the headline above.
1017 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1018 this:
1019 :DRAWERNAME:
1020 .....
1021 :END:
1022 The drawer \"PROPERTIES\" is special for capturing properties through
1023 the property API.
1025 Drawers can be defined on the per-file basis with a line like:
1027 #+DRAWERS: HIDDEN STATE PROPERTIES"
1028 :group 'org-structure
1029 :group 'org-cycle
1030 :type '(repeat (string :tag "Drawer Name")))
1032 (defcustom org-hide-block-startup nil
1033 "Non-nil means entering Org-mode will fold all blocks.
1034 This can also be set in on a per-file basis with
1036 #+STARTUP: hideblocks
1037 #+STARTUP: showblocks"
1038 :group 'org-startup
1039 :group 'org-cycle
1040 :type 'boolean)
1042 (defcustom org-cycle-global-at-bob nil
1043 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1044 This makes it possible to do global cycling without having to use S-TAB or
1045 \\[universal-argument] TAB. For this special case to work, the first line
1046 of the buffer must not be a headline -- it may be empty or some other text.
1047 When used in this way, `org-cycle-hook' is disabled temporarily to make
1048 sure the cursor stays at the beginning of the buffer. When this option is
1049 nil, don't do anything special at the beginning of the buffer."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-level-after-item/entry-creation t
1054 "Non-nil means cycle entry level or item indentation in new empty entries.
1056 When the cursor is at the end of an empty headline, i.e., with only stars
1057 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1058 and then all possible ancestor states, before returning to the original state.
1059 This makes data entry extremely fast: M-RET to create a new headline,
1060 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1062 When the cursor is at the end of an empty plain list item, one TAB will
1063 make it a subitem, two or more tabs will back up to make this an item
1064 higher up in the item hierarchy."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-emulate-tab t
1069 "Where should `org-cycle' emulate TAB.
1070 nil Never
1071 white Only in completely white lines
1072 whitestart Only at the beginning of lines, before the first non-white char
1073 t Everywhere except in headlines
1074 exc-hl-bol Everywhere except at the start of a headline
1075 If TAB is used in a place where it does not emulate TAB, the current subtree
1076 visibility is cycled."
1077 :group 'org-cycle
1078 :type '(choice (const :tag "Never" nil)
1079 (const :tag "Only in completely white lines" white)
1080 (const :tag "Before first char in a line" whitestart)
1081 (const :tag "Everywhere except in headlines" t)
1082 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1085 (defcustom org-cycle-separator-lines 2
1086 "Number of empty lines needed to keep an empty line between collapsed trees.
1087 If you leave an empty line between the end of a subtree and the following
1088 headline, this empty line is hidden when the subtree is folded.
1089 Org-mode will leave (exactly) one empty line visible if the number of
1090 empty lines is equal or larger to the number given in this variable.
1091 So the default 2 means at least 2 empty lines after the end of a subtree
1092 are needed to produce free space between a collapsed subtree and the
1093 following headline.
1095 If the number is negative, and the number of empty lines is at least -N,
1096 all empty lines are shown.
1098 Special case: when 0, never leave empty lines in collapsed view."
1099 :group 'org-cycle
1100 :type 'integer)
1101 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1103 (defcustom org-pre-cycle-hook nil
1104 "Hook that is run before visibility cycling is happening.
1105 The function(s) in this hook must accept a single argument which indicates
1106 the new state that will be set right after running this hook. The
1107 argument is a symbol. Before a global state change, it can have the values
1108 `overview', `content', or `all'. Before a local state change, it can have
1109 the values `folded', `children', or `subtree'."
1110 :group 'org-cycle
1111 :type 'hook)
1113 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1114 org-cycle-hide-drawers
1115 org-cycle-hide-inline-tasks
1116 org-cycle-show-empty-lines
1117 org-optimize-window-after-visibility-change)
1118 "Hook that is run after `org-cycle' has changed the buffer visibility.
1119 The function(s) in this hook must accept a single argument which indicates
1120 the new state that was set by the most recent `org-cycle' command. The
1121 argument is a symbol. After a global state change, it can have the values
1122 `overview', `contents', or `all'. After a local state change, it can have
1123 the values `folded', `children', or `subtree'."
1124 :group 'org-cycle
1125 :type 'hook)
1127 (defgroup org-edit-structure nil
1128 "Options concerning structure editing in Org-mode."
1129 :tag "Org Edit Structure"
1130 :group 'org-structure)
1132 (defcustom org-odd-levels-only nil
1133 "Non-nil means skip even levels and only use odd levels for the outline.
1134 This has the effect that two stars are being added/taken away in
1135 promotion/demotion commands. It also influences how levels are
1136 handled by the exporters.
1137 Changing it requires restart of `font-lock-mode' to become effective
1138 for fontification also in regions already fontified.
1139 You may also set this on a per-file basis by adding one of the following
1140 lines to the buffer:
1142 #+STARTUP: odd
1143 #+STARTUP: oddeven"
1144 :group 'org-edit-structure
1145 :group 'org-appearance
1146 :type 'boolean)
1148 (defcustom org-adapt-indentation t
1149 "Non-nil means adapt indentation to outline node level.
1151 When this variable is set, Org assumes that you write outlines by
1152 indenting text in each node to align with the headline (after the stars).
1153 The following issues are influenced by this variable:
1155 - When this is set and the *entire* text in an entry is indented, the
1156 indentation is increased by one space in a demotion command, and
1157 decreased by one in a promotion command. If any line in the entry
1158 body starts with text at column 0, indentation is not changed at all.
1160 - Property drawers and planning information is inserted indented when
1161 this variable s set. When nil, they will not be indented.
1163 - TAB indents a line relative to context. The lines below a headline
1164 will be indented when this variable is set.
1166 Note that this is all about true indentation, by adding and removing
1167 space characters. See also `org-indent.el' which does level-dependent
1168 indentation in a virtual way, i.e. at display time in Emacs."
1169 :group 'org-edit-structure
1170 :type 'boolean)
1172 (defcustom org-special-ctrl-a/e nil
1173 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1175 When t, `C-a' will bring back the cursor to the beginning of the
1176 headline text, i.e. after the stars and after a possible TODO
1177 keyword. In an item, this will be the position after bullet and
1178 check-box, if any. When the cursor is already at that position,
1179 another `C-a' will bring it to the beginning of the line.
1181 `C-e' will jump to the end of the headline, ignoring the presence
1182 of tags in the headline. A second `C-e' will then jump to the
1183 true end of the line, after any tags. This also means that, when
1184 this variable is non-nil, `C-e' also will never jump beyond the
1185 end of the heading of a folded section, i.e. not after the
1186 ellipses.
1188 When set to the symbol `reversed', the first `C-a' or `C-e' works
1189 normally, going to the true line boundary first. Only a directly
1190 following, identical keypress will bring the cursor to the
1191 special positions.
1193 This may also be a cons cell where the behavior for `C-a' and
1194 `C-e' is set separately."
1195 :group 'org-edit-structure
1196 :type '(choice
1197 (const :tag "off" nil)
1198 (const :tag "on: after stars/bullet and before tags first" t)
1199 (const :tag "reversed: true line boundary first" reversed)
1200 (cons :tag "Set C-a and C-e separately"
1201 (choice :tag "Special C-a"
1202 (const :tag "off" nil)
1203 (const :tag "on: after stars/bullet first" t)
1204 (const :tag "reversed: before stars/bullet first" reversed))
1205 (choice :tag "Special C-e"
1206 (const :tag "off" nil)
1207 (const :tag "on: before tags first" t)
1208 (const :tag "reversed: after tags first" reversed)))))
1209 (if (fboundp 'defvaralias)
1210 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1212 (defcustom org-special-ctrl-k nil
1213 "Non-nil means `C-k' will behave specially in headlines.
1214 When nil, `C-k' will call the default `kill-line' command.
1215 When t, the following will happen while the cursor is in the headline:
1217 - When the cursor is at the beginning of a headline, kill the entire
1218 line and possible the folded subtree below the line.
1219 - When in the middle of the headline text, kill the headline up to the tags.
1220 - When after the headline text, kill the tags."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-ctrl-k-protect-subtree nil
1225 "Non-nil means, do not delete a hidden subtree with C-k.
1226 When set to the symbol `error', simply throw an error when C-k is
1227 used to kill (part-of) a headline that has hidden text behind it.
1228 Any other non-nil value will result in a query to the user, if it is
1229 OK to kill that hidden subtree. When nil, kill without remorse."
1230 :group 'org-edit-structure
1231 :version "24.1"
1232 :type '(choice
1233 (const :tag "Do not protect hidden subtrees" nil)
1234 (const :tag "Protect hidden subtrees with a security query" t)
1235 (const :tag "Never kill a hidden subtree with C-k" error)))
1237 (defcustom org-catch-invisible-edits nil
1238 "Check if in invisible region before inserting or deleting a character.
1239 Valid values are:
1241 nil Do not check, so just do invisible edits.
1242 error Throw an error and do nothing.
1243 show Make point visible, and do the requested edit.
1244 show-and-error Make point visible, then throw an error and abort the edit.
1245 smart Make point visible, and do insertion/deletion if it is
1246 adjacent to visible text and the change feels predictable.
1247 Never delete a previously invisible character or add in the
1248 middle or right after an invisible region. Basically, this
1249 allows insertion and backward-delete right before ellipses.
1250 FIXME: maybe in this case we should not even show?"
1251 :group 'org-edit-structure
1252 :version "24.1"
1253 :type '(choice
1254 (const :tag "Do not check" nil)
1255 (const :tag "Throw error when trying to edit" error)
1256 (const :tag "Unhide, but do not do the edit" show-and-error)
1257 (const :tag "Show invisible part and do the edit" show)
1258 (const :tag "Be smart and do the right thing" smart)))
1260 (defcustom org-yank-folded-subtrees t
1261 "Non-nil means when yanking subtrees, fold them.
1262 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1263 it starts with a heading and all other headings in it are either children
1264 or siblings, then fold all the subtrees. However, do this only if no
1265 text after the yank would be swallowed into a folded tree by this action."
1266 :group 'org-edit-structure
1267 :type 'boolean)
1269 (defcustom org-yank-adjusted-subtrees nil
1270 "Non-nil means when yanking subtrees, adjust the level.
1271 With this setting, `org-paste-subtree' is used to insert the subtree, see
1272 this function for details."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-M-RET-may-split-line '((default . t))
1277 "Non-nil means M-RET will split the line at the cursor position.
1278 When nil, it will go to the end of the line before making a
1279 new line.
1280 You may also set this option in a different way for different
1281 contexts. Valid contexts are:
1283 headline when creating a new headline
1284 item when creating a new item
1285 table in a table field
1286 default the value to be used for all contexts not explicitly
1287 customized"
1288 :group 'org-structure
1289 :group 'org-table
1290 :type '(choice
1291 (const :tag "Always" t)
1292 (const :tag "Never" nil)
1293 (repeat :greedy t :tag "Individual contexts"
1294 (cons
1295 (choice :tag "Context"
1296 (const headline)
1297 (const item)
1298 (const table)
1299 (const default))
1300 (boolean)))))
1303 (defcustom org-insert-heading-respect-content nil
1304 "Non-nil means insert new headings after the current subtree.
1305 When nil, the new heading is created directly after the current line.
1306 The commands \\[org-insert-heading-respect-content] and
1307 \\[org-insert-todo-heading-respect-content] turn this variable on
1308 for the duration of the command."
1309 :group 'org-structure
1310 :type 'boolean)
1312 (defcustom org-blank-before-new-entry '((heading . auto)
1313 (plain-list-item . auto))
1314 "Should `org-insert-heading' leave a blank line before new heading/item?
1315 The value is an alist, with `heading' and `plain-list-item' as CAR,
1316 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1317 which case Org will look at the surrounding headings/items and try to
1318 make an intelligent decision whether to insert a blank line or not.
1320 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1321 set, the setting here is ignored and no empty line is inserted, to avoid
1322 breaking the list structure."
1323 :group 'org-edit-structure
1324 :type '(list
1325 (cons (const heading)
1326 (choice (const :tag "Never" nil)
1327 (const :tag "Always" t)
1328 (const :tag "Auto" auto)))
1329 (cons (const plain-list-item)
1330 (choice (const :tag "Never" nil)
1331 (const :tag "Always" t)
1332 (const :tag "Auto" auto)))))
1334 (defcustom org-insert-heading-hook nil
1335 "Hook being run after inserting a new heading."
1336 :group 'org-edit-structure
1337 :type 'hook)
1339 (defcustom org-enable-fixed-width-editor t
1340 "Non-nil means lines starting with \":\" are treated as fixed-width.
1341 This currently only means they are never auto-wrapped.
1342 When nil, such lines will be treated like ordinary lines.
1343 See also the QUOTE keyword."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-goto-auto-isearch t
1348 "Non-nil means typing characters in `org-goto' starts incremental search.
1349 When nil, you can use these keybindings to navigate the buffer:
1351 q Quit the org-goto interface
1352 n Go to the next visible heading
1353 p Go to the previous visible heading
1354 f Go one heading forward on same level
1355 b Go one heading backward on same level
1356 u Go one heading up"
1357 :group 'org-edit-structure
1358 :type 'boolean)
1360 (defgroup org-sparse-trees nil
1361 "Options concerning sparse trees in Org-mode."
1362 :tag "Org Sparse Trees"
1363 :group 'org-structure)
1365 (defcustom org-highlight-sparse-tree-matches t
1366 "Non-nil means highlight all matches that define a sparse tree.
1367 The highlights will automatically disappear the next time the buffer is
1368 changed by an edit command."
1369 :group 'org-sparse-trees
1370 :type 'boolean)
1372 (defcustom org-remove-highlights-with-change t
1373 "Non-nil means any change to the buffer will remove temporary highlights.
1374 Such highlights are created by `org-occur' and `org-clock-display'.
1375 When nil, `C-c C-c needs to be used to get rid of the highlights.
1376 The highlights created by `org-preview-latex-fragment' always need
1377 `C-c C-c' to be removed."
1378 :group 'org-sparse-trees
1379 :group 'org-time
1380 :type 'boolean)
1383 (defcustom org-occur-hook '(org-first-headline-recenter)
1384 "Hook that is run after `org-occur' has constructed a sparse tree.
1385 This can be used to recenter the window to show as much of the structure
1386 as possible."
1387 :group 'org-sparse-trees
1388 :type 'hook)
1390 (defgroup org-imenu-and-speedbar nil
1391 "Options concerning imenu and speedbar in Org-mode."
1392 :tag "Org Imenu and Speedbar"
1393 :group 'org-structure)
1395 (defcustom org-imenu-depth 2
1396 "The maximum level for Imenu access to Org-mode headlines.
1397 This also applied for speedbar access."
1398 :group 'org-imenu-and-speedbar
1399 :type 'integer)
1401 (defgroup org-table nil
1402 "Options concerning tables in Org-mode."
1403 :tag "Org Table"
1404 :group 'org)
1406 (defcustom org-enable-table-editor 'optimized
1407 "Non-nil means lines starting with \"|\" are handled by the table editor.
1408 When nil, such lines will be treated like ordinary lines.
1410 When equal to the symbol `optimized', the table editor will be optimized to
1411 do the following:
1412 - Automatic overwrite mode in front of whitespace in table fields.
1413 This makes the structure of the table stay in tact as long as the edited
1414 field does not exceed the column width.
1415 - Minimize the number of realigns. Normally, the table is aligned each time
1416 TAB or RET are pressed to move to another field. With optimization this
1417 happens only if changes to a field might have changed the column width.
1418 Optimization requires replacing the functions `self-insert-command',
1419 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1420 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1421 very good at guessing when a re-align will be necessary, but you can always
1422 force one with \\[org-ctrl-c-ctrl-c].
1424 If you would like to use the optimized version in Org-mode, but the
1425 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1427 This variable can be used to turn on and off the table editor during a session,
1428 but in order to toggle optimization, a restart is required.
1430 See also the variable `org-table-auto-blank-field'."
1431 :group 'org-table
1432 :type '(choice
1433 (const :tag "off" nil)
1434 (const :tag "on" t)
1435 (const :tag "on, optimized" optimized)))
1437 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1438 (version<= emacs-version "24.1"))
1439 "Non-nil means cluster self-insert commands for undo when possible.
1440 If this is set, then, like in the Emacs command loop, 20 consecutive
1441 characters will be undone together.
1442 This is configurable, because there is some impact on typing performance."
1443 :group 'org-table
1444 :type 'boolean)
1446 (defcustom org-table-tab-recognizes-table.el t
1447 "Non-nil means TAB will automatically notice a table.el table.
1448 When it sees such a table, it moves point into it and - if necessary -
1449 calls `table-recognize-table'."
1450 :group 'org-table-editing
1451 :type 'boolean)
1453 (defgroup org-link nil
1454 "Options concerning links in Org-mode."
1455 :tag "Org Link"
1456 :group 'org)
1458 (defvar org-link-abbrev-alist-local nil
1459 "Buffer-local version of `org-link-abbrev-alist', which see.
1460 The value of this is taken from the #+LINK lines.")
1461 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1463 (defcustom org-link-abbrev-alist nil
1464 "Alist of link abbreviations.
1465 The car of each element is a string, to be replaced at the start of a link.
1466 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1467 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1469 [[linkkey:tag][description]]
1471 The 'linkkey' must be a word word, starting with a letter, followed
1472 by letters, numbers, '-' or '_'.
1474 If REPLACE is a string, the tag will simply be appended to create the link.
1475 If the string contains \"%s\", the tag will be inserted there. If the string
1476 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1477 at that point (see the function `url-hexify-string'). If the string contains
1478 the specifier \"%(my-function)\", then the custom function `my-function' will
1479 be invoked: this function takes the tag as its only argument and must return
1480 a string.
1482 REPLACE may also be a function that will be called with the tag as the
1483 only argument to create the link, which should be returned as a string.
1485 See the manual for examples."
1486 :group 'org-link
1487 :type '(repeat
1488 (cons
1489 (string :tag "Protocol")
1490 (choice
1491 (string :tag "Format")
1492 (function)))))
1494 (defcustom org-descriptive-links t
1495 "Non-nil means Org will display descriptive links.
1496 E.g. [[http://orgmode.org][Org website]] will be displayed as
1497 \"Org Website\", hiding the link itself and just displaying its
1498 description. When set to `nil', Org will display the full links
1499 literally.
1501 You can interactively set the value of this variable by calling
1502 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1503 :group 'org-link
1504 :type 'boolean)
1506 (defcustom org-link-file-path-type 'adaptive
1507 "How the path name in file links should be stored.
1508 Valid values are:
1510 relative Relative to the current directory, i.e. the directory of the file
1511 into which the link is being inserted.
1512 absolute Absolute path, if possible with ~ for home directory.
1513 noabbrev Absolute path, no abbreviation of home directory.
1514 adaptive Use relative path for files in the current directory and sub-
1515 directories of it. For other files, use an absolute path."
1516 :group 'org-link
1517 :type '(choice
1518 (const relative)
1519 (const absolute)
1520 (const noabbrev)
1521 (const adaptive)))
1523 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1524 "Types of links that should be activated in Org-mode files.
1525 This is a list of symbols, each leading to the activation of a certain link
1526 type. In principle, it does not hurt to turn on most link types - there may
1527 be a small gain when turning off unused link types. The types are:
1529 bracket The recommended [[link][description]] or [[link]] links with hiding.
1530 angle Links in angular brackets that may contain whitespace like
1531 <bbdb:Carsten Dominik>.
1532 plain Plain links in normal text, no whitespace, like http://google.com.
1533 radio Text that is matched by a radio target, see manual for details.
1534 tag Tag settings in a headline (link to tag search).
1535 date Time stamps (link to calendar).
1536 footnote Footnote labels.
1538 Changing this variable requires a restart of Emacs to become effective."
1539 :group 'org-link
1540 :type '(set :greedy t
1541 (const :tag "Double bracket links" bracket)
1542 (const :tag "Angular bracket links" angle)
1543 (const :tag "Plain text links" plain)
1544 (const :tag "Radio target matches" radio)
1545 (const :tag "Tags" tag)
1546 (const :tag "Timestamps" date)
1547 (const :tag "Footnotes" footnote)))
1549 (defcustom org-make-link-description-function nil
1550 "Function to use for generating link descriptions from links.
1551 When nil, the link location will be used. This function must take
1552 two parameters: the first one is the link, the second one is the
1553 description generated by `org-insert-link'. The function should
1554 return the description to use."
1555 :group 'org-link
1556 :type 'function)
1558 (defgroup org-link-store nil
1559 "Options concerning storing links in Org-mode."
1560 :tag "Org Store Link"
1561 :group 'org-link)
1563 (defcustom org-url-hexify-p t
1564 "When non-nil, hexify URL when creating a link."
1565 :type 'boolean
1566 :version "24.3"
1567 :group 'org-link-store)
1569 (defcustom org-email-link-description-format "Email %c: %.30s"
1570 "Format of the description part of a link to an email or usenet message.
1571 The following %-escapes will be replaced by corresponding information:
1573 %F full \"From\" field
1574 %f name, taken from \"From\" field, address if no name
1575 %T full \"To\" field
1576 %t first name in \"To\" field, address if no name
1577 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1578 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1579 %s subject
1580 %d date
1581 %m message-id.
1583 You may use normal field width specification between the % and the letter.
1584 This is for example useful to limit the length of the subject.
1586 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1587 :group 'org-link-store
1588 :type 'string)
1590 (defcustom org-from-is-user-regexp
1591 (let (r1 r2)
1592 (when (and user-mail-address (not (string= user-mail-address "")))
1593 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1594 (when (and user-full-name (not (string= user-full-name "")))
1595 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1596 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1597 "Regexp matched against the \"From:\" header of an email or usenet message.
1598 It should match if the message is from the user him/herself."
1599 :group 'org-link-store
1600 :type 'regexp)
1602 (defcustom org-context-in-file-links t
1603 "Non-nil means file links from `org-store-link' contain context.
1604 A search string will be added to the file name with :: as separator and
1605 used to find the context when the link is activated by the command
1606 `org-open-at-point'. When this option is t, the entire active region
1607 will be placed in the search string of the file link. If set to a
1608 positive integer, only the first n lines of context will be stored.
1610 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1611 negates this setting for the duration of the command."
1612 :group 'org-link-store
1613 :type '(choice boolean integer))
1615 (defcustom org-keep-stored-link-after-insertion nil
1616 "Non-nil means keep link in list for entire session.
1618 The command `org-store-link' adds a link pointing to the current
1619 location to an internal list. These links accumulate during a session.
1620 The command `org-insert-link' can be used to insert links into any
1621 Org-mode file (offering completion for all stored links). When this
1622 option is nil, every link which has been inserted once using \\[org-insert-link]
1623 will be removed from the list, to make completing the unused links
1624 more efficient."
1625 :group 'org-link-store
1626 :type 'boolean)
1628 (defgroup org-link-follow nil
1629 "Options concerning following links in Org-mode."
1630 :tag "Org Follow Link"
1631 :group 'org-link)
1633 (defcustom org-link-translation-function nil
1634 "Function to translate links with different syntax to Org syntax.
1635 This can be used to translate links created for example by the Planner
1636 or emacs-wiki packages to Org syntax.
1637 The function must accept two parameters, a TYPE containing the link
1638 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1639 which is everything after the link protocol. It should return a cons
1640 with possibly modified values of type and path.
1641 Org contains a function for this, so if you set this variable to
1642 `org-translate-link-from-planner', you should be able follow many
1643 links created by planner."
1644 :group 'org-link-follow
1645 :type 'function)
1647 (defcustom org-follow-link-hook nil
1648 "Hook that is run after a link has been followed."
1649 :group 'org-link-follow
1650 :type 'hook)
1652 (defcustom org-tab-follows-link nil
1653 "Non-nil means on links TAB will follow the link.
1654 Needs to be set before org.el is loaded.
1655 This really should not be used, it does not make sense, and the
1656 implementation is bad."
1657 :group 'org-link-follow
1658 :type 'boolean)
1660 (defcustom org-return-follows-link nil
1661 "Non-nil means on links RET will follow the link.
1662 In tables, the special behavior of RET has precedence."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-mouse-1-follows-link
1667 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1668 "Non-nil means mouse-1 on a link will follow the link.
1669 A longer mouse click will still set point. Does not work on XEmacs.
1670 Needs to be set before org.el is loaded."
1671 :group 'org-link-follow
1672 :type 'boolean)
1674 (defcustom org-mark-ring-length 4
1675 "Number of different positions to be recorded in the ring.
1676 Changing this requires a restart of Emacs to work correctly."
1677 :group 'org-link-follow
1678 :type 'integer)
1680 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1681 "Non-nil means internal links in Org files must exactly match a headline.
1682 When nil, the link search tries to match a phrase with all words
1683 in the search text."
1684 :group 'org-link-follow
1685 :version "24.1"
1686 :type '(choice
1687 (const :tag "Use fuzzy text search" nil)
1688 (const :tag "Match only exact headline" t)
1689 (const :tag "Match exact headline or query to create it"
1690 query-to-create)))
1692 (defcustom org-link-frame-setup
1693 '((vm . vm-visit-folder-other-frame)
1694 (vm-imap . vm-visit-imap-folder-other-frame)
1695 (gnus . org-gnus-no-new-news)
1696 (file . find-file-other-window)
1697 (wl . wl-other-frame))
1698 "Setup the frame configuration for following links.
1699 When following a link with Emacs, it may often be useful to display
1700 this link in another window or frame. This variable can be used to
1701 set this up for the different types of links.
1702 For VM, use any of
1703 `vm-visit-folder'
1704 `vm-visit-folder-other-window'
1705 `vm-visit-folder-other-frame'
1706 For Gnus, use any of
1707 `gnus'
1708 `gnus-other-frame'
1709 `org-gnus-no-new-news'
1710 For FILE, use any of
1711 `find-file'
1712 `find-file-other-window'
1713 `find-file-other-frame'
1714 For Wanderlust use any of
1715 `wl'
1716 `wl-other-frame'
1717 For the calendar, use the variable `calendar-setup'.
1718 For BBDB, it is currently only possible to display the matches in
1719 another window."
1720 :group 'org-link-follow
1721 :type '(list
1722 (cons (const vm)
1723 (choice
1724 (const vm-visit-folder)
1725 (const vm-visit-folder-other-window)
1726 (const vm-visit-folder-other-frame)))
1727 (cons (const gnus)
1728 (choice
1729 (const gnus)
1730 (const gnus-other-frame)
1731 (const org-gnus-no-new-news)))
1732 (cons (const file)
1733 (choice
1734 (const find-file)
1735 (const find-file-other-window)
1736 (const find-file-other-frame)))
1737 (cons (const wl)
1738 (choice
1739 (const wl)
1740 (const wl-other-frame)))))
1742 (defcustom org-display-internal-link-with-indirect-buffer nil
1743 "Non-nil means use indirect buffer to display infile links.
1744 Activating internal links (from one location in a file to another location
1745 in the same file) normally just jumps to the location. When the link is
1746 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1747 is displayed in
1748 another window. When this option is set, the other window actually displays
1749 an indirect buffer clone of the current buffer, to avoid any visibility
1750 changes to the current buffer."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-open-non-existing-files nil
1755 "Non-nil means `org-open-file' will open non-existing files.
1756 When nil, an error will be generated.
1757 This variable applies only to external applications because they
1758 might choke on non-existing files. If the link is to a file that
1759 will be opened in Emacs, the variable is ignored."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-directory-means-index-dot-org nil
1764 "Non-nil means a link to a directory really means to index.org.
1765 When nil, following a directory link will run dired or open a finder/explorer
1766 window on that directory."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1771 "Function and arguments to call for following mailto links.
1772 This is a list with the first element being a Lisp function, and the
1773 remaining elements being arguments to the function. In string arguments,
1774 %a will be replaced by the address, and %s will be replaced by the subject
1775 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1776 :group 'org-link-follow
1777 :type '(choice
1778 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1779 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1780 (const :tag "message-mail" (message-mail "%a" "%s"))
1781 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1783 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1784 "Non-nil means ask for confirmation before executing shell links.
1785 Shell links can be dangerous: just think about a link
1787 [[shell:rm -rf ~/*][Google Search]]
1789 This link would show up in your Org-mode document as \"Google Search\",
1790 but really it would remove your entire home directory.
1791 Therefore we advise against setting this variable to nil.
1792 Just change it to `y-or-n-p' if you want to confirm with a
1793 single keystroke rather than having to type \"yes\"."
1794 :group 'org-link-follow
1795 :type '(choice
1796 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1797 (const :tag "with y-or-n (faster)" y-or-n-p)
1798 (const :tag "no confirmation (dangerous)" nil)))
1799 (put 'org-confirm-shell-link-function
1800 'safe-local-variable
1801 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1803 (defcustom org-confirm-shell-link-not-regexp ""
1804 "A regexp to skip confirmation for shell links."
1805 :group 'org-link-follow
1806 :version "24.1"
1807 :type 'regexp)
1809 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1810 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1811 Elisp links can be dangerous: just think about a link
1813 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1815 This link would show up in your Org-mode document as \"Google Search\",
1816 but really it would remove your entire home directory.
1817 Therefore we advise against setting this variable to nil.
1818 Just change it to `y-or-n-p' if you want to confirm with a
1819 single keystroke rather than having to type \"yes\"."
1820 :group 'org-link-follow
1821 :type '(choice
1822 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1823 (const :tag "with y-or-n (faster)" y-or-n-p)
1824 (const :tag "no confirmation (dangerous)" nil)))
1825 (put 'org-confirm-shell-link-function
1826 'safe-local-variable
1827 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1829 (defcustom org-confirm-elisp-link-not-regexp ""
1830 "A regexp to skip confirmation for Elisp links."
1831 :group 'org-link-follow
1832 :version "24.1"
1833 :type 'regexp)
1835 (defconst org-file-apps-defaults-gnu
1836 '((remote . emacs)
1837 (system . mailcap)
1838 (t . mailcap))
1839 "Default file applications on a UNIX or GNU/Linux system.
1840 See `org-file-apps'.")
1842 (defconst org-file-apps-defaults-macosx
1843 '((remote . emacs)
1844 (t . "open %s")
1845 (system . "open %s")
1846 ("ps.gz" . "gv %s")
1847 ("eps.gz" . "gv %s")
1848 ("dvi" . "xdvi %s")
1849 ("fig" . "xfig %s"))
1850 "Default file applications on a MacOS X system.
1851 The system \"open\" is known as a default, but we use X11 applications
1852 for some files for which the OS does not have a good default.
1853 See `org-file-apps'.")
1855 (defconst org-file-apps-defaults-windowsnt
1856 (list
1857 '(remote . emacs)
1858 (cons t
1859 (list (if (featurep 'xemacs)
1860 'mswindows-shell-execute
1861 'w32-shell-execute)
1862 "open" 'file))
1863 (cons 'system
1864 (list (if (featurep 'xemacs)
1865 'mswindows-shell-execute
1866 'w32-shell-execute)
1867 "open" 'file)))
1868 "Default file applications on a Windows NT system.
1869 The system \"open\" is used for most files.
1870 See `org-file-apps'.")
1872 (defcustom org-file-apps
1874 (auto-mode . emacs)
1875 ("\\.mm\\'" . default)
1876 ("\\.x?html?\\'" . default)
1877 ("\\.pdf\\'" . default)
1879 "External applications for opening `file:path' items in a document.
1880 Org-mode uses system defaults for different file types, but
1881 you can use this variable to set the application for a given file
1882 extension. The entries in this list are cons cells where the car identifies
1883 files and the cdr the corresponding command. Possible values for the
1884 file identifier are
1885 \"string\" A string as a file identifier can be interpreted in different
1886 ways, depending on its contents:
1888 - Alphanumeric characters only:
1889 Match links with this file extension.
1890 Example: (\"pdf\" . \"evince %s\")
1891 to open PDFs with evince.
1893 - Regular expression: Match links where the
1894 filename matches the regexp. If you want to
1895 use groups here, use shy groups.
1897 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1898 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1899 to open *.html and *.xhtml with firefox.
1901 - Regular expression which contains (non-shy) groups:
1902 Match links where the whole link, including \"::\", and
1903 anything after that, matches the regexp.
1904 In a custom command string, %1, %2, etc. are replaced with
1905 the parts of the link that were matched by the groups.
1906 For backwards compatibility, if a command string is given
1907 that does not use any of the group matches, this case is
1908 handled identically to the second one (i.e. match against
1909 file name only).
1910 In a custom lisp form, you can access the group matches with
1911 (match-string n link).
1913 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1914 to open [[file:document.pdf::5]] with evince at page 5.
1916 `directory' Matches a directory
1917 `remote' Matches a remote file, accessible through tramp or efs.
1918 Remote files most likely should be visited through Emacs
1919 because external applications cannot handle such paths.
1920 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1921 so all files Emacs knows how to handle. Using this with
1922 command `emacs' will open most files in Emacs. Beware that this
1923 will also open html files inside Emacs, unless you add
1924 (\"html\" . default) to the list as well.
1925 t Default for files not matched by any of the other options.
1926 `system' The system command to open files, like `open' on Windows
1927 and Mac OS X, and mailcap under GNU/Linux. This is the command
1928 that will be selected if you call `C-c C-o' with a double
1929 \\[universal-argument] \\[universal-argument] prefix.
1931 Possible values for the command are:
1932 `emacs' The file will be visited by the current Emacs process.
1933 `default' Use the default application for this file type, which is the
1934 association for t in the list, most likely in the system-specific
1935 part.
1936 This can be used to overrule an unwanted setting in the
1937 system-specific variable.
1938 `system' Use the system command for opening files, like \"open\".
1939 This command is specified by the entry whose car is `system'.
1940 Most likely, the system-specific version of this variable
1941 does define this command, but you can overrule/replace it
1942 here.
1943 string A command to be executed by a shell; %s will be replaced
1944 by the path to the file.
1945 sexp A Lisp form which will be evaluated. The file path will
1946 be available in the Lisp variable `file'.
1947 For more examples, see the system specific constants
1948 `org-file-apps-defaults-macosx'
1949 `org-file-apps-defaults-windowsnt'
1950 `org-file-apps-defaults-gnu'."
1951 :group 'org-link-follow
1952 :type '(repeat
1953 (cons (choice :value ""
1954 (string :tag "Extension")
1955 (const :tag "System command to open files" system)
1956 (const :tag "Default for unrecognized files" t)
1957 (const :tag "Remote file" remote)
1958 (const :tag "Links to a directory" directory)
1959 (const :tag "Any files that have Emacs modes"
1960 auto-mode))
1961 (choice :value ""
1962 (const :tag "Visit with Emacs" emacs)
1963 (const :tag "Use default" default)
1964 (const :tag "Use the system command" system)
1965 (string :tag "Command")
1966 (sexp :tag "Lisp form")))))
1968 (defcustom org-doi-server-url "http://dx.doi.org/"
1969 "The URL of the DOI server."
1970 :type 'string
1971 :version "24.3"
1972 :group 'org-link-follow)
1974 (defgroup org-refile nil
1975 "Options concerning refiling entries in Org-mode."
1976 :tag "Org Refile"
1977 :group 'org)
1979 (defcustom org-directory "~/org"
1980 "Directory with org files.
1981 This is just a default location to look for Org files. There is no need
1982 at all to put your files into this directory. It is only used in the
1983 following situations:
1985 1. When a capture template specifies a target file that is not an
1986 absolute path. The path will then be interpreted relative to
1987 `org-directory'
1988 2. When a capture note is filed away in an interactive way (when exiting the
1989 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1990 with `org-directory' as the default path."
1991 :group 'org-refile
1992 :group 'org-remember
1993 :group 'org-capture
1994 :type 'directory)
1996 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1997 "Default target for storing notes.
1998 Used as a fall back file for org-remember.el and org-capture.el, for
1999 templates that do not specify a target file."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type '(choice
2004 (const :tag "Default from remember-data-file" nil)
2005 file))
2007 (defcustom org-goto-interface 'outline
2008 "The default interface to be used for `org-goto'.
2009 Allowed values are:
2010 outline The interface shows an outline of the relevant file
2011 and the correct heading is found by moving through
2012 the outline or by searching with incremental search.
2013 outline-path-completion Headlines in the current buffer are offered via
2014 completion. This is the interface also used by
2015 the refile command."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Outline" outline)
2019 (const :tag "Outline-path-completion" outline-path-completion)))
2021 (defcustom org-goto-max-level 5
2022 "Maximum target level when running `org-goto' with refile interface."
2023 :group 'org-refile
2024 :type 'integer)
2026 (defcustom org-reverse-note-order nil
2027 "Non-nil means store new notes at the beginning of a file or entry.
2028 When nil, new notes will be filed to the end of a file or entry.
2029 This can also be a list with cons cells of regular expressions that
2030 are matched against file names, and values."
2031 :group 'org-remember
2032 :group 'org-capture
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Reverse always" t)
2036 (const :tag "Reverse never" nil)
2037 (repeat :tag "By file name regexp"
2038 (cons regexp boolean))))
2040 (defcustom org-log-refile nil
2041 "Information to record when a task is refiled.
2043 Possible values are:
2045 nil Don't add anything
2046 time Add a time stamp to the task
2047 note Prompt for a note and add it with template `org-log-note-headings'
2049 This option can also be set with on a per-file-basis with
2051 #+STARTUP: nologrefile
2052 #+STARTUP: logrefile
2053 #+STARTUP: lognoterefile
2055 You can have local logging settings for a subtree by setting the LOGGING
2056 property to one or more of these keywords.
2058 When bulk-refiling from the agenda, the value `note' is forbidden and
2059 will temporarily be changed to `time'."
2060 :group 'org-refile
2061 :group 'org-progress
2062 :version "24.1"
2063 :type '(choice
2064 (const :tag "No logging" nil)
2065 (const :tag "Record timestamp" time)
2066 (const :tag "Record timestamp with note." note)))
2068 (defcustom org-refile-targets nil
2069 "Targets for refiling entries with \\[org-refile].
2070 This is a list of cons cells. Each cell contains:
2071 - a specification of the files to be considered, either a list of files,
2072 or a symbol whose function or variable value will be used to retrieve
2073 a file name or a list of file names. If you use `org-agenda-files' for
2074 that, all agenda files will be scanned for targets. Nil means consider
2075 headings in the current buffer.
2076 - A specification of how to find candidate refile targets. This may be
2077 any of:
2078 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2079 This tag has to be present in all target headlines, inheritance will
2080 not be considered.
2081 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2082 todo keyword.
2083 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2084 headlines that are refiling targets.
2085 - a cons cell (:level . N). Any headline of level N is considered a target.
2086 Note that, when `org-odd-levels-only' is set, level corresponds to
2087 order in hierarchy, not to the number of stars.
2088 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2089 Note that, when `org-odd-levels-only' is set, level corresponds to
2090 order in hierarchy, not to the number of stars.
2092 Each element of this list generates a set of possible targets.
2093 The union of these sets is presented (with completion) to
2094 the user by `org-refile'.
2096 You can set the variable `org-refile-target-verify-function' to a function
2097 to verify each headline found by the simple criteria above.
2099 When this variable is nil, all top-level headlines in the current buffer
2100 are used, equivalent to the value `((nil . (:level . 1))'."
2101 :group 'org-refile
2102 :type '(repeat
2103 (cons
2104 (choice :value org-agenda-files
2105 (const :tag "All agenda files" org-agenda-files)
2106 (const :tag "Current buffer" nil)
2107 (function) (variable) (file))
2108 (choice :tag "Identify target headline by"
2109 (cons :tag "Specific tag" (const :value :tag) (string))
2110 (cons :tag "TODO keyword" (const :value :todo) (string))
2111 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2112 (cons :tag "Level number" (const :value :level) (integer))
2113 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2115 (defcustom org-refile-target-verify-function nil
2116 "Function to verify if the headline at point should be a refile target.
2117 The function will be called without arguments, with point at the
2118 beginning of the headline. It should return t and leave point
2119 where it is if the headline is a valid target for refiling.
2121 If the target should not be selected, the function must return nil.
2122 In addition to this, it may move point to a place from where the search
2123 should be continued. For example, the function may decide that the entire
2124 subtree of the current entry should be excluded and move point to the end
2125 of the subtree."
2126 :group 'org-refile
2127 :type 'function)
2129 (defcustom org-refile-use-cache nil
2130 "Non-nil means cache refile targets to speed up the process.
2131 The cache for a particular file will be updated automatically when
2132 the buffer has been killed, or when any of the marker used for flagging
2133 refile targets no longer points at a live buffer.
2134 If you have added new entries to a buffer that might themselves be targets,
2135 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2136 find that easier, `C-u C-u C-u C-c C-w'."
2137 :group 'org-refile
2138 :version "24.1"
2139 :type 'boolean)
2141 (defcustom org-refile-use-outline-path nil
2142 "Non-nil means provide refile targets as paths.
2143 So a level 3 headline will be available as level1/level2/level3.
2145 When the value is `file', also include the file name (without directory)
2146 into the path. In this case, you can also stop the completion after
2147 the file name, to get entries inserted as top level in the file.
2149 When `full-file-path', include the full file path."
2150 :group 'org-refile
2151 :type '(choice
2152 (const :tag "Not" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Start with file name" file)
2155 (const :tag "Start with full file path" full-file-path)))
2157 (defcustom org-outline-path-complete-in-steps t
2158 "Non-nil means complete the outline path in hierarchical steps.
2159 When Org-mode uses the refile interface to select an outline path
2160 \(see variable `org-refile-use-outline-path'), the completion of
2161 the path can be done is a single go, or if can be done in steps down
2162 the headline hierarchy. Going in steps is probably the best if you
2163 do not use a special completion package like `ido' or `icicles'.
2164 However, when using these packages, going in one step can be very
2165 fast, while still showing the whole path to the entry."
2166 :group 'org-refile
2167 :type 'boolean)
2169 (defcustom org-refile-allow-creating-parent-nodes nil
2170 "Non-nil means allow to create new nodes as refile targets.
2171 New nodes are then created by adding \"/new node name\" to the completion
2172 of an existing node. When the value of this variable is `confirm',
2173 new node creation must be confirmed by the user (recommended)
2174 When nil, the completion must match an existing entry.
2176 Note that, if the new heading is not seen by the criteria
2177 listed in `org-refile-targets', multiple instances of the same
2178 heading would be created by trying again to file under the new
2179 heading."
2180 :group 'org-refile
2181 :type '(choice
2182 (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "Prompt for confirmation" confirm)))
2186 (defcustom org-refile-active-region-within-subtree nil
2187 "Non-nil means also refile active region within a subtree.
2189 By default `org-refile' doesn't allow refiling regions if they
2190 don't contain a set of subtrees, but it might be convenient to
2191 do so sometimes: in that case, the first line of the region is
2192 converted to a headline before refiling."
2193 :group 'org-refile
2194 :version "24.1"
2195 :type 'boolean)
2197 (defgroup org-todo nil
2198 "Options concerning TODO items in Org-mode."
2199 :tag "Org TODO"
2200 :group 'org)
2202 (defgroup org-progress nil
2203 "Options concerning Progress logging in Org-mode."
2204 :tag "Org Progress"
2205 :group 'org-time)
2207 (defvar org-todo-interpretation-widgets
2208 '((:tag "Sequence (cycling hits every state)" sequence)
2209 (:tag "Type (cycling directly to DONE)" type))
2210 "The available interpretation symbols for customizing `org-todo-keywords'.
2211 Interested libraries should add to this list.")
2213 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2214 "List of TODO entry keyword sequences and their interpretation.
2215 \\<org-mode-map>This is a list of sequences.
2217 Each sequence starts with a symbol, either `sequence' or `type',
2218 indicating if the keywords should be interpreted as a sequence of
2219 action steps, or as different types of TODO items. The first
2220 keywords are states requiring action - these states will select a headline
2221 for inclusion into the global TODO list Org-mode produces. If one of
2222 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2223 signify that no further action is necessary. If \"|\" is not found,
2224 the last keyword is treated as the only DONE state of the sequence.
2226 The command \\[org-todo] cycles an entry through these states, and one
2227 additional state where no keyword is present. For details about this
2228 cycling, see the manual.
2230 TODO keywords and interpretation can also be set on a per-file basis with
2231 the special #+SEQ_TODO and #+TYP_TODO lines.
2233 Each keyword can optionally specify a character for fast state selection
2234 \(in combination with the variable `org-use-fast-todo-selection')
2235 and specifiers for state change logging, using the same syntax that
2236 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2237 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2238 indicates to record a time stamp each time this state is selected.
2240 Each keyword may also specify if a timestamp or a note should be
2241 recorded when entering or leaving the state, by adding additional
2242 characters in the parenthesis after the keyword. This looks like this:
2243 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2244 record only the time of the state change. With X and Y being either
2245 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2246 Y when leaving the state if and only if the *target* state does not
2247 define X. You may omit any of the fast-selection key or X or /Y,
2248 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2250 For backward compatibility, this variable may also be just a list
2251 of keywords. In this case the interpretation (sequence or type) will be
2252 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2253 :group 'org-todo
2254 :group 'org-keywords
2255 :type '(choice
2256 (repeat :tag "Old syntax, just keywords"
2257 (string :tag "Keyword"))
2258 (repeat :tag "New syntax"
2259 (cons
2260 (choice
2261 :tag "Interpretation"
2262 ;;Quick and dirty way to see
2263 ;;`org-todo-interpretations'. This takes the
2264 ;;place of item arguments
2265 :convert-widget
2266 (lambda (widget)
2267 (widget-put widget
2268 :args (mapcar
2269 #'(lambda (x)
2270 (widget-convert
2271 (cons 'const x)))
2272 org-todo-interpretation-widgets))
2273 widget))
2274 (repeat
2275 (string :tag "Keyword"))))))
2277 (defvar org-todo-keywords-1 nil
2278 "All TODO and DONE keywords active in a buffer.")
2279 (make-variable-buffer-local 'org-todo-keywords-1)
2280 (defvar org-todo-keywords-for-agenda nil)
2281 (defvar org-done-keywords-for-agenda nil)
2282 (defvar org-drawers-for-agenda nil)
2283 (defvar org-todo-keyword-alist-for-agenda nil)
2284 (defvar org-tag-alist-for-agenda nil)
2285 (defvar org-agenda-contributing-files nil)
2286 (defvar org-not-done-keywords nil)
2287 (make-variable-buffer-local 'org-not-done-keywords)
2288 (defvar org-done-keywords nil)
2289 (make-variable-buffer-local 'org-done-keywords)
2290 (defvar org-todo-heads nil)
2291 (make-variable-buffer-local 'org-todo-heads)
2292 (defvar org-todo-sets nil)
2293 (make-variable-buffer-local 'org-todo-sets)
2294 (defvar org-todo-log-states nil)
2295 (make-variable-buffer-local 'org-todo-log-states)
2296 (defvar org-todo-kwd-alist nil)
2297 (make-variable-buffer-local 'org-todo-kwd-alist)
2298 (defvar org-todo-key-alist nil)
2299 (make-variable-buffer-local 'org-todo-key-alist)
2300 (defvar org-todo-key-trigger nil)
2301 (make-variable-buffer-local 'org-todo-key-trigger)
2303 (defcustom org-todo-interpretation 'sequence
2304 "Controls how TODO keywords are interpreted.
2305 This variable is in principle obsolete and is only used for
2306 backward compatibility, if the interpretation of todo keywords is
2307 not given already in `org-todo-keywords'. See that variable for
2308 more information."
2309 :group 'org-todo
2310 :group 'org-keywords
2311 :type '(choice (const sequence)
2312 (const type)))
2314 (defcustom org-use-fast-todo-selection t
2315 "Non-nil means use the fast todo selection scheme with C-c C-t.
2316 This variable describes if and under what circumstances the cycling
2317 mechanism for TODO keywords will be replaced by a single-key, direct
2318 selection scheme.
2320 When nil, fast selection is never used.
2322 When the symbol `prefix', it will be used when `org-todo' is called
2323 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2324 `C-u t' in an agenda buffer.
2326 When t, fast selection is used by default. In this case, the prefix
2327 argument forces cycling instead.
2329 In all cases, the special interface is only used if access keys have
2330 actually been assigned by the user, i.e. if keywords in the configuration
2331 are followed by a letter in parenthesis, like TODO(t)."
2332 :group 'org-todo
2333 :type '(choice
2334 (const :tag "Never" nil)
2335 (const :tag "By default" t)
2336 (const :tag "Only with C-u C-c C-t" prefix)))
2338 (defcustom org-provide-todo-statistics t
2339 "Non-nil means update todo statistics after insert and toggle.
2340 ALL-HEADLINES means update todo statistics by including headlines
2341 with no TODO keyword as well, counting them as not done.
2342 A list of TODO keywords means the same, but skip keywords that are
2343 not in this list.
2345 When this is set, todo statistics is updated in the parent of the
2346 current entry each time a todo state is changed."
2347 :group 'org-todo
2348 :type '(choice
2349 (const :tag "Yes, only for TODO entries" t)
2350 (const :tag "Yes, including all entries" 'all-headlines)
2351 (repeat :tag "Yes, for TODOs in this list"
2352 (string :tag "TODO keyword"))
2353 (other :tag "No TODO statistics" nil)))
2355 (defcustom org-hierarchical-todo-statistics t
2356 "Non-nil means TODO statistics covers just direct children.
2357 When nil, all entries in the subtree are considered.
2358 This has only an effect if `org-provide-todo-statistics' is set.
2359 To set this to nil for only a single subtree, use a COOKIE_DATA
2360 property and include the word \"recursive\" into the value."
2361 :group 'org-todo
2362 :type 'boolean)
2364 (defcustom org-after-todo-state-change-hook nil
2365 "Hook which is run after the state of a TODO item was changed.
2366 The new state (a string with a TODO keyword, or nil) is available in the
2367 Lisp variable `org-state'."
2368 :group 'org-todo
2369 :type 'hook)
2371 (defvar org-blocker-hook nil
2372 "Hook for functions that are allowed to block a state change.
2374 Functions in this hook should not modify the buffer.
2375 Each function gets as its single argument a property list,
2376 see `org-trigger-hook' for more information about this list.
2378 If any of the functions in this hook returns nil, the state change
2379 is blocked.")
2381 (defvar org-trigger-hook nil
2382 "Hook for functions that are triggered by a state change.
2384 Each function gets as its single argument a property list with at
2385 least the following elements:
2387 (:type type-of-change :position pos-at-entry-start
2388 :from old-state :to new-state)
2390 Depending on the type, more properties may be present.
2392 This mechanism is currently implemented for:
2394 TODO state changes
2395 ------------------
2396 :type todo-state-change
2397 :from previous state (keyword as a string), or nil, or a symbol
2398 'todo' or 'done', to indicate the general type of state.
2399 :to new state, like in :from")
2401 (defcustom org-enforce-todo-dependencies nil
2402 "Non-nil means undone TODO entries will block switching the parent to DONE.
2403 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2404 be blocked if any prior sibling is not yet done.
2405 Finally, if the parent is blocked because of ordered siblings of its own,
2406 the child will also be blocked."
2407 :set (lambda (var val)
2408 (set var val)
2409 (if val
2410 (add-hook 'org-blocker-hook
2411 'org-block-todo-from-children-or-siblings-or-parent)
2412 (remove-hook 'org-blocker-hook
2413 'org-block-todo-from-children-or-siblings-or-parent)))
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-enforce-todo-checkbox-dependencies nil
2418 "Non-nil means unchecked boxes will block switching the parent to DONE.
2419 When this is nil, checkboxes have no influence on switching TODO states.
2420 When non-nil, you first need to check off all check boxes before the TODO
2421 entry can be switched to DONE.
2422 This variable needs to be set before org.el is loaded, and you need to
2423 restart Emacs after a change to make the change effective. The only way
2424 to change is while Emacs is running is through the customize interface."
2425 :set (lambda (var val)
2426 (set var val)
2427 (if val
2428 (add-hook 'org-blocker-hook
2429 'org-block-todo-from-checkboxes)
2430 (remove-hook 'org-blocker-hook
2431 'org-block-todo-from-checkboxes)))
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-treat-insert-todo-heading-as-state-change nil
2436 "Non-nil means inserting a TODO heading is treated as state change.
2437 So when the command \\[org-insert-todo-heading] is used, state change
2438 logging will apply if appropriate. When nil, the new TODO item will
2439 be inserted directly, and no logging will take place."
2440 :group 'org-todo
2441 :type 'boolean)
2443 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2444 "Non-nil means switching TODO states with S-cursor counts as state change.
2445 This is the default behavior. However, setting this to nil allows a
2446 convenient way to select a TODO state and bypass any logging associated
2447 with that."
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-todo-state-tags-triggers nil
2452 "Tag changes that should be triggered by TODO state changes.
2453 This is a list. Each entry is
2455 (state-change (tag . flag) .......)
2457 State-change can be a string with a state, and empty string to indicate the
2458 state that has no TODO keyword, or it can be one of the symbols `todo'
2459 or `done', meaning any not-done or done state, respectively."
2460 :group 'org-todo
2461 :group 'org-tags
2462 :type '(repeat
2463 (cons (choice :tag "When changing to"
2464 (const :tag "Not-done state" todo)
2465 (const :tag "Done state" done)
2466 (string :tag "State"))
2467 (repeat
2468 (cons :tag "Tag action"
2469 (string :tag "Tag")
2470 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2472 (defcustom org-log-done nil
2473 "Information to record when a task moves to the DONE state.
2475 Possible values are:
2477 nil Don't add anything, just change the keyword
2478 time Add a time stamp to the task
2479 note Prompt for a note and add it with template `org-log-note-headings'
2481 This option can also be set with on a per-file-basis with
2483 #+STARTUP: nologdone
2484 #+STARTUP: logdone
2485 #+STARTUP: lognotedone
2487 You can have local logging settings for a subtree by setting the LOGGING
2488 property to one or more of these keywords."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "No logging" nil)
2493 (const :tag "Record CLOSED timestamp" time)
2494 (const :tag "Record CLOSED timestamp with note." note)))
2496 ;; Normalize old uses of org-log-done.
2497 (cond
2498 ((eq org-log-done t) (setq org-log-done 'time))
2499 ((and (listp org-log-done) (memq 'done org-log-done))
2500 (setq org-log-done 'note)))
2502 (defcustom org-log-reschedule nil
2503 "Information to record when the scheduling date of a tasks is modified.
2505 Possible values are:
2507 nil Don't add anything, just change the date
2508 time Add a time stamp to the task
2509 note Prompt for a note and add it with template `org-log-note-headings'
2511 This option can also be set with on a per-file-basis with
2513 #+STARTUP: nologreschedule
2514 #+STARTUP: logreschedule
2515 #+STARTUP: lognotereschedule"
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type '(choice
2519 (const :tag "No logging" nil)
2520 (const :tag "Record timestamp" time)
2521 (const :tag "Record timestamp with note." note)))
2523 (defcustom org-log-redeadline nil
2524 "Information to record when the deadline date of a tasks is modified.
2526 Possible values are:
2528 nil Don't add anything, just change the date
2529 time Add a time stamp to the task
2530 note Prompt for a note and add it with template `org-log-note-headings'
2532 This option can also be set with on a per-file-basis with
2534 #+STARTUP: nologredeadline
2535 #+STARTUP: logredeadline
2536 #+STARTUP: lognoteredeadline
2538 You can have local logging settings for a subtree by setting the LOGGING
2539 property to one or more of these keywords."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type '(choice
2543 (const :tag "No logging" nil)
2544 (const :tag "Record timestamp" time)
2545 (const :tag "Record timestamp with note." note)))
2547 (defcustom org-log-note-clock-out nil
2548 "Non-nil means record a note when clocking out of an item.
2549 This can also be configured on a per-file basis by adding one of
2550 the following lines anywhere in the buffer:
2552 #+STARTUP: lognoteclock-out
2553 #+STARTUP: nolognoteclock-out"
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type 'boolean)
2558 (defcustom org-log-done-with-time t
2559 "Non-nil means the CLOSED time stamp will contain date and time.
2560 When nil, only the date will be recorded."
2561 :group 'org-progress
2562 :type 'boolean)
2564 (defcustom org-log-note-headings
2565 '((done . "CLOSING NOTE %t")
2566 (state . "State %-12s from %-12S %t")
2567 (note . "Note taken on %t")
2568 (reschedule . "Rescheduled from %S on %t")
2569 (delschedule . "Not scheduled, was %S on %t")
2570 (redeadline . "New deadline from %S on %t")
2571 (deldeadline . "Removed deadline, was %S on %t")
2572 (refile . "Refiled on %t")
2573 (clock-out . ""))
2574 "Headings for notes added to entries.
2575 The value is an alist, with the car being a symbol indicating the note
2576 context, and the cdr is the heading to be used. The heading may also be the
2577 empty string.
2578 %t in the heading will be replaced by a time stamp.
2579 %T will be an active time stamp instead the default inactive one
2580 %d will be replaced by a short-format time stamp.
2581 %D will be replaced by an active short-format time stamp.
2582 %s will be replaced by the new TODO state, in double quotes.
2583 %S will be replaced by the old TODO state, in double quotes.
2584 %u will be replaced by the user name.
2585 %U will be replaced by the full user name.
2587 In fact, it is not a good idea to change the `state' entry, because
2588 agenda log mode depends on the format of these entries."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(list :greedy t
2592 (cons (const :tag "Heading when closing an item" done) string)
2593 (cons (const :tag
2594 "Heading when changing todo state (todo sequence only)"
2595 state) string)
2596 (cons (const :tag "Heading when just taking a note" note) string)
2597 (cons (const :tag "Heading when clocking out" clock-out) string)
2598 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2599 (cons (const :tag "Heading when rescheduling" reschedule) string)
2600 (cons (const :tag "Heading when changing deadline" redeadline) string)
2601 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2602 (cons (const :tag "Heading when refiling" refile) string)))
2604 (unless (assq 'note org-log-note-headings)
2605 (push '(note . "%t") org-log-note-headings))
2607 (defcustom org-log-into-drawer nil
2608 "Non-nil means insert state change notes and time stamps into a drawer.
2609 When nil, state changes notes will be inserted after the headline and
2610 any scheduling and clock lines, but not inside a drawer.
2612 The value of this variable should be the name of the drawer to use.
2613 LOGBOOK is proposed as the default drawer for this purpose, you can
2614 also set this to a string to define the drawer of your choice.
2616 A value of t is also allowed, representing \"LOGBOOK\".
2618 A value of t or nil can also be set with on a per-file-basis with
2620 #+STARTUP: logdrawer
2621 #+STARTUP: nologdrawer
2623 If this variable is set, `org-log-state-notes-insert-after-drawers'
2624 will be ignored.
2626 You can set the property LOG_INTO_DRAWER to overrule this setting for
2627 a subtree."
2628 :group 'org-todo
2629 :group 'org-progress
2630 :type '(choice
2631 (const :tag "Not into a drawer" nil)
2632 (const :tag "LOGBOOK" t)
2633 (string :tag "Other")))
2635 (if (fboundp 'defvaralias)
2636 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2638 (defun org-log-into-drawer ()
2639 "Return the value of `org-log-into-drawer', but let properties overrule.
2640 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2641 used instead of the default value."
2642 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2643 (cond
2644 ((not p) org-log-into-drawer)
2645 ((equal p "nil") nil)
2646 ((equal p "t") "LOGBOOK")
2647 (t p))))
2649 (defcustom org-log-state-notes-insert-after-drawers nil
2650 "Non-nil means insert state change notes after any drawers in entry.
2651 Only the drawers that *immediately* follow the headline and the
2652 deadline/scheduled line are skipped.
2653 When nil, insert notes right after the heading and perhaps the line
2654 with deadline/scheduling if present.
2656 This variable will have no effect if `org-log-into-drawer' is
2657 set."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-log-states-order-reversed t
2663 "Non-nil means the latest state note will be directly after heading.
2664 When nil, the state change notes will be ordered according to time.
2666 This option can also be set with on a per-file-basis with
2668 #+STARTUP: logstatesreversed
2669 #+STARTUP: nologstatesreversed"
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type 'boolean)
2674 (defcustom org-todo-repeat-to-state nil
2675 "The TODO state to which a repeater should return the repeating task.
2676 By default this is the first task in a TODO sequence, or the previous state
2677 in a TODO_TYP set. But you can specify another task here.
2678 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2679 :group 'org-todo
2680 :version "24.1"
2681 :type '(choice (const :tag "Head of sequence" nil)
2682 (string :tag "Specific state")))
2684 (defcustom org-log-repeat 'time
2685 "Non-nil means record moving through the DONE state when triggering repeat.
2686 An auto-repeating task is immediately switched back to TODO when
2687 marked DONE. If you are not logging state changes (by adding \"@\"
2688 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2689 record a closing note, there will be no record of the task moving
2690 through DONE. This variable forces taking a note anyway.
2692 nil Don't force a record
2693 time Record a time stamp
2694 note Prompt for a note and add it with template `org-log-note-headings'
2696 This option can also be set with on a per-file-basis with
2698 #+STARTUP: nologrepeat
2699 #+STARTUP: logrepeat
2700 #+STARTUP: lognoterepeat
2702 You can have local logging settings for a subtree by setting the LOGGING
2703 property to one or more of these keywords."
2704 :group 'org-todo
2705 :group 'org-progress
2706 :type '(choice
2707 (const :tag "Don't force a record" nil)
2708 (const :tag "Force recording the DONE state" time)
2709 (const :tag "Force recording a note with the DONE state" note)))
2712 (defgroup org-priorities nil
2713 "Priorities in Org-mode."
2714 :tag "Org Priorities"
2715 :group 'org-todo)
2717 (defcustom org-enable-priority-commands t
2718 "Non-nil means priority commands are active.
2719 When nil, these commands will be disabled, so that you never accidentally
2720 set a priority."
2721 :group 'org-priorities
2722 :type 'boolean)
2724 (defcustom org-highest-priority ?A
2725 "The highest priority of TODO items. A character like ?A, ?B etc.
2726 Must have a smaller ASCII number than `org-lowest-priority'."
2727 :group 'org-priorities
2728 :type 'character)
2730 (defcustom org-lowest-priority ?C
2731 "The lowest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a larger ASCII number than `org-highest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-default-priority ?B
2737 "The default priority of TODO items.
2738 This is the priority an item gets if no explicit priority is given.
2739 When starting to cycle on an empty priority the first step in the cycle
2740 depends on `org-priority-start-cycle-with-default'. The resulting first
2741 step priority must not exceed the range from `org-highest-priority' to
2742 `org-lowest-priority' which means that `org-default-priority' has to be
2743 in this range exclusive or inclusive the range boundaries. Else the
2744 first step refuses to set the default and the second will fall back
2745 to (depending on the command used) the highest or lowest priority."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-priority-start-cycle-with-default t
2750 "Non-nil means start with default priority when starting to cycle.
2751 When this is nil, the first step in the cycle will be (depending on the
2752 command used) one higher or lower than the default priority.
2753 See also `org-default-priority'."
2754 :group 'org-priorities
2755 :type 'boolean)
2757 (defcustom org-get-priority-function nil
2758 "Function to extract the priority from a string.
2759 The string is normally the headline. If this is nil Org computes the
2760 priority from the priority cookie like [#A] in the headline. It returns
2761 an integer, increasing by 1000 for each priority level.
2762 The user can set a different function here, which should take a string
2763 as an argument and return the numeric priority."
2764 :group 'org-priorities
2765 :version "24.1"
2766 :type 'function)
2768 (defgroup org-time nil
2769 "Options concerning time stamps and deadlines in Org-mode."
2770 :tag "Org Time"
2771 :group 'org)
2773 (defcustom org-insert-labeled-timestamps-at-point nil
2774 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2775 When nil, these labeled time stamps are forces into the second line of an
2776 entry, just after the headline. When scheduling from the global TODO list,
2777 the time stamp will always be forced into the second line."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2782 "Formats for `format-time-string' which are used for time stamps.
2783 It is not recommended to change this constant.")
2785 (defcustom org-time-stamp-rounding-minutes '(0 5)
2786 "Number of minutes to round time stamps to.
2787 These are two values, the first applies when first creating a time stamp.
2788 The second applies when changing it with the commands `S-up' and `S-down'.
2789 When changing the time stamp, this means that it will change in steps
2790 of N minutes, as given by the second value.
2792 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2793 numbers should be factors of 60, so for example 5, 10, 15.
2795 When this is larger than 1, you can still force an exact time stamp by using
2796 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2797 and by using a prefix arg to `S-up/down' to specify the exact number
2798 of minutes to shift."
2799 :group 'org-time
2800 :get #'(lambda (var) ; Make sure both elements are there
2801 (if (integerp (default-value var))
2802 (list (default-value var) 5)
2803 (default-value var)))
2804 :type '(list
2805 (integer :tag "when inserting times")
2806 (integer :tag "when modifying times")))
2808 ;; Normalize old customizations of this variable.
2809 (when (integerp org-time-stamp-rounding-minutes)
2810 (setq org-time-stamp-rounding-minutes
2811 (list org-time-stamp-rounding-minutes
2812 org-time-stamp-rounding-minutes)))
2814 (defcustom org-display-custom-times nil
2815 "Non-nil means overlay custom formats over all time stamps.
2816 The formats are defined through the variable `org-time-stamp-custom-formats'.
2817 To turn this on on a per-file basis, insert anywhere in the file:
2818 #+STARTUP: customtime"
2819 :group 'org-time
2820 :set 'set-default
2821 :type 'sexp)
2822 (make-variable-buffer-local 'org-display-custom-times)
2824 (defcustom org-time-stamp-custom-formats
2825 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2826 "Custom formats for time stamps. See `format-time-string' for the syntax.
2827 These are overlaid over the default ISO format if the variable
2828 `org-display-custom-times' is set. Time like %H:%M should be at the
2829 end of the second format. The custom formats are also honored by export
2830 commands, if custom time display is turned on at the time of export."
2831 :group 'org-time
2832 :type 'sexp)
2834 (defun org-time-stamp-format (&optional long inactive)
2835 "Get the right format for a time string."
2836 (let ((f (if long (cdr org-time-stamp-formats)
2837 (car org-time-stamp-formats))))
2838 (if inactive
2839 (concat "[" (substring f 1 -1) "]")
2840 f)))
2842 (defcustom org-time-clocksum-format
2843 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2844 "The format string used when creating CLOCKSUM lines.
2845 This is also used when Org mode generates a time duration.
2847 The value can be a single format string containing two
2848 %-sequences, which will be filled with the number of hours and
2849 minutes in that order.
2851 Alternatively, the value can be a plist associating any of the
2852 keys :years, :months, :weeks, :days, :hours or :minutes with
2853 format strings. The time duration is formatted using only the
2854 time components that are needed and concatenating the results.
2855 If a time unit in absent, it falls back to the next smallest
2856 unit.
2858 The keys :require-years, :require-months, :require-days,
2859 :require-weeks, :require-hours, :require-minutes are also
2860 meaningful. A non-nil value for these keys indicates that the
2861 corresponding time component should always be included, even if
2862 its value is 0.
2865 For example,
2867 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2868 :require-minutes t)
2870 means durations longer than a day will be expressed in days,
2871 hours and minutes, and durations less than a day will always be
2872 expressed in hours and minutes (even for durations less than an
2873 hour).
2875 The value
2877 \(:days \"%dd\" :minutes \"%dm\")
2879 means durations longer than a day will be expressed in days and
2880 minutes, and durations less than a day will be expressed entirely
2881 in minutes (even for durations longer than an hour)."
2882 :group 'org-time
2883 :group 'org-clock
2884 :version "24.3"
2885 :type '(choice (string :tag "Format string")
2886 (set :tag "Plist"
2887 (group :inline t (const :tag "Years" :years)
2888 (string :tag "Format string"))
2889 (group :inline t
2890 (const :tag "Always show years" :require-years)
2891 (const t))
2892 (group :inline t (const :tag "Months" :months)
2893 (string :tag "Format string"))
2894 (group :inline t
2895 (const :tag "Always show months" :require-months)
2896 (const t))
2897 (group :inline t (const :tag "Weeks" :weeks)
2898 (string :tag "Format string"))
2899 (group :inline t
2900 (const :tag "Always show weeks" :require-weeks)
2901 (const t))
2902 (group :inline t (const :tag "Days" :days)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show days" :require-days)
2906 (const t))
2907 (group :inline t (const :tag "Hours" :hours)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show hours" :require-hours)
2911 (const t))
2912 (group :inline t (const :tag "Minutes" :minutes)
2913 (string :tag "Format string"))
2914 (group :inline t
2915 (const :tag "Always show minutes" :require-minutes)
2916 (const t)))))
2918 (defcustom org-time-clocksum-use-fractional nil
2919 "When non-nil, \\[org-clock-display] uses fractional times.
2920 See `org-time-clocksum-format' for more on time clock formats."
2921 :group 'org-time
2922 :group 'org-clock
2923 :version "24.3"
2924 :type 'boolean)
2926 (defcustom org-time-clocksum-use-effort-durations t
2927 "When non-nil, \\[org-clock-display] uses effort durations.
2928 E.g. by default, one day is considered to be a 8 hours effort,
2929 so a task that has been clocked for 16 hours will be displayed
2930 as during 2 days in the clock display or in the clocktable.
2932 See `org-effort-durations' on how to set effort durations
2933 and `org-time-clocksum-format' for more on time clock formats."
2934 :group 'org-time
2935 :group 'org-clock
2936 :version "24.3"
2937 :type 'boolean)
2939 (defcustom org-time-clocksum-fractional-format "%.2f"
2940 "The format string used when creating CLOCKSUM lines,
2941 or when Org mode generates a time duration, if
2942 `org-time-clocksum-use-fractional' is enabled.
2944 The value can be a single format string containing one
2945 %-sequence, which will be filled with the number of hours as
2946 a float.
2948 Alternatively, the value can be a plist associating any of the
2949 keys :years, :months, :weeks, :days, :hours or :minutes with
2950 a format string. The time duration is formatted using the
2951 largest time unit which gives a non-zero integer part. If all
2952 specified formats have zero integer part, the smallest time unit
2953 is used."
2954 :group 'org-time
2955 :type '(choice (string :tag "Format string")
2956 (set (group :inline t (const :tag "Years" :years)
2957 (string :tag "Format string"))
2958 (group :inline t (const :tag "Months" :months)
2959 (string :tag "Format string"))
2960 (group :inline t (const :tag "Weeks" :weeks)
2961 (string :tag "Format string"))
2962 (group :inline t (const :tag "Days" :days)
2963 (string :tag "Format string"))
2964 (group :inline t (const :tag "Hours" :hours)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string")))))
2969 (defcustom org-deadline-warning-days 14
2970 "Number of days before expiration during which a deadline becomes active.
2971 This variable governs the display in sparse trees and in the agenda.
2972 When 0 or negative, it means use this number (the absolute value of it)
2973 even if a deadline has a different individual lead time specified.
2975 Custom commands can set this variable in the options section."
2976 :group 'org-time
2977 :group 'org-agenda-daily/weekly
2978 :type 'integer)
2980 (defcustom org-scheduled-delay-days 0
2981 "Number of days before a scheduled item becomes active.
2982 This variable governs the display in sparse trees and in the agenda.
2983 The default value (i.e. 0) means: don't delay scheduled item.
2984 When negative, it means use this number (the absolute value of it)
2985 even if a scheduled item has a different individual delay time
2986 specified.
2988 Custom commands can set this variable in the options section."
2989 :group 'org-time
2990 :group 'org-agenda-daily/weekly
2991 :version "24.3"
2992 :type 'integer)
2994 (defcustom org-read-date-prefer-future t
2995 "Non-nil means assume future for incomplete date input from user.
2996 This affects the following situations:
2997 1. The user gives a month but not a year.
2998 For example, if it is April and you enter \"feb 2\", this will be read
2999 as Feb 2, *next* year. \"May 5\", however, will be this year.
3000 2. The user gives a day, but no month.
3001 For example, if today is the 15th, and you enter \"3\", Org-mode will
3002 read this as the third of *next* month. However, if you enter \"17\",
3003 it will be considered as *this* month.
3005 If you set this variable to the symbol `time', then also the following
3006 will work:
3008 3. If the user gives a time.
3009 If the time is before now, it will be interpreted as tomorrow.
3011 Currently none of this works for ISO week specifications.
3013 When this option is nil, the current day, month and year will always be
3014 used as defaults.
3016 See also `org-agenda-jump-prefer-future'."
3017 :group 'org-time
3018 :type '(choice
3019 (const :tag "Never" nil)
3020 (const :tag "Check month and day" t)
3021 (const :tag "Check month, day, and time" time)))
3023 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3024 "Should the agenda jump command prefer the future for incomplete dates?
3025 The default is to do the same as configured in `org-read-date-prefer-future'.
3026 But you can also set a deviating value here.
3027 This may t or nil, or the symbol `org-read-date-prefer-future'."
3028 :group 'org-agenda
3029 :group 'org-time
3030 :version "24.1"
3031 :type '(choice
3032 (const :tag "Use org-read-date-prefer-future"
3033 org-read-date-prefer-future)
3034 (const :tag "Never" nil)
3035 (const :tag "Always" t)))
3037 (defcustom org-read-date-force-compatible-dates t
3038 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3040 Depending on the system Emacs is running on, certain dates cannot
3041 be represented with the type used internally to represent time.
3042 Dates between 1970-1-1 and 2038-1-1 can always be represented
3043 correctly. Some systems allow for earlier dates, some for later,
3044 some for both. One way to find out it to insert any date into an
3045 Org buffer, putting the cursor on the year and hitting S-up and
3046 S-down to test the range.
3048 When this variable is set to t, the date/time prompt will not let
3049 you specify dates outside the 1970-2037 range, so it is certain that
3050 these dates will work in whatever version of Emacs you are
3051 running, and also that you can move a file from one Emacs implementation
3052 to another. WHenever Org is forcing the year for you, it will display
3053 a message and beep.
3055 When this variable is nil, Org will check if the date is
3056 representable in the specific Emacs implementation you are using.
3057 If not, it will force a year, usually the current year, and beep
3058 to remind you. Currently this setting is not recommended because
3059 the likelihood that you will open your Org files in an Emacs that
3060 has limited date range is not negligible.
3062 A workaround for this problem is to use diary sexp dates for time
3063 stamps outside of this range."
3064 :group 'org-time
3065 :version "24.1"
3066 :type 'boolean)
3068 (defcustom org-read-date-display-live t
3069 "Non-nil means display current interpretation of date prompt live.
3070 This display will be in an overlay, in the minibuffer."
3071 :group 'org-time
3072 :type 'boolean)
3074 (defcustom org-read-date-popup-calendar t
3075 "Non-nil means pop up a calendar when prompting for a date.
3076 In the calendar, the date can be selected with mouse-1. However, the
3077 minibuffer will also be active, and you can simply enter the date as well.
3078 When nil, only the minibuffer will be available."
3079 :group 'org-time
3080 :type 'boolean)
3081 (if (fboundp 'defvaralias)
3082 (defvaralias 'org-popup-calendar-for-date-prompt
3083 'org-read-date-popup-calendar))
3085 (make-obsolete-variable
3086 'org-read-date-minibuffer-setup-hook
3087 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3088 (defcustom org-read-date-minibuffer-setup-hook nil
3089 "Hook to be used to set up keys for the date/time interface.
3090 Add key definitions to `minibuffer-local-map', which will be a
3091 temporary copy.
3093 WARNING: This option is obsolete, you should use
3094 `org-read-date-minibuffer-local-map' to set up keys."
3095 :group 'org-time
3096 :type 'hook)
3098 (defcustom org-extend-today-until 0
3099 "The hour when your day really ends. Must be an integer.
3100 This has influence for the following applications:
3101 - When switching the agenda to \"today\". It it is still earlier than
3102 the time given here, the day recognized as TODAY is actually yesterday.
3103 - When a date is read from the user and it is still before the time given
3104 here, the current date and time will be assumed to be yesterday, 23:59.
3105 Also, timestamps inserted in capture templates follow this rule.
3107 IMPORTANT: This is a feature whose implementation is and likely will
3108 remain incomplete. Really, it is only here because past midnight seems to
3109 be the favorite working time of John Wiegley :-)"
3110 :group 'org-time
3111 :type 'integer)
3113 (defcustom org-use-effective-time nil
3114 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3115 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3116 \"effective time\" of any timestamps between midnight and 8am will be
3117 23:59 of the previous day."
3118 :group 'org-time
3119 :version "24.1"
3120 :type 'boolean)
3122 (defcustom org-use-last-clock-out-time-as-effective-time nil
3123 "When non-nil, use the last clock out time for `org-todo'.
3124 Note that this option has precedence over the combined use of
3125 `org-use-effective-time' and `org-extend-today-until'."
3126 :group 'org-time
3127 ;; :version "24.3"
3128 :type 'boolean)
3130 (defcustom org-edit-timestamp-down-means-later nil
3131 "Non-nil means S-down will increase the time in a time stamp.
3132 When nil, S-up will increase."
3133 :group 'org-time
3134 :type 'boolean)
3136 (defcustom org-calendar-follow-timestamp-change t
3137 "Non-nil means make the calendar window follow timestamp changes.
3138 When a timestamp is modified and the calendar window is visible, it will be
3139 moved to the new date."
3140 :group 'org-time
3141 :type 'boolean)
3143 (defgroup org-tags nil
3144 "Options concerning tags in Org-mode."
3145 :tag "Org Tags"
3146 :group 'org)
3148 (defcustom org-tag-alist nil
3149 "List of tags allowed in Org-mode files.
3150 When this list is nil, Org-mode will base TAG input on what is already in the
3151 buffer.
3152 The value of this variable is an alist, the car of each entry must be a
3153 keyword as a string, the cdr may be a character that is used to select
3154 that tag through the fast-tag-selection interface.
3155 See the manual for details."
3156 :group 'org-tags
3157 :type '(repeat
3158 (choice
3159 (cons (string :tag "Tag name")
3160 (character :tag "Access char"))
3161 (list :tag "Start radio group"
3162 (const :startgroup)
3163 (option (string :tag "Group description")))
3164 (list :tag "End radio group"
3165 (const :endgroup)
3166 (option (string :tag "Group description")))
3167 (const :tag "New line" (:newline)))))
3169 (defcustom org-tag-persistent-alist nil
3170 "List of tags that will always appear in all Org-mode files.
3171 This is in addition to any in buffer settings or customizations
3172 of `org-tag-alist'.
3173 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3174 The value of this variable is an alist, the car of each entry must be a
3175 keyword as a string, the cdr may be a character that is used to select
3176 that tag through the fast-tag-selection interface.
3177 See the manual for details.
3178 To disable these tags on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: noptag"
3180 :group 'org-tags
3181 :type '(repeat
3182 (choice
3183 (cons (string :tag "Tag name")
3184 (character :tag "Access char"))
3185 (const :tag "Start radio group" (:startgroup))
3186 (const :tag "End radio group" (:endgroup))
3187 (const :tag "New line" (:newline)))))
3189 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3190 "If non-nil, always offer completion for all tags of all agenda files.
3191 Instead of customizing this variable directly, you might want to
3192 set it locally for capture buffers, because there no list of
3193 tags in that file can be created dynamically (there are none).
3195 (add-hook 'org-capture-mode-hook
3196 (lambda ()
3197 (set (make-local-variable
3198 'org-complete-tags-always-offer-all-agenda-tags)
3199 t)))"
3200 :group 'org-tags
3201 :version "24.1"
3202 :type 'boolean)
3204 (defvar org-file-tags nil
3205 "List of tags that can be inherited by all entries in the file.
3206 The tags will be inherited if the variable `org-use-tag-inheritance'
3207 says they should be.
3208 This variable is populated from #+FILETAGS lines.")
3210 (defcustom org-use-fast-tag-selection 'auto
3211 "Non-nil means use fast tag selection scheme.
3212 This is a special interface to select and deselect tags with single keys.
3213 When nil, fast selection is never used.
3214 When the symbol `auto', fast selection is used if and only if selection
3215 characters for tags have been configured, either through the variable
3216 `org-tag-alist' or through a #+TAGS line in the buffer.
3217 When t, fast selection is always used and selection keys are assigned
3218 automatically if necessary."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "Always" t)
3222 (const :tag "Never" nil)
3223 (const :tag "When selection characters are configured" 'auto)))
3225 (defcustom org-fast-tag-selection-single-key nil
3226 "Non-nil means fast tag selection exits after first change.
3227 When nil, you have to press RET to exit it.
3228 During fast tag selection, you can toggle this flag with `C-c'.
3229 This variable can also have the value `expert'. In this case, the window
3230 displaying the tags menu is not even shown, until you press C-c again."
3231 :group 'org-tags
3232 :type '(choice
3233 (const :tag "No" nil)
3234 (const :tag "Yes" t)
3235 (const :tag "Expert" expert)))
3237 (defvar org-fast-tag-selection-include-todo nil
3238 "Non-nil means fast tags selection interface will also offer TODO states.
3239 This is an undocumented feature, you should not rely on it.")
3241 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3242 "The column to which tags should be indented in a headline.
3243 If this number is positive, it specifies the column. If it is negative,
3244 it means that the tags should be flushright to that column. For example,
3245 -80 works well for a normal 80 character screen.
3246 When 0, place tags directly after headline text, with only one space in
3247 between."
3248 :group 'org-tags
3249 :type 'integer)
3251 (defcustom org-auto-align-tags t
3252 "Non-nil keeps tags aligned when modifying headlines.
3253 Some operations (i.e. demoting) change the length of a headline and
3254 therefore shift the tags around. With this option turned on, after
3255 each such operation the tags are again aligned to `org-tags-column'."
3256 :group 'org-tags
3257 :type 'boolean)
3259 (defcustom org-use-tag-inheritance t
3260 "Non-nil means tags in levels apply also for sublevels.
3261 When nil, only the tags directly given in a specific line apply there.
3262 This may also be a list of tags that should be inherited, or a regexp that
3263 matches tags that should be inherited. Additional control is possible
3264 with the variable `org-tags-exclude-from-inheritance' which gives an
3265 explicit list of tags to be excluded from inheritance, even if the value of
3266 `org-use-tag-inheritance' would select it for inheritance.
3268 If this option is t, a match early-on in a tree can lead to a large
3269 number of matches in the subtree when constructing the agenda or creating
3270 a sparse tree. If you only want to see the first match in a tree during
3271 a search, check out the variable `org-tags-match-list-sublevels'."
3272 :group 'org-tags
3273 :type '(choice
3274 (const :tag "Not" nil)
3275 (const :tag "Always" t)
3276 (repeat :tag "Specific tags" (string :tag "Tag"))
3277 (regexp :tag "Tags matched by regexp")))
3279 (defcustom org-tags-exclude-from-inheritance nil
3280 "List of tags that should never be inherited.
3281 This is a way to exclude a few tags from inheritance. For way to do
3282 the opposite, to actively allow inheritance for selected tags,
3283 see the variable `org-use-tag-inheritance'."
3284 :group 'org-tags
3285 :type '(repeat (string :tag "Tag")))
3287 (defun org-tag-inherit-p (tag)
3288 "Check if TAG is one that should be inherited."
3289 (cond
3290 ((member tag org-tags-exclude-from-inheritance) nil)
3291 ((eq org-use-tag-inheritance t) t)
3292 ((not org-use-tag-inheritance) nil)
3293 ((stringp org-use-tag-inheritance)
3294 (string-match org-use-tag-inheritance tag))
3295 ((listp org-use-tag-inheritance)
3296 (member tag org-use-tag-inheritance))
3297 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3299 (defcustom org-tags-match-list-sublevels t
3300 "Non-nil means list also sublevels of headlines matching a search.
3301 This variable applies to tags/property searches, and also to stuck
3302 projects because this search is based on a tags match as well.
3304 When set to the symbol `indented', sublevels are indented with
3305 leading dots.
3307 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3308 the sublevels of a headline matching a tag search often also match
3309 the same search. Listing all of them can create very long lists.
3310 Setting this variable to nil causes subtrees of a match to be skipped.
3312 This variable is semi-obsolete and probably should always be true. It
3313 is better to limit inheritance to certain tags using the variables
3314 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3315 :group 'org-tags
3316 :type '(choice
3317 (const :tag "No, don't list them" nil)
3318 (const :tag "Yes, do list them" t)
3319 (const :tag "List them, indented with leading dots" indented)))
3321 (defcustom org-tags-sort-function nil
3322 "When set, tags are sorted using this function as a comparator."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "No sorting" nil)
3326 (const :tag "Alphabetical" string<)
3327 (const :tag "Reverse alphabetical" string>)
3328 (function :tag "Custom function" nil)))
3330 (defvar org-tags-history nil
3331 "History of minibuffer reads for tags.")
3332 (defvar org-last-tags-completion-table nil
3333 "The last used completion table for tags.")
3334 (defvar org-after-tags-change-hook nil
3335 "Hook that is run after the tags in a line have changed.")
3337 (defgroup org-properties nil
3338 "Options concerning properties in Org-mode."
3339 :tag "Org Properties"
3340 :group 'org)
3342 (defcustom org-property-format "%-10s %s"
3343 "How property key/value pairs should be formatted by `indent-line'.
3344 When `indent-line' hits a property definition, it will format the line
3345 according to this format, mainly to make sure that the values are
3346 lined-up with respect to each other."
3347 :group 'org-properties
3348 :type 'string)
3350 (defcustom org-properties-postprocess-alist nil
3351 "Alist of properties and functions to adjust inserted values.
3352 Elements of this alist must be of the form
3354 ([string] [function])
3356 where [string] must be a property name and [function] must be a
3357 lambda expression: this lambda expression must take one argument,
3358 the value to adjust, and return the new value as a string.
3360 For example, this element will allow the property \"Remaining\"
3361 to be updated wrt the relation between the \"Effort\" property
3362 and the clock summary:
3364 ((\"Remaining\" (lambda(value)
3365 (let ((clocksum (org-clock-sum-current-item))
3366 (effort (org-duration-string-to-minutes
3367 (org-entry-get (point) \"Effort\"))))
3368 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3369 :group 'org-properties
3370 :version "24.1"
3371 :type '(alist :key-type (string :tag "Property")
3372 :value-type (function :tag "Function")))
3374 (defcustom org-use-property-inheritance nil
3375 "Non-nil means properties apply also for sublevels.
3377 This setting is chiefly used during property searches. Turning it on can
3378 cause significant overhead when doing a search, which is why it is not
3379 on by default.
3381 When nil, only the properties directly given in the current entry count.
3382 When t, every property is inherited. The value may also be a list of
3383 properties that should have inheritance, or a regular expression matching
3384 properties that should be inherited.
3386 However, note that some special properties use inheritance under special
3387 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3388 and the properties ending in \"_ALL\" when they are used as descriptor
3389 for valid values of a property.
3391 Note for programmers:
3392 When querying an entry with `org-entry-get', you can control if inheritance
3393 should be used. By default, `org-entry-get' looks only at the local
3394 properties. You can request inheritance by setting the inherit argument
3395 to t (to force inheritance) or to `selective' (to respect the setting
3396 in this variable)."
3397 :group 'org-properties
3398 :type '(choice
3399 (const :tag "Not" nil)
3400 (const :tag "Always" t)
3401 (repeat :tag "Specific properties" (string :tag "Property"))
3402 (regexp :tag "Properties matched by regexp")))
3404 (defun org-property-inherit-p (property)
3405 "Check if PROPERTY is one that should be inherited."
3406 (cond
3407 ((eq org-use-property-inheritance t) t)
3408 ((not org-use-property-inheritance) nil)
3409 ((stringp org-use-property-inheritance)
3410 (string-match org-use-property-inheritance property))
3411 ((listp org-use-property-inheritance)
3412 (member property org-use-property-inheritance))
3413 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3415 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3416 "The default column format, if no other format has been defined.
3417 This variable can be set on the per-file basis by inserting a line
3419 #+COLUMNS: %25ITEM ....."
3420 :group 'org-properties
3421 :type 'string)
3423 (defcustom org-columns-ellipses ".."
3424 "The ellipses to be used when a field in column view is truncated.
3425 When this is the empty string, as many characters as possible are shown,
3426 but then there will be no visual indication that the field has been truncated.
3427 When this is a string of length N, the last N characters of a truncated
3428 field are replaced by this string. If the column is narrower than the
3429 ellipses string, only part of the ellipses string will be shown."
3430 :group 'org-properties
3431 :type 'string)
3433 (defcustom org-columns-modify-value-for-display-function nil
3434 "Function that modifies values for display in column view.
3435 For example, it can be used to cut out a certain part from a time stamp.
3436 The function must take 2 arguments:
3438 column-title The title of the column (*not* the property name)
3439 value The value that should be modified.
3441 The function should return the value that should be displayed,
3442 or nil if the normal value should be used."
3443 :group 'org-properties
3444 :type 'function)
3446 (defcustom org-effort-property "Effort"
3447 "The property that is being used to keep track of effort estimates.
3448 Effort estimates given in this property need to have the format H:MM."
3449 :group 'org-properties
3450 :group 'org-progress
3451 :type '(string :tag "Property"))
3453 (defconst org-global-properties-fixed
3454 '(("VISIBILITY_ALL" . "folded children content all")
3455 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3456 "List of property/value pairs that can be inherited by any entry.
3458 These are fixed values, for the preset properties. The user variable
3459 that can be used to add to this list is `org-global-properties'.
3461 The entries in this list are cons cells where the car is a property
3462 name and cdr is a string with the value. If the value represents
3463 multiple items like an \"_ALL\" property, separate the items by
3464 spaces.")
3466 (defcustom org-global-properties nil
3467 "List of property/value pairs that can be inherited by any entry.
3469 This list will be combined with the constant `org-global-properties-fixed'.
3471 The entries in this list are cons cells where the car is a property
3472 name and cdr is a string with the value.
3474 You can set buffer-local values for the same purpose in the variable
3475 `org-file-properties' this by adding lines like
3477 #+PROPERTY: NAME VALUE"
3478 :group 'org-properties
3479 :type '(repeat
3480 (cons (string :tag "Property")
3481 (string :tag "Value"))))
3483 (defvar org-file-properties nil
3484 "List of property/value pairs that can be inherited by any entry.
3485 Valid for the current buffer.
3486 This variable is populated from #+PROPERTY lines.")
3487 (make-variable-buffer-local 'org-file-properties)
3489 (defgroup org-agenda nil
3490 "Options concerning agenda views in Org-mode."
3491 :tag "Org Agenda"
3492 :group 'org)
3494 (defvar org-category nil
3495 "Variable used by org files to set a category for agenda display.
3496 Such files should use a file variable to set it, for example
3498 # -*- mode: org; org-category: \"ELisp\"
3500 or contain a special line
3502 #+CATEGORY: ELisp
3504 If the file does not specify a category, then file's base name
3505 is used instead.")
3506 (make-variable-buffer-local 'org-category)
3507 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3509 (defcustom org-agenda-files nil
3510 "The files to be used for agenda display.
3511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3512 \\[org-remove-file]. You can also use customize to edit the list.
3514 If an entry is a directory, all files in that directory that are matched by
3515 `org-agenda-file-regexp' will be part of the file list.
3517 If the value of the variable is not a list but a single file name, then
3518 the list of agenda files is actually stored and maintained in that file, one
3519 agenda file per line. In this file paths can be given relative to
3520 `org-directory'. Tilde expansion and environment variable substitution
3521 are also made."
3522 :group 'org-agenda
3523 :type '(choice
3524 (repeat :tag "List of files and directories" file)
3525 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3527 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3528 "Regular expression to match files for `org-agenda-files'.
3529 If any element in the list in that variable contains a directory instead
3530 of a normal file, all files in that directory that are matched by this
3531 regular expression will be included."
3532 :group 'org-agenda
3533 :type 'regexp)
3535 (defcustom org-agenda-text-search-extra-files nil
3536 "List of extra files to be searched by text search commands.
3537 These files will be search in addition to the agenda files by the
3538 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3539 Note that these files will only be searched for text search commands,
3540 not for the other agenda views like todo lists, tag searches or the weekly
3541 agenda. This variable is intended to list notes and possibly archive files
3542 that should also be searched by these two commands.
3543 In fact, if the first element in the list is the symbol `agenda-archives',
3544 than all archive files of all agenda files will be added to the search
3545 scope."
3546 :group 'org-agenda
3547 :type '(set :greedy t
3548 (const :tag "Agenda Archives" agenda-archives)
3549 (repeat :inline t (file))))
3551 (if (fboundp 'defvaralias)
3552 (defvaralias 'org-agenda-multi-occur-extra-files
3553 'org-agenda-text-search-extra-files))
3555 (defcustom org-agenda-skip-unavailable-files nil
3556 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3557 A nil value means to remove them, after a query, from the list."
3558 :group 'org-agenda
3559 :type 'boolean)
3561 (defcustom org-calendar-to-agenda-key [?c]
3562 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3563 The command `org-calendar-goto-agenda' will be bound to this key. The
3564 default is the character `c' because then `c' can be used to switch back and
3565 forth between agenda and calendar."
3566 :group 'org-agenda
3567 :type 'sexp)
3569 (defcustom org-calendar-insert-diary-entry-key [?i]
3570 "The key to be installed in `calendar-mode-map' for adding diary entries.
3571 This option is irrelevant until `org-agenda-diary-file' has been configured
3572 to point to an Org-mode file. When that is the case, the command
3573 `org-agenda-diary-entry' will be bound to the key given here, by default
3574 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3575 if you want to continue doing this, you need to change this to a different
3576 key."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-agenda-diary-file 'diary-file
3581 "File to which to add new entries with the `i' key in agenda and calendar.
3582 When this is the symbol `diary-file', the functionality in the Emacs
3583 calendar will be used to add entries to the `diary-file'. But when this
3584 points to a file, `org-agenda-diary-entry' will be used instead."
3585 :group 'org-agenda
3586 :type '(choice
3587 (const :tag "The standard Emacs diary file" diary-file)
3588 (file :tag "Special Org file diary entries")))
3590 (eval-after-load "calendar"
3591 '(progn
3592 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3593 'org-calendar-goto-agenda)
3594 (add-hook 'calendar-mode-hook
3595 (lambda ()
3596 (unless (eq org-agenda-diary-file 'diary-file)
3597 (define-key calendar-mode-map
3598 org-calendar-insert-diary-entry-key
3599 'org-agenda-diary-entry))))))
3601 (defgroup org-latex nil
3602 "Options for embedding LaTeX code into Org-mode."
3603 :tag "Org LaTeX"
3604 :group 'org)
3606 (defcustom org-format-latex-options
3607 '(:foreground default :background default :scale 1.0
3608 :html-foreground "Black" :html-background "Transparent"
3609 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3610 "Options for creating images from LaTeX fragments.
3611 This is a property list with the following properties:
3612 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3613 `default' means use the foreground of the default face.
3614 `auto' means use the foreground from the text face.
3615 :background the background color, or \"Transparent\".
3616 `default' means use the background of the default face.
3617 `auto' means use the background from the text face.
3618 :scale a scaling factor for the size of the images, to get more pixels
3619 :html-foreground, :html-background, :html-scale
3620 the same numbers for HTML export.
3621 :matchers a list indicating which matchers should be used to
3622 find LaTeX fragments. Valid members of this list are:
3623 \"begin\" find environments
3624 \"$1\" find single characters surrounded by $.$
3625 \"$\" find math expressions surrounded by $...$
3626 \"$$\" find math expressions surrounded by $$....$$
3627 \"\\(\" find math expressions surrounded by \\(...\\)
3628 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3629 :group 'org-latex
3630 :type 'plist)
3632 (defcustom org-format-latex-signal-error t
3633 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3634 When nil, just push out a message."
3635 :group 'org-latex
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-latex-to-mathml-jar-file nil
3640 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3641 Use this to specify additional executable file say a jar file.
3643 When using MathToWeb as the converter, specify the full-path to
3644 your mathtoweb.jar file."
3645 :group 'org-latex
3646 :version "24.1"
3647 :type '(choice
3648 (const :tag "None" nil)
3649 (file :tag "JAR file" :must-match t)))
3651 (defcustom org-latex-to-mathml-convert-command nil
3652 "Command to convert LaTeX fragments to MathML.
3653 Replace format-specifiers in the command as noted below and use
3654 `shell-command' to convert LaTeX to MathML.
3655 %j: Executable file in fully expanded form as specified by
3656 `org-latex-to-mathml-jar-file'.
3657 %I: Input LaTeX file in fully expanded form
3658 %o: Output MathML file
3659 This command is used by `org-create-math-formula'.
3661 When using MathToWeb as the converter, set this to
3662 \"java -jar %j -unicode -force -df %o %I\"."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (string :tag "\nShell command")))
3669 (defcustom org-latex-create-formula-image-program 'dvipng
3670 "Program to convert LaTeX fragments with.
3672 dvipng Process the LaTeX fragments to dvi file, then convert
3673 dvi files to png files using dvipng.
3674 This will also include processing of non-math environments.
3675 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3676 to convert pdf files to png files"
3677 :group 'org-latex
3678 :version "24.1"
3679 :type '(choice
3680 (const :tag "dvipng" dvipng)
3681 (const :tag "imagemagick" imagemagick)))
3683 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3684 "Path to store latex preview images.
3685 A relative path here creates many directories relative to the
3686 processed org files paths. An absolute path puts all preview
3687 images at the same place."
3688 :group 'org-latex
3689 :version "24.3"
3690 :type 'string)
3692 (defun org-format-latex-mathml-available-p ()
3693 "Return t if `org-latex-to-mathml-convert-command' is usable."
3694 (save-match-data
3695 (when (and (boundp 'org-latex-to-mathml-convert-command)
3696 org-latex-to-mathml-convert-command)
3697 (let ((executable (car (split-string
3698 org-latex-to-mathml-convert-command))))
3699 (when (executable-find executable)
3700 (if (string-match
3701 "%j" org-latex-to-mathml-convert-command)
3702 (file-readable-p org-latex-to-mathml-jar-file)
3703 t))))))
3705 (defcustom org-format-latex-header "\\documentclass{article}
3706 \\usepackage[usenames]{color}
3707 \\usepackage{amsmath}
3708 \\usepackage[mathscr]{eucal}
3709 \\pagestyle{empty} % do not remove
3710 \[PACKAGES]
3711 \[DEFAULT-PACKAGES]
3712 % The settings below are copied from fullpage.sty
3713 \\setlength{\\textwidth}{\\paperwidth}
3714 \\addtolength{\\textwidth}{-3cm}
3715 \\setlength{\\oddsidemargin}{1.5cm}
3716 \\addtolength{\\oddsidemargin}{-2.54cm}
3717 \\setlength{\\evensidemargin}{\\oddsidemargin}
3718 \\setlength{\\textheight}{\\paperheight}
3719 \\addtolength{\\textheight}{-\\headheight}
3720 \\addtolength{\\textheight}{-\\headsep}
3721 \\addtolength{\\textheight}{-\\footskip}
3722 \\addtolength{\\textheight}{-3cm}
3723 \\setlength{\\topmargin}{1.5cm}
3724 \\addtolength{\\topmargin}{-2.54cm}"
3725 "The document header used for processing LaTeX fragments.
3726 It is imperative that this header make sure that no page number
3727 appears on the page. The package defined in the variables
3728 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3729 will either replace the placeholder \"[PACKAGES]\" in this
3730 header, or they will be appended."
3731 :group 'org-latex
3732 :type 'string)
3734 (defun org-set-packages-alist (var val)
3735 "Set the packages alist and make sure it has 3 elements per entry."
3736 (set var (mapcar (lambda (x)
3737 (if (and (consp x) (= (length x) 2))
3738 (list (car x) (nth 1 x) t)
3740 val)))
3742 (defun org-get-packages-alist (var)
3743 "Get the packages alist and make sure it has 3 elements per entry."
3744 (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 (default-value var)))
3750 (defcustom org-latex-default-packages-alist
3751 '(("AUTO" "inputenc" t)
3752 ("T1" "fontenc" t)
3753 ("" "fixltx2e" nil)
3754 ("" "graphicx" t)
3755 ("" "longtable" nil)
3756 ("" "float" nil)
3757 ("" "wrapfig" nil)
3758 ("" "soul" t)
3759 ("" "textcomp" t)
3760 ("" "marvosym" t)
3761 ("" "wasysym" t)
3762 ("" "latexsym" t)
3763 ("" "amssymb" t)
3764 ("" "hyperref" nil)
3765 "\\tolerance=1000")
3766 "Alist of default packages to be inserted in the header.
3768 Change this only if one of the packages here causes an
3769 incompatibility with another package you are using.
3771 The packages in this list are needed by one part or another of
3772 Org mode to function properly:
3774 - inputenc, fontenc: for basic font and character selection
3775 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3776 symbols used for interpreting the entities in `org-entities'.
3777 You can skip some of these packages if you don't use any of the
3778 symbols in it.
3779 - graphicx: for including images
3780 - float, wrapfig: for figure placement
3781 - longtable: for long tables
3782 - hyperref: for cross references
3784 Therefore you should not modify this variable unless you know
3785 what you are doing. The one reason to change it anyway is that
3786 you might be loading some other package that conflicts with one
3787 of the default packages. Each cell is of the format
3788 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3789 the package also needs to be included when compiling LaTeX
3790 snippets into images for inclusion into non-LaTeX output."
3791 :group 'org-latex
3792 :group 'org-export-latex
3793 :set 'org-set-packages-alist
3794 :get 'org-get-packages-alist
3795 :version "24.1"
3796 :type '(repeat
3797 (choice
3798 (list :tag "options/package pair"
3799 (string :tag "options")
3800 (string :tag "package")
3801 (boolean :tag "Snippet"))
3802 (string :tag "A line of LaTeX"))))
3804 (defcustom org-latex-packages-alist nil
3805 "Alist of packages to be inserted in every LaTeX header.
3807 These will be inserted after `org-latex-default-packages-alist'.
3808 Each cell is of the format:
3810 \(\"options\" \"package\" snippet-flag)
3812 SNIPPET-FLAG, when t, indicates that this package is also needed
3813 when turning LaTeX snippets into images for inclusion into
3814 non-LaTeX output.
3816 Make sure that you only list packages here which:
3818 - you want in every file
3819 - do not conflict with the setup in `org-format-latex-header'.
3820 - do not conflict with the default packages in
3821 `org-latex-default-packages-alist'."
3822 :group 'org-latex
3823 :group 'org-export-latex
3824 :set 'org-set-packages-alist
3825 :get 'org-get-packages-alist
3826 :type '(repeat
3827 (choice
3828 (list :tag "options/package pair"
3829 (string :tag "options")
3830 (string :tag "package")
3831 (boolean :tag "Snippet"))
3832 (string :tag "A line of LaTeX"))))
3834 (defgroup org-appearance nil
3835 "Settings for Org-mode appearance."
3836 :tag "Org Appearance"
3837 :group 'org)
3839 (defcustom org-level-color-stars-only nil
3840 "Non-nil means fontify only the stars in each headline.
3841 When nil, the entire headline is fontified.
3842 Changing it requires restart of `font-lock-mode' to become effective
3843 also in regions already fontified."
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hide-leading-stars nil
3848 "Non-nil means hide the first N-1 stars in a headline.
3849 This works by using the face `org-hide' for these stars. This
3850 face is white for a light background, and black for a dark
3851 background. You may have to customize the face `org-hide' to
3852 make this work.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified.
3855 You may also set this on a per-file basis by adding one of the following
3856 lines to the buffer:
3858 #+STARTUP: hidestars
3859 #+STARTUP: showstars"
3860 :group 'org-appearance
3861 :type 'boolean)
3863 (defcustom org-hidden-keywords nil
3864 "List of symbols corresponding to keywords to be hidden the org buffer.
3865 For example, a value '(title) for this list will make the document's title
3866 appear in the buffer without the initial #+TITLE: keyword."
3867 :group 'org-appearance
3868 :version "24.1"
3869 :type '(set (const :tag "#+AUTHOR" author)
3870 (const :tag "#+DATE" date)
3871 (const :tag "#+EMAIL" email)
3872 (const :tag "#+TITLE" title)))
3874 (defcustom org-custom-properties nil
3875 "List of properties (as strings) with a special meaning.
3876 The default use of these custom properties is to let the user
3877 hide them with `org-toggle-custom-properties-visibility'."
3878 :group 'org-properties
3879 :group 'org-appearance
3880 :version "24.3"
3881 :type '(repeat (string :tag "Property Name")))
3883 (defcustom org-fontify-done-headline nil
3884 "Non-nil means change the face of a headline if it is marked DONE.
3885 Normally, only the TODO/DONE keyword indicates the state of a headline.
3886 When this is non-nil, the headline after the keyword is set to the
3887 `org-headline-done' as an additional indication."
3888 :group 'org-appearance
3889 :type 'boolean)
3891 (defcustom org-fontify-emphasized-text t
3892 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3893 Changing this variable requires a restart of Emacs to take effect."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-fontify-whole-heading-line nil
3898 "Non-nil means fontify the whole line for headings.
3899 This is useful when setting a background color for the
3900 org-level-* faces."
3901 :group 'org-appearance
3902 :type 'boolean)
3904 (defcustom org-highlight-latex-and-related nil
3905 "Non-nil means highlight LaTeX related syntax in the buffer.
3906 When non nil, the value should be a list containing any of the
3907 following symbols:
3908 `latex' Highlight LaTeX snippets and environments.
3909 `script' Highlight subscript and superscript.
3910 `entities' Highlight entities."
3911 :group 'org-appearance
3912 :type '(choice
3913 (const :tag "No highlighting" nil)
3914 (set :greedy t :tag "Highlight"
3915 (const :tag "LaTeX snippets and environments" latex)
3916 (const :tag "Subscript and superscript" script)
3917 (const :tag "Entities" entities))))
3919 (defcustom org-hide-emphasis-markers nil
3920 "Non-nil mean font-lock should hide the emphasis marker characters."
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-pretty-entities nil
3925 "Non-nil means show entities as UTF8 characters.
3926 When nil, the \\name form remains in the buffer."
3927 :group 'org-appearance
3928 :version "24.1"
3929 :type 'boolean)
3931 (defcustom org-pretty-entities-include-sub-superscripts t
3932 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3933 :group 'org-appearance
3934 :version "24.1"
3935 :type 'boolean)
3937 (defvar org-emph-re nil
3938 "Regular expression for matching emphasis.
3939 After a match, the match groups contain these elements:
3940 0 The match of the full regular expression, including the characters
3941 before and after the proper match
3942 1 The character before the proper match, or empty at beginning of line
3943 2 The proper match, including the leading and trailing markers
3944 3 The leading marker like * or /, indicating the type of highlighting
3945 4 The text between the emphasis markers, not including the markers
3946 5 The character after the match, empty at the end of a line")
3947 (defvar org-verbatim-re nil
3948 "Regular expression for matching verbatim text.")
3949 (defvar org-emphasis-regexp-components) ; defined just below
3950 (defvar org-emphasis-alist) ; defined just below
3951 (defun org-set-emph-re (var val)
3952 "Set variable and compute the emphasis regular expression."
3953 (set var val)
3954 (when (and (boundp 'org-emphasis-alist)
3955 (boundp 'org-emphasis-regexp-components)
3956 org-emphasis-alist org-emphasis-regexp-components)
3957 (let* ((e org-emphasis-regexp-components)
3958 (pre (car e))
3959 (post (nth 1 e))
3960 (border (nth 2 e))
3961 (body (nth 3 e))
3962 (nl (nth 4 e))
3963 (body1 (concat body "*?"))
3964 (markers (mapconcat 'car org-emphasis-alist ""))
3965 (vmarkers (mapconcat
3966 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3967 org-emphasis-alist "")))
3968 ;; make sure special characters appear at the right position in the class
3969 (if (string-match "\\^" markers)
3970 (setq markers (concat (replace-match "" t t markers) "^")))
3971 (if (string-match "-" markers)
3972 (setq markers (concat (replace-match "" t t markers) "-")))
3973 (if (string-match "\\^" vmarkers)
3974 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3975 (if (string-match "-" vmarkers)
3976 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3977 (if (> nl 0)
3978 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3979 (int-to-string nl) "\\}")))
3980 ;; Make the regexp
3981 (setq org-emph-re
3982 (concat "\\([" pre "]\\|^\\)"
3983 "\\("
3984 "\\([" markers "]\\)"
3985 "\\("
3986 "[^" border "]\\|"
3987 "[^" border "]"
3988 body1
3989 "[^" border "]"
3990 "\\)"
3991 "\\3\\)"
3992 "\\([" post "]\\|$\\)"))
3993 (setq org-verbatim-re
3994 (concat "\\([" pre "]\\|^\\)"
3995 "\\("
3996 "\\([" vmarkers "]\\)"
3997 "\\("
3998 "[^" border "]\\|"
3999 "[^" border "]"
4000 body1
4001 "[^" border "]"
4002 "\\)"
4003 "\\3\\)"
4004 "\\([" post "]\\|$\\)")))))
4006 (defcustom org-emphasis-regexp-components
4007 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4008 "Components used to build the regular expression for emphasis.
4009 This is a list with five entries. Terminology: In an emphasis string
4010 like \" *strong word* \", we call the initial space PREMATCH, the final
4011 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4012 and \"trong wor\" is the body. The different components in this variable
4013 specify what is allowed/forbidden in each part:
4015 pre Chars allowed as prematch. Beginning of line will be allowed too.
4016 post Chars allowed as postmatch. End of line will be allowed too.
4017 border The chars *forbidden* as border characters.
4018 body-regexp A regexp like \".\" to match a body character. Don't use
4019 non-shy groups here, and don't allow newline here.
4020 newline The maximum number of newlines allowed in an emphasis exp.
4022 Use customize to modify this, or restart Emacs after changing it."
4023 :group 'org-appearance
4024 :set 'org-set-emph-re
4025 :type '(list
4026 (sexp :tag "Allowed chars in pre ")
4027 (sexp :tag "Allowed chars in post ")
4028 (sexp :tag "Forbidden chars in border ")
4029 (sexp :tag "Regexp for body ")
4030 (integer :tag "number of newlines allowed")
4031 (option (boolean :tag "Please ignore this button"))))
4033 (defcustom org-emphasis-alist
4034 `(("*" bold "<b>" "</b>")
4035 ("/" italic "<i>" "</i>")
4036 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4037 ("=" org-code "<code>" "</code>" verbatim)
4038 ("~" org-verbatim "<code>" "</code>" verbatim)
4039 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4040 "<del>" "</del>")
4042 "Special syntax for emphasized text.
4043 Text starting and ending with a special character will be emphasized, for
4044 example *bold*, _underlined_ and /italic/. This variable sets the marker
4045 characters, the face to be used by font-lock for highlighting in Org-mode
4046 Emacs buffers, and the HTML tags to be used for this.
4047 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4048 Use customize to modify this, or restart Emacs after changing it."
4049 :group 'org-appearance
4050 :set 'org-set-emph-re
4051 :type '(repeat
4052 (list
4053 (string :tag "Marker character")
4054 (choice
4055 (face :tag "Font-lock-face")
4056 (plist :tag "Face property list"))
4057 (string :tag "HTML start tag")
4058 (string :tag "HTML end tag")
4059 (option (const verbatim)))))
4061 (defvar org-protecting-blocks
4062 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4063 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4064 This is needed for font-lock setup.")
4066 ;;; Miscellaneous options
4068 (defgroup org-completion nil
4069 "Completion in Org-mode."
4070 :tag "Org Completion"
4071 :group 'org)
4073 (defcustom org-completion-use-ido nil
4074 "Non-nil means use ido completion wherever possible.
4075 Note that `ido-mode' must be active for this variable to be relevant.
4076 If you decide to turn this variable on, you might well want to turn off
4077 `org-outline-path-complete-in-steps'.
4078 See also `org-completion-use-iswitchb'."
4079 :group 'org-completion
4080 :type 'boolean)
4082 (defcustom org-completion-use-iswitchb nil
4083 "Non-nil means use iswitchb completion wherever possible.
4084 Note that `iswitchb-mode' must be active for this variable to be relevant.
4085 If you decide to turn this variable on, you might well want to turn off
4086 `org-outline-path-complete-in-steps'.
4087 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4088 :group 'org-completion
4089 :type 'boolean)
4091 (defcustom org-completion-fallback-command 'hippie-expand
4092 "The expansion command called by \\[pcomplete] in normal context.
4093 Normal means, no org-mode-specific context."
4094 :group 'org-completion
4095 :type 'function)
4097 ;;; Functions and variables from their packages
4098 ;; Declared here to avoid compiler warnings
4100 ;; XEmacs only
4101 (defvar outline-mode-menu-heading)
4102 (defvar outline-mode-menu-show)
4103 (defvar outline-mode-menu-hide)
4104 (defvar zmacs-regions) ; XEmacs regions
4106 ;; Emacs only
4107 (defvar mark-active)
4109 ;; Various packages
4110 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4111 (declare-function calendar-forward-day "cal-move" (arg))
4112 (declare-function calendar-goto-date "cal-move" (date))
4113 (declare-function calendar-goto-today "cal-move" ())
4114 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4115 (defvar calc-embedded-close-formula)
4116 (defvar calc-embedded-open-formula)
4117 (declare-function cdlatex-tab "ext:cdlatex" ())
4118 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4119 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4120 (defvar font-lock-unfontify-region-function)
4121 (declare-function iswitchb-read-buffer "iswitchb"
4122 (prompt &optional default require-match start matches-set))
4123 (defvar iswitchb-temp-buflist)
4124 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4125 (defvar org-agenda-tags-todo-honor-ignore-options)
4126 (declare-function org-agenda-skip "org-agenda" ())
4127 (declare-function
4128 org-agenda-format-item "org-agenda"
4129 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4130 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4131 (declare-function org-agenda-change-all-lines "org-agenda"
4132 (newhead hdmarker &optional fixface just-this))
4133 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4134 (declare-function org-agenda-maybe-redo "org-agenda" ())
4135 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4136 (beg end))
4137 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4138 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4139 "org-agenda" (&optional end))
4140 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4141 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4142 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4143 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4144 (declare-function org-indent-mode "org-indent" (&optional arg))
4145 (declare-function parse-time-string "parse-time" (string))
4146 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4147 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4148 (defvar remember-data-file)
4149 (defvar texmathp-why)
4150 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4151 (declare-function table--at-cell-p "table" (position &optional object at-column))
4153 (defvar org-latex-regexps)
4155 ;;; Autoload and prepare some org modules
4157 ;; Some table stuff that needs to be defined here, because it is used
4158 ;; by the functions setting up org-mode or checking for table context.
4160 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4161 "Detect an org-type or table-type table.")
4162 (defconst org-table-line-regexp "^[ \t]*|"
4163 "Detect an org-type table line.")
4164 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4165 "Detect an org-type table line.")
4166 (defconst org-table-hline-regexp "^[ \t]*|-"
4167 "Detect an org-type table hline.")
4168 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4169 "Detect a table-type table hline.")
4170 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4171 "Detect the first line outside a table when searching from within it.
4172 This works for both table types.")
4174 ;; Autoload the functions in org-table.el that are needed by functions here.
4176 (eval-and-compile
4177 (org-autoload "org-table"
4178 '(org-table-begin org-table-blank-field org-table-end)))
4180 ;;;###autoload
4181 (defun turn-on-orgtbl ()
4182 "Unconditionally turn on `orgtbl-mode'."
4183 (require 'org-table)
4184 (orgtbl-mode 1))
4186 (defun org-at-table-p (&optional table-type)
4187 "Return t if the cursor is inside an org-type table.
4188 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4189 (if org-enable-table-editor
4190 (save-excursion
4191 (beginning-of-line 1)
4192 (looking-at (if table-type org-table-any-line-regexp
4193 org-table-line-regexp)))
4194 nil))
4195 (defsubst org-table-p () (org-at-table-p))
4197 (defun org-at-table.el-p ()
4198 "Return t if and only if we are at a table.el table."
4199 (and (org-at-table-p 'any)
4200 (save-excursion
4201 (goto-char (org-table-begin 'any))
4202 (looking-at org-table1-hline-regexp))))
4203 (defun org-table-recognize-table.el ()
4204 "If there is a table.el table nearby, recognize it and move into it."
4205 (if org-table-tab-recognizes-table.el
4206 (if (org-at-table.el-p)
4207 (progn
4208 (beginning-of-line 1)
4209 (if (looking-at org-table-dataline-regexp)
4211 (if (looking-at org-table1-hline-regexp)
4212 (progn
4213 (beginning-of-line 2)
4214 (if (looking-at org-table-any-border-regexp)
4215 (beginning-of-line -1)))))
4216 (if (re-search-forward "|" (org-table-end t) t)
4217 (progn
4218 (require 'table)
4219 (if (table--at-cell-p (point))
4221 (message "recognizing table.el table...")
4222 (table-recognize-table)
4223 (message "recognizing table.el table...done")))
4224 (error "This should not happen"))
4226 nil)
4227 nil))
4229 (defun org-at-table-hline-p ()
4230 "Return t if the cursor is inside a hline in a table."
4231 (if org-enable-table-editor
4232 (save-excursion
4233 (beginning-of-line 1)
4234 (looking-at org-table-hline-regexp))
4235 nil))
4237 (defvar org-table-clean-did-remove-column nil)
4239 (defun org-table-map-tables (function &optional quietly)
4240 "Apply FUNCTION to the start of all tables in the buffer."
4241 (save-excursion
4242 (save-restriction
4243 (widen)
4244 (goto-char (point-min))
4245 (while (re-search-forward org-table-any-line-regexp nil t)
4246 (unless quietly
4247 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4248 (beginning-of-line 1)
4249 (when (and (looking-at org-table-line-regexp)
4250 ;; Exclude tables in src/example/verbatim/clocktable blocks
4251 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4252 (save-excursion (funcall function))
4253 (or (looking-at org-table-line-regexp)
4254 (forward-char 1)))
4255 (re-search-forward org-table-any-border-regexp nil 1))))
4256 (unless quietly (message "Mapping tables: done")))
4258 ;; Declare and autoload functions from ox.el and al.
4260 (declare-function org-export-get-environment "ox"
4261 (&optional backend subtreep ext-plist))
4262 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4264 ;; Declare and autoload functions from org-agenda.el
4266 (eval-and-compile
4267 (org-autoload "org-agenda"
4268 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4270 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4271 (declare-function org-clock-update-mode-line "org-clock" ())
4272 (declare-function org-resolve-clocks "org-clock"
4273 (&optional also-non-dangling-p prompt last-valid))
4274 (defvar org-clock-start-time)
4275 (defvar org-clock-marker (make-marker)
4276 "Marker recording the last clock-in.")
4277 (defvar org-clock-hd-marker (make-marker)
4278 "Marker recording the last clock-in, but the headline position.")
4279 (defvar org-clock-heading ""
4280 "The heading of the current clock entry.")
4281 (defun org-clock-is-active ()
4282 "Return non-nil if clock is currently running.
4283 The return value is actually the clock marker."
4284 (marker-buffer org-clock-marker))
4286 (eval-and-compile
4287 (org-autoload "org-clock" '(org-clock-remove-overlays
4288 org-clock-update-time-maybe
4289 org-clocktable-shift)))
4291 (defun org-check-running-clock ()
4292 "Check if the current buffer contains the running clock.
4293 If yes, offer to stop it and to save the buffer with the changes."
4294 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4295 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4296 (buffer-name))))
4297 (org-clock-out)
4298 (when (y-or-n-p "Save changed buffer?")
4299 (save-buffer))))
4301 (defun org-clocktable-try-shift (dir n)
4302 "Check if this line starts a clock table, if yes, shift the time block."
4303 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4304 (org-clocktable-shift dir n)))
4306 ;;;###autoload
4307 (defun org-clock-persistence-insinuate ()
4308 "Set up hooks for clock persistence."
4309 (require 'org-clock)
4310 (add-hook 'org-mode-hook 'org-clock-load)
4311 (add-hook 'kill-emacs-hook 'org-clock-save))
4313 ;; Define the variable already here, to make sure we have it.
4314 (defvar org-indent-mode nil
4315 "Non-nil if Org-Indent mode is enabled.
4316 Use the command `org-indent-mode' to change this variable.")
4318 ;; Autoload archiving code
4319 ;; The stuff that is needed for cycling and tags has to be defined here.
4321 (defgroup org-archive nil
4322 "Options concerning archiving in Org-mode."
4323 :tag "Org Archive"
4324 :group 'org-structure)
4326 (defcustom org-archive-location "%s_archive::"
4327 "The location where subtrees should be archived.
4329 The value of this variable is a string, consisting of two parts,
4330 separated by a double-colon. The first part is a filename and
4331 the second part is a headline.
4333 When the filename is omitted, archiving happens in the same file.
4334 %s in the filename will be replaced by the current file
4335 name (without the directory part). Archiving to a different file
4336 is useful to keep archived entries from contributing to the
4337 Org-mode Agenda.
4339 The archived entries will be filed as subtrees of the specified
4340 headline. When the headline is omitted, the subtrees are simply
4341 filed away at the end of the file, as top-level entries. Also in
4342 the heading you can use %s to represent the file name, this can be
4343 useful when using the same archive for a number of different files.
4345 Here are a few examples:
4346 \"%s_archive::\"
4347 If the current file is Projects.org, archive in file
4348 Projects.org_archive, as top-level trees. This is the default.
4350 \"::* Archived Tasks\"
4351 Archive in the current file, under the top-level headline
4352 \"* Archived Tasks\".
4354 \"~/org/archive.org::\"
4355 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4357 \"~/org/archive.org::* From %s\"
4358 Archive in file ~/org/archive.org (absolute path), under headlines
4359 \"From FILENAME\" where file name is the current file name.
4361 \"~/org/datetree.org::datetree/* Finished Tasks\"
4362 The \"datetree/\" string is special, signifying to archive
4363 items to the datetree. Items are placed in either the CLOSED
4364 date of the item, or the current date if there is no CLOSED date.
4365 The heading will be a subentry to the current date. There doesn't
4366 need to be a heading, but there always needs to be a slash after
4367 datetree. For example, to store archived items directly in the
4368 datetree, use \"~/org/datetree.org::datetree/\".
4370 \"basement::** Finished Tasks\"
4371 Archive in file ./basement (relative path), as level 3 trees
4372 below the level 2 heading \"** Finished Tasks\".
4374 You may set this option on a per-file basis by adding to the buffer a
4375 line like
4377 #+ARCHIVE: basement::** Finished Tasks
4379 You may also define it locally for a subtree by setting an ARCHIVE property
4380 in the entry. If such a property is found in an entry, or anywhere up
4381 the hierarchy, it will be used."
4382 :group 'org-archive
4383 :type 'string)
4385 (defcustom org-archive-tag "ARCHIVE"
4386 "The tag that marks a subtree as archived.
4387 An archived subtree does not open during visibility cycling, and does
4388 not contribute to the agenda listings.
4389 After changing this, font-lock must be restarted in the relevant buffers to
4390 get the proper fontification."
4391 :group 'org-archive
4392 :group 'org-keywords
4393 :type 'string)
4395 (defcustom org-agenda-skip-archived-trees t
4396 "Non-nil means the agenda will skip any items located in archived trees.
4397 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4398 variable is no longer recommended, you should leave it at the value t.
4399 Instead, use the key `v' to cycle the archives-mode in the agenda."
4400 :group 'org-archive
4401 :group 'org-agenda-skip
4402 :type 'boolean)
4404 (defcustom org-columns-skip-archived-trees t
4405 "Non-nil means ignore archived trees when creating column view."
4406 :group 'org-archive
4407 :group 'org-properties
4408 :type 'boolean)
4410 (defcustom org-cycle-open-archived-trees nil
4411 "Non-nil means `org-cycle' will open archived trees.
4412 An archived tree is a tree marked with the tag ARCHIVE.
4413 When nil, archived trees will stay folded. You can still open them with
4414 normal outline commands like `show-all', but not with the cycling commands."
4415 :group 'org-archive
4416 :group 'org-cycle
4417 :type 'boolean)
4419 (defcustom org-sparse-tree-open-archived-trees nil
4420 "Non-nil means sparse tree construction shows matches in archived trees.
4421 When nil, matches in these trees are highlighted, but the trees are kept in
4422 collapsed state."
4423 :group 'org-archive
4424 :group 'org-sparse-trees
4425 :type 'boolean)
4427 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4428 "The default date type when building a sparse tree.
4429 When this is nil, a date is a scheduled or a deadline timestamp.
4430 Otherwise, these types are allowed:
4432 all: all timestamps
4433 active: only active timestamps (<...>)
4434 inactive: only inactive timestamps (<...)
4435 scheduled: only scheduled timestamps
4436 deadline: only deadline timestamps"
4437 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4438 (const :tag "All timestamps" all)
4439 (const :tag "Only active timestamps" active)
4440 (const :tag "Only inactive timestamps" inactive)
4441 (const :tag "Only scheduled timestamps" scheduled)
4442 (const :tag "Only deadline timestamps" deadline))
4443 :version "24.3"
4444 :group 'org-sparse-trees)
4446 (defun org-cycle-hide-archived-subtrees (state)
4447 "Re-hide all archived subtrees after a visibility state change."
4448 (when (and (not org-cycle-open-archived-trees)
4449 (not (memq state '(overview folded))))
4450 (save-excursion
4451 (let* ((globalp (memq state '(contents all)))
4452 (beg (if globalp (point-min) (point)))
4453 (end (if globalp (point-max) (org-end-of-subtree t))))
4454 (org-hide-archived-subtrees beg end)
4455 (goto-char beg)
4456 (if (looking-at (concat ".*:" org-archive-tag ":"))
4457 (message "%s" (substitute-command-keys
4458 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4460 (defun org-force-cycle-archived ()
4461 "Cycle subtree even if it is archived."
4462 (interactive)
4463 (setq this-command 'org-cycle)
4464 (let ((org-cycle-open-archived-trees t))
4465 (call-interactively 'org-cycle)))
4467 (defun org-hide-archived-subtrees (beg end)
4468 "Re-hide all archived subtrees after a visibility state change."
4469 (save-excursion
4470 (let* ((re (concat ":" org-archive-tag ":")))
4471 (goto-char beg)
4472 (while (re-search-forward re end t)
4473 (when (org-at-heading-p)
4474 (org-flag-subtree t)
4475 (org-end-of-subtree t))))))
4477 (declare-function outline-end-of-heading "outline" ())
4478 (declare-function outline-flag-region "outline" (from to flag))
4479 (defun org-flag-subtree (flag)
4480 (save-excursion
4481 (org-back-to-heading t)
4482 (outline-end-of-heading)
4483 (outline-flag-region (point)
4484 (progn (org-end-of-subtree t) (point))
4485 flag)))
4487 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4489 (eval-and-compile
4490 (org-autoload "org-archive"
4491 '(org-add-archive-files)))
4493 ;; Autoload Column View Code
4495 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4496 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4497 (declare-function org-columns-compute "org-colview" (property))
4499 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4500 '(org-columns-number-to-string
4501 org-columns-get-format-and-top-level
4502 org-columns-compute
4503 org-columns-remove-overlays))
4505 ;; Autoload ID code
4507 (declare-function org-id-store-link "org-id")
4508 (declare-function org-id-locations-load "org-id")
4509 (declare-function org-id-locations-save "org-id")
4510 (defvar org-id-track-globally)
4511 (org-autoload "org-id"
4512 '(org-id-new
4513 org-id-copy
4514 org-id-get-with-outline-path-completion
4515 org-id-get-with-outline-drilling))
4517 ;;; Variables for pre-computed regular expressions, all buffer local
4519 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4520 "Matches first line of a hidden block.")
4521 (make-variable-buffer-local 'org-drawer-regexp)
4522 (defvar org-todo-regexp nil
4523 "Matches any of the TODO state keywords.")
4524 (make-variable-buffer-local 'org-todo-regexp)
4525 (defvar org-not-done-regexp nil
4526 "Matches any of the TODO state keywords except the last one.")
4527 (make-variable-buffer-local 'org-not-done-regexp)
4528 (defvar org-not-done-heading-regexp nil
4529 "Matches a TODO headline that is not done.")
4530 (make-variable-buffer-local 'org-not-done-regexp)
4531 (defvar org-todo-line-regexp nil
4532 "Matches a headline and puts TODO state into group 2 if present.")
4533 (make-variable-buffer-local 'org-todo-line-regexp)
4534 (defvar org-complex-heading-regexp nil
4535 "Matches a headline and puts everything into groups:
4536 group 1: the stars
4537 group 2: The todo keyword, maybe
4538 group 3: Priority cookie
4539 group 4: True headline
4540 group 5: Tags")
4541 (make-variable-buffer-local 'org-complex-heading-regexp)
4542 (defvar org-complex-heading-regexp-format nil
4543 "Printf format to make regexp to match an exact headline.
4544 This regexp will match the headline of any node which has the
4545 exact headline text that is put into the format, but may have any
4546 TODO state, priority and tags.")
4547 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4548 (defvar org-todo-line-tags-regexp nil
4549 "Matches a headline and puts TODO state into group 2 if present.
4550 Also put tags into group 4 if tags are present.")
4551 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4552 (defvar org-ds-keyword-length 12
4553 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4554 (make-variable-buffer-local 'org-ds-keyword-length)
4555 (defvar org-deadline-regexp nil
4556 "Matches the DEADLINE keyword.")
4557 (make-variable-buffer-local 'org-deadline-regexp)
4558 (defvar org-deadline-time-regexp nil
4559 "Matches the DEADLINE keyword together with a time stamp.")
4560 (make-variable-buffer-local 'org-deadline-time-regexp)
4561 (defvar org-deadline-line-regexp nil
4562 "Matches the DEADLINE keyword and the rest of the line.")
4563 (make-variable-buffer-local 'org-deadline-line-regexp)
4564 (defvar org-scheduled-regexp nil
4565 "Matches the SCHEDULED keyword.")
4566 (make-variable-buffer-local 'org-scheduled-regexp)
4567 (defvar org-scheduled-time-regexp nil
4568 "Matches the SCHEDULED keyword together with a time stamp.")
4569 (make-variable-buffer-local 'org-scheduled-time-regexp)
4570 (defvar org-closed-time-regexp nil
4571 "Matches the CLOSED keyword together with a time stamp.")
4572 (make-variable-buffer-local 'org-closed-time-regexp)
4574 (defvar org-keyword-time-regexp nil
4575 "Matches any of the 4 keywords, together with the time stamp.")
4576 (make-variable-buffer-local 'org-keyword-time-regexp)
4577 (defvar org-keyword-time-not-clock-regexp nil
4578 "Matches any of the 3 keywords, together with the time stamp.")
4579 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4580 (defvar org-maybe-keyword-time-regexp nil
4581 "Matches a timestamp, possibly preceded by a keyword.")
4582 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4583 (defvar org-all-time-keywords nil
4584 "List of time keywords.")
4585 (make-variable-buffer-local 'org-all-time-keywords)
4587 (defconst org-plain-time-of-day-regexp
4588 (concat
4589 "\\(\\<[012]?[0-9]"
4590 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4591 "\\(--?"
4592 "\\(\\<[012]?[0-9]"
4593 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4594 "\\)?")
4595 "Regular expression to match a plain time or time range.
4596 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4597 groups carry important information:
4598 0 the full match
4599 1 the first time, range or not
4600 8 the second time, if it is a range.")
4602 (defconst org-plain-time-extension-regexp
4603 (concat
4604 "\\(\\<[012]?[0-9]"
4605 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4606 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4607 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4608 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4609 groups carry important information:
4610 0 the full match
4611 7 hours of duration
4612 9 minutes of duration")
4614 (defconst org-stamp-time-of-day-regexp
4615 (concat
4616 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4617 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4618 "\\(--?"
4619 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4620 "Regular expression to match a timestamp time or time range.
4621 After a match, the following groups carry important information:
4622 0 the full match
4623 1 date plus weekday, for back referencing to make sure both times are on the same day
4624 2 the first time, range or not
4625 4 the second time, if it is a range.")
4627 (defconst org-startup-options
4628 '(("fold" org-startup-folded t)
4629 ("overview" org-startup-folded t)
4630 ("nofold" org-startup-folded nil)
4631 ("showall" org-startup-folded nil)
4632 ("showeverything" org-startup-folded showeverything)
4633 ("content" org-startup-folded content)
4634 ("indent" org-startup-indented t)
4635 ("noindent" org-startup-indented nil)
4636 ("hidestars" org-hide-leading-stars t)
4637 ("showstars" org-hide-leading-stars nil)
4638 ("odd" org-odd-levels-only t)
4639 ("oddeven" org-odd-levels-only nil)
4640 ("align" org-startup-align-all-tables t)
4641 ("noalign" org-startup-align-all-tables nil)
4642 ("inlineimages" org-startup-with-inline-images t)
4643 ("noinlineimages" org-startup-with-inline-images nil)
4644 ("latexpreview" org-startup-with-latex-preview t)
4645 ("nolatexpreview" org-startup-with-latex-preview nil)
4646 ("customtime" org-display-custom-times t)
4647 ("logdone" org-log-done time)
4648 ("lognotedone" org-log-done note)
4649 ("nologdone" org-log-done nil)
4650 ("lognoteclock-out" org-log-note-clock-out t)
4651 ("nolognoteclock-out" org-log-note-clock-out nil)
4652 ("logrepeat" org-log-repeat state)
4653 ("lognoterepeat" org-log-repeat note)
4654 ("logdrawer" org-log-into-drawer t)
4655 ("nologdrawer" org-log-into-drawer nil)
4656 ("logstatesreversed" org-log-states-order-reversed t)
4657 ("nologstatesreversed" org-log-states-order-reversed nil)
4658 ("nologrepeat" org-log-repeat nil)
4659 ("logreschedule" org-log-reschedule time)
4660 ("lognotereschedule" org-log-reschedule note)
4661 ("nologreschedule" org-log-reschedule nil)
4662 ("logredeadline" org-log-redeadline time)
4663 ("lognoteredeadline" org-log-redeadline note)
4664 ("nologredeadline" org-log-redeadline nil)
4665 ("logrefile" org-log-refile time)
4666 ("lognoterefile" org-log-refile note)
4667 ("nologrefile" org-log-refile nil)
4668 ("fninline" org-footnote-define-inline t)
4669 ("nofninline" org-footnote-define-inline nil)
4670 ("fnlocal" org-footnote-section nil)
4671 ("fnauto" org-footnote-auto-label t)
4672 ("fnprompt" org-footnote-auto-label nil)
4673 ("fnconfirm" org-footnote-auto-label confirm)
4674 ("fnplain" org-footnote-auto-label plain)
4675 ("fnadjust" org-footnote-auto-adjust t)
4676 ("nofnadjust" org-footnote-auto-adjust nil)
4677 ("constcgs" constants-unit-system cgs)
4678 ("constSI" constants-unit-system SI)
4679 ("noptag" org-tag-persistent-alist nil)
4680 ("hideblocks" org-hide-block-startup t)
4681 ("nohideblocks" org-hide-block-startup nil)
4682 ("beamer" org-startup-with-beamer-mode t)
4683 ("entitiespretty" org-pretty-entities t)
4684 ("entitiesplain" org-pretty-entities nil))
4685 "Variable associated with STARTUP options for org-mode.
4686 Each element is a list of three items: the startup options (as written
4687 in the #+STARTUP line), the corresponding variable, and the value to set
4688 this variable to if the option is found. An optional forth element PUSH
4689 means to push this value onto the list in the variable.")
4691 (defun org-update-property-plist (key val props)
4692 "Update PROPS with KEY and VAL."
4693 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4694 (key (if appending (substring key 0 (- (length key) 1)) key))
4695 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4696 (previous (cdr (assoc key props))))
4697 (if appending
4698 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4699 (cons (cons key val) remainder))))
4701 (defconst org-block-regexp
4702 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4703 "Regular expression for hiding blocks.")
4704 (defconst org-heading-keyword-regexp-format
4705 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4706 "Printf format for a regexp matching an headline with some keyword.
4707 This regexp will match the headline of any node which has the
4708 exact keyword that is put into the format. The keyword isn't in
4709 any group by default, but the stars and the body are.")
4710 (defconst org-heading-keyword-maybe-regexp-format
4711 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4712 "Printf format for a regexp matching an headline, possibly with some keyword.
4713 This regexp can match any headline with the specified keyword, or
4714 without a keyword. The keyword isn't in any group by default,
4715 but the stars and the body are.")
4717 (defun org-set-regexps-and-options ()
4718 "Precompute regular expressions for current buffer."
4719 (when (derived-mode-p 'org-mode)
4720 (org-set-local 'org-todo-kwd-alist nil)
4721 (org-set-local 'org-todo-key-alist nil)
4722 (org-set-local 'org-todo-key-trigger nil)
4723 (org-set-local 'org-todo-keywords-1 nil)
4724 (org-set-local 'org-done-keywords nil)
4725 (org-set-local 'org-todo-heads nil)
4726 (org-set-local 'org-todo-sets nil)
4727 (org-set-local 'org-todo-log-states nil)
4728 (org-set-local 'org-file-properties nil)
4729 (org-set-local 'org-file-tags nil)
4730 (let ((re (org-make-options-regexp
4731 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4732 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4733 "SETUPFILE" "OPTIONS")
4734 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4735 (splitre "[ \t]+")
4736 (scripts org-use-sub-superscripts)
4737 kwds kws0 kwsa key log value cat arch tags const links hw dws
4738 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4739 (start 0))
4740 (save-excursion
4741 (save-restriction
4742 (widen)
4743 (goto-char (point-min))
4744 (while (or (and ext-setup-or-nil
4745 (string-match re ext-setup-or-nil start)
4746 (setq start (match-end 0)))
4747 (and (setq ext-setup-or-nil nil start 0)
4748 (re-search-forward re nil t)))
4749 (setq key (upcase (match-string 1 ext-setup-or-nil))
4750 value (org-match-string-no-properties 2 ext-setup-or-nil))
4751 (if (stringp value) (setq value (org-trim value)))
4752 (cond
4753 ((equal key "CATEGORY")
4754 (setq cat value))
4755 ((member key '("SEQ_TODO" "TODO"))
4756 (push (cons 'sequence (org-split-string value splitre)) kwds))
4757 ((equal key "TYP_TODO")
4758 (push (cons 'type (org-split-string value splitre)) kwds))
4759 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4760 ;; general TODO-like setup
4761 (push (cons (intern (downcase (match-string 1 key)))
4762 (org-split-string value splitre)) kwds))
4763 ((equal key "TAGS")
4764 (setq tags (append tags (if tags '("\\n") nil)
4765 (org-split-string value splitre))))
4766 ((equal key "COLUMNS")
4767 (org-set-local 'org-columns-default-format value))
4768 ((equal key "LINK")
4769 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4770 (push (cons (match-string 1 value)
4771 (org-trim (match-string 2 value)))
4772 links)))
4773 ((equal key "PRIORITIES")
4774 (setq prio (org-split-string value " +")))
4775 ((equal key "PROPERTY")
4776 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4777 (setq props (org-update-property-plist (match-string 1 value)
4778 (match-string 2 value)
4779 props))))
4780 ((equal key "FILETAGS")
4781 (when (string-match "\\S-" value)
4782 (setq ftags
4783 (append
4784 ftags
4785 (apply 'append
4786 (mapcar (lambda (x) (org-split-string x ":"))
4787 (org-split-string value)))))))
4788 ((equal key "DRAWERS")
4789 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4790 ((equal key "CONSTANTS")
4791 (setq const (append const (org-split-string value splitre))))
4792 ((equal key "STARTUP")
4793 (let ((opts (org-split-string value splitre))
4794 l var val)
4795 (while (setq l (pop opts))
4796 (when (setq l (assoc l org-startup-options))
4797 (setq var (nth 1 l) val (nth 2 l))
4798 (if (not (nth 3 l))
4799 (set (make-local-variable var) val)
4800 (if (not (listp (symbol-value var)))
4801 (set (make-local-variable var) nil))
4802 (set (make-local-variable var) (symbol-value var))
4803 (add-to-list var val))))))
4804 ((equal key "ARCHIVE")
4805 (setq arch value)
4806 (remove-text-properties 0 (length arch)
4807 '(face t fontified t) arch))
4808 ((equal key "OPTIONS")
4809 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4810 (setq scripts (read (match-string 2 value)))))
4811 ((equal key "SETUPFILE")
4812 (setq setup-contents (org-file-contents
4813 (expand-file-name
4814 (org-remove-double-quotes value))
4815 'noerror))
4816 (if (not ext-setup-or-nil)
4817 (setq ext-setup-or-nil setup-contents start 0)
4818 (setq ext-setup-or-nil
4819 (concat (substring ext-setup-or-nil 0 start)
4820 "\n" setup-contents "\n"
4821 (substring ext-setup-or-nil start)))))))
4822 ;; search for property blocks
4823 (goto-char (point-min))
4824 (while (re-search-forward org-block-regexp nil t)
4825 (when (equal "PROPERTY" (upcase (match-string 1)))
4826 (setq value (replace-regexp-in-string
4827 "[\n\r]" " " (match-string 4)))
4828 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4829 (setq props (org-update-property-plist (match-string 1 value)
4830 (match-string 2 value)
4831 props)))))))
4832 (org-set-local 'org-use-sub-superscripts scripts)
4833 (when cat
4834 (org-set-local 'org-category (intern cat))
4835 (push (cons "CATEGORY" cat) props))
4836 (when prio
4837 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4838 (setq prio (mapcar 'string-to-char prio))
4839 (org-set-local 'org-highest-priority (nth 0 prio))
4840 (org-set-local 'org-lowest-priority (nth 1 prio))
4841 (org-set-local 'org-default-priority (nth 2 prio)))
4842 (and props (org-set-local 'org-file-properties (nreverse props)))
4843 (and ftags (org-set-local 'org-file-tags
4844 (mapcar 'org-add-prop-inherited ftags)))
4845 (and drawers (org-set-local 'org-drawers drawers))
4846 (and arch (org-set-local 'org-archive-location arch))
4847 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4848 ;; Process the TODO keywords
4849 (unless kwds
4850 ;; Use the global values as if they had been given locally.
4851 (setq kwds (default-value 'org-todo-keywords))
4852 (if (stringp (car kwds))
4853 (setq kwds (list (cons org-todo-interpretation
4854 (default-value 'org-todo-keywords)))))
4855 (setq kwds (reverse kwds)))
4856 (setq kwds (nreverse kwds))
4857 (let (inter kws kw)
4858 (while (setq kws (pop kwds))
4859 (let ((kws (or
4860 (run-hook-with-args-until-success
4861 'org-todo-setup-filter-hook kws)
4862 kws)))
4863 (setq inter (pop kws) sep (member "|" kws)
4864 kws0 (delete "|" (copy-sequence kws))
4865 kwsa nil
4866 kws1 (mapcar
4867 (lambda (x)
4868 ;; 1 2
4869 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4870 (progn
4871 (setq kw (match-string 1 x)
4872 key (and (match-end 2) (match-string 2 x))
4873 log (org-extract-log-state-settings x))
4874 (push (cons kw (and key (string-to-char key))) kwsa)
4875 (and log (push log org-todo-log-states))
4877 (error "Invalid TODO keyword %s" x)))
4878 kws0)
4879 kwsa (if kwsa (append '((:startgroup))
4880 (nreverse kwsa)
4881 '((:endgroup))))
4882 hw (car kws1)
4883 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4884 tail (list inter hw (car dws) (org-last dws))))
4885 (add-to-list 'org-todo-heads hw 'append)
4886 (push kws1 org-todo-sets)
4887 (setq org-done-keywords (append org-done-keywords dws nil))
4888 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4889 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4890 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4891 (setq org-todo-sets (nreverse org-todo-sets)
4892 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4893 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4894 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4895 ;; Process the constants
4896 (when const
4897 (let (e cst)
4898 (while (setq e (pop const))
4899 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4900 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4901 (setq org-table-formula-constants-local cst)))
4903 ;; Process the tags.
4904 (when tags
4905 (let (e tgs)
4906 (while (setq e (pop tags))
4907 (cond
4908 ((equal e "{") (push '(:startgroup) tgs))
4909 ((equal e "}") (push '(:endgroup) tgs))
4910 ((equal e "\\n") (push '(:newline) tgs))
4911 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4912 (push (cons (match-string 1 e)
4913 (string-to-char (match-string 2 e)))
4914 tgs))
4915 (t (push (list e) tgs))))
4916 (org-set-local 'org-tag-alist nil)
4917 (while (setq e (pop tgs))
4918 (or (and (stringp (car e))
4919 (assoc (car e) org-tag-alist))
4920 (push e org-tag-alist)))))
4922 ;; Compute the regular expressions and other local variables.
4923 ;; Using `org-outline-regexp-bol' would complicate them much,
4924 ;; because of the fixed white space at the end of that string.
4925 (if (not org-done-keywords)
4926 (setq org-done-keywords (and org-todo-keywords-1
4927 (list (org-last org-todo-keywords-1)))))
4928 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4929 (length org-scheduled-string)
4930 (length org-clock-string)
4931 (length org-closed-string)))
4932 org-drawer-regexp
4933 (concat "^[ \t]*:\\("
4934 (mapconcat 'regexp-quote org-drawers "\\|")
4935 "\\):[ \t]*$")
4936 org-not-done-keywords
4937 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4938 org-todo-regexp
4939 (concat "\\("
4940 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4941 "\\)")
4942 org-not-done-regexp
4943 (concat "\\("
4944 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4945 "\\)")
4946 org-not-done-heading-regexp
4947 (format org-heading-keyword-regexp-format org-not-done-regexp)
4948 org-todo-line-regexp
4949 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4950 org-complex-heading-regexp
4951 (concat "^\\(\\*+\\)"
4952 "\\(?: +" org-todo-regexp "\\)?"
4953 "\\(?: +\\(\\[#.\\]\\)\\)?"
4954 "\\(?: +\\(.*?\\)\\)??"
4955 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4956 "[ \t]*$")
4957 org-complex-heading-regexp-format
4958 (concat "^\\(\\*+\\)"
4959 "\\(?: +" org-todo-regexp "\\)?"
4960 "\\(?: +\\(\\[#.\\]\\)\\)?"
4961 "\\(?: +"
4962 ;; Stats cookies can be stuck to body.
4963 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4964 "\\(%s\\)"
4965 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4966 "\\)"
4967 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4968 "[ \t]*$")
4969 org-todo-line-tags-regexp
4970 (concat "^\\(\\*+\\)"
4971 "\\(?: +" org-todo-regexp "\\)?"
4972 "\\(?: +\\(.*?\\)\\)??"
4973 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4974 "[ \t]*$")
4975 org-deadline-regexp (concat "\\<" org-deadline-string)
4976 org-deadline-time-regexp
4977 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4978 org-deadline-line-regexp
4979 (concat "\\<\\(" org-deadline-string "\\).*")
4980 org-scheduled-regexp
4981 (concat "\\<" org-scheduled-string)
4982 org-scheduled-time-regexp
4983 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4984 org-closed-time-regexp
4985 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4986 org-keyword-time-regexp
4987 (concat "\\<\\(" org-scheduled-string
4988 "\\|" org-deadline-string
4989 "\\|" org-closed-string
4990 "\\|" org-clock-string "\\)"
4991 " *[[<]\\([^]>]+\\)[]>]")
4992 org-keyword-time-not-clock-regexp
4993 (concat "\\<\\(" org-scheduled-string
4994 "\\|" org-deadline-string
4995 "\\|" org-closed-string
4996 "\\)"
4997 " *[[<]\\([^]>]+\\)[]>]")
4998 org-maybe-keyword-time-regexp
4999 (concat "\\(\\<\\(" org-scheduled-string
5000 "\\|" org-deadline-string
5001 "\\|" org-closed-string
5002 "\\|" org-clock-string "\\)\\)?"
5003 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5004 org-all-time-keywords
5005 (mapcar (lambda (w) (substring w 0 -1))
5006 (list org-scheduled-string org-deadline-string
5007 org-clock-string org-closed-string)))
5008 (org-compute-latex-and-related-regexp)
5009 (org-set-font-lock-defaults))))
5011 (defun org-file-contents (file &optional noerror)
5012 "Return the contents of FILE, as a string."
5013 (if (or (not file)
5014 (not (file-readable-p file)))
5015 (if noerror
5016 (progn
5017 (message "Cannot read file \"%s\"" file)
5018 (ding) (sit-for 2)
5020 (error "Cannot read file \"%s\"" file))
5021 (with-temp-buffer
5022 (insert-file-contents file)
5023 (buffer-string))))
5025 (defun org-extract-log-state-settings (x)
5026 "Extract the log state setting from a TODO keyword string.
5027 This will extract info from a string like \"WAIT(w@/!)\"."
5028 (let (kw key log1 log2)
5029 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5030 (setq kw (match-string 1 x)
5031 key (and (match-end 2) (match-string 2 x))
5032 log1 (and (match-end 3) (match-string 3 x))
5033 log2 (and (match-end 4) (match-string 4 x)))
5034 (and (or log1 log2)
5035 (list kw
5036 (and log1 (if (equal log1 "!") 'time 'note))
5037 (and log2 (if (equal log2 "!") 'time 'note)))))))
5039 (defun org-remove-keyword-keys (list)
5040 "Remove a pair of parenthesis at the end of each string in LIST."
5041 (mapcar (lambda (x)
5042 (if (string-match "(.*)$" x)
5043 (substring x 0 (match-beginning 0))
5045 list))
5047 (defun org-assign-fast-keys (alist)
5048 "Assign fast keys to a keyword-key alist.
5049 Respect keys that are already there."
5050 (let (new e (alt ?0))
5051 (while (setq e (pop alist))
5052 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5053 (cdr e)) ;; Key already assigned.
5054 (push e new)
5055 (let ((clist (string-to-list (downcase (car e))))
5056 (used (append new alist)))
5057 (when (= (car clist) ?@)
5058 (pop clist))
5059 (while (and clist (rassoc (car clist) used))
5060 (pop clist))
5061 (unless clist
5062 (while (rassoc alt used)
5063 (incf alt)))
5064 (push (cons (car e) (or (car clist) alt)) new))))
5065 (nreverse new)))
5067 ;;; Some variables used in various places
5069 (defvar org-window-configuration nil
5070 "Used in various places to store a window configuration.")
5071 (defvar org-selected-window nil
5072 "Used in various places to store a window configuration.")
5073 (defvar org-finish-function nil
5074 "Function to be called when `C-c C-c' is used.
5075 This is for getting out of special buffers like capture.")
5078 ;; FIXME: Occasionally check by commenting these, to make sure
5079 ;; no other functions uses these, forgetting to let-bind them.
5080 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5081 (defvar org-last-state)
5082 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5084 ;; Defined somewhere in this file, but used before definition.
5085 (defvar org-entities) ;; defined in org-entities.el
5086 (defvar org-struct-menu)
5087 (defvar org-org-menu)
5088 (defvar org-tbl-menu)
5090 ;;;; Define the Org-mode
5092 ;; We use a before-change function to check if a table might need
5093 ;; an update.
5094 (defvar org-table-may-need-update t
5095 "Indicates that a table might need an update.
5096 This variable is set by `org-before-change-function'.
5097 `org-table-align' sets it back to nil.")
5098 (defun org-before-change-function (beg end)
5099 "Every change indicates that a table might need an update."
5100 (setq org-table-may-need-update t))
5101 (defvar org-mode-map)
5102 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5103 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5104 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5105 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5106 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5107 (defvar org-table-buffer-is-an nil)
5109 (defvar bidi-paragraph-direction)
5110 (defvar buffer-face-mode-face)
5112 (require 'outline)
5113 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5114 (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"))
5115 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5117 ;; Other stuff we need.
5118 (require 'time-date)
5119 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5120 (require 'easymenu)
5121 (require 'overlay)
5123 ;; (require 'org-macs) moved higher up in the file before it is first used
5124 (require 'org-entities)
5125 ;; (require 'org-compat) moved higher up in the file before it is first used
5126 (require 'org-faces)
5127 (require 'org-list)
5128 (require 'org-pcomplete)
5129 (require 'org-src)
5130 (require 'org-footnote)
5131 (require 'org-macro)
5133 ;; babel
5134 (require 'ob)
5136 ;;;###autoload
5137 (define-derived-mode org-mode outline-mode "Org"
5138 "Outline-based notes management and organizer, alias
5139 \"Carsten's outline-mode for keeping track of everything.\"
5141 Org-mode develops organizational tasks around a NOTES file which
5142 contains information about projects as plain text. Org-mode is
5143 implemented on top of outline-mode, which is ideal to keep the content
5144 of large files well structured. It supports ToDo items, deadlines and
5145 time stamps, which magically appear in the diary listing of the Emacs
5146 calendar. Tables are easily created with a built-in table editor.
5147 Plain text URL-like links connect to websites, emails (VM), Usenet
5148 messages (Gnus), BBDB entries, and any files related to the project.
5149 For printing and sharing of notes, an Org-mode file (or a part of it)
5150 can be exported as a structured ASCII or HTML file.
5152 The following commands are available:
5154 \\{org-mode-map}"
5156 ;; Get rid of Outline menus, they are not needed
5157 ;; Need to do this here because define-derived-mode sets up
5158 ;; the keymap so late. Still, it is a waste to call this each time
5159 ;; we switch another buffer into org-mode.
5160 (if (featurep 'xemacs)
5161 (when (boundp 'outline-mode-menu-heading)
5162 ;; Assume this is Greg's port, it uses easymenu
5163 (easy-menu-remove outline-mode-menu-heading)
5164 (easy-menu-remove outline-mode-menu-show)
5165 (easy-menu-remove outline-mode-menu-hide))
5166 (define-key org-mode-map [menu-bar headings] 'undefined)
5167 (define-key org-mode-map [menu-bar hide] 'undefined)
5168 (define-key org-mode-map [menu-bar show] 'undefined))
5170 (org-load-modules-maybe)
5171 (easy-menu-add org-org-menu)
5172 (easy-menu-add org-tbl-menu)
5173 (org-install-agenda-files-menu)
5174 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5175 (add-to-invisibility-spec '(org-cwidth))
5176 (add-to-invisibility-spec '(org-hide-block . t))
5177 (when (featurep 'xemacs)
5178 (org-set-local 'line-move-ignore-invisible t))
5179 (org-set-local 'outline-regexp org-outline-regexp)
5180 (org-set-local 'outline-level 'org-outline-level)
5181 (setq bidi-paragraph-direction 'left-to-right)
5182 (when (and org-ellipsis
5183 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5184 (fboundp 'make-glyph-code))
5185 (unless org-display-table
5186 (setq org-display-table (make-display-table)))
5187 (set-display-table-slot
5188 org-display-table 4
5189 (vconcat (mapcar
5190 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5191 org-ellipsis)))
5192 (if (stringp org-ellipsis) org-ellipsis "..."))))
5193 (setq buffer-display-table org-display-table))
5194 (org-set-regexps-and-options)
5195 (when (and org-tag-faces (not org-tags-special-faces-re))
5196 ;; tag faces set outside customize.... force initialization.
5197 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5198 ;; Calc embedded
5199 (org-set-local 'calc-embedded-open-mode "# ")
5200 (mapc (lambda(c) (modify-syntax-entry (string-to-char (car c)) "w p"))
5201 org-emphasis-alist)
5202 (modify-syntax-entry ?< "(")
5203 (modify-syntax-entry ?> ")")
5204 (modify-syntax-entry ?{ "(")
5205 (modify-syntax-entry ?} ")")
5206 (modify-syntax-entry ?@ "w")
5207 (modify-syntax-entry ?\" "\"")
5208 (if org-startup-truncated (setq truncate-lines t))
5209 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5210 (org-set-local 'font-lock-unfontify-region-function
5211 'org-unfontify-region)
5212 ;; Activate before-change-function
5213 (org-set-local 'org-table-may-need-update t)
5214 (org-add-hook 'before-change-functions 'org-before-change-function nil
5215 'local)
5216 ;; Check for running clock before killing a buffer
5217 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5218 ;; Initialize macros templates.
5219 (org-macro-initialize-templates)
5220 ;; Initialize radio targets.
5221 (org-update-radio-target-regexp)
5222 ;; Indentation.
5223 (org-set-local 'indent-line-function 'org-indent-line)
5224 (org-set-local 'indent-region-function 'org-indent-region)
5225 ;; Filling and auto-filling.
5226 (org-setup-filling)
5227 ;; Comments.
5228 (org-setup-comments-handling)
5229 ;; Beginning/end of defun
5230 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5231 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5232 ;; Next error for sparse trees
5233 (org-set-local 'next-error-function 'org-occur-next-match)
5234 ;; Make sure dependence stuff works reliably, even for users who set it
5235 ;; too late :-(
5236 (if org-enforce-todo-dependencies
5237 (add-hook 'org-blocker-hook
5238 'org-block-todo-from-children-or-siblings-or-parent)
5239 (remove-hook 'org-blocker-hook
5240 'org-block-todo-from-children-or-siblings-or-parent))
5241 (if org-enforce-todo-checkbox-dependencies
5242 (add-hook 'org-blocker-hook
5243 'org-block-todo-from-checkboxes)
5244 (remove-hook 'org-blocker-hook
5245 'org-block-todo-from-checkboxes))
5247 ;; Align options lines
5248 (org-set-local
5249 'align-mode-rules-list
5250 '((org-in-buffer-settings
5251 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5252 (modes . '(org-mode)))))
5254 ;; Imenu
5255 (org-set-local 'imenu-create-index-function
5256 'org-imenu-get-tree)
5258 ;; Make isearch reveal context
5259 (if (or (featurep 'xemacs)
5260 (not (boundp 'outline-isearch-open-invisible-function)))
5261 ;; Emacs 21 and XEmacs make use of the hook
5262 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5263 ;; Emacs 22 deals with this through a special variable
5264 (org-set-local 'outline-isearch-open-invisible-function
5265 (lambda (&rest ignore) (org-show-context 'isearch))))
5267 ;; Setup the pcomplete hooks
5268 (set (make-local-variable 'pcomplete-command-completion-function)
5269 'org-pcomplete-initial)
5270 (set (make-local-variable 'pcomplete-command-name-function)
5271 'org-command-at-point)
5272 (set (make-local-variable 'pcomplete-default-completion-function)
5273 'ignore)
5274 (set (make-local-variable 'pcomplete-parse-arguments-function)
5275 'org-parse-arguments)
5276 (set (make-local-variable 'pcomplete-termination-string) "")
5277 (when (>= emacs-major-version 23)
5278 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5280 ;; If empty file that did not turn on org-mode automatically, make it to.
5281 (if (and org-insert-mode-line-in-empty-file
5282 (org-called-interactively-p 'any)
5283 (= (point-min) (point-max)))
5284 (insert "# -*- mode: org -*-\n\n"))
5285 (unless org-inhibit-startup
5286 (org-unmodified
5287 (and org-startup-with-beamer-mode (org-beamer-mode))
5288 (when org-startup-align-all-tables
5289 (org-table-map-tables 'org-table-align 'quietly))
5290 (when org-startup-with-inline-images
5291 (org-display-inline-images))
5292 (when org-startup-with-latex-preview
5293 (org-preview-latex-fragment))
5294 (unless org-inhibit-startup-visibility-stuff
5295 (org-set-startup-visibility))))
5296 ;; Try to set org-hide correctly
5297 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5299 (when (fboundp 'abbrev-table-put)
5300 (abbrev-table-put org-mode-abbrev-table
5301 :parents (list text-mode-abbrev-table)))
5303 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5306 (defun org-find-invisible-foreground ()
5307 (let ((candidates (remove
5308 "unspecified-bg"
5309 (nconc
5310 (list (face-background 'default)
5311 (face-background 'org-default))
5312 (mapcar
5313 (lambda (alist)
5314 (when (boundp alist)
5315 (cdr (assoc 'background-color (symbol-value alist)))))
5316 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5317 (list (face-foreground 'org-hide))))))
5318 (car (remove nil candidates))))
5320 (defun org-current-time (&optional rounding-minutes)
5321 "Current time, possibly rounded to ROUNDING-MINUTES.
5322 When ROUNDING-MINUTES is not an integer, fall back on the car of
5323 `org-time-stamp-rounding-minutes'."
5324 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5325 (car org-time-stamp-rounding-minutes)))
5326 (time (decode-time)))
5327 (if (> r 1)
5328 (apply 'encode-time
5329 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5330 (nthcdr 2 time)))
5331 (current-time))))
5333 (defun org-today ()
5334 "Return today date, considering `org-extend-today-until'."
5335 (time-to-days
5336 (time-subtract (current-time)
5337 (list 0 (* 3600 org-extend-today-until) 0))))
5339 ;;;; Font-Lock stuff, including the activators
5341 (defvar org-mouse-map (make-sparse-keymap))
5342 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5343 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5344 (when org-mouse-1-follows-link
5345 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5346 (when org-tab-follows-link
5347 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5348 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5350 (require 'font-lock)
5352 (defconst org-non-link-chars "]\t\n\r<>")
5353 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5354 "shell" "elisp" "doi" "message"))
5355 (defvar org-link-types-re nil
5356 "Matches a link that has a url-like prefix like \"http:\"")
5357 (defvar org-link-re-with-space nil
5358 "Matches a link with spaces, optional angular brackets around it.")
5359 (defvar org-link-re-with-space2 nil
5360 "Matches a link with spaces, optional angular brackets around it.")
5361 (defvar org-link-re-with-space3 nil
5362 "Matches a link with spaces, only for internal part in bracket links.")
5363 (defvar org-angle-link-re nil
5364 "Matches link with angular brackets, spaces are allowed.")
5365 (defvar org-plain-link-re nil
5366 "Matches plain link, without spaces.")
5367 (defvar org-bracket-link-regexp nil
5368 "Matches a link in double brackets.")
5369 (defvar org-bracket-link-analytic-regexp nil
5370 "Regular expression used to analyze links.
5371 Here is what the match groups contain after a match:
5372 1: http:
5373 2: http
5374 3: path
5375 4: [desc]
5376 5: desc")
5377 (defvar org-bracket-link-analytic-regexp++ nil
5378 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5379 (defvar org-any-link-re nil
5380 "Regular expression matching any link.")
5382 (defconst org-match-sexp-depth 3
5383 "Number of stacked braces for sub/superscript matching.")
5385 (defun org-create-multibrace-regexp (left right n)
5386 "Create a regular expression which will match a balanced sexp.
5387 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5388 as single character strings.
5389 The regexp returned will match the entire expression including the
5390 delimiters. It will also define a single group which contains the
5391 match except for the outermost delimiters. The maximum depth of
5392 stacked delimiters is N. Escaping delimiters is not possible."
5393 (let* ((nothing (concat "[^" left right "]*?"))
5394 (or "\\|")
5395 (re nothing)
5396 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5397 (while (> n 1)
5398 (setq n (1- n)
5399 re (concat re or next)
5400 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5401 (concat left "\\(" re "\\)" right)))
5403 (defvar org-match-substring-regexp
5404 (concat
5405 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5406 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5407 "\\|"
5408 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5409 "\\|"
5410 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5411 "The regular expression matching a sub- or superscript.")
5413 (defvar org-match-substring-with-braces-regexp
5414 (concat
5415 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5416 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5417 "\\)")
5418 "The regular expression matching a sub- or superscript, forcing braces.")
5420 (defun org-make-link-regexps ()
5421 "Update the link regular expressions.
5422 This should be called after the variable `org-link-types' has changed."
5423 (setq org-link-types-re
5424 (concat
5425 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5426 org-link-re-with-space
5427 (concat
5428 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5429 "\\([^" org-non-link-chars " ]"
5430 "[^" org-non-link-chars "]*"
5431 "[^" org-non-link-chars " ]\\)>?")
5432 org-link-re-with-space2
5433 (concat
5434 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5435 "\\([^" org-non-link-chars " ]"
5436 "[^\t\n\r]*"
5437 "[^" org-non-link-chars " ]\\)>?")
5438 org-link-re-with-space3
5439 (concat
5440 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5441 "\\([^" org-non-link-chars " ]"
5442 "[^\t\n\r]*\\)")
5443 org-angle-link-re
5444 (concat
5445 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5446 "\\([^" org-non-link-chars " ]"
5447 "[^" org-non-link-chars "]*"
5448 "\\)>")
5449 org-plain-link-re
5450 (concat
5451 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5452 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5453 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5454 org-bracket-link-regexp
5455 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5456 org-bracket-link-analytic-regexp
5457 (concat
5458 "\\[\\["
5459 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5460 "\\([^]]+\\)"
5461 "\\]"
5462 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5463 "\\]")
5464 org-bracket-link-analytic-regexp++
5465 (concat
5466 "\\[\\["
5467 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5468 "\\([^]]+\\)"
5469 "\\]"
5470 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5471 "\\]")
5472 org-any-link-re
5473 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5474 org-angle-link-re "\\)\\|\\("
5475 org-plain-link-re "\\)")))
5477 (org-make-link-regexps)
5479 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5480 "Regular expression for fast time stamp matching.")
5481 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5482 "Regular expression for fast time stamp matching.")
5483 (defconst org-ts-regexp0
5484 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5485 "Regular expression matching time strings for analysis.
5486 This one does not require the space after the date, so it can be used
5487 on a string that terminates immediately after the date.")
5488 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5489 "Regular expression matching time strings for analysis.")
5490 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5491 "Regular expression matching time stamps, with groups.")
5492 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5493 "Regular expression matching time stamps (also [..]), with groups.")
5494 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5495 "Regular expression matching a time stamp range.")
5496 (defconst org-tr-regexp-both
5497 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5498 "Regular expression matching a time stamp range.")
5499 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5500 org-ts-regexp "\\)?")
5501 "Regular expression matching a time stamp or time stamp range.")
5502 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5503 org-ts-regexp-both "\\)?")
5504 "Regular expression matching a time stamp or time stamp range.
5505 The time stamps may be either active or inactive.")
5507 (defvar org-emph-face nil)
5509 (defun org-do-emphasis-faces (limit)
5510 "Run through the buffer and add overlays to emphasized strings."
5511 (let (rtn a)
5512 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5513 (if (not (= (char-after (match-beginning 3))
5514 (char-after (match-beginning 4))))
5515 (progn
5516 (setq rtn t)
5517 (setq a (assoc (match-string 3) org-emphasis-alist))
5518 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5519 'face
5520 (nth 1 a))
5521 (and (nth 4 a)
5522 (org-remove-flyspell-overlays-in
5523 (match-beginning 0) (match-end 0)))
5524 (add-text-properties (match-beginning 2) (match-end 2)
5525 '(font-lock-multiline t org-emphasis t))
5526 (when org-hide-emphasis-markers
5527 (add-text-properties (match-end 4) (match-beginning 5)
5528 '(invisible org-link))
5529 (add-text-properties (match-beginning 3) (match-end 3)
5530 '(invisible org-link)))))
5531 (backward-char 1))
5532 rtn))
5534 (defun org-emphasize (&optional char)
5535 "Insert or change an emphasis, i.e. a font like bold or italic.
5536 If there is an active region, change that region to a new emphasis.
5537 If there is no region, just insert the marker characters and position
5538 the cursor between them.
5539 CHAR should be either the marker character, or the first character of the
5540 HTML tag associated with that emphasis. If CHAR is a space, the means
5541 to remove the emphasis of the selected region.
5542 If char is not given (for example in an interactive call) it
5543 will be prompted for."
5544 (interactive)
5545 (let ((eal org-emphasis-alist) e det
5546 (erc org-emphasis-regexp-components)
5547 (prompt "")
5548 (string "") beg end move tag c s)
5549 (if (org-region-active-p)
5550 (setq beg (region-beginning) end (region-end)
5551 string (buffer-substring beg end))
5552 (setq move t))
5554 (while (setq e (pop eal))
5555 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5556 c (aref tag 0))
5557 (push (cons c (string-to-char (car e))) det)
5558 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5559 (substring tag 1)))))
5560 (setq det (nreverse det))
5561 (unless char
5562 (message "%s" (concat "Emphasis marker or tag:" prompt))
5563 (setq char (read-char-exclusive)))
5564 (setq char (or (cdr (assoc char det)) char))
5565 (if (equal char ?\ )
5566 (setq s "" move nil)
5567 (unless (assoc (char-to-string char) org-emphasis-alist)
5568 (error "No such emphasis marker: \"%c\"" char))
5569 (setq s (char-to-string char)))
5570 (while (and (> (length string) 1)
5571 (equal (substring string 0 1) (substring string -1))
5572 (assoc (substring string 0 1) org-emphasis-alist))
5573 (setq string (substring string 1 -1)))
5574 (setq string (concat s string s))
5575 (if beg (delete-region beg end))
5576 (unless (or (bolp)
5577 (string-match (concat "[" (nth 0 erc) "\n]")
5578 (char-to-string (char-before (point)))))
5579 (insert " "))
5580 (unless (or (eobp)
5581 (string-match (concat "[" (nth 1 erc) "\n]")
5582 (char-to-string (char-after (point)))))
5583 (insert " ") (backward-char 1))
5584 (insert string)
5585 (and move (backward-char 1))))
5587 (defconst org-nonsticky-props
5588 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5590 (defsubst org-rear-nonsticky-at (pos)
5591 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5593 (defun org-activate-plain-links (limit)
5594 "Run through the buffer and add overlays to links."
5595 (catch 'exit
5596 (let (f hl)
5597 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5598 (not (org-in-src-block-p)))
5599 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5600 (setq f (get-text-property (match-beginning 0) 'face))
5601 (setq hl (org-match-string-no-properties 0))
5602 (if (or (eq f 'org-tag)
5603 (and (listp f) (memq 'org-tag f)))
5605 (add-text-properties (match-beginning 0) (match-end 0)
5606 (list 'mouse-face 'highlight
5607 'face 'org-link
5608 'htmlize-link `(:uri ,hl)
5609 'keymap org-mouse-map))
5610 (org-rear-nonsticky-at (match-end 0)))
5611 t))))
5613 (defun org-activate-code (limit)
5614 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5615 (progn
5616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5617 (remove-text-properties (match-beginning 0) (match-end 0)
5618 '(display t invisible t intangible t))
5619 t)))
5621 (defcustom org-src-fontify-natively nil
5622 "When non-nil, fontify code in code blocks."
5623 :type 'boolean
5624 :version "24.1"
5625 :group 'org-appearance
5626 :group 'org-babel)
5628 (defcustom org-allow-promoting-top-level-subtree nil
5629 "When non-nil, allow promoting a top level subtree.
5630 The leading star of the top level headline will be replaced
5631 by a #."
5632 :type 'boolean
5633 :version "24.1"
5634 :group 'org-appearance)
5636 (defun org-fontify-meta-lines-and-blocks (limit)
5637 (condition-case nil
5638 (org-fontify-meta-lines-and-blocks-1 limit)
5639 (error (message "org-mode fontification error"))))
5641 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5642 "Fontify #+ lines and blocks, in the correct ways."
5643 (let ((case-fold-search t))
5644 (if (re-search-forward
5645 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5646 limit t)
5647 (let ((beg (match-beginning 0))
5648 (block-start (match-end 0))
5649 (block-end nil)
5650 (lang (match-string 7))
5651 (beg1 (line-beginning-position 2))
5652 (dc1 (downcase (match-string 2)))
5653 (dc3 (downcase (match-string 3)))
5654 end end1 quoting block-type ovl)
5655 (cond
5656 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5657 ;; a single line of backend-specific content
5658 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5659 (remove-text-properties (match-beginning 0) (match-end 0)
5660 '(display t invisible t intangible t))
5661 (add-text-properties (match-beginning 1) (match-end 3)
5662 '(font-lock-fontified t face org-meta-line))
5663 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5664 '(font-lock-fontified t face org-block))
5665 ; for backend-specific code
5667 ((and (match-end 4) (equal dc3 "+begin"))
5668 ;; Truly a block
5669 (setq block-type (downcase (match-string 5))
5670 quoting (member block-type org-protecting-blocks))
5671 (when (re-search-forward
5672 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5673 nil t) ;; on purpose, we look further than LIMIT
5674 (setq end (min (point-max) (match-end 0))
5675 end1 (min (point-max) (1- (match-beginning 0))))
5676 (setq block-end (match-beginning 0))
5677 (when quoting
5678 (remove-text-properties beg end
5679 '(display t invisible t intangible t)))
5680 (add-text-properties
5681 beg end
5682 '(font-lock-fontified t font-lock-multiline t))
5683 (add-text-properties beg beg1 '(face org-meta-line))
5684 (add-text-properties end1 (min (point-max) (1+ end))
5685 '(face org-meta-line)) ; for end_src
5686 (cond
5687 ((and lang (not (string= lang "")) org-src-fontify-natively)
5688 (org-src-font-lock-fontify-block lang block-start block-end)
5689 ;; remove old background overlays
5690 (mapc (lambda (ov)
5691 (if (eq (overlay-get ov 'face) 'org-block-background)
5692 (delete-overlay ov)))
5693 (overlays-at (/ (+ beg1 block-end) 2)))
5694 ;; add a background overlay
5695 (setq ovl (make-overlay beg1 block-end))
5696 (overlay-put ovl 'face 'org-block-background)
5697 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5698 (quoting
5699 (add-text-properties beg1 (min (point-max) (1+ end1))
5700 '(face org-block))) ; end of source block
5701 ((not org-fontify-quote-and-verse-blocks))
5702 ((string= block-type "quote")
5703 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5704 ((string= block-type "verse")
5705 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5706 (add-text-properties beg beg1 '(face org-block-begin-line))
5707 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5708 '(face org-block-end-line))
5710 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5711 (add-text-properties
5712 beg (match-end 3)
5713 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5714 '(font-lock-fontified t invisible t)
5715 '(font-lock-fontified t face org-document-info-keyword)))
5716 (add-text-properties
5717 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5718 (if (string-equal dc1 "+title:")
5719 '(font-lock-fontified t face org-document-title)
5720 '(font-lock-fontified t face org-document-info))))
5721 ((or (equal dc1 "+results")
5722 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5723 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5724 "+call:" "+header:" "+headers:" "+name:"))
5725 (and (match-end 4) (equal dc3 "+attr")))
5726 (add-text-properties
5727 beg (match-end 0)
5728 '(font-lock-fontified t face org-meta-line))
5730 ((member dc3 '(" " ""))
5731 (add-text-properties
5732 beg (match-end 0)
5733 '(font-lock-fontified t face font-lock-comment-face)))
5734 ((not (member (char-after beg) '(?\ ?\t)))
5735 ;; just any other in-buffer setting, but not indented
5736 (add-text-properties
5737 beg (match-end 0)
5738 '(font-lock-fontified t face org-meta-line))
5740 (t nil))))))
5742 (defun org-activate-angle-links (limit)
5743 "Run through the buffer and add overlays to links."
5744 (if (and (re-search-forward org-angle-link-re limit t)
5745 (not (org-in-src-block-p)))
5746 (progn
5747 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5748 (add-text-properties (match-beginning 0) (match-end 0)
5749 (list 'mouse-face 'highlight
5750 'keymap org-mouse-map))
5751 (org-rear-nonsticky-at (match-end 0))
5752 t)))
5754 (defun org-activate-footnote-links (limit)
5755 "Run through the buffer and add overlays to footnotes."
5756 (let ((fn (org-footnote-next-reference-or-definition limit)))
5757 (when fn
5758 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5759 (org-remove-flyspell-overlays-in beg end)
5760 (add-text-properties beg end
5761 (list 'mouse-face 'highlight
5762 'keymap org-mouse-map
5763 'help-echo
5764 (if (= (point-at-bol) beg)
5765 "Footnote definition"
5766 "Footnote reference")
5767 'font-lock-fontified t
5768 'font-lock-multiline t
5769 'face 'org-footnote))))))
5771 (defun org-activate-bracket-links (limit)
5772 "Run through the buffer and add overlays to bracketed links."
5773 (if (and (re-search-forward org-bracket-link-regexp limit t)
5774 (not (org-in-src-block-p)))
5775 (let* ((hl (org-match-string-no-properties 1))
5776 (help (concat "LINK: " hl))
5777 ;; FIXME: Above we should remove the escapes. But that
5778 ;; requires another match, protecting match data, a lot
5779 ;; of overhead for font-lock.
5780 (ip (org-maybe-intangible
5781 (list 'invisible 'org-link
5782 'keymap org-mouse-map 'mouse-face 'highlight
5783 'font-lock-multiline t 'help-echo help
5784 'htmlize-link `(:uri ,hl))))
5785 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5786 'font-lock-multiline t 'help-echo help
5787 'htmlize-link `(:uri ,hl))))
5788 ;; We need to remove the invisible property here. Table narrowing
5789 ;; may have made some of this invisible.
5790 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5791 (remove-text-properties (match-beginning 0) (match-end 0)
5792 '(invisible nil))
5793 (if (match-end 3)
5794 (progn
5795 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5796 (org-rear-nonsticky-at (match-beginning 3))
5797 (add-text-properties (match-beginning 3) (match-end 3) vp)
5798 (org-rear-nonsticky-at (match-end 3))
5799 (add-text-properties (match-end 3) (match-end 0) ip)
5800 (org-rear-nonsticky-at (match-end 0)))
5801 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5802 (org-rear-nonsticky-at (match-beginning 1))
5803 (add-text-properties (match-beginning 1) (match-end 1) vp)
5804 (org-rear-nonsticky-at (match-end 1))
5805 (add-text-properties (match-end 1) (match-end 0) ip)
5806 (org-rear-nonsticky-at (match-end 0)))
5807 t)))
5809 (defun org-activate-dates (limit)
5810 "Run through the buffer and add overlays to dates."
5811 (if (re-search-forward org-tsr-regexp-both limit t)
5812 (progn
5813 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5814 (add-text-properties (match-beginning 0) (match-end 0)
5815 (list 'mouse-face 'highlight
5816 'keymap org-mouse-map))
5817 (org-rear-nonsticky-at (match-end 0))
5818 (when org-display-custom-times
5819 (if (match-end 3)
5820 (org-display-custom-time (match-beginning 3) (match-end 3)))
5821 (org-display-custom-time (match-beginning 1) (match-end 1)))
5822 t)))
5824 (defvar org-target-link-regexp nil
5825 "Regular expression matching radio targets in plain text.")
5826 (make-variable-buffer-local 'org-target-link-regexp)
5827 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5828 "Regular expression matching a link target.")
5829 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5830 "Regular expression matching a radio target.")
5831 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5832 "Regular expression matching any target.")
5834 (defun org-activate-target-links (limit)
5835 "Run through the buffer and add overlays to target matches."
5836 (when org-target-link-regexp
5837 (let ((case-fold-search t))
5838 (if (re-search-forward org-target-link-regexp limit t)
5839 (progn
5840 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5841 (add-text-properties (match-beginning 0) (match-end 0)
5842 (list 'mouse-face 'highlight
5843 'keymap org-mouse-map
5844 'help-echo "Radio target link"
5845 'org-linked-text t))
5846 (org-rear-nonsticky-at (match-end 0))
5847 t)))))
5849 (defun org-update-radio-target-regexp ()
5850 "Find all radio targets in this file and update the regular expression."
5851 (interactive)
5852 (when (memq 'radio org-activate-links)
5853 (setq org-target-link-regexp
5854 (org-make-target-link-regexp (org-all-targets 'radio)))
5855 (org-restart-font-lock)))
5857 (defun org-hide-wide-columns (limit)
5858 (let (s e)
5859 (setq s (text-property-any (point) (or limit (point-max))
5860 'org-cwidth t))
5861 (when s
5862 (setq e (next-single-property-change s 'org-cwidth))
5863 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5864 (goto-char e)
5865 t)))
5867 (defvar org-latex-and-related-regexp nil
5868 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5869 (defvar org-match-substring-regexp)
5870 (defvar org-match-substring-with-braces-regexp)
5872 (defun org-compute-latex-and-related-regexp ()
5873 "Compute regular expression for LaTeX, entities and sub/superscript.
5874 Result depends on variable `org-highlight-latex-and-related'."
5875 (org-set-local
5876 'org-latex-and-related-regexp
5877 (let* ((re-sub
5878 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5879 ((eq org-use-sub-superscripts '{})
5880 (list org-match-substring-with-braces-regexp))
5881 (org-use-sub-superscripts (list org-match-substring-regexp))))
5882 (re-latex
5883 (when (memq 'latex org-highlight-latex-and-related)
5884 (let ((matchers (plist-get org-format-latex-options :matchers)))
5885 (delq nil
5886 (mapcar (lambda (x)
5887 (and (member (car x) matchers) (nth 1 x)))
5888 org-latex-regexps)))))
5889 (re-entities
5890 (when (memq 'entities org-highlight-latex-and-related)
5891 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5892 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5894 (defun org-do-latex-and-related (limit)
5895 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5896 LIMIT bounds the search for syntax to highlight. Stop at first
5897 highlighted object, if any. Return t if some highlighting was
5898 done, nil otherwise."
5899 (when org-highlight-latex-and-related
5900 (catch 'found
5901 (while (re-search-forward org-latex-and-related-regexp limit t)
5902 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5903 'face))
5904 '(org-code org-verbatim underline))
5905 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5906 '(?_ ?^))
5908 0)))
5909 (font-lock-prepend-text-property
5910 (+ offset (match-beginning 0)) (match-end 0)
5911 'face 'org-latex-and-related)
5912 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5913 '(font-lock-multiline t)))
5914 (throw 'found t)))
5915 nil)))
5917 (defun org-restart-font-lock ()
5918 "Restart `font-lock-mode', to force refontification."
5919 (when (and (boundp 'font-lock-mode) font-lock-mode)
5920 (font-lock-mode -1)
5921 (font-lock-mode 1)))
5923 (defun org-all-targets (&optional radio)
5924 "Return a list of all targets in this file.
5925 When optional argument RADIO is non-nil, only find radio
5926 targets."
5927 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5928 (save-excursion
5929 (goto-char (point-min))
5930 (while (re-search-forward re nil t)
5931 ;; Make sure point is really within the object.
5932 (backward-char)
5933 (let ((obj (org-element-context)))
5934 (when (memq (org-element-type obj) '(radio-target target))
5935 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5936 rtn)))
5938 (defun org-make-target-link-regexp (targets)
5939 "Make regular expression matching all strings in TARGETS.
5940 The regular expression finds the targets also if there is a line break
5941 between words."
5942 (and targets
5943 (concat
5944 "\\<\\("
5945 (mapconcat
5946 (lambda (x)
5947 (setq x (regexp-quote x))
5948 (while (string-match " +" x)
5949 (setq x (replace-match "\\s-+" t t x)))
5951 targets
5952 "\\|")
5953 "\\)\\>")))
5955 (defun org-activate-tags (limit)
5956 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5957 (progn
5958 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5959 (add-text-properties (match-beginning 1) (match-end 1)
5960 (list 'mouse-face 'highlight
5961 'keymap org-mouse-map))
5962 (org-rear-nonsticky-at (match-end 1))
5963 t)))
5965 (defun org-outline-level ()
5966 "Compute the outline level of the heading at point.
5967 If this is called at a normal headline, the level is the number of stars.
5968 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5969 (save-excursion
5970 (if (not (condition-case nil
5971 (org-back-to-heading t)
5972 (error nil)))
5974 (looking-at org-outline-regexp)
5975 (1- (- (match-end 0) (match-beginning 0))))))
5977 (defvar org-font-lock-keywords nil)
5979 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5980 "Regular expression matching a property line.")
5982 (defvar org-font-lock-hook nil
5983 "Functions to be called for special font lock stuff.")
5985 (defvar org-font-lock-set-keywords-hook nil
5986 "Functions that can manipulate `org-font-lock-extra-keywords'.
5987 This is called after `org-font-lock-extra-keywords' is defined, but before
5988 it is installed to be used by font lock. This can be useful if something
5989 needs to be inserted at a specific position in the font-lock sequence.")
5991 (defun org-font-lock-hook (limit)
5992 "Run `org-font-lock-hook' within LIMIT."
5993 (run-hook-with-args 'org-font-lock-hook limit))
5995 (defun org-set-font-lock-defaults ()
5996 "Set font lock defaults for the current buffer."
5997 (let* ((em org-fontify-emphasized-text)
5998 (lk org-activate-links)
5999 (org-font-lock-extra-keywords
6000 (list
6001 ;; Call the hook
6002 '(org-font-lock-hook)
6003 ;; Headlines
6004 `(,(if org-fontify-whole-heading-line
6005 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6006 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6007 (1 (org-get-level-face 1))
6008 (2 (org-get-level-face 2))
6009 (3 (org-get-level-face 3)))
6010 ;; Table lines
6011 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6012 (1 'org-table t))
6013 ;; Table internals
6014 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6015 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6016 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6017 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6018 ;; Drawers
6019 (list org-drawer-regexp '(0 'org-special-keyword t))
6020 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6021 ;; Properties
6022 (list org-property-re
6023 '(1 'org-special-keyword t)
6024 '(3 'org-property-value t))
6025 ;; Links
6026 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6027 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6028 (if (memq 'plain lk) '(org-activate-plain-links))
6029 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6030 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6031 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6032 (if (memq 'footnote lk) '(org-activate-footnote-links))
6033 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6034 '(org-hide-wide-columns (0 nil append))
6035 ;; TODO keyword
6036 (list (format org-heading-keyword-regexp-format
6037 org-todo-regexp)
6038 '(2 (org-get-todo-face 2) t))
6039 ;; DONE
6040 (if org-fontify-done-headline
6041 (list (format org-heading-keyword-regexp-format
6042 (concat
6043 "\\(?:"
6044 (mapconcat 'regexp-quote org-done-keywords "\\|")
6045 "\\)"))
6046 '(2 'org-headline-done t))
6047 nil)
6048 ;; Priorities
6049 '(org-font-lock-add-priority-faces)
6050 ;; Tags
6051 '(org-font-lock-add-tag-faces)
6052 ;; Special keywords
6053 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6054 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6055 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6056 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6057 ;; Emphasis
6058 (if em
6059 (if (featurep 'xemacs)
6060 '(org-do-emphasis-faces (0 nil append))
6061 '(org-do-emphasis-faces)))
6062 ;; Checkboxes
6063 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6064 1 'org-checkbox prepend)
6065 (if (cdr (assq 'checkbox org-list-automatic-rules))
6066 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6067 (0 (org-get-checkbox-statistics-face) t)))
6068 ;; Description list items
6069 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6070 1 'org-list-dt prepend)
6071 ;; ARCHIVEd headings
6072 (list (concat
6073 org-outline-regexp-bol
6074 "\\(.*:" org-archive-tag ":.*\\)")
6075 '(1 'org-archived prepend))
6076 ;; Specials
6077 '(org-do-latex-and-related)
6078 '(org-fontify-entities)
6079 '(org-raise-scripts)
6080 ;; Code
6081 '(org-activate-code (1 'org-code t))
6082 ;; COMMENT
6083 (list (format org-heading-keyword-regexp-format
6084 (concat "\\("
6085 org-comment-string "\\|" org-quote-string
6086 "\\)"))
6087 '(2 'org-special-keyword t))
6088 ;; Blocks and meta lines
6089 '(org-fontify-meta-lines-and-blocks)
6091 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6092 (run-hooks 'org-font-lock-set-keywords-hook)
6093 ;; Now set the full font-lock-keywords
6094 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6095 (org-set-local 'font-lock-defaults
6096 '(org-font-lock-keywords t nil nil backward-paragraph))
6097 (kill-local-variable 'font-lock-keywords) nil))
6099 (defun org-toggle-pretty-entities ()
6100 "Toggle the composition display of entities as UTF8 characters."
6101 (interactive)
6102 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6103 (org-restart-font-lock)
6104 (if org-pretty-entities
6105 (message "Entities are displayed as UTF8 characters")
6106 (save-restriction
6107 (widen)
6108 (org-decompose-region (point-min) (point-max))
6109 (message "Entities are displayed plain"))))
6111 (defvar org-custom-properties-overlays nil
6112 "List of overlays used for custom properties.")
6113 (make-variable-buffer-local 'org-custom-properties-overlays)
6115 (defun org-toggle-custom-properties-visibility ()
6116 "Display or hide properties in `org-custom-properties'."
6117 (interactive)
6118 (if org-custom-properties-overlays
6119 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6120 (setq org-custom-properties-overlays nil))
6121 (unless (not org-custom-properties)
6122 (save-excursion
6123 (save-restriction
6124 (widen)
6125 (goto-char (point-min))
6126 (while (re-search-forward org-property-re nil t)
6127 (mapc (lambda(p)
6128 (when (equal p (substring (match-string 1) 1 -1))
6129 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6130 (overlay-put o 'invisible t)
6131 (overlay-put o 'org-custom-property t)
6132 (push o org-custom-properties-overlays))))
6133 org-custom-properties)))))))
6135 (defun org-fontify-entities (limit)
6136 "Find an entity to fontify."
6137 (let (ee)
6138 (when org-pretty-entities
6139 (catch 'match
6140 (while (re-search-forward
6141 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6142 limit t)
6143 (if (and (not (org-in-indented-comment-line))
6144 (setq ee (org-entity-get (match-string 1)))
6145 (= (length (nth 6 ee)) 1))
6146 (let*
6147 ((end (if (equal (match-string 2) "{}")
6148 (match-end 2)
6149 (match-end 1))))
6150 (add-text-properties
6151 (match-beginning 0) end
6152 (list 'font-lock-fontified t))
6153 (compose-region (match-beginning 0) end
6154 (nth 6 ee) nil)
6155 (backward-char 1)
6156 (throw 'match t))))
6157 nil))))
6159 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6160 "Fontify string S like in Org-mode."
6161 (with-temp-buffer
6162 (insert s)
6163 (let ((org-odd-levels-only odd-levels))
6164 (org-mode)
6165 (font-lock-fontify-buffer)
6166 (buffer-string))))
6168 (defvar org-m nil)
6169 (defvar org-l nil)
6170 (defvar org-f nil)
6171 (defun org-get-level-face (n)
6172 "Get the right face for match N in font-lock matching of headlines."
6173 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6174 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6175 (if org-cycle-level-faces
6176 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6177 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6178 (cond
6179 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6180 ((eq n 2) org-f)
6181 (t (if org-level-color-stars-only nil org-f))))
6184 (defun org-get-todo-face (kwd)
6185 "Get the right face for a TODO keyword KWD.
6186 If KWD is a number, get the corresponding match group."
6187 (if (numberp kwd) (setq kwd (match-string kwd)))
6188 (or (org-face-from-face-or-color
6189 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6190 (and (member kwd org-done-keywords) 'org-done)
6191 'org-todo))
6193 (defun org-face-from-face-or-color (context inherit face-or-color)
6194 "Create a face list that inherits INHERIT, but sets the foreground color.
6195 When FACE-OR-COLOR is not a string, just return it."
6196 (if (stringp face-or-color)
6197 (list :inherit inherit
6198 (cdr (assoc context org-faces-easy-properties))
6199 face-or-color)
6200 face-or-color))
6202 (defun org-font-lock-add-tag-faces (limit)
6203 "Add the special tag faces."
6204 (when (and org-tag-faces org-tags-special-faces-re)
6205 (while (re-search-forward org-tags-special-faces-re limit t)
6206 (add-text-properties (match-beginning 1) (match-end 1)
6207 (list 'face (org-get-tag-face 1)
6208 'font-lock-fontified t))
6209 (backward-char 1))))
6211 (defun org-font-lock-add-priority-faces (limit)
6212 "Add the special priority faces."
6213 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6214 (when (save-match-data (org-at-heading-p))
6215 (add-text-properties
6216 (match-beginning 0) (match-end 0)
6217 (list 'face (or (org-face-from-face-or-color
6218 'priority 'org-priority
6219 (cdr (assoc (char-after (match-beginning 1))
6220 org-priority-faces)))
6221 'org-priority)
6222 'font-lock-fontified t)))))
6224 (defun org-get-tag-face (kwd)
6225 "Get the right face for a TODO keyword KWD.
6226 If KWD is a number, get the corresponding match group."
6227 (if (numberp kwd) (setq kwd (match-string kwd)))
6228 (or (org-face-from-face-or-color
6229 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6230 'org-tag))
6232 (defun org-unfontify-region (beg end &optional maybe_loudly)
6233 "Remove fontification and activation overlays from links."
6234 (font-lock-default-unfontify-region beg end)
6235 (let* ((buffer-undo-list t)
6236 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6237 (inhibit-modification-hooks t)
6238 deactivate-mark buffer-file-name buffer-file-truename)
6239 (org-decompose-region beg end)
6240 (remove-text-properties beg end
6241 '(mouse-face t keymap t org-linked-text t
6242 invisible t intangible t
6243 org-no-flyspell t org-emphasis t))
6244 (org-remove-font-lock-display-properties beg end)))
6246 (defconst org-script-display '(((raise -0.3) (height 0.7))
6247 ((raise 0.3) (height 0.7))
6248 ((raise -0.5))
6249 ((raise 0.5)))
6250 "Display properties for showing superscripts and subscripts.")
6252 (defun org-remove-font-lock-display-properties (beg end)
6253 "Remove specific display properties that have been added by font lock.
6254 The will remove the raise properties that are used to show superscripts
6255 and subscripts."
6256 (let (next prop)
6257 (while (< beg end)
6258 (setq next (next-single-property-change beg 'display nil end)
6259 prop (get-text-property beg 'display))
6260 (if (member prop org-script-display)
6261 (put-text-property beg next 'display nil))
6262 (setq beg next))))
6264 (defun org-raise-scripts (limit)
6265 "Add raise properties to sub/superscripts."
6266 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6267 (if (re-search-forward
6268 (if (eq org-use-sub-superscripts t)
6269 org-match-substring-regexp
6270 org-match-substring-with-braces-regexp)
6271 limit t)
6272 (let* ((pos (point)) table-p comment-p
6273 (mpos (match-beginning 3))
6274 (emph-p (get-text-property mpos 'org-emphasis))
6275 (link-p (get-text-property mpos 'mouse-face))
6276 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6277 (goto-char (point-at-bol))
6278 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6279 comment-p (org-looking-at-p "[ \t]*#"))
6280 (goto-char pos)
6281 ;; FIXME: Should we go back one character here, for a_b^c
6282 ;; (goto-char (1- pos)) ;????????????????????
6283 (if (or comment-p emph-p link-p keyw-p)
6285 (put-text-property (match-beginning 3) (match-end 0)
6286 'display
6287 (if (equal (char-after (match-beginning 2)) ?^)
6288 (nth (if table-p 3 1) org-script-display)
6289 (nth (if table-p 2 0) org-script-display)))
6290 (add-text-properties (match-beginning 2) (match-end 2)
6291 (list 'invisible t
6292 'org-dwidth t 'org-dwidth-n 1))
6293 (if (and (eq (char-after (match-beginning 3)) ?{)
6294 (eq (char-before (match-end 3)) ?}))
6295 (progn
6296 (add-text-properties
6297 (match-beginning 3) (1+ (match-beginning 3))
6298 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6299 (add-text-properties
6300 (1- (match-end 3)) (match-end 3)
6301 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6302 t)))))
6304 ;;;; Visibility cycling, including org-goto and indirect buffer
6306 ;;; Cycling
6308 (defvar org-cycle-global-status nil)
6309 (make-variable-buffer-local 'org-cycle-global-status)
6310 (put 'org-cycle-global-status 'org-state t)
6311 (defvar org-cycle-subtree-status nil)
6312 (make-variable-buffer-local 'org-cycle-subtree-status)
6313 (put 'org-cycle-subtree-status 'org-state t)
6315 (defvar org-inlinetask-min-level)
6317 ;;;###autoload
6318 (defun org-cycle (&optional arg)
6319 "TAB-action and visibility cycling for Org-mode.
6321 This is the command invoked in Org-mode by the TAB key. Its main purpose
6322 is outline visibility cycling, but it also invokes other actions
6323 in special contexts.
6325 - When this function is called with a prefix argument, rotate the entire
6326 buffer through 3 states (global cycling)
6327 1. OVERVIEW: Show only top-level headlines.
6328 2. CONTENTS: Show all headlines of all levels, but no body text.
6329 3. SHOW ALL: Show everything.
6330 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6331 determined by the variable `org-startup-folded', and by any VISIBILITY
6332 properties in the buffer.
6333 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6334 including any drawers.
6336 - When inside a table, re-align the table and move to the next field.
6338 - When point is at the beginning of a headline, rotate the subtree started
6339 by this line through 3 different states (local cycling)
6340 1. FOLDED: Only the main headline is shown.
6341 2. CHILDREN: The main headline and the direct children are shown.
6342 From this state, you can move to one of the children
6343 and zoom in further.
6344 3. SUBTREE: Show the entire subtree, including body text.
6345 If there is no subtree, switch directly from CHILDREN to FOLDED.
6347 - When point is at the beginning of an empty headline and the variable
6348 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6349 of the headline by demoting and promoting it to likely levels. This
6350 speeds up creation document structure by pressing TAB once or several
6351 times right after creating a new headline.
6353 - When there is a numeric prefix, go up to a heading with level ARG, do
6354 a `show-subtree' and return to the previous cursor position. If ARG
6355 is negative, go up that many levels.
6357 - When point is not at the beginning of a headline, execute the global
6358 binding for TAB, which is re-indenting the line. See the option
6359 `org-cycle-emulate-tab' for details.
6361 - Special case: if point is at the beginning of the buffer and there is
6362 no headline in line 1, this function will act as if called with prefix arg
6363 (C-u TAB, same as S-TAB) also when called without prefix arg.
6364 But only if also the variable `org-cycle-global-at-bob' is t."
6365 (interactive "P")
6366 (org-load-modules-maybe)
6367 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6368 (and org-cycle-level-after-item/entry-creation
6369 (or (org-cycle-level)
6370 (org-cycle-item-indentation))))
6371 (let* (message-log-max ; Don't populate the *Messages* buffer
6372 (limit-level
6373 (or org-cycle-max-level
6374 (and (boundp 'org-inlinetask-min-level)
6375 org-inlinetask-min-level
6376 (1- org-inlinetask-min-level))))
6377 (nstars (and limit-level
6378 (if org-odd-levels-only
6379 (and limit-level (1- (* limit-level 2)))
6380 limit-level)))
6381 (org-outline-regexp
6382 (if (not (derived-mode-p 'org-mode))
6383 outline-regexp
6384 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6385 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6386 (not (looking-at org-outline-regexp))))
6387 (org-cycle-hook
6388 (if bob-special
6389 (delq 'org-optimize-window-after-visibility-change
6390 (copy-sequence org-cycle-hook))
6391 org-cycle-hook))
6392 (pos (point)))
6394 (if (or bob-special (equal arg '(4)))
6395 ;; special case: use global cycling
6396 (setq arg t))
6398 (cond
6400 ((equal arg '(16))
6401 (setq last-command 'dummy)
6402 (org-set-startup-visibility)
6403 (message "Startup visibility, plus VISIBILITY properties"))
6405 ((equal arg '(64))
6406 (show-all)
6407 (message "Entire buffer visible, including drawers"))
6409 ;; Table: enter it or move to the next field.
6410 ((org-at-table-p 'any)
6411 (if (org-at-table.el-p)
6412 (message "Use C-c ' to edit table.el tables")
6413 (if arg (org-table-edit-field t)
6414 (org-table-justify-field-maybe)
6415 (call-interactively 'org-table-next-field))))
6417 ((run-hook-with-args-until-success
6418 'org-tab-after-check-for-table-hook))
6420 ;; Global cycling: delegate to `org-cycle-internal-global'.
6421 ((eq arg t) (org-cycle-internal-global))
6423 ;; Drawers: delegate to `org-flag-drawer'.
6424 ((and org-drawers org-drawer-regexp
6425 (save-excursion
6426 (beginning-of-line 1)
6427 (looking-at org-drawer-regexp)))
6428 (org-flag-drawer ; toggle block visibility
6429 (not (get-char-property (match-end 0) 'invisible))))
6431 ;; Show-subtree, ARG levels up from here.
6432 ((integerp arg)
6433 (save-excursion
6434 (org-back-to-heading)
6435 (outline-up-heading (if (< arg 0) (- arg)
6436 (- (funcall outline-level) arg)))
6437 (org-show-subtree)))
6439 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6440 ((and (featurep 'org-inlinetask)
6441 (org-inlinetask-at-task-p)
6442 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6443 (org-inlinetask-toggle-visibility))
6445 ((org-try-cdlatex-tab))
6447 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6448 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6449 (save-excursion (beginning-of-line 1)
6450 (looking-at org-outline-regexp)))
6451 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6452 (org-cycle-internal-local))
6454 ;; From there: TAB emulation and template completion.
6455 (buffer-read-only (org-back-to-heading))
6457 ((run-hook-with-args-until-success
6458 'org-tab-after-check-for-cycling-hook))
6460 ((org-try-structure-completion))
6462 ((run-hook-with-args-until-success
6463 'org-tab-before-tab-emulation-hook))
6465 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6466 (or (not (bolp))
6467 (not (looking-at org-outline-regexp))))
6468 (call-interactively (global-key-binding "\t")))
6470 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6471 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6472 (or (and (eq org-cycle-emulate-tab 'white)
6473 (= (match-end 0) (point-at-eol)))
6474 (and (eq org-cycle-emulate-tab 'whitestart)
6475 (>= (match-end 0) pos))))
6477 (eq org-cycle-emulate-tab t))
6478 (call-interactively (global-key-binding "\t")))
6480 (t (save-excursion
6481 (org-back-to-heading)
6482 (org-cycle)))))))
6484 (defun org-cycle-internal-global ()
6485 "Do the global cycling action."
6486 ;; Hack to avoid display of messages for .org attachments in Gnus
6487 (let (message-log-max ; Don't populate the *Messages* buffer
6488 (ga (string-match "\\*fontification" (buffer-name))))
6489 (cond
6490 ((and (eq last-command this-command)
6491 (eq org-cycle-global-status 'overview))
6492 ;; We just created the overview - now do table of contents
6493 ;; This can be slow in very large buffers, so indicate action
6494 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6495 (unless ga (message "CONTENTS..."))
6496 (org-content)
6497 (unless ga (message "CONTENTS...done"))
6498 (setq org-cycle-global-status 'contents)
6499 (run-hook-with-args 'org-cycle-hook 'contents))
6501 ((and (eq last-command this-command)
6502 (eq org-cycle-global-status 'contents))
6503 ;; We just showed the table of contents - now show everything
6504 (run-hook-with-args 'org-pre-cycle-hook 'all)
6505 (show-all)
6506 (unless ga (message "SHOW ALL"))
6507 (setq org-cycle-global-status 'all)
6508 (run-hook-with-args 'org-cycle-hook 'all))
6511 ;; Default action: go to overview
6512 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6513 (org-overview)
6514 (unless ga (message "OVERVIEW"))
6515 (setq org-cycle-global-status 'overview)
6516 (run-hook-with-args 'org-cycle-hook 'overview)))))
6518 (defun org-cycle-internal-local ()
6519 "Do the local cycling action."
6520 (let (message-log-max ; Don't populate the *Messages* buffer
6521 (goal-column 0) eoh eol eos has-children children-skipped struct)
6522 ;; First, determine end of headline (EOH), end of subtree or item
6523 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6524 (save-excursion
6525 (if (org-at-item-p)
6526 (progn
6527 (beginning-of-line)
6528 (setq struct (org-list-struct))
6529 (setq eoh (point-at-eol))
6530 (setq eos (org-list-get-item-end-before-blank (point) struct))
6531 (setq has-children (org-list-has-child-p (point) struct)))
6532 (org-back-to-heading)
6533 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6534 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6535 (setq has-children
6536 (or (save-excursion
6537 (let ((level (funcall outline-level)))
6538 (outline-next-heading)
6539 (and (org-at-heading-p t)
6540 (> (funcall outline-level) level))))
6541 (save-excursion
6542 (org-list-search-forward (org-item-beginning-re) eos t)))))
6543 ;; Determine end invisible part of buffer (EOL)
6544 (beginning-of-line 2)
6545 ;; XEmacs doesn't have `next-single-char-property-change'
6546 (if (featurep 'xemacs)
6547 (while (and (not (eobp)) ;; this is like `next-line'
6548 (get-char-property (1- (point)) 'invisible))
6549 (beginning-of-line 2))
6550 (while (and (not (eobp)) ;; this is like `next-line'
6551 (get-char-property (1- (point)) 'invisible))
6552 (goto-char (next-single-char-property-change (point) 'invisible))
6553 (and (eolp) (beginning-of-line 2))))
6554 (setq eol (point)))
6555 ;; Find out what to do next and set `this-command'
6556 (cond
6557 ((= eos eoh)
6558 ;; Nothing is hidden behind this heading
6559 (unless (org-before-first-heading-p)
6560 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6561 (message "EMPTY ENTRY")
6562 (setq org-cycle-subtree-status nil)
6563 (save-excursion
6564 (goto-char eos)
6565 (outline-next-heading)
6566 (if (outline-invisible-p) (org-flag-heading nil))))
6567 ((and (or (>= eol eos)
6568 (not (string-match "\\S-" (buffer-substring eol eos))))
6569 (or has-children
6570 (not (setq children-skipped
6571 org-cycle-skip-children-state-if-no-children))))
6572 ;; Entire subtree is hidden in one line: children view
6573 (unless (org-before-first-heading-p)
6574 (run-hook-with-args 'org-pre-cycle-hook 'children))
6575 (if (org-at-item-p)
6576 (org-list-set-item-visibility (point-at-bol) struct 'children)
6577 (org-show-entry)
6578 (org-with-limited-levels (show-children))
6579 ;; FIXME: This slows down the func way too much.
6580 ;; How keep drawers hidden in subtree anyway?
6581 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6582 ;; (org-cycle-hide-drawers 'subtree))
6584 ;; Fold every list in subtree to top-level items.
6585 (when (eq org-cycle-include-plain-lists 'integrate)
6586 (save-excursion
6587 (org-back-to-heading)
6588 (while (org-list-search-forward (org-item-beginning-re) eos t)
6589 (beginning-of-line 1)
6590 (let* ((struct (org-list-struct))
6591 (prevs (org-list-prevs-alist struct))
6592 (end (org-list-get-bottom-point struct)))
6593 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6594 (org-list-get-all-items (point) struct prevs))
6595 (goto-char end))))))
6596 (message "CHILDREN")
6597 (save-excursion
6598 (goto-char eos)
6599 (outline-next-heading)
6600 (if (outline-invisible-p) (org-flag-heading nil)))
6601 (setq org-cycle-subtree-status 'children)
6602 (unless (org-before-first-heading-p)
6603 (run-hook-with-args 'org-cycle-hook 'children)))
6604 ((or children-skipped
6605 (and (eq last-command this-command)
6606 (eq org-cycle-subtree-status 'children)))
6607 ;; We just showed the children, or no children are there,
6608 ;; now show everything.
6609 (unless (org-before-first-heading-p)
6610 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6611 (outline-flag-region eoh eos nil)
6612 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6613 (setq org-cycle-subtree-status 'subtree)
6614 (unless (org-before-first-heading-p)
6615 (run-hook-with-args 'org-cycle-hook 'subtree)))
6617 ;; Default action: hide the subtree.
6618 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6619 (outline-flag-region eoh eos t)
6620 (message "FOLDED")
6621 (setq org-cycle-subtree-status 'folded)
6622 (unless (org-before-first-heading-p)
6623 (run-hook-with-args 'org-cycle-hook 'folded))))))
6625 ;;;###autoload
6626 (defun org-global-cycle (&optional arg)
6627 "Cycle the global visibility. For details see `org-cycle'.
6628 With \\[universal-argument] prefix arg, switch to startup visibility.
6629 With a numeric prefix, show all headlines up to that level."
6630 (interactive "P")
6631 (let ((org-cycle-include-plain-lists
6632 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6633 (cond
6634 ((integerp arg)
6635 (show-all)
6636 (hide-sublevels arg)
6637 (setq org-cycle-global-status 'contents))
6638 ((equal arg '(4))
6639 (org-set-startup-visibility)
6640 (message "Startup visibility, plus VISIBILITY properties."))
6642 (org-cycle '(4))))))
6644 (defun org-set-startup-visibility ()
6645 "Set the visibility required by startup options and properties."
6646 (cond
6647 ((eq org-startup-folded t)
6648 (org-cycle '(4)))
6649 ((eq org-startup-folded 'content)
6650 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6651 (org-cycle '(4)) (org-cycle '(4)))))
6652 (unless (eq org-startup-folded 'showeverything)
6653 (if org-hide-block-startup (org-hide-block-all))
6654 (org-set-visibility-according-to-property 'no-cleanup)
6655 (org-cycle-hide-archived-subtrees 'all)
6656 (org-cycle-hide-drawers 'all)
6657 (org-cycle-show-empty-lines t)))
6659 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6660 "Switch subtree visibilities according to :VISIBILITY: property."
6661 (interactive)
6662 (let (org-show-entry-below state)
6663 (save-excursion
6664 (goto-char (point-min))
6665 (while (re-search-forward
6666 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6667 nil t)
6668 (setq state (match-string 1))
6669 (save-excursion
6670 (org-back-to-heading t)
6671 (hide-subtree)
6672 (org-reveal)
6673 (cond
6674 ((equal state '("fold" "folded"))
6675 (hide-subtree))
6676 ((equal state "children")
6677 (org-show-hidden-entry)
6678 (show-children))
6679 ((equal state "content")
6680 (save-excursion
6681 (save-restriction
6682 (org-narrow-to-subtree)
6683 (org-content))))
6684 ((member state '("all" "showall"))
6685 (show-subtree)))))
6686 (unless no-cleanup
6687 (org-cycle-hide-archived-subtrees 'all)
6688 (org-cycle-hide-drawers 'all)
6689 (org-cycle-show-empty-lines 'all)))))
6691 ;; This function uses outline-regexp instead of the more fundamental
6692 ;; org-outline-regexp so that org-cycle-global works outside of Org
6693 ;; buffers, where outline-regexp is needed.
6694 (defun org-overview ()
6695 "Switch to overview mode, showing only top-level headlines.
6696 Really, this shows all headlines with level equal or greater than the level
6697 of the first headline in the buffer. This is important, because if the
6698 first headline is not level one, then (hide-sublevels 1) gives confusing
6699 results."
6700 (interactive)
6701 (let ((level (save-excursion
6702 (goto-char (point-min))
6703 (if (re-search-forward (concat "^" outline-regexp) nil t)
6704 (progn
6705 (goto-char (match-beginning 0))
6706 (funcall outline-level))))))
6707 (and level (hide-sublevels level))))
6709 (defun org-content (&optional arg)
6710 "Show all headlines in the buffer, like a table of contents.
6711 With numerical argument N, show content up to level N."
6712 (interactive "P")
6713 (save-excursion
6714 ;; Visit all headings and show their offspring
6715 (and (integerp arg) (org-overview))
6716 (goto-char (point-max))
6717 (catch 'exit
6718 (while (and (progn (condition-case nil
6719 (outline-previous-visible-heading 1)
6720 (error (goto-char (point-min))))
6722 (looking-at org-outline-regexp))
6723 (if (integerp arg)
6724 (show-children (1- arg))
6725 (show-branches))
6726 (if (bobp) (throw 'exit nil))))))
6729 (defun org-optimize-window-after-visibility-change (state)
6730 "Adjust the window after a change in outline visibility.
6731 This function is the default value of the hook `org-cycle-hook'."
6732 (when (get-buffer-window (current-buffer))
6733 (cond
6734 ((eq state 'content) nil)
6735 ((eq state 'all) nil)
6736 ((eq state 'folded) nil)
6737 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6738 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6740 (defun org-remove-empty-overlays-at (pos)
6741 "Remove outline overlays that do not contain non-white stuff."
6742 (mapc
6743 (lambda (o)
6744 (and (eq 'outline (overlay-get o 'invisible))
6745 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6746 (overlay-end o))))
6747 (delete-overlay o)))
6748 (overlays-at pos)))
6750 (defun org-clean-visibility-after-subtree-move ()
6751 "Fix visibility issues after moving a subtree."
6752 ;; First, find a reasonable region to look at:
6753 ;; Start two siblings above, end three below
6754 (let* ((beg (save-excursion
6755 (and (org-get-last-sibling)
6756 (org-get-last-sibling))
6757 (point)))
6758 (end (save-excursion
6759 (and (org-get-next-sibling)
6760 (org-get-next-sibling)
6761 (org-get-next-sibling))
6762 (if (org-at-heading-p)
6763 (point-at-eol)
6764 (point))))
6765 (level (looking-at "\\*+"))
6766 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6767 (save-excursion
6768 (save-restriction
6769 (narrow-to-region beg end)
6770 (when re
6771 ;; Properly fold already folded siblings
6772 (goto-char (point-min))
6773 (while (re-search-forward re nil t)
6774 (if (and (not (outline-invisible-p))
6775 (save-excursion
6776 (goto-char (point-at-eol)) (outline-invisible-p)))
6777 (hide-entry))))
6778 (org-cycle-show-empty-lines 'overview)
6779 (org-cycle-hide-drawers 'overview)))))
6781 (defun org-cycle-show-empty-lines (state)
6782 "Show empty lines above all visible headlines.
6783 The region to be covered depends on STATE when called through
6784 `org-cycle-hook'. Lisp program can use t for STATE to get the
6785 entire buffer covered. Note that an empty line is only shown if there
6786 are at least `org-cycle-separator-lines' empty lines before the headline."
6787 (when (not (= org-cycle-separator-lines 0))
6788 (save-excursion
6789 (let* ((n (abs org-cycle-separator-lines))
6790 (re (cond
6791 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6792 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6793 (t (let ((ns (number-to-string (- n 2))))
6794 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6795 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6796 beg end b e)
6797 (cond
6798 ((memq state '(overview contents t))
6799 (setq beg (point-min) end (point-max)))
6800 ((memq state '(children folded))
6801 (setq beg (point) end (progn (org-end-of-subtree t t)
6802 (beginning-of-line 2)
6803 (point)))))
6804 (when beg
6805 (goto-char beg)
6806 (while (re-search-forward re end t)
6807 (unless (get-char-property (match-end 1) 'invisible)
6808 (setq e (match-end 1))
6809 (if (< org-cycle-separator-lines 0)
6810 (setq b (save-excursion
6811 (goto-char (match-beginning 0))
6812 (org-back-over-empty-lines)
6813 (if (save-excursion
6814 (goto-char (max (point-min) (1- (point))))
6815 (org-at-heading-p))
6816 (1- (point))
6817 (point))))
6818 (setq b (match-beginning 1)))
6819 (outline-flag-region b e nil)))))))
6820 ;; Never hide empty lines at the end of the file.
6821 (save-excursion
6822 (goto-char (point-max))
6823 (outline-previous-heading)
6824 (outline-end-of-heading)
6825 (if (and (looking-at "[ \t\n]+")
6826 (= (match-end 0) (point-max)))
6827 (outline-flag-region (point) (match-end 0) nil))))
6829 (defun org-show-empty-lines-in-parent ()
6830 "Move to the parent and re-show empty lines before visible headlines."
6831 (save-excursion
6832 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6833 (org-cycle-show-empty-lines context))))
6835 (defun org-files-list ()
6836 "Return `org-agenda-files' list, plus all open org-mode files.
6837 This is useful for operations that need to scan all of a user's
6838 open and agenda-wise Org files."
6839 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6840 (dolist (buf (buffer-list))
6841 (with-current-buffer buf
6842 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6843 (let ((file (expand-file-name (buffer-file-name))))
6844 (unless (member file files)
6845 (push file files))))))
6846 files))
6848 (defsubst org-entry-beginning-position ()
6849 "Return the beginning position of the current entry."
6850 (save-excursion (outline-back-to-heading t) (point)))
6852 (defsubst org-entry-end-position ()
6853 "Return the end position of the current entry."
6854 (save-excursion (outline-next-heading) (point)))
6856 (defun org-cycle-hide-drawers (state)
6857 "Re-hide all drawers after a visibility state change."
6858 (when (and (derived-mode-p 'org-mode)
6859 (not (memq state '(overview folded contents))))
6860 (save-excursion
6861 (let* ((globalp (memq state '(contents all)))
6862 (beg (if globalp (point-min) (point)))
6863 (end (if globalp (point-max)
6864 (if (eq state 'children)
6865 (save-excursion (outline-next-heading) (point))
6866 (org-end-of-subtree t)))))
6867 (goto-char beg)
6868 (while (re-search-forward org-drawer-regexp end t)
6869 (org-flag-drawer t))))))
6871 (defun org-cycle-hide-inline-tasks (state)
6872 "Re-hide inline task when switching to 'contents visibility state."
6873 (when (and (eq state 'contents)
6874 (boundp 'org-inlinetask-min-level)
6875 org-inlinetask-min-level)
6876 (hide-sublevels (1- org-inlinetask-min-level))))
6878 (defun org-flag-drawer (flag)
6879 "When FLAG is non-nil, hide the drawer we are within.
6880 Otherwise make it visible."
6881 (save-excursion
6882 (beginning-of-line 1)
6883 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6884 (let ((b (match-end 0)))
6885 (if (re-search-forward
6886 "^[ \t]*:END:"
6887 (save-excursion (outline-next-heading) (point)) t)
6888 (outline-flag-region b (point-at-eol) flag)
6889 (error ":END: line missing at position %s" b))))))
6891 (defun org-subtree-end-visible-p ()
6892 "Is the end of the current subtree visible?"
6893 (pos-visible-in-window-p
6894 (save-excursion (org-end-of-subtree t) (point))))
6896 (defun org-first-headline-recenter (&optional N)
6897 "Move cursor to the first headline and recenter the headline.
6898 Optional argument N means put the headline into the Nth line of the window."
6899 (goto-char (point-min))
6900 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6901 (beginning-of-line)
6902 (recenter (prefix-numeric-value N))))
6904 ;;; Saving and restoring visibility
6906 (defun org-outline-overlay-data (&optional use-markers)
6907 "Return a list of the locations of all outline overlays.
6908 These are overlays with the `invisible' property value `outline'.
6909 The return value is a list of cons cells, with start and stop
6910 positions for each overlay.
6911 If USE-MARKERS is set, return the positions as markers."
6912 (let (beg end)
6913 (save-excursion
6914 (save-restriction
6915 (widen)
6916 (delq nil
6917 (mapcar (lambda (o)
6918 (when (eq (overlay-get o 'invisible) 'outline)
6919 (setq beg (overlay-start o)
6920 end (overlay-end o))
6921 (and beg end (> end beg)
6922 (if use-markers
6923 (cons (move-marker (make-marker) beg)
6924 (move-marker (make-marker) end))
6925 (cons beg end)))))
6926 (overlays-in (point-min) (point-max))))))))
6928 (defun org-set-outline-overlay-data (data)
6929 "Create visibility overlays for all positions in DATA.
6930 DATA should have been made by `org-outline-overlay-data'."
6931 (let (o)
6932 (save-excursion
6933 (save-restriction
6934 (widen)
6935 (show-all)
6936 (mapc (lambda (c)
6937 (outline-flag-region (car c) (cdr c) t))
6938 data)))))
6940 ;;; Folding of blocks
6942 (defvar org-hide-block-overlays nil
6943 "Overlays hiding blocks.")
6944 (make-variable-buffer-local 'org-hide-block-overlays)
6946 (defun org-block-map (function &optional start end)
6947 "Call FUNCTION at the head of all source blocks in the current buffer.
6948 Optional arguments START and END can be used to limit the range."
6949 (let ((start (or start (point-min)))
6950 (end (or end (point-max))))
6951 (save-excursion
6952 (goto-char start)
6953 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6954 (save-excursion
6955 (save-match-data
6956 (goto-char (match-beginning 0))
6957 (funcall function)))))))
6959 (defun org-hide-block-toggle-all ()
6960 "Toggle the visibility of all blocks in the current buffer."
6961 (org-block-map #'org-hide-block-toggle))
6963 (defun org-hide-block-all ()
6964 "Fold all blocks in the current buffer."
6965 (interactive)
6966 (org-show-block-all)
6967 (org-block-map #'org-hide-block-toggle-maybe))
6969 (defun org-show-block-all ()
6970 "Unfold all blocks in the current buffer."
6971 (interactive)
6972 (mapc 'delete-overlay org-hide-block-overlays)
6973 (setq org-hide-block-overlays nil))
6975 (defun org-hide-block-toggle-maybe ()
6976 "Toggle visibility of block at point."
6977 (interactive)
6978 (let ((case-fold-search t))
6979 (if (save-excursion
6980 (beginning-of-line 1)
6981 (looking-at org-block-regexp))
6982 (progn (org-hide-block-toggle)
6983 t) ;; to signal that we took action
6984 nil))) ;; to signal that we did not
6986 (defun org-hide-block-toggle (&optional force)
6987 "Toggle the visibility of the current block."
6988 (interactive)
6989 (save-excursion
6990 (beginning-of-line)
6991 (if (re-search-forward org-block-regexp nil t)
6992 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6993 (end (match-end 0)) ;; end of entire body
6995 (if (memq t (mapcar (lambda (overlay)
6996 (eq (overlay-get overlay 'invisible)
6997 'org-hide-block))
6998 (overlays-at start)))
6999 (if (or (not force) (eq force 'off))
7000 (mapc (lambda (ov)
7001 (when (member ov org-hide-block-overlays)
7002 (setq org-hide-block-overlays
7003 (delq ov org-hide-block-overlays)))
7004 (when (eq (overlay-get ov 'invisible)
7005 'org-hide-block)
7006 (delete-overlay ov)))
7007 (overlays-at start)))
7008 (setq ov (make-overlay start end))
7009 (overlay-put ov 'invisible 'org-hide-block)
7010 ;; make the block accessible to isearch
7011 (overlay-put
7012 ov 'isearch-open-invisible
7013 (lambda (ov)
7014 (when (member ov org-hide-block-overlays)
7015 (setq org-hide-block-overlays
7016 (delq ov org-hide-block-overlays)))
7017 (when (eq (overlay-get ov 'invisible)
7018 'org-hide-block)
7019 (delete-overlay ov))))
7020 (push ov org-hide-block-overlays)))
7021 (error "Not looking at a source block"))))
7023 ;; org-tab-after-check-for-cycling-hook
7024 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7025 ;; Remove overlays when changing major mode
7026 (add-hook 'org-mode-hook
7027 (lambda () (org-add-hook 'change-major-mode-hook
7028 'org-show-block-all 'append 'local)))
7030 ;;; Org-goto
7032 (defvar org-goto-window-configuration nil)
7033 (defvar org-goto-marker nil)
7034 (defvar org-goto-map)
7035 (defun org-goto-map ()
7036 "Set the keymap `org-goto'."
7037 (setq org-goto-map
7038 (let ((map (make-sparse-keymap)))
7039 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7040 mouse-drag-region universal-argument org-occur))
7041 cmd)
7042 (while (setq cmd (pop cmds))
7043 (substitute-key-definition cmd cmd map global-map)))
7044 (suppress-keymap map)
7045 (org-defkey map "\C-m" 'org-goto-ret)
7046 (org-defkey map [(return)] 'org-goto-ret)
7047 (org-defkey map [(left)] 'org-goto-left)
7048 (org-defkey map [(right)] 'org-goto-right)
7049 (org-defkey map [(control ?g)] 'org-goto-quit)
7050 (org-defkey map "\C-i" 'org-cycle)
7051 (org-defkey map [(tab)] 'org-cycle)
7052 (org-defkey map [(down)] 'outline-next-visible-heading)
7053 (org-defkey map [(up)] 'outline-previous-visible-heading)
7054 (if org-goto-auto-isearch
7055 (if (fboundp 'define-key-after)
7056 (define-key-after map [t] 'org-goto-local-auto-isearch)
7057 nil)
7058 (org-defkey map "q" 'org-goto-quit)
7059 (org-defkey map "n" 'outline-next-visible-heading)
7060 (org-defkey map "p" 'outline-previous-visible-heading)
7061 (org-defkey map "f" 'outline-forward-same-level)
7062 (org-defkey map "b" 'outline-backward-same-level)
7063 (org-defkey map "u" 'outline-up-heading))
7064 (org-defkey map "/" 'org-occur)
7065 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7066 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7067 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7068 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7069 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7070 map)))
7072 (defconst org-goto-help
7073 "Browse buffer copy, to find location or copy text.%s
7074 RET=jump to location C-g=quit and return to previous location
7075 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7077 (defvar org-goto-start-pos) ; dynamically scoped parameter
7079 ;; FIXME: Docstring does not mention both interfaces
7080 (defun org-goto (&optional alternative-interface)
7081 "Look up a different location in the current file, keeping current visibility.
7083 When you want look-up or go to a different location in a
7084 document, the fastest way is often to fold the entire buffer and
7085 then dive into the tree. This method has the disadvantage, that
7086 the previous location will be folded, which may not be what you
7087 want.
7089 This command works around this by showing a copy of the current
7090 buffer in an indirect buffer, in overview mode. You can dive
7091 into the tree in that copy, use org-occur and incremental search
7092 to find a location. When pressing RET or `Q', the command
7093 returns to the original buffer in which the visibility is still
7094 unchanged. After RET it will also jump to the location selected
7095 in the indirect buffer and expose the headline hierarchy above.
7097 With a prefix argument, use the alternative interface: e.g. if
7098 `org-goto-interface' is 'outline use 'outline-path-completion."
7099 (interactive "P")
7100 (org-goto-map)
7101 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7102 (org-refile-use-outline-path t)
7103 (org-refile-target-verify-function nil)
7104 (interface
7105 (if (not alternative-interface)
7106 org-goto-interface
7107 (if (eq org-goto-interface 'outline)
7108 'outline-path-completion
7109 'outline)))
7110 (org-goto-start-pos (point))
7111 (selected-point
7112 (if (eq interface 'outline)
7113 (car (org-get-location (current-buffer) org-goto-help))
7114 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7115 (org-refile-check-position pa)
7116 (nth 3 pa)))))
7117 (if selected-point
7118 (progn
7119 (org-mark-ring-push org-goto-start-pos)
7120 (goto-char selected-point)
7121 (if (or (outline-invisible-p) (org-invisible-p2))
7122 (org-show-context 'org-goto)))
7123 (message "Quit"))))
7125 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7126 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7127 (defvar org-goto-local-auto-isearch-map) ; defined below
7129 (defun org-get-location (buf help)
7130 "Let the user select a location in the Org-mode buffer BUF.
7131 This function uses a recursive edit. It returns the selected position
7132 or nil."
7133 (org-no-popups
7134 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7135 (isearch-hide-immediately nil)
7136 (isearch-search-fun-function
7137 (lambda () 'org-goto-local-search-headings))
7138 (org-goto-selected-point org-goto-exit-command))
7139 (save-excursion
7140 (save-window-excursion
7141 (delete-other-windows)
7142 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7143 (org-pop-to-buffer-same-window
7144 (condition-case nil
7145 (make-indirect-buffer (current-buffer) "*org-goto*")
7146 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7147 (with-output-to-temp-buffer "*Org Help*"
7148 (princ (format help (if org-goto-auto-isearch
7149 " Just type for auto-isearch."
7150 " n/p/f/b/u to navigate, q to quit."))))
7151 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7152 (setq buffer-read-only nil)
7153 (let ((org-startup-truncated t)
7154 (org-startup-folded nil)
7155 (org-startup-align-all-tables nil))
7156 (org-mode)
7157 (org-overview))
7158 (setq buffer-read-only t)
7159 (if (and (boundp 'org-goto-start-pos)
7160 (integer-or-marker-p org-goto-start-pos))
7161 (let ((org-show-hierarchy-above t)
7162 (org-show-siblings t)
7163 (org-show-following-heading t))
7164 (goto-char org-goto-start-pos)
7165 (and (outline-invisible-p) (org-show-context)))
7166 (goto-char (point-min)))
7167 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7168 (message "Select location and press RET")
7169 (use-local-map org-goto-map)
7170 (recursive-edit)))
7171 (kill-buffer "*org-goto*")
7172 (cons org-goto-selected-point org-goto-exit-command))))
7174 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7175 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7176 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7177 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7179 (defun org-goto-local-search-headings (string bound noerror)
7180 "Search and make sure that any matches are in headlines."
7181 (catch 'return
7182 (while (if isearch-forward
7183 (search-forward string bound noerror)
7184 (search-backward string bound noerror))
7185 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7186 (and (member :headline context)
7187 (not (member :tags context))))
7188 (throw 'return (point))))))
7190 (defun org-goto-local-auto-isearch ()
7191 "Start isearch."
7192 (interactive)
7193 (goto-char (point-min))
7194 (let ((keys (this-command-keys)))
7195 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7196 (isearch-mode t)
7197 (isearch-process-search-char (string-to-char keys)))))
7199 (defun org-goto-ret (&optional arg)
7200 "Finish `org-goto' by going to the new location."
7201 (interactive "P")
7202 (setq org-goto-selected-point (point)
7203 org-goto-exit-command 'return)
7204 (throw 'exit nil))
7206 (defun org-goto-left ()
7207 "Finish `org-goto' by going to the new location."
7208 (interactive)
7209 (if (org-at-heading-p)
7210 (progn
7211 (beginning-of-line 1)
7212 (setq org-goto-selected-point (point)
7213 org-goto-exit-command 'left)
7214 (throw 'exit nil))
7215 (error "Not on a heading")))
7217 (defun org-goto-right ()
7218 "Finish `org-goto' by going to the new location."
7219 (interactive)
7220 (if (org-at-heading-p)
7221 (progn
7222 (setq org-goto-selected-point (point)
7223 org-goto-exit-command 'right)
7224 (throw 'exit nil))
7225 (error "Not on a heading")))
7227 (defun org-goto-quit ()
7228 "Finish `org-goto' without cursor motion."
7229 (interactive)
7230 (setq org-goto-selected-point nil)
7231 (setq org-goto-exit-command 'quit)
7232 (throw 'exit nil))
7234 ;;; Indirect buffer display of subtrees
7236 (defvar org-indirect-dedicated-frame nil
7237 "This is the frame being used for indirect tree display.")
7238 (defvar org-last-indirect-buffer nil)
7240 (defun org-tree-to-indirect-buffer (&optional arg)
7241 "Create indirect buffer and narrow it to current subtree.
7242 With a numerical prefix ARG, go up to this level and then take that tree.
7243 If ARG is negative, go up that many levels.
7245 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7246 indirect buffer previously made with this command, to avoid proliferation of
7247 indirect buffers. However, when you call the command with a \
7248 \\[universal-argument] prefix, or
7249 when `org-indirect-buffer-display' is `new-frame', the last buffer
7250 is kept so that you can work with several indirect buffers at the same time.
7251 If `org-indirect-buffer-display' is `dedicated-frame', the \
7252 \\[universal-argument] prefix also
7253 requests that a new frame be made for the new buffer, so that the dedicated
7254 frame is not changed."
7255 (interactive "P")
7256 (let ((cbuf (current-buffer))
7257 (cwin (selected-window))
7258 (pos (point))
7259 beg end level heading ibuf)
7260 (save-excursion
7261 (org-back-to-heading t)
7262 (when (numberp arg)
7263 (setq level (org-outline-level))
7264 (if (< arg 0) (setq arg (+ level arg)))
7265 (while (> (setq level (org-outline-level)) arg)
7266 (org-up-heading-safe)))
7267 (setq beg (point)
7268 heading (org-get-heading))
7269 (org-end-of-subtree t t)
7270 (if (org-at-heading-p) (backward-char 1))
7271 (setq end (point)))
7272 (if (and (buffer-live-p org-last-indirect-buffer)
7273 (not (eq org-indirect-buffer-display 'new-frame))
7274 (not arg))
7275 (kill-buffer org-last-indirect-buffer))
7276 (setq ibuf (org-get-indirect-buffer cbuf)
7277 org-last-indirect-buffer ibuf)
7278 (cond
7279 ((or (eq org-indirect-buffer-display 'new-frame)
7280 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7281 (select-frame (make-frame))
7282 (delete-other-windows)
7283 (org-pop-to-buffer-same-window ibuf)
7284 (org-set-frame-title heading))
7285 ((eq org-indirect-buffer-display 'dedicated-frame)
7286 (raise-frame
7287 (select-frame (or (and org-indirect-dedicated-frame
7288 (frame-live-p org-indirect-dedicated-frame)
7289 org-indirect-dedicated-frame)
7290 (setq org-indirect-dedicated-frame (make-frame)))))
7291 (delete-other-windows)
7292 (org-pop-to-buffer-same-window ibuf)
7293 (org-set-frame-title (concat "Indirect: " heading)))
7294 ((eq org-indirect-buffer-display 'current-window)
7295 (org-pop-to-buffer-same-window ibuf))
7296 ((eq org-indirect-buffer-display 'other-window)
7297 (pop-to-buffer ibuf))
7298 (t (error "Invalid value")))
7299 (if (featurep 'xemacs)
7300 (save-excursion (org-mode) (turn-on-font-lock)))
7301 (narrow-to-region beg end)
7302 (show-all)
7303 (goto-char pos)
7304 (run-hook-with-args 'org-cycle-hook 'all)
7305 (and (window-live-p cwin) (select-window cwin))))
7307 (defun org-get-indirect-buffer (&optional buffer)
7308 (setq buffer (or buffer (current-buffer)))
7309 (let ((n 1) (base (buffer-name buffer)) bname)
7310 (while (buffer-live-p
7311 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7312 (setq n (1+ n)))
7313 (condition-case nil
7314 (make-indirect-buffer buffer bname 'clone)
7315 (error (make-indirect-buffer buffer bname)))))
7317 (defun org-set-frame-title (title)
7318 "Set the title of the current frame to the string TITLE."
7319 ;; FIXME: how to name a single frame in XEmacs???
7320 (unless (featurep 'xemacs)
7321 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7323 ;;;; Structure editing
7325 ;;; Inserting headlines
7327 (defun org-previous-line-empty-p ()
7328 (save-excursion
7329 (and (not (bobp))
7330 (or (beginning-of-line 0) t)
7331 (save-match-data
7332 (looking-at "[ \t]*$")))))
7334 (defun org-insert-heading (&optional force-heading invisible-ok)
7335 "Insert a new heading or item with same depth at point.
7336 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7337 If point is at the beginning of a headline, insert a sibling before the
7338 current headline. If point is not at the beginning, split the line,
7339 create the new headline with the text in the current line after point
7340 \(but see also the variable `org-M-RET-may-split-line').
7342 With a double prefix arg, force the heading to be inserted at the
7343 end of the parent subtree.
7345 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7346 This is important for non-interactive uses of the command."
7347 (interactive "P")
7348 (if (or (= (buffer-size) 0)
7349 (and (not (save-excursion
7350 (and (ignore-errors (org-back-to-heading invisible-ok))
7351 (org-at-heading-p))))
7352 (or force-heading (not (org-in-item-p)))))
7353 (progn
7354 (insert "\n* ")
7355 (run-hooks 'org-insert-heading-hook))
7356 (when (or force-heading (not (org-insert-item)))
7357 (let* ((empty-line-p nil)
7358 (level nil)
7359 (on-heading (org-at-heading-p))
7360 (head (save-excursion
7361 (condition-case nil
7362 (progn
7363 (org-back-to-heading invisible-ok)
7364 (when (and (not on-heading)
7365 (featurep 'org-inlinetask)
7366 (integerp org-inlinetask-min-level)
7367 (>= (length (match-string 0))
7368 org-inlinetask-min-level))
7369 ;; Find a heading level before the inline task
7370 (while (and (setq level (org-up-heading-safe))
7371 (>= level org-inlinetask-min-level)))
7372 (if (org-at-heading-p)
7373 (org-back-to-heading invisible-ok)
7374 (error "This should not happen")))
7375 (setq empty-line-p (org-previous-line-empty-p))
7376 (match-string 0))
7377 (error "*"))))
7378 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7379 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7380 pos hide-previous previous-pos)
7381 (cond
7382 ((and (org-at-heading-p) (bolp)
7383 (or (bobp)
7384 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7385 ;; insert before the current line
7386 (open-line (if blank 2 1)))
7387 ((and (bolp)
7388 (not org-insert-heading-respect-content)
7389 (or (bobp)
7390 (save-excursion
7391 (backward-char 1) (not (outline-invisible-p)))))
7392 ;; insert right here
7393 nil)
7395 ;; somewhere in the line
7396 (save-excursion
7397 (setq previous-pos (point-at-bol))
7398 (end-of-line)
7399 (setq hide-previous (outline-invisible-p)))
7400 (and org-insert-heading-respect-content (org-show-subtree))
7401 (let ((split
7402 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7403 (save-excursion
7404 (let ((p (point)))
7405 (goto-char (point-at-bol))
7406 (and (looking-at org-complex-heading-regexp)
7407 (match-beginning 4)
7408 (> p (match-beginning 4)))))))
7409 tags pos)
7410 (cond
7411 (org-insert-heading-respect-content
7412 (if (not (equal force-heading '(16)))
7413 (org-end-of-subtree nil t)
7414 (org-up-heading-safe)
7415 (org-end-of-subtree nil t))
7416 (when (featurep 'org-inlinetask)
7417 (while (and (not (eobp))
7418 (looking-at "\\(\\*+\\)[ \t]+")
7419 (>= (length (match-string 1))
7420 org-inlinetask-min-level))
7421 (org-end-of-subtree nil t)))
7422 (or (bolp) (newline))
7423 (or (org-previous-line-empty-p)
7424 (and blank (newline)))
7425 (open-line 1))
7426 ((org-at-heading-p)
7427 (when hide-previous
7428 (show-children)
7429 (org-show-entry))
7430 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7431 (setq tags (and (match-end 2) (match-string 2)))
7432 (and (match-end 1)
7433 (delete-region (match-beginning 1) (match-end 1)))
7434 (setq pos (point-at-bol))
7435 (or split (end-of-line 1))
7436 (delete-horizontal-space)
7437 (if (string-match "\\`\\*+\\'"
7438 (buffer-substring (point-at-bol) (point)))
7439 (insert " "))
7440 (newline (if blank 2 1))
7441 (when tags
7442 (save-excursion
7443 (goto-char pos)
7444 (end-of-line 1)
7445 (insert " " tags)
7446 (org-set-tags nil 'align))))
7448 (or split (end-of-line 1))
7449 (newline (if blank 2 1)))))))
7450 (insert head) (just-one-space)
7451 (setq pos (point))
7452 (end-of-line 1)
7453 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7454 (when (and org-insert-heading-respect-content hide-previous)
7455 (save-excursion
7456 (goto-char previous-pos)
7457 (hide-subtree)))
7458 (run-hooks 'org-insert-heading-hook)))))
7460 (defun org-get-heading (&optional no-tags no-todo)
7461 "Return the heading of the current entry, without the stars.
7462 When NO-TAGS is non-nil, don't include tags.
7463 When NO-TODO is non-nil, don't include TODO keywords."
7464 (save-excursion
7465 (org-back-to-heading t)
7466 (cond
7467 ((and no-tags no-todo)
7468 (looking-at org-complex-heading-regexp)
7469 (match-string 4))
7470 (no-tags
7471 (looking-at (concat org-outline-regexp
7472 "\\(.*?\\)"
7473 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7474 (match-string 1))
7475 (no-todo
7476 (looking-at org-todo-line-regexp)
7477 (match-string 3))
7478 (t (looking-at org-heading-regexp)
7479 (match-string 2)))))
7481 (defvar orgstruct-mode) ; defined below
7483 (defun org-heading-components ()
7484 "Return the components of the current heading.
7485 This is a list with the following elements:
7486 - the level as an integer
7487 - the reduced level, different if `org-odd-levels-only' is set.
7488 - the TODO keyword, or nil
7489 - the priority character, like ?A, or nil if no priority is given
7490 - the headline text itself, or the tags string if no headline text
7491 - the tags string, or nil."
7492 (save-excursion
7493 (org-back-to-heading t)
7494 (if (let (case-fold-search)
7495 (looking-at
7496 (if orgstruct-mode
7497 org-heading-regexp
7498 org-complex-heading-regexp)))
7499 (if orgstruct-mode
7500 (list (length (match-string 1))
7501 (org-reduced-level (length (match-string 1)))
7504 (match-string 2)
7505 nil)
7506 (list (length (match-string 1))
7507 (org-reduced-level (length (match-string 1)))
7508 (org-match-string-no-properties 2)
7509 (and (match-end 3) (aref (match-string 3) 2))
7510 (org-match-string-no-properties 4)
7511 (org-match-string-no-properties 5))))))
7513 (defun org-get-entry ()
7514 "Get the entry text, after heading, entire subtree."
7515 (save-excursion
7516 (org-back-to-heading t)
7517 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7519 (defun org-insert-heading-after-current ()
7520 "Insert a new heading with same level as current, after current subtree."
7521 (interactive)
7522 (org-back-to-heading)
7523 (org-insert-heading)
7524 (org-move-subtree-down)
7525 (end-of-line 1))
7527 (defun org-insert-heading-respect-content (invisible-ok)
7528 "Insert heading with `org-insert-heading-respect-content' set to t."
7529 (interactive "P")
7530 (let ((org-insert-heading-respect-content t))
7531 (org-insert-heading t invisible-ok)))
7533 (defun org-insert-todo-heading-respect-content (&optional force-state)
7534 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7535 (interactive "P")
7536 (let ((org-insert-heading-respect-content t))
7537 (org-insert-todo-heading force-state t)))
7539 (defun org-insert-todo-heading (arg &optional force-heading)
7540 "Insert a new heading with the same level and TODO state as current heading.
7541 If the heading has no TODO state, or if the state is DONE, use the first
7542 state (TODO by default). Also one prefix arg, force first state. With two
7543 prefix args, force inserting at the end of the parent subtree."
7544 (interactive "P")
7545 (when (or force-heading (not (org-insert-item 'checkbox)))
7546 (org-insert-heading (or (and (equal arg '(16)) '(16))
7547 force-heading))
7548 (save-excursion
7549 (org-back-to-heading)
7550 (outline-previous-heading)
7551 (looking-at org-todo-line-regexp))
7552 (let*
7553 ((new-mark-x
7554 (if (or arg
7555 (not (match-beginning 2))
7556 (member (match-string 2) org-done-keywords))
7557 (car org-todo-keywords-1)
7558 (match-string 2)))
7559 (new-mark
7561 (run-hook-with-args-until-success
7562 'org-todo-get-default-hook new-mark-x nil)
7563 new-mark-x)))
7564 (beginning-of-line 1)
7565 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7566 (if org-treat-insert-todo-heading-as-state-change
7567 (org-todo new-mark)
7568 (insert new-mark " "))))
7569 (when org-provide-todo-statistics
7570 (org-update-parent-todo-statistics))))
7572 (defun org-insert-subheading (arg)
7573 "Insert a new subheading and demote it.
7574 Works for outline headings and for plain lists alike."
7575 (interactive "P")
7576 (org-insert-heading arg)
7577 (cond
7578 ((org-at-heading-p) (org-do-demote))
7579 ((org-at-item-p) (org-indent-item))))
7581 (defun org-insert-todo-subheading (arg)
7582 "Insert a new subheading with TODO keyword or checkbox and demote it.
7583 Works for outline headings and for plain lists alike."
7584 (interactive "P")
7585 (org-insert-todo-heading arg)
7586 (cond
7587 ((org-at-heading-p) (org-do-demote))
7588 ((org-at-item-p) (org-indent-item))))
7590 ;;; Promotion and Demotion
7592 (defvar org-after-demote-entry-hook nil
7593 "Hook run after an entry has been demoted.
7594 The cursor will be at the beginning of the entry.
7595 When a subtree is being demoted, the hook will be called for each node.")
7597 (defvar org-after-promote-entry-hook nil
7598 "Hook run after an entry has been promoted.
7599 The cursor will be at the beginning of the entry.
7600 When a subtree is being promoted, the hook will be called for each node.")
7602 (defun org-promote-subtree ()
7603 "Promote the entire subtree.
7604 See also `org-promote'."
7605 (interactive)
7606 (save-excursion
7607 (org-with-limited-levels (org-map-tree 'org-promote)))
7608 (org-fix-position-after-promote))
7610 (defun org-demote-subtree ()
7611 "Demote the entire subtree. See `org-demote'.
7612 See also `org-promote'."
7613 (interactive)
7614 (save-excursion
7615 (org-with-limited-levels (org-map-tree 'org-demote)))
7616 (org-fix-position-after-promote))
7619 (defun org-do-promote ()
7620 "Promote the current heading higher up the tree.
7621 If the region is active in `transient-mark-mode', promote all headings
7622 in the region."
7623 (interactive)
7624 (save-excursion
7625 (if (org-region-active-p)
7626 (org-map-region 'org-promote (region-beginning) (region-end))
7627 (org-promote)))
7628 (org-fix-position-after-promote))
7630 (defun org-do-demote ()
7631 "Demote the current heading lower down the tree.
7632 If the region is active in `transient-mark-mode', demote all headings
7633 in the region."
7634 (interactive)
7635 (save-excursion
7636 (if (org-region-active-p)
7637 (org-map-region 'org-demote (region-beginning) (region-end))
7638 (org-demote)))
7639 (org-fix-position-after-promote))
7641 (defun org-fix-position-after-promote ()
7642 "Make sure that after pro/demotion cursor position is right."
7643 (let ((pos (point)))
7644 (when (save-excursion
7645 (beginning-of-line 1)
7646 (looking-at org-todo-line-regexp)
7647 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7648 (cond ((eobp) (insert " "))
7649 ((eolp) (insert " "))
7650 ((equal (char-after) ?\ ) (forward-char 1))))))
7652 (defun org-current-level ()
7653 "Return the level of the current entry, or nil if before the first headline.
7654 The level is the number of stars at the beginning of the headline."
7655 (save-excursion
7656 (org-with-limited-levels
7657 (if (ignore-errors (org-back-to-heading t))
7658 (funcall outline-level)))))
7660 (defun org-get-previous-line-level ()
7661 "Return the outline depth of the last headline before the current line.
7662 Returns 0 for the first headline in the buffer, and nil if before the
7663 first headline."
7664 (let ((current-level (org-current-level))
7665 (prev-level (when (> (line-number-at-pos) 1)
7666 (save-excursion
7667 (beginning-of-line 0)
7668 (org-current-level)))))
7669 (cond ((null current-level) nil) ; Before first headline
7670 ((null prev-level) 0) ; At first headline
7671 (prev-level))))
7673 (defun org-reduced-level (l)
7674 "Compute the effective level of a heading.
7675 This takes into account the setting of `org-odd-levels-only'."
7676 (cond
7677 ((zerop l) 0)
7678 (org-odd-levels-only (1+ (floor (/ l 2))))
7679 (t l)))
7681 (defun org-level-increment ()
7682 "Return the number of stars that will be added or removed at a
7683 time to headlines when structure editing, based on the value of
7684 `org-odd-levels-only'."
7685 (if org-odd-levels-only 2 1))
7687 (defun org-get-valid-level (level &optional change)
7688 "Rectify a level change under the influence of `org-odd-levels-only'
7689 LEVEL is a current level, CHANGE is by how much the level should be
7690 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7691 even level numbers will become the next higher odd number."
7692 (if org-odd-levels-only
7693 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7694 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7695 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7696 (max 1 (+ level (or change 0)))))
7698 (if (boundp 'define-obsolete-function-alias)
7699 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7700 (define-obsolete-function-alias 'org-get-legal-level
7701 'org-get-valid-level)
7702 (define-obsolete-function-alias 'org-get-legal-level
7703 'org-get-valid-level "23.1")))
7705 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7706 ;; ̀org-with-limited-levels'
7707 (defun org-promote ()
7708 "Promote the current heading higher up the tree.
7709 If the region is active in `transient-mark-mode', promote all headings
7710 in the region."
7711 (org-back-to-heading t)
7712 (let* ((level (save-match-data (funcall outline-level)))
7713 (after-change-functions (remove 'flyspell-after-change-function
7714 after-change-functions))
7715 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7716 (diff (abs (- level (length up-head) -1))))
7717 (cond ((and (= level 1) org-called-with-limited-levels
7718 org-allow-promoting-top-level-subtree)
7719 (replace-match "# " nil t))
7720 ((= level 1)
7721 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7722 (t (replace-match up-head nil t)))
7723 ;; Fixup tag positioning
7724 (unless (= level 1)
7725 (and org-auto-align-tags (org-set-tags nil t))
7726 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7727 (run-hooks 'org-after-promote-entry-hook)))
7729 (defun org-demote ()
7730 "Demote the current heading lower down the tree.
7731 If the region is active in `transient-mark-mode', demote all headings
7732 in the region."
7733 (org-back-to-heading t)
7734 (let* ((level (save-match-data (funcall outline-level)))
7735 (after-change-functions (remove 'flyspell-after-change-function
7736 after-change-functions))
7737 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7738 (diff (abs (- level (length down-head) -1))))
7739 (replace-match down-head nil t)
7740 ;; Fixup tag positioning
7741 (and org-auto-align-tags (org-set-tags nil t))
7742 (if org-adapt-indentation (org-fixup-indentation diff))
7743 (run-hooks 'org-after-demote-entry-hook)))
7745 (defun org-cycle-level ()
7746 "Cycle the level of an empty headline through possible states.
7747 This goes first to child, then to parent, level, then up the hierarchy.
7748 After top level, it switches back to sibling level."
7749 (interactive)
7750 (let ((org-adapt-indentation nil))
7751 (when (org-point-at-end-of-empty-headline)
7752 (setq this-command 'org-cycle-level) ; Only needed for caching
7753 (let ((cur-level (org-current-level))
7754 (prev-level (org-get-previous-line-level)))
7755 (cond
7756 ;; If first headline in file, promote to top-level.
7757 ((= prev-level 0)
7758 (loop repeat (/ (- cur-level 1) (org-level-increment))
7759 do (org-do-promote)))
7760 ;; If same level as prev, demote one.
7761 ((= prev-level cur-level)
7762 (org-do-demote))
7763 ;; If parent is top-level, promote to top level if not already.
7764 ((= prev-level 1)
7765 (loop repeat (/ (- cur-level 1) (org-level-increment))
7766 do (org-do-promote)))
7767 ;; If top-level, return to prev-level.
7768 ((= cur-level 1)
7769 (loop repeat (/ (- prev-level 1) (org-level-increment))
7770 do (org-do-demote)))
7771 ;; If less than prev-level, promote one.
7772 ((< cur-level prev-level)
7773 (org-do-promote))
7774 ;; If deeper than prev-level, promote until higher than
7775 ;; prev-level.
7776 ((> cur-level prev-level)
7777 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7778 do (org-do-promote))))
7779 t))))
7781 (defun org-map-tree (fun)
7782 "Call FUN for every heading underneath the current one."
7783 (org-back-to-heading)
7784 (let ((level (funcall outline-level)))
7785 (save-excursion
7786 (funcall fun)
7787 (while (and (progn
7788 (outline-next-heading)
7789 (> (funcall outline-level) level))
7790 (not (eobp)))
7791 (funcall fun)))))
7793 (defun org-map-region (fun beg end)
7794 "Call FUN for every heading between BEG and END."
7795 (let ((org-ignore-region t))
7796 (save-excursion
7797 (setq end (copy-marker end))
7798 (goto-char beg)
7799 (if (and (re-search-forward org-outline-regexp-bol nil t)
7800 (< (point) end))
7801 (funcall fun))
7802 (while (and (progn
7803 (outline-next-heading)
7804 (< (point) end))
7805 (not (eobp)))
7806 (funcall fun)))))
7808 (defvar org-property-end-re) ; silence byte-compiler
7809 (defun org-fixup-indentation (diff)
7810 "Change the indentation in the current entry by DIFF.
7811 However, if any line in the current entry has no indentation, or if it
7812 would end up with no indentation after the change, nothing at all is done."
7813 (save-excursion
7814 (let ((end (save-excursion (outline-next-heading)
7815 (point-marker)))
7816 (prohibit (if (> diff 0)
7817 "^\\S-"
7818 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7819 col)
7820 (unless (save-excursion (end-of-line 1)
7821 (re-search-forward prohibit end t))
7822 (while (and (< (point) end)
7823 (re-search-forward "^[ \t]+" end t))
7824 (goto-char (match-end 0))
7825 (setq col (current-column))
7826 (if (< diff 0) (replace-match ""))
7827 (org-indent-to-column (+ diff col))))
7828 (move-marker end nil))))
7830 (defun org-convert-to-odd-levels ()
7831 "Convert an org-mode file with all levels allowed to one with odd levels.
7832 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7833 level 5 etc."
7834 (interactive)
7835 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7836 (let ((outline-level 'org-outline-level)
7837 (org-odd-levels-only nil) n)
7838 (save-excursion
7839 (goto-char (point-min))
7840 (while (re-search-forward "^\\*\\*+ " nil t)
7841 (setq n (- (length (match-string 0)) 2))
7842 (while (>= (setq n (1- n)) 0)
7843 (org-demote))
7844 (end-of-line 1))))))
7846 (defun org-convert-to-oddeven-levels ()
7847 "Convert an org-mode file with only odd levels to one with odd/even levels.
7848 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7849 file contains a section with an even level, conversion would
7850 destroy the structure of the file. An error is signaled in this
7851 case."
7852 (interactive)
7853 (goto-char (point-min))
7854 ;; First check if there are no even levels
7855 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7856 (org-show-context t)
7857 (error "Not all levels are odd in this file. Conversion not possible"))
7858 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7859 (let ((outline-regexp org-outline-regexp)
7860 (outline-level 'org-outline-level)
7861 (org-odd-levels-only nil) n)
7862 (save-excursion
7863 (goto-char (point-min))
7864 (while (re-search-forward "^\\*\\*+ " nil t)
7865 (setq n (/ (1- (length (match-string 0))) 2))
7866 (while (>= (setq n (1- n)) 0)
7867 (org-promote))
7868 (end-of-line 1))))))
7870 (defun org-tr-level (n)
7871 "Make N odd if required."
7872 (if org-odd-levels-only (1+ (/ n 2)) n))
7874 ;;; Vertical tree motion, cutting and pasting of subtrees
7876 (defun org-move-subtree-up (&optional arg)
7877 "Move the current subtree up past ARG headlines of the same level."
7878 (interactive "p")
7879 (org-move-subtree-down (- (prefix-numeric-value arg))))
7881 (defun org-move-subtree-down (&optional arg)
7882 "Move the current subtree down past ARG headlines of the same level."
7883 (interactive "p")
7884 (setq arg (prefix-numeric-value arg))
7885 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7886 'org-get-last-sibling))
7887 (ins-point (make-marker))
7888 (cnt (abs arg))
7889 (col (current-column))
7890 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7891 ;; Select the tree
7892 (org-back-to-heading)
7893 (setq beg0 (point))
7894 (save-excursion
7895 (setq ne-beg (org-back-over-empty-lines))
7896 (setq beg (point)))
7897 (save-match-data
7898 (save-excursion (outline-end-of-heading)
7899 (setq folded (outline-invisible-p)))
7900 (outline-end-of-subtree))
7901 (outline-next-heading)
7902 (setq ne-end (org-back-over-empty-lines))
7903 (setq end (point))
7904 (goto-char beg0)
7905 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7906 ;; include less whitespace
7907 (save-excursion
7908 (goto-char beg)
7909 (forward-line (- ne-beg ne-end))
7910 (setq beg (point))))
7911 ;; Find insertion point, with error handling
7912 (while (> cnt 0)
7913 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7914 (progn (goto-char beg0)
7915 (error "Cannot move past superior level or buffer limit")))
7916 (setq cnt (1- cnt)))
7917 (if (> arg 0)
7918 ;; Moving forward - still need to move over subtree
7919 (progn (org-end-of-subtree t t)
7920 (save-excursion
7921 (org-back-over-empty-lines)
7922 (or (bolp) (newline)))))
7923 (setq ne-ins (org-back-over-empty-lines))
7924 (move-marker ins-point (point))
7925 (setq txt (buffer-substring beg end))
7926 (org-save-markers-in-region beg end)
7927 (delete-region beg end)
7928 (org-remove-empty-overlays-at beg)
7929 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7930 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7931 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7932 (let ((bbb (point)))
7933 (insert-before-markers txt)
7934 (org-reinstall-markers-in-region bbb)
7935 (move-marker ins-point bbb))
7936 (or (bolp) (insert "\n"))
7937 (setq ins-end (point))
7938 (goto-char ins-point)
7939 (org-skip-whitespace)
7940 (when (and (< arg 0)
7941 (org-first-sibling-p)
7942 (> ne-ins ne-beg))
7943 ;; Move whitespace back to beginning
7944 (save-excursion
7945 (goto-char ins-end)
7946 (let ((kill-whole-line t))
7947 (kill-line (- ne-ins ne-beg)) (point)))
7948 (insert (make-string (- ne-ins ne-beg) ?\n)))
7949 (move-marker ins-point nil)
7950 (if folded
7951 (hide-subtree)
7952 (org-show-entry)
7953 (show-children)
7954 (org-cycle-hide-drawers 'children))
7955 (org-clean-visibility-after-subtree-move)
7956 ;; move back to the initial column we were at
7957 (move-to-column col)))
7959 (defvar org-subtree-clip ""
7960 "Clipboard for cut and paste of subtrees.
7961 This is actually only a copy of the kill, because we use the normal kill
7962 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7964 (defvar org-subtree-clip-folded nil
7965 "Was the last copied subtree folded?
7966 This is used to fold the tree back after pasting.")
7968 (defun org-cut-subtree (&optional n)
7969 "Cut the current subtree into the clipboard.
7970 With prefix arg N, cut this many sequential subtrees.
7971 This is a short-hand for marking the subtree and then cutting it."
7972 (interactive "p")
7973 (org-copy-subtree n 'cut))
7975 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7976 "Cut the current subtree into the clipboard.
7977 With prefix arg N, cut this many sequential subtrees.
7978 This is a short-hand for marking the subtree and then copying it.
7979 If CUT is non-nil, actually cut the subtree.
7980 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7981 of some markers in the region, even if CUT is non-nil. This is
7982 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7983 (interactive "p")
7984 (let (beg end folded (beg0 (point)))
7985 (if (org-called-interactively-p 'any)
7986 (org-back-to-heading nil) ; take what looks like a subtree
7987 (org-back-to-heading t)) ; take what is really there
7988 (setq beg (point))
7989 (skip-chars-forward " \t\r\n")
7990 (save-match-data
7991 (if nosubtrees
7992 (outline-next-heading)
7993 (save-excursion (outline-end-of-heading)
7994 (setq folded (outline-invisible-p)))
7995 (condition-case nil
7996 (org-forward-heading-same-level (1- n) t)
7997 (error nil))
7998 (org-end-of-subtree t t)))
7999 (setq end (point))
8000 (goto-char beg0)
8001 (when (> end beg)
8002 (setq org-subtree-clip-folded folded)
8003 (when (or cut force-store-markers)
8004 (org-save-markers-in-region beg end))
8005 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8006 (setq org-subtree-clip (current-kill 0))
8007 (message "%s: Subtree(s) with %d characters"
8008 (if cut "Cut" "Copied")
8009 (length org-subtree-clip)))))
8011 (defun org-paste-subtree (&optional level tree for-yank)
8012 "Paste the clipboard as a subtree, with modification of headline level.
8013 The entire subtree is promoted or demoted in order to match a new headline
8014 level.
8016 If the cursor is at the beginning of a headline, the same level as
8017 that headline is used to paste the tree.
8019 If not, the new level is derived from the *visible* headings
8020 before and after the insertion point, and taken to be the inferior headline
8021 level of the two. So if the previous visible heading is level 3 and the
8022 next is level 4 (or vice versa), level 4 will be used for insertion.
8023 This makes sure that the subtree remains an independent subtree and does
8024 not swallow low level entries.
8026 You can also force a different level, either by using a numeric prefix
8027 argument, or by inserting the heading marker by hand. For example, if the
8028 cursor is after \"*****\", then the tree will be shifted to level 5.
8030 If optional TREE is given, use this text instead of the kill ring.
8032 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8033 move back over whitespace before inserting, and move point to the end of
8034 the inserted text when done."
8035 (interactive "P")
8036 (setq tree (or tree (and kill-ring (current-kill 0))))
8037 (unless (org-kill-is-subtree-p tree)
8038 (error "%s"
8039 (substitute-command-keys
8040 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8041 (org-with-limited-levels
8042 (let* ((visp (not (outline-invisible-p)))
8043 (txt tree)
8044 (^re_ "\\(\\*+\\)[ \t]*")
8045 (old-level (if (string-match org-outline-regexp-bol txt)
8046 (- (match-end 0) (match-beginning 0) 1)
8047 -1))
8048 (force-level (cond (level (prefix-numeric-value level))
8049 ((and (looking-at "[ \t]*$")
8050 (string-match
8051 "^\\*+$" (buffer-substring
8052 (point-at-bol) (point))))
8053 (- (match-end 1) (match-beginning 1)))
8054 ((and (bolp)
8055 (looking-at org-outline-regexp))
8056 (- (match-end 0) (point) 1))))
8057 (previous-level (save-excursion
8058 (condition-case nil
8059 (progn
8060 (outline-previous-visible-heading 1)
8061 (if (looking-at ^re_)
8062 (- (match-end 0) (match-beginning 0) 1)
8064 (error 1))))
8065 (next-level (save-excursion
8066 (condition-case nil
8067 (progn
8068 (or (looking-at org-outline-regexp)
8069 (outline-next-visible-heading 1))
8070 (if (looking-at ^re_)
8071 (- (match-end 0) (match-beginning 0) 1)
8073 (error 1))))
8074 (new-level (or force-level (max previous-level next-level)))
8075 (shift (if (or (= old-level -1)
8076 (= new-level -1)
8077 (= old-level new-level))
8079 (- new-level old-level)))
8080 (delta (if (> shift 0) -1 1))
8081 (func (if (> shift 0) 'org-demote 'org-promote))
8082 (org-odd-levels-only nil)
8083 beg end newend)
8084 ;; Remove the forced level indicator
8085 (if force-level
8086 (delete-region (point-at-bol) (point)))
8087 ;; Paste
8088 (beginning-of-line (if (bolp) 1 2))
8089 (setq beg (point))
8090 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8091 (insert-before-markers txt)
8092 (unless (string-match "\n\\'" txt) (insert "\n"))
8093 (setq newend (point))
8094 (org-reinstall-markers-in-region beg)
8095 (setq end (point))
8096 (goto-char beg)
8097 (skip-chars-forward " \t\n\r")
8098 (setq beg (point))
8099 (if (and (outline-invisible-p) visp)
8100 (save-excursion (outline-show-heading)))
8101 ;; Shift if necessary
8102 (unless (= shift 0)
8103 (save-restriction
8104 (narrow-to-region beg end)
8105 (while (not (= shift 0))
8106 (org-map-region func (point-min) (point-max))
8107 (setq shift (+ delta shift)))
8108 (goto-char (point-min))
8109 (setq newend (point-max))))
8110 (when (or (org-called-interactively-p 'interactive) for-yank)
8111 (message "Clipboard pasted as level %d subtree" new-level))
8112 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8113 kill-ring
8114 (eq org-subtree-clip (current-kill 0))
8115 org-subtree-clip-folded)
8116 ;; The tree was folded before it was killed/copied
8117 (hide-subtree))
8118 (and for-yank (goto-char newend)))))
8120 (defun org-kill-is-subtree-p (&optional txt)
8121 "Check if the current kill is an outline subtree, or a set of trees.
8122 Returns nil if kill does not start with a headline, or if the first
8123 headline level is not the largest headline level in the tree.
8124 So this will actually accept several entries of equal levels as well,
8125 which is OK for `org-paste-subtree'.
8126 If optional TXT is given, check this string instead of the current kill."
8127 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8128 (re (org-get-limited-outline-regexp))
8129 (^re (concat "^" re))
8130 (start-level (and kill
8131 (string-match
8132 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8133 kill)
8134 (- (match-end 2) (match-beginning 2) 1)))
8135 (start (1+ (or (match-beginning 2) -1))))
8136 (if (not start-level)
8137 (progn
8138 nil) ;; does not even start with a heading
8139 (catch 'exit
8140 (while (setq start (string-match ^re kill (1+ start)))
8141 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8142 (throw 'exit nil)))
8143 t))))
8145 (defvar org-markers-to-move nil
8146 "Markers that should be moved with a cut-and-paste operation.
8147 Those markers are stored together with their positions relative to
8148 the start of the region.")
8150 (defun org-save-markers-in-region (beg end)
8151 "Check markers in region.
8152 If these markers are between BEG and END, record their position relative
8153 to BEG, so that after moving the block of text, we can put the markers back
8154 into place.
8155 This function gets called just before an entry or tree gets cut from the
8156 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8157 called immediately, to move the markers with the entries."
8158 (setq org-markers-to-move nil)
8159 (when (featurep 'org-clock)
8160 (org-clock-save-markers-for-cut-and-paste beg end))
8161 (when (featurep 'org-agenda)
8162 (org-agenda-save-markers-for-cut-and-paste beg end)))
8164 (defun org-check-and-save-marker (marker beg end)
8165 "Check if MARKER is between BEG and END.
8166 If yes, remember the marker and the distance to BEG."
8167 (when (and (marker-buffer marker)
8168 (equal (marker-buffer marker) (current-buffer)))
8169 (if (and (>= marker beg) (< marker end))
8170 (push (cons marker (- marker beg)) org-markers-to-move))))
8172 (defun org-reinstall-markers-in-region (beg)
8173 "Move all remembered markers to their position relative to BEG."
8174 (mapc (lambda (x)
8175 (move-marker (car x) (+ beg (cdr x))))
8176 org-markers-to-move)
8177 (setq org-markers-to-move nil))
8179 (defun org-narrow-to-subtree ()
8180 "Narrow buffer to the current subtree."
8181 (interactive)
8182 (save-excursion
8183 (save-match-data
8184 (org-with-limited-levels
8185 (narrow-to-region
8186 (progn (org-back-to-heading t) (point))
8187 (progn (org-end-of-subtree t t)
8188 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8189 (point)))))))
8191 (defun org-narrow-to-block ()
8192 "Narrow buffer to the current block."
8193 (interactive)
8194 (let* ((case-fold-search t)
8195 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8196 "^[ \t]*#\\+end_.*")))
8197 (if blockp
8198 (narrow-to-region (car blockp) (cdr blockp))
8199 (error "Not in a block"))))
8201 (eval-when-compile
8202 (defvar org-property-drawer-re))
8204 (defvar org-property-start-re) ;; defined below
8205 (defun org-clone-subtree-with-time-shift (n &optional shift)
8206 "Clone the task (subtree) at point N times.
8207 The clones will be inserted as siblings.
8209 In interactive use, the user will be prompted for the number of
8210 clones to be produced, and for a time SHIFT, which may be a
8211 repeater as used in time stamps, for example `+3d'.
8213 When a valid repeater is given and the entry contains any time
8214 stamps, the clones will become a sequence in time, with time
8215 stamps in the subtree shifted for each clone produced. If SHIFT
8216 is nil or the empty string, time stamps will be left alone. The
8217 ID property of the original subtree is removed.
8219 If the original subtree did contain time stamps with a repeater,
8220 the following will happen:
8221 - the repeater will be removed in each clone
8222 - an additional clone will be produced, with the current, unshifted
8223 date(s) in the entry.
8224 - the original entry will be placed *after* all the clones, with
8225 repeater intact.
8226 - the start days in the repeater in the original entry will be shifted
8227 to past the last clone.
8228 In this way you can spell out a number of instances of a repeating task,
8229 and still retain the repeater to cover future instances of the task."
8230 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8231 (let (beg end template task idprop
8232 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8233 (drawer-re org-drawer-regexp))
8234 (if (not (and (integerp n) (> n 0)))
8235 (error "Invalid number of replications %s" n))
8236 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8237 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8238 shift)))
8239 (error "Invalid shift specification %s" shift))
8240 (when doshift
8241 (setq shift-n (string-to-number (match-string 1 shift))
8242 shift-what (cdr (assoc (match-string 2 shift)
8243 '(("d" . day) ("w" . week)
8244 ("m" . month) ("y" . year))))))
8245 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8246 (setq nmin 1 nmax n)
8247 (org-back-to-heading t)
8248 (setq beg (point))
8249 (setq idprop (org-entry-get nil "ID"))
8250 (org-end-of-subtree t t)
8251 (or (bolp) (insert "\n"))
8252 (setq end (point))
8253 (setq template (buffer-substring beg end))
8254 (when (and doshift
8255 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8256 (delete-region beg end)
8257 (setq end beg)
8258 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8259 (goto-char end)
8260 (loop for n from nmin to nmax do
8261 ;; prepare clone
8262 (with-temp-buffer
8263 (insert template)
8264 (org-mode)
8265 (goto-char (point-min))
8266 (org-show-subtree)
8267 (and idprop (if org-clone-delete-id
8268 (org-entry-delete nil "ID")
8269 (org-id-get-create t)))
8270 (unless (= n 0)
8271 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8272 (kill-whole-line))
8273 (goto-char (point-min))
8274 (while (re-search-forward drawer-re nil t)
8275 (mapc (lambda (d)
8276 (org-remove-empty-drawer-at d (point))) org-drawers)))
8277 (goto-char (point-min))
8278 (when doshift
8279 (while (re-search-forward org-ts-regexp-both nil t)
8280 (org-timestamp-change (* n shift-n) shift-what))
8281 (unless (= n n-no-remove)
8282 (goto-char (point-min))
8283 (while (re-search-forward org-ts-regexp nil t)
8284 (save-excursion
8285 (goto-char (match-beginning 0))
8286 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8287 (delete-region (match-beginning 1) (match-end 1)))))))
8288 (setq task (buffer-string)))
8289 (insert task))
8290 (goto-char beg)))
8292 ;;; Outline Sorting
8294 (defun org-sort (with-case)
8295 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8296 Optional argument WITH-CASE means sort case-sensitively."
8297 (interactive "P")
8298 (cond
8299 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8300 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8302 (org-call-with-arg 'org-sort-entries with-case))))
8304 (defun org-sort-remove-invisible (s)
8305 (remove-text-properties 0 (length s) org-rm-props s)
8306 (while (string-match org-bracket-link-regexp s)
8307 (setq s (replace-match (if (match-end 2)
8308 (match-string 3 s)
8309 (match-string 1 s)) t t s)))
8312 (defvar org-priority-regexp) ; defined later in the file
8314 (defvar org-after-sorting-entries-or-items-hook nil
8315 "Hook that is run after a bunch of entries or items have been sorted.
8316 When children are sorted, the cursor is in the parent line when this
8317 hook gets called. When a region or a plain list is sorted, the cursor
8318 will be in the first entry of the sorted region/list.")
8320 (defun org-sort-entries
8321 (&optional with-case sorting-type getkey-func compare-func property)
8322 "Sort entries on a certain level of an outline tree.
8323 If there is an active region, the entries in the region are sorted.
8324 Else, if the cursor is before the first entry, sort the top-level items.
8325 Else, the children of the entry at point are sorted.
8327 Sorting can be alphabetically, numerically, by date/time as given by
8328 a time stamp, by a property or by priority.
8330 The command prompts for the sorting type unless it has been given to the
8331 function through the SORTING-TYPE argument, which needs to be a character,
8332 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8333 precise meaning of each character:
8335 n Numerically, by converting the beginning of the entry/item to a number.
8336 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8337 o By order of TODO keywords.
8338 t By date/time, either the first active time stamp in the entry, or, if
8339 none exist, by the first inactive one.
8340 s By the scheduled date/time.
8341 d By deadline date/time.
8342 c By creation time, which is assumed to be the first inactive time stamp
8343 at the beginning of a line.
8344 p By priority according to the cookie.
8345 r By the value of a property.
8347 Capital letters will reverse the sort order.
8349 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8350 called with point at the beginning of the record. It must return either
8351 a string or a number that should serve as the sorting key for that record.
8353 Comparing entries ignores case by default. However, with an optional argument
8354 WITH-CASE, the sorting considers case as well."
8355 (interactive "P")
8356 (let ((case-func (if with-case 'identity 'downcase))
8357 (cmstr
8358 ;; The clock marker is lost when using `sort-subr', let's
8359 ;; store the clocking string.
8360 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8361 (save-excursion
8362 (goto-char org-clock-marker)
8363 (looking-back "^.*") (match-string-no-properties 0))))
8364 start beg end stars re re2
8365 txt what tmp)
8366 ;; Find beginning and end of region to sort
8367 (cond
8368 ((org-region-active-p)
8369 ;; we will sort the region
8370 (setq end (region-end)
8371 what "region")
8372 (goto-char (region-beginning))
8373 (if (not (org-at-heading-p)) (outline-next-heading))
8374 (setq start (point)))
8375 ((or (org-at-heading-p)
8376 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8377 ;; we will sort the children of the current headline
8378 (org-back-to-heading)
8379 (setq start (point)
8380 end (progn (org-end-of-subtree t t)
8381 (or (bolp) (insert "\n"))
8382 (org-back-over-empty-lines)
8383 (point))
8384 what "children")
8385 (goto-char start)
8386 (show-subtree)
8387 (outline-next-heading))
8389 ;; we will sort the top-level entries in this file
8390 (goto-char (point-min))
8391 (or (org-at-heading-p) (outline-next-heading))
8392 (setq start (point))
8393 (goto-char (point-max))
8394 (beginning-of-line 1)
8395 (when (looking-at ".*?\\S-")
8396 ;; File ends in a non-white line
8397 (end-of-line 1)
8398 (insert "\n"))
8399 (setq end (point-max))
8400 (setq what "top-level")
8401 (goto-char start)
8402 (show-all)))
8404 (setq beg (point))
8405 (if (>= beg end) (error "Nothing to sort"))
8407 (looking-at "\\(\\*+\\)")
8408 (setq stars (match-string 1)
8409 re (concat "^" (regexp-quote stars) " +")
8410 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8411 txt (buffer-substring beg end))
8412 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8413 (if (and (not (equal stars "*")) (string-match re2 txt))
8414 (error "Region to sort contains a level above the first entry"))
8416 (unless sorting-type
8417 (message
8418 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8419 [t]ime [s]cheduled [d]eadline [c]reated
8420 A/N/P/R/O/F/T/S/D/C means reversed:"
8421 what)
8422 (setq sorting-type (read-char-exclusive))
8424 (unless getkey-func
8425 (and (= (downcase sorting-type) ?f)
8426 (setq getkey-func
8427 (org-icompleting-read "Sort using function: "
8428 obarray 'fboundp t nil nil))
8429 (setq getkey-func (intern getkey-func))))
8431 (and (= (downcase sorting-type) ?r)
8432 (not property)
8433 (setq property
8434 (org-icompleting-read "Property: "
8435 (mapcar 'list (org-buffer-property-keys t))
8436 nil t))))
8438 (message "Sorting entries...")
8440 (save-restriction
8441 (narrow-to-region start end)
8442 (let ((dcst (downcase sorting-type))
8443 (case-fold-search nil)
8444 (now (current-time)))
8445 (sort-subr
8446 (/= dcst sorting-type)
8447 ;; This function moves to the beginning character of the "record" to
8448 ;; be sorted.
8449 (lambda nil
8450 (if (re-search-forward re nil t)
8451 (goto-char (match-beginning 0))
8452 (goto-char (point-max))))
8453 ;; This function moves to the last character of the "record" being
8454 ;; sorted.
8455 (lambda nil
8456 (save-match-data
8457 (condition-case nil
8458 (outline-forward-same-level 1)
8459 (error
8460 (goto-char (point-max))))))
8461 ;; This function returns the value that gets sorted against.
8462 (lambda nil
8463 (cond
8464 ((= dcst ?n)
8465 (if (looking-at org-complex-heading-regexp)
8466 (string-to-number (match-string 4))
8467 nil))
8468 ((= dcst ?a)
8469 (if (looking-at org-complex-heading-regexp)
8470 (funcall case-func (match-string 4))
8471 nil))
8472 ((= dcst ?t)
8473 (let ((end (save-excursion (outline-next-heading) (point))))
8474 (if (or (re-search-forward org-ts-regexp end t)
8475 (re-search-forward org-ts-regexp-both end t))
8476 (org-time-string-to-seconds (match-string 0))
8477 (org-float-time now))))
8478 ((= dcst ?c)
8479 (let ((end (save-excursion (outline-next-heading) (point))))
8480 (if (re-search-forward
8481 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8482 end t)
8483 (org-time-string-to-seconds (match-string 0))
8484 (org-float-time now))))
8485 ((= dcst ?s)
8486 (let ((end (save-excursion (outline-next-heading) (point))))
8487 (if (re-search-forward org-scheduled-time-regexp end t)
8488 (org-time-string-to-seconds (match-string 1))
8489 (org-float-time now))))
8490 ((= dcst ?d)
8491 (let ((end (save-excursion (outline-next-heading) (point))))
8492 (if (re-search-forward org-deadline-time-regexp end t)
8493 (org-time-string-to-seconds (match-string 1))
8494 (org-float-time now))))
8495 ((= dcst ?p)
8496 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8497 (string-to-char (match-string 2))
8498 org-default-priority))
8499 ((= dcst ?r)
8500 (or (org-entry-get nil property) ""))
8501 ((= dcst ?o)
8502 (if (looking-at org-complex-heading-regexp)
8503 (- 9999 (length (member (match-string 2)
8504 org-todo-keywords-1)))))
8505 ((= dcst ?f)
8506 (if getkey-func
8507 (progn
8508 (setq tmp (funcall getkey-func))
8509 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8510 tmp)
8511 (error "Invalid key function `%s'" getkey-func)))
8512 (t (error "Invalid sorting type `%c'" sorting-type))))
8514 (cond
8515 ((= dcst ?a) 'string<)
8516 ((= dcst ?f) compare-func)
8517 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8518 (run-hooks 'org-after-sorting-entries-or-items-hook)
8519 ;; Reset the clock marker if needed
8520 (when cmstr
8521 (save-excursion
8522 (goto-char start)
8523 (search-forward cmstr nil t)
8524 (move-marker org-clock-marker (point))))
8525 (message "Sorting entries...done")))
8527 (defun org-do-sort (table what &optional with-case sorting-type)
8528 "Sort TABLE of WHAT according to SORTING-TYPE.
8529 The user will be prompted for the SORTING-TYPE if the call to this
8530 function does not specify it. WHAT is only for the prompt, to indicate
8531 what is being sorted. The sorting key will be extracted from
8532 the car of the elements of the table.
8533 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8534 (unless sorting-type
8535 (message
8536 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8537 what)
8538 (setq sorting-type (read-char-exclusive)))
8539 (let ((dcst (downcase sorting-type))
8540 extractfun comparefun)
8541 ;; Define the appropriate functions
8542 (cond
8543 ((= dcst ?n)
8544 (setq extractfun 'string-to-number
8545 comparefun (if (= dcst sorting-type) '< '>)))
8546 ((= dcst ?a)
8547 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8548 (lambda(x) (downcase (org-sort-remove-invisible x))))
8549 comparefun (if (= dcst sorting-type)
8550 'string<
8551 (lambda (a b) (and (not (string< a b))
8552 (not (string= a b)))))))
8553 ((= dcst ?t)
8554 (setq extractfun
8555 (lambda (x)
8556 (if (or (string-match org-ts-regexp x)
8557 (string-match org-ts-regexp-both x))
8558 (org-float-time
8559 (org-time-string-to-time (match-string 0 x)))
8561 comparefun (if (= dcst sorting-type) '< '>)))
8562 (t (error "Invalid sorting type `%c'" sorting-type)))
8564 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8565 table)
8566 (lambda (a b) (funcall comparefun (car a) (car b))))))
8569 ;;; The orgstruct minor mode
8571 ;; Define a minor mode which can be used in other modes in order to
8572 ;; integrate the org-mode structure editing commands.
8574 ;; This is really a hack, because the org-mode structure commands use
8575 ;; keys which normally belong to the major mode. Here is how it
8576 ;; works: The minor mode defines all the keys necessary to operate the
8577 ;; structure commands, but wraps the commands into a function which
8578 ;; tests if the cursor is currently at a headline or a plain list
8579 ;; item. If that is the case, the structure command is used,
8580 ;; temporarily setting many Org-mode variables like regular
8581 ;; expressions for filling etc. However, when any of those keys is
8582 ;; used at a different location, function uses `key-binding' to look
8583 ;; up if the key has an associated command in another currently active
8584 ;; keymap (minor modes, major mode, global), and executes that
8585 ;; command. There might be problems if any of the keys is otherwise
8586 ;; used as a prefix key.
8588 (defcustom orgstruct-heading-prefix-regexp ""
8589 "Regexp that matches the custom prefix of Org headlines in
8590 orgstruct(++)-mode."
8591 :group 'org
8592 :type 'string)
8593 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8595 (defcustom orgstruct-setup-hook nil
8596 "Hook run after orgstruct-mode-map is filled."
8597 :group 'org
8598 :type 'hook)
8600 (defvar orgstruct-initialized nil)
8602 (defvar org-local-vars nil
8603 "List of local variables, for use by `orgstruct-mode'.")
8605 ;;;###autoload
8606 (define-minor-mode orgstruct-mode
8607 "Toggle the minor mode `orgstruct-mode'.
8608 This mode is for using Org-mode structure commands in other
8609 modes. The following keys behave as if Org-mode were active, if
8610 the cursor is on a headline, or on a plain list item (both as
8611 defined by Org-mode)."
8612 nil " OrgStruct" (make-sparse-keymap)
8613 (when orgstruct-mode
8614 (org-load-modules-maybe)
8615 (unless orgstruct-initialized
8616 (orgstruct-setup)
8617 (setq orgstruct-initialized t))))
8619 ;;;###autoload
8620 (defun turn-on-orgstruct ()
8621 "Unconditionally turn on `orgstruct-mode'."
8622 (orgstruct-mode 1))
8624 (defvar org-fb-vars nil)
8625 (make-variable-buffer-local 'org-fb-vars)
8626 (defun orgstruct++-mode (&optional arg)
8627 "Toggle `orgstruct-mode', the enhanced version of it.
8628 In addition to setting orgstruct-mode, this also exports all
8629 indentation and autofilling variables from org-mode into the
8630 buffer. It will also recognize item context in multiline items."
8631 (interactive "P")
8632 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8633 (if (< arg 1)
8634 (progn (orgstruct-mode -1)
8635 (mapc (lambda(v)
8636 (org-set-local (car v)
8637 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8638 org-fb-vars))
8639 (orgstruct-mode 1)
8640 (setq org-fb-vars nil)
8641 (let (var val)
8642 (mapc
8643 (lambda (x)
8644 (when (string-match
8645 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8646 (symbol-name (car x)))
8647 (setq var (car x) val (nth 1 x))
8648 (push (list var `(quote ,(eval var))) org-fb-vars)
8649 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8650 org-local-vars)
8651 (org-set-local 'orgstruct-is-++ t))))
8653 (defvar orgstruct-is-++ nil
8654 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8655 (make-variable-buffer-local 'orgstruct-is-++)
8657 ;;;###autoload
8658 (defun turn-on-orgstruct++ ()
8659 "Unconditionally turn on `orgstruct++-mode'."
8660 (orgstruct++-mode 1))
8662 (defun orgstruct-error ()
8663 "Error when there is no default binding for a structure key."
8664 (interactive)
8665 (error "This key has no function outside structure elements"))
8667 (defun orgstruct-setup ()
8668 "Setup orgstruct keymap."
8669 (dolist (f
8670 '("org-meta"
8671 "org-shiftmeta"
8672 org-shifttab
8673 org-backward-element
8674 org-backward-heading-same-level
8675 org-ctrl-c-ret
8676 org-cycle
8677 org-forward-heading-same-level
8678 org-insert-heading
8679 org-insert-heading-respect-content
8680 org-kill-note-or-show-branches
8681 org-mark-subtree
8682 org-narrow-to-subtree
8683 org-promote-subtree
8684 org-reveal
8685 org-show-subtree
8686 org-sort
8687 org-up-element
8688 outline-demote
8689 outline-next-visible-heading
8690 outline-previous-visible-heading
8691 outline-promote
8692 outline-up-heading
8693 show-children))
8694 (dolist (f (if (stringp f)
8695 (let ((flist))
8696 (dolist (postfix
8697 '("-return" "tab" "left" "right" "up" "down")
8698 flist)
8699 (let ((f (intern (concat f postfix))))
8700 (when (fboundp f)
8701 (push f flist)))))
8702 (list f)))
8703 (dolist (binding (nconc (where-is-internal f org-mode-map)
8704 (where-is-internal f outline-mode-map)))
8705 ;; TODO use local-function-key-map
8706 (dolist (rep '(("<tab>" . "TAB")
8707 ("<ret>" . "RET")
8708 ("<esc>" . "ESC")
8709 ("<del>" . "DEL")))
8710 (setq binding (read-kbd-macro (replace-regexp-in-string
8711 (regexp-quote (car rep))
8712 (cdr rep)
8713 (key-description binding)))))
8714 (let ((key (lookup-key orgstruct-mode-map binding)))
8715 (when (or (not key) (numberp key))
8716 (condition-case nil
8717 (org-defkey orgstruct-mode-map
8718 binding
8719 (orgstruct-make-binding f binding))
8720 (error nil)))))))
8721 (run-hooks 'orgstruct-setup-hook))
8723 (defun orgstruct-make-binding (fun key)
8724 "Create a function for binding in the structure minor mode.
8725 FUN is the command to call inside a table. KEY is the key that
8726 should be checked in for a command to execute outside of tables."
8727 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8728 (let ((nname name)
8729 (i 0))
8730 (while (fboundp (intern nname))
8731 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8732 (setq name (intern nname)))
8733 (eval
8734 `(defun ,name (arg)
8735 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8736 "Outside of structure, run the binding of `"
8737 (key-description key) "'.")
8738 (interactive "p")
8739 (unless
8740 (let* ((org-heading-regexp
8741 (concat "^"
8742 orgstruct-heading-prefix-regexp
8743 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8744 (org-outline-regexp
8745 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8746 (org-outline-regexp-bol
8747 (concat "^" org-outline-regexp))
8748 (outline-regexp org-outline-regexp)
8749 (outline-heading-end-regexp "\n")
8750 (outline-level 'outline-level)
8751 (outline-heading-alist))
8752 (when (org-context-p 'headline 'item
8753 ,(when (memq fun '(org-insert-heading))
8754 '(when orgstruct-is-++
8755 'item-body)))
8756 (org-run-like-in-org-mode ',fun)
8758 (let* ((orgstruct-mode)
8759 (binding (key-binding ,key)))
8760 (if (keymapp binding)
8761 (set-temporary-overlay-map binding)
8762 (call-interactively
8763 (or binding 'orgstruct-error)))))))
8764 name))
8766 (defun org-contextualize-keys (alist contexts)
8767 "Return valid elements in ALIST depending on CONTEXTS.
8769 `org-agenda-custom-commands' or `org-capture-templates' are the
8770 values used for ALIST, and `org-agenda-custom-commands-contexts'
8771 or `org-capture-templates-contexts' are the associated contexts
8772 definitions."
8773 (let ((contexts
8774 ;; normalize contexts
8775 (mapcar
8776 (lambda(c) (cond ((listp (cadr c))
8777 (list (car c) (car c) (cadr c)))
8778 ((string= "" (cadr c))
8779 (list (car c) (car c) (caddr c)))
8780 (t c))) contexts))
8781 (a alist) c r s)
8782 ;; loop over all commands or templates
8783 (while (setq c (pop a))
8784 (let (vrules repl)
8785 (cond
8786 ((not (assoc (car c) contexts))
8787 (push c r))
8788 ((and (assoc (car c) contexts)
8789 (setq vrules (org-contextualize-validate-key
8790 (car c) contexts)))
8791 (mapc (lambda (vr)
8792 (when (not (equal (car vr) (cadr vr)))
8793 (setq repl vr))) vrules)
8794 (if (not repl) (push c r)
8795 (push (cadr repl) s)
8796 (push
8797 (cons (car c)
8798 (cdr (or (assoc (cadr repl) alist)
8799 (error "Undefined key `%s' as contextual replacement for `%s'"
8800 (cadr repl) (car c)))))
8801 r))))))
8802 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8803 (delq
8805 (delete-dups
8806 (mapcar (lambda (x)
8807 (let ((tpl (car x)))
8808 (when (not (delq
8810 (mapcar (lambda(y)
8811 (equal y tpl)) s))) x)))
8812 (reverse r))))))
8814 (defun org-contextualize-validate-key (key contexts)
8815 "Check CONTEXTS for agenda or capture KEY."
8816 (let (r rr res)
8817 (while (setq r (pop contexts))
8818 (mapc
8819 (lambda (rr)
8820 (when
8821 (and (equal key (car r))
8822 (if (functionp rr) (funcall rr)
8823 (or (and (eq (car rr) 'in-file)
8824 (buffer-file-name)
8825 (string-match (cdr rr) (buffer-file-name)))
8826 (and (eq (car rr) 'in-mode)
8827 (string-match (cdr rr) (symbol-name major-mode)))
8828 (and (eq (car rr) 'in-buffer)
8829 (string-match (cdr rr) (buffer-name)))
8830 (when (and (eq (car rr) 'not-in-file)
8831 (buffer-file-name))
8832 (not (string-match (cdr rr) (buffer-file-name))))
8833 (when (eq (car rr) 'not-in-mode)
8834 (not (string-match (cdr rr) (symbol-name major-mode))))
8835 (when (eq (car rr) 'not-in-buffer)
8836 (not (string-match (cdr rr) (buffer-name)))))))
8837 (push r res)))
8838 (car (last r))))
8839 (delete-dups (delq nil res))))
8841 (defun org-context-p (&rest contexts)
8842 "Check if local context is any of CONTEXTS.
8843 Possible values in the list of contexts are `table', `headline', and `item'."
8844 (let ((pos (point)))
8845 (goto-char (point-at-bol))
8846 (prog1 (or (and (memq 'table contexts)
8847 (looking-at "[ \t]*|"))
8848 (and (memq 'headline contexts)
8849 (looking-at org-outline-regexp))
8850 (and (memq 'item contexts)
8851 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8852 (and (memq 'item-body contexts)
8853 (org-in-item-p)))
8854 (goto-char pos))))
8856 (defun org-get-local-variables ()
8857 "Return a list of all local variables in an Org mode buffer."
8858 (let (varlist)
8859 (with-current-buffer (get-buffer-create "*Org tmp*")
8860 (erase-buffer)
8861 (org-mode)
8862 (setq varlist (buffer-local-variables)))
8863 (kill-buffer "*Org tmp*")
8864 (delq nil
8865 (mapcar
8866 (lambda (x)
8867 (setq x
8868 (if (symbolp x)
8869 (list x)
8870 (list (car x) (cdr x))))
8871 (if (and (not (get (car x) 'org-state))
8872 (string-match
8873 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8874 (symbol-name (car x))))
8875 x nil))
8876 varlist))))
8878 (defun org-clone-local-variables (from-buffer &optional regexp)
8879 "Clone local variables from FROM-BUFFER.
8880 Optional argument REGEXP selects variables to clone."
8881 (mapc
8882 (lambda (pair)
8883 (and (symbolp (car pair))
8884 (or (null regexp)
8885 (string-match regexp (symbol-name (car pair))))
8886 (set (make-local-variable (car pair))
8887 (cdr pair))))
8888 (buffer-local-variables from-buffer)))
8890 ;;;###autoload
8891 (defun org-run-like-in-org-mode (cmd)
8892 "Run a command, pretending that the current buffer is in Org-mode.
8893 This will temporarily bind local variables that are typically bound in
8894 Org-mode to the values they have in Org-mode, and then interactively
8895 call CMD."
8896 (org-load-modules-maybe)
8897 (unless org-local-vars
8898 (setq org-local-vars (org-get-local-variables)))
8899 (let (binds)
8900 (dolist (var org-local-vars)
8901 (when (or (not (boundp (car var)))
8902 (eq (symbol-value (car var))
8903 (default-value (car var))))
8904 (push (list (car var) `(quote ,(cadr var))) binds)))
8905 (eval `(let ,binds
8906 (call-interactively (quote ,cmd))))))
8908 ;;;; Archiving
8910 (defun org-get-category (&optional pos force-refresh)
8911 "Get the category applying to position POS."
8912 (save-match-data
8913 (if force-refresh (org-refresh-category-properties))
8914 (let ((pos (or pos (point))))
8915 (or (get-text-property pos 'org-category)
8916 (progn (org-refresh-category-properties)
8917 (get-text-property pos 'org-category))))))
8919 (defun org-refresh-category-properties ()
8920 "Refresh category text properties in the buffer."
8921 (let ((case-fold-search t)
8922 (inhibit-read-only t)
8923 (def-cat (cond
8924 ((null org-category)
8925 (if buffer-file-name
8926 (file-name-sans-extension
8927 (file-name-nondirectory buffer-file-name))
8928 "???"))
8929 ((symbolp org-category) (symbol-name org-category))
8930 (t org-category)))
8931 beg end cat pos optionp)
8932 (org-unmodified
8933 (save-excursion
8934 (save-restriction
8935 (widen)
8936 (goto-char (point-min))
8937 (put-text-property (point) (point-max) 'org-category def-cat)
8938 (while (re-search-forward
8939 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8940 (setq pos (match-end 0)
8941 optionp (equal (char-after (match-beginning 0)) ?#)
8942 cat (org-trim (match-string 2)))
8943 (if optionp
8944 (setq beg (point-at-bol) end (point-max))
8945 (org-back-to-heading t)
8946 (setq beg (point) end (org-end-of-subtree t t)))
8947 (put-text-property beg end 'org-category cat)
8948 (put-text-property beg end 'org-category-position beg)
8949 (goto-char pos)))))))
8951 (defun org-refresh-properties (dprop tprop)
8952 "Refresh buffer text properties.
8953 DPROP is the drawer property and TPROP is the corresponding text
8954 property to set."
8955 (let ((case-fold-search t)
8956 (inhibit-read-only t) p)
8957 (org-unmodified
8958 (save-excursion
8959 (save-restriction
8960 (widen)
8961 (goto-char (point-min))
8962 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8963 (setq p (org-match-string-no-properties 1))
8964 (save-excursion
8965 (org-back-to-heading t)
8966 (put-text-property
8967 (point-at-bol) (point-at-eol) tprop p))))))))
8970 ;;;; Link Stuff
8972 ;;; Link abbreviations
8974 (defun org-link-expand-abbrev (link)
8975 "Apply replacements as defined in `org-link-abbrev-alist'."
8976 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8977 (let* ((key (match-string 1 link))
8978 (as (or (assoc key org-link-abbrev-alist-local)
8979 (assoc key org-link-abbrev-alist)))
8980 (tag (and (match-end 2) (match-string 3 link)))
8981 rpl)
8982 (if (not as)
8983 link
8984 (setq rpl (cdr as))
8985 (cond
8986 ((symbolp rpl) (funcall rpl tag))
8987 ((string-match "%(\\([^)]+\\))" rpl)
8988 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8989 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8990 ((string-match "%h" rpl)
8991 (replace-match (url-hexify-string (or tag "")) t t rpl))
8992 (t (concat rpl tag)))))
8993 link))
8995 ;;; Storing and inserting links
8997 (defvar org-insert-link-history nil
8998 "Minibuffer history for links inserted with `org-insert-link'.")
9000 (defvar org-stored-links nil
9001 "Contains the links stored with `org-store-link'.")
9003 (defvar org-store-link-plist nil
9004 "Plist with info about the most recently link created with `org-store-link'.")
9006 (defvar org-link-protocols nil
9007 "Link protocols added to Org-mode using `org-add-link-type'.")
9009 (defvar org-store-link-functions nil
9010 "List of functions that are called to create and store a link.
9011 Each function will be called in turn until one returns a non-nil
9012 value. Each function should check if it is responsible for creating
9013 this link (for example by looking at the major mode).
9014 If not, it must exit and return nil.
9015 If yes, it should return a non-nil value after a calling
9016 `org-store-link-props' with a list of properties and values.
9017 Special properties are:
9019 :type The link prefix, like \"http\". This must be given.
9020 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9021 This is obligatory as well.
9022 :description Optional default description for the second pair
9023 of brackets in an Org-mode link. The user can still change
9024 this when inserting this link into an Org-mode buffer.
9026 In addition to these, any additional properties can be specified
9027 and then used in capture templates.")
9029 (defun org-add-link-type (type &optional follow export)
9030 "Add TYPE to the list of `org-link-types'.
9031 Re-compute all regular expressions depending on `org-link-types'
9033 FOLLOW and EXPORT are two functions.
9035 FOLLOW should take the link path as the single argument and do whatever
9036 is necessary to follow the link, for example find a file or display
9037 a mail message.
9039 EXPORT should format the link path for export to one of the export formats.
9040 It should be a function accepting three arguments:
9042 path the path of the link, the text after the prefix (like \"http:\")
9043 desc the description of the link, if any, or a description added by
9044 org-export-normalize-links if there is none
9045 format the export format, a symbol like `html' or `latex' or `ascii'..
9047 The function may use the FORMAT information to return different values
9048 depending on the format. The return value will be put literally into
9049 the exported file. If the return value is nil, this means Org should
9050 do what it normally does with links which do not have EXPORT defined.
9052 Org-mode has a built-in default for exporting links. If you are happy with
9053 this default, there is no need to define an export function for the link
9054 type. For a simple example of an export function, see `org-bbdb.el'."
9055 (add-to-list 'org-link-types type t)
9056 (org-make-link-regexps)
9057 (if (assoc type org-link-protocols)
9058 (setcdr (assoc type org-link-protocols) (list follow export))
9059 (push (list type follow export) org-link-protocols)))
9061 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9062 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9064 ;;;###autoload
9065 (defun org-store-link (arg)
9066 "\\<org-mode-map>Store an org-link to the current location.
9067 This link is added to `org-stored-links' and can later be inserted
9068 into an org-buffer with \\[org-insert-link].
9070 For some link types, a prefix arg is interpreted.
9071 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9072 For file links, arg negates `org-context-in-file-links'.
9074 A double prefix arg force skipping storing functions that are not
9075 part of Org's core."
9076 (interactive "P")
9077 (org-load-modules-maybe)
9078 (setq org-store-link-plist nil) ; reset
9079 (org-with-limited-levels
9080 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9081 (cond
9082 ((and (not (equal arg '(16)))
9083 (setq sfuns
9084 (delq
9085 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9086 org-store-link-functions))
9087 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9088 (or (and (cdr sfuns)
9089 (funcall (intern
9090 (completing-read "Which function for creating the link? "
9091 sfunsn t (car sfunsn)))))
9092 (funcall (caar sfuns)))
9093 (setq link (plist-get org-store-link-plist :link)
9094 desc (or (plist-get org-store-link-plist :description) link))))
9095 ((org-src-edit-buffer-p)
9096 (let (label gc)
9097 (while (or (not label)
9098 (save-excursion
9099 (save-restriction
9100 (widen)
9101 (goto-char (point-min))
9102 (re-search-forward
9103 (regexp-quote (format org-coderef-label-format label))
9104 nil t))))
9105 (when label (message "Label exists already") (sit-for 2))
9106 (setq label (read-string "Code line label: " label)))
9107 (end-of-line 1)
9108 (setq link (format org-coderef-label-format label))
9109 (setq gc (- 79 (length link)))
9110 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9111 (insert link)
9112 (setq link (concat "(" label ")") desc nil)))
9114 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9115 ;; We are in the agenda, link to referenced location
9116 (let ((m (or (get-text-property (point) 'org-hd-marker)
9117 (get-text-property (point) 'org-marker))))
9118 (when m
9119 (org-with-point-at m
9120 (setq agenda-link
9121 (if (org-called-interactively-p 'any)
9122 (call-interactively 'org-store-link)
9123 (org-store-link nil)))))))
9125 ((eq major-mode 'calendar-mode)
9126 (let ((cd (calendar-cursor-to-date)))
9127 (setq link
9128 (format-time-string
9129 (car org-time-stamp-formats)
9130 (apply 'encode-time
9131 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9132 nil nil nil))))
9133 (org-store-link-props :type "calendar" :date cd)))
9135 ((eq major-mode 'help-mode)
9136 (setq link (concat "help:" (save-excursion
9137 (goto-char (point-min))
9138 (looking-at "^[^ ]+")
9139 (match-string 0))))
9140 (org-store-link-props :type "help"))
9142 ((eq major-mode 'w3-mode)
9143 (setq cpltxt (if (and (buffer-name)
9144 (not (string-match "Untitled" (buffer-name))))
9145 (buffer-name)
9146 (url-view-url t))
9147 link (url-view-url t))
9148 (org-store-link-props :type "w3" :url (url-view-url t)))
9150 ((setq search (run-hook-with-args-until-success
9151 'org-create-file-search-functions))
9152 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9153 "::" search))
9154 (setq cpltxt (or description link)))
9156 ((eq major-mode 'image-mode)
9157 (setq cpltxt (concat "file:"
9158 (abbreviate-file-name buffer-file-name))
9159 link cpltxt)
9160 (org-store-link-props :type "image" :file buffer-file-name))
9162 ((eq major-mode 'dired-mode)
9163 ;; link to the file in the current line
9164 (let ((file (dired-get-filename nil t)))
9165 (setq file (if file
9166 (abbreviate-file-name
9167 (expand-file-name (dired-get-filename nil t)))
9168 ;; otherwise, no file so use current directory.
9169 default-directory))
9170 (setq cpltxt (concat "file:" file)
9171 link cpltxt)))
9173 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9174 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9175 (cond
9176 ((org-in-regexp "<<\\(.*?\\)>>")
9177 (setq cpltxt
9178 (concat "file:"
9179 (abbreviate-file-name
9180 (buffer-file-name (buffer-base-buffer)))
9181 "::" (match-string 1))
9182 link cpltxt))
9183 ((and (featurep 'org-id)
9184 (or (eq org-id-link-to-org-use-id t)
9185 (and (org-called-interactively-p 'any)
9186 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9187 (and (eq org-id-link-to-org-use-id
9188 'create-if-interactive-and-no-custom-id)
9189 (not custom-id))))
9190 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9191 ;; We can make a link using the ID.
9192 (setq link (condition-case nil
9193 (prog1 (org-id-store-link)
9194 (setq desc (plist-get org-store-link-plist :description)))
9195 (error
9196 ;; probably before first headline, link to file only
9197 (concat "file:"
9198 (abbreviate-file-name
9199 (buffer-file-name (buffer-base-buffer))))))))
9201 ;; Just link to current headline
9202 (setq cpltxt (concat "file:"
9203 (abbreviate-file-name
9204 (buffer-file-name (buffer-base-buffer)))))
9205 ;; Add a context search string
9206 (when (org-xor org-context-in-file-links arg)
9207 (let* ((ee (org-element-at-point))
9208 (et (org-element-type ee))
9209 (ev (plist-get (cadr ee) :value)))
9210 (setq txt (cond
9211 ((org-at-heading-p) nil)
9212 ((eq et 'keyword) ev)
9213 ((org-region-active-p)
9214 (buffer-substring (region-beginning) (region-end)))))
9215 (when (or (null txt) (string-match "\\S-" txt))
9216 (setq cpltxt
9217 (concat cpltxt "::"
9218 (condition-case nil
9219 (org-make-org-heading-search-string txt)
9220 (error "")))
9221 desc (or (and (eq et 'keyword) ev)
9222 (nth 4 (ignore-errors (org-heading-components)))
9223 "NONE")))))
9224 (if (string-match "::\\'" cpltxt)
9225 (setq cpltxt (substring cpltxt 0 -2)))
9226 (setq link cpltxt))))
9228 ((buffer-file-name (buffer-base-buffer))
9229 ;; Just link to this file here.
9230 (setq cpltxt (concat "file:"
9231 (abbreviate-file-name
9232 (buffer-file-name (buffer-base-buffer)))))
9233 ;; Add a context string
9234 (when (org-xor org-context-in-file-links arg)
9235 (setq txt (if (org-region-active-p)
9236 (buffer-substring (region-beginning) (region-end))
9237 (buffer-substring (point-at-bol) (point-at-eol))))
9238 ;; Only use search option if there is some text.
9239 (when (string-match "\\S-" txt)
9240 (setq cpltxt
9241 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9242 desc "NONE")))
9243 (setq link cpltxt))
9245 ((org-called-interactively-p 'interactive)
9246 (user-error "No method for storing a link from this buffer"))
9248 (t (setq link nil)))
9250 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9251 (setq link (or link cpltxt)
9252 desc (or desc cpltxt))
9253 (cond ((equal desc "NONE") (setq desc nil))
9254 ((string-match org-bracket-link-regexp desc)
9255 (setq desc (replace-regexp-in-string
9256 org-bracket-link-regexp
9257 (concat "\\3" (if (equal (length (match-string 0 desc))
9258 (length desc)) "*" "")) desc))))
9260 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9261 (progn
9262 (setq org-stored-links
9263 (cons (list link desc) org-stored-links))
9264 (message "Stored: %s" (or desc link))
9265 (when custom-id
9266 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9267 "::#" custom-id))
9268 (setq org-stored-links
9269 (cons (list link desc) org-stored-links))))
9270 (or agenda-link (and link (org-make-link-string link desc)))))))
9272 (defun org-store-link-props (&rest plist)
9273 "Store link properties, extract names and addresses."
9274 (let (x adr)
9275 (when (setq x (plist-get plist :from))
9276 (setq adr (mail-extract-address-components x))
9277 (setq plist (plist-put plist :fromname (car adr)))
9278 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9279 (when (setq x (plist-get plist :to))
9280 (setq adr (mail-extract-address-components x))
9281 (setq plist (plist-put plist :toname (car adr)))
9282 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9283 (let ((from (plist-get plist :from))
9284 (to (plist-get plist :to)))
9285 (when (and from to org-from-is-user-regexp)
9286 (setq plist
9287 (plist-put plist :fromto
9288 (if (string-match org-from-is-user-regexp from)
9289 (concat "to %t")
9290 (concat "from %f"))))))
9291 (setq org-store-link-plist plist))
9293 (defun org-add-link-props (&rest plist)
9294 "Add these properties to the link property list."
9295 (let (key value)
9296 (while plist
9297 (setq key (pop plist) value (pop plist))
9298 (setq org-store-link-plist
9299 (plist-put org-store-link-plist key value)))))
9301 (defun org-email-link-description (&optional fmt)
9302 "Return the description part of an email link.
9303 This takes information from `org-store-link-plist' and formats it
9304 according to FMT (default from `org-email-link-description-format')."
9305 (setq fmt (or fmt org-email-link-description-format))
9306 (let* ((p org-store-link-plist)
9307 (to (plist-get p :toaddress))
9308 (from (plist-get p :fromaddress))
9309 (table
9310 (list
9311 (cons "%c" (plist-get p :fromto))
9312 (cons "%F" (plist-get p :from))
9313 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9314 (cons "%T" (plist-get p :to))
9315 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9316 (cons "%s" (plist-get p :subject))
9317 (cons "%d" (plist-get p :date))
9318 (cons "%m" (plist-get p :message-id)))))
9319 (when (string-match "%c" fmt)
9320 ;; Check if the user wrote this message
9321 (if (and org-from-is-user-regexp from to
9322 (save-match-data (string-match org-from-is-user-regexp from)))
9323 (setq fmt (replace-match "to %t" t t fmt))
9324 (setq fmt (replace-match "from %f" t t fmt))))
9325 (org-replace-escapes fmt table)))
9327 (defun org-make-org-heading-search-string (&optional string)
9328 "Make search string for the current headline or STRING."
9329 (let ((s (or string
9330 (and (derived-mode-p 'org-mode)
9331 (save-excursion
9332 (org-back-to-heading t)
9333 (org-element-property :raw-value (org-element-at-point))))))
9334 (lines org-context-in-file-links))
9335 (or string (setq s (concat "*" s))) ; Add * for headlines
9336 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9337 (when (and string (integerp lines) (> lines 0))
9338 (let ((slines (org-split-string s "\n")))
9339 (when (< lines (length slines))
9340 (setq s (mapconcat
9341 'identity
9342 (reverse (nthcdr (- (length slines) lines)
9343 (reverse slines))) "\n")))))
9344 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9346 (defun org-make-link-string (link &optional description)
9347 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9348 (unless (string-match "\\S-" link)
9349 (error "Empty link"))
9350 (when (and description
9351 (stringp description)
9352 (not (string-match "\\S-" description)))
9353 (setq description nil))
9354 (when (stringp description)
9355 ;; Remove brackets from the description, they are fatal.
9356 (while (string-match "\\[" description)
9357 (setq description (replace-match "{" t t description)))
9358 (while (string-match "\\]" description)
9359 (setq description (replace-match "}" t t description))))
9360 (when (equal link description)
9361 ;; No description needed, it is identical
9362 (setq description nil))
9363 (when (and (not description)
9364 (not (string-match (org-image-file-name-regexp) link))
9365 (not (equal link (org-link-escape link))))
9366 (setq description (org-extract-attributes link)))
9367 (setq link
9368 (cond ((string-match (org-image-file-name-regexp) link) link)
9369 ((string-match org-link-types-re link)
9370 (concat (match-string 1 link)
9371 (org-link-escape (substring link (match-end 1)))))
9372 (t (org-link-escape link))))
9373 (concat "[[" link "]"
9374 (if description (concat "[" description "]") "")
9375 "]"))
9377 (defconst org-link-escape-chars
9378 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9379 "List of characters that should be escaped in link.
9380 This is the list that is used for internal purposes.")
9382 (defconst org-link-escape-chars-browser
9383 '(?\ )
9384 "List of escapes for characters that are problematic in links.
9385 This is the list that is used before handing over to the browser.")
9387 (defun org-link-escape (text &optional table merge)
9388 "Return percent escaped representation of TEXT.
9389 TEXT is a string with the text to escape.
9390 Optional argument TABLE is a list with characters that should be
9391 escaped. When nil, `org-link-escape-chars' is used.
9392 If optional argument MERGE is set, merge TABLE into
9393 `org-link-escape-chars'."
9394 (cond
9395 ((and table merge)
9396 (mapc (lambda (defchr)
9397 (unless (member defchr table)
9398 (setq table (cons defchr table)))) org-link-escape-chars))
9399 ((null table)
9400 (setq table org-link-escape-chars)))
9401 (mapconcat
9402 (lambda (char)
9403 (if (or (member char table)
9404 (and (or (< char 32) (= char 37) (> char 126))
9405 org-url-hexify-p))
9406 (mapconcat (lambda (sequence-element)
9407 (format "%%%.2X" sequence-element))
9408 (or (encode-coding-char char 'utf-8)
9409 (error "Unable to percent escape character: %s"
9410 (char-to-string char))) "")
9411 (char-to-string char))) text ""))
9413 (defun org-link-unescape (str)
9414 "Unhex hexified Unicode strings as returned from the JavaScript function
9415 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9416 (unless (and (null str) (string= "" str))
9417 (let ((pos 0) (case-fold-search t) unhexed)
9418 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9419 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9420 (setq str (replace-match unhexed t t str))
9421 (setq pos (+ pos (length unhexed))))))
9422 str)
9424 (defun org-link-unescape-compound (hex)
9425 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9426 Note: this function also decodes single byte encodings like
9427 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9428 (save-match-data
9429 (let* ((bytes (cdr (split-string hex "%")))
9430 (ret "")
9431 (eat 0)
9432 (sum 0))
9433 (while bytes
9434 (let* ((val (string-to-number (pop bytes) 16))
9435 (shift-xor
9436 (if (= 0 eat)
9437 (cond
9438 ((>= val 252) (cons 6 252))
9439 ((>= val 248) (cons 5 248))
9440 ((>= val 240) (cons 4 240))
9441 ((>= val 224) (cons 3 224))
9442 ((>= val 192) (cons 2 192))
9443 (t (cons 0 0)))
9444 (cons 6 128))))
9445 (if (>= val 192) (setq eat (car shift-xor)))
9446 (setq val (logxor val (cdr shift-xor)))
9447 (setq sum (+ (lsh sum (car shift-xor)) val))
9448 (if (> eat 0) (setq eat (- eat 1)))
9449 (cond
9450 ((= 0 eat) ;multi byte
9451 (setq ret (concat ret (org-char-to-string sum)))
9452 (setq sum 0))
9453 ((not bytes) ; single byte(s)
9454 (setq ret (org-link-unescape-single-byte-sequence hex))))
9455 )) ;; end (while bytes
9456 ret )))
9458 (defun org-link-unescape-single-byte-sequence (hex)
9459 "Unhexify hex-encoded single byte character sequences."
9460 (mapconcat (lambda (byte)
9461 (char-to-string (string-to-number byte 16)))
9462 (cdr (split-string hex "%")) ""))
9464 (defun org-xor (a b)
9465 "Exclusive or."
9466 (if a (not b) b))
9468 (defun org-fixup-message-id-for-http (s)
9469 "Replace special characters in a message id, so it can be used in an http query."
9470 (when (string-match "%" s)
9471 (setq s (mapconcat (lambda (c)
9472 (if (eq c ?%)
9473 "%25"
9474 (char-to-string c)))
9475 s "")))
9476 (while (string-match "<" s)
9477 (setq s (replace-match "%3C" t t s)))
9478 (while (string-match ">" s)
9479 (setq s (replace-match "%3E" t t s)))
9480 (while (string-match "@" s)
9481 (setq s (replace-match "%40" t t s)))
9484 (defun org-link-prettify (link)
9485 "Return a human-readable representation of LINK.
9486 The car of LINK must be a raw link the cdr of LINK must be either
9487 a link description or nil."
9488 (let ((desc (or (cadr link) "<no description>")))
9489 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9490 "<" (car link) ">")))
9492 ;;;###autoload
9493 (defun org-insert-link-global ()
9494 "Insert a link like Org-mode does.
9495 This command can be called in any mode to insert a link in Org-mode syntax."
9496 (interactive)
9497 (org-load-modules-maybe)
9498 (org-run-like-in-org-mode 'org-insert-link))
9500 (defun org-insert-all-links (&optional keep)
9501 "Insert all links in `org-stored-links'."
9502 (interactive "P")
9503 (let ((links (copy-sequence org-stored-links)) l)
9504 (while (setq l (if keep (pop links) (pop org-stored-links)))
9505 (insert "- ")
9506 (org-insert-link nil (car l) (cadr l))
9507 (insert "\n"))))
9509 (defun org-link-fontify-links-to-this-file ()
9510 "Fontify links to the current file in `org-stored-links'."
9511 (let ((f (buffer-file-name)) a b)
9512 (setq a (mapcar (lambda(l)
9513 (let ((ll (car l)))
9514 (when (and (string-match "^file:\\(.+\\)::" ll)
9515 (equal f (expand-file-name (match-string 1 ll))))
9516 ll)))
9517 org-stored-links))
9518 (when (featurep 'org-id)
9519 (setq b (mapcar (lambda(l)
9520 (let ((ll (car l)))
9521 (when (and (string-match "^id:\\(.+\\)$" ll)
9522 (equal f (expand-file-name
9523 (or (org-id-find-id-file
9524 (match-string 1 ll)) ""))))
9525 ll)))
9526 org-stored-links)))
9527 (mapcar (lambda(l)
9528 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9529 (delq nil (append a b)))))
9531 (defvar org-link-links-in-this-file nil)
9532 (defun org-insert-link (&optional complete-file link-location default-description)
9533 "Insert a link. At the prompt, enter the link.
9535 Completion can be used to insert any of the link protocol prefixes like
9536 http or ftp in use.
9538 The history can be used to select a link previously stored with
9539 `org-store-link'. When the empty string is entered (i.e. if you just
9540 press RET at the prompt), the link defaults to the most recently
9541 stored link. As SPC triggers completion in the minibuffer, you need to
9542 use M-SPC or C-q SPC to force the insertion of a space character.
9544 You will also be prompted for a description, and if one is given, it will
9545 be displayed in the buffer instead of the link.
9547 If there is already a link at point, this command will allow you to edit link
9548 and description parts.
9550 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9551 be selected using completion. The path to the file will be relative to the
9552 current directory if the file is in the current directory or a subdirectory.
9553 Otherwise, the link will be the absolute path as completed in the minibuffer
9554 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9555 option `org-link-file-path-type'.
9557 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9558 the current directory or below.
9560 With three \\[universal-argument] prefixes, negate the meaning of
9561 `org-keep-stored-link-after-insertion'.
9563 If `org-make-link-description-function' is non-nil, this function will be
9564 called with the link target, and the result will be the default
9565 link description.
9567 If the LINK-LOCATION parameter is non-nil, this value will be
9568 used as the link location instead of reading one interactively.
9570 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9571 be used as the default description."
9572 (interactive "P")
9573 (let* ((wcf (current-window-configuration))
9574 (origbuf (current-buffer))
9575 (region (if (org-region-active-p)
9576 (buffer-substring (region-beginning) (region-end))))
9577 (remove (and region (list (region-beginning) (region-end))))
9578 (desc region)
9579 tmphist ; byte-compile incorrectly complains about this
9580 (link link-location)
9581 (abbrevs org-link-abbrev-alist-local)
9582 entry file all-prefixes auto-desc)
9583 (cond
9584 (link-location) ; specified by arg, just use it.
9585 ((org-in-regexp org-bracket-link-regexp 1)
9586 ;; We do have a link at point, and we are going to edit it.
9587 (setq remove (list (match-beginning 0) (match-end 0)))
9588 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9589 (setq link (read-string "Link: "
9590 (org-link-unescape
9591 (org-match-string-no-properties 1)))))
9592 ((or (org-in-regexp org-angle-link-re)
9593 (org-in-regexp org-plain-link-re))
9594 ;; Convert to bracket link
9595 (setq remove (list (match-beginning 0) (match-end 0))
9596 link (read-string "Link: "
9597 (org-remove-angle-brackets (match-string 0)))))
9598 ((member complete-file '((4) (16)))
9599 ;; Completing read for file names.
9600 (setq link (org-file-complete-link complete-file)))
9602 ;; Read link, with completion for stored links.
9603 (org-link-fontify-links-to-this-file)
9604 (org-switch-to-buffer-other-window "*Org Links*")
9605 (with-current-buffer "*Org Links*"
9606 (erase-buffer)
9607 (insert "Insert a link.
9608 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9609 (when org-stored-links
9610 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9611 (insert (mapconcat 'org-link-prettify
9612 (reverse org-stored-links) "\n")))
9613 (goto-char (point-min)))
9614 (let ((cw (selected-window)))
9615 (select-window (get-buffer-window "*Org Links*" 'visible))
9616 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9617 (unless (pos-visible-in-window-p (point-max))
9618 (org-fit-window-to-buffer))
9619 (and (window-live-p cw) (select-window cw)))
9620 ;; Fake a link history, containing the stored links.
9621 (setq tmphist (append (mapcar 'car org-stored-links)
9622 org-insert-link-history))
9623 (setq all-prefixes (append (mapcar 'car abbrevs)
9624 (mapcar 'car org-link-abbrev-alist)
9625 org-link-types))
9626 (unwind-protect
9627 (progn
9628 (setq link
9629 (org-completing-read
9630 "Link: "
9631 (append
9632 (mapcar (lambda (x) (concat x ":"))
9633 all-prefixes)
9634 (mapcar 'car org-stored-links))
9635 nil nil nil
9636 'tmphist
9637 (caar org-stored-links)))
9638 (if (not (string-match "\\S-" link))
9639 (error "No link selected"))
9640 (mapc (lambda(l)
9641 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9642 org-stored-links)
9643 (if (or (member link all-prefixes)
9644 (and (equal ":" (substring link -1))
9645 (member (substring link 0 -1) all-prefixes)
9646 (setq link (substring link 0 -1))))
9647 (setq link (with-current-buffer origbuf
9648 (org-link-try-special-completion link)))))
9649 (set-window-configuration wcf)
9650 (kill-buffer "*Org Links*"))
9651 (setq entry (assoc link org-stored-links))
9652 (or entry (push link org-insert-link-history))
9653 (setq desc (or desc (nth 1 entry)))))
9655 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9656 (not org-keep-stored-link-after-insertion))
9657 (setq org-stored-links (delq (assoc link org-stored-links)
9658 org-stored-links)))
9660 (if (string-match org-plain-link-re link)
9661 ;; URL-like link, normalize the use of angular brackets.
9662 (setq link (org-remove-angle-brackets link)))
9664 ;; Check if we are linking to the current file with a search
9665 ;; option If yes, simplify the link by using only the search
9666 ;; option.
9667 (when (and buffer-file-name
9668 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9669 (let* ((path (match-string 1 link))
9670 (case-fold-search nil)
9671 (search (match-string 2 link)))
9672 (save-match-data
9673 (if (equal (file-truename buffer-file-name) (file-truename path))
9674 ;; We are linking to this same file, with a search option
9675 (setq link search)))))
9677 ;; Check if we can/should use a relative path. If yes, simplify the link
9678 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9679 (let* ((type (match-string 1 link))
9680 (path (match-string 2 link))
9681 (origpath path)
9682 (case-fold-search nil))
9683 (cond
9684 ((or (eq org-link-file-path-type 'absolute)
9685 (equal complete-file '(16)))
9686 (setq path (abbreviate-file-name (expand-file-name path))))
9687 ((eq org-link-file-path-type 'noabbrev)
9688 (setq path (expand-file-name path)))
9689 ((eq org-link-file-path-type 'relative)
9690 (setq path (file-relative-name path)))
9692 (save-match-data
9693 (if (string-match (concat "^" (regexp-quote
9694 (expand-file-name
9695 (file-name-as-directory
9696 default-directory))))
9697 (expand-file-name path))
9698 ;; We are linking a file with relative path name.
9699 (setq path (substring (expand-file-name path)
9700 (match-end 0)))
9701 (setq path (abbreviate-file-name (expand-file-name path)))))))
9702 (setq link (concat type path))
9703 (if (equal desc origpath)
9704 (setq desc path))))
9706 (if org-make-link-description-function
9707 (setq desc
9708 (or (condition-case nil
9709 (funcall org-make-link-description-function link desc)
9710 (error (progn (message "Can't get link description from `%s'"
9711 (symbol-name org-make-link-description-function))
9712 (sit-for 2) nil)))
9713 (read-string "Description: " default-description)))
9714 (if default-description (setq desc default-description)
9715 (setq desc (or (and auto-desc desc)
9716 (read-string "Description: " desc)))))
9718 (unless (string-match "\\S-" desc) (setq desc nil))
9719 (if remove (apply 'delete-region remove))
9720 (insert (org-make-link-string link desc))))
9722 (defun org-link-try-special-completion (type)
9723 "If there is completion support for link type TYPE, offer it."
9724 (let ((fun (intern (concat "org-" type "-complete-link"))))
9725 (if (functionp fun)
9726 (funcall fun)
9727 (read-string "Link (no completion support): " (concat type ":")))))
9729 (defun org-file-complete-link (&optional arg)
9730 "Create a file link using completion."
9731 (let (file link)
9732 (setq file (org-iread-file-name "File: "))
9733 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9734 (pwd1 (file-name-as-directory (abbreviate-file-name
9735 (expand-file-name ".")))))
9736 (cond
9737 ((equal arg '(16))
9738 (setq link (concat
9739 "file:"
9740 (abbreviate-file-name (expand-file-name file)))))
9741 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9742 (setq link (concat "file:" (match-string 1 file))))
9743 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9744 (expand-file-name file))
9745 (setq link (concat
9746 "file:" (match-string 1 (expand-file-name file)))))
9747 (t (setq link (concat "file:" file)))))
9748 link))
9750 (defun org-iread-file-name (&rest args)
9751 "Read-file-name using `ido-mode' speedup if available.
9752 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9753 See `read-file-name' for a description of parameters."
9754 (org-without-partial-completion
9755 (if (and org-completion-use-ido
9756 (fboundp 'ido-read-file-name)
9757 (boundp 'ido-mode) ido-mode
9758 (listp (second args)))
9759 (let ((ido-enter-matching-directory nil))
9760 (apply 'ido-read-file-name args))
9761 (apply 'read-file-name args))))
9763 (defun org-completing-read (&rest args)
9764 "Completing-read with SPACE being a normal character."
9765 (let ((enable-recursive-minibuffers t)
9766 (minibuffer-local-completion-map
9767 (copy-keymap minibuffer-local-completion-map)))
9768 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9769 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9770 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9771 (apply 'org-icompleting-read args)))
9773 (defun org-completing-read-no-i (&rest args)
9774 (let (org-completion-use-ido org-completion-use-iswitchb)
9775 (apply 'org-completing-read args)))
9777 (defun org-iswitchb-completing-read (prompt choices &rest args)
9778 "Use iswitch as a completing-read replacement to choose from choices.
9779 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9780 from."
9781 (let* ((iswitchb-use-virtual-buffers nil)
9782 (iswitchb-make-buflist-hook
9783 (lambda ()
9784 (setq iswitchb-temp-buflist choices))))
9785 (iswitchb-read-buffer prompt)))
9787 (defun org-icompleting-read (&rest args)
9788 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9789 (org-without-partial-completion
9790 (if (and org-completion-use-ido
9791 (fboundp 'ido-completing-read)
9792 (boundp 'ido-mode) ido-mode
9793 (listp (second args)))
9794 (let ((ido-enter-matching-directory nil))
9795 (apply 'ido-completing-read (concat (car args))
9796 (if (consp (car (nth 1 args)))
9797 (mapcar 'car (nth 1 args))
9798 (nth 1 args))
9799 (cddr args)))
9800 (if (and org-completion-use-iswitchb
9801 (boundp 'iswitchb-mode) iswitchb-mode
9802 (listp (second args)))
9803 (apply 'org-iswitchb-completing-read (concat (car args))
9804 (if (consp (car (nth 1 args)))
9805 (mapcar 'car (nth 1 args))
9806 (nth 1 args))
9807 (cddr args))
9808 (apply 'completing-read args)))))
9810 (defun org-extract-attributes (s)
9811 "Extract the attributes cookie from a string and set as text property."
9812 (let (a attr (start 0) key value)
9813 (save-match-data
9814 (when (string-match "{{\\([^}]+\\)}}$" s)
9815 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9816 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9817 (setq key (match-string 1 a) value (match-string 2 a)
9818 start (match-end 0)
9819 attr (plist-put attr (intern key) value))))
9820 (org-add-props s nil 'org-attr attr))
9823 (defun org-extract-attributes-from-string (tag)
9824 (let (key value attr)
9825 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9826 (setq key (match-string 1 tag) value (match-string 2 tag)
9827 tag (replace-match "" t t tag)
9828 attr (plist-put attr (intern key) value)))
9829 (cons tag attr)))
9831 (defun org-attributes-to-string (plist)
9832 "Format a property list into an HTML attribute list."
9833 (let ((s "") key value)
9834 (while plist
9835 (setq key (pop plist) value (pop plist))
9836 (and value
9837 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9840 ;;; Opening/following a link
9842 (defvar org-link-search-failed nil)
9844 (defvar org-open-link-functions nil
9845 "Hook for functions finding a plain text link.
9846 These functions must take a single argument, the link content.
9847 They will be called for links that look like [[link text][description]]
9848 when LINK TEXT does not have a protocol like \"http:\" and does not look
9849 like a filename (e.g. \"./blue.png\").
9851 These functions will be called *before* Org attempts to resolve the
9852 link by doing text searches in the current buffer - so if you want a
9853 link \"[[target]]\" to still find \"<<target>>\", your function should
9854 handle this as a special case.
9856 When the function does handle the link, it must return a non-nil value.
9857 If it decides that it is not responsible for this link, it must return
9858 nil to indicate that that Org-mode can continue with other options
9859 like exact and fuzzy text search.")
9861 (defun org-next-link ()
9862 "Move forward to the next link.
9863 If the link is in hidden text, expose it."
9864 (interactive)
9865 (when (and org-link-search-failed (eq this-command last-command))
9866 (goto-char (point-min))
9867 (message "Link search wrapped back to beginning of buffer"))
9868 (setq org-link-search-failed nil)
9869 (let* ((pos (point))
9870 (ct (org-context))
9871 (a (assoc :link ct)))
9872 (if a (goto-char (nth 2 a)))
9873 (if (re-search-forward org-any-link-re nil t)
9874 (progn
9875 (goto-char (match-beginning 0))
9876 (if (outline-invisible-p) (org-show-context)))
9877 (goto-char pos)
9878 (setq org-link-search-failed t)
9879 (error "No further link found"))))
9881 (defun org-previous-link ()
9882 "Move backward to the previous link.
9883 If the link is in hidden text, expose it."
9884 (interactive)
9885 (when (and org-link-search-failed (eq this-command last-command))
9886 (goto-char (point-max))
9887 (message "Link search wrapped back to end of buffer"))
9888 (setq org-link-search-failed nil)
9889 (let* ((pos (point))
9890 (ct (org-context))
9891 (a (assoc :link ct)))
9892 (if a (goto-char (nth 1 a)))
9893 (if (re-search-backward org-any-link-re nil t)
9894 (progn
9895 (goto-char (match-beginning 0))
9896 (if (outline-invisible-p) (org-show-context)))
9897 (goto-char pos)
9898 (setq org-link-search-failed t)
9899 (error "No further link found"))))
9901 (defun org-translate-link (s)
9902 "Translate a link string if a translation function has been defined."
9903 (if (and org-link-translation-function
9904 (fboundp org-link-translation-function)
9905 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9906 (progn
9907 (setq s (funcall org-link-translation-function
9908 (match-string 1 s) (match-string 2 s)))
9909 (concat (car s) ":" (cdr s)))
9912 (defun org-translate-link-from-planner (type path)
9913 "Translate a link from Emacs Planner syntax so that Org can follow it.
9914 This is still an experimental function, your mileage may vary."
9915 (cond
9916 ((member type '("http" "https" "news" "ftp"))
9917 ;; standard Internet links are the same.
9918 nil)
9919 ((and (equal type "irc") (string-match "^//" path))
9920 ;; Planner has two / at the beginning of an irc link, we have 1.
9921 ;; We should have zero, actually....
9922 (setq path (substring path 1)))
9923 ((and (equal type "lisp") (string-match "^/" path))
9924 ;; Planner has a slash, we do not.
9925 (setq type "elisp" path (substring path 1)))
9926 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9927 ;; A typical message link. Planner has the id after the final slash,
9928 ;; we separate it with a hash mark
9929 (setq path (concat (match-string 1 path) "#"
9930 (org-remove-angle-brackets (match-string 2 path)))))
9932 (cons type path))
9934 (defun org-find-file-at-mouse (ev)
9935 "Open file link or URL at mouse."
9936 (interactive "e")
9937 (mouse-set-point ev)
9938 (org-open-at-point 'in-emacs))
9940 (defun org-open-at-mouse (ev)
9941 "Open file link or URL at mouse.
9942 See the docstring of `org-open-file' for details."
9943 (interactive "e")
9944 (mouse-set-point ev)
9945 (if (eq major-mode 'org-agenda-mode)
9946 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9947 (org-open-at-point))
9949 (defvar org-window-config-before-follow-link nil
9950 "The window configuration before following a link.
9951 This is saved in case the need arises to restore it.")
9953 (defvar org-open-link-marker (make-marker)
9954 "Marker pointing to the location where `org-open-at-point; was called.")
9956 ;;;###autoload
9957 (defun org-open-at-point-global ()
9958 "Follow a link like Org-mode does.
9959 This command can be called in any mode to follow a link that has
9960 Org-mode syntax."
9961 (interactive)
9962 (org-run-like-in-org-mode 'org-open-at-point))
9964 ;;;###autoload
9965 (defun org-open-link-from-string (s &optional arg reference-buffer)
9966 "Open a link in the string S, as if it was in Org-mode."
9967 (interactive "sLink: \nP")
9968 (let ((reference-buffer (or reference-buffer (current-buffer))))
9969 (with-temp-buffer
9970 (let ((org-inhibit-startup (not reference-buffer)))
9971 (org-mode)
9972 (insert s)
9973 (goto-char (point-min))
9974 (when reference-buffer
9975 (setq org-link-abbrev-alist-local
9976 (with-current-buffer reference-buffer
9977 org-link-abbrev-alist-local)))
9978 (org-open-at-point arg reference-buffer)))))
9980 (defvar org-open-at-point-functions nil
9981 "Hook that is run when following a link at point.
9983 Functions in this hook must return t if they identify and follow
9984 a link at point. If they don't find anything interesting at point,
9985 they must return nil.")
9987 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9988 (defun org-open-at-point (&optional arg reference-buffer)
9989 "Open link at or after point.
9990 If there is no link at point, this function will search forward up to
9991 the end of the current line.
9992 Normally, files will be opened by an appropriate application. If the
9993 optional prefix argument ARG is non-nil, Emacs will visit the file.
9994 With a double prefix argument, try to open outside of Emacs, in the
9995 application the system uses for this file type."
9996 (interactive "P")
9997 ;; if in a code block, then open the block's results
9998 (unless (call-interactively #'org-babel-open-src-block-result)
9999 (org-load-modules-maybe)
10000 (move-marker org-open-link-marker (point))
10001 (setq org-window-config-before-follow-link (current-window-configuration))
10002 (org-remove-occur-highlights nil nil t)
10003 (cond
10004 ((and (org-at-heading-p)
10005 (not (org-at-timestamp-p t))
10006 (not (org-in-regexp
10007 (concat org-plain-link-re "\\|"
10008 org-bracket-link-regexp "\\|"
10009 org-angle-link-re "\\|"
10010 "[ \t]:[^ \t\n]+:[ \t]*$")))
10011 (not (get-text-property (point) 'org-linked-text)))
10012 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10013 (lk0 (car lkall))
10014 (lk (if (stringp lk0) (list lk0) lk0))
10015 (lkend (cdr lkall)))
10016 (mapcar (lambda(l)
10017 (search-forward l nil lkend)
10018 (goto-char (match-beginning 0))
10019 (org-open-at-point))
10020 lk))
10021 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10022 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10023 ((and (org-at-timestamp-p t)
10024 (not (org-in-regexp org-bracket-link-regexp)))
10025 (org-follow-timestamp-link))
10026 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10027 (not (org-in-regexp org-any-link-re)))
10028 (org-footnote-action))
10030 (let (type path link line search (pos (point)))
10031 (catch 'match
10032 (save-excursion
10033 (skip-chars-forward "^]\n\r")
10034 (when (org-in-regexp org-bracket-link-regexp 1)
10035 (setq link (org-extract-attributes
10036 (org-link-unescape (org-match-string-no-properties 1))))
10037 (while (string-match " *\n *" link)
10038 (setq link (replace-match " " t t link)))
10039 (setq link (org-link-expand-abbrev link))
10040 (cond
10041 ((or (file-name-absolute-p link)
10042 (string-match "^\\.\\.?/" link))
10043 (setq type "file" path link))
10044 ((string-match org-link-re-with-space3 link)
10045 (setq type (match-string 1 link) path (match-string 2 link)))
10046 ((string-match "^help:+\\(.+\\)" link)
10047 (setq type "help" path (match-string 1 link)))
10048 (t (setq type "thisfile" path link)))
10049 (throw 'match t)))
10051 (when (get-text-property (point) 'org-linked-text)
10052 (setq type "thisfile"
10053 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10054 (1+ (point)) (point))
10055 path (buffer-substring
10056 (or (previous-single-property-change pos 'org-linked-text)
10057 (point-min))
10058 (or (next-single-property-change pos 'org-linked-text)
10059 (point-max))))
10060 (throw 'match t))
10062 (save-excursion
10063 (when (or (org-in-regexp org-angle-link-re)
10064 (let ((match (org-in-regexp org-plain-link-re)))
10065 ;; Check a plain link is not within a bracket link
10066 (and match
10067 (save-excursion
10068 (progn
10069 (goto-char (car match))
10070 (not (org-in-regexp org-bracket-link-regexp))))))
10071 (let ((line_ending (save-excursion (end-of-line) (point))))
10072 ;; We are in a line before a plain or bracket link
10073 (or (re-search-forward org-plain-link-re line_ending t)
10074 (re-search-forward org-bracket-link-regexp line_ending t))))
10075 (setq type (match-string 1)
10076 path (org-link-unescape (match-string 2)))
10077 (throw 'match t)))
10078 (save-excursion
10079 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10080 (setq type "tags"
10081 path (match-string 1))
10082 (while (string-match ":" path)
10083 (setq path (replace-match "+" t t path)))
10084 (throw 'match t)))
10085 (when (org-in-regexp "<\\([^><\n]+\\)>")
10086 (setq type "tree-match"
10087 path (match-string 1))
10088 (throw 'match t)))
10089 (unless path
10090 (user-error "No link found"))
10092 ;; switch back to reference buffer
10093 ;; needed when if called in a temporary buffer through
10094 ;; org-open-link-from-string
10095 (with-current-buffer (or reference-buffer (current-buffer))
10097 ;; Remove any trailing spaces in path
10098 (if (string-match " +\\'" path)
10099 (setq path (replace-match "" t t path)))
10100 (if (and org-link-translation-function
10101 (fboundp org-link-translation-function))
10102 ;; Check if we need to translate the link
10103 (let ((tmp (funcall org-link-translation-function type path)))
10104 (setq type (car tmp) path (cdr tmp))))
10106 (cond
10108 ((assoc type org-link-protocols)
10109 (funcall (nth 1 (assoc type org-link-protocols)) path))
10111 ((equal type "help")
10112 (let ((f-or-v (intern path)))
10113 (cond ((fboundp f-or-v)
10114 (describe-function f-or-v))
10115 ((boundp f-or-v)
10116 (describe-variable f-or-v))
10117 (t (error "Not a known function or variable")))))
10119 ((equal type "mailto")
10120 (let ((cmd (car org-link-mailto-program))
10121 (args (cdr org-link-mailto-program)) args1
10122 (address path) (subject "") a)
10123 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10124 (setq address (match-string 1 path)
10125 subject (org-link-escape (match-string 2 path))))
10126 (while args
10127 (cond
10128 ((not (stringp (car args))) (push (pop args) args1))
10129 (t (setq a (pop args))
10130 (if (string-match "%a" a)
10131 (setq a (replace-match address t t a)))
10132 (if (string-match "%s" a)
10133 (setq a (replace-match subject t t a)))
10134 (push a args1))))
10135 (apply cmd (nreverse args1))))
10137 ((member type '("http" "https" "ftp" "news"))
10138 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10139 (org-link-escape
10140 path org-link-escape-chars-browser)
10141 path))))
10143 ((string= type "doi")
10144 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10145 (org-link-escape
10146 path org-link-escape-chars-browser)
10147 path))))
10149 ((member type '("message"))
10150 (browse-url (concat type ":" path)))
10152 ((string= type "tags")
10153 (org-tags-view arg path))
10155 ((string= type "tree-match")
10156 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10158 ((string= type "file")
10159 (if (string-match "::\\([0-9]+\\)\\'" path)
10160 (setq line (string-to-number (match-string 1 path))
10161 path (substring path 0 (match-beginning 0)))
10162 (if (string-match "::\\(.+\\)\\'" path)
10163 (setq search (match-string 1 path)
10164 path (substring path 0 (match-beginning 0)))))
10165 (if (string-match "[*?{]" (file-name-nondirectory path))
10166 (dired path)
10167 (org-open-file path arg line search)))
10169 ((string= type "shell")
10170 (let ((buf (generate-new-buffer "*Org Shell Output"))
10171 (cmd path))
10172 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10173 (string-match org-confirm-shell-link-not-regexp cmd))
10174 (not org-confirm-shell-link-function)
10175 (funcall org-confirm-shell-link-function
10176 (format "Execute \"%s\" in shell? "
10177 (org-add-props cmd nil
10178 'face 'org-warning))))
10179 (progn
10180 (message "Executing %s" cmd)
10181 (shell-command cmd buf)
10182 (if (featurep 'midnight)
10183 (setq clean-buffer-list-kill-buffer-names
10184 (cons buf clean-buffer-list-kill-buffer-names))))
10185 (error "Abort"))))
10187 ((string= type "elisp")
10188 (let ((cmd path))
10189 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10190 (string-match org-confirm-elisp-link-not-regexp cmd))
10191 (not org-confirm-elisp-link-function)
10192 (funcall org-confirm-elisp-link-function
10193 (format "Execute \"%s\" as elisp? "
10194 (org-add-props cmd nil
10195 'face 'org-warning))))
10196 (message "%s => %s" cmd
10197 (if (equal (string-to-char cmd) ?\()
10198 (eval (read cmd))
10199 (call-interactively (read cmd))))
10200 (error "Abort"))))
10202 ((and (string= type "thisfile")
10203 (run-hook-with-args-until-success
10204 'org-open-link-functions path)))
10206 ((string= type "thisfile")
10207 (if arg
10208 (switch-to-buffer-other-window
10209 (org-get-buffer-for-internal-link (current-buffer)))
10210 (org-mark-ring-push))
10211 (let ((cmd `(org-link-search
10212 ,path
10213 ,(cond ((equal arg '(4)) ''occur)
10214 ((equal arg '(16)) ''org-occur))
10215 ,pos)))
10216 (condition-case nil (let ((org-link-search-inhibit-query t))
10217 (eval cmd))
10218 (error (progn (widen) (eval cmd))))))
10220 (t (browse-url-at-point)))))))
10221 (move-marker org-open-link-marker nil)
10222 (run-hook-with-args 'org-follow-link-hook)))
10224 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10225 "Offer links in the current entry and return the selected link.
10226 If there is only one link, return it.
10227 If NTH is an integer, return the NTH link found.
10228 If ZERO is a string, check also this string for a link, and if
10229 there is one, return it."
10230 (with-current-buffer buffer
10231 (save-excursion
10232 (save-restriction
10233 (widen)
10234 (goto-char marker)
10235 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10236 "\\(" org-angle-link-re "\\)\\|"
10237 "\\(" org-plain-link-re "\\)"))
10238 (cnt ?0)
10239 (in-emacs (if (integerp nth) nil nth))
10240 have-zero end links link c)
10241 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10242 (push (match-string 0 zero) links)
10243 (setq cnt (1- cnt) have-zero t))
10244 (save-excursion
10245 (org-back-to-heading t)
10246 (setq end (save-excursion (outline-next-heading) (point)))
10247 (while (re-search-forward re end t)
10248 (push (match-string 0) links))
10249 (setq links (org-uniquify (reverse links))))
10250 (cond
10251 ((null links)
10252 (message "No links"))
10253 ((equal (length links) 1)
10254 (setq link (car links)))
10255 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10256 (setq link (nth (if have-zero nth (1- nth)) links)))
10257 (t ; we have to select a link
10258 (save-excursion
10259 (save-window-excursion
10260 (delete-other-windows)
10261 (with-output-to-temp-buffer "*Select Link*"
10262 (mapc (lambda (l)
10263 (if (not (string-match org-bracket-link-regexp l))
10264 (princ (format "[%c] %s\n" (incf cnt)
10265 (org-remove-angle-brackets l)))
10266 (if (match-end 3)
10267 (princ (format "[%c] %s (%s)\n" (incf cnt)
10268 (match-string 3 l) (match-string 1 l)))
10269 (princ (format "[%c] %s\n" (incf cnt)
10270 (match-string 1 l))))))
10271 links))
10272 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10273 (message "Select link to open, RET to open all:")
10274 (setq c (read-char-exclusive))
10275 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10276 (when (equal c ?q) (error "Abort"))
10277 (if (equal c ?\C-m)
10278 (setq link links)
10279 (setq nth (- c ?0))
10280 (if have-zero (setq nth (1+ nth)))
10281 (unless (and (integerp nth) (>= (length links) nth))
10282 (error "Invalid link selection"))
10283 (setq link (nth (1- nth) links)))))
10284 (cons link end))))))
10286 ;; Add special file links that specify the way of opening
10288 (org-add-link-type "file+sys" 'org-open-file-with-system)
10289 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10290 (defun org-open-file-with-system (path)
10291 "Open file at PATH using the system way of opening it."
10292 (org-open-file path 'system))
10293 (defun org-open-file-with-emacs (path)
10294 "Open file at PATH in Emacs."
10295 (org-open-file path 'emacs))
10298 ;;; File search
10300 (defvar org-create-file-search-functions nil
10301 "List of functions to construct the right search string for a file link.
10302 These functions are called in turn with point at the location to
10303 which the link should point.
10305 A function in the hook should first test if it would like to
10306 handle this file type, for example by checking the `major-mode'
10307 or the file extension. If it decides not to handle this file, it
10308 should just return nil to give other functions a chance. If it
10309 does handle the file, it must return the search string to be used
10310 when following the link. The search string will be part of the
10311 file link, given after a double colon, and `org-open-at-point'
10312 will automatically search for it. If special measures must be
10313 taken to make the search successful, another function should be
10314 added to the companion hook `org-execute-file-search-functions',
10315 which see.
10317 A function in this hook may also use `setq' to set the variable
10318 `description' to provide a suggestion for the descriptive text to
10319 be used for this link when it gets inserted into an Org-mode
10320 buffer with \\[org-insert-link].")
10322 (defvar org-execute-file-search-functions nil
10323 "List of functions to execute a file search triggered by a link.
10325 Functions added to this hook must accept a single argument, the
10326 search string that was part of the file link, the part after the
10327 double colon. The function must first check if it would like to
10328 handle this search, for example by checking the `major-mode' or
10329 the file extension. If it decides not to handle this search, it
10330 should just return nil to give other functions a chance. If it
10331 does handle the search, it must return a non-nil value to keep
10332 other functions from trying.
10334 Each function can access the current prefix argument through the
10335 variable `current-prefix-argument'. Note that a single prefix is
10336 used to force opening a link in Emacs, so it may be good to only
10337 use a numeric or double prefix to guide the search function.
10339 In case this is needed, a function in this hook can also restore
10340 the window configuration before `org-open-at-point' was called using:
10342 (set-window-configuration org-window-config-before-follow-link)")
10344 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10345 (defun org-link-search (s &optional type avoid-pos stealth)
10346 "Search for a link search option.
10347 If S is surrounded by forward slashes, it is interpreted as a
10348 regular expression. In org-mode files, this will create an `org-occur'
10349 sparse tree. In ordinary files, `occur' will be used to list matches.
10350 If the current buffer is in `dired-mode', grep will be used to search
10351 in all files. If AVOID-POS is given, ignore matches near that position.
10353 When optional argument STEALTH is non-nil, do not modify
10354 visibility around point, thus ignoring
10355 `org-show-hierarchy-above', `org-show-following-heading' and
10356 `org-show-siblings' variables."
10357 (let ((case-fold-search t)
10358 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10359 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10360 (append '(("") (" ") ("\t") ("\n"))
10361 org-emphasis-alist)
10362 "\\|") "\\)"))
10363 (pos (point))
10364 (pre nil) (post nil)
10365 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10366 (cond
10367 ;; First check if there are any special search functions
10368 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10369 ;; Now try the builtin stuff
10370 ((and (equal (string-to-char s0) ?#)
10371 (> (length s0) 1)
10372 (save-excursion
10373 (goto-char (point-min))
10374 (and
10375 (re-search-forward
10376 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10377 (setq type 'dedicated
10378 pos (match-beginning 0))))
10379 ;; There is an exact target for this
10380 (goto-char pos)
10381 (org-back-to-heading t)))
10382 ((save-excursion
10383 (goto-char (point-min))
10384 (and
10385 (re-search-forward
10386 (concat "<<" (regexp-quote s0) ">>") nil t)
10387 (setq type 'dedicated
10388 pos (match-beginning 0))))
10389 ;; There is an exact target for this
10390 (goto-char pos))
10391 ((save-excursion
10392 (goto-char (point-min))
10393 (and
10394 (re-search-forward
10395 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10396 (setq type 'dedicated pos (match-beginning 0))))
10397 ;; Found an invisible target.
10398 (goto-char pos))
10399 ((save-excursion
10400 (goto-char (point-min))
10401 (and
10402 (re-search-forward
10403 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10404 (setq type 'dedicated pos (match-beginning 0))))
10405 ;; Found an element with a matching #+name affiliated keyword.
10406 (goto-char pos))
10407 ((and (string-match "^(\\(.*\\))$" s0)
10408 (save-excursion
10409 (goto-char (point-min))
10410 (and
10411 (re-search-forward
10412 (concat "[^[]" (regexp-quote
10413 (format org-coderef-label-format
10414 (match-string 1 s0))))
10415 nil t)
10416 (setq type 'dedicated
10417 pos (1+ (match-beginning 0))))))
10418 ;; There is a coderef target for this
10419 (goto-char pos))
10420 ((string-match "^/\\(.*\\)/$" s)
10421 ;; A regular expression
10422 (cond
10423 ((derived-mode-p 'org-mode)
10424 (org-occur (match-string 1 s)))
10425 (t (org-do-occur (match-string 1 s)))))
10426 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10427 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10428 (goto-char (point-min))
10429 (cond
10430 ((let (case-fold-search)
10431 (re-search-forward (format org-complex-heading-regexp-format
10432 (regexp-quote s))
10433 nil t))
10434 ;; OK, found a match
10435 (setq type 'dedicated)
10436 (goto-char (match-beginning 0)))
10437 ((and (not org-link-search-inhibit-query)
10438 (eq org-link-search-must-match-exact-headline 'query-to-create)
10439 (y-or-n-p "No match - create this as a new heading? "))
10440 (goto-char (point-max))
10441 (or (bolp) (newline))
10442 (insert "* " s "\n")
10443 (beginning-of-line 0))
10445 (goto-char pos)
10446 (error "No match"))))
10448 ;; A normal search string
10449 (when (equal (string-to-char s) ?*)
10450 ;; Anchor on headlines, post may include tags.
10451 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10452 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10453 s (substring s 1)))
10454 (remove-text-properties
10455 0 (length s)
10456 '(face nil mouse-face nil keymap nil fontified nil) s)
10457 ;; Make a series of regular expressions to find a match
10458 (setq words (org-split-string s "[ \n\r\t]+")
10460 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10461 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10462 "\\)" markers)
10463 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10464 re2a (concat "[ \t\r\n]" re2a_)
10465 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10466 re4 (concat "[^a-zA-Z_]" re4_)
10468 re1 (concat pre re2 post)
10469 re3 (concat pre (if pre re4_ re4) post)
10470 re5 (concat pre ".*" re4)
10471 re2 (concat pre re2)
10472 re2a (concat pre (if pre re2a_ re2a))
10473 re4 (concat pre (if pre re4_ re4))
10474 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10475 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10476 re5 "\\)"
10478 (cond
10479 ((eq type 'org-occur) (org-occur reall))
10480 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10481 (t (goto-char (point-min))
10482 (setq type 'fuzzy)
10483 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10484 (org-search-not-self 1 re1 nil t)
10485 (org-search-not-self 1 re2 nil t)
10486 (org-search-not-self 1 re2a nil t)
10487 (org-search-not-self 1 re3 nil t)
10488 (org-search-not-self 1 re4 nil t)
10489 (org-search-not-self 1 re5 nil t)
10491 (goto-char (match-beginning 1))
10492 (goto-char pos)
10493 (error "No match"))))))
10494 (and (derived-mode-p 'org-mode)
10495 (not stealth)
10496 (org-show-context 'link-search))
10497 type))
10499 (defun org-search-not-self (group &rest args)
10500 "Execute `re-search-forward', but only accept matches that do not
10501 enclose the position of `org-open-link-marker'."
10502 (let ((m org-open-link-marker))
10503 (catch 'exit
10504 (while (apply 're-search-forward args)
10505 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10506 (goto-char (match-end group))
10507 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10508 (> (match-beginning 0) (marker-position m))
10509 (< (match-end 0) (marker-position m)))
10510 (save-match-data
10511 (or (not (org-in-regexp
10512 org-bracket-link-analytic-regexp 1))
10513 (not (match-end 4)) ; no description
10514 (and (<= (match-beginning 4) (point))
10515 (>= (match-end 4) (point))))))
10516 (throw 'exit (point))))))))
10518 (defun org-get-buffer-for-internal-link (buffer)
10519 "Return a buffer to be used for displaying the link target of internal links."
10520 (cond
10521 ((not org-display-internal-link-with-indirect-buffer)
10522 buffer)
10523 ((string-match "(Clone)$" (buffer-name buffer))
10524 (message "Buffer is already a clone, not making another one")
10525 ;; we also do not modify visibility in this case
10526 buffer)
10527 (t ; make a new indirect buffer for displaying the link
10528 (let* ((bn (buffer-name buffer))
10529 (ibn (concat bn "(Clone)"))
10530 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10531 (with-current-buffer ib (org-overview))
10532 ib))))
10534 (defun org-do-occur (regexp &optional cleanup)
10535 "Call the Emacs command `occur'.
10536 If CLEANUP is non-nil, remove the printout of the regular expression
10537 in the *Occur* buffer. This is useful if the regex is long and not useful
10538 to read."
10539 (occur regexp)
10540 (when cleanup
10541 (let ((cwin (selected-window)) win beg end)
10542 (when (setq win (get-buffer-window "*Occur*"))
10543 (select-window win))
10544 (goto-char (point-min))
10545 (when (re-search-forward "match[a-z]+" nil t)
10546 (setq beg (match-end 0))
10547 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10548 (setq end (1- (match-beginning 0)))))
10549 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10550 (goto-char (point-min))
10551 (select-window cwin))))
10553 ;;; The mark ring for links jumps
10555 (defvar org-mark-ring nil
10556 "Mark ring for positions before jumps in Org-mode.")
10557 (defvar org-mark-ring-last-goto nil
10558 "Last position in the mark ring used to go back.")
10559 ;; Fill and close the ring
10560 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10561 (loop for i from 1 to org-mark-ring-length do
10562 (push (make-marker) org-mark-ring))
10563 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10564 org-mark-ring)
10566 (defun org-mark-ring-push (&optional pos buffer)
10567 "Put the current position or POS into the mark ring and rotate it."
10568 (interactive)
10569 (setq pos (or pos (point)))
10570 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10571 (move-marker (car org-mark-ring)
10572 (or pos (point))
10573 (or buffer (current-buffer)))
10574 (message "%s"
10575 (substitute-command-keys
10576 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10578 (defun org-mark-ring-goto (&optional n)
10579 "Jump to the previous position in the mark ring.
10580 With prefix arg N, jump back that many stored positions. When
10581 called several times in succession, walk through the entire ring.
10582 Org-mode commands jumping to a different position in the current file,
10583 or to another Org-mode file, automatically push the old position
10584 onto the ring."
10585 (interactive "p")
10586 (let (p m)
10587 (if (eq last-command this-command)
10588 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10589 (setq p org-mark-ring))
10590 (setq org-mark-ring-last-goto p)
10591 (setq m (car p))
10592 (org-pop-to-buffer-same-window (marker-buffer m))
10593 (goto-char m)
10594 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10596 (defun org-remove-angle-brackets (s)
10597 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10598 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10600 (defun org-add-angle-brackets (s)
10601 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10602 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10604 (defun org-remove-double-quotes (s)
10605 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10606 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10609 ;;; Following specific links
10611 (defun org-follow-timestamp-link ()
10612 "Open an agenda view for the time-stamp date/range at point."
10613 (cond
10614 ((org-at-date-range-p t)
10615 (let ((org-agenda-start-on-weekday)
10616 (t1 (match-string 1))
10617 (t2 (match-string 2)) tt1 tt2)
10618 (setq tt1 (time-to-days (org-time-string-to-time t1))
10619 tt2 (time-to-days (org-time-string-to-time t2)))
10620 (let ((org-agenda-buffer-tmp-name
10621 (format "*Org Agenda(a:%s)"
10622 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10623 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10624 ((org-at-timestamp-p t)
10625 (let ((org-agenda-buffer-tmp-name
10626 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10627 (org-agenda-list nil (time-to-days (org-time-string-to-time
10628 (substring (match-string 1) 0 10)))
10629 1)))
10630 (t (error "This should not happen"))))
10633 ;;; Following file links
10634 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10635 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10636 (declare-function mailcap-mime-info
10637 "mailcap" (string &optional request no-decode))
10638 (defvar org-wait nil)
10639 (defun org-open-file (path &optional in-emacs line search)
10640 "Open the file at PATH.
10641 First, this expands any special file name abbreviations. Then the
10642 configuration variable `org-file-apps' is checked if it contains an
10643 entry for this file type, and if yes, the corresponding command is launched.
10645 If no application is found, Emacs simply visits the file.
10647 With optional prefix argument IN-EMACS, Emacs will visit the file.
10648 With a double \\[universal-argument] \\[universal-argument] \
10649 prefix arg, Org tries to avoid opening in Emacs
10650 and to use an external application to visit the file.
10652 Optional LINE specifies a line to go to, optional SEARCH a string
10653 to search for. If LINE or SEARCH is given, the file will be
10654 opened in Emacs, unless an entry from org-file-apps that makes
10655 use of groups in a regexp matches.
10657 If you want to change the way frames are used when following a
10658 link, please customize `org-link-frame-setup'.
10660 If the file does not exist, an error is thrown."
10661 (let* ((file (if (equal path "")
10662 buffer-file-name
10663 (substitute-in-file-name (expand-file-name path))))
10664 (file-apps (append org-file-apps (org-default-apps)))
10665 (apps (org-remove-if
10666 'org-file-apps-entry-match-against-dlink-p file-apps))
10667 (apps-dlink (org-remove-if-not
10668 'org-file-apps-entry-match-against-dlink-p file-apps))
10669 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10670 (dirp (if remp nil (file-directory-p file)))
10671 (file (if (and dirp org-open-directory-means-index-dot-org)
10672 (concat (file-name-as-directory file) "index.org")
10673 file))
10674 (a-m-a-p (assq 'auto-mode apps))
10675 (dfile (downcase file))
10676 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10677 (link (cond ((and (eq line nil)
10678 (eq search nil))
10679 file)
10680 (line
10681 (concat file "::" (number-to-string line)))
10682 (search
10683 (concat file "::" search))))
10684 (dlink (downcase link))
10685 (old-buffer (current-buffer))
10686 (old-pos (point))
10687 (old-mode major-mode)
10688 ext cmd link-match-data)
10689 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10690 (setq ext (match-string 1 dfile))
10691 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10692 (setq ext (match-string 1 dfile))))
10693 (cond
10694 ((member in-emacs '((16) system))
10695 (setq cmd (cdr (assoc 'system apps))))
10696 (in-emacs (setq cmd 'emacs))
10698 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10699 (and dirp (cdr (assoc 'directory apps)))
10700 ; first, try matching against apps-dlink
10701 ; if we get a match here, store the match data for later
10702 (let ((match (assoc-default dlink apps-dlink
10703 'string-match)))
10704 (if match
10705 (progn (setq link-match-data (match-data))
10706 match)
10707 (progn (setq in-emacs (or in-emacs line search))
10708 nil))) ; if we have no match in apps-dlink,
10709 ; always open the file in emacs if line or search
10710 ; is given (for backwards compatibility)
10711 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10712 'string-match)
10713 (cdr (assoc ext apps))
10714 (cdr (assoc t apps))))))
10715 (when (eq cmd 'system)
10716 (setq cmd (cdr (assoc 'system apps))))
10717 (when (eq cmd 'default)
10718 (setq cmd (cdr (assoc t apps))))
10719 (when (eq cmd 'mailcap)
10720 (require 'mailcap)
10721 (mailcap-parse-mailcaps)
10722 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10723 (command (mailcap-mime-info mime-type)))
10724 (if (stringp command)
10725 (setq cmd command)
10726 (setq cmd 'emacs))))
10727 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10728 (not (file-exists-p file))
10729 (not org-open-non-existing-files))
10730 (error "No such file: %s" file))
10731 (cond
10732 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10733 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10734 (while (string-match "['\"]%s['\"]" cmd)
10735 (setq cmd (replace-match "%s" t t cmd)))
10736 (while (string-match "%s" cmd)
10737 (setq cmd (replace-match
10738 (save-match-data
10739 (shell-quote-argument
10740 (convert-standard-filename file)))
10741 t t cmd)))
10743 ;; Replace "%1", "%2" etc. in command with group matches from regex
10744 (save-match-data
10745 (let ((match-index 1)
10746 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10747 (set-match-data link-match-data)
10748 (while (<= match-index number-of-groups)
10749 (let ((regex (concat "%" (number-to-string match-index)))
10750 (replace-with (match-string match-index dlink)))
10751 (while (string-match regex cmd)
10752 (setq cmd (replace-match replace-with t t cmd))))
10753 (setq match-index (+ match-index 1)))))
10755 (save-window-excursion
10756 (message "Running %s...done" cmd)
10757 (start-process-shell-command cmd nil cmd)
10758 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10759 ((or (stringp cmd)
10760 (eq cmd 'emacs))
10761 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10762 (widen)
10763 (if line (org-goto-line line)
10764 (if search (org-link-search search))))
10765 ((consp cmd)
10766 (let ((file (convert-standard-filename file)))
10767 (save-match-data
10768 (set-match-data link-match-data)
10769 (eval cmd))))
10770 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10771 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10772 (or (not (equal old-buffer (current-buffer)))
10773 (not (equal old-pos (point))))
10774 (org-mark-ring-push old-pos old-buffer))))
10776 (defun org-file-apps-entry-match-against-dlink-p (entry)
10777 "This function returns non-nil if `entry' uses a regular
10778 expression which should be matched against the whole link by
10779 org-open-file.
10781 It assumes that is the case when the entry uses a regular
10782 expression which has at least one grouping construct and the
10783 action is either a lisp form or a command string containing
10784 '%1', i.e. using at least one subexpression match as a
10785 parameter."
10786 (let ((selector (car entry))
10787 (action (cdr entry)))
10788 (if (stringp selector)
10789 (and (> (regexp-opt-depth selector) 0)
10790 (or (and (stringp action)
10791 (string-match "%[0-9]" action))
10792 (consp action)))
10793 nil)))
10795 (defun org-default-apps ()
10796 "Return the default applications for this operating system."
10797 (cond
10798 ((eq system-type 'darwin)
10799 org-file-apps-defaults-macosx)
10800 ((eq system-type 'windows-nt)
10801 org-file-apps-defaults-windowsnt)
10802 (t org-file-apps-defaults-gnu)))
10804 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10805 "Convert extensions to regular expressions in the cars of LIST.
10806 Also, weed out any non-string entries, because the return value is used
10807 only for regexp matching.
10808 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10809 point to the symbol `emacs', indicating that the file should
10810 be opened in Emacs."
10811 (append
10812 (delq nil
10813 (mapcar (lambda (x)
10814 (if (not (stringp (car x)))
10816 (if (string-match "\\W" (car x))
10818 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10819 list))
10820 (if add-auto-mode
10821 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10823 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10824 (defun org-file-remote-p (file)
10825 "Test whether FILE specifies a location on a remote system.
10826 Return non-nil if the location is indeed remote.
10828 For example, the filename \"/user@host:/foo\" specifies a location
10829 on the system \"/user@host:\"."
10830 (cond ((fboundp 'file-remote-p)
10831 (file-remote-p file))
10832 ((fboundp 'tramp-handle-file-remote-p)
10833 (tramp-handle-file-remote-p file))
10834 ((and (boundp 'ange-ftp-name-format)
10835 (string-match (car ange-ftp-name-format) file))
10836 t)))
10839 ;;;; Refiling
10841 (defun org-get-org-file ()
10842 "Read a filename, with default directory `org-directory'."
10843 (let ((default (or org-default-notes-file remember-data-file)))
10844 (read-file-name (format "File name [%s]: " default)
10845 (file-name-as-directory org-directory)
10846 default)))
10848 (defun org-notes-order-reversed-p ()
10849 "Check if the current file should receive notes in reversed order."
10850 (cond
10851 ((not org-reverse-note-order) nil)
10852 ((eq t org-reverse-note-order) t)
10853 ((not (listp org-reverse-note-order)) nil)
10854 (t (catch 'exit
10855 (let ((all org-reverse-note-order)
10856 entry)
10857 (while (setq entry (pop all))
10858 (if (string-match (car entry) buffer-file-name)
10859 (throw 'exit (cdr entry))))
10860 nil)))))
10862 (defvar org-refile-target-table nil
10863 "The list of refile targets, created by `org-refile'.")
10865 (defvar org-agenda-new-buffers nil
10866 "Buffers created to visit agenda files.")
10868 (defvar org-refile-cache nil
10869 "Cache for refile targets.")
10871 (defvar org-refile-markers nil
10872 "All the markers used for caching refile locations.")
10874 (defun org-refile-marker (pos)
10875 "Get a new refile marker, but only if caching is in use."
10876 (if (not org-refile-use-cache)
10878 (let ((m (make-marker)))
10879 (move-marker m pos)
10880 (push m org-refile-markers)
10881 m)))
10883 (defun org-refile-cache-clear ()
10884 "Clear the refile cache and disable all the markers."
10885 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10886 (setq org-refile-markers nil)
10887 (setq org-refile-cache nil)
10888 (message "Refile cache has been cleared"))
10890 (defun org-refile-cache-check-set (set)
10891 "Check if all the markers in the cache still have live buffers."
10892 (let (marker)
10893 (catch 'exit
10894 (while (and set (setq marker (nth 3 (pop set))))
10895 ;; if org-refile-use-outline-path is 'file, marker may be nil
10896 (when (and marker (null (marker-buffer marker)))
10897 (message "not found") (sit-for 3)
10898 (throw 'exit nil)))
10899 t)))
10901 (defun org-refile-cache-put (set &rest identifiers)
10902 "Push the refile targets SET into the cache, under IDENTIFIERS."
10903 (let* ((key (sha1 (prin1-to-string identifiers)))
10904 (entry (assoc key org-refile-cache)))
10905 (if entry
10906 (setcdr entry set)
10907 (push (cons key set) org-refile-cache))))
10909 (defun org-refile-cache-get (&rest identifiers)
10910 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10911 (cond
10912 ((not org-refile-cache) nil)
10913 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10915 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10916 org-refile-cache))))
10917 (and set (org-refile-cache-check-set set) set)))))
10919 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10920 "Produce a table with refile targets."
10921 (let ((case-fold-search nil)
10922 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10923 (entries (or org-refile-targets '((nil . (:level . 1)))))
10924 targets tgs txt re files f desc descre fast-path-p level pos0)
10925 (message "Getting targets...")
10926 (with-current-buffer (or default-buffer (current-buffer))
10927 (while (setq entry (pop entries))
10928 (setq files (car entry) desc (cdr entry))
10929 (setq fast-path-p nil)
10930 (cond
10931 ((null files) (setq files (list (current-buffer))))
10932 ((eq files 'org-agenda-files)
10933 (setq files (org-agenda-files 'unrestricted)))
10934 ((and (symbolp files) (fboundp files))
10935 (setq files (funcall files)))
10936 ((and (symbolp files) (boundp files))
10937 (setq files (symbol-value files))))
10938 (if (stringp files) (setq files (list files)))
10939 (cond
10940 ((eq (car desc) :tag)
10941 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10942 ((eq (car desc) :todo)
10943 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10944 ((eq (car desc) :regexp)
10945 (setq descre (cdr desc)))
10946 ((eq (car desc) :level)
10947 (setq descre (concat "^\\*\\{" (number-to-string
10948 (if org-odd-levels-only
10949 (1- (* 2 (cdr desc)))
10950 (cdr desc)))
10951 "\\}[ \t]")))
10952 ((eq (car desc) :maxlevel)
10953 (setq fast-path-p t)
10954 (setq descre (concat "^\\*\\{1," (number-to-string
10955 (if org-odd-levels-only
10956 (1- (* 2 (cdr desc)))
10957 (cdr desc)))
10958 "\\}[ \t]")))
10959 (t (error "Bad refiling target description %s" desc)))
10960 (while (setq f (pop files))
10961 (with-current-buffer
10962 (if (bufferp f) f (org-get-agenda-file-buffer f))
10964 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10965 (progn
10966 (if (bufferp f) (setq f (buffer-file-name
10967 (buffer-base-buffer f))))
10968 (setq f (and f (expand-file-name f)))
10969 (if (eq org-refile-use-outline-path 'file)
10970 (push (list (file-name-nondirectory f) f nil nil) tgs))
10971 (save-excursion
10972 (save-restriction
10973 (widen)
10974 (goto-char (point-min))
10975 (while (re-search-forward descre nil t)
10976 (goto-char (setq pos0 (point-at-bol)))
10977 (catch 'next
10978 (when org-refile-target-verify-function
10979 (save-match-data
10980 (or (funcall org-refile-target-verify-function)
10981 (throw 'next t))))
10982 (when (and (looking-at org-complex-heading-regexp)
10983 (not (member (match-string 4) excluded-entries))
10984 (match-string 4))
10985 (setq level (org-reduced-level
10986 (- (match-end 1) (match-beginning 1)))
10987 txt (org-link-display-format (match-string 4))
10988 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10989 re (format org-complex-heading-regexp-format
10990 (regexp-quote (match-string 4))))
10991 (when org-refile-use-outline-path
10992 (setq txt (mapconcat
10993 'org-protect-slash
10994 (append
10995 (if (eq org-refile-use-outline-path
10996 'file)
10997 (list (file-name-nondirectory
10998 (buffer-file-name
10999 (buffer-base-buffer))))
11000 (if (eq org-refile-use-outline-path
11001 'full-file-path)
11002 (list (buffer-file-name
11003 (buffer-base-buffer)))))
11004 (org-get-outline-path fast-path-p
11005 level txt)
11006 (list txt))
11007 "/")))
11008 (push (list txt f re (org-refile-marker (point)))
11009 tgs)))
11010 (when (= (point) pos0)
11011 ;; verification function has not moved point
11012 (goto-char (point-at-eol))))))))
11013 (when org-refile-use-cache
11014 (org-refile-cache-put tgs (buffer-file-name) descre))
11015 (setq targets (append tgs targets))
11016 ))))
11017 (message "Getting targets...done")
11018 (nreverse targets)))
11020 (defun org-protect-slash (s)
11021 (while (string-match "/" s)
11022 (setq s (replace-match "\\" t t s)))
11025 (defvar org-olpa (make-vector 20 nil))
11027 (defun org-get-outline-path (&optional fastp level heading)
11028 "Return the outline path to the current entry, as a list.
11030 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11031 routine which makes outline path derivations for an entire file,
11032 avoiding backtracing. Refile target collection makes use of that."
11033 (if fastp
11034 (progn
11035 (if (> level 19)
11036 (error "Outline path failure, more than 19 levels"))
11037 (loop for i from level upto 19 do
11038 (aset org-olpa i nil))
11039 (prog1
11040 (delq nil (append org-olpa nil))
11041 (aset org-olpa level heading)))
11042 (let (rtn case-fold-search)
11043 (save-excursion
11044 (save-restriction
11045 (widen)
11046 (while (org-up-heading-safe)
11047 (when (looking-at org-complex-heading-regexp)
11048 (push (org-match-string-no-properties 4) rtn)))
11049 rtn)))))
11051 (defun org-format-outline-path (path &optional width prefix separator)
11052 "Format the outline path PATH for display.
11053 WIDTH is the maximum number of characters that is available.
11054 PREFIX is a prefix to be included in the returned string,
11055 such as the file name.
11056 SEPARATOR is inserted between the different parts of the path,
11057 the default is \"/\"."
11058 (setq width (or width 79))
11059 (if prefix (setq width (- width (length prefix))))
11060 (if (not path)
11061 (or prefix "")
11062 (let* ((nsteps (length path))
11063 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11064 (maxwidth (if (<= total-width width)
11065 10000 ;; everything fits
11066 ;; we need to shorten the level headings
11067 (/ (- width nsteps) nsteps)))
11068 (org-odd-levels-only nil)
11069 (n 0)
11070 (total (1+ (length prefix))))
11071 (setq maxwidth (max maxwidth 10))
11072 (concat prefix
11073 (if prefix (or separator "/"))
11074 (mapconcat
11075 (lambda (h)
11076 (setq n (1+ n))
11077 (if (and (= n nsteps) (< maxwidth 10000))
11078 (setq maxwidth (- total-width total)))
11079 (if (< (length h) maxwidth)
11080 (progn (setq total (+ total (length h) 1)) h)
11081 (setq h (substring h 0 (- maxwidth 2))
11082 total (+ total maxwidth 1))
11083 (if (string-match "[ \t]+\\'" h)
11084 (setq h (substring h 0 (match-beginning 0))))
11085 (setq h (concat h "..")))
11086 (org-add-props h nil 'face
11087 (nth (% (1- n) org-n-level-faces)
11088 org-level-faces))
11090 path (or separator "/"))))))
11092 (defun org-display-outline-path (&optional file current separator just-return-string)
11093 "Display the current outline path in the echo area.
11095 If FILE is non-nil, prepend the output with the file name.
11096 If CURRENT is non-nil, append the current heading to the output.
11097 SEPARATOR is passed through to `org-format-outline-path'. It separates
11098 the different parts of the path and defaults to \"/\".
11099 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11100 (interactive "P")
11101 (let* (case-fold-search
11102 message-log-max ; Don't populate the *Messages* buffer
11103 (bfn (buffer-file-name (buffer-base-buffer)))
11104 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11105 res)
11106 (if current (setq path (append path
11107 (save-excursion
11108 (org-back-to-heading t)
11109 (if (looking-at org-complex-heading-regexp)
11110 (list (match-string 4)))))))
11111 (setq res
11112 (org-format-outline-path
11113 path
11114 (1- (frame-width))
11115 (and file bfn (concat (file-name-nondirectory bfn) separator))
11116 separator))
11117 (if just-return-string
11118 (org-no-properties res)
11119 (message "%s" res))))
11121 (defvar org-refile-history nil
11122 "History for refiling operations.")
11124 (defvar org-after-refile-insert-hook nil
11125 "Hook run after `org-refile' has inserted its stuff at the new location.
11126 Note that this is still *before* the stuff will be removed from
11127 the *old* location.")
11129 (defvar org-capture-last-stored-marker)
11130 (defvar org-refile-keep nil
11131 "Non-nil means `org-refile' will copy instead of refile.")
11133 (defun org-copy ()
11134 "Like `org-refile', but copy."
11135 (interactive)
11136 (let ((org-refile-keep t))
11137 (funcall 'org-refile nil nil nil "Copy")))
11139 (defun org-refile (&optional goto default-buffer rfloc msg)
11140 "Move the entry or entries at point to another heading.
11141 The list of target headings is compiled using the information in
11142 `org-refile-targets', which see.
11144 At the target location, the entry is filed as a subitem of the target
11145 heading. Depending on `org-reverse-note-order', the new subitem will
11146 either be the first or the last subitem.
11148 If there is an active region, all entries in that region will be moved.
11149 However, the region must fulfill the requirement that the first heading
11150 is the first one sets the top-level of the moved text - at most siblings
11151 below it are allowed.
11153 With prefix arg GOTO, the command will only visit the target location
11154 and not actually move anything.
11156 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11157 go to the location where the last refiling operation has put the subtree.
11158 With a prefix argument of `2', refile to the running clock.
11160 RFLOC can be a refile location obtained in a different way.
11162 MSG is a string to replace \"Refile\" in the default prompt with
11163 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11165 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11167 If you are using target caching (see `org-refile-use-cache'),
11168 you have to clear the target cache in order to find new targets.
11169 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11170 prefix argument (`C-u C-u C-u C-c C-w')."
11172 (interactive "P")
11173 (if (member goto '(0 (64)))
11174 (org-refile-cache-clear)
11175 (let* ((actionmsg (or msg "Refile"))
11176 (cbuf (current-buffer))
11177 (regionp (org-region-active-p))
11178 (region-start (and regionp (region-beginning)))
11179 (region-end (and regionp (region-end)))
11180 (region-length (and regionp (- region-end region-start)))
11181 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11182 pos it nbuf file re level reversed)
11183 (setq last-command nil)
11184 (when regionp
11185 (goto-char region-start)
11186 (or (bolp) (goto-char (point-at-bol)))
11187 (setq region-start (point))
11188 (unless (or (org-kill-is-subtree-p
11189 (buffer-substring region-start region-end))
11190 (prog1 org-refile-active-region-within-subtree
11191 (org-toggle-heading)))
11192 (error "The region is not a (sequence of) subtree(s)")))
11193 (if (equal goto '(16))
11194 (org-refile-goto-last-stored)
11195 (when (or
11196 (and (equal goto 2)
11197 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11198 (prog1
11199 (setq it (list (or org-clock-heading "running clock")
11200 (buffer-file-name
11201 (marker-buffer org-clock-hd-marker))
11203 (marker-position org-clock-hd-marker)))
11204 (setq goto nil)))
11205 (setq it (or rfloc
11206 (let (heading-text)
11207 (save-excursion
11208 (unless goto
11209 (org-back-to-heading t)
11210 (setq heading-text
11211 (nth 4 (org-heading-components))))
11213 (org-refile-get-location
11214 (cond (goto "Goto")
11215 (regionp (concat actionmsg " region to"))
11216 (t (concat actionmsg " subtree \""
11217 heading-text "\" to")))
11218 default-buffer
11219 (and (not (equal '(4) goto))
11220 org-refile-allow-creating-parent-nodes)
11221 goto))))))
11222 (setq file (nth 1 it)
11223 re (nth 2 it)
11224 pos (nth 3 it))
11225 (if (and (not goto)
11227 (equal (buffer-file-name) file)
11228 (if regionp
11229 (and (>= pos region-start)
11230 (<= pos region-end))
11231 (and (>= pos (point))
11232 (< pos (save-excursion
11233 (org-end-of-subtree t t))))))
11234 (error "Cannot refile to position inside the tree or region"))
11236 (setq nbuf (or (find-buffer-visiting file)
11237 (find-file-noselect file)))
11238 (if goto
11239 (progn
11240 (org-pop-to-buffer-same-window nbuf)
11241 (goto-char pos)
11242 (org-show-context 'org-goto))
11243 (if regionp
11244 (progn
11245 (org-kill-new (buffer-substring region-start region-end))
11246 (org-save-markers-in-region region-start region-end))
11247 (org-copy-subtree 1 nil t))
11248 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11249 (find-file-noselect file)))
11250 (setq reversed (org-notes-order-reversed-p))
11251 (save-excursion
11252 (save-restriction
11253 (widen)
11254 (if pos
11255 (progn
11256 (goto-char pos)
11257 (looking-at org-outline-regexp)
11258 (setq level (org-get-valid-level (funcall outline-level) 1))
11259 (goto-char
11260 (if reversed
11261 (or (outline-next-heading) (point-max))
11262 (or (save-excursion (org-get-next-sibling))
11263 (org-end-of-subtree t t)
11264 (point-max)))))
11265 (setq level 1)
11266 (if (not reversed)
11267 (goto-char (point-max))
11268 (goto-char (point-min))
11269 (or (outline-next-heading) (goto-char (point-max)))))
11270 (if (not (bolp)) (newline))
11271 (org-paste-subtree level)
11272 (when org-log-refile
11273 (org-add-log-setup 'refile nil nil 'findpos
11274 org-log-refile)
11275 (unless (eq org-log-refile 'note)
11276 (save-excursion (org-add-log-note))))
11277 (and org-auto-align-tags
11278 (let ((org-loop-over-headlines-in-active-region nil))
11279 (org-set-tags nil t)))
11280 (with-demoted-errors
11281 (bookmark-set "org-refile-last-stored"))
11282 ;; If we are refiling for capture, make sure that the
11283 ;; last-capture pointers point here
11284 (when (org-bound-and-true-p org-refile-for-capture)
11285 (with-demoted-errors
11286 (bookmark-set "org-capture-last-stored-marker"))
11287 (move-marker org-capture-last-stored-marker (point)))
11288 (if (fboundp 'deactivate-mark) (deactivate-mark))
11289 (run-hooks 'org-after-refile-insert-hook))))
11290 (unless org-refile-keep
11291 (if regionp
11292 (delete-region (point) (+ (point) region-length))
11293 (org-cut-subtree)))
11294 (when (featurep 'org-inlinetask)
11295 (org-inlinetask-remove-END-maybe))
11296 (setq org-markers-to-move nil)
11297 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11299 (defun org-refile-goto-last-stored ()
11300 "Go to the location where the last refile was stored."
11301 (interactive)
11302 (bookmark-jump "org-refile-last-stored")
11303 (message "This is the location of the last refile"))
11305 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11306 no-exclude)
11307 "Prompt the user for a refile location, using PROMPT.
11308 PROMPT should not be suffixed with a colon and a space, because
11309 this function appends the default value from
11310 `org-refile-history' automatically, if that is not empty.
11311 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11312 this is used for the GOTO interface."
11313 (let ((org-refile-targets org-refile-targets)
11314 (org-refile-use-outline-path org-refile-use-outline-path)
11315 excluded-entries)
11316 (when (and (derived-mode-p 'org-mode)
11317 (not org-refile-use-cache)
11318 (not no-exclude))
11319 (org-map-tree
11320 (lambda()
11321 (setq excluded-entries
11322 (append excluded-entries (list (org-get-heading t t)))))))
11323 (setq org-refile-target-table
11324 (org-refile-get-targets default-buffer excluded-entries)))
11325 (unless org-refile-target-table
11326 (error "No refile targets"))
11327 (let* ((cbuf (current-buffer))
11328 (partial-completion-mode nil)
11329 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11330 (cfunc (if (and org-refile-use-outline-path
11331 org-outline-path-complete-in-steps)
11332 'org-olpath-completing-read
11333 'org-icompleting-read))
11334 (extra (if org-refile-use-outline-path "/" ""))
11335 (cbnex (concat (buffer-name) extra))
11336 (filename (and cfn (expand-file-name cfn)))
11337 (tbl (mapcar
11338 (lambda (x)
11339 (if (and (not (member org-refile-use-outline-path
11340 '(file full-file-path)))
11341 (not (equal filename (nth 1 x))))
11342 (cons (concat (car x) extra " ("
11343 (file-name-nondirectory (nth 1 x)) ")")
11344 (cdr x))
11345 (cons (concat (car x) extra) (cdr x))))
11346 org-refile-target-table))
11347 (completion-ignore-case t)
11348 cdef
11349 (prompt (concat prompt
11350 (or (and (car org-refile-history)
11351 (concat " (default " (car org-refile-history) ")"))
11352 (and (assoc cbnex tbl) (setq cdef cbnex)
11353 (concat " (default " cbnex ")"))) ": "))
11354 pa answ parent-target child parent old-hist)
11355 (setq old-hist org-refile-history)
11356 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11357 nil 'org-refile-history (or cdef (car org-refile-history))))
11358 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11359 (org-refile-check-position pa)
11360 (if pa
11361 (progn
11362 (when (or (not org-refile-history)
11363 (not (eq old-hist org-refile-history))
11364 (not (equal (car pa) (car org-refile-history))))
11365 (setq org-refile-history
11366 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11367 org-refile-history
11368 (cdr org-refile-history))))
11369 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11370 (pop org-refile-history)))
11372 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11373 (progn
11374 (setq parent (match-string 1 answ)
11375 child (match-string 2 answ))
11376 (setq parent-target (or (assoc parent tbl)
11377 (assoc (concat parent "/") tbl)))
11378 (when (and parent-target
11379 (or (eq new-nodes t)
11380 (and (eq new-nodes 'confirm)
11381 (y-or-n-p (format "Create new node \"%s\"? "
11382 child)))))
11383 (org-refile-new-child parent-target child)))
11384 (error "Invalid target location")))))
11386 (declare-function org-string-nw-p "org-macs" (s))
11387 (defun org-refile-check-position (refile-pointer)
11388 "Check if the refile pointer matches the headline to which it points."
11389 (let* ((file (nth 1 refile-pointer))
11390 (re (nth 2 refile-pointer))
11391 (pos (nth 3 refile-pointer))
11392 buffer)
11393 (if (and (not (markerp pos)) (not file))
11394 (error "Please save the buffer to a file before refiling")
11395 (when (org-string-nw-p re)
11396 (setq buffer (if (markerp pos)
11397 (marker-buffer pos)
11398 (or (find-buffer-visiting file)
11399 (find-file-noselect file))))
11400 (with-current-buffer buffer
11401 (save-excursion
11402 (save-restriction
11403 (widen)
11404 (goto-char pos)
11405 (beginning-of-line 1)
11406 (unless (org-looking-at-p re)
11407 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11409 (defun org-refile-new-child (parent-target child)
11410 "Use refile target PARENT-TARGET to add new CHILD below it."
11411 (unless parent-target
11412 (error "Cannot find parent for new node"))
11413 (let ((file (nth 1 parent-target))
11414 (pos (nth 3 parent-target))
11415 level)
11416 (with-current-buffer (or (find-buffer-visiting file)
11417 (find-file-noselect file))
11418 (save-excursion
11419 (save-restriction
11420 (widen)
11421 (if pos
11422 (goto-char pos)
11423 (goto-char (point-max))
11424 (if (not (bolp)) (newline)))
11425 (when (looking-at org-outline-regexp)
11426 (setq level (funcall outline-level))
11427 (org-end-of-subtree t t))
11428 (org-back-over-empty-lines)
11429 (insert "\n" (make-string
11430 (if pos (org-get-valid-level level 1) 1) ?*)
11431 " " child "\n")
11432 (beginning-of-line 0)
11433 (list (concat (car parent-target) "/" child) file "" (point)))))))
11435 (defun org-olpath-completing-read (prompt collection &rest args)
11436 "Read an outline path like a file name."
11437 (let ((thetable collection)
11438 (org-completion-use-ido nil) ; does not work with ido.
11439 (org-completion-use-iswitchb nil)) ; or iswitchb
11440 (apply
11441 'org-icompleting-read prompt
11442 (lambda (string predicate &optional flag)
11443 (let (rtn r f (l (length string)))
11444 (cond
11445 ((eq flag nil)
11446 ;; try completion
11447 (try-completion string thetable))
11448 ((eq flag t)
11449 ;; all-completions
11450 (setq rtn (all-completions string thetable predicate))
11451 (mapcar
11452 (lambda (x)
11453 (setq r (substring x l))
11454 (if (string-match " ([^)]*)$" x)
11455 (setq f (match-string 0 x))
11456 (setq f ""))
11457 (if (string-match "/" r)
11458 (concat string (substring r 0 (match-end 0)) f)
11460 rtn))
11461 ((eq flag 'lambda)
11462 ;; exact match?
11463 (assoc string thetable)))))
11464 args)))
11466 ;;;; Dynamic blocks
11468 (defun org-find-dblock (name)
11469 "Find the first dynamic block with name NAME in the buffer.
11470 If not found, stay at current position and return nil."
11471 (let ((case-fold-search t) pos)
11472 (save-excursion
11473 (goto-char (point-min))
11474 (setq pos (and (re-search-forward
11475 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11476 (match-beginning 0))))
11477 (if pos (goto-char pos))
11478 pos))
11480 (defconst org-dblock-start-re
11481 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11482 "Matches the start line of a dynamic block, with parameters.")
11484 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11485 "Matches the end of a dynamic block.")
11487 (defun org-create-dblock (plist)
11488 "Create a dynamic block section, with parameters taken from PLIST.
11489 PLIST must contain a :name entry which is used as name of the block."
11490 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11491 (end-of-line 1)
11492 (newline))
11493 (let ((col (current-column))
11494 (name (plist-get plist :name)))
11495 (insert "#+BEGIN: " name)
11496 (while plist
11497 (if (eq (car plist) :name)
11498 (setq plist (cddr plist))
11499 (insert " " (prin1-to-string (pop plist)))))
11500 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11501 (beginning-of-line -2)))
11503 (defun org-prepare-dblock ()
11504 "Prepare dynamic block for refresh.
11505 This empties the block, puts the cursor at the insert position and returns
11506 the property list including an extra property :name with the block name."
11507 (unless (looking-at org-dblock-start-re)
11508 (error "Not at a dynamic block"))
11509 (let* ((begdel (1+ (match-end 0)))
11510 (name (org-no-properties (match-string 1)))
11511 (params (append (list :name name)
11512 (read (concat "(" (match-string 3) ")")))))
11513 (save-excursion
11514 (beginning-of-line 1)
11515 (skip-chars-forward " \t")
11516 (setq params (plist-put params :indentation-column (current-column))))
11517 (unless (re-search-forward org-dblock-end-re nil t)
11518 (error "Dynamic block not terminated"))
11519 (setq params
11520 (append params
11521 (list :content (buffer-substring
11522 begdel (match-beginning 0)))))
11523 (delete-region begdel (match-beginning 0))
11524 (goto-char begdel)
11525 (open-line 1)
11526 params))
11528 (defun org-map-dblocks (&optional command)
11529 "Apply COMMAND to all dynamic blocks in the current buffer.
11530 If COMMAND is not given, use `org-update-dblock'."
11531 (let ((cmd (or command 'org-update-dblock)))
11532 (save-excursion
11533 (goto-char (point-min))
11534 (while (re-search-forward org-dblock-start-re nil t)
11535 (goto-char (match-beginning 0))
11536 (save-excursion
11537 (condition-case nil
11538 (funcall cmd)
11539 (error (message "Error during update of dynamic block"))))
11540 (unless (re-search-forward org-dblock-end-re nil t)
11541 (error "Dynamic block not terminated"))))))
11543 (defun org-dblock-update (&optional arg)
11544 "User command for updating dynamic blocks.
11545 Update the dynamic block at point. With prefix ARG, update all dynamic
11546 blocks in the buffer."
11547 (interactive "P")
11548 (if arg
11549 (org-update-all-dblocks)
11550 (or (looking-at org-dblock-start-re)
11551 (org-beginning-of-dblock))
11552 (org-update-dblock)))
11554 (defun org-update-dblock ()
11555 "Update the dynamic block at point.
11556 This means to empty the block, parse for parameters and then call
11557 the correct writing function."
11558 (interactive)
11559 (save-window-excursion
11560 (let* ((pos (point))
11561 (line (org-current-line))
11562 (params (org-prepare-dblock))
11563 (name (plist-get params :name))
11564 (indent (plist-get params :indentation-column))
11565 (cmd (intern (concat "org-dblock-write:" name))))
11566 (message "Updating dynamic block `%s' at line %d..." name line)
11567 (funcall cmd params)
11568 (message "Updating dynamic block `%s' at line %d...done" name line)
11569 (goto-char pos)
11570 (when (and indent (> indent 0))
11571 (setq indent (make-string indent ?\ ))
11572 (save-excursion
11573 (org-beginning-of-dblock)
11574 (forward-line 1)
11575 (while (not (looking-at org-dblock-end-re))
11576 (insert indent)
11577 (beginning-of-line 2))
11578 (when (looking-at org-dblock-end-re)
11579 (and (looking-at "[ \t]+")
11580 (replace-match ""))
11581 (insert indent)))))))
11583 (defun org-beginning-of-dblock ()
11584 "Find the beginning of the dynamic block at point.
11585 Error if there is no such block at point."
11586 (let ((pos (point))
11587 beg)
11588 (end-of-line 1)
11589 (if (and (re-search-backward org-dblock-start-re nil t)
11590 (setq beg (match-beginning 0))
11591 (re-search-forward org-dblock-end-re nil t)
11592 (> (match-end 0) pos))
11593 (goto-char beg)
11594 (goto-char pos)
11595 (error "Not in a dynamic block"))))
11597 (defun org-update-all-dblocks ()
11598 "Update all dynamic blocks in the buffer.
11599 This function can be used in a hook."
11600 (interactive)
11601 (when (derived-mode-p 'org-mode)
11602 (org-map-dblocks 'org-update-dblock)))
11605 ;;;; Completion
11607 (defun org-get-export-keywords ()
11608 "Return a list of all currently understood export keywords.
11609 Export keywords include options, block names, attributes and
11610 keywords relative to each registered export back-end."
11611 (delq nil
11612 (let (keywords)
11613 (mapc
11614 (lambda (back-end)
11615 (let ((props (cdr back-end)))
11616 ;; Back-end name (for keywords, like #+LATEX:)
11617 (push (upcase (symbol-name (car back-end))) keywords)
11618 ;; Back-end options.
11619 (mapc (lambda (option) (push (cadr option) keywords))
11620 (plist-get (cdr back-end) :options-alist))))
11621 (org-bound-and-true-p org-export-registered-backends))
11622 keywords)))
11624 (defconst org-options-keywords
11625 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11626 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11627 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11628 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11629 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11631 (defcustom org-structure-template-alist
11632 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11633 "<src lang=\"?\">\n\n</src>")
11634 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11635 "<example>\n?\n</example>")
11636 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11637 "<quote>\n?\n</quote>")
11638 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11639 "<verse>\n?\n</verse>")
11640 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11641 "<verbatim>\n?\n</verbatim>")
11642 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11643 "<center>\n?\n</center>")
11644 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11645 "<literal style=\"latex\">\n?\n</literal>")
11646 ("L" "#+LaTeX: "
11647 "<literal style=\"latex\">?</literal>")
11648 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11649 "<literal style=\"html\">\n?\n</literal>")
11650 ("H" "#+HTML: "
11651 "<literal style=\"html\">?</literal>")
11652 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11653 ("A" "#+ASCII: ")
11654 ("i" "#+INDEX: ?"
11655 "#+INDEX: ?")
11656 ("I" "#+INCLUDE: %file ?"
11657 "<include file=%file markup=\"?\">"))
11658 "Structure completion elements.
11659 This is a list of abbreviation keys and values. The value gets inserted
11660 if you type `<' followed by the key and then press the completion key,
11661 usually `M-TAB'. %file will be replaced by a file name after prompting
11662 for the file using completion. The cursor will be placed at the position
11663 of the `?` in the template.
11664 There are two templates for each key, the first uses the original Org syntax,
11665 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11666 the default when the /org-mtags.el/ module has been loaded. See also the
11667 variable `org-mtags-prefer-muse-templates'."
11668 :group 'org-completion
11669 :type '(repeat
11670 (string :tag "Key")
11671 (string :tag "Template")
11672 (string :tag "Muse Template")))
11674 (defun org-try-structure-completion ()
11675 "Try to complete a structure template before point.
11676 This looks for strings like \"<e\" on an otherwise empty line and
11677 expands them."
11678 (let ((l (buffer-substring (point-at-bol) (point)))
11680 (when (and (looking-at "[ \t]*$")
11681 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11682 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11683 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11684 (match-beginning 1)) a)
11685 t)))
11687 (defun org-complete-expand-structure-template (start cell)
11688 "Expand a structure template."
11689 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11690 (rpl (nth (if musep 2 1) cell))
11691 (ind ""))
11692 (delete-region start (point))
11693 (when (string-match "\\`#\\+" rpl)
11694 (cond
11695 ((bolp))
11696 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11697 (setq ind (buffer-substring (point-at-bol) (point))))
11698 (t (newline))))
11699 (setq start (point))
11700 (if (string-match "%file" rpl)
11701 (setq rpl (replace-match
11702 (concat
11703 "\""
11704 (save-match-data
11705 (abbreviate-file-name (read-file-name "Include file: ")))
11706 "\"")
11707 t t rpl)))
11708 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11709 (concat "\n" ind)))
11710 (insert rpl)
11711 (if (re-search-backward "\\?" start t) (delete-char 1))))
11713 ;;;; TODO, DEADLINE, Comments
11715 (defun org-toggle-comment ()
11716 "Change the COMMENT state of an entry."
11717 (interactive)
11718 (save-excursion
11719 (org-back-to-heading)
11720 (let (case-fold-search)
11721 (cond
11722 ((looking-at (format org-heading-keyword-regexp-format
11723 org-comment-string))
11724 (goto-char (match-end 1))
11725 (looking-at (concat " +" org-comment-string))
11726 (replace-match "" t t)
11727 (when (eolp) (insert " ")))
11728 ((looking-at org-outline-regexp)
11729 (goto-char (match-end 0))
11730 (insert org-comment-string " "))))))
11732 (defvar org-last-todo-state-is-todo nil
11733 "This is non-nil when the last TODO state change led to a TODO state.
11734 If the last change removed the TODO tag or switched to DONE, then
11735 this is nil.")
11737 (defvar org-setting-tags nil) ; dynamically skipped
11739 (defvar org-todo-setup-filter-hook nil
11740 "Hook for functions that pre-filter todo specs.
11741 Each function takes a todo spec and returns either nil or the spec
11742 transformed into canonical form." )
11744 (defvar org-todo-get-default-hook nil
11745 "Hook for functions that get a default item for todo.
11746 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11747 nil or a string to be used for the todo mark." )
11749 (defvar org-agenda-headline-snapshot-before-repeat)
11751 (defun org-current-effective-time ()
11752 "Return current time adjusted for `org-extend-today-until' variable."
11753 (let* ((ct (org-current-time))
11754 (dct (decode-time ct))
11755 (ct1
11756 (cond
11757 (org-use-last-clock-out-time-as-effective-time
11758 (or (org-clock-get-last-clock-out-time) ct))
11759 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11760 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11761 (t ct))))
11762 ct1))
11764 (defun org-todo-yesterday (&optional arg)
11765 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11766 (interactive "P")
11767 (if (eq major-mode 'org-agenda-mode)
11768 (apply 'org-agenda-todo-yesterday arg)
11769 (let* ((hour (third (decode-time
11770 (org-current-time))))
11771 (org-extend-today-until (1+ hour)))
11772 (org-todo arg))))
11774 (defvar org-block-entry-blocking ""
11775 "First entry preventing the TODO state change.")
11777 (defun org-todo (&optional arg)
11778 "Change the TODO state of an item.
11779 The state of an item is given by a keyword at the start of the heading,
11780 like
11781 *** TODO Write paper
11782 *** DONE Call mom
11784 The different keywords are specified in the variable `org-todo-keywords'.
11785 By default the available states are \"TODO\" and \"DONE\".
11786 So for this example: when the item starts with TODO, it is changed to DONE.
11787 When it starts with DONE, the DONE is removed. And when neither TODO nor
11788 DONE are present, add TODO at the beginning of the heading.
11790 With \\[universal-argument] prefix arg, use completion to determine the new \
11791 state.
11792 With numeric prefix arg, switch to that state.
11793 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11794 keywords (nextset).
11795 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11796 With a numeric prefix arg of 0, inhibit note taking for the change.
11798 For calling through lisp, arg is also interpreted in the following way:
11799 'none -> empty state
11800 \"\"(empty string) -> switch to empty state
11801 'done -> switch to DONE
11802 'nextset -> switch to the next set of keywords
11803 'previousset -> switch to the previous set of keywords
11804 \"WAITING\" -> switch to the specified keyword, but only if it
11805 really is a member of `org-todo-keywords'."
11806 (interactive "P")
11807 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11808 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11809 'region-start-level 'region))
11810 org-loop-over-headlines-in-active-region)
11811 (org-map-entries
11812 `(org-todo ,arg)
11813 org-loop-over-headlines-in-active-region
11814 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11815 (if (equal arg '(16)) (setq arg 'nextset))
11816 (let ((org-blocker-hook org-blocker-hook)
11817 commentp
11818 case-fold-search)
11819 (when (equal arg '(64))
11820 (setq arg nil org-blocker-hook nil))
11821 (when (and org-blocker-hook
11822 (or org-inhibit-blocking
11823 (org-entry-get nil "NOBLOCKING")))
11824 (setq org-blocker-hook nil))
11825 (save-excursion
11826 (catch 'exit
11827 (org-back-to-heading t)
11828 (when (looking-at (concat "^\\*+ " org-comment-string))
11829 (org-toggle-comment)
11830 (setq commentp t))
11831 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11832 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11833 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11834 (let* ((match-data (match-data))
11835 (startpos (point-at-bol))
11836 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11837 (org-log-done org-log-done)
11838 (org-log-repeat org-log-repeat)
11839 (org-todo-log-states org-todo-log-states)
11840 (org-inhibit-logging
11841 (if (equal arg 0)
11842 (progn (setq arg nil) 'note) org-inhibit-logging))
11843 (this (match-string 1))
11844 (hl-pos (match-beginning 0))
11845 (head (org-get-todo-sequence-head this))
11846 (ass (assoc head org-todo-kwd-alist))
11847 (interpret (nth 1 ass))
11848 (done-word (nth 3 ass))
11849 (final-done-word (nth 4 ass))
11850 (org-last-state (or this ""))
11851 (completion-ignore-case t)
11852 (member (member this org-todo-keywords-1))
11853 (tail (cdr member))
11854 (org-state (cond
11855 ((and org-todo-key-trigger
11856 (or (and (equal arg '(4))
11857 (eq org-use-fast-todo-selection 'prefix))
11858 (and (not arg) org-use-fast-todo-selection
11859 (not (eq org-use-fast-todo-selection
11860 'prefix)))))
11861 ;; Use fast selection
11862 (org-fast-todo-selection))
11863 ((and (equal arg '(4))
11864 (or (not org-use-fast-todo-selection)
11865 (not org-todo-key-trigger)))
11866 ;; Read a state with completion
11867 (org-icompleting-read
11868 "State: " (mapcar (lambda(x) (list x))
11869 org-todo-keywords-1)
11870 nil t))
11871 ((eq arg 'right)
11872 (if this
11873 (if tail (car tail) nil)
11874 (car org-todo-keywords-1)))
11875 ((eq arg 'left)
11876 (if (equal member org-todo-keywords-1)
11878 (if this
11879 (nth (- (length org-todo-keywords-1)
11880 (length tail) 2)
11881 org-todo-keywords-1)
11882 (org-last org-todo-keywords-1))))
11883 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11884 (setq arg nil))) ; hack to fall back to cycling
11885 (arg
11886 ;; user or caller requests a specific state
11887 (cond
11888 ((equal arg "") nil)
11889 ((eq arg 'none) nil)
11890 ((eq arg 'done) (or done-word (car org-done-keywords)))
11891 ((eq arg 'nextset)
11892 (or (car (cdr (member head org-todo-heads)))
11893 (car org-todo-heads)))
11894 ((eq arg 'previousset)
11895 (let ((org-todo-heads (reverse org-todo-heads)))
11896 (or (car (cdr (member head org-todo-heads)))
11897 (car org-todo-heads))))
11898 ((car (member arg org-todo-keywords-1)))
11899 ((stringp arg)
11900 (error "State `%s' not valid in this file" arg))
11901 ((nth (1- (prefix-numeric-value arg))
11902 org-todo-keywords-1))))
11903 ((null member) (or head (car org-todo-keywords-1)))
11904 ((equal this final-done-word) nil) ;; -> make empty
11905 ((null tail) nil) ;; -> first entry
11906 ((memq interpret '(type priority))
11907 (if (eq this-command last-command)
11908 (car tail)
11909 (if (> (length tail) 0)
11910 (or done-word (car org-done-keywords))
11911 nil)))
11913 (car tail))))
11914 (org-state (or
11915 (run-hook-with-args-until-success
11916 'org-todo-get-default-hook org-state org-last-state)
11917 org-state))
11918 (next (if org-state (concat " " org-state " ") " "))
11919 (change-plist (list :type 'todo-state-change :from this :to org-state
11920 :position startpos))
11921 dolog now-done-p)
11922 (when org-blocker-hook
11923 (setq org-last-todo-state-is-todo
11924 (not (member this org-done-keywords)))
11925 (unless (save-excursion
11926 (save-match-data
11927 (org-with-wide-buffer
11928 (run-hook-with-args-until-failure
11929 'org-blocker-hook change-plist))))
11930 (if (org-called-interactively-p 'interactive)
11931 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11932 this org-state org-block-entry-blocking)
11933 ;; fail silently
11934 (message "TODO state change from %s to %s blocked (by \"%s\")"
11935 this org-state org-block-entry-blocking)
11936 (throw 'exit nil))))
11937 (store-match-data match-data)
11938 (replace-match next t t)
11939 (unless (pos-visible-in-window-p hl-pos)
11940 (message "TODO state changed to %s" (org-trim next)))
11941 (unless head
11942 (setq head (org-get-todo-sequence-head org-state)
11943 ass (assoc head org-todo-kwd-alist)
11944 interpret (nth 1 ass)
11945 done-word (nth 3 ass)
11946 final-done-word (nth 4 ass)))
11947 (when (memq arg '(nextset previousset))
11948 (message "Keyword-Set %d/%d: %s"
11949 (- (length org-todo-sets) -1
11950 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11951 (length org-todo-sets)
11952 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11953 (setq org-last-todo-state-is-todo
11954 (not (member org-state org-done-keywords)))
11955 (setq now-done-p (and (member org-state org-done-keywords)
11956 (not (member this org-done-keywords))))
11957 (and logging (org-local-logging logging))
11958 (when (and (or org-todo-log-states org-log-done)
11959 (not (eq org-inhibit-logging t))
11960 (not (memq arg '(nextset previousset))))
11961 ;; we need to look at recording a time and note
11962 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11963 (nth 2 (assoc this org-todo-log-states))))
11964 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11965 (setq dolog 'time))
11966 (when (and org-state
11967 (member org-state org-not-done-keywords)
11968 (not (member this org-not-done-keywords)))
11969 ;; This is now a todo state and was not one before
11970 ;; If there was a CLOSED time stamp, get rid of it.
11971 (org-add-planning-info nil nil 'closed))
11972 (when (and now-done-p org-log-done)
11973 ;; It is now done, and it was not done before
11974 (org-add-planning-info 'closed (org-current-effective-time))
11975 (if (and (not dolog) (eq 'note org-log-done))
11976 (org-add-log-setup 'done org-state this 'findpos 'note)))
11977 (when (and org-state dolog)
11978 ;; This is a non-nil state, and we need to log it
11979 (org-add-log-setup 'state org-state this 'findpos dolog)))
11980 ;; Fixup tag positioning
11981 (org-todo-trigger-tag-changes org-state)
11982 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11983 (when org-provide-todo-statistics
11984 (org-update-parent-todo-statistics))
11985 (run-hooks 'org-after-todo-state-change-hook)
11986 (if (and arg (not (member org-state org-done-keywords)))
11987 (setq head (org-get-todo-sequence-head org-state)))
11988 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11989 ;; Do we need to trigger a repeat?
11990 (when now-done-p
11991 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11992 ;; This is for the agenda, take a snapshot of the headline.
11993 (save-match-data
11994 (setq org-agenda-headline-snapshot-before-repeat
11995 (org-get-heading))))
11996 (org-auto-repeat-maybe org-state))
11997 ;; Fixup cursor location if close to the keyword
11998 (if (and (outline-on-heading-p)
11999 (not (bolp))
12000 (save-excursion (beginning-of-line 1)
12001 (looking-at org-todo-line-regexp))
12002 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12003 (progn
12004 (goto-char (or (match-end 2) (match-end 1)))
12005 (and (looking-at " ") (just-one-space))))
12006 (when org-trigger-hook
12007 (save-excursion
12008 (run-hook-with-args 'org-trigger-hook change-plist)))
12009 (when commentp (org-toggle-comment))))))))
12011 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12012 "Block turning an entry into a TODO, using the hierarchy.
12013 This checks whether the current task should be blocked from state
12014 changes. Such blocking occurs when:
12016 1. The task has children which are not all in a completed state.
12018 2. A task has a parent with the property :ORDERED:, and there
12019 are siblings prior to the current task with incomplete
12020 status.
12022 3. The parent of the task is blocked because it has siblings that should
12023 be done first, or is child of a block grandparent TODO entry."
12025 (if (not org-enforce-todo-dependencies)
12026 t ; if locally turned off don't block
12027 (catch 'dont-block
12028 ;; If this is not a todo state change, or if this entry is already DONE,
12029 ;; do not block
12030 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12031 (member (plist-get change-plist :from)
12032 (cons 'done org-done-keywords))
12033 (member (plist-get change-plist :to)
12034 (cons 'todo org-not-done-keywords))
12035 (not (plist-get change-plist :to)))
12036 (throw 'dont-block t))
12037 ;; If this task has children, and any are undone, it's blocked
12038 (save-excursion
12039 (org-back-to-heading t)
12040 (let ((this-level (funcall outline-level)))
12041 (outline-next-heading)
12042 (let ((child-level (funcall outline-level)))
12043 (while (and (not (eobp))
12044 (> child-level this-level))
12045 ;; this todo has children, check whether they are all
12046 ;; completed
12047 (if (and (not (org-entry-is-done-p))
12048 (org-entry-is-todo-p))
12049 (progn (setq org-block-entry-blocking (org-get-heading))
12050 (throw 'dont-block nil)))
12051 (outline-next-heading)
12052 (setq child-level (funcall outline-level))))))
12053 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12054 ;; any previous siblings are undone, it's blocked
12055 (save-excursion
12056 (org-back-to-heading t)
12057 (let* ((pos (point))
12058 (parent-pos (and (org-up-heading-safe) (point))))
12059 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12060 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12061 (forward-line 1)
12062 (re-search-forward org-not-done-heading-regexp pos t))
12063 (setq org-block-entry-blocking (match-string 0))
12064 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12065 ;; Search further up the hierarchy, to see if an ancestor is blocked
12066 (while t
12067 (goto-char parent-pos)
12068 (if (not (looking-at org-not-done-heading-regexp))
12069 (throw 'dont-block t)) ; do not block, parent is not a TODO
12070 (setq pos (point))
12071 (setq parent-pos (and (org-up-heading-safe) (point)))
12072 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12073 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12074 (forward-line 1)
12075 (re-search-forward org-not-done-heading-regexp pos t)
12076 (setq org-block-entry-blocking (org-get-heading)))
12077 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12079 (defcustom org-track-ordered-property-with-tag nil
12080 "Should the ORDERED property also be shown as a tag?
12081 The ORDERED property decides if an entry should require subtasks to be
12082 completed in sequence. Since a property is not very visible, setting
12083 this option means that toggling the ORDERED property with the command
12084 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12085 not relevant for the behavior, but it makes things more visible.
12087 Note that toggling the tag with tags commands will not change the property
12088 and therefore not influence behavior!
12090 This can be t, meaning the tag ORDERED should be used, It can also be a
12091 string to select a different tag for this task."
12092 :group 'org-todo
12093 :type '(choice
12094 (const :tag "No tracking" nil)
12095 (const :tag "Track with ORDERED tag" t)
12096 (string :tag "Use other tag")))
12098 (defun org-toggle-ordered-property ()
12099 "Toggle the ORDERED property of the current entry.
12100 For better visibility, you can track the value of this property with a tag.
12101 See variable `org-track-ordered-property-with-tag'."
12102 (interactive)
12103 (let* ((t1 org-track-ordered-property-with-tag)
12104 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12105 (save-excursion
12106 (org-back-to-heading)
12107 (if (org-entry-get nil "ORDERED")
12108 (progn
12109 (org-delete-property "ORDERED" "PROPERTIES")
12110 (and tag (org-toggle-tag tag 'off))
12111 (message "Subtasks can be completed in arbitrary order"))
12112 (org-entry-put nil "ORDERED" "t")
12113 (and tag (org-toggle-tag tag 'on))
12114 (message "Subtasks must be completed in sequence")))))
12116 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12117 (defun org-block-todo-from-checkboxes (change-plist)
12118 "Block turning an entry into a TODO, using checkboxes.
12119 This checks whether the current task should be blocked from state
12120 changes because there are unchecked boxes in this entry."
12121 (if (not org-enforce-todo-checkbox-dependencies)
12122 t ; if locally turned off don't block
12123 (catch 'dont-block
12124 ;; If this is not a todo state change, or if this entry is already DONE,
12125 ;; do not block
12126 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12127 (member (plist-get change-plist :from)
12128 (cons 'done org-done-keywords))
12129 (member (plist-get change-plist :to)
12130 (cons 'todo org-not-done-keywords))
12131 (not (plist-get change-plist :to)))
12132 (throw 'dont-block t))
12133 ;; If this task has checkboxes that are not checked, it's blocked
12134 (save-excursion
12135 (org-back-to-heading t)
12136 (let ((beg (point)) end)
12137 (outline-next-heading)
12138 (setq end (point))
12139 (goto-char beg)
12140 (if (org-list-search-forward
12141 (concat (org-item-beginning-re)
12142 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12143 "\\[[- ]\\]")
12144 end t)
12145 (progn
12146 (if (boundp 'org-blocked-by-checkboxes)
12147 (setq org-blocked-by-checkboxes t))
12148 (throw 'dont-block nil)))))
12149 t))) ; do not block
12151 (defun org-entry-blocked-p ()
12152 "Is the current entry blocked?"
12153 (org-with-buffer-modified-unmodified
12154 (if (org-entry-get nil "NOBLOCKING")
12155 nil ;; Never block this entry
12156 (not
12157 (run-hook-with-args-until-failure
12158 'org-blocker-hook
12159 (list :type 'todo-state-change
12160 :position (point)
12161 :from 'todo
12162 :to 'done))))))
12164 (defun org-update-statistics-cookies (all)
12165 "Update the statistics cookie, either from TODO or from checkboxes.
12166 This should be called with the cursor in a line with a statistics cookie."
12167 (interactive "P")
12168 (if all
12169 (progn
12170 (org-update-checkbox-count 'all)
12171 (org-map-entries 'org-update-parent-todo-statistics))
12172 (if (not (org-at-heading-p))
12173 (org-update-checkbox-count)
12174 (let ((pos (point-marker))
12175 end l1 l2)
12176 (ignore-errors (org-back-to-heading t))
12177 (if (not (org-at-heading-p))
12178 (org-update-checkbox-count)
12179 (setq l1 (org-outline-level))
12180 (setq end (save-excursion
12181 (outline-next-heading)
12182 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12183 (point)))
12184 (if (and (save-excursion
12185 (re-search-forward
12186 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12187 (not (save-excursion (re-search-forward
12188 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12189 (org-update-checkbox-count)
12190 (if (and l2 (> l2 l1))
12191 (progn
12192 (goto-char end)
12193 (org-update-parent-todo-statistics))
12194 (goto-char pos)
12195 (beginning-of-line 1)
12196 (while (re-search-forward
12197 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12198 (point-at-eol) t)
12199 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12200 (goto-char pos)
12201 (move-marker pos nil)))))
12203 (defvar org-entry-property-inherited-from) ;; defined below
12204 (defun org-update-parent-todo-statistics ()
12205 "Update any statistics cookie in the parent of the current headline.
12206 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12207 the entire subtree and this will travel up the hierarchy and update
12208 statistics everywhere."
12209 (let* ((prop (save-excursion (org-up-heading-safe)
12210 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12211 (recursive (or (not org-hierarchical-todo-statistics)
12212 (and prop (string-match "\\<recursive\\>" prop))))
12213 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12215 (first t)
12216 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12217 level ltoggle l1 new ndel
12218 (cnt-all 0) (cnt-done 0) is-percent kwd
12219 checkbox-beg ov ovs ove cookie-present)
12220 (catch 'exit
12221 (save-excursion
12222 (beginning-of-line 1)
12223 (setq ltoggle (funcall outline-level))
12224 ;; Three situations are to consider:
12226 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12227 ;; to the top-level ancestor on the headline;
12229 ;; 2. If parent has "recursive" property, repeat up to the
12230 ;; headline setting that property, taking inheritance into
12231 ;; account;
12233 ;; 3. Else, move up to direct parent and proceed only once.
12234 (while (and (setq level (org-up-heading-safe))
12235 (or recursive first)
12236 (>= (point) lim))
12237 (setq first nil cookie-present nil)
12238 (unless (and level
12239 (not (string-match
12240 "\\<checkbox\\>"
12241 (downcase (or (org-entry-get nil "COOKIE_DATA")
12242 "")))))
12243 (throw 'exit nil))
12244 (while (re-search-forward box-re (point-at-eol) t)
12245 (setq cnt-all 0 cnt-done 0 cookie-present t)
12246 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12247 (save-match-data
12248 (unless (outline-next-heading) (throw 'exit nil))
12249 (while (and (looking-at org-complex-heading-regexp)
12250 (> (setq l1 (length (match-string 1))) level))
12251 (setq kwd (and (or recursive (= l1 ltoggle))
12252 (match-string 2)))
12253 (if (or (eq org-provide-todo-statistics 'all-headlines)
12254 (and (listp org-provide-todo-statistics)
12255 (or (member kwd org-provide-todo-statistics)
12256 (member kwd org-done-keywords))))
12257 (setq cnt-all (1+ cnt-all))
12258 (if (eq org-provide-todo-statistics t)
12259 (and kwd (setq cnt-all (1+ cnt-all)))))
12260 (and (member kwd org-done-keywords)
12261 (setq cnt-done (1+ cnt-done)))
12262 (outline-next-heading)))
12263 (setq new
12264 (if is-percent
12265 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12266 (format "[%d/%d]" cnt-done cnt-all))
12267 ndel (- (match-end 0) checkbox-beg))
12268 ;; handle overlays when updating cookie from column view
12269 (when (setq ov (car (overlays-at checkbox-beg)))
12270 (setq ovs (overlay-start ov) ove (overlay-end ov))
12271 (delete-overlay ov))
12272 (goto-char checkbox-beg)
12273 (insert new)
12274 (delete-region (point) (+ (point) ndel))
12275 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12276 (when ov (move-overlay ov ovs ove)))
12277 (when cookie-present
12278 (run-hook-with-args 'org-after-todo-statistics-hook
12279 cnt-done (- cnt-all cnt-done))))))
12280 (run-hooks 'org-todo-statistics-hook)))
12282 (defvar org-after-todo-statistics-hook nil
12283 "Hook that is called after a TODO statistics cookie has been updated.
12284 Each function is called with two arguments: the number of not-done entries
12285 and the number of done entries.
12287 For example, the following function, when added to this hook, will switch
12288 an entry to DONE when all children are done, and back to TODO when new
12289 entries are set to a TODO status. Note that this hook is only called
12290 when there is a statistics cookie in the headline!
12292 (defun org-summary-todo (n-done n-not-done)
12293 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12294 (let (org-log-done org-log-states) ; turn off logging
12295 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12298 (defvar org-todo-statistics-hook nil
12299 "Hook that is run whenever Org thinks TODO statistics should be updated.
12300 This hook runs even if there is no statistics cookie present, in which case
12301 `org-after-todo-statistics-hook' would not run.")
12303 (defun org-todo-trigger-tag-changes (state)
12304 "Apply the changes defined in `org-todo-state-tags-triggers'."
12305 (let ((l org-todo-state-tags-triggers)
12306 changes)
12307 (when (or (not state) (equal state ""))
12308 (setq changes (append changes (cdr (assoc "" l)))))
12309 (when (and (stringp state) (> (length state) 0))
12310 (setq changes (append changes (cdr (assoc state l)))))
12311 (when (member state org-not-done-keywords)
12312 (setq changes (append changes (cdr (assoc 'todo l)))))
12313 (when (member state org-done-keywords)
12314 (setq changes (append changes (cdr (assoc 'done l)))))
12315 (dolist (c changes)
12316 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12318 (defun org-local-logging (value)
12319 "Get logging settings from a property VALUE."
12320 (let* (words w a)
12321 ;; directly set the variables, they are already local.
12322 (setq org-log-done nil
12323 org-log-repeat nil
12324 org-todo-log-states nil)
12325 (setq words (org-split-string value))
12326 (while (setq w (pop words))
12327 (cond
12328 ((setq a (assoc w org-startup-options))
12329 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12330 (set (nth 1 a) (nth 2 a))))
12331 ((setq a (org-extract-log-state-settings w))
12332 (and (member (car a) org-todo-keywords-1)
12333 (push a org-todo-log-states)))))))
12335 (defun org-get-todo-sequence-head (kwd)
12336 "Return the head of the TODO sequence to which KWD belongs.
12337 If KWD is not set, check if there is a text property remembering the
12338 right sequence."
12339 (let (p)
12340 (cond
12341 ((not kwd)
12342 (or (get-text-property (point-at-bol) 'org-todo-head)
12343 (progn
12344 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12345 nil (point-at-eol)))
12346 (get-text-property p 'org-todo-head))))
12347 ((not (member kwd org-todo-keywords-1))
12348 (car org-todo-keywords-1))
12349 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12351 (defun org-fast-todo-selection ()
12352 "Fast TODO keyword selection with single keys.
12353 Returns the new TODO keyword, or nil if no state change should occur."
12354 (let* ((fulltable org-todo-key-alist)
12355 (done-keywords org-done-keywords) ;; needed for the faces.
12356 (maxlen (apply 'max (mapcar
12357 (lambda (x)
12358 (if (stringp (car x)) (string-width (car x)) 0))
12359 fulltable)))
12360 (expert nil)
12361 (fwidth (+ maxlen 3 1 3))
12362 (ncol (/ (- (window-width) 4) fwidth))
12363 tg cnt e c tbl
12364 groups ingroup)
12365 (save-excursion
12366 (save-window-excursion
12367 (if expert
12368 (set-buffer (get-buffer-create " *Org todo*"))
12369 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12370 (erase-buffer)
12371 (org-set-local 'org-done-keywords done-keywords)
12372 (setq tbl fulltable cnt 0)
12373 (while (setq e (pop tbl))
12374 (cond
12375 ((equal e '(:startgroup))
12376 (push '() groups) (setq ingroup t)
12377 (when (not (= cnt 0))
12378 (setq cnt 0)
12379 (insert "\n"))
12380 (insert "{ "))
12381 ((equal e '(:endgroup))
12382 (setq ingroup nil cnt 0)
12383 (insert "}\n"))
12384 ((equal e '(:newline))
12385 (when (not (= cnt 0))
12386 (setq cnt 0)
12387 (insert "\n")
12388 (setq e (car tbl))
12389 (while (equal (car tbl) '(:newline))
12390 (insert "\n")
12391 (setq tbl (cdr tbl)))))
12393 (setq tg (car e) c (cdr e))
12394 (if ingroup (push tg (car groups)))
12395 (setq tg (org-add-props tg nil 'face
12396 (org-get-todo-face tg)))
12397 (if (and (= cnt 0) (not ingroup)) (insert " "))
12398 (insert "[" c "] " tg (make-string
12399 (- fwidth 4 (length tg)) ?\ ))
12400 (when (= (setq cnt (1+ cnt)) ncol)
12401 (insert "\n")
12402 (if ingroup (insert " "))
12403 (setq cnt 0)))))
12404 (insert "\n")
12405 (goto-char (point-min))
12406 (if (not expert) (org-fit-window-to-buffer))
12407 (message "[a-z..]:Set [SPC]:clear")
12408 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12409 (cond
12410 ((or (= c ?\C-g)
12411 (and (= c ?q) (not (rassoc c fulltable))))
12412 (setq quit-flag t))
12413 ((= c ?\ ) nil)
12414 ((setq e (rassoc c fulltable) tg (car e))
12416 (t (setq quit-flag t)))))))
12418 (defun org-entry-is-todo-p ()
12419 (member (org-get-todo-state) org-not-done-keywords))
12421 (defun org-entry-is-done-p ()
12422 (member (org-get-todo-state) org-done-keywords))
12424 (defun org-get-todo-state ()
12425 (save-excursion
12426 (org-back-to-heading t)
12427 (and (looking-at org-todo-line-regexp)
12428 (match-end 2)
12429 (match-string 2))))
12431 (defun org-at-date-range-p (&optional inactive-ok)
12432 "Is the cursor inside a date range?"
12433 (interactive)
12434 (save-excursion
12435 (catch 'exit
12436 (let ((pos (point)))
12437 (skip-chars-backward "^[<\r\n")
12438 (skip-chars-backward "<[")
12439 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12440 (>= (match-end 0) pos)
12441 (throw 'exit t))
12442 (skip-chars-backward "^<[\r\n")
12443 (skip-chars-backward "<[")
12444 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12445 (>= (match-end 0) pos)
12446 (throw 'exit t)))
12447 nil)))
12449 (defun org-get-repeat (&optional tagline)
12450 "Check if there is a deadline/schedule with repeater in this entry."
12451 (save-match-data
12452 (save-excursion
12453 (org-back-to-heading t)
12454 (and (re-search-forward (if tagline
12455 (concat tagline "\\s-*" org-repeat-re)
12456 org-repeat-re)
12457 (org-entry-end-position) t)
12458 (match-string-no-properties 1)))))
12460 (defvar org-last-changed-timestamp)
12461 (defvar org-last-inserted-timestamp)
12462 (defvar org-log-post-message)
12463 (defvar org-log-note-purpose)
12464 (defvar org-log-note-how)
12465 (defvar org-log-note-extra)
12466 (defun org-auto-repeat-maybe (done-word)
12467 "Check if the current headline contains a repeated deadline/schedule.
12468 If yes, set TODO state back to what it was and change the base date
12469 of repeating deadline/scheduled time stamps to new date.
12470 This function is run automatically after each state change to a DONE state."
12471 ;; last-state is dynamically scoped into this function
12472 (let* ((repeat (org-get-repeat))
12473 (aa (assoc org-last-state org-todo-kwd-alist))
12474 (interpret (nth 1 aa))
12475 (head (nth 2 aa))
12476 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12477 (msg "Entry repeats: ")
12478 (org-log-done nil)
12479 (org-todo-log-states nil)
12480 re type n what ts time to-state)
12481 (when repeat
12482 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12483 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12484 org-todo-repeat-to-state))
12485 (unless (and to-state (member to-state org-todo-keywords-1))
12486 (setq to-state (if (eq interpret 'type) org-last-state head)))
12487 (org-todo to-state)
12488 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12489 (org-entry-put nil "LAST_REPEAT" (format-time-string
12490 (org-time-stamp-format t t))))
12491 (when org-log-repeat
12492 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12493 (memq 'org-add-log-note post-command-hook))
12494 ;; OK, we are already setup for some record
12495 (if (eq org-log-repeat 'note)
12496 ;; make sure we take a note, not only a time stamp
12497 (setq org-log-note-how 'note))
12498 ;; Set up for taking a record
12499 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12500 org-last-state
12501 'findpos org-log-repeat)))
12502 (org-back-to-heading t)
12503 (org-add-planning-info nil nil 'closed)
12504 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12505 org-deadline-time-regexp "\\)\\|\\("
12506 org-ts-regexp "\\)"))
12507 (while (re-search-forward
12508 re (save-excursion (outline-next-heading) (point)) t)
12509 (setq type (if (match-end 1) org-scheduled-string
12510 (if (match-end 3) org-deadline-string "Plain:"))
12511 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12512 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12513 (setq n (string-to-number (match-string 2 ts))
12514 what (match-string 3 ts))
12515 (if (equal what "w") (setq n (* n 7) what "d"))
12516 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12517 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12518 ;; Preparation, see if we need to modify the start date for the change
12519 (when (match-end 1)
12520 (setq time (save-match-data (org-time-string-to-time ts)))
12521 (cond
12522 ((equal (match-string 1 ts) ".")
12523 ;; Shift starting date to today
12524 (org-timestamp-change
12525 (- (org-today) (time-to-days time))
12526 'day))
12527 ((equal (match-string 1 ts) "+")
12528 (let ((nshiftmax 10) (nshift 0))
12529 (while (or (= nshift 0)
12530 (<= (time-to-days time)
12531 (time-to-days (current-time))))
12532 (when (= (incf nshift) nshiftmax)
12533 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12534 (error "Abort")))
12535 (org-timestamp-change n (cdr (assoc what whata)))
12536 (org-at-timestamp-p t)
12537 (setq ts (match-string 1))
12538 (setq time (save-match-data (org-time-string-to-time ts)))))
12539 (org-timestamp-change (- n) (cdr (assoc what whata)))
12540 ;; rematch, so that we have everything in place for the real shift
12541 (org-at-timestamp-p t)
12542 (setq ts (match-string 1))
12543 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12544 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12545 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12546 (setq org-log-post-message msg)
12547 (message "%s" msg))))
12549 (defun org-show-todo-tree (arg)
12550 "Make a compact tree which shows all headlines marked with TODO.
12551 The tree will show the lines where the regexp matches, and all higher
12552 headlines above the match.
12553 With a \\[universal-argument] prefix, prompt for a regexp to match.
12554 With a numeric prefix N, construct a sparse tree for the Nth element
12555 of `org-todo-keywords-1'."
12556 (interactive "P")
12557 (let ((case-fold-search nil)
12558 (kwd-re
12559 (cond ((null arg) org-not-done-regexp)
12560 ((equal arg '(4))
12561 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12562 (mapcar 'list org-todo-keywords-1))))
12563 (concat "\\("
12564 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12565 "\\)\\>")))
12566 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12567 (regexp-quote (nth (1- (prefix-numeric-value arg))
12568 org-todo-keywords-1)))
12569 (t (error "Invalid prefix argument: %s" arg)))))
12570 (message "%d TODO entries found"
12571 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12573 (defun org-deadline (&optional arg time)
12574 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12575 With one universal prefix argument, remove any deadline from the item.
12576 With two universal prefix arguments, prompt for a warning delay.
12577 With argument TIME, set the deadline at the corresponding date. TIME
12578 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12579 (interactive "P")
12580 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12581 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12582 'region-start-level 'region))
12583 org-loop-over-headlines-in-active-region)
12584 (org-map-entries
12585 `(org-deadline ',arg ,time)
12586 org-loop-over-headlines-in-active-region
12587 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12588 (let* ((old-date (org-entry-get nil "DEADLINE"))
12589 (repeater (and old-date
12590 (string-match
12591 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12592 old-date)
12593 (match-string 1 old-date))))
12594 (cond
12595 ((equal arg '(4))
12596 (when (and old-date org-log-redeadline)
12597 (org-add-log-setup 'deldeadline nil old-date 'findpos
12598 org-log-redeadline))
12599 (org-remove-timestamp-with-keyword org-deadline-string)
12600 (message "Item no longer has a deadline."))
12601 ((equal arg '(16))
12602 (save-excursion
12603 (if (re-search-forward
12604 org-deadline-time-regexp
12605 (save-excursion (outline-next-heading) (point)) t)
12606 (let* ((rpl0 (match-string 1))
12607 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12608 (replace-match
12609 (concat org-deadline-string
12610 " <" rpl
12611 (format " -%dd" (abs
12612 (- (time-to-days
12613 (save-match-data
12614 (org-read-date nil t nil "Warn starting from")))
12615 (time-to-days nil))))
12616 ">") t t))
12617 (user-error "No deadline information to update"))))
12619 (org-add-planning-info 'deadline time 'closed)
12620 (when (and old-date org-log-redeadline
12621 (not (equal old-date
12622 (substring org-last-inserted-timestamp 1 -1))))
12623 (org-add-log-setup 'redeadline nil old-date 'findpos
12624 org-log-redeadline))
12625 (when repeater
12626 (save-excursion
12627 (org-back-to-heading t)
12628 (when (re-search-forward (concat org-deadline-string " "
12629 org-last-inserted-timestamp)
12630 (save-excursion
12631 (outline-next-heading) (point)) t)
12632 (goto-char (1- (match-end 0)))
12633 (insert " " repeater)
12634 (setq org-last-inserted-timestamp
12635 (concat (substring org-last-inserted-timestamp 0 -1)
12636 " " repeater
12637 (substring org-last-inserted-timestamp -1))))))
12638 (message "Deadline on %s" org-last-inserted-timestamp))))))
12640 (defun org-schedule (&optional arg time)
12641 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12642 With one universal prefix argument, remove any scheduling date from the item.
12643 With two universal prefix arguments, prompt for a delay cookie.
12644 With argument TIME, scheduled at the corresponding date. TIME can
12645 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12646 (interactive "P")
12647 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12648 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12649 'region-start-level 'region))
12650 org-loop-over-headlines-in-active-region)
12651 (org-map-entries
12652 `(org-schedule ',arg ,time)
12653 org-loop-over-headlines-in-active-region
12654 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12655 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12656 (repeater (and old-date
12657 (string-match
12658 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12659 old-date)
12660 (match-string 1 old-date))))
12661 (cond
12662 ((equal arg '(4))
12663 (progn
12664 (when (and old-date org-log-reschedule)
12665 (org-add-log-setup 'delschedule nil old-date 'findpos
12666 org-log-reschedule))
12667 (org-remove-timestamp-with-keyword org-scheduled-string)
12668 (message "Item is no longer scheduled.")))
12669 ((equal arg '(16))
12670 (save-excursion
12671 (if (re-search-forward
12672 org-scheduled-time-regexp
12673 (save-excursion (outline-next-heading) (point)) t)
12674 (let* ((rpl0 (match-string 1))
12675 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12676 (replace-match
12677 (concat org-scheduled-string
12678 " <" rpl
12679 (format " -%dd" (abs
12680 (- (time-to-days
12681 (save-match-data
12682 (org-read-date nil t nil "Delay until")))
12683 (time-to-days nil))))
12684 ">") t t))
12685 (user-error "No scheduled information to update"))))
12687 (org-add-planning-info 'scheduled time 'closed)
12688 (when (and old-date org-log-reschedule
12689 (not (equal old-date
12690 (substring org-last-inserted-timestamp 1 -1))))
12691 (org-add-log-setup 'reschedule nil old-date 'findpos
12692 org-log-reschedule))
12693 (when repeater
12694 (save-excursion
12695 (org-back-to-heading t)
12696 (when (re-search-forward (concat org-scheduled-string " "
12697 org-last-inserted-timestamp)
12698 (save-excursion
12699 (outline-next-heading) (point)) t)
12700 (goto-char (1- (match-end 0)))
12701 (insert " " repeater)
12702 (setq org-last-inserted-timestamp
12703 (concat (substring org-last-inserted-timestamp 0 -1)
12704 " " repeater
12705 (substring org-last-inserted-timestamp -1))))))
12706 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12708 (defun org-get-scheduled-time (pom &optional inherit)
12709 "Get the scheduled time as a time tuple, of a format suitable
12710 for calling org-schedule with, or if there is no scheduling,
12711 returns nil."
12712 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12713 (when time
12714 (apply 'encode-time (org-parse-time-string time)))))
12716 (defun org-get-deadline-time (pom &optional inherit)
12717 "Get the deadline as a time tuple, of a format suitable for
12718 calling org-deadline with, or if there is no scheduling, returns
12719 nil."
12720 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12721 (when time
12722 (apply 'encode-time (org-parse-time-string time)))))
12724 (defun org-remove-timestamp-with-keyword (keyword)
12725 "Remove all time stamps with KEYWORD in the current entry."
12726 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12727 beg)
12728 (save-excursion
12729 (org-back-to-heading t)
12730 (setq beg (point))
12731 (outline-next-heading)
12732 (while (re-search-backward re beg t)
12733 (replace-match "")
12734 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12735 (equal (char-before) ?\ ))
12736 (backward-delete-char 1)
12737 (if (string-match "^[ \t]*$" (buffer-substring
12738 (point-at-bol) (point-at-eol)))
12739 (delete-region (point-at-bol)
12740 (min (point-max) (1+ (point-at-eol))))))))))
12742 (defun org-add-planning-info (what &optional time &rest remove)
12743 "Insert new timestamp with keyword in the line directly after the headline.
12744 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12745 If non is given, the user is prompted for a date.
12746 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12747 be removed."
12748 (interactive)
12749 (let (org-time-was-given org-end-time-was-given ts
12750 end default-time default-input)
12752 (catch 'exit
12753 (when (and (memq what '(scheduled deadline))
12754 (or (not time)
12755 (and (stringp time)
12756 (string-match "^[-+]+[0-9]" time))))
12757 ;; Try to get a default date/time from existing timestamp
12758 (save-excursion
12759 (org-back-to-heading t)
12760 (setq end (save-excursion (outline-next-heading) (point)))
12761 (when (re-search-forward (if (eq what 'scheduled)
12762 org-scheduled-time-regexp
12763 org-deadline-time-regexp)
12764 end t)
12765 (setq ts (match-string 1)
12766 default-time
12767 (apply 'encode-time (org-parse-time-string ts))
12768 default-input (and ts (org-get-compact-tod ts))))))
12769 (when what
12770 (setq time
12771 (if (stringp time)
12772 ;; This is a string (relative or absolute), set proper date
12773 (apply 'encode-time
12774 (org-read-date-analyze
12775 time default-time (decode-time default-time)))
12776 ;; If necessary, get the time from the user
12777 (or time (org-read-date nil 'to-time nil nil
12778 default-time default-input)))))
12780 (when (and org-insert-labeled-timestamps-at-point
12781 (member what '(scheduled deadline)))
12782 (insert
12783 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12784 (org-insert-time-stamp time org-time-was-given
12785 nil nil nil (list org-end-time-was-given))
12786 (setq what nil))
12787 (save-excursion
12788 (save-restriction
12789 (let (col list elt ts buffer-invisibility-spec)
12790 (org-back-to-heading t)
12791 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12792 (goto-char (match-end 1))
12793 (setq col (current-column))
12794 (goto-char (match-end 0))
12795 (if (eobp) (insert "\n") (forward-char 1))
12796 (when (and (not what)
12797 (not (looking-at
12798 (concat "[ \t]*"
12799 org-keyword-time-not-clock-regexp))))
12800 ;; Nothing to add, nothing to remove...... :-)
12801 (throw 'exit nil))
12802 (if (and (not (looking-at org-outline-regexp))
12803 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12804 "[^\r\n]*"))
12805 (not (equal (match-string 1) org-clock-string)))
12806 (narrow-to-region (match-beginning 0) (match-end 0))
12807 (insert-before-markers "\n")
12808 (backward-char 1)
12809 (narrow-to-region (point) (point))
12810 (and org-adapt-indentation (org-indent-to-column col)))
12811 ;; Check if we have to remove something.
12812 (setq list (cons what remove))
12813 (while list
12814 (setq elt (pop list))
12815 (when (or (and (eq elt 'scheduled)
12816 (re-search-forward org-scheduled-time-regexp nil t))
12817 (and (eq elt 'deadline)
12818 (re-search-forward org-deadline-time-regexp nil t))
12819 (and (eq elt 'closed)
12820 (re-search-forward org-closed-time-regexp nil t)))
12821 (replace-match "")
12822 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12823 (and (looking-at "[ \t]+") (replace-match ""))
12824 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12825 (when what
12826 (insert
12827 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12828 (cond ((eq what 'scheduled) org-scheduled-string)
12829 ((eq what 'deadline) org-deadline-string)
12830 ((eq what 'closed) org-closed-string))
12831 " ")
12832 (setq ts (org-insert-time-stamp
12833 time
12834 (or org-time-was-given
12835 (and (eq what 'closed) org-log-done-with-time))
12836 (eq what 'closed)
12837 nil nil (list org-end-time-was-given)))
12838 (insert
12839 (if (not (or (bolp) (eq (char-before) ?\ )
12840 (memq (char-after) '(32 10))
12841 (eobp))) " " ""))
12842 (end-of-line 1))
12843 (goto-char (point-min))
12844 (widen)
12845 (if (and (looking-at "[ \t]*\n")
12846 (equal (char-before) ?\n))
12847 (delete-region (1- (point)) (point-at-eol)))
12848 ts))))))
12850 (defvar org-log-note-marker (make-marker))
12851 (defvar org-log-note-purpose nil)
12852 (defvar org-log-note-state nil)
12853 (defvar org-log-note-previous-state nil)
12854 (defvar org-log-note-how nil)
12855 (defvar org-log-note-extra nil)
12856 (defvar org-log-note-window-configuration nil)
12857 (defvar org-log-note-return-to (make-marker))
12858 (defvar org-log-note-effective-time nil
12859 "Remembered current time so that dynamically scoped
12860 `org-extend-today-until' affects tha timestamps in state change
12861 log")
12863 (defvar org-log-post-message nil
12864 "Message to be displayed after a log note has been stored.
12865 The auto-repeater uses this.")
12867 (defun org-add-note ()
12868 "Add a note to the current entry.
12869 This is done in the same way as adding a state change note."
12870 (interactive)
12871 (org-add-log-setup 'note nil nil 'findpos nil))
12873 (defvar org-property-end-re)
12874 (defun org-add-log-setup (&optional purpose state prev-state
12875 findpos how extra)
12876 "Set up the post command hook to take a note.
12877 If this is about to TODO state change, the new state is expected in STATE.
12878 When FINDPOS is non-nil, find the correct position for the note in
12879 the current entry. If not, assume that it can be inserted at point.
12880 HOW is an indicator what kind of note should be created.
12881 EXTRA is additional text that will be inserted into the notes buffer."
12882 (let* ((org-log-into-drawer (org-log-into-drawer))
12883 (drawer (cond ((stringp org-log-into-drawer)
12884 org-log-into-drawer)
12885 (org-log-into-drawer "LOGBOOK"))))
12886 (save-restriction
12887 (save-excursion
12888 (when findpos
12889 (org-back-to-heading t)
12890 (narrow-to-region (point) (save-excursion
12891 (outline-next-heading) (point)))
12892 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12893 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12894 "[^\r\n]*\\)?"))
12895 (goto-char (match-end 0))
12896 (cond
12897 (drawer
12898 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12899 nil t)
12900 (progn
12901 (goto-char (match-end 0))
12902 (or org-log-states-order-reversed
12903 (and (re-search-forward org-property-end-re nil t)
12904 (goto-char (1- (match-beginning 0))))))
12905 (insert "\n:" drawer ":\n:END:")
12906 (beginning-of-line 0)
12907 (org-indent-line)
12908 (beginning-of-line 2)
12909 (org-indent-line)
12910 (end-of-line 0)))
12911 ((and org-log-state-notes-insert-after-drawers
12912 (save-excursion
12913 (forward-line) (looking-at org-drawer-regexp)))
12914 (forward-line)
12915 (while (looking-at org-drawer-regexp)
12916 (goto-char (match-end 0))
12917 (re-search-forward org-property-end-re (point-max) t)
12918 (forward-line))
12919 (forward-line -1)))
12920 (unless org-log-states-order-reversed
12921 (and (= (char-after) ?\n) (forward-char 1))
12922 (org-skip-over-state-notes)
12923 (skip-chars-backward " \t\n\r")))
12924 (move-marker org-log-note-marker (point))
12925 (setq org-log-note-purpose purpose
12926 org-log-note-state state
12927 org-log-note-previous-state prev-state
12928 org-log-note-how how
12929 org-log-note-extra extra
12930 org-log-note-effective-time (org-current-effective-time))
12931 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12933 (defun org-skip-over-state-notes ()
12934 "Skip past the list of State notes in an entry."
12935 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12936 (when (ignore-errors (goto-char (org-in-item-p)))
12937 (let* ((struct (org-list-struct))
12938 (prevs (org-list-prevs-alist struct)))
12939 (while (looking-at "[ \t]*- State")
12940 (goto-char (or (org-list-get-next-item (point) struct prevs)
12941 (org-list-get-item-end (point) struct)))))))
12943 (defun org-add-log-note (&optional purpose)
12944 "Pop up a window for taking a note, and add this note later at point."
12945 (remove-hook 'post-command-hook 'org-add-log-note)
12946 (setq org-log-note-window-configuration (current-window-configuration))
12947 (delete-other-windows)
12948 (move-marker org-log-note-return-to (point))
12949 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12950 (goto-char org-log-note-marker)
12951 (org-switch-to-buffer-other-window "*Org Note*")
12952 (erase-buffer)
12953 (if (memq org-log-note-how '(time state))
12954 (let (current-prefix-arg) (org-store-log-note))
12955 (let ((org-inhibit-startup t)) (org-mode))
12956 (insert (format "# Insert note for %s.
12957 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12958 (cond
12959 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12960 ((eq org-log-note-purpose 'done) "closed todo item")
12961 ((eq org-log-note-purpose 'state)
12962 (format "state change from \"%s\" to \"%s\""
12963 (or org-log-note-previous-state "")
12964 (or org-log-note-state "")))
12965 ((eq org-log-note-purpose 'reschedule)
12966 "rescheduling")
12967 ((eq org-log-note-purpose 'delschedule)
12968 "no longer scheduled")
12969 ((eq org-log-note-purpose 'redeadline)
12970 "changing deadline")
12971 ((eq org-log-note-purpose 'deldeadline)
12972 "removing deadline")
12973 ((eq org-log-note-purpose 'refile)
12974 "refiling")
12975 ((eq org-log-note-purpose 'note)
12976 "this entry")
12977 (t (error "This should not happen")))))
12978 (if org-log-note-extra (insert org-log-note-extra))
12979 (org-set-local 'org-finish-function 'org-store-log-note)
12980 (run-hooks 'org-log-buffer-setup-hook)))
12982 (defvar org-note-abort nil) ; dynamically scoped
12983 (defun org-store-log-note ()
12984 "Finish taking a log note, and insert it to where it belongs."
12985 (let ((txt (buffer-string)))
12986 (kill-buffer (current-buffer))
12987 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12988 lines ind bul)
12989 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12990 (setq txt (replace-match "" t t txt)))
12991 (if (string-match "\\s-+\\'" txt)
12992 (setq txt (replace-match "" t t txt)))
12993 (setq lines (org-split-string txt "\n"))
12994 (when (and note (string-match "\\S-" note))
12995 (setq note
12996 (org-replace-escapes
12997 note
12998 (list (cons "%u" (user-login-name))
12999 (cons "%U" user-full-name)
13000 (cons "%t" (format-time-string
13001 (org-time-stamp-format 'long 'inactive)
13002 org-log-note-effective-time))
13003 (cons "%T" (format-time-string
13004 (org-time-stamp-format 'long nil)
13005 org-log-note-effective-time))
13006 (cons "%d" (format-time-string
13007 (org-time-stamp-format nil 'inactive)
13008 org-log-note-effective-time))
13009 (cons "%D" (format-time-string
13010 (org-time-stamp-format nil nil)
13011 org-log-note-effective-time))
13012 (cons "%s" (if org-log-note-state
13013 (concat "\"" org-log-note-state "\"")
13014 ""))
13015 (cons "%S" (if org-log-note-previous-state
13016 (concat "\"" org-log-note-previous-state "\"")
13017 "\"\"")))))
13018 (if lines (setq note (concat note " \\\\")))
13019 (push note lines))
13020 (when (or current-prefix-arg org-note-abort)
13021 (when org-log-into-drawer
13022 (org-remove-empty-drawer-at
13023 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13024 org-log-note-marker))
13025 (setq lines nil))
13026 (when lines
13027 (with-current-buffer (marker-buffer org-log-note-marker)
13028 (save-excursion
13029 (goto-char org-log-note-marker)
13030 (move-marker org-log-note-marker nil)
13031 (end-of-line 1)
13032 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13033 (setq ind (save-excursion
13034 (if (ignore-errors (goto-char (org-in-item-p)))
13035 (let ((struct (org-list-struct)))
13036 (org-list-get-ind
13037 (org-list-get-top-point struct) struct))
13038 (skip-chars-backward " \r\t\n")
13039 (cond
13040 ((and (org-at-heading-p)
13041 org-adapt-indentation)
13042 (1+ (org-current-level)))
13043 ((org-at-heading-p) 0)
13044 (t (org-get-indentation))))))
13045 (setq bul (org-list-bullet-string "-"))
13046 (org-indent-line-to ind)
13047 (insert bul (pop lines))
13048 (let ((ind-body (+ (length bul) ind)))
13049 (while lines
13050 (insert "\n")
13051 (org-indent-line-to ind-body)
13052 (insert (pop lines))))
13053 (message "Note stored")
13054 (org-back-to-heading t)
13055 (org-cycle-hide-drawers 'children))))))
13056 (set-window-configuration org-log-note-window-configuration)
13057 (with-current-buffer (marker-buffer org-log-note-return-to)
13058 (goto-char org-log-note-return-to))
13059 (move-marker org-log-note-return-to nil)
13060 (and org-log-post-message (message "%s" org-log-post-message)))
13062 (defun org-remove-empty-drawer-at (drawer pos)
13063 "Remove an empty drawer DRAWER at position POS.
13064 POS may also be a marker."
13065 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13066 (save-excursion
13067 (save-restriction
13068 (widen)
13069 (goto-char pos)
13070 (if (org-in-regexp
13071 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13072 (replace-match ""))))))
13074 (defvar org-ts-type nil)
13075 (defun org-sparse-tree (&optional arg type)
13076 "Create a sparse tree, prompt for the details.
13077 This command can create sparse trees. You first need to select the type
13078 of match used to create the tree:
13080 t Show all TODO entries.
13081 T Show entries with a specific TODO keyword.
13082 m Show entries selected by a tags/property match.
13083 p Enter a property name and its value (both with completion on existing
13084 names/values) and show entries with that property.
13085 r Show entries matching a regular expression (`/' can be used as well).
13086 b Show deadlines and scheduled items before a date.
13087 a Show deadlines and scheduled items after a date.
13088 d Show deadlines due within `org-deadline-warning-days'.
13089 D Show deadlines and scheduled items between a date range."
13090 (interactive "P")
13091 (let (ans kwd value ts-type)
13092 (setq type (or type org-sparse-tree-default-date-type))
13093 (setq org-ts-type type)
13094 (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"
13095 (cond ((eq type 'all) "all timestamps")
13096 ((eq type 'scheduled) "only scheduled")
13097 ((eq type 'deadline) "only deadline")
13098 ((eq type 'active) "only active timestamps")
13099 ((eq type 'inactive) "only inactive timestamps")
13100 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13101 (t "scheduled/deadline")))
13102 (setq ans (read-char-exclusive))
13103 (cond
13104 ((equal ans ?c)
13105 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13106 ((equal ans ?d)
13107 (call-interactively 'org-check-deadlines))
13108 ((equal ans ?b)
13109 (call-interactively 'org-check-before-date))
13110 ((equal ans ?a)
13111 (call-interactively 'org-check-after-date))
13112 ((equal ans ?D)
13113 (call-interactively 'org-check-dates-range))
13114 ((equal ans ?t)
13115 (call-interactively 'org-show-todo-tree))
13116 ((equal ans ?T)
13117 (org-show-todo-tree '(4)))
13118 ((member ans '(?T ?m))
13119 (call-interactively 'org-match-sparse-tree))
13120 ((member ans '(?p ?P))
13121 (setq kwd (org-icompleting-read "Property: "
13122 (mapcar 'list (org-buffer-property-keys))))
13123 (setq value (org-icompleting-read "Value: "
13124 (mapcar 'list (org-property-values kwd))))
13125 (unless (string-match "\\`{.*}\\'" value)
13126 (setq value (concat "\"" value "\"")))
13127 (org-match-sparse-tree arg (concat kwd "=" value)))
13128 ((member ans '(?r ?R ?/))
13129 (call-interactively 'org-occur))
13130 (t (error "No such sparse tree command \"%c\"" ans)))))
13132 (defvar org-occur-highlights nil
13133 "List of overlays used for occur matches.")
13134 (make-variable-buffer-local 'org-occur-highlights)
13135 (defvar org-occur-parameters nil
13136 "Parameters of the active org-occur calls.
13137 This is a list, each call to org-occur pushes as cons cell,
13138 containing the regular expression and the callback, onto the list.
13139 The list can contain several entries if `org-occur' has been called
13140 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13141 will only contain one set of parameters. When the highlights are
13142 removed (for example with `C-c C-c', or with the next edit (depending
13143 on `org-remove-highlights-with-change'), this variable is emptied
13144 as well.")
13145 (make-variable-buffer-local 'org-occur-parameters)
13147 (defun org-occur (regexp &optional keep-previous callback)
13148 "Make a compact tree which shows all matches of REGEXP.
13149 The tree will show the lines where the regexp matches, and all higher
13150 headlines above the match. It will also show the heading after the match,
13151 to make sure editing the matching entry is easy.
13152 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13153 call to `org-occur' will be kept, to allow stacking of calls to this
13154 command.
13155 If CALLBACK is non-nil, it is a function which is called to confirm
13156 that the match should indeed be shown."
13157 (interactive "sRegexp: \nP")
13158 (when (equal regexp "")
13159 (error "Regexp cannot be empty"))
13160 (unless keep-previous
13161 (org-remove-occur-highlights nil nil t))
13162 (push (cons regexp callback) org-occur-parameters)
13163 (let ((cnt 0))
13164 (save-excursion
13165 (goto-char (point-min))
13166 (if (or (not keep-previous) ; do not want to keep
13167 (not org-occur-highlights)) ; no previous matches
13168 ;; hide everything
13169 (org-overview))
13170 (while (re-search-forward regexp nil t)
13171 (when (or (not callback)
13172 (save-match-data (funcall callback)))
13173 (setq cnt (1+ cnt))
13174 (when org-highlight-sparse-tree-matches
13175 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13176 (org-show-context 'occur-tree))))
13177 (when org-remove-highlights-with-change
13178 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13179 nil 'local))
13180 (unless org-sparse-tree-open-archived-trees
13181 (org-hide-archived-subtrees (point-min) (point-max)))
13182 (run-hooks 'org-occur-hook)
13183 (if (org-called-interactively-p 'interactive)
13184 (message "%d match(es) for regexp %s" cnt regexp))
13185 cnt))
13187 (defun org-occur-next-match (&optional n reset)
13188 "Function for `next-error-function' to find sparse tree matches.
13189 N is the number of matches to move, when negative move backwards.
13190 RESET is entirely ignored - this function always goes back to the
13191 starting point when no match is found."
13192 (let* ((limit (if (< n 0) (point-min) (point-max)))
13193 (search-func (if (< n 0)
13194 'previous-single-char-property-change
13195 'next-single-char-property-change))
13196 (n (abs n))
13197 (pos (point))
13199 (catch 'exit
13200 (while (setq p1 (funcall search-func (point) 'org-type))
13201 (when (equal p1 limit)
13202 (goto-char pos)
13203 (error "No more matches"))
13204 (when (equal (get-char-property p1 'org-type) 'org-occur)
13205 (setq n (1- n))
13206 (when (= n 0)
13207 (goto-char p1)
13208 (throw 'exit (point))))
13209 (goto-char p1))
13210 (goto-char p1)
13211 (error "No more matches"))))
13213 (defun org-show-context (&optional key)
13214 "Make sure point and context are visible.
13215 How much context is shown depends upon the variables
13216 `org-show-hierarchy-above', `org-show-following-heading',
13217 `org-show-entry-below' and `org-show-siblings'."
13218 (let ((heading-p (org-at-heading-p t))
13219 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13220 (following-p (org-get-alist-option org-show-following-heading key))
13221 (entry-p (org-get-alist-option org-show-entry-below key))
13222 (siblings-p (org-get-alist-option org-show-siblings key)))
13223 (catch 'exit
13224 ;; Show heading or entry text
13225 (if (and heading-p (not entry-p))
13226 (org-flag-heading nil) ; only show the heading
13227 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13228 (org-show-hidden-entry))) ; show entire entry
13229 (when following-p
13230 ;; Show next sibling, or heading below text
13231 (save-excursion
13232 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13233 (org-flag-heading nil))))
13234 (when siblings-p (org-show-siblings))
13235 (when hierarchy-p
13236 ;; show all higher headings, possibly with siblings
13237 (save-excursion
13238 (while (and (condition-case nil
13239 (progn (org-up-heading-all 1) t)
13240 (error nil))
13241 (not (bobp)))
13242 (org-flag-heading nil)
13243 (when siblings-p (org-show-siblings))))))))
13245 (defvar org-reveal-start-hook nil
13246 "Hook run before revealing a location.")
13248 (defun org-reveal (&optional siblings)
13249 "Show current entry, hierarchy above it, and the following headline.
13250 This can be used to show a consistent set of context around locations
13251 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13252 not t for the search context.
13254 With optional argument SIBLINGS, on each level of the hierarchy all
13255 siblings are shown. This repairs the tree structure to what it would
13256 look like when opened with hierarchical calls to `org-cycle'.
13257 With double optional argument \\[universal-argument] \\[universal-argument], \
13258 go to the parent and show the
13259 entire tree."
13260 (interactive "P")
13261 (run-hooks 'org-reveal-start-hook)
13262 (let ((org-show-hierarchy-above t)
13263 (org-show-following-heading t)
13264 (org-show-siblings (if siblings t org-show-siblings)))
13265 (org-show-context nil))
13266 (when (equal siblings '(16))
13267 (save-excursion
13268 (when (org-up-heading-safe)
13269 (org-show-subtree)
13270 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13272 (defun org-highlight-new-match (beg end)
13273 "Highlight from BEG to END and mark the highlight is an occur headline."
13274 (let ((ov (make-overlay beg end)))
13275 (overlay-put ov 'face 'secondary-selection)
13276 (overlay-put ov 'org-type 'org-occur)
13277 (push ov org-occur-highlights)))
13279 (defun org-remove-occur-highlights (&optional beg end noremove)
13280 "Remove the occur highlights from the buffer.
13281 BEG and END are ignored. If NOREMOVE is nil, remove this function
13282 from the `before-change-functions' in the current buffer."
13283 (interactive)
13284 (unless org-inhibit-highlight-removal
13285 (mapc 'delete-overlay org-occur-highlights)
13286 (setq org-occur-highlights nil)
13287 (setq org-occur-parameters nil)
13288 (unless noremove
13289 (remove-hook 'before-change-functions
13290 'org-remove-occur-highlights 'local))))
13292 ;;;; Priorities
13294 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13295 "Regular expression matching the priority indicator.")
13297 (defvar org-remove-priority-next-time nil)
13299 (defun org-priority-up ()
13300 "Increase the priority of the current item."
13301 (interactive)
13302 (org-priority 'up))
13304 (defun org-priority-down ()
13305 "Decrease the priority of the current item."
13306 (interactive)
13307 (org-priority 'down))
13309 (defun org-priority (&optional action show)
13310 "Change the priority of an item.
13311 ACTION can be `set', `up', `down', or a character."
13312 (interactive "P")
13313 (if (equal action '(4))
13314 (org-show-priority)
13315 (unless org-enable-priority-commands
13316 (error "Priority commands are disabled"))
13317 (setq action (or action 'set))
13318 (let (current new news have remove)
13319 (save-excursion
13320 (org-back-to-heading t)
13321 (if (looking-at org-priority-regexp)
13322 (setq current (string-to-char (match-string 2))
13323 have t))
13324 (cond
13325 ((eq action 'remove)
13326 (setq remove t new ?\ ))
13327 ((or (eq action 'set)
13328 (if (featurep 'xemacs) (characterp action) (integerp action)))
13329 (if (not (eq action 'set))
13330 (setq new action)
13331 (message "Priority %c-%c, SPC to remove: "
13332 org-highest-priority org-lowest-priority)
13333 (save-match-data
13334 (setq new (read-char-exclusive))))
13335 (if (and (= (upcase org-highest-priority) org-highest-priority)
13336 (= (upcase org-lowest-priority) org-lowest-priority))
13337 (setq new (upcase new)))
13338 (cond ((equal new ?\ ) (setq remove t))
13339 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13340 (error "Priority must be between `%c' and `%c'"
13341 org-highest-priority org-lowest-priority))))
13342 ((eq action 'up)
13343 (setq new (if have
13344 (1- current) ; normal cycling
13345 ;; last priority was empty
13346 (if (eq last-command this-command)
13347 org-lowest-priority ; wrap around empty to lowest
13348 ;; default
13349 (if org-priority-start-cycle-with-default
13350 org-default-priority
13351 (1- org-default-priority))))))
13352 ((eq action 'down)
13353 (setq new (if have
13354 (1+ current) ; normal cycling
13355 ;; last priority was empty
13356 (if (eq last-command this-command)
13357 org-highest-priority ; wrap around empty to highest
13358 ;; default
13359 (if org-priority-start-cycle-with-default
13360 org-default-priority
13361 (1+ org-default-priority))))))
13362 (t (error "Invalid action")))
13363 (if (or (< (upcase new) org-highest-priority)
13364 (> (upcase new) org-lowest-priority))
13365 (if (and (memq action '(up down))
13366 (not have) (not (eq last-command this-command)))
13367 ;; `new' is from default priority
13368 (error
13369 "The default can not be set, see `org-default-priority' why")
13370 ;; normal cycling: `new' is beyond highest/lowest priority
13371 ;; and is wrapped around to the empty priority
13372 (setq remove t)))
13373 (setq news (format "%c" new))
13374 (if have
13375 (if remove
13376 (replace-match "" t t nil 1)
13377 (replace-match news t t nil 2))
13378 (if remove
13379 (error "No priority cookie found in line")
13380 (let ((case-fold-search nil))
13381 (looking-at org-todo-line-regexp))
13382 (if (match-end 2)
13383 (progn
13384 (goto-char (match-end 2))
13385 (insert " [#" news "]"))
13386 (goto-char (match-beginning 3))
13387 (insert "[#" news "] "))))
13388 (org-preserve-lc (org-set-tags nil 'align)))
13389 (if remove
13390 (message "Priority removed")
13391 (message "Priority of current item set to %s" news)))))
13393 (defun org-show-priority ()
13394 "Show the priority of the current item.
13395 This priority is composed of the main priority given with the [#A] cookies,
13396 and by additional input from the age of a schedules or deadline entry."
13397 (interactive)
13398 (let ((pri (if (eq major-mode 'org-agenda-mode)
13399 (org-get-at-bol 'priority)
13400 (save-excursion
13401 (save-match-data
13402 (beginning-of-line)
13403 (and (looking-at org-heading-regexp)
13404 (org-get-priority (match-string 0))))))))
13405 (message "Priority is %d" (if pri pri -1000))))
13407 (defun org-get-priority (s)
13408 "Find priority cookie and return priority."
13409 (save-match-data
13410 (if (functionp org-get-priority-function)
13411 (funcall org-get-priority-function)
13412 (if (not (string-match org-priority-regexp s))
13413 (* 1000 (- org-lowest-priority org-default-priority))
13414 (* 1000 (- org-lowest-priority
13415 (string-to-char (match-string 2 s))))))))
13417 ;;;; Tags
13419 (defvar org-agenda-archives-mode)
13420 (defvar org-map-continue-from nil
13421 "Position from where mapping should continue.
13422 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13424 (defvar org-scanner-tags nil
13425 "The current tag list while the tags scanner is running.")
13426 (defvar org-trust-scanner-tags nil
13427 "Should `org-get-tags-at' use the tags for the scanner.
13428 This is for internal dynamical scoping only.
13429 When this is non-nil, the function `org-get-tags-at' will return the value
13430 of `org-scanner-tags' instead of building the list by itself. This
13431 can lead to large speed-ups when the tags scanner is used in a file with
13432 many entries, and when the list of tags is retrieved, for example to
13433 obtain a list of properties. Building the tags list for each entry in such
13434 a file becomes an N^2 operation - but with this variable set, it scales
13435 as N.")
13437 (defun org-scan-tags (action matcher todo-only &optional start-level)
13438 "Scan headline tags with inheritance and produce output ACTION.
13440 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13441 or `agenda' to produce an entry list for an agenda view. It can also be
13442 a Lisp form or a function that should be called at each matched headline, in
13443 this case the return value is a list of all return values from these calls.
13445 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13446 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13447 only lines with a not-done TODO keyword are included in the output.
13448 This should be the same variable that was scoped into
13449 and set by `org-make-tags-matcher' when it constructed MATCHER.
13451 START-LEVEL can be a string with asterisks, reducing the scope to
13452 headlines matching this string."
13453 (require 'org-agenda)
13454 (let* ((re (concat "^"
13455 (if start-level
13456 ;; Get the correct level to match
13457 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13458 org-outline-regexp)
13459 " *\\(\\<\\("
13460 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13461 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13462 (props (list 'face 'default
13463 'done-face 'org-agenda-done
13464 'undone-face 'default
13465 'mouse-face 'highlight
13466 'org-not-done-regexp org-not-done-regexp
13467 'org-todo-regexp org-todo-regexp
13468 'org-complex-heading-regexp org-complex-heading-regexp
13469 'help-echo
13470 (format "mouse-2 or RET jump to org file %s"
13471 (abbreviate-file-name
13472 (or (buffer-file-name (buffer-base-buffer))
13473 (buffer-name (buffer-base-buffer)))))))
13474 (case-fold-search nil)
13475 (org-map-continue-from nil)
13476 lspos tags tags-list
13477 (tags-alist (list (cons 0 org-file-tags)))
13478 (llast 0) rtn rtn1 level category i txt
13479 todo marker entry priority)
13480 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13481 (setq action (list 'lambda nil action)))
13482 (save-excursion
13483 (goto-char (point-min))
13484 (when (eq action 'sparse-tree)
13485 (org-overview)
13486 (org-remove-occur-highlights))
13487 (while (re-search-forward re nil t)
13488 (setq org-map-continue-from nil)
13489 (catch :skip
13490 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13491 tags (if (match-end 4) (org-match-string-no-properties 4)))
13492 (goto-char (setq lspos (match-beginning 0)))
13493 (setq level (org-reduced-level (org-outline-level))
13494 category (org-get-category))
13495 (setq i llast llast level)
13496 ;; remove tag lists from same and sublevels
13497 (while (>= i level)
13498 (when (setq entry (assoc i tags-alist))
13499 (setq tags-alist (delete entry tags-alist)))
13500 (setq i (1- i)))
13501 ;; add the next tags
13502 (when tags
13503 (setq tags (org-split-string tags ":")
13504 tags-alist
13505 (cons (cons level tags) tags-alist)))
13506 ;; compile tags for current headline
13507 (setq tags-list
13508 (if org-use-tag-inheritance
13509 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13510 tags)
13511 org-scanner-tags tags-list)
13512 (when org-use-tag-inheritance
13513 (setcdr (car tags-alist)
13514 (mapcar (lambda (x)
13515 (setq x (copy-sequence x))
13516 (org-add-prop-inherited x))
13517 (cdar tags-alist))))
13518 (when (and tags org-use-tag-inheritance
13519 (or (not (eq t org-use-tag-inheritance))
13520 org-tags-exclude-from-inheritance))
13521 ;; selective inheritance, remove uninherited ones
13522 (setcdr (car tags-alist)
13523 (org-remove-uninherited-tags (cdar tags-alist))))
13524 (when (and
13526 ;; eval matcher only when the todo condition is OK
13527 (and (or (not todo-only) (member todo org-not-done-keywords))
13528 (let ((case-fold-search t) (org-trust-scanner-tags t))
13529 (eval matcher)))
13531 ;; Call the skipper, but return t if it does not skip,
13532 ;; so that the `and' form continues evaluating
13533 (progn
13534 (unless (eq action 'sparse-tree) (org-agenda-skip))
13537 ;; Check if timestamps are deselecting this entry
13538 (or (not todo-only)
13539 (and (member todo org-not-done-keywords)
13540 (or (not org-agenda-tags-todo-honor-ignore-options)
13541 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13543 ;; select this headline
13544 (cond
13545 ((eq action 'sparse-tree)
13546 (and org-highlight-sparse-tree-matches
13547 (org-get-heading) (match-end 0)
13548 (org-highlight-new-match
13549 (match-beginning 1) (match-end 1)))
13550 (org-show-context 'tags-tree))
13551 ((eq action 'agenda)
13552 (setq txt (org-agenda-format-item
13554 (concat
13555 (if (eq org-tags-match-list-sublevels 'indented)
13556 (make-string (1- level) ?.) "")
13557 (org-get-heading))
13558 level category
13559 tags-list)
13560 priority (org-get-priority txt))
13561 (goto-char lspos)
13562 (setq marker (org-agenda-new-marker))
13563 (org-add-props txt props
13564 'org-marker marker 'org-hd-marker marker 'org-category category
13565 'todo-state todo
13566 'priority priority 'type "tagsmatch")
13567 (push txt rtn))
13568 ((functionp action)
13569 (setq org-map-continue-from nil)
13570 (save-excursion
13571 (setq rtn1 (funcall action))
13572 (push rtn1 rtn)))
13573 (t (error "Invalid action")))
13575 ;; if we are to skip sublevels, jump to end of subtree
13576 (unless org-tags-match-list-sublevels
13577 (org-end-of-subtree t)
13578 (backward-char 1))))
13579 ;; Get the correct position from where to continue
13580 (if org-map-continue-from
13581 (goto-char org-map-continue-from)
13582 (and (= (point) lspos) (end-of-line 1)))))
13583 (when (and (eq action 'sparse-tree)
13584 (not org-sparse-tree-open-archived-trees))
13585 (org-hide-archived-subtrees (point-min) (point-max)))
13586 (nreverse rtn)))
13588 (defun org-remove-uninherited-tags (tags)
13589 "Remove all tags that are not inherited from the list TAGS."
13590 (cond
13591 ((eq org-use-tag-inheritance t)
13592 (if org-tags-exclude-from-inheritance
13593 (org-delete-all org-tags-exclude-from-inheritance tags)
13594 tags))
13595 ((not org-use-tag-inheritance) nil)
13596 ((stringp org-use-tag-inheritance)
13597 (delq nil (mapcar
13598 (lambda (x)
13599 (if (and (string-match org-use-tag-inheritance x)
13600 (not (member x org-tags-exclude-from-inheritance)))
13601 x nil))
13602 tags)))
13603 ((listp org-use-tag-inheritance)
13604 (delq nil (mapcar
13605 (lambda (x)
13606 (if (member x org-use-tag-inheritance) x nil))
13607 tags)))))
13609 (defun org-match-sparse-tree (&optional todo-only match)
13610 "Create a sparse tree according to tags string MATCH.
13611 MATCH can contain positive and negative selection of tags, like
13612 \"+WORK+URGENT-WITHBOSS\".
13613 If optional argument TODO-ONLY is non-nil, only select lines that are
13614 also TODO lines."
13615 (interactive "P")
13616 (org-agenda-prepare-buffers (list (current-buffer)))
13617 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13619 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13621 (defvar org-cached-props nil)
13622 (defun org-cached-entry-get (pom property)
13623 (if (or (eq t org-use-property-inheritance)
13624 (and (stringp org-use-property-inheritance)
13625 (string-match org-use-property-inheritance property))
13626 (and (listp org-use-property-inheritance)
13627 (member property org-use-property-inheritance)))
13628 ;; Caching is not possible, check it directly
13629 (org-entry-get pom property 'inherit)
13630 ;; Get all properties, so that we can do complicated checks easily
13631 (cdr (assoc property (or org-cached-props
13632 (setq org-cached-props
13633 (org-entry-properties pom)))))))
13635 (defun org-global-tags-completion-table (&optional files)
13636 "Return the list of all tags in all agenda buffer/files.
13637 Optional FILES argument is a list of files which can be used
13638 instead of the agenda files."
13639 (save-excursion
13640 (org-uniquify
13641 (delq nil
13642 (apply 'append
13643 (mapcar
13644 (lambda (file)
13645 (set-buffer (find-file-noselect file))
13646 (append (org-get-buffer-tags)
13647 (mapcar (lambda (x) (if (stringp (car-safe x))
13648 (list (car-safe x)) nil))
13649 org-tag-alist)))
13650 (if (and files (car files))
13651 files
13652 (org-agenda-files))))))))
13654 (defun org-make-tags-matcher (match)
13655 "Create the TAGS/TODO matcher form for the selection string MATCH.
13657 The variable `todo-only' is scoped dynamically into this function.
13658 It will be set to t if the matcher restricts matching to TODO entries,
13659 otherwise will not be touched.
13661 Returns a cons of the selection string MATCH and the constructed
13662 lisp form implementing the matcher. The matcher is to be evaluated
13663 at an Org entry, with point on the headline, and returns t if the
13664 entry matches the selection string MATCH. The returned lisp form
13665 references two variables with information about the entry, which
13666 must be bound around the form's evaluation: todo, the TODO keyword
13667 at the entry (or nil of none); and tags-list, the list of all tags
13668 at the entry including inherited ones. Additionally, the category
13669 of the entry (if any) must be specified as the text property
13670 'org-category on the headline.
13672 See also `org-scan-tags'.
13674 (declare (special todo-only))
13675 (unless (boundp 'todo-only)
13676 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13677 (unless match
13678 ;; Get a new match request, with completion
13679 (let ((org-last-tags-completion-table
13680 (org-global-tags-completion-table)))
13681 (setq match (org-completing-read-no-i
13682 "Match: " 'org-tags-completion-function nil nil nil
13683 'org-tags-history))))
13685 ;; Parse the string and create a lisp form
13686 (let ((match0 match)
13687 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13688 minus tag mm
13689 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13690 orterms term orlist re-p str-p level-p level-op time-p
13691 prop-p pn pv po gv rest)
13692 (if (string-match "/+" match)
13693 ;; match contains also a todo-matching request
13694 (progn
13695 (setq tagsmatch (substring match 0 (match-beginning 0))
13696 todomatch (substring match (match-end 0)))
13697 (if (string-match "^!" todomatch)
13698 (setq todo-only t todomatch (substring todomatch 1)))
13699 (if (string-match "^\\s-*$" todomatch)
13700 (setq todomatch nil)))
13701 ;; only matching tags
13702 (setq tagsmatch match todomatch nil))
13704 ;; Make the tags matcher
13705 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13706 (setq tagsmatcher t)
13707 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13708 (while (setq term (pop orterms))
13709 (while (and (equal (substring term -1) "\\") orterms)
13710 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13711 (while (string-match re term)
13712 (setq rest (substring term (match-end 0))
13713 minus (and (match-end 1)
13714 (equal (match-string 1 term) "-"))
13715 tag (save-match-data (replace-regexp-in-string
13716 "\\\\-" "-"
13717 (match-string 2 term)))
13718 re-p (equal (string-to-char tag) ?{)
13719 level-p (match-end 4)
13720 prop-p (match-end 5)
13721 mm (cond
13722 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13723 (level-p
13724 (setq level-op (org-op-to-function (match-string 3 term)))
13725 `(,level-op level ,(string-to-number
13726 (match-string 4 term))))
13727 (prop-p
13728 (setq pn (match-string 5 term)
13729 po (match-string 6 term)
13730 pv (match-string 7 term)
13731 re-p (equal (string-to-char pv) ?{)
13732 str-p (equal (string-to-char pv) ?\")
13733 time-p (save-match-data
13734 (string-match "^\"[[<].*[]>]\"$" pv))
13735 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13736 (if time-p (setq pv (org-matcher-time pv)))
13737 (setq po (org-op-to-function po (if time-p 'time str-p)))
13738 (cond
13739 ((equal pn "CATEGORY")
13740 (setq gv '(get-text-property (point) 'org-category)))
13741 ((equal pn "TODO")
13742 (setq gv 'todo))
13744 (setq gv `(org-cached-entry-get nil ,pn))))
13745 (if re-p
13746 (if (eq po 'org<>)
13747 `(not (string-match ,pv (or ,gv "")))
13748 `(string-match ,pv (or ,gv "")))
13749 (if str-p
13750 `(,po (or ,gv "") ,pv)
13751 `(,po (string-to-number (or ,gv ""))
13752 ,(string-to-number pv) ))))
13753 (t `(member ,tag tags-list)))
13754 mm (if minus (list 'not mm) mm)
13755 term rest)
13756 (push mm tagsmatcher))
13757 (push (if (> (length tagsmatcher) 1)
13758 (cons 'and tagsmatcher)
13759 (car tagsmatcher))
13760 orlist)
13761 (setq tagsmatcher nil))
13762 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13763 (setq tagsmatcher
13764 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13765 ;; Make the todo matcher
13766 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13767 (setq todomatcher t)
13768 (setq orterms (org-split-string todomatch "|") orlist nil)
13769 (while (setq term (pop orterms))
13770 (while (string-match re term)
13771 (setq minus (and (match-end 1)
13772 (equal (match-string 1 term) "-"))
13773 kwd (match-string 2 term)
13774 re-p (equal (string-to-char kwd) ?{)
13775 term (substring term (match-end 0))
13776 mm (if re-p
13777 `(string-match ,(substring kwd 1 -1) todo)
13778 (list 'equal 'todo kwd))
13779 mm (if minus (list 'not mm) mm))
13780 (push mm todomatcher))
13781 (push (if (> (length todomatcher) 1)
13782 (cons 'and todomatcher)
13783 (car todomatcher))
13784 orlist)
13785 (setq todomatcher nil))
13786 (setq todomatcher (if (> (length orlist) 1)
13787 (cons 'or orlist) (car orlist))))
13789 ;; Return the string and lisp forms of the matcher
13790 (setq matcher (if todomatcher
13791 (list 'and tagsmatcher todomatcher)
13792 tagsmatcher))
13793 (when todo-only
13794 (setq matcher (list 'and '(member todo org-not-done-keywords)
13795 matcher)))
13796 (cons match0 matcher)))
13798 (defun org-op-to-function (op &optional stringp)
13799 "Turn an operator into the appropriate function."
13800 (setq op
13801 (cond
13802 ((equal op "<" ) '(< string< org-time<))
13803 ((equal op ">" ) '(> org-string> org-time>))
13804 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13805 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13806 ((member op '("=" "==")) '(= string= org-time=))
13807 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13808 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13810 (defun org<> (a b) (not (= a b)))
13811 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13812 (defun org-string>= (a b) (not (string< a b)))
13813 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13814 (defun org-string<> (a b) (not (string= a b)))
13815 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13816 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13817 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13818 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13819 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13820 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13821 (defun org-2ft (s)
13822 "Convert S to a floating point time.
13823 If S is already a number, just return it. If it is a string, parse
13824 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13825 (cond
13826 ((numberp s) s)
13827 ((stringp s)
13828 (condition-case nil
13829 (float-time (apply 'encode-time (org-parse-time-string s)))
13830 (error 0.)))
13831 (t 0.)))
13833 (defun org-time-today ()
13834 "Time in seconds today at 0:00.
13835 Returns the float number of seconds since the beginning of the
13836 epoch to the beginning of today (00:00)."
13837 (float-time (apply 'encode-time
13838 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13840 (defun org-matcher-time (s)
13841 "Interpret a time comparison value."
13842 (save-match-data
13843 (cond
13844 ((string= s "<now>") (float-time))
13845 ((string= s "<today>") (org-time-today))
13846 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13847 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13848 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13849 (+ (org-time-today)
13850 (* (string-to-number (match-string 1 s))
13851 (cdr (assoc (match-string 2 s)
13852 '(("d" . 86400.0) ("w" . 604800.0)
13853 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13854 (t (org-2ft s)))))
13856 (defun org-match-any-p (re list)
13857 "Does re match any element of list?"
13858 (setq list (mapcar (lambda (x) (string-match re x)) list))
13859 (delq nil list))
13861 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13862 (defvar org-tags-overlay (make-overlay 1 1))
13863 (org-detach-overlay org-tags-overlay)
13865 (defun org-get-local-tags-at (&optional pos)
13866 "Get a list of tags defined in the current headline."
13867 (org-get-tags-at pos 'local))
13869 (defun org-get-local-tags ()
13870 "Get a list of tags defined in the current headline."
13871 (org-get-tags-at nil 'local))
13873 (defun org-get-tags-at (&optional pos local)
13874 "Get a list of all headline tags applicable at POS.
13875 POS defaults to point. If tags are inherited, the list contains
13876 the targets in the same sequence as the headlines appear, i.e.
13877 the tags of the current headline come last.
13878 When LOCAL is non-nil, only return tags from the current headline,
13879 ignore inherited ones."
13880 (interactive)
13881 (if (and org-trust-scanner-tags
13882 (or (not pos) (equal pos (point)))
13883 (not local))
13884 org-scanner-tags
13885 (let (tags ltags lastpos parent)
13886 (save-excursion
13887 (save-restriction
13888 (widen)
13889 (goto-char (or pos (point)))
13890 (save-match-data
13891 (catch 'done
13892 (condition-case nil
13893 (progn
13894 (org-back-to-heading t)
13895 (while (not (equal lastpos (point)))
13896 (setq lastpos (point))
13897 (when (looking-at
13898 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13899 (setq ltags (org-split-string
13900 (org-match-string-no-properties 1) ":"))
13901 (when parent
13902 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13903 (setq tags (append
13904 (if parent
13905 (org-remove-uninherited-tags ltags)
13906 ltags)
13907 tags)))
13908 (or org-use-tag-inheritance (throw 'done t))
13909 (if local (throw 'done t))
13910 (or (org-up-heading-safe) (error nil))
13911 (setq parent t)))
13912 (error nil)))))
13913 (if local
13914 tags
13915 (reverse (delete-dups
13916 (reverse (append
13917 (org-remove-uninherited-tags
13918 org-file-tags) tags)))))))))
13920 (defun org-add-prop-inherited (s)
13921 (add-text-properties 0 (length s) '(inherited t) s)
13924 (defun org-toggle-tag (tag &optional onoff)
13925 "Toggle the tag TAG for the current line.
13926 If ONOFF is `on' or `off', don't toggle but set to this state."
13927 (let (res current)
13928 (save-excursion
13929 (org-back-to-heading t)
13930 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13931 (point-at-eol) t)
13932 (progn
13933 (setq current (match-string 1))
13934 (replace-match ""))
13935 (setq current ""))
13936 (setq current (nreverse (org-split-string current ":")))
13937 (cond
13938 ((eq onoff 'on)
13939 (setq res t)
13940 (or (member tag current) (push tag current)))
13941 ((eq onoff 'off)
13942 (or (not (member tag current)) (setq current (delete tag current))))
13943 (t (if (member tag current)
13944 (setq current (delete tag current))
13945 (setq res t)
13946 (push tag current))))
13947 (end-of-line 1)
13948 (if current
13949 (progn
13950 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13951 (org-set-tags nil t))
13952 (delete-horizontal-space))
13953 (run-hooks 'org-after-tags-change-hook))
13954 res))
13956 (defun org-align-tags-here (to-col)
13957 ;; Assumes that this is a headline
13958 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13959 (beginning-of-line 1)
13960 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13961 (< pos (match-beginning 2)))
13962 (progn
13963 (setq tags-l (- (match-end 2) (match-beginning 2)))
13964 (goto-char (match-beginning 1))
13965 (insert " ")
13966 (delete-region (point) (1+ (match-beginning 2)))
13967 (setq ncol (max (current-column)
13968 (1+ col)
13969 (if (> to-col 0)
13970 to-col
13971 (- (abs to-col) tags-l))))
13972 (setq p (point))
13973 (insert (make-string (- ncol (current-column)) ?\ ))
13974 (setq ncol (current-column))
13975 (when indent-tabs-mode (tabify p (point-at-eol)))
13976 (org-move-to-column (min ncol col) t))
13977 (goto-char pos))))
13979 (defun org-set-tags-command (&optional arg just-align)
13980 "Call the set-tags command for the current entry."
13981 (interactive "P")
13982 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13983 (org-set-tags arg just-align)
13984 (save-excursion
13985 (unless (and (org-region-active-p)
13986 org-loop-over-headlines-in-active-region)
13987 (org-back-to-heading t))
13988 (org-set-tags arg just-align))))
13990 (defun org-set-tags-to (data)
13991 "Set the tags of the current entry to DATA, replacing the current tags.
13992 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13993 If DATA is nil or the empty string, any tags will be removed."
13994 (interactive "sTags: ")
13995 (setq data
13996 (cond
13997 ((eq data nil) "")
13998 ((equal data "") "")
13999 ((stringp data)
14000 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14001 ":"))
14002 ((listp data)
14003 (concat ":" (mapconcat 'identity data ":") ":"))))
14004 (when data
14005 (save-excursion
14006 (org-back-to-heading t)
14007 (when (looking-at org-complex-heading-regexp)
14008 (if (match-end 5)
14009 (progn
14010 (goto-char (match-beginning 5))
14011 (insert data)
14012 (delete-region (point) (point-at-eol))
14013 (org-set-tags nil 'align))
14014 (goto-char (point-at-eol))
14015 (insert " " data)
14016 (org-set-tags nil 'align)))
14017 (beginning-of-line 1)
14018 (if (looking-at ".*?\\([ \t]+\\)$")
14019 (delete-region (match-beginning 1) (match-end 1))))))
14021 (defun org-align-all-tags ()
14022 "Align the tags i all headings."
14023 (interactive)
14024 (save-excursion
14025 (or (ignore-errors (org-back-to-heading t))
14026 (outline-next-heading))
14027 (if (org-at-heading-p)
14028 (org-set-tags t)
14029 (message "No headings"))))
14031 (defvar org-indent-indentation-per-level)
14032 (defun org-set-tags (&optional arg just-align)
14033 "Set the tags for the current headline.
14034 With prefix ARG, realign all tags in headings in the current buffer."
14035 (interactive "P")
14036 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14037 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14038 'region-start-level 'region))
14039 org-loop-over-headlines-in-active-region)
14040 (org-map-entries
14041 ;; We don't use ARG and JUST-ALIGN here these args are not
14042 ;; useful when looping over headlines
14043 `(org-set-tags)
14044 org-loop-over-headlines-in-active-region
14045 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14046 (let* ((re org-outline-regexp-bol)
14047 (current (unless arg (org-get-tags-string)))
14048 (col (current-column))
14049 (org-setting-tags t)
14050 table current-tags inherited-tags ; computed below when needed
14051 tags p0 c0 c1 rpl di tc level)
14052 (if arg
14053 (save-excursion
14054 (goto-char (point-min))
14055 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14056 (while (re-search-forward re nil t)
14057 (org-set-tags nil t)
14058 (end-of-line 1)))
14059 (message "All tags realigned to column %d" org-tags-column))
14060 (if just-align
14061 (setq tags current)
14062 ;; Get a new set of tags from the user
14063 (save-excursion
14064 (setq table (append org-tag-persistent-alist
14065 (or org-tag-alist (org-get-buffer-tags))
14066 (and
14067 org-complete-tags-always-offer-all-agenda-tags
14068 (org-global-tags-completion-table
14069 (org-agenda-files))))
14070 org-last-tags-completion-table table
14071 current-tags (org-split-string current ":")
14072 inherited-tags (nreverse
14073 (nthcdr (length current-tags)
14074 (nreverse (org-get-tags-at))))
14075 tags
14076 (if (or (eq t org-use-fast-tag-selection)
14077 (and org-use-fast-tag-selection
14078 (delq nil (mapcar 'cdr table))))
14079 (org-fast-tag-selection
14080 current-tags inherited-tags table
14081 (if org-fast-tag-selection-include-todo
14082 org-todo-key-alist))
14083 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14084 (org-trim
14085 (org-icompleting-read "Tags: "
14086 'org-tags-completion-function
14087 nil nil current 'org-tags-history))))))
14088 (while (string-match "[-+&]+" tags)
14089 ;; No boolean logic, just a list
14090 (setq tags (replace-match ":" t t tags))))
14092 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14094 (if org-tags-sort-function
14095 (setq tags (mapconcat 'identity
14096 (sort (org-split-string
14097 tags (org-re "[^[:alnum:]_@#%]+"))
14098 org-tags-sort-function) ":")))
14100 (if (string-match "\\`[\t ]*\\'" tags)
14101 (setq tags "")
14102 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14103 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14105 ;; Insert new tags at the correct column
14106 (beginning-of-line 1)
14107 (setq level (or (and (looking-at org-outline-regexp)
14108 (- (match-end 0) (point) 1))
14110 (cond
14111 ((and (equal current "") (equal tags "")))
14112 ((re-search-forward
14113 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14114 (point-at-eol) t)
14115 (if (equal tags "")
14116 (setq rpl "")
14117 (goto-char (match-beginning 0))
14118 (setq c0 (current-column)
14119 ;; compute offset for the case of org-indent-mode active
14120 di (if org-indent-mode
14121 (* (1- org-indent-indentation-per-level) (1- level))
14123 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14124 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14125 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14126 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14127 (replace-match rpl t t)
14128 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14129 tags)
14130 (t (error "Tags alignment failed")))
14131 (org-move-to-column col)
14132 (unless just-align
14133 (run-hooks 'org-after-tags-change-hook))))))
14135 (defun org-change-tag-in-region (beg end tag off)
14136 "Add or remove TAG for each entry in the region.
14137 This works in the agenda, and also in an org-mode buffer."
14138 (interactive
14139 (list (region-beginning) (region-end)
14140 (let ((org-last-tags-completion-table
14141 (if (derived-mode-p 'org-mode)
14142 (org-get-buffer-tags)
14143 (org-global-tags-completion-table))))
14144 (org-icompleting-read
14145 "Tag: " 'org-tags-completion-function nil nil nil
14146 'org-tags-history))
14147 (progn
14148 (message "[s]et or [r]emove? ")
14149 (equal (read-char-exclusive) ?r))))
14150 (if (fboundp 'deactivate-mark) (deactivate-mark))
14151 (let ((agendap (equal major-mode 'org-agenda-mode))
14152 l1 l2 m buf pos newhead (cnt 0))
14153 (goto-char end)
14154 (setq l2 (1- (org-current-line)))
14155 (goto-char beg)
14156 (setq l1 (org-current-line))
14157 (loop for l from l1 to l2 do
14158 (org-goto-line l)
14159 (setq m (get-text-property (point) 'org-hd-marker))
14160 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14161 (and agendap m))
14162 (setq buf (if agendap (marker-buffer m) (current-buffer))
14163 pos (if agendap m (point)))
14164 (with-current-buffer buf
14165 (save-excursion
14166 (save-restriction
14167 (goto-char pos)
14168 (setq cnt (1+ cnt))
14169 (org-toggle-tag tag (if off 'off 'on))
14170 (setq newhead (org-get-heading)))))
14171 (and agendap (org-agenda-change-all-lines newhead m))))
14172 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14174 (defun org-tags-completion-function (string predicate &optional flag)
14175 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14176 (confirm (lambda (x) (stringp (car x)))))
14177 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14178 (setq s1 (match-string 1 string)
14179 s2 (match-string 2 string))
14180 (setq s1 "" s2 string))
14181 (cond
14182 ((eq flag nil)
14183 ;; try completion
14184 (setq rtn (try-completion s2 ctable confirm))
14185 (if (stringp rtn)
14186 (setq rtn
14187 (concat s1 s2 (substring rtn (length s2))
14188 (if (and org-add-colon-after-tag-completion
14189 (assoc rtn ctable))
14190 ":" ""))))
14191 rtn)
14192 ((eq flag t)
14193 ;; all-completions
14194 (all-completions s2 ctable confirm)
14196 ((eq flag 'lambda)
14197 ;; exact match?
14198 (assoc s2 ctable)))
14201 (defun org-fast-tag-insert (kwd tags face &optional end)
14202 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14203 (insert (format "%-12s" (concat kwd ":"))
14204 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14205 (or end "")))
14207 (defun org-fast-tag-show-exit (flag)
14208 (save-excursion
14209 (org-goto-line 3)
14210 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14211 (replace-match ""))
14212 (when flag
14213 (end-of-line 1)
14214 (org-move-to-column (- (window-width) 19) t)
14215 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14217 (defun org-set-current-tags-overlay (current prefix)
14218 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14219 (if (featurep 'xemacs)
14220 (org-overlay-display org-tags-overlay (concat prefix s)
14221 'secondary-selection)
14222 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14223 (org-overlay-display org-tags-overlay (concat prefix s)))))
14225 (defvar org-last-tag-selection-key nil)
14226 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14227 "Fast tag selection with single keys.
14228 CURRENT is the current list of tags in the headline, INHERITED is the
14229 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14230 possibly with grouping information. TODO-TABLE is a similar table with
14231 TODO keywords, should these have keys assigned to them.
14232 If the keys are nil, a-z are automatically assigned.
14233 Returns the new tags string, or nil to not change the current settings."
14234 (let* ((fulltable (append table todo-table))
14235 (maxlen (apply 'max (mapcar
14236 (lambda (x)
14237 (if (stringp (car x)) (string-width (car x)) 0))
14238 fulltable)))
14239 (buf (current-buffer))
14240 (expert (eq org-fast-tag-selection-single-key 'expert))
14241 (buffer-tags nil)
14242 (fwidth (+ maxlen 3 1 3))
14243 (ncol (/ (- (window-width) 4) fwidth))
14244 (i-face 'org-done)
14245 (c-face 'org-todo)
14246 tg cnt e c char c1 c2 ntable tbl rtn
14247 ov-start ov-end ov-prefix
14248 (exit-after-next org-fast-tag-selection-single-key)
14249 (done-keywords org-done-keywords)
14250 groups ingroup)
14251 (save-excursion
14252 (beginning-of-line 1)
14253 (if (looking-at
14254 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14255 (setq ov-start (match-beginning 1)
14256 ov-end (match-end 1)
14257 ov-prefix "")
14258 (setq ov-start (1- (point-at-eol))
14259 ov-end (1+ ov-start))
14260 (skip-chars-forward "^\n\r")
14261 (setq ov-prefix
14262 (concat
14263 (buffer-substring (1- (point)) (point))
14264 (if (> (current-column) org-tags-column)
14266 (make-string (- org-tags-column (current-column)) ?\ ))))))
14267 (move-overlay org-tags-overlay ov-start ov-end)
14268 (save-window-excursion
14269 (if expert
14270 (set-buffer (get-buffer-create " *Org tags*"))
14271 (delete-other-windows)
14272 (split-window-vertically)
14273 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14274 (erase-buffer)
14275 (org-set-local 'org-done-keywords done-keywords)
14276 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14277 (org-fast-tag-insert "Current" current c-face "\n\n")
14278 (org-fast-tag-show-exit exit-after-next)
14279 (org-set-current-tags-overlay current ov-prefix)
14280 (setq tbl fulltable char ?a cnt 0)
14281 (while (setq e (pop tbl))
14282 (cond
14283 ((equal (car e) :startgroup)
14284 (push '() groups) (setq ingroup t)
14285 (when (not (= cnt 0))
14286 (setq cnt 0)
14287 (insert "\n"))
14288 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14289 ((equal (car e) :endgroup)
14290 (setq ingroup nil cnt 0)
14291 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14292 ((equal e '(:newline))
14293 (when (not (= cnt 0))
14294 (setq cnt 0)
14295 (insert "\n")
14296 (setq e (car tbl))
14297 (while (equal (car tbl) '(:newline))
14298 (insert "\n")
14299 (setq tbl (cdr tbl)))))
14301 (setq tg (copy-sequence (car e)) c2 nil)
14302 (if (cdr e)
14303 (setq c (cdr e))
14304 ;; automatically assign a character.
14305 (setq c1 (string-to-char
14306 (downcase (substring
14307 tg (if (= (string-to-char tg) ?@) 1 0)))))
14308 (if (or (rassoc c1 ntable) (rassoc c1 table))
14309 (while (or (rassoc char ntable) (rassoc char table))
14310 (setq char (1+ char)))
14311 (setq c2 c1))
14312 (setq c (or c2 char)))
14313 (if ingroup (push tg (car groups)))
14314 (setq tg (org-add-props tg nil 'face
14315 (cond
14316 ((not (assoc tg table))
14317 (org-get-todo-face tg))
14318 ((member tg current) c-face)
14319 ((member tg inherited) i-face))))
14320 (if (and (= cnt 0) (not ingroup)) (insert " "))
14321 (insert "[" c "] " tg (make-string
14322 (- fwidth 4 (length tg)) ?\ ))
14323 (push (cons tg c) ntable)
14324 (when (= (setq cnt (1+ cnt)) ncol)
14325 (insert "\n")
14326 (if ingroup (insert " "))
14327 (setq cnt 0)))))
14328 (setq ntable (nreverse ntable))
14329 (insert "\n")
14330 (goto-char (point-min))
14331 (if (not expert) (org-fit-window-to-buffer))
14332 (setq rtn
14333 (catch 'exit
14334 (while t
14335 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14336 (if (not groups) "no " "")
14337 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14338 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14339 (setq org-last-tag-selection-key c)
14340 (cond
14341 ((= c ?\r) (throw 'exit t))
14342 ((= c ?!)
14343 (setq groups (not groups))
14344 (goto-char (point-min))
14345 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14346 ((= c ?\C-c)
14347 (if (not expert)
14348 (org-fast-tag-show-exit
14349 (setq exit-after-next (not exit-after-next)))
14350 (setq expert nil)
14351 (delete-other-windows)
14352 (set-window-buffer (split-window-vertically) " *Org tags*")
14353 (org-switch-to-buffer-other-window " *Org tags*")
14354 (org-fit-window-to-buffer)))
14355 ((or (= c ?\C-g)
14356 (and (= c ?q) (not (rassoc c ntable))))
14357 (org-detach-overlay org-tags-overlay)
14358 (setq quit-flag t))
14359 ((= c ?\ )
14360 (setq current nil)
14361 (if exit-after-next (setq exit-after-next 'now)))
14362 ((= c ?\t)
14363 (condition-case nil
14364 (setq tg (org-icompleting-read
14365 "Tag: "
14366 (or buffer-tags
14367 (with-current-buffer buf
14368 (org-get-buffer-tags)))))
14369 (quit (setq tg "")))
14370 (when (string-match "\\S-" tg)
14371 (add-to-list 'buffer-tags (list tg))
14372 (if (member tg current)
14373 (setq current (delete tg current))
14374 (push tg current)))
14375 (if exit-after-next (setq exit-after-next 'now)))
14376 ((setq e (rassoc c todo-table) tg (car e))
14377 (with-current-buffer buf
14378 (save-excursion (org-todo tg)))
14379 (if exit-after-next (setq exit-after-next 'now)))
14380 ((setq e (rassoc c ntable) tg (car e))
14381 (if (member tg current)
14382 (setq current (delete tg current))
14383 (loop for g in groups do
14384 (if (member tg g)
14385 (mapc (lambda (x)
14386 (setq current (delete x current)))
14387 g)))
14388 (push tg current))
14389 (if exit-after-next (setq exit-after-next 'now))))
14391 ;; Create a sorted list
14392 (setq current
14393 (sort current
14394 (lambda (a b)
14395 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14396 (if (eq exit-after-next 'now) (throw 'exit t))
14397 (goto-char (point-min))
14398 (beginning-of-line 2)
14399 (delete-region (point) (point-at-eol))
14400 (org-fast-tag-insert "Current" current c-face)
14401 (org-set-current-tags-overlay current ov-prefix)
14402 (while (re-search-forward
14403 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14404 (setq tg (match-string 1))
14405 (add-text-properties
14406 (match-beginning 1) (match-end 1)
14407 (list 'face
14408 (cond
14409 ((member tg current) c-face)
14410 ((member tg inherited) i-face)
14411 (t (get-text-property (match-beginning 1) 'face))))))
14412 (goto-char (point-min)))))
14413 (org-detach-overlay org-tags-overlay)
14414 (if rtn
14415 (mapconcat 'identity current ":")
14416 nil))))
14418 (defun org-get-tags-string ()
14419 "Get the TAGS string in the current headline."
14420 (unless (org-at-heading-p t)
14421 (error "Not on a heading"))
14422 (save-excursion
14423 (beginning-of-line 1)
14424 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14425 (org-match-string-no-properties 1)
14426 "")))
14428 (defun org-get-tags ()
14429 "Get the list of tags specified in the current headline."
14430 (org-split-string (org-get-tags-string) ":"))
14432 (defun org-get-buffer-tags ()
14433 "Get a table of all tags used in the buffer, for completion."
14434 (let (tags)
14435 (save-excursion
14436 (goto-char (point-min))
14437 (while (re-search-forward
14438 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14439 (when (equal (char-after (point-at-bol 0)) ?*)
14440 (mapc (lambda (x) (add-to-list 'tags x))
14441 (org-split-string (org-match-string-no-properties 1) ":")))))
14442 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14443 (mapcar 'list tags)))
14445 ;;;; The mapping API
14447 (defun org-map-entries (func &optional match scope &rest skip)
14448 "Call FUNC at each headline selected by MATCH in SCOPE.
14450 FUNC is a function or a lisp form. The function will be called without
14451 arguments, with the cursor positioned at the beginning of the headline.
14452 The return values of all calls to the function will be collected and
14453 returned as a list.
14455 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14456 does not need to preserve point. After evaluation, the cursor will be
14457 moved to the end of the line (presumably of the headline of the
14458 processed entry) and search continues from there. Under some
14459 circumstances, this may not produce the wanted results. For example,
14460 if you have removed (e.g. archived) the current (sub)tree it could
14461 mean that the next entry will be skipped entirely. In such cases, you
14462 can specify the position from where search should continue by making
14463 FUNC set the variable `org-map-continue-from' to the desired buffer
14464 position.
14466 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14467 Only headlines that are matched by this query will be considered during
14468 the iteration. When MATCH is nil or t, all headlines will be
14469 visited by the iteration.
14471 SCOPE determines the scope of this command. It can be any of:
14473 nil The current buffer, respecting the restriction if any
14474 tree The subtree started with the entry at point
14475 region The entries within the active region, if any
14476 region-start-level
14477 The entries within the active region, but only those at
14478 the same level than the first one.
14479 file The current buffer, without restriction
14480 file-with-archives
14481 The current buffer, and any archives associated with it
14482 agenda All agenda files
14483 agenda-with-archives
14484 All agenda files with any archive files associated with them
14485 \(file1 file2 ...)
14486 If this is a list, all files in the list will be scanned
14488 The remaining args are treated as settings for the skipping facilities of
14489 the scanner. The following items can be given here:
14491 archive skip trees with the archive tag.
14492 comment skip trees with the COMMENT keyword
14493 function or Emacs Lisp form:
14494 will be used as value for `org-agenda-skip-function', so whenever
14495 the function returns t, FUNC will not be called for that
14496 entry and search will continue from the point where the
14497 function leaves it.
14499 If your function needs to retrieve the tags including inherited tags
14500 at the *current* entry, you can use the value of the variable
14501 `org-scanner-tags' which will be much faster than getting the value
14502 with `org-get-tags-at'. If your function gets properties with
14503 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14504 to t around the call to `org-entry-properties' to get the same speedup.
14505 Note that if your function moves around to retrieve tags and properties at
14506 a *different* entry, you cannot use these techniques."
14507 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14508 (not (org-region-active-p)))
14509 (let* ((org-agenda-archives-mode nil) ; just to make sure
14510 (org-agenda-skip-archived-trees (memq 'archive skip))
14511 (org-agenda-skip-comment-trees (memq 'comment skip))
14512 (org-agenda-skip-function
14513 (car (org-delete-all '(comment archive) skip)))
14514 (org-tags-match-list-sublevels t)
14515 (start-level (eq scope 'region-start-level))
14516 matcher file res
14517 org-todo-keywords-for-agenda
14518 org-done-keywords-for-agenda
14519 org-todo-keyword-alist-for-agenda
14520 org-drawers-for-agenda
14521 org-tag-alist-for-agenda
14522 todo-only)
14524 (cond
14525 ((eq match t) (setq matcher t))
14526 ((eq match nil) (setq matcher t))
14527 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14529 (save-excursion
14530 (save-restriction
14531 (cond ((eq scope 'tree)
14532 (org-back-to-heading t)
14533 (org-narrow-to-subtree)
14534 (setq scope nil))
14535 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14536 (org-region-active-p))
14537 ;; If needed, set start-level to a string like "2"
14538 (when start-level
14539 (save-excursion
14540 (goto-char (region-beginning))
14541 (unless (org-at-heading-p) (outline-next-heading))
14542 (setq start-level (org-current-level))))
14543 (narrow-to-region (region-beginning)
14544 (save-excursion
14545 (goto-char (region-end))
14546 (unless (and (bolp) (org-at-heading-p))
14547 (outline-next-heading))
14548 (point)))
14549 (setq scope nil)))
14551 (if (not scope)
14552 (progn
14553 (org-agenda-prepare-buffers
14554 (list (buffer-file-name (current-buffer))))
14555 (setq res (org-scan-tags func matcher todo-only start-level)))
14556 ;; Get the right scope
14557 (cond
14558 ((and scope (listp scope) (symbolp (car scope)))
14559 (setq scope (eval scope)))
14560 ((eq scope 'agenda)
14561 (setq scope (org-agenda-files t)))
14562 ((eq scope 'agenda-with-archives)
14563 (setq scope (org-agenda-files t))
14564 (setq scope (org-add-archive-files scope)))
14565 ((eq scope 'file)
14566 (setq scope (list (buffer-file-name))))
14567 ((eq scope 'file-with-archives)
14568 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14569 (org-agenda-prepare-buffers scope)
14570 (while (setq file (pop scope))
14571 (with-current-buffer (org-find-base-buffer-visiting file)
14572 (save-excursion
14573 (save-restriction
14574 (widen)
14575 (goto-char (point-min))
14576 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14577 res)))
14579 ;;;; Properties
14581 ;;; Setting and retrieving properties
14583 (defconst org-special-properties
14584 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14585 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14586 "The special properties valid in Org-mode.
14588 These are properties that are not defined in the property drawer,
14589 but in some other way.")
14591 (defconst org-default-properties
14592 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14593 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14594 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14595 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14596 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14597 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14598 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14599 "Some properties that are used by Org-mode for various purposes.
14600 Being in this list makes sure that they are offered for completion.")
14602 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14603 "Regular expression matching the first line of a property drawer.")
14605 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14606 "Regular expression matching the last line of a property drawer.")
14608 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14609 "Regular expression matching the first line of a property drawer.")
14611 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14612 "Regular expression matching the first line of a property drawer.")
14614 (defconst org-property-drawer-re
14615 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14616 org-property-end-re "\\)\n?")
14617 "Matches an entire property drawer.")
14619 (defconst org-clock-drawer-re
14620 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14621 org-property-end-re "\\)\n?")
14622 "Matches an entire clock drawer.")
14624 (defsubst org-re-property (property)
14625 "Return a regexp matching a PROPERTY line.
14626 Match group 1 will be set to the value."
14627 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14629 (defsubst org-re-property-keyword (property)
14630 "Return a regexp matching a PROPERTY line, possibly with no
14631 value for the property."
14632 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14634 (defun org-property-action ()
14635 "Do an action on properties."
14636 (interactive)
14637 (let (c)
14638 (org-at-property-p)
14639 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14640 (setq c (read-char-exclusive))
14641 (cond
14642 ((equal c ?s)
14643 (call-interactively 'org-set-property))
14644 ((equal c ?d)
14645 (call-interactively 'org-delete-property))
14646 ((equal c ?D)
14647 (call-interactively 'org-delete-property-globally))
14648 ((equal c ?c)
14649 (call-interactively 'org-compute-property-at-point))
14650 (t (error "No such property action %c" c)))))
14652 (defun org-inc-effort ()
14653 "Increment the value of the effort property in the current entry."
14654 (interactive)
14655 (org-set-effort nil t))
14657 (defun org-set-effort (&optional value increment)
14658 "Set the effort property of the current entry.
14659 With numerical prefix arg, use the nth allowed value, 0 stands for the
14660 10th allowed value.
14662 When INCREMENT is non-nil, set the property to the next allowed value."
14663 (interactive "P")
14664 (if (equal value 0) (setq value 10))
14665 (let* ((completion-ignore-case t)
14666 (prop org-effort-property)
14667 (cur (org-entry-get nil prop))
14668 (allowed (org-property-get-allowed-values nil prop 'table))
14669 (existing (mapcar 'list (org-property-values prop)))
14671 (val (cond
14672 ((stringp value) value)
14673 ((and allowed (integerp value))
14674 (or (car (nth (1- value) allowed))
14675 (car (org-last allowed))))
14676 ((and allowed increment)
14677 (or (caadr (member (list cur) allowed))
14678 (error "Allowed effort values are not set")))
14679 (allowed
14680 (message "Select 1-9,0, [RET%s]: %s"
14681 (if cur (concat "=" cur) "")
14682 (mapconcat 'car allowed " "))
14683 (setq rpl (read-char-exclusive))
14684 (if (equal rpl ?\r)
14686 (setq rpl (- rpl ?0))
14687 (if (equal rpl 0) (setq rpl 10))
14688 (if (and (> rpl 0) (<= rpl (length allowed)))
14689 (car (nth (1- rpl) allowed))
14690 (org-completing-read "Effort: " allowed nil))))
14692 (let (org-completion-use-ido org-completion-use-iswitchb)
14693 (org-completing-read
14694 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14695 (concat "[" cur "]") "")
14696 ": ")
14697 existing nil nil "" nil cur))))))
14698 (unless (equal (org-entry-get nil prop) val)
14699 (org-entry-put nil prop val))
14700 (save-excursion
14701 (org-back-to-heading t)
14702 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14703 (message "%s is now %s" prop val)))
14705 (defun org-at-property-p ()
14706 "Is cursor inside a property drawer?"
14707 (save-excursion
14708 (beginning-of-line 1)
14709 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14710 (save-match-data ;; Used by calling procedures
14711 (let ((p (point))
14712 (range (unless (org-before-first-heading-p)
14713 (org-get-property-block))))
14714 (and range (<= (car range) p) (< p (cdr range))))))))
14716 (defun org-get-property-block (&optional beg end force)
14717 "Return the (beg . end) range of the body of the property drawer.
14718 BEG and END are the beginning and end of the current subtree, or of
14719 the part before the first headline. If they are not given, they will
14720 be found. If the drawer does not exist and FORCE is non-nil, create
14721 the drawer."
14722 (catch 'exit
14723 (save-excursion
14724 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14725 (progn (org-back-to-heading t) (point))))
14726 (end (or end (and (not (outline-next-heading)) (point-max))
14727 (point))))
14728 (goto-char beg)
14729 (if (re-search-forward org-property-start-re end t)
14730 (setq beg (1+ (match-end 0)))
14731 (if force
14732 (save-excursion
14733 (org-insert-property-drawer)
14734 (setq end (progn (outline-next-heading) (point))))
14735 (throw 'exit nil))
14736 (goto-char beg)
14737 (if (re-search-forward org-property-start-re end t)
14738 (setq beg (1+ (match-end 0)))))
14739 (if (re-search-forward org-property-end-re end t)
14740 (setq end (match-beginning 0))
14741 (or force (throw 'exit nil))
14742 (goto-char beg)
14743 (setq end beg)
14744 (org-indent-line)
14745 (insert ":END:\n"))
14746 (cons beg end)))))
14748 (defun org-entry-properties (&optional pom which specific)
14749 "Get all properties of the entry at point-or-marker POM.
14750 This includes the TODO keyword, the tags, time strings for deadline,
14751 scheduled, and clocking, and any additional properties defined in the
14752 entry. The return value is an alist, keys may occur multiple times
14753 if the property key was used several times.
14754 POM may also be nil, in which case the current entry is used.
14755 If WHICH is nil or `all', get all properties. If WHICH is
14756 `special' or `standard', only get that subclass. If WHICH
14757 is a string only get exactly this property. SPECIFIC can be a string, the
14758 specific property we are interested in. Specifying it can speed
14759 things up because then unnecessary parsing is avoided."
14760 (setq which (or which 'all))
14761 (org-with-point-at pom
14762 (let ((clockstr (substring org-clock-string 0 -1))
14763 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14764 (case-fold-search nil)
14765 beg end range props sum-props key key1 value string clocksum clocksumt)
14766 (save-excursion
14767 (when (condition-case nil
14768 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14769 (error nil))
14770 (setq beg (point))
14771 (setq sum-props (get-text-property (point) 'org-summaries))
14772 (setq clocksum (get-text-property (point) :org-clock-minutes)
14773 clocksumt (get-text-property (point) :org-clock-minutes-today))
14774 (outline-next-heading)
14775 (setq end (point))
14776 (when (memq which '(all special))
14777 ;; Get the special properties, like TODO and tags
14778 (goto-char beg)
14779 (when (and (or (not specific) (string= specific "TODO"))
14780 (looking-at org-todo-line-regexp) (match-end 2))
14781 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14782 (when (and (or (not specific) (string= specific "PRIORITY"))
14783 (looking-at org-priority-regexp))
14784 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14785 (when (or (not specific) (string= specific "FILE"))
14786 (push (cons "FILE" buffer-file-name) props))
14787 (when (and (or (not specific) (string= specific "TAGS"))
14788 (setq value (org-get-tags-string))
14789 (string-match "\\S-" value))
14790 (push (cons "TAGS" value) props))
14791 (when (and (or (not specific) (string= specific "ALLTAGS"))
14792 (setq value (org-get-tags-at)))
14793 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14794 ":"))
14795 props))
14796 (when (or (not specific) (string= specific "BLOCKED"))
14797 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14798 (when (or (not specific)
14799 (member specific
14800 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14801 "TIMESTAMP" "TIMESTAMP_IA")))
14802 (catch 'match
14803 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14804 (setq key (if (match-end 1)
14805 (substring (org-match-string-no-properties 1)
14806 0 -1))
14807 string (if (equal key clockstr)
14808 (org-trim
14809 (buffer-substring-no-properties
14810 (match-beginning 3) (goto-char
14811 (point-at-eol))))
14812 (substring (org-match-string-no-properties 3)
14813 1 -1)))
14814 ;; Get the correct property name from the key. This is
14815 ;; necessary if the user has configured time keywords.
14816 (setq key1 (concat key ":"))
14817 (cond
14818 ((not key)
14819 (setq key
14820 (if (= (char-after (match-beginning 3)) ?\[)
14821 "TIMESTAMP_IA" "TIMESTAMP")))
14822 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14823 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14824 ((equal key1 org-closed-string) (setq key "CLOSED"))
14825 ((equal key1 org-clock-string) (setq key "CLOCK")))
14826 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14827 (progn
14828 (push (cons key string) props)
14829 ;; no need to search further if match is found
14830 (throw 'match t))
14831 (when (or (equal key "CLOCK") (not (assoc key props)))
14832 (push (cons key string) props)))))))
14834 (when (memq which '(all standard))
14835 ;; Get the standard properties, like :PROP: ...
14836 (setq range (org-get-property-block beg end))
14837 (when range
14838 (goto-char (car range))
14839 (while (re-search-forward
14840 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14841 (cdr range) t)
14842 (setq key (org-match-string-no-properties 1)
14843 value (org-trim (or (org-match-string-no-properties 2) "")))
14844 (unless (member key excluded)
14845 (push (cons key (or value "")) props)))))
14846 (if clocksum
14847 (push (cons "CLOCKSUM"
14848 (org-columns-number-to-string (/ (float clocksum) 60.)
14849 'add_times))
14850 props))
14851 (if clocksumt
14852 (push (cons "CLOCKSUM_T"
14853 (org-columns-number-to-string (/ (float clocksumt) 60.)
14854 'add_times))
14855 props))
14856 (unless (assoc "CATEGORY" props)
14857 (push (cons "CATEGORY" (org-get-category)) props))
14858 (append sum-props (nreverse props)))))))
14860 (defun org-entry-get (pom property &optional inherit literal-nil)
14861 "Get value of PROPERTY for entry or content at point-or-marker POM.
14862 If INHERIT is non-nil and the entry does not have the property,
14863 then also check higher levels of the hierarchy.
14864 If INHERIT is the symbol `selective', use inheritance only if the setting
14865 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14866 If the property is present but empty, the return value is the empty string.
14867 If the property is not present at all, nil is returned.
14869 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14870 do not interpret it as the list atom nil. This is used for inheritance
14871 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14872 (org-with-point-at pom
14873 (if (and inherit (if (eq inherit 'selective)
14874 (org-property-inherit-p property)
14876 (org-entry-get-with-inheritance property literal-nil)
14877 (if (member property org-special-properties)
14878 ;; We need a special property. Use `org-entry-properties' to
14879 ;; retrieve it, but specify the wanted property
14880 (cdr (assoc property (org-entry-properties nil 'special property)))
14881 (let ((range (org-get-property-block)))
14882 (when (and range (not (eq (car range) (cdr range))))
14883 (let* ((props (list (or (assoc property org-file-properties)
14884 (assoc property org-global-properties)
14885 (assoc property org-global-properties-fixed))))
14886 (ap (lambda (key)
14887 (when (re-search-forward
14888 (org-re-property key) (cdr range) t)
14889 (setq props
14890 (org-update-property-plist
14892 (if (match-end 1)
14893 (org-match-string-no-properties 1) "")
14894 props)))))
14895 val)
14896 (goto-char (car range))
14897 (funcall ap property)
14898 (goto-char (car range))
14899 (while (funcall ap (concat property "+")))
14900 (setq val (cdr (assoc property props)))
14901 (when val (if literal-nil val (org-not-nil val))))))))))
14903 (defun org-property-or-variable-value (var &optional inherit)
14904 "Check if there is a property fixing the value of VAR.
14905 If yes, return this value. If not, return the current value of the variable."
14906 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14907 (if (and prop (stringp prop) (string-match "\\S-" prop))
14908 (read prop)
14909 (symbol-value var))))
14911 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14912 "Delete the property PROPERTY from entry at point-or-marker POM.
14913 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14914 an empty drawer to delete."
14915 (org-with-point-at pom
14916 (if (member property org-special-properties)
14917 nil ; cannot delete these properties.
14918 (let ((range (org-get-property-block)))
14919 (if (and range
14920 (goto-char (car range))
14921 (re-search-forward
14922 (org-re-property property)
14923 (cdr range) t))
14924 (progn
14925 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14926 (and delete-empty-drawer
14927 (org-remove-empty-drawer-at
14928 delete-empty-drawer (car range)))
14930 nil)))))
14932 ;; Multi-values properties are properties that contain multiple values
14933 ;; These values are assumed to be single words, separated by whitespace.
14934 (defun org-entry-add-to-multivalued-property (pom property value)
14935 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14936 (let* ((old (org-entry-get pom property))
14937 (values (and old (org-split-string old "[ \t]"))))
14938 (setq value (org-entry-protect-space value))
14939 (unless (member value values)
14940 (setq values (cons value values))
14941 (org-entry-put pom property
14942 (mapconcat 'identity values " ")))))
14944 (defun org-entry-remove-from-multivalued-property (pom property value)
14945 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14946 (let* ((old (org-entry-get pom property))
14947 (values (and old (org-split-string old "[ \t]"))))
14948 (setq value (org-entry-protect-space value))
14949 (when (member value values)
14950 (setq values (delete value values))
14951 (org-entry-put pom property
14952 (mapconcat 'identity values " ")))))
14954 (defun org-entry-member-in-multivalued-property (pom property value)
14955 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14956 (let* ((old (org-entry-get pom property))
14957 (values (and old (org-split-string old "[ \t]"))))
14958 (setq value (org-entry-protect-space value))
14959 (member value values)))
14961 (defun org-entry-get-multivalued-property (pom property)
14962 "Return a list of values in a multivalued property."
14963 (let* ((value (org-entry-get pom property))
14964 (values (and value (org-split-string value "[ \t]"))))
14965 (mapcar 'org-entry-restore-space values)))
14967 (defun org-entry-put-multivalued-property (pom property &rest values)
14968 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14969 VALUES should be a list of strings. Spaces will be protected."
14970 (org-entry-put pom property
14971 (mapconcat 'org-entry-protect-space values " "))
14972 (let* ((value (org-entry-get pom property))
14973 (values (and value (org-split-string value "[ \t]"))))
14974 (mapcar 'org-entry-restore-space values)))
14976 (defun org-entry-protect-space (s)
14977 "Protect spaces and newline in string S."
14978 (while (string-match " " s)
14979 (setq s (replace-match "%20" t t s)))
14980 (while (string-match "\n" s)
14981 (setq s (replace-match "%0A" t t s)))
14984 (defun org-entry-restore-space (s)
14985 "Restore spaces and newline in string S."
14986 (while (string-match "%20" s)
14987 (setq s (replace-match " " t t s)))
14988 (while (string-match "%0A" s)
14989 (setq s (replace-match "\n" t t s)))
14992 (defvar org-entry-property-inherited-from (make-marker)
14993 "Marker pointing to the entry from where a property was inherited.
14994 Each call to `org-entry-get-with-inheritance' will set this marker to the
14995 location of the entry where the inheritance search matched. If there was
14996 no match, the marker will point nowhere.
14997 Note that also `org-entry-get' calls this function, if the INHERIT flag
14998 is set.")
15000 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15001 "Get PROPERTY of entry or content at point, search higher levels if needed.
15002 The search will stop at the first ancestor which has the property defined.
15003 If the value found is \"nil\", return nil to show that the property
15004 should be considered as undefined (this is the meaning of nil here).
15005 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15006 (move-marker org-entry-property-inherited-from nil)
15007 (let (tmp)
15008 (save-excursion
15009 (save-restriction
15010 (widen)
15011 (catch 'ex
15012 (while t
15013 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15014 (or (ignore-errors (org-back-to-heading t))
15015 (goto-char (point-min)))
15016 (move-marker org-entry-property-inherited-from (point))
15017 (throw 'ex tmp))
15018 (or (ignore-errors (org-up-heading-safe))
15019 (throw 'ex nil))))))
15020 (setq tmp (or tmp
15021 (cdr (assoc property org-file-properties))
15022 (cdr (assoc property org-global-properties))
15023 (cdr (assoc property org-global-properties-fixed))))
15024 (if literal-nil tmp (org-not-nil tmp))))
15026 (defvar org-property-changed-functions nil
15027 "Hook called when the value of a property has changed.
15028 Each hook function should accept two arguments, the name of the property
15029 and the new value.")
15031 (defun org-entry-put (pom property value)
15032 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15033 (org-with-point-at pom
15034 (org-back-to-heading t)
15035 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15036 range)
15037 (cond
15038 ((equal property "TODO")
15039 (when (and (stringp value) (string-match "\\S-" value)
15040 (not (member value org-todo-keywords-1)))
15041 (error "\"%s\" is not a valid TODO state" value))
15042 (if (or (not value)
15043 (not (string-match "\\S-" value)))
15044 (setq value 'none))
15045 (org-todo value)
15046 (org-set-tags nil 'align))
15047 ((equal property "PRIORITY")
15048 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15049 (string-to-char value) ?\ ))
15050 (org-set-tags nil 'align))
15051 ((equal property "CLOCKSUM")
15052 (if (not (re-search-forward
15053 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15054 (error "Cannot find a clock log")
15055 (goto-char (- (match-end 1) 2))
15056 (cond
15057 ((eq value 'earlier) (org-timestamp-down))
15058 ((eq value 'later) (org-timestamp-up)))
15059 (org-clock-sum-current-item)))
15060 ((equal property "SCHEDULED")
15061 (if (re-search-forward org-scheduled-time-regexp end t)
15062 (cond
15063 ((eq value 'earlier) (org-timestamp-change -1 'day))
15064 ((eq value 'later) (org-timestamp-change 1 'day))
15065 (t (call-interactively 'org-schedule)))
15066 (call-interactively 'org-schedule)))
15067 ((equal property "DEADLINE")
15068 (if (re-search-forward org-deadline-time-regexp end t)
15069 (cond
15070 ((eq value 'earlier) (org-timestamp-change -1 'day))
15071 ((eq value 'later) (org-timestamp-change 1 'day))
15072 (t (call-interactively 'org-deadline)))
15073 (call-interactively 'org-deadline)))
15074 ((member property org-special-properties)
15075 (error "The %s property can not yet be set with `org-entry-put'"
15076 property))
15077 (t ; a non-special property
15078 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15079 (setq range (org-get-property-block beg end 'force))
15080 (goto-char (car range))
15081 (if (re-search-forward
15082 (org-re-property-keyword property) (cdr range) t)
15083 (progn
15084 (delete-region (match-beginning 0) (match-end 0))
15085 (goto-char (match-beginning 0)))
15086 (goto-char (cdr range))
15087 (insert "\n")
15088 (backward-char 1)
15089 (org-indent-line))
15090 (insert ":" property ":")
15091 (and value (insert " " value))
15092 (org-indent-line)))))
15093 (run-hook-with-args 'org-property-changed-functions property value)))
15095 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15096 "Get all property keys in the current buffer.
15097 With INCLUDE-SPECIALS, also list the special properties that reflect things
15098 like tags and TODO state.
15099 With INCLUDE-DEFAULTS, also include properties that has special meaning
15100 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15101 and others.
15102 With INCLUDE-COLUMNS, also include property names given in COLUMN
15103 formats in the current buffer."
15104 (let (rtn range cfmt s p)
15105 (save-excursion
15106 (save-restriction
15107 (widen)
15108 (goto-char (point-min))
15109 (while (re-search-forward org-property-start-re nil t)
15110 (setq range (org-get-property-block))
15111 (goto-char (car range))
15112 (while (re-search-forward
15113 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15114 (cdr range) t)
15115 (add-to-list 'rtn (org-match-string-no-properties 1)))
15116 (outline-next-heading))))
15118 (when include-specials
15119 (setq rtn (append org-special-properties rtn)))
15121 (when include-defaults
15122 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15123 (add-to-list 'rtn org-effort-property))
15125 (when include-columns
15126 (save-excursion
15127 (save-restriction
15128 (widen)
15129 (goto-char (point-min))
15130 (while (re-search-forward
15131 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15132 nil t)
15133 (setq cfmt (match-string 2) s 0)
15134 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15135 cfmt s)
15136 (setq s (match-end 0)
15137 p (match-string 1 cfmt))
15138 (unless (or (equal p "ITEM")
15139 (member p org-special-properties))
15140 (add-to-list 'rtn (match-string 1 cfmt))))))))
15142 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15144 (defun org-property-values (key)
15145 "Return a list of all values of property KEY in the current buffer."
15146 (save-excursion
15147 (save-restriction
15148 (widen)
15149 (goto-char (point-min))
15150 (let ((re (org-re-property key))
15151 values)
15152 (while (re-search-forward re nil t)
15153 (add-to-list 'values (org-trim (match-string 1))))
15154 (delete "" values)))))
15156 (defun org-insert-property-drawer ()
15157 "Insert a property drawer into the current entry."
15158 (org-back-to-heading t)
15159 (looking-at org-outline-regexp)
15160 (let ((indent (if org-adapt-indentation
15161 (- (match-end 0) (match-beginning 0))
15163 (beg (point))
15164 (re (concat "^[ \t]*" org-keyword-time-regexp))
15165 end hiddenp)
15166 (outline-next-heading)
15167 (setq end (point))
15168 (goto-char beg)
15169 (while (re-search-forward re end t))
15170 (setq hiddenp (outline-invisible-p))
15171 (end-of-line 1)
15172 (and (equal (char-after) ?\n) (forward-char 1))
15173 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15174 (if (member (match-string 1) '("CLOCK:" ":END:"))
15175 ;; just skip this line
15176 (beginning-of-line 2)
15177 ;; Drawer start, find the end
15178 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15179 (beginning-of-line 1)))
15180 (org-skip-over-state-notes)
15181 (skip-chars-backward " \t\n\r")
15182 (if (eq (char-before) ?*) (forward-char 1))
15183 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15184 (beginning-of-line 0)
15185 (org-indent-to-column indent)
15186 (beginning-of-line 2)
15187 (org-indent-to-column indent)
15188 (beginning-of-line 0)
15189 (if hiddenp
15190 (save-excursion
15191 (org-back-to-heading t)
15192 (hide-entry))
15193 (org-flag-drawer t))))
15195 (defun org-insert-drawer (&optional arg drawer)
15196 "Insert a drawer at point.
15198 Optional argument DRAWER, when non-nil, is a string representing
15199 drawer's name. Otherwise, the user is prompted for a name.
15201 If a region is active, insert the drawer around that region
15202 instead.
15204 Point is left between drawer's boundaries."
15205 (interactive "P")
15206 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15207 "LOGBOOK"))
15208 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15209 ;; internally by Org. They are meant to be inserted
15210 ;; automatically.
15211 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15212 ;; Remove system drawers from list. Note: For some reason,
15213 ;; `org-completing-read' ignores the predicate while
15214 ;; `completing-read' handles it fine.
15215 (drawer (if arg "PROPERTIES"
15216 (or drawer
15217 (completing-read
15218 "Drawer: " org-drawers
15219 (lambda (d) (not (member d system-drawers))))))))
15220 (cond
15221 ;; With C-u, fall back on `org-insert-property-drawer'
15222 (arg (org-insert-property-drawer))
15223 ;; With an active region, insert a drawer at point.
15224 ((not (org-region-active-p))
15225 (progn
15226 (unless (bolp) (insert "\n"))
15227 (insert (format ":%s:\n\n:END:\n" drawer))
15228 (forward-line -2)))
15229 ;; Otherwise, insert the drawer at point
15231 (let ((rbeg (region-beginning))
15232 (rend (copy-marker (region-end))))
15233 (unwind-protect
15234 (progn
15235 (goto-char rbeg)
15236 (beginning-of-line)
15237 (when (save-excursion
15238 (re-search-forward org-outline-regexp-bol rend t))
15239 (error "Drawers cannot contain headlines"))
15240 ;; Position point at the beginning of the first
15241 ;; non-blank line in region. Insert drawer's opening
15242 ;; there, then indent it.
15243 (org-skip-whitespace)
15244 (beginning-of-line)
15245 (insert ":" drawer ":\n")
15246 (forward-line -1)
15247 (indent-for-tab-command)
15248 ;; Move point to the beginning of the first blank line
15249 ;; after the last non-blank line in region. Insert
15250 ;; drawer's closing, then indent it.
15251 (goto-char rend)
15252 (skip-chars-backward " \r\t\n")
15253 (insert "\n:END:")
15254 (deactivate-mark t)
15255 (indent-for-tab-command)
15256 (unless (eolp) (insert "\n")))
15257 ;; Clear marker, whatever the outcome of insertion is.
15258 (set-marker rend nil)))))))
15260 (defvar org-property-set-functions-alist nil
15261 "Property set function alist.
15262 Each entry should have the following format:
15264 (PROPERTY . READ-FUNCTION)
15266 The read function will be called with the same argument as
15267 `org-completing-read'.")
15269 (defun org-set-property-function (property)
15270 "Get the function that should be used to set PROPERTY.
15271 This is computed according to `org-property-set-functions-alist'."
15272 (or (cdr (assoc property org-property-set-functions-alist))
15273 'org-completing-read))
15275 (defun org-read-property-value (property)
15276 "Read PROPERTY value from user."
15277 (let* ((completion-ignore-case t)
15278 (allowed (org-property-get-allowed-values nil property 'table))
15279 (cur (org-entry-get nil property))
15280 (prompt (concat property " value"
15281 (if (and cur (string-match "\\S-" cur))
15282 (concat " [" cur "]") "") ": "))
15283 (set-function (org-set-property-function property))
15284 (val (if allowed
15285 (funcall set-function prompt allowed nil
15286 (not (get-text-property 0 'org-unrestricted
15287 (caar allowed))))
15288 (let (org-completion-use-ido org-completion-use-iswitchb)
15289 (funcall set-function prompt
15290 (mapcar 'list (org-property-values property))
15291 nil nil "" nil cur)))))
15292 (if (equal val "")
15294 val)))
15296 (defvar org-last-set-property nil)
15297 (defvar org-last-set-property-value nil)
15298 (defun org-read-property-name ()
15299 "Read a property name."
15300 (let* ((completion-ignore-case t)
15301 (keys (org-buffer-property-keys nil t t))
15302 (default-prop (or (save-excursion
15303 (save-match-data
15304 (beginning-of-line)
15305 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15306 (null (string= (match-string 1) "END"))
15307 (match-string 1))))
15308 org-last-set-property))
15309 (property (org-icompleting-read
15310 (concat "Property"
15311 (if default-prop (concat " [" default-prop "]") "")
15312 ": ")
15313 (mapcar 'list keys)
15314 nil nil nil nil
15315 default-prop)))
15316 (if (member property keys)
15317 property
15318 (or (cdr (assoc (downcase property)
15319 (mapcar (lambda (x) (cons (downcase x) x))
15320 keys)))
15321 property))))
15323 (defun org-set-property-and-value (use-last)
15324 "Allow to set [PROPERTY]: [value] direction from prompt.
15325 When use-default, don't even ask, just use the last
15326 \"[PROPERTY]: [value]\" string from the history."
15327 (interactive "P")
15328 (let* ((completion-ignore-case t)
15329 (pv (or (and use-last org-last-set-property-value)
15330 (org-completing-read
15331 "Enter a \"[Property]: [value]\" pair: "
15332 nil nil nil nil nil
15333 org-last-set-property-value)))
15334 prop val)
15335 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15336 (setq prop (match-string 1 pv)
15337 val (match-string 2 pv))
15338 (org-set-property prop val))))
15340 (defun org-set-property (property value)
15341 "In the current entry, set PROPERTY to VALUE.
15342 When called interactively, this will prompt for a property name, offering
15343 completion on existing and default properties. And then it will prompt
15344 for a value, offering completion either on allowed values (via an inherited
15345 xxx_ALL property) or on existing values in other instances of this property
15346 in the current file."
15347 (interactive (list nil nil))
15348 (let* ((property (or property (org-read-property-name)))
15349 (value (or value (org-read-property-value property)))
15350 (fn (cdr (assoc property org-properties-postprocess-alist))))
15351 (setq org-last-set-property property)
15352 (setq org-last-set-property-value (concat property ": " value))
15353 ;; Possibly postprocess the inserted value:
15354 (when fn (setq value (funcall fn value)))
15355 (unless (equal (org-entry-get nil property) value)
15356 (org-entry-put nil property value))))
15358 (defun org-delete-property (property &optional delete-empty-drawer)
15359 "In the current entry, delete PROPERTY.
15360 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15361 an empty drawer to delete."
15362 (interactive
15363 (let* ((completion-ignore-case t)
15364 (prop (org-icompleting-read "Property: "
15365 (org-entry-properties nil 'standard))))
15366 (list prop)))
15367 (message "Property %s %s" property
15368 (if (org-entry-delete nil property delete-empty-drawer)
15369 "deleted"
15370 "was not present in the entry")))
15372 (defun org-delete-property-globally (property)
15373 "Remove PROPERTY globally, from all entries."
15374 (interactive
15375 (let* ((completion-ignore-case t)
15376 (prop (org-icompleting-read
15377 "Globally remove property: "
15378 (mapcar 'list (org-buffer-property-keys)))))
15379 (list prop)))
15380 (save-excursion
15381 (save-restriction
15382 (widen)
15383 (goto-char (point-min))
15384 (let ((cnt 0))
15385 (while (re-search-forward
15386 (org-re-property property)
15387 nil t)
15388 (setq cnt (1+ cnt))
15389 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15390 (message "Property \"%s\" removed from %d entries" property cnt)))))
15392 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15394 (defun org-compute-property-at-point ()
15395 "Compute the property at point.
15396 This looks for an enclosing column format, extracts the operator and
15397 then applies it to the property in the column format's scope."
15398 (interactive)
15399 (unless (org-at-property-p)
15400 (error "Not at a property"))
15401 (let ((prop (org-match-string-no-properties 2)))
15402 (org-columns-get-format-and-top-level)
15403 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15404 (error "No operator defined for property %s" prop))
15405 (org-columns-compute prop)))
15407 (defvar org-property-allowed-value-functions nil
15408 "Hook for functions supplying allowed values for a specific property.
15409 The functions must take a single argument, the name of the property, and
15410 return a flat list of allowed values. If \":ETC\" is one of
15411 the values, this means that these values are intended as defaults for
15412 completion, but that other values should be allowed too.
15413 The functions must return nil if they are not responsible for this
15414 property.")
15416 (defun org-property-get-allowed-values (pom property &optional table)
15417 "Get allowed values for the property PROPERTY.
15418 When TABLE is non-nil, return an alist that can directly be used for
15419 completion."
15420 (let (vals)
15421 (cond
15422 ((equal property "TODO")
15423 (setq vals (org-with-point-at pom
15424 (append org-todo-keywords-1 '("")))))
15425 ((equal property "PRIORITY")
15426 (let ((n org-lowest-priority))
15427 (while (>= n org-highest-priority)
15428 (push (char-to-string n) vals)
15429 (setq n (1- n)))))
15430 ((member property org-special-properties))
15431 ((setq vals (run-hook-with-args-until-success
15432 'org-property-allowed-value-functions property)))
15434 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15435 (when (and vals (string-match "\\S-" vals))
15436 (setq vals (car (read-from-string (concat "(" vals ")"))))
15437 (setq vals (mapcar (lambda (x)
15438 (cond ((stringp x) x)
15439 ((numberp x) (number-to-string x))
15440 ((symbolp x) (symbol-name x))
15441 (t "???")))
15442 vals)))))
15443 (when (member ":ETC" vals)
15444 (setq vals (remove ":ETC" vals))
15445 (org-add-props (car vals) '(org-unrestricted t)))
15446 (if table (mapcar 'list vals) vals)))
15448 (defun org-property-previous-allowed-value (&optional previous)
15449 "Switch to the next allowed value for this property."
15450 (interactive)
15451 (org-property-next-allowed-value t))
15453 (defun org-property-next-allowed-value (&optional previous)
15454 "Switch to the next allowed value for this property."
15455 (interactive)
15456 (unless (org-at-property-p)
15457 (error "Not at a property"))
15458 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15459 (key (match-string 2))
15460 (value (match-string 3))
15461 (allowed (or (org-property-get-allowed-values (point) key)
15462 (and (member value '("[ ]" "[-]" "[X]"))
15463 '("[ ]" "[X]"))))
15464 nval)
15465 (unless allowed
15466 (error "Allowed values for this property have not been defined"))
15467 (if previous (setq allowed (reverse allowed)))
15468 (if (member value allowed)
15469 (setq nval (car (cdr (member value allowed)))))
15470 (setq nval (or nval (car allowed)))
15471 (if (equal nval value)
15472 (error "Only one allowed value for this property"))
15473 (org-at-property-p)
15474 (replace-match (concat " :" key ": " nval) t t)
15475 (org-indent-line)
15476 (beginning-of-line 1)
15477 (skip-chars-forward " \t")
15478 (when (equal prop org-effort-property)
15479 (save-excursion
15480 (org-back-to-heading t)
15481 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15482 (run-hook-with-args 'org-property-changed-functions key nval)))
15484 (defun org-find-olp (path &optional this-buffer)
15485 "Return a marker pointing to the entry at outline path OLP.
15486 If anything goes wrong, throw an error.
15487 You can wrap this call to catch the error like this:
15489 (condition-case msg
15490 (org-mobile-locate-entry (match-string 4))
15491 (error (nth 1 msg)))
15493 The return value will then be either a string with the error message,
15494 or a marker if everything is OK.
15496 If THIS-BUFFER is set, the outline path does not contain a file,
15497 only headings."
15498 (let* ((file (if this-buffer buffer-file-name (pop path)))
15499 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15500 (level 1)
15501 (lmin 1)
15502 (lmax 1)
15503 limit re end found pos heading cnt flevel)
15504 (unless buffer (error "File not found :%s" file))
15505 (with-current-buffer buffer
15506 (save-excursion
15507 (save-restriction
15508 (widen)
15509 (setq limit (point-max))
15510 (goto-char (point-min))
15511 (while (setq heading (pop path))
15512 (setq re (format org-complex-heading-regexp-format
15513 (regexp-quote heading)))
15514 (setq cnt 0 pos (point))
15515 (while (re-search-forward re end t)
15516 (setq level (- (match-end 1) (match-beginning 1)))
15517 (if (and (>= level lmin) (<= level lmax))
15518 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15519 (when (= cnt 0) (error "Heading not found on level %d: %s"
15520 lmax heading))
15521 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15522 lmax heading))
15523 (goto-char found)
15524 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15525 (setq end (save-excursion (org-end-of-subtree t t))))
15526 (when (org-at-heading-p)
15527 (point-marker)))))))
15529 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15530 "Find node HEADING in BUFFER.
15531 Return a marker to the heading if it was found, or nil if not.
15532 If POS-ONLY is set, return just the position instead of a marker.
15534 The heading text must match exact, but it may have a TODO keyword,
15535 a priority cookie and tags in the standard locations."
15536 (with-current-buffer (or buffer (current-buffer))
15537 (save-excursion
15538 (save-restriction
15539 (widen)
15540 (goto-char (point-min))
15541 (let (case-fold-search)
15542 (if (re-search-forward
15543 (format org-complex-heading-regexp-format
15544 (regexp-quote heading)) nil t)
15545 (if pos-only
15546 (match-beginning 0)
15547 (move-marker (make-marker) (match-beginning 0)))))))))
15549 (defun org-find-exact-heading-in-directory (heading &optional dir)
15550 "Find Org node headline HEADING in all .org files in directory DIR.
15551 When the target headline is found, return a marker to this location."
15552 (let ((files (directory-files (or dir default-directory)
15553 nil "\\`[^.#].*\\.org\\'"))
15554 file visiting m buffer)
15555 (catch 'found
15556 (while (setq file (pop files))
15557 (message "trying %s" file)
15558 (setq visiting (org-find-base-buffer-visiting file))
15559 (setq buffer (or visiting (find-file-noselect file)))
15560 (setq m (org-find-exact-headline-in-buffer
15561 heading buffer))
15562 (when (and (not m) (not visiting)) (kill-buffer buffer))
15563 (and m (throw 'found m))))))
15565 (defun org-find-entry-with-id (ident)
15566 "Locate the entry that contains the ID property with exact value IDENT.
15567 IDENT can be a string, a symbol or a number, this function will search for
15568 the string representation of it.
15569 Return the position where this entry starts, or nil if there is no such entry."
15570 (interactive "sID: ")
15571 (let ((id (cond
15572 ((stringp ident) ident)
15573 ((symbol-name ident) (symbol-name ident))
15574 ((numberp ident) (number-to-string ident))
15575 (t (error "IDENT %s must be a string, symbol or number" ident))))
15576 (case-fold-search nil))
15577 (save-excursion
15578 (save-restriction
15579 (widen)
15580 (goto-char (point-min))
15581 (when (re-search-forward
15582 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15583 nil t)
15584 (org-back-to-heading t)
15585 (point))))))
15587 ;;;; Timestamps
15589 (defvar org-last-changed-timestamp nil)
15590 (defvar org-last-inserted-timestamp nil
15591 "The last time stamp inserted with `org-insert-time-stamp'.")
15592 (defvar org-time-was-given) ; dynamically scoped parameter
15593 (defvar org-end-time-was-given) ; dynamically scoped parameter
15594 (defvar org-ts-what) ; dynamically scoped parameter
15596 (defun org-time-stamp (arg &optional inactive)
15597 "Prompt for a date/time and insert a time stamp.
15598 If the user specifies a time like HH:MM or if this command is
15599 called with at least one prefix argument, the time stamp contains
15600 the date and the time. Otherwise, only the date is be included.
15602 All parts of a date not specified by the user is filled in from
15603 the current date/time. So if you just press return without
15604 typing anything, the time stamp will represent the current
15605 date/time.
15607 If there is already a timestamp at the cursor, it will be
15608 modified.
15610 With two universal prefix arguments, insert an active timestamp
15611 with the current time without prompting the user."
15612 (interactive "P")
15613 (let* ((ts nil)
15614 (default-time
15615 ;; Default time is either today, or, when entering a range,
15616 ;; the range start.
15617 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15618 (save-excursion
15619 (re-search-backward
15620 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15621 (- (point) 20) t)))
15622 (apply 'encode-time (org-parse-time-string (match-string 1)))
15623 (current-time)))
15624 (default-input (and ts (org-get-compact-tod ts)))
15625 (repeater (save-excursion
15626 (save-match-data
15627 (beginning-of-line)
15628 (when (re-search-forward
15629 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15630 (save-excursion (progn (end-of-line) (point))) t)
15631 (match-string 0)))))
15632 org-time-was-given org-end-time-was-given time)
15633 (cond
15634 ((and (org-at-timestamp-p t)
15635 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15636 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15637 (insert "--")
15638 (setq time (let ((this-command this-command))
15639 (org-read-date arg 'totime nil nil
15640 default-time default-input inactive)))
15641 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15642 ((org-at-timestamp-p t)
15643 (setq time (let ((this-command this-command))
15644 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15645 (when (org-at-timestamp-p t) ; just to get the match data
15646 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15647 (replace-match "")
15648 (setq org-last-changed-timestamp
15649 (org-insert-time-stamp
15650 time (or org-time-was-given arg)
15651 inactive nil nil (list org-end-time-was-given)))
15652 (when repeater (goto-char (1- (point))) (insert " " repeater)
15653 (setq org-last-changed-timestamp
15654 (concat (substring org-last-inserted-timestamp 0 -1)
15655 " " repeater ">"))))
15656 (message "Timestamp updated"))
15657 ((equal arg '(16))
15658 (org-insert-time-stamp (current-time) t))
15660 (setq time (let ((this-command this-command))
15661 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15662 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15663 nil nil (list org-end-time-was-given))))))
15665 ;; FIXME: can we use this for something else, like computing time differences?
15666 (defun org-get-compact-tod (s)
15667 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15668 (let* ((t1 (match-string 1 s))
15669 (h1 (string-to-number (match-string 2 s)))
15670 (m1 (string-to-number (match-string 3 s)))
15671 (t2 (and (match-end 4) (match-string 5 s)))
15672 (h2 (and t2 (string-to-number (match-string 6 s))))
15673 (m2 (and t2 (string-to-number (match-string 7 s))))
15674 dh dm)
15675 (if (not t2)
15677 (setq dh (- h2 h1) dm (- m2 m1))
15678 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15679 (concat t1 "+" (number-to-string dh)
15680 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15682 (defun org-time-stamp-inactive (&optional arg)
15683 "Insert an inactive time stamp.
15684 An inactive time stamp is enclosed in square brackets instead of angle
15685 brackets. It is inactive in the sense that it does not trigger agenda entries,
15686 does not link to the calendar and cannot be changed with the S-cursor keys.
15687 So these are more for recording a certain time/date."
15688 (interactive "P")
15689 (org-time-stamp arg 'inactive))
15691 (defvar org-date-ovl (make-overlay 1 1))
15692 (overlay-put org-date-ovl 'face 'org-date-selected)
15693 (org-detach-overlay org-date-ovl)
15695 (defvar org-ans1) ; dynamically scoped parameter
15696 (defvar org-ans2) ; dynamically scoped parameter
15698 (defvar org-plain-time-of-day-regexp) ; defined below
15700 (defvar org-overriding-default-time nil) ; dynamically scoped
15701 (defvar org-read-date-overlay nil)
15702 (defvar org-dcst nil) ; dynamically scoped
15703 (defvar org-read-date-history nil)
15704 (defvar org-read-date-final-answer nil)
15705 (defvar org-read-date-analyze-futurep nil)
15706 (defvar org-read-date-analyze-forced-year nil)
15707 (defvar org-read-date-inactive)
15709 (defvar org-read-date-minibuffer-local-map
15710 (let ((map (make-sparse-keymap)))
15711 (set-keymap-parent map minibuffer-local-map)
15712 (org-defkey map (kbd ".")
15713 (lambda () (interactive)
15714 (org-eval-in-calendar '(calendar-goto-today))))
15715 (org-defkey map [(meta shift left)]
15716 (lambda () (interactive)
15717 (org-eval-in-calendar '(calendar-backward-month 1))))
15718 (org-defkey map [(meta shift right)]
15719 (lambda () (interactive)
15720 (org-eval-in-calendar '(calendar-forward-month 1))))
15721 (org-defkey map [(meta shift up)]
15722 (lambda () (interactive)
15723 (org-eval-in-calendar '(calendar-backward-year 1))))
15724 (org-defkey map [(meta shift down)]
15725 (lambda () (interactive)
15726 (org-eval-in-calendar '(calendar-forward-year 1))))
15727 (org-defkey map [?\e (shift left)]
15728 (lambda () (interactive)
15729 (org-eval-in-calendar '(calendar-backward-month 1))))
15730 (org-defkey map [?\e (shift right)]
15731 (lambda () (interactive)
15732 (org-eval-in-calendar '(calendar-forward-month 1))))
15733 (org-defkey map [?\e (shift up)]
15734 (lambda () (interactive)
15735 (org-eval-in-calendar '(calendar-backward-year 1))))
15736 (org-defkey map [?\e (shift down)]
15737 (lambda () (interactive)
15738 (org-eval-in-calendar '(calendar-forward-year 1))))
15739 (org-defkey map [(shift up)]
15740 (lambda () (interactive)
15741 (org-eval-in-calendar '(calendar-backward-week 1))))
15742 (org-defkey map [(shift down)]
15743 (lambda () (interactive)
15744 (org-eval-in-calendar '(calendar-forward-week 1))))
15745 (org-defkey map [(shift left)]
15746 (lambda () (interactive)
15747 (org-eval-in-calendar '(calendar-backward-day 1))))
15748 (org-defkey map [(shift right)]
15749 (lambda () (interactive)
15750 (org-eval-in-calendar '(calendar-forward-day 1))))
15751 (org-defkey map "!"
15752 (lambda () (interactive)
15753 (org-eval-in-calendar '(diary-view-entries))
15754 (message "")))
15755 (org-defkey map ">"
15756 (lambda () (interactive)
15757 (org-eval-in-calendar '(scroll-calendar-left 1))))
15758 (org-defkey map "<"
15759 (lambda () (interactive)
15760 (org-eval-in-calendar '(scroll-calendar-right 1))))
15761 (org-defkey map "\C-v"
15762 (lambda () (interactive)
15763 (org-eval-in-calendar
15764 '(calendar-scroll-left-three-months 1))))
15765 (org-defkey map "\M-v"
15766 (lambda () (interactive)
15767 (org-eval-in-calendar
15768 '(calendar-scroll-right-three-months 1))))
15769 map)
15770 "Keymap for minibuffer commands when using `org-read-date'.")
15772 (defun org-read-date (&optional org-with-time to-time from-string prompt
15773 default-time default-input inactive)
15774 "Read a date, possibly a time, and make things smooth for the user.
15775 The prompt will suggest to enter an ISO date, but you can also enter anything
15776 which will at least partially be understood by `parse-time-string'.
15777 Unrecognized parts of the date will default to the current day, month, year,
15778 hour and minute. If this command is called to replace a timestamp at point,
15779 or to enter the second timestamp of a range, the default time is taken
15780 from the existing stamp. Furthermore, the command prefers the future,
15781 so if you are giving a date where the year is not given, and the day-month
15782 combination is already past in the current year, it will assume you
15783 mean next year. For details, see the manual. A few examples:
15785 3-2-5 --> 2003-02-05
15786 feb 15 --> currentyear-02-15
15787 2/15 --> currentyear-02-15
15788 sep 12 9 --> 2009-09-12
15789 12:45 --> today 12:45
15790 22 sept 0:34 --> currentyear-09-22 0:34
15791 12 --> currentyear-currentmonth-12
15792 Fri --> nearest Friday (today or later)
15793 etc.
15795 Furthermore you can specify a relative date by giving, as the *first* thing
15796 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15797 change in days weeks, months, years.
15798 With a single plus or minus, the date is relative to today. With a double
15799 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15800 +4d --> four days from today
15801 +4 --> same as above
15802 +2w --> two weeks from today
15803 ++5 --> five days from default date
15805 The function understands only English month and weekday abbreviations.
15807 While prompting, a calendar is popped up - you can also select the
15808 date with the mouse (button 1). The calendar shows a period of three
15809 months. To scroll it to other months, use the keys `>' and `<'.
15810 If you don't like the calendar, turn it off with
15811 \(setq org-read-date-popup-calendar nil)
15813 With optional argument TO-TIME, the date will immediately be converted
15814 to an internal time.
15815 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15816 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15817 still enter a time, and this function will inform the calling routine
15818 about this change. The calling routine may then choose to change the
15819 format used to insert the time stamp into the buffer to include the time.
15820 With optional argument FROM-STRING, read from this string instead from
15821 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15822 the time/date that is used for everything that is not specified by the
15823 user."
15824 (require 'parse-time)
15825 (let* ((org-time-stamp-rounding-minutes
15826 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15827 (org-dcst org-display-custom-times)
15828 (ct (org-current-time))
15829 (org-def (or org-overriding-default-time default-time ct))
15830 (org-defdecode (decode-time org-def))
15831 (dummy (progn
15832 (when (< (nth 2 org-defdecode) org-extend-today-until)
15833 (setcar (nthcdr 2 org-defdecode) -1)
15834 (setcar (nthcdr 1 org-defdecode) 59)
15835 (setq org-def (apply 'encode-time org-defdecode)
15836 org-defdecode (decode-time org-def)))))
15837 (mouse-autoselect-window nil) ; Don't let the mouse jump
15838 (calendar-frame-setup nil)
15839 (calendar-setup nil)
15840 (calendar-move-hook nil)
15841 (calendar-view-diary-initially-flag nil)
15842 (calendar-view-holidays-initially-flag nil)
15843 (timestr (format-time-string
15844 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15845 (prompt (concat (if prompt (concat prompt " ") "")
15846 (format "Date+time [%s]: " timestr)))
15847 ans (org-ans0 "") org-ans1 org-ans2 final)
15849 (cond
15850 (from-string (setq ans from-string))
15851 (org-read-date-popup-calendar
15852 (save-excursion
15853 (save-window-excursion
15854 (calendar)
15855 (org-eval-in-calendar '(setq cursor-type nil) t)
15856 (unwind-protect
15857 (progn
15858 (calendar-forward-day (- (time-to-days org-def)
15859 (calendar-absolute-from-gregorian
15860 (calendar-current-date))))
15861 (org-eval-in-calendar nil t)
15862 (let* ((old-map (current-local-map))
15863 (map (copy-keymap calendar-mode-map))
15864 (minibuffer-local-map
15865 (copy-keymap org-read-date-minibuffer-local-map)))
15866 (org-defkey map (kbd "RET") 'org-calendar-select)
15867 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15868 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15869 (unwind-protect
15870 (progn
15871 (use-local-map map)
15872 (setq org-read-date-inactive inactive)
15873 (add-hook 'post-command-hook 'org-read-date-display)
15874 (setq org-ans0 (read-string prompt default-input
15875 'org-read-date-history nil))
15876 ;; org-ans0: from prompt
15877 ;; org-ans1: from mouse click
15878 ;; org-ans2: from calendar motion
15879 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15880 (remove-hook 'post-command-hook 'org-read-date-display)
15881 (use-local-map old-map)
15882 (when org-read-date-overlay
15883 (delete-overlay org-read-date-overlay)
15884 (setq org-read-date-overlay nil)))))
15885 (bury-buffer "*Calendar*")))))
15887 (t ; Naked prompt only
15888 (unwind-protect
15889 (setq ans (read-string prompt default-input
15890 'org-read-date-history timestr))
15891 (when org-read-date-overlay
15892 (delete-overlay org-read-date-overlay)
15893 (setq org-read-date-overlay nil)))))
15895 (setq final (org-read-date-analyze ans org-def org-defdecode))
15897 (when org-read-date-analyze-forced-year
15898 (message "Year was forced into %s"
15899 (if org-read-date-force-compatible-dates
15900 "compatible range (1970-2037)"
15901 "range representable on this machine"))
15902 (ding))
15904 ;; One round trip to get rid of 34th of August and stuff like that....
15905 (setq final (decode-time (apply 'encode-time final)))
15907 (setq org-read-date-final-answer ans)
15909 (if to-time
15910 (apply 'encode-time final)
15911 (if (and (boundp 'org-time-was-given) org-time-was-given)
15912 (format "%04d-%02d-%02d %02d:%02d"
15913 (nth 5 final) (nth 4 final) (nth 3 final)
15914 (nth 2 final) (nth 1 final))
15915 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15917 (defvar org-def)
15918 (defvar org-defdecode)
15919 (defvar org-with-time)
15920 (defun org-read-date-display ()
15921 "Display the current date prompt interpretation in the minibuffer."
15922 (when org-read-date-display-live
15923 (when org-read-date-overlay
15924 (delete-overlay org-read-date-overlay))
15925 (when (minibufferp (current-buffer))
15926 (save-excursion
15927 (end-of-line 1)
15928 (while (not (equal (buffer-substring
15929 (max (point-min) (- (point) 4)) (point))
15930 " "))
15931 (insert " ")))
15932 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15933 " " (or org-ans1 org-ans2)))
15934 (org-end-time-was-given nil)
15935 (f (org-read-date-analyze ans org-def org-defdecode))
15936 (fmts (if org-dcst
15937 org-time-stamp-custom-formats
15938 org-time-stamp-formats))
15939 (fmt (if (or org-with-time
15940 (and (boundp 'org-time-was-given) org-time-was-given))
15941 (cdr fmts)
15942 (car fmts)))
15943 (txt (format-time-string fmt (apply 'encode-time f)))
15944 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15945 (txt (concat "=> " txt)))
15946 (when (and org-end-time-was-given
15947 (string-match org-plain-time-of-day-regexp txt))
15948 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15949 org-end-time-was-given
15950 (substring txt (match-end 0)))))
15951 (when org-read-date-analyze-futurep
15952 (setq txt (concat txt " (=>F)")))
15953 (setq org-read-date-overlay
15954 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15955 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15957 (defun org-read-date-analyze (ans org-def org-defdecode)
15958 "Analyze the combined answer of the date prompt."
15959 ;; FIXME: cleanup and comment
15960 (let ((nowdecode (decode-time (current-time)))
15961 delta deltan deltaw deltadef year month day
15962 hour minute second wday pm h2 m2 tl wday1
15963 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15964 (setq org-read-date-analyze-futurep nil
15965 org-read-date-analyze-forced-year nil)
15966 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15967 (setq ans "+0"))
15969 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15970 (setq ans (replace-match "" t t ans)
15971 deltan (car delta)
15972 deltaw (nth 1 delta)
15973 deltadef (nth 2 delta)))
15975 ;; Check if there is an iso week date in there. If yes, store the
15976 ;; info and postpone interpreting it until the rest of the parsing
15977 ;; is done.
15978 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15979 (setq iso-year (if (match-end 1)
15980 (org-small-year-to-year
15981 (string-to-number (match-string 1 ans))))
15982 iso-weekday (if (match-end 3)
15983 (string-to-number (match-string 3 ans)))
15984 iso-week (string-to-number (match-string 2 ans)))
15985 (setq ans (replace-match "" t t ans)))
15987 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15988 (when (string-match
15989 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15990 (setq year (if (match-end 2)
15991 (string-to-number (match-string 2 ans))
15992 (progn (setq kill-year t)
15993 (string-to-number (format-time-string "%Y"))))
15994 month (string-to-number (match-string 3 ans))
15995 day (string-to-number (match-string 4 ans)))
15996 (if (< year 100) (setq year (+ 2000 year)))
15997 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15998 t nil ans)))
16000 ;; Help matching dotted european dates
16001 (when (string-match
16002 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16003 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16004 (setq kill-year t)
16005 (string-to-number (format-time-string "%Y")))
16006 day (string-to-number (match-string 1 ans))
16007 month (string-to-number (match-string 2 ans))
16008 ans (replace-match (format "%04d-%02d-%02d" year month day)
16009 t nil ans)))
16011 ;; Help matching american dates, like 5/30 or 5/30/7
16012 (when (string-match
16013 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16014 (setq year (if (match-end 4)
16015 (string-to-number (match-string 4 ans))
16016 (progn (setq kill-year t)
16017 (string-to-number (format-time-string "%Y"))))
16018 month (string-to-number (match-string 1 ans))
16019 day (string-to-number (match-string 2 ans)))
16020 (if (< year 100) (setq year (+ 2000 year)))
16021 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16022 t nil ans)))
16023 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16024 ;; If there is a time with am/pm, and *no* time without it, we convert
16025 ;; so that matching will be successful.
16026 (loop for i from 1 to 2 do ; twice, for end time as well
16027 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16028 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16029 (setq hour (string-to-number (match-string 1 ans))
16030 minute (if (match-end 3)
16031 (string-to-number (match-string 3 ans))
16033 pm (equal ?p
16034 (string-to-char (downcase (match-string 4 ans)))))
16035 (if (and (= hour 12) (not pm))
16036 (setq hour 0)
16037 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16038 (setq ans (replace-match (format "%02d:%02d" hour minute)
16039 t t ans))))
16041 ;; Check if a time range is given as a duration
16042 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16043 (setq hour (string-to-number (match-string 1 ans))
16044 h2 (+ hour (string-to-number (match-string 3 ans)))
16045 minute (string-to-number (match-string 2 ans))
16046 m2 (+ minute (if (match-end 5) (string-to-number
16047 (match-string 5 ans))0)))
16048 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16049 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16050 t t ans)))
16052 ;; Check if there is a time range
16053 (when (boundp 'org-end-time-was-given)
16054 (setq org-time-was-given nil)
16055 (when (and (string-match org-plain-time-of-day-regexp ans)
16056 (match-end 8))
16057 (setq org-end-time-was-given (match-string 8 ans))
16058 (setq ans (concat (substring ans 0 (match-beginning 7))
16059 (substring ans (match-end 7))))))
16061 (setq tl (parse-time-string ans)
16062 day (or (nth 3 tl) (nth 3 org-defdecode))
16063 month (or (nth 4 tl)
16064 (if (and org-read-date-prefer-future
16065 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16066 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16067 (nth 4 org-defdecode)))
16068 year (or (and (not kill-year) (nth 5 tl))
16069 (if (and org-read-date-prefer-future
16070 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16071 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16072 (nth 5 org-defdecode)))
16073 hour (or (nth 2 tl) (nth 2 org-defdecode))
16074 minute (or (nth 1 tl) (nth 1 org-defdecode))
16075 second (or (nth 0 tl) 0)
16076 wday (nth 6 tl))
16078 (when (and (eq org-read-date-prefer-future 'time)
16079 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16080 (equal day (nth 3 nowdecode))
16081 (equal month (nth 4 nowdecode))
16082 (equal year (nth 5 nowdecode))
16083 (nth 2 tl)
16084 (or (< (nth 2 tl) (nth 2 nowdecode))
16085 (and (= (nth 2 tl) (nth 2 nowdecode))
16086 (nth 1 tl)
16087 (< (nth 1 tl) (nth 1 nowdecode)))))
16088 (setq day (1+ day)
16089 futurep t))
16091 ;; Special date definitions below
16092 (cond
16093 (iso-week
16094 ;; There was an iso week
16095 (require 'cal-iso)
16096 (setq futurep nil)
16097 (setq year (or iso-year year)
16098 day (or iso-weekday wday 1)
16099 wday nil ; to make sure that the trigger below does not match
16100 iso-date (calendar-gregorian-from-absolute
16101 (calendar-absolute-from-iso
16102 (list iso-week day year))))
16103 ; FIXME: Should we also push ISO weeks into the future?
16104 ; (when (and org-read-date-prefer-future
16105 ; (not iso-year)
16106 ; (< (calendar-absolute-from-gregorian iso-date)
16107 ; (time-to-days (current-time))))
16108 ; (setq year (1+ year)
16109 ; iso-date (calendar-gregorian-from-absolute
16110 ; (calendar-absolute-from-iso
16111 ; (list iso-week day year)))))
16112 (setq month (car iso-date)
16113 year (nth 2 iso-date)
16114 day (nth 1 iso-date)))
16115 (deltan
16116 (setq futurep nil)
16117 (unless deltadef
16118 (let ((now (decode-time (current-time))))
16119 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16120 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16121 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16122 ((equal deltaw "m") (setq month (+ month deltan)))
16123 ((equal deltaw "y") (setq year (+ year deltan)))))
16124 ((and wday (not (nth 3 tl)))
16125 ;; Weekday was given, but no day, so pick that day in the week
16126 ;; on or after the derived date.
16127 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16128 (unless (equal wday wday1)
16129 (setq day (+ day (% (- wday wday1 -7) 7))))))
16130 (if (and (boundp 'org-time-was-given)
16131 (nth 2 tl))
16132 (setq org-time-was-given t))
16133 (if (< year 100) (setq year (+ 2000 year)))
16134 ;; Check of the date is representable
16135 (if org-read-date-force-compatible-dates
16136 (progn
16137 (if (< year 1970)
16138 (setq year 1970 org-read-date-analyze-forced-year t))
16139 (if (> year 2037)
16140 (setq year 2037 org-read-date-analyze-forced-year t)))
16141 (condition-case nil
16142 (ignore (encode-time second minute hour day month year))
16143 (error
16144 (setq year (nth 5 org-defdecode))
16145 (setq org-read-date-analyze-forced-year t))))
16146 (setq org-read-date-analyze-futurep futurep)
16147 (list second minute hour day month year)))
16149 (defvar parse-time-weekdays)
16150 (defun org-read-date-get-relative (s today default)
16151 "Check string S for special relative date string.
16152 TODAY and DEFAULT are internal times, for today and for a default.
16153 Return shift list (N what def-flag)
16154 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16155 N is the number of WHATs to shift.
16156 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16157 the DEFAULT date rather than TODAY."
16158 (require 'parse-time)
16159 (when (and
16160 (string-match
16161 (concat
16162 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16163 "\\([0-9]+\\)?"
16164 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16165 "\\([ \t]\\|$\\)") s)
16166 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16167 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16168 (string-to-char (substring (match-string 1 s) -1))
16169 ?+))
16170 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16171 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16172 (what (if (match-end 3) (match-string 3 s) "d"))
16173 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16174 (date (if rel default today))
16175 (wday (nth 6 (decode-time date)))
16176 delta)
16177 (if wday1
16178 (progn
16179 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16180 (if (= dir ?-) (setq delta (- delta 7)))
16181 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16182 (list delta "d" rel))
16183 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16185 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16186 "Turn a user-specified date into the internal representation.
16187 The internal representation needed by the calendar is (month day year).
16188 This is a wrapper to handle the brain-dead convention in calendar that
16189 user function argument order change dependent on argument order."
16190 (if (boundp 'calendar-date-style)
16191 (cond
16192 ((eq calendar-date-style 'american)
16193 (list arg1 arg2 arg3))
16194 ((eq calendar-date-style 'european)
16195 (list arg2 arg1 arg3))
16196 ((eq calendar-date-style 'iso)
16197 (list arg2 arg3 arg1)))
16198 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16199 (if (org-bound-and-true-p european-calendar-style)
16200 (list arg2 arg1 arg3)
16201 (list arg1 arg2 arg3)))))
16203 (defun org-eval-in-calendar (form &optional keepdate)
16204 "Eval FORM in the calendar window and return to current window.
16205 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16206 otherwise stick to the current value of `org-ans2'."
16207 (let ((sf (selected-frame))
16208 (sw (selected-window)))
16209 (select-window (get-buffer-window "*Calendar*" t))
16210 (eval form)
16211 (when (and (not keepdate) (calendar-cursor-to-date))
16212 (let* ((date (calendar-cursor-to-date))
16213 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16214 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16215 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16216 (select-window sw)
16217 (org-select-frame-set-input-focus sf)))
16219 (defun org-calendar-select ()
16220 "Return to `org-read-date' with the date currently selected.
16221 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16222 (interactive)
16223 (when (calendar-cursor-to-date)
16224 (let* ((date (calendar-cursor-to-date))
16225 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16226 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16227 (if (active-minibuffer-window) (exit-minibuffer))))
16229 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16230 "Insert a date stamp for the date given by the internal TIME.
16231 WITH-HM means use the stamp format that includes the time of the day.
16232 INACTIVE means use square brackets instead of angular ones, so that the
16233 stamp will not contribute to the agenda.
16234 PRE and POST are optional strings to be inserted before and after the
16235 stamp.
16236 The command returns the inserted time stamp."
16237 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16238 stamp)
16239 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16240 (insert-before-markers (or pre ""))
16241 (when (listp extra)
16242 (setq extra (car extra))
16243 (if (and (stringp extra)
16244 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16245 (setq extra (format "-%02d:%02d"
16246 (string-to-number (match-string 1 extra))
16247 (string-to-number (match-string 2 extra))))
16248 (setq extra nil)))
16249 (when extra
16250 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16251 (insert-before-markers (setq stamp (format-time-string fmt time)))
16252 (insert-before-markers (or post ""))
16253 (setq org-last-inserted-timestamp stamp)))
16255 (defun org-toggle-time-stamp-overlays ()
16256 "Toggle the use of custom time stamp formats."
16257 (interactive)
16258 (setq org-display-custom-times (not org-display-custom-times))
16259 (unless org-display-custom-times
16260 (let ((p (point-min)) (bmp (buffer-modified-p)))
16261 (while (setq p (next-single-property-change p 'display))
16262 (if (and (get-text-property p 'display)
16263 (eq (get-text-property p 'face) 'org-date))
16264 (remove-text-properties
16265 p (setq p (next-single-property-change p 'display))
16266 '(display t))))
16267 (set-buffer-modified-p bmp)))
16268 (if (featurep 'xemacs)
16269 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16270 (org-restart-font-lock)
16271 (setq org-table-may-need-update t)
16272 (if org-display-custom-times
16273 (message "Time stamps are overlaid with custom format")
16274 (message "Time stamp overlays removed")))
16276 (defun org-display-custom-time (beg end)
16277 "Overlay modified time stamp format over timestamp between BEG and END."
16278 (let* ((ts (buffer-substring beg end))
16279 t1 w1 with-hm tf time str w2 (off 0))
16280 (save-match-data
16281 (setq t1 (org-parse-time-string ts t))
16282 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16283 (setq off (- (match-end 0) (match-beginning 0)))))
16284 (setq end (- end off))
16285 (setq w1 (- end beg)
16286 with-hm (and (nth 1 t1) (nth 2 t1))
16287 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16288 time (org-fix-decoded-time t1)
16289 str (org-add-props
16290 (format-time-string
16291 (substring tf 1 -1) (apply 'encode-time time))
16292 nil 'mouse-face 'highlight)
16293 w2 (length str))
16294 (if (not (= w2 w1))
16295 (add-text-properties (1+ beg) (+ 2 beg)
16296 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16297 (if (featurep 'xemacs)
16298 (progn
16299 (put-text-property beg end 'invisible t)
16300 (put-text-property beg end 'end-glyph (make-glyph str)))
16301 (put-text-property beg end 'display str))))
16303 (defun org-translate-time (string)
16304 "Translate all timestamps in STRING to custom format.
16305 But do this only if the variable `org-display-custom-times' is set."
16306 (when org-display-custom-times
16307 (save-match-data
16308 (let* ((start 0)
16309 (re org-ts-regexp-both)
16310 t1 with-hm inactive tf time str beg end)
16311 (while (setq start (string-match re string start))
16312 (setq beg (match-beginning 0)
16313 end (match-end 0)
16314 t1 (save-match-data
16315 (org-parse-time-string (substring string beg end) t))
16316 with-hm (and (nth 1 t1) (nth 2 t1))
16317 inactive (equal (substring string beg (1+ beg)) "[")
16318 tf (funcall (if with-hm 'cdr 'car)
16319 org-time-stamp-custom-formats)
16320 time (org-fix-decoded-time t1)
16321 str (format-time-string
16322 (concat
16323 (if inactive "[" "<") (substring tf 1 -1)
16324 (if inactive "]" ">"))
16325 (apply 'encode-time time))
16326 string (replace-match str t t string)
16327 start (+ start (length str)))))))
16328 string)
16330 (defun org-fix-decoded-time (time)
16331 "Set 0 instead of nil for the first 6 elements of time.
16332 Don't touch the rest."
16333 (let ((n 0))
16334 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16336 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16338 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16339 "Difference between TIMESTAMP-STRING and now in days.
16340 If SECONDS is non-nil, return the difference in seconds."
16341 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16342 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16343 (funcall fdiff (current-time)))))
16345 (defun org-deadline-close (timestamp-string &optional ndays)
16346 "Is the time in TIMESTAMP-STRING close to the current date?"
16347 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16348 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16349 (not (org-entry-is-done-p))))
16351 (defun org-get-wdays (ts &optional delay zero-delay)
16352 "Get the deadline lead time appropriate for timestring TS.
16353 When DELAY is non-nil, get the delay time for scheduled items
16354 instead of the deadline lead time. When ZERO-DELAY is non-nil
16355 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16356 don't try to find the delay cookie in the scheduled timestamp."
16357 (let ((tv (if delay org-scheduled-delay-days
16358 org-deadline-warning-days)))
16359 (cond
16360 ((or (and delay (< tv 0))
16361 (and delay zero-delay (<= tv 0))
16362 (and (not delay) (<= tv 0)))
16363 ;; Enforce this value no matter what
16364 (- tv))
16365 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16366 ;; lead time is specified.
16367 (floor (* (string-to-number (match-string 1 ts))
16368 (cdr (assoc (match-string 2 ts)
16369 '(("d" . 1) ("w" . 7)
16370 ("m" . 30.4) ("y" . 365.25)
16371 ("h" . 0.041667)))))))
16372 ;; go for the default.
16373 (t tv))))
16375 (defun org-calendar-select-mouse (ev)
16376 "Return to `org-read-date' with the date currently selected.
16377 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16378 (interactive "e")
16379 (mouse-set-point ev)
16380 (when (calendar-cursor-to-date)
16381 (let* ((date (calendar-cursor-to-date))
16382 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16383 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16384 (if (active-minibuffer-window) (exit-minibuffer))))
16386 (defun org-check-deadlines (ndays)
16387 "Check if there are any deadlines due or past due.
16388 A deadline is considered due if it happens within `org-deadline-warning-days'
16389 days from today's date. If the deadline appears in an entry marked DONE,
16390 it is not shown. The prefix arg NDAYS can be used to test that many
16391 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16392 (interactive "P")
16393 (let* ((org-warn-days
16394 (cond
16395 ((equal ndays '(4)) 100000)
16396 (ndays (prefix-numeric-value ndays))
16397 (t (abs org-deadline-warning-days))))
16398 (case-fold-search nil)
16399 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16400 (callback
16401 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16403 (message "%d deadlines past-due or due within %d days"
16404 (org-occur regexp nil callback)
16405 org-warn-days)))
16407 (defsubst org-re-timestamp (type)
16408 "Return a regexp for timestamp TYPE.
16409 Allowed values for TYPE are:
16411 all: all timestamps
16412 active: only active timestamps (<...>)
16413 inactive: only inactive timestamps ([...])
16414 scheduled: only scheduled timestamps
16415 deadline: only deadline timestamps
16417 When TYPE is nil, fall back on returning a regexp that matches
16418 both scheduled and deadline timestamps."
16419 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16420 ((eq type 'active) org-ts-regexp)
16421 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16422 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16423 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16424 ((eq type 'scheduled-or-deadline)
16425 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16427 (defun org-check-before-date (date)
16428 "Check if there are deadlines or scheduled entries before DATE."
16429 (interactive (list (org-read-date)))
16430 (let ((case-fold-search nil)
16431 (regexp (org-re-timestamp org-ts-type))
16432 (callback
16433 (lambda () (time-less-p
16434 (org-time-string-to-time (match-string 1))
16435 (org-time-string-to-time date)))))
16436 (message "%d entries before %s"
16437 (org-occur regexp nil callback) date)))
16439 (defun org-check-after-date (date)
16440 "Check if there are deadlines or scheduled entries after DATE."
16441 (interactive (list (org-read-date)))
16442 (let ((case-fold-search nil)
16443 (regexp (org-re-timestamp org-ts-type))
16444 (callback
16445 (lambda () (not
16446 (time-less-p
16447 (org-time-string-to-time (match-string 1))
16448 (org-time-string-to-time date))))))
16449 (message "%d entries after %s"
16450 (org-occur regexp nil callback) date)))
16452 (defun org-check-dates-range (start-date end-date)
16453 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16454 (interactive (list (org-read-date nil nil nil "Range starts")
16455 (org-read-date nil nil nil "Range end")))
16456 (let ((case-fold-search nil)
16457 (regexp (org-re-timestamp org-ts-type))
16458 (callback
16459 (lambda ()
16460 (let ((match (match-string 1)))
16461 (and
16462 (not (time-less-p
16463 (org-time-string-to-time match)
16464 (org-time-string-to-time start-date)))
16465 (time-less-p
16466 (org-time-string-to-time match)
16467 (org-time-string-to-time end-date)))))))
16468 (message "%d entries between %s and %s"
16469 (org-occur regexp nil callback) start-date end-date)))
16471 (defun org-evaluate-time-range (&optional to-buffer)
16472 "Evaluate a time range by computing the difference between start and end.
16473 Normally the result is just printed in the echo area, but with prefix arg
16474 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16475 If the time range is actually in a table, the result is inserted into the
16476 next column.
16477 For time difference computation, a year is assumed to be exactly 365
16478 days in order to avoid rounding problems."
16479 (interactive "P")
16481 (org-clock-update-time-maybe)
16482 (save-excursion
16483 (unless (org-at-date-range-p t)
16484 (goto-char (point-at-bol))
16485 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16486 (if (not (org-at-date-range-p t))
16487 (error "Not at a time-stamp range, and none found in current line")))
16488 (let* ((ts1 (match-string 1))
16489 (ts2 (match-string 2))
16490 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16491 (match-end (match-end 0))
16492 (time1 (org-time-string-to-time ts1))
16493 (time2 (org-time-string-to-time ts2))
16494 (t1 (org-float-time time1))
16495 (t2 (org-float-time time2))
16496 (diff (abs (- t2 t1)))
16497 (negative (< (- t2 t1) 0))
16498 ;; (ys (floor (* 365 24 60 60)))
16499 (ds (* 24 60 60))
16500 (hs (* 60 60))
16501 (fy "%dy %dd %02d:%02d")
16502 (fy1 "%dy %dd")
16503 (fd "%dd %02d:%02d")
16504 (fd1 "%dd")
16505 (fh "%02d:%02d")
16506 y d h m align)
16507 (if havetime
16508 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16510 d (floor (/ diff ds)) diff (mod diff ds)
16511 h (floor (/ diff hs)) diff (mod diff hs)
16512 m (floor (/ diff 60)))
16513 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16515 d (floor (+ (/ diff ds) 0.5))
16516 h 0 m 0))
16517 (if (not to-buffer)
16518 (message "%s" (org-make-tdiff-string y d h m))
16519 (if (org-at-table-p)
16520 (progn
16521 (goto-char match-end)
16522 (setq align t)
16523 (and (looking-at " *|") (goto-char (match-end 0))))
16524 (goto-char match-end))
16525 (if (looking-at
16526 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16527 (replace-match ""))
16528 (if negative (insert " -"))
16529 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16530 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16531 (insert " " (format fh h m))))
16532 (if align (org-table-align))
16533 (message "Time difference inserted")))))
16535 (defun org-make-tdiff-string (y d h m)
16536 (let ((fmt "")
16537 (l nil))
16538 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16539 l (push y l)))
16540 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16541 l (push d l)))
16542 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16543 l (push h l)))
16544 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16545 l (push m l)))
16546 (apply 'format fmt (nreverse l))))
16548 (defun org-time-string-to-time (s &optional buffer pos)
16549 "Convert a timestamp string into internal time."
16550 (condition-case errdata
16551 (apply 'encode-time (org-parse-time-string s))
16552 (error (error "Bad timestamp `%s'%s\nError was: %s"
16553 s (if (not (and buffer pos))
16555 (format " at %d in buffer `%s'" pos buffer))
16556 (cdr errdata)))))
16558 (defun org-time-string-to-seconds (s)
16559 "Convert a timestamp string to a number of seconds."
16560 (org-float-time (org-time-string-to-time s)))
16562 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16563 "Convert a time stamp to an absolute day number.
16564 If there is a specifier for a cyclic time stamp, get the closest
16565 date to DAYNR.
16566 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16567 The variable date is bound by the calendar when this is called."
16568 (cond
16569 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16570 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16571 daynr
16572 (+ daynr 1000)))
16573 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16574 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16575 (time-to-days (current-time))) (match-string 0 s)
16576 prefer show-all))
16577 (t (time-to-days
16578 (condition-case errdata
16579 (apply 'encode-time (org-parse-time-string s))
16580 (error (error "Bad timestamp `%s'%s\nError was: %s"
16581 s (if (not (and buffer pos))
16583 (format " at %d in buffer `%s'" pos buffer))
16584 (cdr errdata))))))))
16586 (defun org-days-to-iso-week (days)
16587 "Return the iso week number."
16588 (require 'cal-iso)
16589 (car (calendar-iso-from-absolute days)))
16591 (defun org-small-year-to-year (year)
16592 "Convert 2-digit years into 4-digit years.
16593 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16594 The year 2000 cannot be abbreviated. Any year larger than 99
16595 is returned unchanged."
16596 (if (< year 38)
16597 (setq year (+ 2000 year))
16598 (if (< year 100)
16599 (setq year (+ 1900 year))))
16600 year)
16602 (defun org-time-from-absolute (d)
16603 "Return the time corresponding to date D.
16604 D may be an absolute day number, or a calendar-type list (month day year)."
16605 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16606 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16608 (defun org-calendar-holiday ()
16609 "List of holidays, for Diary display in Org-mode."
16610 (require 'holidays)
16611 (let ((hl (funcall
16612 (if (fboundp 'calendar-check-holidays)
16613 'calendar-check-holidays 'check-calendar-holidays) date)))
16614 (if hl (mapconcat 'identity hl "; "))))
16616 (defun org-diary-sexp-entry (sexp entry date)
16617 "Process a SEXP diary ENTRY for DATE."
16618 (require 'diary-lib)
16619 (let ((result (if calendar-debug-sexp
16620 (let ((stack-trace-on-error t))
16621 (eval (car (read-from-string sexp))))
16622 (condition-case nil
16623 (eval (car (read-from-string sexp)))
16624 (error
16625 (beep)
16626 (message "Bad sexp at line %d in %s: %s"
16627 (org-current-line)
16628 (buffer-file-name) sexp)
16629 (sleep-for 2))))))
16630 (cond ((stringp result) (split-string result "; "))
16631 ((and (consp result)
16632 (not (consp (cdr result)))
16633 (stringp (cdr result))) (cdr result))
16634 ((and (consp result)
16635 (stringp (car result))) result)
16636 (result entry))))
16638 (defun org-diary-to-ical-string (frombuf)
16639 "Get iCalendar entries from diary entries in buffer FROMBUF.
16640 This uses the icalendar.el library."
16641 (let* ((tmpdir (if (featurep 'xemacs)
16642 (temp-directory)
16643 temporary-file-directory))
16644 (tmpfile (make-temp-name
16645 (expand-file-name "orgics" tmpdir)))
16646 buf rtn b e)
16647 (with-current-buffer frombuf
16648 (icalendar-export-region (point-min) (point-max) tmpfile)
16649 (setq buf (find-buffer-visiting tmpfile))
16650 (set-buffer buf)
16651 (goto-char (point-min))
16652 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16653 (setq b (match-beginning 0)))
16654 (goto-char (point-max))
16655 (if (re-search-backward "^END:VEVENT" nil t)
16656 (setq e (match-end 0)))
16657 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16658 (kill-buffer buf)
16659 (delete-file tmpfile)
16660 rtn))
16662 (defun org-closest-date (start current change prefer show-all)
16663 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16664 When PREFER is `past', return a date that is either CURRENT or past.
16665 When PREFER is `future', return a date that is either CURRENT or future.
16666 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16667 ;; Make the proper lists from the dates
16668 (catch 'exit
16669 (let ((a1 '(("h" . hour)
16670 ("d" . day)
16671 ("w" . week)
16672 ("m" . month)
16673 ("y" . year)))
16674 (shour (nth 2 (org-parse-time-string start)))
16675 dn dw sday cday n1 n2 n0
16676 d m y y1 y2 date1 date2 nmonths nm ny m2)
16678 (setq start (org-date-to-gregorian start)
16679 current (org-date-to-gregorian
16680 (if show-all
16681 current
16682 (time-to-days (current-time))))
16683 sday (calendar-absolute-from-gregorian start)
16684 cday (calendar-absolute-from-gregorian current))
16686 (if (<= cday sday) (throw 'exit sday))
16688 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16689 (setq dn (string-to-number (match-string 1 change))
16690 dw (cdr (assoc (match-string 2 change) a1)))
16691 (error "Invalid change specifier: %s" change))
16692 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16693 (cond
16694 ((eq dw 'hour)
16695 (let ((missing-hours
16696 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16697 dn)))
16698 (setq n1 (if (zerop missing-hours) cday
16699 (- cday (1+ (floor (/ missing-hours 24)))))
16700 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16701 ((eq dw 'day)
16702 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16703 n2 (+ n1 dn)))
16704 ((eq dw 'year)
16705 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16706 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16707 (setq date1 (list m d y1)
16708 n1 (calendar-absolute-from-gregorian date1)
16709 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16710 n2 (calendar-absolute-from-gregorian date2)))
16711 ((eq dw 'month)
16712 ;; approx number of month between the two dates
16713 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16714 ;; How often does dn fit in there?
16715 (setq d (nth 1 start) m (car start) y (nth 2 start)
16716 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16717 m (+ m nm)
16718 ny (floor (/ m 12))
16719 y (+ y ny)
16720 m (- m (* ny 12)))
16721 (while (> m 12) (setq m (- m 12) y (1+ y)))
16722 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16723 (setq m2 (+ m dn) y2 y)
16724 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16725 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16726 (while (<= n2 cday)
16727 (setq n1 n2 m m2 y y2)
16728 (setq m2 (+ m dn) y2 y)
16729 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16730 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16731 ;; Make sure n1 is the earlier date
16732 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16733 (if show-all
16734 (cond
16735 ((eq prefer 'past) (if (= cday n2) n2 n1))
16736 ((eq prefer 'future) (if (= cday n1) n1 n2))
16737 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16738 (cond
16739 ((eq prefer 'past) (if (= cday n2) n2 n1))
16740 ((eq prefer 'future) (if (= cday n1) n1 n2))
16741 (t (if (= cday n1) n1 n2)))))))
16743 (defun org-date-to-gregorian (date)
16744 "Turn any specification of DATE into a Gregorian date for the calendar."
16745 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16746 ((and (listp date) (= (length date) 3)) date)
16747 ((stringp date)
16748 (setq date (org-parse-time-string date))
16749 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16750 ((listp date)
16751 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16753 (defun org-parse-time-string (s &optional nodefault)
16754 "Parse the standard Org-mode time string.
16755 This should be a lot faster than the normal `parse-time-string'.
16756 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16757 hour and minute fields will be nil if not given."
16758 (cond ((string-match org-ts-regexp0 s)
16759 (list 0
16760 (if (or (match-beginning 8) (not nodefault))
16761 (string-to-number (or (match-string 8 s) "0")))
16762 (if (or (match-beginning 7) (not nodefault))
16763 (string-to-number (or (match-string 7 s) "0")))
16764 (string-to-number (match-string 4 s))
16765 (string-to-number (match-string 3 s))
16766 (string-to-number (match-string 2 s))
16767 nil nil nil))
16768 ((string-match "^<[^>]+>$" s)
16769 (decode-time (seconds-to-time (org-matcher-time s))))
16770 (t (error "Not a standard Org-mode time string: %s" s))))
16772 (defun org-timestamp-up (&optional arg)
16773 "Increase the date item at the cursor by one.
16774 If the cursor is on the year, change the year. If it is on the month,
16775 the day or the time, change that.
16776 With prefix ARG, change by that many units."
16777 (interactive "p")
16778 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16780 (defun org-timestamp-down (&optional arg)
16781 "Decrease the date item at the cursor by one.
16782 If the cursor is on the year, change the year. If it is on the month,
16783 the day or the time, change that.
16784 With prefix ARG, change by that many units."
16785 (interactive "p")
16786 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16788 (defun org-timestamp-up-day (&optional arg)
16789 "Increase the date in the time stamp by one day.
16790 With prefix ARG, change that many days."
16791 (interactive "p")
16792 (if (and (not (org-at-timestamp-p t))
16793 (org-at-heading-p))
16794 (org-todo 'up)
16795 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16797 (defun org-timestamp-down-day (&optional arg)
16798 "Decrease the date in the time stamp by one day.
16799 With prefix ARG, change that many days."
16800 (interactive "p")
16801 (if (and (not (org-at-timestamp-p t))
16802 (org-at-heading-p))
16803 (org-todo 'down)
16804 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16806 (defun org-at-timestamp-p (&optional inactive-ok)
16807 "Determine if the cursor is in or at a timestamp."
16808 (interactive)
16809 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16810 (pos (point))
16811 (ans (or (looking-at tsr)
16812 (save-excursion
16813 (skip-chars-backward "^[<\n\r\t")
16814 (if (> (point) (point-min)) (backward-char 1))
16815 (and (looking-at tsr)
16816 (> (- (match-end 0) pos) -1))))))
16817 (and ans
16818 (boundp 'org-ts-what)
16819 (setq org-ts-what
16820 (cond
16821 ((= pos (match-beginning 0)) 'bracket)
16822 ;; Point is considered to be "on the bracket" whether
16823 ;; it's really on it or right after it.
16824 ((= pos (1- (match-end 0))) 'bracket)
16825 ((= pos (match-end 0)) 'after)
16826 ((org-pos-in-match-range pos 2) 'year)
16827 ((org-pos-in-match-range pos 3) 'month)
16828 ((org-pos-in-match-range pos 7) 'hour)
16829 ((org-pos-in-match-range pos 8) 'minute)
16830 ((or (org-pos-in-match-range pos 4)
16831 (org-pos-in-match-range pos 5)) 'day)
16832 ((and (> pos (or (match-end 8) (match-end 5)))
16833 (< pos (match-end 0)))
16834 (- pos (or (match-end 8) (match-end 5))))
16835 (t 'day))))
16836 ans))
16838 (defun org-toggle-timestamp-type ()
16839 "Toggle the type (<active> or [inactive]) of a time stamp."
16840 (interactive)
16841 (when (org-at-timestamp-p t)
16842 (let ((beg (match-beginning 0)) (end (match-end 0))
16843 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16844 (save-excursion
16845 (goto-char beg)
16846 (while (re-search-forward "[][<>]" end t)
16847 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16848 t t)))
16849 (message "Timestamp is now %sactive"
16850 (if (equal (char-after beg) ?<) "" "in")))))
16852 (defvar org-clock-history) ; defined in org-clock.el
16853 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16854 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16855 "Change the date in the time stamp at point.
16856 The date will be changed by N times WHAT. WHAT can be `day', `month',
16857 `year', `minute', `second'. If WHAT is not given, the cursor position
16858 in the timestamp determines what will be changed.
16859 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16860 (let ((origin (point)) origin-cat
16861 with-hm inactive
16862 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16863 org-ts-what
16864 extra rem
16865 ts time time0 fixnext clrgx)
16866 (if (not (org-at-timestamp-p t))
16867 (error "Not at a timestamp"))
16868 (if (and (not what) (eq org-ts-what 'bracket))
16869 (org-toggle-timestamp-type)
16870 ;; Point isn't on brackets. Remember the part of the time-stamp
16871 ;; the point was in. Indeed, size of time-stamps may change,
16872 ;; but point must be kept in the same category nonetheless.
16873 (setq origin-cat org-ts-what)
16874 (if (and (not what) (not (eq org-ts-what 'day))
16875 org-display-custom-times
16876 (get-text-property (point) 'display)
16877 (not (get-text-property (1- (point)) 'display)))
16878 (setq org-ts-what 'day))
16879 (setq org-ts-what (or what org-ts-what)
16880 inactive (= (char-after (match-beginning 0)) ?\[)
16881 ts (match-string 0))
16882 (replace-match "")
16883 (when (string-match
16884 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16886 (setq extra (match-string 1 ts))
16887 (if suppress-tmp-delay
16888 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16889 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16890 (setq with-hm t))
16891 (setq time0 (org-parse-time-string ts))
16892 (when (and updown
16893 (eq org-ts-what 'minute)
16894 (not current-prefix-arg))
16895 ;; This looks like s-up and s-down. Change by one rounding step.
16896 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16897 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16898 (setcar (cdr time0) (+ (nth 1 time0)
16899 (if (> n 0) (- rem) (- dm rem))))))
16900 (setq time
16901 (encode-time (or (car time0) 0)
16902 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16903 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16904 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16905 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16906 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16907 (nthcdr 6 time0)))
16908 (when (and (member org-ts-what '(hour minute))
16909 extra
16910 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16911 (setq extra (org-modify-ts-extra
16912 extra
16913 (if (eq org-ts-what 'hour) 2 5)
16914 n dm)))
16915 (when (integerp org-ts-what)
16916 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16917 (if (eq what 'calendar)
16918 (let ((cal-date (org-get-date-from-calendar)))
16919 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16920 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16921 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16922 (setcar time0 (or (car time0) 0))
16923 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16924 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16925 (setq time (apply 'encode-time time0))))
16926 ;; Insert the new time-stamp, and ensure point stays in the same
16927 ;; category as before (i.e. not after the last position in that
16928 ;; category).
16929 (let ((pos (point)))
16930 ;; Stay before inserted string. `save-excursion' is of no use.
16931 (setq org-last-changed-timestamp
16932 (org-insert-time-stamp time with-hm inactive nil nil extra))
16933 (goto-char pos))
16934 (save-match-data
16935 (looking-at org-ts-regexp3)
16936 (goto-char (cond
16937 ;; `day' category ends before `hour' if any, or at
16938 ;; the end of the day name.
16939 ((eq origin-cat 'day)
16940 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16941 ((eq origin-cat 'hour) (min (match-end 7) origin))
16942 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16943 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16944 ;; `year' and `month' have both fixed size: point
16945 ;; couldn't have moved into another part.
16946 (t origin))))
16947 ;; Update clock if on a CLOCK line.
16948 (org-clock-update-time-maybe)
16949 ;; Maybe adjust the closest clock in `org-clock-history'
16950 (when org-clock-adjust-closest
16951 (if (not (and (org-at-clock-log-p)
16952 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16953 org-clock-history))))))
16954 (message "No clock to adjust")
16955 (cond ((save-excursion ; fix previous clock?
16956 (re-search-backward org-ts-regexp0 nil t)
16957 (org-looking-back (concat org-clock-string " \\[")))
16958 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16959 ((save-excursion ; fix next clock?
16960 (re-search-backward org-ts-regexp0 nil t)
16961 (looking-at (concat org-ts-regexp0 "\\] =>")))
16962 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16963 (save-window-excursion
16964 ;; Find closest clock to point, adjust the previous/next one in history
16965 (let* ((p (save-excursion (org-back-to-heading t)))
16966 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16967 (clfixnth
16968 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16969 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16970 (if (not clfixpos)
16971 (message "No clock to adjust")
16972 (save-excursion
16973 (org-goto-marker-or-bmk clfixpos)
16974 (org-show-subtree)
16975 (when (re-search-forward clrgx nil t)
16976 (goto-char (match-beginning 1))
16977 (let (org-clock-adjust-closest)
16978 (org-timestamp-change n org-ts-what updown))
16979 (message "Clock adjusted in %s for heading: %s"
16980 (file-name-nondirectory (buffer-file-name))
16981 (org-get-heading t t)))))))))
16982 ;; Try to recenter the calendar window, if any.
16983 (if (and org-calendar-follow-timestamp-change
16984 (get-buffer-window "*Calendar*" t)
16985 (memq org-ts-what '(day month year)))
16986 (org-recenter-calendar (time-to-days time))))))
16988 (defun org-modify-ts-extra (s pos n dm)
16989 "Change the different parts of the lead-time and repeat fields in timestamp."
16990 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16991 ng h m new rem)
16992 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16993 (cond
16994 ((or (org-pos-in-match-range pos 2)
16995 (org-pos-in-match-range pos 3))
16996 (setq m (string-to-number (match-string 3 s))
16997 h (string-to-number (match-string 2 s)))
16998 (if (org-pos-in-match-range pos 2)
16999 (setq h (+ h n))
17000 (setq n (* dm (org-no-warnings (signum n))))
17001 (when (not (= 0 (setq rem (% m dm))))
17002 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17003 (setq m (+ m n)))
17004 (if (< m 0) (setq m (+ m 60) h (1- h)))
17005 (if (> m 59) (setq m (- m 60) h (1+ h)))
17006 (setq h (min 24 (max 0 h)))
17007 (setq ng 1 new (format "-%02d:%02d" h m)))
17008 ((org-pos-in-match-range pos 6)
17009 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17010 ((org-pos-in-match-range pos 5)
17011 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17013 ((org-pos-in-match-range pos 9)
17014 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17015 ((org-pos-in-match-range pos 8)
17016 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17018 (when ng
17019 (setq s (concat
17020 (substring s 0 (match-beginning ng))
17022 (substring s (match-end ng))))))
17025 (defun org-recenter-calendar (date)
17026 "If the calendar is visible, recenter it to DATE."
17027 (let ((cwin (get-buffer-window "*Calendar*" t)))
17028 (when cwin
17029 (let ((calendar-move-hook nil))
17030 (with-selected-window cwin
17031 (calendar-goto-date (if (listp date) date
17032 (calendar-gregorian-from-absolute date))))))))
17034 (defun org-goto-calendar (&optional arg)
17035 "Go to the Emacs calendar at the current date.
17036 If there is a time stamp in the current line, go to that date.
17037 A prefix ARG can be used to force the current date."
17038 (interactive "P")
17039 (let ((tsr org-ts-regexp) diff
17040 (calendar-move-hook nil)
17041 (calendar-view-holidays-initially-flag nil)
17042 (calendar-view-diary-initially-flag nil))
17043 (if (or (org-at-timestamp-p)
17044 (save-excursion
17045 (beginning-of-line 1)
17046 (looking-at (concat ".*" tsr))))
17047 (let ((d1 (time-to-days (current-time)))
17048 (d2 (time-to-days
17049 (org-time-string-to-time (match-string 1)))))
17050 (setq diff (- d2 d1))))
17051 (calendar)
17052 (calendar-goto-today)
17053 (if (and diff (not arg)) (calendar-forward-day diff))))
17055 (defun org-get-date-from-calendar ()
17056 "Return a list (month day year) of date at point in calendar."
17057 (with-current-buffer "*Calendar*"
17058 (save-match-data
17059 (calendar-cursor-to-date))))
17061 (defun org-date-from-calendar ()
17062 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17063 If there is already a time stamp at the cursor position, update it."
17064 (interactive)
17065 (if (org-at-timestamp-p t)
17066 (org-timestamp-change 0 'calendar)
17067 (let ((cal-date (org-get-date-from-calendar)))
17068 (org-insert-time-stamp
17069 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17071 (defcustom org-effort-durations
17072 `(("h" . 60)
17073 ("d" . ,(* 60 8))
17074 ("w" . ,(* 60 8 5))
17075 ("m" . ,(* 60 8 5 4))
17076 ("y" . ,(* 60 8 5 40)))
17077 "Conversion factor to minutes for an effort modifier.
17079 Each entry has the form (MODIFIER . MINUTES).
17081 In an effort string, a number followed by MODIFIER is multiplied
17082 by the specified number of MINUTES to obtain an effort in
17083 minutes.
17085 For example, if the value of this variable is ((\"hours\" . 60)), then an
17086 effort string \"2hours\" is equivalent to 120 minutes."
17087 :group 'org-agenda
17088 :version "24.1"
17089 :type '(alist :key-type (string :tag "Modifier")
17090 :value-type (number :tag "Minutes")))
17092 (defun org-minutes-to-clocksum-string (m)
17093 "Format number of minutes as a clocksum string.
17094 The format is determined by `org-time-clocksum-format',
17095 `org-time-clocksum-use-fractional' and
17096 `org-time-clocksum-fractional-format' and
17097 `org-time-clocksum-use-effort-durations'."
17098 (let ((clocksum "") h d w mo y fmt n)
17099 (setq h (if org-time-clocksum-use-effort-durations
17100 (cdr (assoc "h" org-effort-durations)) 60)
17101 d (if org-time-clocksum-use-effort-durations
17102 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17103 w (if org-time-clocksum-use-effort-durations
17104 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17105 mo (if org-time-clocksum-use-effort-durations
17106 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17107 y (if org-time-clocksum-use-effort-durations
17108 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17109 ;; fractional format
17110 (if org-time-clocksum-use-fractional
17111 (cond
17112 ;; single format string
17113 ((stringp org-time-clocksum-fractional-format)
17114 (format org-time-clocksum-fractional-format (/ m (float h))))
17115 ;; choice of fractional formats for different time units
17116 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17117 (> (/ (truncate m) (* y d h)) 0))
17118 (format fmt (/ m (* y d (float h)))))
17119 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17120 (> (/ (truncate m) (* mo d h)) 0))
17121 (format fmt (/ m (* mo d (float h)))))
17122 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17123 (> (/ (truncate m) (* w d h)) 0))
17124 (format fmt (/ m (* w d (float h)))))
17125 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17126 (> (/ (truncate m) (* d h)) 0))
17127 (format fmt (/ m (* d (float h)))))
17128 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17129 (> (/ (truncate m) h) 0))
17130 (format fmt (/ m (float h))))
17131 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17132 (format fmt m))
17133 ;; fall back to smallest time unit with a format
17134 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17135 (format fmt (/ m (float h))))
17136 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17137 (format fmt (/ m (* d (float h)))))
17138 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17139 (format fmt (/ m (* w d (float h)))))
17140 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17141 (format fmt (/ m (* mo d (float h)))))
17142 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17143 (format fmt (/ m (* y d (float h))))))
17144 ;; standard (non-fractional) format, with single format string
17145 (if (stringp org-time-clocksum-format)
17146 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17147 ;; separate formats components
17148 (and (setq fmt (plist-get org-time-clocksum-format :years))
17149 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17150 (plist-get org-time-clocksum-format :require-years))
17151 (setq clocksum (concat clocksum (format fmt n))
17152 m (- m (* n y d h))))
17153 (and (setq fmt (plist-get org-time-clocksum-format :months))
17154 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17155 (plist-get org-time-clocksum-format :require-months))
17156 (setq clocksum (concat clocksum (format fmt n))
17157 m (- m (* n mo d h))))
17158 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17159 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17160 (plist-get org-time-clocksum-format :require-weeks))
17161 (setq clocksum (concat clocksum (format fmt n))
17162 m (- m (* n w d h))))
17163 (and (setq fmt (plist-get org-time-clocksum-format :days))
17164 (or (> (setq n (/ (truncate m) (* d h))) 0)
17165 (plist-get org-time-clocksum-format :require-days))
17166 (setq clocksum (concat clocksum (format fmt n))
17167 m (- m (* n d h))))
17168 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17169 (or (> (setq n (/ (truncate m) h)) 0)
17170 (plist-get org-time-clocksum-format :require-hours))
17171 (setq clocksum (concat clocksum (format fmt n))
17172 m (- m (* n h))))
17173 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17174 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17175 (setq clocksum (concat clocksum (format fmt m))))
17176 ;; return formatted time duration
17177 clocksum))))
17179 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17180 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17181 "Org mode version 8.0")
17183 (defun org-hours-to-clocksum-string (n)
17184 (org-minutes-to-clocksum-string (* n 60)))
17186 (defun org-hh:mm-string-to-minutes (s)
17187 "Convert a string H:MM to a number of minutes.
17188 If the string is just a number, interpret it as minutes.
17189 In fact, the first hh:mm or number in the string will be taken,
17190 there can be extra stuff in the string.
17191 If no number is found, the return value is 0."
17192 (cond
17193 ((integerp s) s)
17194 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17195 (+ (* (string-to-number (match-string 1 s)) 60)
17196 (string-to-number (match-string 2 s))))
17197 ((string-match "\\([0-9]+\\)" s)
17198 (string-to-number (match-string 1 s)))
17199 (t 0)))
17201 (defcustom org-image-actual-width t
17202 "Should we use the actual width of images when inlining them?
17204 When set to `t', always use the image width.
17206 When set to a number, use imagemagick (when available) to set
17207 the image's width to this value.
17209 When set to a number in a list, try to get the width from the
17210 #+ATTR.* keyword if it matches a width specification like
17211 width=\"[0-9]+\", and fall back on that number if none is found.
17213 When set to nil, try to get the width from an #+ATTR.* keyword
17214 and fall back on the original width if none is found.
17216 This requires Emacs >= 24.1, build with imagemagick support."
17217 :group 'org-appearance
17218 :version "24.3"
17219 :type '(choice
17220 (const :tag "Use the image width" t)
17221 (integer :tag "Use a number of pixels")
17222 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17223 (const :tag "Use #+ATTR* or don't resize" nil)))
17225 (defcustom org-agenda-inhibit-startup t
17226 "Inhibit startup when preparing agenda buffers.
17227 When this variable is `t' (the default), the initialization of
17228 the Org agenda buffers is inhibited: e.g. the visibility state
17229 is not set, the tables are not re-aligned, etc."
17230 :type 'boolean
17231 :version "24.3"
17232 :group 'org-agenda)
17234 (defun org-duration-string-to-minutes (s &optional output-to-string)
17235 "Convert a duration string S to minutes.
17237 A bare number is interpreted as minutes, modifiers can be set by
17238 customizing `org-effort-durations' (which see).
17240 Entries containing a colon are interpreted as H:MM by
17241 `org-hh:mm-string-to-minutes'."
17242 (let ((result 0)
17243 (re (concat "\\([0-9.]+\\) *\\("
17244 (regexp-opt (mapcar 'car org-effort-durations))
17245 "\\)")))
17246 (while (string-match re s)
17247 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17248 (string-to-number (match-string 1 s))))
17249 (setq s (replace-match "" nil t s)))
17250 (setq result (floor result))
17251 (incf result (org-hh:mm-string-to-minutes s))
17252 (if output-to-string (number-to-string result) result)))
17254 ;;;; Files
17256 (defun org-save-all-org-buffers ()
17257 "Save all Org-mode buffers without user confirmation."
17258 (interactive)
17259 (message "Saving all Org-mode buffers...")
17260 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17261 (when (featurep 'org-id) (org-id-locations-save))
17262 (message "Saving all Org-mode buffers... done"))
17264 (defun org-revert-all-org-buffers ()
17265 "Revert all Org-mode buffers.
17266 Prompt for confirmation when there are unsaved changes.
17267 Be sure you know what you are doing before letting this function
17268 overwrite your changes.
17270 This function is useful in a setup where one tracks org files
17271 with a version control system, to revert on one machine after pulling
17272 changes from another. I believe the procedure must be like this:
17274 1. M-x org-save-all-org-buffers
17275 2. Pull changes from the other machine, resolve conflicts
17276 3. M-x org-revert-all-org-buffers"
17277 (interactive)
17278 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17279 (error "Abort"))
17280 (save-excursion
17281 (save-window-excursion
17282 (mapc
17283 (lambda (b)
17284 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17285 (with-current-buffer b buffer-file-name))
17286 (org-pop-to-buffer-same-window b)
17287 (revert-buffer t 'no-confirm)))
17288 (buffer-list))
17289 (when (and (featurep 'org-id) org-id-track-globally)
17290 (org-id-locations-load)))))
17292 ;;;; Agenda files
17294 ;;;###autoload
17295 (defun org-switchb (&optional arg)
17296 "Switch between Org buffers.
17297 With one prefix argument, restrict available buffers to files.
17298 With two prefix arguments, restrict available buffers to agenda files.
17300 Defaults to `iswitchb' for buffer name completion.
17301 Set `org-completion-use-ido' to make it use ido instead."
17302 (interactive "P")
17303 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17304 ((equal arg '(16)) (org-buffer-list 'agenda))
17305 (t (org-buffer-list))))
17306 (org-completion-use-iswitchb org-completion-use-iswitchb)
17307 (org-completion-use-ido org-completion-use-ido))
17308 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17309 (setq org-completion-use-iswitchb t))
17310 (org-pop-to-buffer-same-window
17311 (org-icompleting-read "Org buffer: "
17312 (mapcar 'list (mapcar 'buffer-name blist))
17313 nil t))))
17315 ;;; Define some older names previously used for this functionality
17316 ;;;###autoload
17317 (defalias 'org-ido-switchb 'org-switchb)
17318 ;;;###autoload
17319 (defalias 'org-iswitchb 'org-switchb)
17321 (defun org-buffer-list (&optional predicate exclude-tmp)
17322 "Return a list of Org buffers.
17323 PREDICATE can be `export', `files' or `agenda'.
17325 export restrict the list to Export buffers.
17326 files restrict the list to buffers visiting Org files.
17327 agenda restrict the list to buffers visiting agenda files.
17329 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17330 (let* ((bfn nil)
17331 (agenda-files (and (eq predicate 'agenda)
17332 (mapcar 'file-truename (org-agenda-files t))))
17333 (filter
17334 (cond
17335 ((eq predicate 'files)
17336 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17337 ((eq predicate 'export)
17338 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17339 ((eq predicate 'agenda)
17340 (lambda (b)
17341 (with-current-buffer b
17342 (and (derived-mode-p 'org-mode)
17343 (setq bfn (buffer-file-name b))
17344 (member (file-truename bfn) agenda-files)))))
17345 (t (lambda (b) (with-current-buffer b
17346 (or (derived-mode-p 'org-mode)
17347 (string-match "\*Org .*Export"
17348 (buffer-name b)))))))))
17349 (delq nil
17350 (mapcar
17351 (lambda(b)
17352 (if (and (funcall filter b)
17353 (or (not exclude-tmp)
17354 (not (string-match "tmp" (buffer-name b)))))
17356 nil))
17357 (buffer-list)))))
17359 (defun org-agenda-files (&optional unrestricted archives)
17360 "Get the list of agenda files.
17361 Optional UNRESTRICTED means return the full list even if a restriction
17362 is currently in place.
17363 When ARCHIVES is t, include all archive files that are really being
17364 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17365 `org-agenda-archives-mode' is t."
17366 (let ((files
17367 (cond
17368 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17369 ((stringp org-agenda-files) (org-read-agenda-file-list))
17370 ((listp org-agenda-files) org-agenda-files)
17371 (t (error "Invalid value of `org-agenda-files'")))))
17372 (setq files (apply 'append
17373 (mapcar (lambda (f)
17374 (if (file-directory-p f)
17375 (directory-files
17376 f t org-agenda-file-regexp)
17377 (list f)))
17378 files)))
17379 (when org-agenda-skip-unavailable-files
17380 (setq files (delq nil
17381 (mapcar (function
17382 (lambda (file)
17383 (and (file-readable-p file) file)))
17384 files))))
17385 (when (or (eq archives t)
17386 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17387 (setq files (org-add-archive-files files)))
17388 files))
17390 (defun org-agenda-file-p (&optional file)
17391 "Return non-nil, if FILE is an agenda file.
17392 If FILE is omitted, use the file associated with the current
17393 buffer."
17394 (member (or file (buffer-file-name))
17395 (org-agenda-files t)))
17397 (defun org-edit-agenda-file-list ()
17398 "Edit the list of agenda files.
17399 Depending on setup, this either uses customize to edit the variable
17400 `org-agenda-files', or it visits the file that is holding the list. In the
17401 latter case, the buffer is set up in a way that saving it automatically kills
17402 the buffer and restores the previous window configuration."
17403 (interactive)
17404 (if (stringp org-agenda-files)
17405 (let ((cw (current-window-configuration)))
17406 (find-file org-agenda-files)
17407 (org-set-local 'org-window-configuration cw)
17408 (org-add-hook 'after-save-hook
17409 (lambda ()
17410 (set-window-configuration
17411 (prog1 org-window-configuration
17412 (kill-buffer (current-buffer))))
17413 (org-install-agenda-files-menu)
17414 (message "New agenda file list installed"))
17415 nil 'local)
17416 (message "%s" (substitute-command-keys
17417 "Edit list and finish with \\[save-buffer]")))
17418 (customize-variable 'org-agenda-files)))
17420 (defun org-store-new-agenda-file-list (list)
17421 "Set new value for the agenda file list and save it correctly."
17422 (if (stringp org-agenda-files)
17423 (let ((fe (org-read-agenda-file-list t)) b u)
17424 (while (setq b (find-buffer-visiting org-agenda-files))
17425 (kill-buffer b))
17426 (with-temp-file org-agenda-files
17427 (insert
17428 (mapconcat
17429 (lambda (f) ;; Keep un-expanded entries.
17430 (if (setq u (assoc f fe))
17431 (cdr u)
17433 list "\n")
17434 "\n")))
17435 (let ((org-mode-hook nil) (org-inhibit-startup t)
17436 (org-insert-mode-line-in-empty-file nil))
17437 (setq org-agenda-files list)
17438 (customize-save-variable 'org-agenda-files org-agenda-files))))
17440 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17441 "Read the list of agenda files from a file.
17442 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17443 filenames, used by `org-store-new-agenda-file-list' to write back
17444 un-expanded file names."
17445 (when (file-directory-p org-agenda-files)
17446 (error "`org-agenda-files' cannot be a single directory"))
17447 (when (stringp org-agenda-files)
17448 (with-temp-buffer
17449 (insert-file-contents org-agenda-files)
17450 (mapcar
17451 (lambda (f)
17452 (let ((e (expand-file-name (substitute-in-file-name f)
17453 org-directory)))
17454 (if pair-with-expansion
17455 (cons e f)
17456 e)))
17457 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17459 ;;;###autoload
17460 (defun org-cycle-agenda-files ()
17461 "Cycle through the files in `org-agenda-files'.
17462 If the current buffer visits an agenda file, find the next one in the list.
17463 If the current buffer does not, find the first agenda file."
17464 (interactive)
17465 (let* ((fs (org-agenda-files t))
17466 (files (append fs (list (car fs))))
17467 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17468 file)
17469 (unless files (error "No agenda files"))
17470 (catch 'exit
17471 (while (setq file (pop files))
17472 (if (equal (file-truename file) tcf)
17473 (when (car files)
17474 (find-file (car files))
17475 (throw 'exit t))))
17476 (find-file (car fs)))
17477 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17479 (defun org-agenda-file-to-front (&optional to-end)
17480 "Move/add the current file to the top of the agenda file list.
17481 If the file is not present in the list, it is added to the front. If it is
17482 present, it is moved there. With optional argument TO-END, add/move to the
17483 end of the list."
17484 (interactive "P")
17485 (let ((org-agenda-skip-unavailable-files nil)
17486 (file-alist (mapcar (lambda (x)
17487 (cons (file-truename x) x))
17488 (org-agenda-files t)))
17489 (ctf (file-truename
17490 (or buffer-file-name
17491 (error "Please save the current buffer to a file"))))
17492 x had)
17493 (setq x (assoc ctf file-alist) had x)
17495 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17496 (if to-end
17497 (setq file-alist (append (delq x file-alist) (list x)))
17498 (setq file-alist (cons x (delq x file-alist))))
17499 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17500 (org-install-agenda-files-menu)
17501 (message "File %s to %s of agenda file list"
17502 (if had "moved" "added") (if to-end "end" "front"))))
17504 (defun org-remove-file (&optional file)
17505 "Remove current file from the list of files in variable `org-agenda-files'.
17506 These are the files which are being checked for agenda entries.
17507 Optional argument FILE means use this file instead of the current."
17508 (interactive)
17509 (let* ((org-agenda-skip-unavailable-files nil)
17510 (file (or file buffer-file-name
17511 (error "Current buffer does not visit a file")))
17512 (true-file (file-truename file))
17513 (afile (abbreviate-file-name file))
17514 (files (delq nil (mapcar
17515 (lambda (x)
17516 (if (equal true-file
17517 (file-truename x))
17518 nil x))
17519 (org-agenda-files t)))))
17520 (if (not (= (length files) (length (org-agenda-files t))))
17521 (progn
17522 (org-store-new-agenda-file-list files)
17523 (org-install-agenda-files-menu)
17524 (message "Removed file: %s" afile))
17525 (message "File was not in list: %s (not removed)" afile))))
17527 (defun org-file-menu-entry (file)
17528 (vector file (list 'find-file file) t))
17530 (defun org-check-agenda-file (file)
17531 "Make sure FILE exists. If not, ask user what to do."
17532 (when (not (file-exists-p file))
17533 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17534 (abbreviate-file-name file))
17535 (let ((r (downcase (read-char-exclusive))))
17536 (cond
17537 ((equal r ?r)
17538 (org-remove-file file)
17539 (throw 'nextfile t))
17540 (t (error "Abort"))))))
17542 (defun org-get-agenda-file-buffer (file)
17543 "Get a buffer visiting FILE. If the buffer needs to be created, add
17544 it to the list of buffers which might be released later."
17545 (let ((buf (org-find-base-buffer-visiting file)))
17546 (if buf
17547 buf ; just return it
17548 ;; Make a new buffer and remember it
17549 (setq buf (find-file-noselect file))
17550 (if buf (push buf org-agenda-new-buffers))
17551 buf)))
17553 (defun org-release-buffers (blist)
17554 "Release all buffers in list, asking the user for confirmation when needed.
17555 When a buffer is unmodified, it is just killed. When modified, it is saved
17556 \(if the user agrees) and then killed."
17557 (let (buf file)
17558 (while (setq buf (pop blist))
17559 (setq file (buffer-file-name buf))
17560 (when (and (buffer-modified-p buf)
17561 file
17562 (y-or-n-p (format "Save file %s? " file)))
17563 (with-current-buffer buf (save-buffer)))
17564 (kill-buffer buf))))
17566 (defun org-agenda-prepare-buffers (files)
17567 "Create buffers for all agenda files, protect archived trees and comments."
17568 (interactive)
17569 (let ((pa '(:org-archived t))
17570 (pc '(:org-comment t))
17571 (pall '(:org-archived t :org-comment t))
17572 (inhibit-read-only t)
17573 (org-inhibit-startup org-agenda-inhibit-startup)
17574 (rea (concat ":" org-archive-tag ":"))
17575 file re)
17576 (save-excursion
17577 (save-restriction
17578 (while (setq file (pop files))
17579 (catch 'nextfile
17580 (if (bufferp file)
17581 (set-buffer file)
17582 (org-check-agenda-file file)
17583 (set-buffer (org-get-agenda-file-buffer file)))
17584 (widen)
17585 (org-unmodified
17586 (org-refresh-category-properties)
17587 (org-refresh-properties org-effort-property 'org-effort)
17588 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17589 (setq org-todo-keywords-for-agenda
17590 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17591 (setq org-done-keywords-for-agenda
17592 (append org-done-keywords-for-agenda org-done-keywords))
17593 (setq org-todo-keyword-alist-for-agenda
17594 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17595 (setq org-drawers-for-agenda
17596 (append org-drawers-for-agenda org-drawers))
17597 (setq org-tag-alist-for-agenda
17598 (append org-tag-alist-for-agenda org-tag-alist))
17600 (save-excursion
17601 (remove-text-properties (point-min) (point-max) pall)
17602 (when org-agenda-skip-archived-trees
17603 (goto-char (point-min))
17604 (while (re-search-forward rea nil t)
17605 (if (org-at-heading-p t)
17606 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17607 (goto-char (point-min))
17608 (setq re (format org-heading-keyword-regexp-format
17609 org-comment-string))
17610 (while (re-search-forward re nil t)
17611 (add-text-properties
17612 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17613 (setq org-todo-keywords-for-agenda
17614 (org-uniquify org-todo-keywords-for-agenda))
17615 (setq org-todo-keyword-alist-for-agenda
17616 (org-uniquify org-todo-keyword-alist-for-agenda)
17617 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17621 ;;;; CDLaTeX minor mode
17623 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17624 "Keymap for the minor `org-cdlatex-mode'.")
17626 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17627 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17628 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17629 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17630 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17632 (defvar org-cdlatex-texmathp-advice-is-done nil
17633 "Flag remembering if we have applied the advice to texmathp already.")
17635 (define-minor-mode org-cdlatex-mode
17636 "Toggle the minor `org-cdlatex-mode'.
17637 This mode supports entering LaTeX environment and math in LaTeX fragments
17638 in Org-mode.
17639 \\{org-cdlatex-mode-map}"
17640 nil " OCDL" nil
17641 (when org-cdlatex-mode
17642 (require 'cdlatex)
17643 (run-hooks 'cdlatex-mode-hook)
17644 (cdlatex-compute-tables))
17645 (unless org-cdlatex-texmathp-advice-is-done
17646 (setq org-cdlatex-texmathp-advice-is-done t)
17647 (defadvice texmathp (around org-math-always-on activate)
17648 "Always return t in org-mode buffers.
17649 This is because we want to insert math symbols without dollars even outside
17650 the LaTeX math segments. If Orgmode thinks that point is actually inside
17651 an embedded LaTeX fragment, let texmathp do its job.
17652 \\[org-cdlatex-mode-map]"
17653 (interactive)
17654 (let (p)
17655 (cond
17656 ((not (derived-mode-p 'org-mode)) ad-do-it)
17657 ((eq this-command 'cdlatex-math-symbol)
17658 (setq ad-return-value t
17659 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17661 (let ((p (org-inside-LaTeX-fragment-p)))
17662 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17663 (setq ad-return-value t
17664 texmathp-why '("Org-mode embedded math" . 0))
17665 (if p ad-do-it)))))))))
17667 (defun turn-on-org-cdlatex ()
17668 "Unconditionally turn on `org-cdlatex-mode'."
17669 (org-cdlatex-mode 1))
17671 (defun org-try-cdlatex-tab ()
17672 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17673 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17674 - inside a LaTeX fragment, or
17675 - after the first word in a line, where an abbreviation expansion could
17676 insert a LaTeX environment."
17677 (when org-cdlatex-mode
17678 (cond
17679 ;; Before any word on the line: No expansion possible.
17680 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17681 ;; Just after first word on the line: Expand it. Make sure it
17682 ;; cannot happen on headlines, though.
17683 ((save-excursion
17684 (skip-chars-backward "a-zA-Z0-9*")
17685 (skip-chars-backward " \t")
17686 (and (bolp) (not (org-at-heading-p))))
17687 (cdlatex-tab) t)
17688 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17690 (defun org-cdlatex-underscore-caret (&optional arg)
17691 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17692 Revert to the normal definition outside of these fragments."
17693 (interactive "P")
17694 (if (org-inside-LaTeX-fragment-p)
17695 (call-interactively 'cdlatex-sub-superscript)
17696 (let (org-cdlatex-mode)
17697 (call-interactively (key-binding (vector last-input-event))))))
17699 (defun org-cdlatex-math-modify (&optional arg)
17700 "Execute `cdlatex-math-modify' in LaTeX fragments.
17701 Revert to the normal definition outside of these fragments."
17702 (interactive "P")
17703 (if (org-inside-LaTeX-fragment-p)
17704 (call-interactively 'cdlatex-math-modify)
17705 (let (org-cdlatex-mode)
17706 (call-interactively (key-binding (vector last-input-event))))))
17710 ;;;; LaTeX fragments
17712 (defvar org-latex-regexps
17713 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17714 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17715 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17716 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17717 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17718 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17719 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17720 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17721 "Regular expressions for matching embedded LaTeX.")
17723 (defun org-inside-LaTeX-fragment-p ()
17724 "Test if point is inside a LaTeX fragment.
17725 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17726 sequence appearing also before point.
17727 Even though the matchers for math are configurable, this function assumes
17728 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17729 delimiters are skipped when they have been removed by customization.
17730 The return value is nil, or a cons cell with the delimiter and the
17731 position of this delimiter.
17733 This function does a reasonably good job, but can locally be fooled by
17734 for example currency specifications. For example it will assume being in
17735 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17736 fragments that are properly closed, but during editing, we have to live
17737 with the uncertainty caused by missing closing delimiters. This function
17738 looks only before point, not after."
17739 (catch 'exit
17740 (let ((pos (point))
17741 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17742 (lim (progn
17743 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17744 (point)))
17745 dd-on str (start 0) m re)
17746 (goto-char pos)
17747 (when dodollar
17748 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17749 re (nth 1 (assoc "$" org-latex-regexps)))
17750 (while (string-match re str start)
17751 (cond
17752 ((= (match-end 0) (length str))
17753 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17754 ((= (match-end 0) (- (length str) 5))
17755 (throw 'exit nil))
17756 (t (setq start (match-end 0))))))
17757 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17758 (goto-char pos)
17759 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17760 (and (match-beginning 2) (throw 'exit nil))
17761 ;; count $$
17762 (while (re-search-backward "\\$\\$" lim t)
17763 (setq dd-on (not dd-on)))
17764 (goto-char pos)
17765 (if dd-on (cons "$$" m))))))
17767 (defun org-inside-latex-macro-p ()
17768 "Is point inside a LaTeX macro or its arguments?"
17769 (save-match-data
17770 (org-in-regexp
17771 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17773 (defvar org-latex-fragment-image-overlays nil
17774 "List of overlays carrying the images of latex fragments.")
17775 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17777 (defun org-remove-latex-fragment-image-overlays ()
17778 "Remove all overlays with LaTeX fragment images in current buffer."
17779 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17780 (setq org-latex-fragment-image-overlays nil))
17782 (defun org-preview-latex-fragment (&optional subtree)
17783 "Preview the LaTeX fragment at point, or all locally or globally.
17784 If the cursor is in a LaTeX fragment, create the image and overlay
17785 it over the source code. If there is no fragment at point, display
17786 all fragments in the current text, from one headline to the next. With
17787 prefix SUBTREE, display all fragments in the current subtree. With a
17788 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17789 the cursor is before the first headline,
17790 display all fragments in the buffer.
17791 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17792 (interactive "P")
17793 (unless buffer-file-name
17794 (error "Can't preview LaTeX fragment in a non-file buffer"))
17795 (org-remove-latex-fragment-image-overlays)
17796 (save-excursion
17797 (save-restriction
17798 (let (beg end at msg)
17799 (cond
17800 ((or (equal subtree '(16))
17801 (not (save-excursion
17802 (re-search-backward org-outline-regexp-bol nil t))))
17803 (setq beg (point-min) end (point-max)
17804 msg "Creating images for buffer...%s"))
17805 ((equal subtree '(4))
17806 (org-back-to-heading)
17807 (setq beg (point) end (org-end-of-subtree t)
17808 msg "Creating images for subtree...%s"))
17810 (if (setq at (org-inside-LaTeX-fragment-p))
17811 (goto-char (max (point-min) (- (cdr at) 2)))
17812 (org-back-to-heading))
17813 (setq beg (point) end (progn (outline-next-heading) (point))
17814 msg (if at "Creating image...%s"
17815 "Creating images for entry...%s"))))
17816 (message msg "")
17817 (narrow-to-region beg end)
17818 (goto-char beg)
17819 (org-format-latex
17820 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17821 (file-name-nondirectory
17822 buffer-file-name)))
17823 default-directory 'overlays msg at 'forbuffer
17824 org-latex-create-formula-image-program)
17825 (message msg "done. Use `C-c C-c' to remove images.")))))
17827 (defun org-format-latex (prefix &optional dir overlays msg at
17828 forbuffer processing-type)
17829 "Replace LaTeX fragments with links to an image, and produce images.
17830 Some of the options can be changed using the variable
17831 `org-format-latex-options'."
17832 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17833 (let* ((prefixnodir (file-name-nondirectory prefix))
17834 (absprefix (expand-file-name prefix dir))
17835 (todir (file-name-directory absprefix))
17836 (opt org-format-latex-options)
17837 (optnew org-format-latex-options)
17838 (matchers (plist-get opt :matchers))
17839 (re-list org-latex-regexps)
17840 (cnt 0) txt hash link beg end re e checkdir
17841 string
17842 m n block-type block linkfile movefile ov)
17843 ;; Check the different regular expressions
17844 (while (setq e (pop re-list))
17845 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17846 block (if block-type "\n\n" ""))
17847 (when (member m matchers)
17848 (goto-char (point-min))
17849 (while (re-search-forward re nil t)
17850 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17851 (or (not overlays)
17852 (not (eq (get-char-property (match-beginning n)
17853 'org-overlay-type)
17854 'org-latex-overlay))))
17855 (cond
17856 ((eq processing-type 'verbatim))
17857 ((eq processing-type 'mathjax)
17858 ;; Prepare for MathJax processing.
17859 (setq string (match-string n))
17860 (when (member m '("$" "$1"))
17861 (save-excursion
17862 (delete-region (match-beginning n) (match-end n))
17863 (goto-char (match-beginning n))
17864 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17865 ((or (eq processing-type 'dvipng)
17866 (eq processing-type 'imagemagick))
17867 ;; Process to an image.
17868 (setq txt (match-string n)
17869 beg (match-beginning n) end (match-end n)
17870 cnt (1+ cnt))
17871 (let ((face (face-at-point))
17872 (fg (plist-get opt :foreground))
17873 (bg (plist-get opt :background))
17874 ;; Ensure full list is printed.
17875 print-length print-level)
17876 (when forbuffer
17877 ;; Get the colors from the face at point.
17878 (goto-char beg)
17879 (when (eq fg 'auto)
17880 (setq fg (face-attribute face :foreground nil 'default)))
17881 (when (eq bg 'auto)
17882 (setq bg (face-attribute face :background nil 'default)))
17883 (setq optnew (copy-sequence opt))
17884 (plist-put optnew :foreground fg)
17885 (plist-put optnew :background bg))
17886 (setq hash (sha1 (prin1-to-string
17887 (list org-format-latex-header
17888 org-latex-default-packages-alist
17889 org-latex-packages-alist
17890 org-format-latex-options
17891 forbuffer txt fg bg)))
17892 linkfile (format "%s_%s.png" prefix hash)
17893 movefile (format "%s_%s.png" absprefix hash)))
17894 (setq link (concat block "[[file:" linkfile "]]" block))
17895 (if msg (message msg cnt))
17896 (goto-char beg)
17897 (unless checkdir ; Ensure the directory exists.
17898 (setq checkdir t)
17899 (or (file-directory-p todir) (make-directory todir t)))
17900 (unless (file-exists-p movefile)
17901 (org-create-formula-image
17902 txt movefile optnew forbuffer processing-type))
17903 (if overlays
17904 (progn
17905 (mapc (lambda (o)
17906 (if (eq (overlay-get o 'org-overlay-type)
17907 'org-latex-overlay)
17908 (delete-overlay o)))
17909 (overlays-in beg end))
17910 (setq ov (make-overlay beg end))
17911 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17912 (if (featurep 'xemacs)
17913 (progn
17914 (overlay-put ov 'invisible t)
17915 (overlay-put
17916 ov 'end-glyph
17917 (make-glyph (vector 'png :file movefile))))
17918 (overlay-put
17919 ov 'display
17920 (list 'image :type 'png :file movefile :ascent 'center)))
17921 (push ov org-latex-fragment-image-overlays)
17922 (goto-char end))
17923 (delete-region beg end)
17924 (insert (org-add-props link
17925 (list 'org-latex-src
17926 (replace-regexp-in-string
17927 "\"" "" txt)
17928 'org-latex-src-embed-type
17929 (if block-type 'paragraph 'character))))))
17930 ((eq processing-type 'mathml)
17931 ;; Process to MathML
17932 (unless (save-match-data (org-format-latex-mathml-available-p))
17933 (error "LaTeX to MathML converter not configured"))
17934 (setq txt (match-string n)
17935 beg (match-beginning n) end (match-end n)
17936 cnt (1+ cnt))
17937 (if msg (message msg cnt))
17938 (goto-char beg)
17939 (delete-region beg end)
17940 (insert (org-format-latex-as-mathml
17941 txt block-type prefix dir)))
17943 (error "Unknown conversion type %s for latex fragments"
17944 processing-type)))))))))
17946 (defun org-create-math-formula (latex-frag &optional mathml-file)
17947 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17948 Use `org-latex-to-mathml-convert-command'. If the conversion is
17949 sucessful, return the portion between \"<math...> </math>\"
17950 elements otherwise return nil. When MATHML-FILE is specified,
17951 write the results in to that file. When invoked as an
17952 interactive command, prompt for LATEX-FRAG, with initial value
17953 set to the current active region and echo the results for user
17954 inspection."
17955 (interactive (list (let ((frag (when (org-region-active-p)
17956 (buffer-substring-no-properties
17957 (region-beginning) (region-end)))))
17958 (read-string "LaTeX Fragment: " frag nil frag))))
17959 (unless latex-frag (error "Invalid latex-frag"))
17960 (let* ((tmp-in-file (file-relative-name
17961 (make-temp-name (expand-file-name "ltxmathml-in"))))
17962 (ignore (write-region latex-frag nil tmp-in-file))
17963 (tmp-out-file (file-relative-name
17964 (make-temp-name (expand-file-name "ltxmathml-out"))))
17965 (cmd (format-spec
17966 org-latex-to-mathml-convert-command
17967 `((?j . ,(shell-quote-argument
17968 (expand-file-name org-latex-to-mathml-jar-file)))
17969 (?I . ,(shell-quote-argument tmp-in-file))
17970 (?o . ,(shell-quote-argument tmp-out-file)))))
17971 mathml shell-command-output)
17972 (when (org-called-interactively-p 'any)
17973 (unless (org-format-latex-mathml-available-p)
17974 (error "LaTeX to MathML converter not configured")))
17975 (message "Running %s" cmd)
17976 (setq shell-command-output (shell-command-to-string cmd))
17977 (setq mathml
17978 (when (file-readable-p tmp-out-file)
17979 (with-current-buffer (find-file-noselect tmp-out-file t)
17980 (goto-char (point-min))
17981 (when (re-search-forward
17982 (concat
17983 (regexp-quote
17984 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17985 "\\(.\\|\n\\)*"
17986 (regexp-quote "</math>")) nil t)
17987 (prog1 (match-string 0) (kill-buffer))))))
17988 (cond
17989 (mathml
17990 (setq mathml
17991 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17992 (when mathml-file
17993 (write-region mathml nil mathml-file))
17994 (when (org-called-interactively-p 'any)
17995 (message mathml)))
17996 ((message "LaTeX to MathML conversion failed")
17997 (message shell-command-output)))
17998 (delete-file tmp-in-file)
17999 (when (file-exists-p tmp-out-file)
18000 (delete-file tmp-out-file))
18001 mathml))
18003 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18004 prefix &optional dir)
18005 "Use `org-create-math-formula' but check local cache first."
18006 (let* ((absprefix (expand-file-name prefix dir))
18007 (print-length nil) (print-level nil)
18008 (formula-id (concat
18009 "formula-"
18010 (sha1
18011 (prin1-to-string
18012 (list latex-frag
18013 org-latex-to-mathml-convert-command)))))
18014 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18015 (formula-cache-dir (file-name-directory formula-cache)))
18017 (unless (file-directory-p formula-cache-dir)
18018 (make-directory formula-cache-dir t))
18020 (unless (file-exists-p formula-cache)
18021 (org-create-math-formula latex-frag formula-cache))
18023 (if (file-exists-p formula-cache)
18024 ;; Successful conversion. Return the link to MathML file.
18025 (org-add-props
18026 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18027 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18028 'org-latex-src-embed-type (if latex-frag-type
18029 'paragraph 'character)))
18030 ;; Failed conversion. Return the LaTeX fragment verbatim
18031 latex-frag)))
18033 (defun org-create-formula-image (string tofile options buffer &optional type)
18034 "Create an image from LaTeX source using dvipng or convert.
18035 This function calls either `org-create-formula-image-with-dvipng'
18036 or `org-create-formula-image-with-imagemagick' depending on the
18037 value of `org-latex-create-formula-image-program' or on the value
18038 of the optional TYPE variable.
18040 Note: ultimately these two function should be combined as they
18041 share a good deal of logic."
18042 (org-check-external-command
18043 "latex" "needed to convert LaTeX fragments to images")
18044 (funcall
18045 (case (or type org-latex-create-formula-image-program)
18046 ('dvipng
18047 (org-check-external-command
18048 "dvipng" "needed to convert LaTeX fragments to images")
18049 #'org-create-formula-image-with-dvipng)
18050 ('imagemagick
18051 (org-check-external-command
18052 "convert" "you need to install imagemagick")
18053 #'org-create-formula-image-with-imagemagick)
18054 (t (error
18055 "invalid value of `org-latex-create-formula-image-program'")))
18056 string tofile options buffer))
18058 ;; This function borrows from Ganesh Swami's latex2png.el
18059 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18060 "This calls dvipng."
18061 (let* ((tmpdir (if (featurep 'xemacs)
18062 (temp-directory)
18063 temporary-file-directory))
18064 (texfilebase (make-temp-name
18065 (expand-file-name "orgtex" tmpdir)))
18066 (texfile (concat texfilebase ".tex"))
18067 (dvifile (concat texfilebase ".dvi"))
18068 (pngfile (concat texfilebase ".png"))
18069 (fnh (if (featurep 'xemacs)
18070 (font-height (face-font 'default))
18071 (face-attribute 'default :height nil)))
18072 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18073 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18074 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18075 "Black"))
18076 (bg (or (plist-get options (if buffer :background :html-background))
18077 "Transparent")))
18078 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18079 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18080 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18081 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18082 (with-temp-file texfile
18083 (require 'ox-latex)
18084 (insert (org-latex-guess-inputenc
18085 (org-splice-latex-header
18086 org-format-latex-header
18087 org-latex-default-packages-alist
18088 org-latex-packages-alist t)))
18089 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18090 (let ((dir default-directory))
18091 (condition-case nil
18092 (progn
18093 (cd tmpdir)
18094 (call-process "latex" nil nil nil texfile))
18095 (error nil))
18096 (cd dir))
18097 (if (not (file-exists-p dvifile))
18098 (progn (message "Failed to create dvi file from %s" texfile) nil)
18099 (condition-case nil
18100 (if (featurep 'xemacs)
18101 (call-process "dvipng" nil nil nil
18102 "-fg" fg "-bg" bg
18103 "-T" "tight"
18104 "-o" pngfile
18105 dvifile)
18106 (call-process "dvipng" nil nil nil
18107 "-fg" fg "-bg" bg
18108 "-D" dpi
18109 ;;"-x" scale "-y" scale
18110 "-T" "tight"
18111 "-o" pngfile
18112 dvifile))
18113 (error nil))
18114 (if (not (file-exists-p pngfile))
18115 (if org-format-latex-signal-error
18116 (error "Failed to create png file from %s" texfile)
18117 (message "Failed to create png file from %s" texfile)
18118 nil)
18119 ;; Use the requested file name and clean up
18120 (copy-file pngfile tofile 'replace)
18121 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18122 (if (file-exists-p (concat texfilebase e))
18123 (delete-file (concat texfilebase e))))
18124 pngfile))))
18126 (defvar org-latex-pdf-process) ; From ox-latex.el
18127 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18128 "This calls convert, which is included into imagemagick."
18129 (let* ((tmpdir (if (featurep 'xemacs)
18130 (temp-directory)
18131 temporary-file-directory))
18132 (texfilebase (make-temp-name
18133 (expand-file-name "orgtex" tmpdir)))
18134 (texfile (concat texfilebase ".tex"))
18135 (pdffile (concat texfilebase ".pdf"))
18136 (pngfile (concat texfilebase ".png"))
18137 (fnh (if (featurep 'xemacs)
18138 (font-height (face-font 'default))
18139 (face-attribute 'default :height nil)))
18140 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18141 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18142 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18143 "black"))
18144 (bg (or (plist-get options (if buffer :background :html-background))
18145 "white")))
18146 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18147 (setq fg (org-latex-color-format fg)))
18148 (if (eq bg 'default) (setq bg (org-latex-color :background))
18149 (setq bg (org-latex-color-format
18150 (if (string= bg "Transparent") "white" bg))))
18151 (with-temp-file texfile
18152 (require 'ox-latex)
18153 (insert (org-latex-guess-inputenc
18154 (org-splice-latex-header
18155 org-format-latex-header
18156 org-latex-default-packages-alist
18157 org-latex-packages-alist t)))
18158 (insert "\n\\begin{document}\n"
18159 "\\definecolor{fg}{rgb}{" fg "}\n"
18160 "\\definecolor{bg}{rgb}{" bg "}\n"
18161 "\n\\pagecolor{bg}\n"
18162 "\n{\\color{fg}\n"
18163 string
18164 "\n}\n"
18165 "\n\\end{document}\n"))
18166 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18167 (condition-case nil
18168 (progn
18169 (cd tmpdir)
18170 (setq cmds org-latex-pdf-process)
18171 (while cmds
18172 (setq latex-frags-cmds (pop cmds))
18173 (if (listp latex-frags-cmds)
18174 (setq cmds nil)
18175 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18176 (while latex-frags-cmds
18177 (setq cmd (pop latex-frags-cmds))
18178 (while (string-match "%b" cmd)
18179 (setq cmd (replace-match
18180 (save-match-data
18181 (shell-quote-argument texfile))
18182 t t cmd)))
18183 (while (string-match "%f" cmd)
18184 (setq cmd (replace-match
18185 (save-match-data
18186 (shell-quote-argument
18187 (file-name-nondirectory texfile)))
18188 t t cmd)))
18189 (while (string-match "%o" cmd)
18190 (setq cmd (replace-match
18191 (save-match-data
18192 (shell-quote-argument
18193 (file-name-directory texfile)))
18194 t t cmd)))
18195 (setq cmd (split-string cmd))
18196 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18197 (error nil))
18198 (cd dir))
18199 (if (not (file-exists-p pdffile))
18200 (progn (message "Failed to create pdf file from %s" texfile) nil)
18201 (condition-case nil
18202 (if (featurep 'xemacs)
18203 (call-process "convert" nil nil nil
18204 "-density" "96"
18205 "-trim"
18206 "-antialias"
18207 pdffile
18208 "-quality" "100"
18209 ;; "-sharpen" "0x1.0"
18210 pngfile)
18211 (call-process "convert" nil nil nil
18212 "-density" dpi
18213 "-trim"
18214 "-antialias"
18215 pdffile
18216 "-quality" "100"
18217 ;; "-sharpen" "0x1.0"
18218 pngfile))
18219 (error nil))
18220 (if (not (file-exists-p pngfile))
18221 (if org-format-latex-signal-error
18222 (error "Failed to create png file from %s" texfile)
18223 (message "Failed to create png file from %s" texfile)
18224 nil)
18225 ;; Use the requested file name and clean up
18226 (copy-file pngfile tofile 'replace)
18227 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18228 (if (file-exists-p (concat texfilebase e))
18229 (delete-file (concat texfilebase e))))
18230 pngfile))))
18232 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18233 "Fill a LaTeX header template TPL.
18234 In the template, the following place holders will be recognized:
18236 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18237 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18238 [PACKAGES] \\usepackage statements for PKG
18239 [NO-PACKAGES] do not include PKG
18240 [EXTRA] the string EXTRA
18241 [NO-EXTRA] do not include EXTRA
18243 For backward compatibility, if both the positive and the negative place
18244 holder is missing, the positive one (without the \"NO-\") will be
18245 assumed to be present at the end of the template.
18246 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18247 EXTRA is a string.
18248 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18249 (let (rpl (end ""))
18250 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18251 (setq rpl (if (or (match-end 1) (not def-pkg))
18252 "" (org-latex-packages-to-string def-pkg snippets-p t))
18253 tpl (replace-match rpl t t tpl))
18254 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18256 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18257 (setq rpl (if (or (match-end 1) (not pkg))
18258 "" (org-latex-packages-to-string pkg snippets-p t))
18259 tpl (replace-match rpl t t tpl))
18260 (if pkg (setq end
18261 (concat end "\n"
18262 (org-latex-packages-to-string pkg snippets-p)))))
18264 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18265 (setq rpl (if (or (match-end 1) (not extra))
18266 "" (concat extra "\n"))
18267 tpl (replace-match rpl t t tpl))
18268 (if (and extra (string-match "\\S-" extra))
18269 (setq end (concat end "\n" extra))))
18271 (if (string-match "\\S-" end)
18272 (concat tpl "\n" end)
18273 tpl)))
18275 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18276 "Turn an alist of packages into a string with the \\usepackage macros."
18277 (setq pkg (mapconcat (lambda(p)
18278 (cond
18279 ((stringp p) p)
18280 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18281 (format "%% Package %s omitted" (cadr p)))
18282 ((equal "" (car p))
18283 (format "\\usepackage{%s}" (cadr p)))
18285 (format "\\usepackage[%s]{%s}"
18286 (car p) (cadr p)))))
18288 "\n"))
18289 (if newline (concat pkg "\n") pkg))
18291 (defun org-dvipng-color (attr)
18292 "Return a RGB color specification for dvipng."
18293 (apply 'format "rgb %s %s %s"
18294 (mapcar 'org-normalize-color
18295 (if (featurep 'xemacs)
18296 (color-rgb-components
18297 (face-property 'default
18298 (cond ((eq attr :foreground) 'foreground)
18299 ((eq attr :background) 'background))))
18300 (color-values (face-attribute 'default attr nil))))))
18302 (defun org-dvipng-color-format (color-name)
18303 "Convert COLOR-NAME to a RGB color value for dvipng."
18304 (apply 'format "rgb %s %s %s"
18305 (mapcar 'org-normalize-color
18306 (color-values color-name))))
18308 (defun org-latex-color (attr)
18309 "Return a RGB color for the LaTeX color package."
18310 (apply 'format "%s,%s,%s"
18311 (mapcar 'org-normalize-color
18312 (if (featurep 'xemacs)
18313 (color-rgb-components
18314 (face-property 'default
18315 (cond ((eq attr :foreground) 'foreground)
18316 ((eq attr :background) 'background))))
18317 (color-values (face-attribute 'default attr nil))))))
18319 (defun org-latex-color-format (color-name)
18320 "Convert COLOR-NAME to a RGB color value."
18321 (apply 'format "%s,%s,%s"
18322 (mapcar 'org-normalize-color
18323 (color-values color-name))))
18325 (defun org-normalize-color (value)
18326 "Return string to be used as color value for an RGB component."
18327 (format "%g" (/ value 65535.0)))
18331 ;; Image display
18333 (defvar org-inline-image-overlays nil)
18334 (make-variable-buffer-local 'org-inline-image-overlays)
18336 (defun org-toggle-inline-images (&optional include-linked)
18337 "Toggle the display of inline images.
18338 INCLUDE-LINKED is passed to `org-display-inline-images'."
18339 (interactive "P")
18340 (if org-inline-image-overlays
18341 (progn
18342 (org-remove-inline-images)
18343 (message "Inline image display turned off"))
18344 (org-display-inline-images include-linked)
18345 (if (and (org-called-interactively-p)
18346 org-inline-image-overlays)
18347 (message "%d images displayed inline"
18348 (length org-inline-image-overlays))
18349 (message "No images to display inline"))))
18351 (defun org-redisplay-inline-images ()
18352 "Refresh the display of inline images."
18353 (interactive)
18354 (if (not org-inline-image-overlays)
18355 (org-toggle-inline-images)
18356 (org-toggle-inline-images)
18357 (org-toggle-inline-images)))
18359 (defun org-display-inline-images (&optional include-linked refresh beg end)
18360 "Display inline images.
18361 Normally only links without a description part are inlined, because this
18362 is how it will work for export. When INCLUDE-LINKED is set, also links
18363 with a description part will be inlined. This can be nice for a quick
18364 look at those images, but it does not reflect what exported files will look
18365 like.
18366 When REFRESH is set, refresh existing images between BEG and END.
18367 This will create new image displays only if necessary.
18368 BEG and END default to the buffer boundaries."
18369 (interactive "P")
18370 (unless refresh
18371 (org-remove-inline-images)
18372 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18373 (save-excursion
18374 (save-restriction
18375 (widen)
18376 (setq beg (or beg (point-min)) end (or end (point-max)))
18377 (goto-char beg)
18378 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18379 (substring (org-image-file-name-regexp) 0 -2)
18380 "\\)\\]" (if include-linked "" "\\]")))
18381 old file ov img type attrwidth width)
18382 (while (re-search-forward re end t)
18383 (setq old (get-char-property-and-overlay (match-beginning 1)
18384 'org-image-overlay)
18385 file (expand-file-name
18386 (concat (or (match-string 3) "") (match-string 4))))
18387 (when (image-type-available-p 'imagemagick)
18388 (setq attrwidth (if (or (listp org-image-actual-width)
18389 (null org-image-actual-width))
18390 (save-excursion
18391 (save-match-data
18392 (when (re-search-backward
18393 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18394 (save-excursion
18395 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18396 (string-to-number (match-string 1))))))
18397 width (cond ((eq org-image-actual-width t) nil)
18398 ((null org-image-actual-width) attrwidth)
18399 ((numberp org-image-actual-width)
18400 org-image-actual-width)
18401 ((listp org-image-actual-width)
18402 (or attrwidth (car org-image-actual-width))))
18403 type (if width 'imagemagick)))
18404 (when (file-exists-p file)
18405 (if (and (car-safe old) refresh)
18406 (image-refresh (overlay-get (cdr old) 'display))
18407 (setq img (save-match-data (create-image file type nil :width width)))
18408 (when img
18409 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18410 (overlay-put ov 'display img)
18411 (overlay-put ov 'face 'default)
18412 (overlay-put ov 'org-image-overlay t)
18413 (overlay-put ov 'modification-hooks
18414 (list 'org-display-inline-remove-overlay))
18415 (push ov org-inline-image-overlays)))))))))
18417 (define-obsolete-function-alias
18418 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18420 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18421 "Remove inline-display overlay if a corresponding region is modified."
18422 (let ((inhibit-modification-hooks t))
18423 (when (and ov after)
18424 (delete ov org-inline-image-overlays)
18425 (delete-overlay ov))))
18427 (defun org-remove-inline-images ()
18428 "Remove inline display of images."
18429 (interactive)
18430 (mapc 'delete-overlay org-inline-image-overlays)
18431 (setq org-inline-image-overlays nil))
18433 ;;;; Key bindings
18435 ;; Outline functions from `outline-mode-prefix-map'
18436 ;; that can be remapped in Org:
18437 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18438 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18439 (define-key org-mode-map [remap outline-forward-same-level]
18440 'org-forward-heading-same-level)
18441 (define-key org-mode-map [remap outline-backward-same-level]
18442 'org-backward-heading-same-level)
18443 (define-key org-mode-map [remap show-branches]
18444 'org-kill-note-or-show-branches)
18445 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18446 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18447 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18449 ;; Outline functions from `outline-mode-prefix-map' that can not
18450 ;; be remapped in Org:
18452 ;; - the column "key binding" shows whether the Outline function is still
18453 ;; available in Org mode on the same key that it has been bound to in
18454 ;; Outline mode:
18455 ;; - "overridden": key used for a different functionality in Org mode
18456 ;; - else: key still bound to the same Outline function in Org mode
18458 ;; | Outline function | key binding | Org replacement |
18459 ;; |------------------------------------+-------------+-----------------------|
18460 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18461 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18462 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18463 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18464 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18465 ;; | `show-entry' | overridden | no replacement |
18466 ;; | `show-children' | `C-c C-i' | visibility cycling |
18467 ;; | `show-branches' | `C-c C-k' | still same function |
18468 ;; | `show-subtree' | overridden | visibility cycling |
18469 ;; | `show-all' | overridden | no replacement |
18470 ;; | `hide-subtree' | overridden | visibility cycling |
18471 ;; | `hide-body' | overridden | no replacement |
18472 ;; | `hide-entry' | overridden | visibility cycling |
18473 ;; | `hide-leaves' | overridden | no replacement |
18474 ;; | `hide-sublevels' | overridden | no replacement |
18475 ;; | `hide-other' | overridden | no replacement |
18477 ;; Make `C-c C-x' a prefix key
18478 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18480 ;; TAB key with modifiers
18481 (org-defkey org-mode-map "\C-i" 'org-cycle)
18482 (org-defkey org-mode-map [(tab)] 'org-cycle)
18483 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18484 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18485 ;; The following line is necessary under Suse GNU/Linux
18486 (unless (featurep 'xemacs)
18487 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18488 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18489 (define-key org-mode-map [backtab] 'org-shifttab)
18491 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18492 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18493 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18495 ;; Cursor keys with modifiers
18496 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18497 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18498 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18499 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18501 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18502 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18503 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18504 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18506 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18507 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18508 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18509 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18511 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18512 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18513 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18514 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18516 ;; Babel keys
18517 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18518 (mapc (lambda (pair)
18519 (define-key org-babel-map (car pair) (cdr pair)))
18520 org-babel-key-bindings)
18522 ;;; Extra keys for tty access.
18523 ;; We only set them when really needed because otherwise the
18524 ;; menus don't show the simple keys
18526 (when (or org-use-extra-keys
18527 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18528 (not window-system))
18529 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18530 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18531 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18532 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18533 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18534 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18535 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18536 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18537 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18538 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18539 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18540 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18541 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18542 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18543 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18544 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18545 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18546 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18547 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18548 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18549 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18550 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18551 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18552 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18553 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18554 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18555 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18556 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18558 ;; All the other keys
18560 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18561 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18562 (if (boundp 'narrow-map)
18563 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18564 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18565 (if (boundp 'narrow-map)
18566 (org-defkey narrow-map "b" 'org-narrow-to-block)
18567 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18568 (if (boundp 'narrow-map)
18569 (org-defkey narrow-map "e" 'org-narrow-to-element)
18570 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18571 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18572 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18573 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18574 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18575 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18576 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18577 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18578 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18579 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18580 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18581 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18582 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18583 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18584 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18585 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18586 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18587 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18588 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18589 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18590 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18591 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18592 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18593 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18594 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18595 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18596 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18597 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18598 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18599 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18600 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18601 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18602 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18603 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18604 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18605 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18606 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18607 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18608 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18609 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18610 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18611 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18612 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18613 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18614 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18615 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18616 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18617 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18618 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18619 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18620 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18621 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18622 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18623 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18624 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18625 (org-defkey org-mode-map "\C-c^" 'org-sort)
18626 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18627 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18628 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18629 (org-defkey org-mode-map "\C-m" 'org-return)
18630 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18631 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18632 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18633 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18634 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18635 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18636 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18637 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18638 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18639 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18640 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18641 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18642 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18643 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18644 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18645 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18646 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18647 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18648 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18649 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18650 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18651 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18652 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18654 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18655 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18656 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18658 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18659 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18660 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18661 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18662 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18663 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18664 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18665 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18666 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18667 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18668 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18669 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18670 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18671 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18672 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18673 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18674 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18675 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18676 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18677 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18678 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18679 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18680 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18682 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18683 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18684 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18685 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18686 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18688 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18690 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18692 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18693 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18695 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18698 (when (featurep 'xemacs)
18699 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18702 (defconst org-speed-commands-default
18704 ("Outline Navigation")
18705 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18706 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18707 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18708 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18709 ("F" . org-next-block)
18710 ("B" . org-previous-block)
18711 ("u" . (org-speed-move-safe 'outline-up-heading))
18712 ("j" . org-goto)
18713 ("g" . (org-refile t))
18714 ("Outline Visibility")
18715 ("c" . org-cycle)
18716 ("C" . org-shifttab)
18717 (" " . org-display-outline-path)
18718 ("=" . org-columns)
18719 ("Outline Structure Editing")
18720 ("U" . org-shiftmetaup)
18721 ("D" . org-shiftmetadown)
18722 ("r" . org-metaright)
18723 ("l" . org-metaleft)
18724 ("R" . org-shiftmetaright)
18725 ("L" . org-shiftmetaleft)
18726 ("i" . (progn (forward-char 1) (call-interactively
18727 'org-insert-heading-respect-content)))
18728 ("^" . org-sort)
18729 ("w" . org-refile)
18730 ("a" . org-archive-subtree-default-with-confirmation)
18731 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18732 ("#" . org-toggle-comment)
18733 ("Clock Commands")
18734 ("I" . org-clock-in)
18735 ("O" . org-clock-out)
18736 ("Meta Data Editing")
18737 ("t" . org-todo)
18738 ("," . (org-priority))
18739 ("0" . (org-priority ?\ ))
18740 ("1" . (org-priority ?A))
18741 ("2" . (org-priority ?B))
18742 ("3" . (org-priority ?C))
18743 (":" . org-set-tags-command)
18744 ("e" . org-set-effort)
18745 ("E" . org-inc-effort)
18746 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18747 (org-entry-put (point) "APPT_WARNTIME" m)))
18748 ("Agenda Views etc")
18749 ("v" . org-agenda)
18750 ("/" . org-sparse-tree)
18751 ("Misc")
18752 ("o" . org-open-at-point)
18753 ("?" . org-speed-command-help)
18754 ("<" . (org-agenda-set-restriction-lock 'subtree))
18755 (">" . (org-agenda-remove-restriction-lock))
18757 "The default speed commands.")
18759 (defun org-print-speed-command (e)
18760 (if (> (length (car e)) 1)
18761 (progn
18762 (princ "\n")
18763 (princ (car e))
18764 (princ "\n")
18765 (princ (make-string (length (car e)) ?-))
18766 (princ "\n"))
18767 (princ (car e))
18768 (princ " ")
18769 (if (symbolp (cdr e))
18770 (princ (symbol-name (cdr e)))
18771 (prin1 (cdr e)))
18772 (princ "\n")))
18774 (defun org-speed-command-help ()
18775 "Show the available speed commands."
18776 (interactive)
18777 (if (not org-use-speed-commands)
18778 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18779 (with-output-to-temp-buffer "*Help*"
18780 (princ "User-defined Speed commands\n===========================\n")
18781 (mapc 'org-print-speed-command org-speed-commands-user)
18782 (princ "\n")
18783 (princ "Built-in Speed commands\n=======================\n")
18784 (mapc 'org-print-speed-command org-speed-commands-default))
18785 (with-current-buffer "*Help*"
18786 (setq truncate-lines t))))
18788 (defun org-speed-move-safe (cmd)
18789 "Execute CMD, but make sure that the cursor always ends up in a headline.
18790 If not, return to the original position and throw an error."
18791 (interactive)
18792 (let ((pos (point)))
18793 (call-interactively cmd)
18794 (unless (and (bolp) (org-at-heading-p))
18795 (goto-char pos)
18796 (error "Boundary reached while executing %s" cmd))))
18798 (defvar org-self-insert-command-undo-counter 0)
18800 (defvar org-table-auto-blank-field) ; defined in org-table.el
18801 (defvar org-speed-command nil)
18803 (define-obsolete-function-alias
18804 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18806 (defun org-speed-command-activate (keys)
18807 "Hook for activating single-letter speed commands.
18808 `org-speed-commands-default' specifies a minimal command set.
18809 Use `org-speed-commands-user' for further customization."
18810 (when (or (and (bolp) (looking-at org-outline-regexp))
18811 (and (functionp org-use-speed-commands)
18812 (funcall org-use-speed-commands)))
18813 (cdr (assoc keys (append org-speed-commands-user
18814 org-speed-commands-default)))))
18816 (define-obsolete-function-alias
18817 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18819 (defun org-babel-speed-command-activate (keys)
18820 "Hook for activating single-letter code block commands."
18821 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18822 (cdr (assoc keys org-babel-key-bindings))))
18824 (defcustom org-speed-command-hook
18825 '(org-speed-command-default-hook org-babel-speed-command-hook)
18826 "Hook for activating speed commands at strategic locations.
18827 Hook functions are called in sequence until a valid handler is
18828 found.
18830 Each hook takes a single argument, a user-pressed command key
18831 which is also a `self-insert-command' from the global map.
18833 Within the hook, examine the cursor position and the command key
18834 and return nil or a valid handler as appropriate. Handler could
18835 be one of an interactive command, a function, or a form.
18837 Set `org-use-speed-commands' to non-nil value to enable this
18838 hook. The default setting is `org-speed-command-activate'."
18839 :group 'org-structure
18840 :version "24.1"
18841 :type 'hook)
18843 (defun org-self-insert-command (N)
18844 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18845 If the cursor is in a table looking at whitespace, the whitespace is
18846 overwritten, and the table is not marked as requiring realignment."
18847 (interactive "p")
18848 (org-check-before-invisible-edit 'insert)
18849 (cond
18850 ((and org-use-speed-commands
18851 (setq org-speed-command
18852 (run-hook-with-args-until-success
18853 'org-speed-command-hook (this-command-keys))))
18854 (cond
18855 ((commandp org-speed-command)
18856 (setq this-command org-speed-command)
18857 (call-interactively org-speed-command))
18858 ((functionp org-speed-command)
18859 (funcall org-speed-command))
18860 ((and org-speed-command (listp org-speed-command))
18861 (eval org-speed-command))
18862 (t (let (org-use-speed-commands)
18863 (call-interactively 'org-self-insert-command)))))
18864 ((and
18865 (org-table-p)
18866 (progn
18867 ;; check if we blank the field, and if that triggers align
18868 (and (featurep 'org-table) org-table-auto-blank-field
18869 (member last-command
18870 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18871 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18872 ;; got extra space, this field does not determine column width
18873 (let (org-table-may-need-update) (org-table-blank-field))
18874 ;; no extra space, this field may determine column width
18875 (org-table-blank-field)))
18877 (eq N 1)
18878 (looking-at "[^|\n]* |"))
18879 (let (org-table-may-need-update)
18880 (goto-char (1- (match-end 0)))
18881 (backward-delete-char 1)
18882 (goto-char (match-beginning 0))
18883 (self-insert-command N)))
18885 (setq org-table-may-need-update t)
18886 (self-insert-command N)
18887 (org-fix-tags-on-the-fly)
18888 (if org-self-insert-cluster-for-undo
18889 (if (not (eq last-command 'org-self-insert-command))
18890 (setq org-self-insert-command-undo-counter 1)
18891 (if (>= org-self-insert-command-undo-counter 20)
18892 (setq org-self-insert-command-undo-counter 1)
18893 (and (> org-self-insert-command-undo-counter 0)
18894 buffer-undo-list (listp buffer-undo-list)
18895 (not (cadr buffer-undo-list)) ; remove nil entry
18896 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18897 (setq org-self-insert-command-undo-counter
18898 (1+ org-self-insert-command-undo-counter))))))))
18900 (defun org-check-before-invisible-edit (kind)
18901 "Check is editing if kind KIND would be dangerous with invisible text around.
18902 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18903 ;; First, try to get out of here as quickly as possible, to reduce overhead
18904 (if (and org-catch-invisible-edits
18905 (or (not (boundp 'visible-mode)) (not visible-mode))
18906 (or (get-char-property (point) 'invisible)
18907 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18908 ;; OK, we need to take a closer look
18909 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18910 (invisible-before-point (if (bobp) nil (get-char-property
18911 (1- (point)) 'invisible)))
18912 (border-and-ok-direction
18914 ;; Check if we are acting predictably before invisible text
18915 (and invisible-at-point (not invisible-before-point)
18916 (memq kind '(insert delete-backward)))
18917 ;; Check if we are acting predictably after invisible text
18918 ;; This works not well, and I have turned it off. It seems
18919 ;; better to always show and stop after invisible text.
18920 ;; (and (not invisible-at-point) invisible-before-point
18921 ;; (memq kind '(insert delete)))
18923 (when (or (memq invisible-at-point '(outline org-hide-block t))
18924 (memq invisible-before-point '(outline org-hide-block t)))
18925 (if (eq org-catch-invisible-edits 'error)
18926 (error "Editing in invisible areas is prohibited - make visible first"))
18927 (if (and org-custom-properties-overlays
18928 (y-or-n-p "Display invisible properties in this buffer? "))
18929 (org-toggle-custom-properties-visibility)
18930 ;; Make the area visible
18931 (save-excursion
18932 (if invisible-before-point
18933 (goto-char (previous-single-char-property-change
18934 (point) 'invisible)))
18935 (org-cycle))
18936 (cond
18937 ((eq org-catch-invisible-edits 'show)
18938 ;; That's it, we do the edit after showing
18939 (message
18940 "Unfolding invisible region around point before editing")
18941 (sit-for 1))
18942 ((and (eq org-catch-invisible-edits 'smart)
18943 border-and-ok-direction)
18944 (message "Unfolding invisible region around point before editing"))
18946 ;; Don't do the edit, make the user repeat it in full visibility
18947 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18949 (defun org-fix-tags-on-the-fly ()
18950 (when (and (equal (char-after (point-at-bol)) ?*)
18951 (org-at-heading-p))
18952 (org-align-tags-here org-tags-column)))
18954 (defun org-delete-backward-char (N)
18955 "Like `delete-backward-char', insert whitespace at field end in tables.
18956 When deleting backwards, in tables this function will insert whitespace in
18957 front of the next \"|\" separator, to keep the table aligned. The table will
18958 still be marked for re-alignment if the field did fill the entire column,
18959 because, in this case the deletion might narrow the column."
18960 (interactive "p")
18961 (save-match-data
18962 (org-check-before-invisible-edit 'delete-backward)
18963 (if (and (org-table-p)
18964 (eq N 1)
18965 (string-match "|" (buffer-substring (point-at-bol) (point)))
18966 (looking-at ".*?|"))
18967 (let ((pos (point))
18968 (noalign (looking-at "[^|\n\r]* |"))
18969 (c org-table-may-need-update))
18970 (backward-delete-char N)
18971 (if (not overwrite-mode)
18972 (progn
18973 (skip-chars-forward "^|")
18974 (insert " ")
18975 (goto-char (1- pos))))
18976 ;; noalign: if there were two spaces at the end, this field
18977 ;; does not determine the width of the column.
18978 (if noalign (setq org-table-may-need-update c)))
18979 (backward-delete-char N)
18980 (org-fix-tags-on-the-fly))))
18982 (defun org-delete-char (N)
18983 "Like `delete-char', but insert whitespace at field end in tables.
18984 When deleting characters, in tables this function will insert whitespace in
18985 front of the next \"|\" separator, to keep the table aligned. The table will
18986 still be marked for re-alignment if the field did fill the entire column,
18987 because, in this case the deletion might narrow the column."
18988 (interactive "p")
18989 (save-match-data
18990 (org-check-before-invisible-edit 'delete)
18991 (if (and (org-table-p)
18992 (not (bolp))
18993 (not (= (char-after) ?|))
18994 (eq N 1))
18995 (if (looking-at ".*?|")
18996 (let ((pos (point))
18997 (noalign (looking-at "[^|\n\r]* |"))
18998 (c org-table-may-need-update))
18999 (replace-match (concat
19000 (substring (match-string 0) 1 -1)
19001 " |"))
19002 (goto-char pos)
19003 ;; noalign: if there were two spaces at the end, this field
19004 ;; does not determine the width of the column.
19005 (if noalign (setq org-table-may-need-update c)))
19006 (delete-char N))
19007 (delete-char N)
19008 (org-fix-tags-on-the-fly))))
19010 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19011 (put 'org-self-insert-command 'delete-selection t)
19012 (put 'orgtbl-self-insert-command 'delete-selection t)
19013 (put 'org-delete-char 'delete-selection 'supersede)
19014 (put 'org-delete-backward-char 'delete-selection 'supersede)
19015 (put 'org-yank 'delete-selection 'yank)
19017 ;; Make `flyspell-mode' delay after some commands
19018 (put 'org-self-insert-command 'flyspell-delayed t)
19019 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19020 (put 'org-delete-char 'flyspell-delayed t)
19021 (put 'org-delete-backward-char 'flyspell-delayed t)
19023 ;; Make pabbrev-mode expand after org-mode commands
19024 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19025 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19027 ;; How to do this: Measure non-white length of current string
19028 ;; If equal to column width, we should realign.
19030 (defun org-remap (map &rest commands)
19031 "In MAP, remap the functions given in COMMANDS.
19032 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19033 (let (new old)
19034 (while commands
19035 (setq old (pop commands) new (pop commands))
19036 (if (fboundp 'command-remapping)
19037 (org-defkey map (vector 'remap old) new)
19038 (substitute-key-definition old new map global-map)))))
19040 (when (eq org-enable-table-editor 'optimized)
19041 ;; If the user wants maximum table support, we need to hijack
19042 ;; some standard editing functions
19043 (org-remap org-mode-map
19044 'self-insert-command 'org-self-insert-command
19045 'delete-char 'org-delete-char
19046 'delete-backward-char 'org-delete-backward-char)
19047 (org-defkey org-mode-map "|" 'org-force-self-insert))
19049 (defvar org-ctrl-c-ctrl-c-hook nil
19050 "Hook for functions attaching themselves to `C-c C-c'.
19052 This can be used to add additional functionality to the C-c C-c
19053 key which executes context-dependent commands. This hook is run
19054 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19055 run after the last test.
19057 Each function will be called with no arguments. The function
19058 must check if the context is appropriate for it to act. If yes,
19059 it should do its thing and then return a non-nil value. If the
19060 context is wrong, just do nothing and return nil.")
19062 (defvar org-ctrl-c-ctrl-c-final-hook nil
19063 "Hook for functions attaching themselves to `C-c C-c'.
19065 This can be used to add additional functionality to the C-c C-c
19066 key which executes context-dependent commands. This hook is run
19067 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19068 before the first test.
19070 Each function will be called with no arguments. The function
19071 must check if the context is appropriate for it to act. If yes,
19072 it should do its thing and then return a non-nil value. If the
19073 context is wrong, just do nothing and return nil.")
19075 (defvar org-tab-first-hook nil
19076 "Hook for functions to attach themselves to TAB.
19077 See `org-ctrl-c-ctrl-c-hook' for more information.
19078 This hook runs as the first action when TAB is pressed, even before
19079 `org-cycle' messes around with the `outline-regexp' to cater for
19080 inline tasks and plain list item folding.
19081 If any function in this hook returns t, any other actions that
19082 would have been caused by TAB (such as table field motion or visibility
19083 cycling) will not occur.")
19085 (defvar org-tab-after-check-for-table-hook nil
19086 "Hook for functions to attach themselves to TAB.
19087 See `org-ctrl-c-ctrl-c-hook' for more information.
19088 This hook runs after it has been established that the cursor is not in a
19089 table, but before checking if the cursor is in a headline or if global cycling
19090 should be done.
19091 If any function in this hook returns t, not other actions like visibility
19092 cycling will be done.")
19094 (defvar org-tab-after-check-for-cycling-hook nil
19095 "Hook for functions to attach themselves to TAB.
19096 See `org-ctrl-c-ctrl-c-hook' for more information.
19097 This hook runs after it has been established that not table field motion and
19098 not visibility should be done because of current context. This is probably
19099 the place where a package like yasnippets can hook in.")
19101 (defvar org-tab-before-tab-emulation-hook nil
19102 "Hook for functions to attach themselves to TAB.
19103 See `org-ctrl-c-ctrl-c-hook' for more information.
19104 This hook runs after every other options for TAB have been exhausted, but
19105 before indentation and \t insertion takes place.")
19107 (defvar org-metaleft-hook nil
19108 "Hook for functions attaching themselves to `M-left'.
19109 See `org-ctrl-c-ctrl-c-hook' for more information.")
19110 (defvar org-metaright-hook nil
19111 "Hook for functions attaching themselves to `M-right'.
19112 See `org-ctrl-c-ctrl-c-hook' for more information.")
19113 (defvar org-metaup-hook nil
19114 "Hook for functions attaching themselves to `M-up'.
19115 See `org-ctrl-c-ctrl-c-hook' for more information.")
19116 (defvar org-metadown-hook nil
19117 "Hook for functions attaching themselves to `M-down'.
19118 See `org-ctrl-c-ctrl-c-hook' for more information.")
19119 (defvar org-shiftmetaleft-hook nil
19120 "Hook for functions attaching themselves to `M-S-left'.
19121 See `org-ctrl-c-ctrl-c-hook' for more information.")
19122 (defvar org-shiftmetaright-hook nil
19123 "Hook for functions attaching themselves to `M-S-right'.
19124 See `org-ctrl-c-ctrl-c-hook' for more information.")
19125 (defvar org-shiftmetaup-hook nil
19126 "Hook for functions attaching themselves to `M-S-up'.
19127 See `org-ctrl-c-ctrl-c-hook' for more information.")
19128 (defvar org-shiftmetadown-hook nil
19129 "Hook for functions attaching themselves to `M-S-down'.
19130 See `org-ctrl-c-ctrl-c-hook' for more information.")
19131 (defvar org-metareturn-hook nil
19132 "Hook for functions attaching themselves to `M-RET'.
19133 See `org-ctrl-c-ctrl-c-hook' for more information.")
19134 (defvar org-shiftup-hook nil
19135 "Hook for functions attaching themselves to `S-up'.
19136 See `org-ctrl-c-ctrl-c-hook' for more information.")
19137 (defvar org-shiftup-final-hook nil
19138 "Hook for functions attaching themselves to `S-up'.
19139 This one runs after all other options except shift-select have been excluded.
19140 See `org-ctrl-c-ctrl-c-hook' for more information.")
19141 (defvar org-shiftdown-hook nil
19142 "Hook for functions attaching themselves to `S-down'.
19143 See `org-ctrl-c-ctrl-c-hook' for more information.")
19144 (defvar org-shiftdown-final-hook nil
19145 "Hook for functions attaching themselves to `S-down'.
19146 This one runs after all other options except shift-select have been excluded.
19147 See `org-ctrl-c-ctrl-c-hook' for more information.")
19148 (defvar org-shiftleft-hook nil
19149 "Hook for functions attaching themselves to `S-left'.
19150 See `org-ctrl-c-ctrl-c-hook' for more information.")
19151 (defvar org-shiftleft-final-hook nil
19152 "Hook for functions attaching themselves to `S-left'.
19153 This one runs after all other options except shift-select have been excluded.
19154 See `org-ctrl-c-ctrl-c-hook' for more information.")
19155 (defvar org-shiftright-hook nil
19156 "Hook for functions attaching themselves to `S-right'.
19157 See `org-ctrl-c-ctrl-c-hook' for more information.")
19158 (defvar org-shiftright-final-hook nil
19159 "Hook for functions attaching themselves to `S-right'.
19160 This one runs after all other options except shift-select have been excluded.
19161 See `org-ctrl-c-ctrl-c-hook' for more information.")
19163 (defun org-modifier-cursor-error ()
19164 "Throw an error, a modified cursor command was applied in wrong context."
19165 (error "This command is active in special context like tables, headlines or items"))
19167 (defun org-shiftselect-error ()
19168 "Throw an error because Shift-Cursor command was applied in wrong context."
19169 (if (and (boundp 'shift-select-mode) shift-select-mode)
19170 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19171 (error "This command works only in special context like headlines or timestamps")))
19173 (defun org-call-for-shift-select (cmd)
19174 (let ((this-command-keys-shift-translated t))
19175 (call-interactively cmd)))
19177 (defun org-shifttab (&optional arg)
19178 "Global visibility cycling or move to previous table field.
19179 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19180 on context.
19181 See the individual commands for more information."
19182 (interactive "P")
19183 (cond
19184 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19185 ((integerp arg)
19186 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19187 (message "Content view to level: %d" arg)
19188 (org-content (prefix-numeric-value arg2))
19189 (setq org-cycle-global-status 'overview)))
19190 (t (call-interactively 'org-global-cycle))))
19192 (defun org-shiftmetaleft ()
19193 "Promote subtree or delete table column.
19194 Calls `org-promote-subtree', `org-outdent-item-tree', or
19195 `org-table-delete-column', depending on context. See the
19196 individual commands for more information."
19197 (interactive)
19198 (cond
19199 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19200 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19201 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19202 ((if (not (org-region-active-p)) (org-at-item-p)
19203 (save-excursion (goto-char (region-beginning))
19204 (org-at-item-p)))
19205 (call-interactively 'org-outdent-item-tree))
19206 (t (org-modifier-cursor-error))))
19208 (defun org-shiftmetaright ()
19209 "Demote subtree or insert table column.
19210 Calls `org-demote-subtree', `org-indent-item-tree', or
19211 `org-table-insert-column', depending on context. See the
19212 individual commands for more information."
19213 (interactive)
19214 (cond
19215 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19216 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19217 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19218 ((if (not (org-region-active-p)) (org-at-item-p)
19219 (save-excursion (goto-char (region-beginning))
19220 (org-at-item-p)))
19221 (call-interactively 'org-indent-item-tree))
19222 (t (org-modifier-cursor-error))))
19224 (defun org-shiftmetaup (&optional arg)
19225 "Move subtree up or kill table row.
19226 Calls `org-move-subtree-up' or `org-table-kill-row' or
19227 `org-move-item-up' or `org-timestamp-up', depending on context.
19228 See the individual commands for more information."
19229 (interactive "P")
19230 (cond
19231 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19232 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19233 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19234 ((org-at-item-p) (call-interactively 'org-move-item-up))
19235 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19236 (call-interactively 'org-timestamp-up)))
19237 (t (call-interactively 'org-drag-line-backward))))
19239 (defun org-shiftmetadown (&optional arg)
19240 "Move subtree down or insert table row.
19241 Calls `org-move-subtree-down' or `org-table-insert-row' or
19242 `org-move-item-down' or `org-timestamp-up', depending on context.
19243 See the individual commands for more information."
19244 (interactive "P")
19245 (cond
19246 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19247 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19248 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19249 ((org-at-item-p) (call-interactively 'org-move-item-down))
19250 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19251 (call-interactively 'org-timestamp-down)))
19252 (t (call-interactively 'org-drag-line-forward))))
19254 (defsubst org-hidden-tree-error ()
19255 (error
19256 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19258 (defun org-metaleft (&optional arg)
19259 "Promote heading or move table column to left.
19260 Calls `org-do-promote' or `org-table-move-column', depending on context.
19261 With no specific context, calls the Emacs default `backward-word'.
19262 See the individual commands for more information."
19263 (interactive "P")
19264 (cond
19265 ((run-hook-with-args-until-success 'org-metaleft-hook))
19266 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19267 ((org-with-limited-levels
19268 (or (org-at-heading-p)
19269 (and (org-region-active-p)
19270 (save-excursion
19271 (goto-char (region-beginning))
19272 (org-at-heading-p)))))
19273 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19274 (call-interactively 'org-do-promote))
19275 ;; At an inline task.
19276 ((org-at-heading-p)
19277 (call-interactively 'org-inlinetask-promote))
19278 ((or (org-at-item-p)
19279 (and (org-region-active-p)
19280 (save-excursion
19281 (goto-char (region-beginning))
19282 (org-at-item-p))))
19283 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19284 (call-interactively 'org-outdent-item))
19285 (t (call-interactively 'backward-word))))
19287 (defun org-metaright (&optional arg)
19288 "Demote a subtree, a list item or move table column to right.
19289 In front of a drawer or a block keyword, indent it correctly.
19290 With no specific context, calls the Emacs default `forward-word'.
19291 See the individual commands for more information."
19292 (interactive "P")
19293 (cond
19294 ((run-hook-with-args-until-success 'org-metaright-hook))
19295 ((org-at-table-p) (call-interactively 'org-table-move-column))
19296 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19297 ((org-at-block-p) (call-interactively 'org-indent-block))
19298 ((org-with-limited-levels
19299 (or (org-at-heading-p)
19300 (and (org-region-active-p)
19301 (save-excursion
19302 (goto-char (region-beginning))
19303 (org-at-heading-p)))))
19304 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19305 (call-interactively 'org-do-demote))
19306 ;; At an inline task.
19307 ((org-at-heading-p)
19308 (call-interactively 'org-inlinetask-demote))
19309 ((or (org-at-item-p)
19310 (and (org-region-active-p)
19311 (save-excursion
19312 (goto-char (region-beginning))
19313 (org-at-item-p))))
19314 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19315 (call-interactively 'org-indent-item))
19316 (t (call-interactively 'forward-word))))
19318 (defun org-check-for-hidden (what)
19319 "Check if there are hidden headlines/items in the current visual line.
19320 WHAT can be either `headlines' or `items'. If the current line is
19321 an outline or item heading and it has a folded subtree below it,
19322 this function returns t, nil otherwise."
19323 (let ((re (cond
19324 ((eq what 'headlines) org-outline-regexp-bol)
19325 ((eq what 'items) (org-item-beginning-re))
19326 (t (error "This should not happen"))))
19327 beg end)
19328 (save-excursion
19329 (catch 'exit
19330 (unless (org-region-active-p)
19331 (setq beg (point-at-bol))
19332 (beginning-of-line 2)
19333 (while (and (not (eobp)) ;; this is like `next-line'
19334 (get-char-property (1- (point)) 'invisible))
19335 (beginning-of-line 2))
19336 (setq end (point))
19337 (goto-char beg)
19338 (goto-char (point-at-eol))
19339 (setq end (max end (point)))
19340 (while (re-search-forward re end t)
19341 (if (get-char-property (match-beginning 0) 'invisible)
19342 (throw 'exit t))))
19343 nil))))
19345 (defun org-metaup (&optional arg)
19346 "Move subtree up or move table row up.
19347 Calls `org-move-subtree-up' or `org-table-move-row' or
19348 `org-move-item-up', depending on context. See the individual commands
19349 for more information."
19350 (interactive "P")
19351 (cond
19352 ((run-hook-with-args-until-success 'org-metaup-hook))
19353 ((org-region-active-p)
19354 (let* ((a (min (region-beginning) (region-end)))
19355 (b (1- (max (region-beginning) (region-end))))
19356 (c (save-excursion (goto-char a)
19357 (move-beginning-of-line 0)))
19358 (d (save-excursion (goto-char a)
19359 (move-end-of-line 0) (point))))
19360 (transpose-regions a b c d)
19361 (goto-char c)))
19362 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19363 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19364 ((org-at-item-p) (call-interactively 'org-move-item-up))
19365 (t (org-drag-element-backward))))
19367 (defun org-metadown (&optional arg)
19368 "Move subtree down or move table row down.
19369 Calls `org-move-subtree-down' or `org-table-move-row' or
19370 `org-move-item-down', depending on context. See the individual
19371 commands for more information."
19372 (interactive "P")
19373 (cond
19374 ((run-hook-with-args-until-success 'org-metadown-hook))
19375 ((org-region-active-p)
19376 (let* ((a (min (region-beginning) (region-end)))
19377 (b (max (region-beginning) (region-end)))
19378 (c (save-excursion (goto-char b)
19379 (move-beginning-of-line 1)))
19380 (d (save-excursion (goto-char b)
19381 (move-end-of-line 1) (1+ (point)))))
19382 (transpose-regions a b c d)
19383 (goto-char d)))
19384 ((org-at-table-p) (call-interactively 'org-table-move-row))
19385 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19386 ((org-at-item-p) (call-interactively 'org-move-item-down))
19387 (t (org-drag-element-forward))))
19389 (defun org-shiftup (&optional arg)
19390 "Increase item in timestamp or increase priority of current headline.
19391 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19392 depending on context. See the individual commands for more information."
19393 (interactive "P")
19394 (cond
19395 ((run-hook-with-args-until-success 'org-shiftup-hook))
19396 ((and org-support-shift-select (org-region-active-p))
19397 (org-call-for-shift-select 'previous-line))
19398 ((org-at-timestamp-p t)
19399 (call-interactively (if org-edit-timestamp-down-means-later
19400 'org-timestamp-down 'org-timestamp-up)))
19401 ((and (not (eq org-support-shift-select 'always))
19402 org-enable-priority-commands
19403 (org-at-heading-p))
19404 (call-interactively 'org-priority-up))
19405 ((and (not org-support-shift-select) (org-at-item-p))
19406 (call-interactively 'org-previous-item))
19407 ((org-clocktable-try-shift 'up arg))
19408 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19409 (org-support-shift-select
19410 (org-call-for-shift-select 'previous-line))
19411 (t (org-shiftselect-error))))
19413 (defun org-shiftdown (&optional arg)
19414 "Decrease item in timestamp or decrease priority of current headline.
19415 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19416 depending on context. See the individual commands for more information."
19417 (interactive "P")
19418 (cond
19419 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19420 ((and org-support-shift-select (org-region-active-p))
19421 (org-call-for-shift-select 'next-line))
19422 ((org-at-timestamp-p t)
19423 (call-interactively (if org-edit-timestamp-down-means-later
19424 'org-timestamp-up 'org-timestamp-down)))
19425 ((and (not (eq org-support-shift-select 'always))
19426 org-enable-priority-commands
19427 (org-at-heading-p))
19428 (call-interactively 'org-priority-down))
19429 ((and (not org-support-shift-select) (org-at-item-p))
19430 (call-interactively 'org-next-item))
19431 ((org-clocktable-try-shift 'down arg))
19432 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19433 (org-support-shift-select
19434 (org-call-for-shift-select 'next-line))
19435 (t (org-shiftselect-error))))
19437 (defun org-shiftright (&optional arg)
19438 "Cycle the thing at point or in the current line, depending on context.
19439 Depending on context, this does one of the following:
19441 - switch a timestamp at point one day into the future
19442 - on a headline, switch to the next TODO keyword.
19443 - on an item, switch entire list to the next bullet type
19444 - on a property line, switch to the next allowed value
19445 - on a clocktable definition line, move time block into the future"
19446 (interactive "P")
19447 (cond
19448 ((run-hook-with-args-until-success 'org-shiftright-hook))
19449 ((and org-support-shift-select (org-region-active-p))
19450 (org-call-for-shift-select 'forward-char))
19451 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19452 ((and (not (eq org-support-shift-select 'always))
19453 (org-at-heading-p))
19454 (let ((org-inhibit-logging
19455 (not org-treat-S-cursor-todo-selection-as-state-change))
19456 (org-inhibit-blocking
19457 (not org-treat-S-cursor-todo-selection-as-state-change)))
19458 (org-call-with-arg 'org-todo 'right)))
19459 ((or (and org-support-shift-select
19460 (not (eq org-support-shift-select 'always))
19461 (org-at-item-bullet-p))
19462 (and (not org-support-shift-select) (org-at-item-p)))
19463 (org-call-with-arg 'org-cycle-list-bullet nil))
19464 ((and (not (eq org-support-shift-select 'always))
19465 (org-at-property-p))
19466 (call-interactively 'org-property-next-allowed-value))
19467 ((org-clocktable-try-shift 'right arg))
19468 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19469 (org-support-shift-select
19470 (org-call-for-shift-select 'forward-char))
19471 (t (org-shiftselect-error))))
19473 (defun org-shiftleft (&optional arg)
19474 "Cycle the thing at point or in the current line, depending on context.
19475 Depending on context, this does one of the following:
19477 - switch a timestamp at point one day into the past
19478 - on a headline, switch to the previous TODO keyword.
19479 - on an item, switch entire list to the previous bullet type
19480 - on a property line, switch to the previous allowed value
19481 - on a clocktable definition line, move time block into the past"
19482 (interactive "P")
19483 (cond
19484 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19485 ((and org-support-shift-select (org-region-active-p))
19486 (org-call-for-shift-select 'backward-char))
19487 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19488 ((and (not (eq org-support-shift-select 'always))
19489 (org-at-heading-p))
19490 (let ((org-inhibit-logging
19491 (not org-treat-S-cursor-todo-selection-as-state-change))
19492 (org-inhibit-blocking
19493 (not org-treat-S-cursor-todo-selection-as-state-change)))
19494 (org-call-with-arg 'org-todo 'left)))
19495 ((or (and org-support-shift-select
19496 (not (eq org-support-shift-select 'always))
19497 (org-at-item-bullet-p))
19498 (and (not org-support-shift-select) (org-at-item-p)))
19499 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19500 ((and (not (eq org-support-shift-select 'always))
19501 (org-at-property-p))
19502 (call-interactively 'org-property-previous-allowed-value))
19503 ((org-clocktable-try-shift 'left arg))
19504 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19505 (org-support-shift-select
19506 (org-call-for-shift-select 'backward-char))
19507 (t (org-shiftselect-error))))
19509 (defun org-shiftcontrolright ()
19510 "Switch to next TODO set."
19511 (interactive)
19512 (cond
19513 ((and org-support-shift-select (org-region-active-p))
19514 (org-call-for-shift-select 'forward-word))
19515 ((and (not (eq org-support-shift-select 'always))
19516 (org-at-heading-p))
19517 (org-call-with-arg 'org-todo 'nextset))
19518 (org-support-shift-select
19519 (org-call-for-shift-select 'forward-word))
19520 (t (org-shiftselect-error))))
19522 (defun org-shiftcontrolleft ()
19523 "Switch to previous TODO set."
19524 (interactive)
19525 (cond
19526 ((and org-support-shift-select (org-region-active-p))
19527 (org-call-for-shift-select 'backward-word))
19528 ((and (not (eq org-support-shift-select 'always))
19529 (org-at-heading-p))
19530 (org-call-with-arg 'org-todo 'previousset))
19531 (org-support-shift-select
19532 (org-call-for-shift-select 'backward-word))
19533 (t (org-shiftselect-error))))
19535 (defun org-shiftcontrolup (&optional n)
19536 "Change timestamps synchronously up in CLOCK log lines.
19537 Optional argument N tells to change by that many units."
19538 (interactive "P")
19539 (cond ((and (not org-support-shift-select)
19540 (org-at-clock-log-p)
19541 (org-at-timestamp-p t))
19542 (org-clock-timestamps-up n))
19543 (t (org-shiftselect-error))))
19545 (defun org-shiftcontroldown (&optional n)
19546 "Change timestamps synchronously down in CLOCK log lines.
19547 Optional argument N tells to change by that many units."
19548 (interactive "P")
19549 (cond ((and (not org-support-shift-select)
19550 (org-at-clock-log-p)
19551 (org-at-timestamp-p t))
19552 (org-clock-timestamps-down n))
19553 (t (org-shiftselect-error))))
19555 (defun org-ctrl-c-ret ()
19556 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19557 (interactive)
19558 (cond
19559 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19560 (t (call-interactively 'org-insert-heading))))
19562 (defun org-find-visible ()
19563 (let ((s (point)))
19564 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19565 (get-char-property s 'invisible)))
19567 (defun org-find-invisible ()
19568 (let ((s (point)))
19569 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19570 (not (get-char-property s 'invisible))))
19573 (defun org-copy-visible (beg end)
19574 "Copy the visible parts of the region."
19575 (interactive "r")
19576 (let (snippets s)
19577 (save-excursion
19578 (save-restriction
19579 (narrow-to-region beg end)
19580 (setq s (goto-char (point-min)))
19581 (while (not (= (point) (point-max)))
19582 (goto-char (org-find-invisible))
19583 (push (buffer-substring s (point)) snippets)
19584 (setq s (goto-char (org-find-visible))))))
19585 (kill-new (apply 'concat (nreverse snippets)))))
19587 (defun org-copy-special ()
19588 "Copy region in table or copy current subtree.
19589 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19590 See the individual commands for more information."
19591 (interactive)
19592 (call-interactively
19593 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19595 (defun org-cut-special ()
19596 "Cut region in table or cut current subtree.
19597 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19598 See the individual commands for more information."
19599 (interactive)
19600 (call-interactively
19601 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19603 (defun org-paste-special (arg)
19604 "Paste rectangular region into table, or past subtree relative to level.
19605 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19606 See the individual commands for more information."
19607 (interactive "P")
19608 (if (org-at-table-p)
19609 (org-table-paste-rectangle)
19610 (org-paste-subtree arg)))
19612 (defsubst org-in-fixed-width-region-p ()
19613 "Is point in a fixed-width region?"
19614 (save-match-data
19615 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19617 (defun org-edit-special (&optional arg)
19618 "Call a special editor for the element at point.
19619 When at a table, call the formula editor with `org-table-edit-formulas'.
19620 When in a source code block, call `org-edit-src-code'.
19621 When in a fixed-width region, call `org-edit-fixed-width-region'.
19622 When at an #+INCLUDE keyword, visit the included file.
19623 On a link, call `ffap' to visit the link at point.
19624 Otherwise, return a user error."
19625 (interactive)
19626 (let ((element (org-element-at-point)))
19627 (assert (not buffer-read-only) nil
19628 "Buffer is read-only: %s" (buffer-name))
19629 (case (org-element-type element)
19630 (src-block
19631 (if (not arg) (org-edit-src-code)
19632 (let* ((info (org-babel-get-src-block-info))
19633 (lang (nth 0 info))
19634 (params (nth 2 info))
19635 (session (cdr (assq :session params))))
19636 (if (not session) (org-edit-src-code)
19637 ;; At a src-block with a session and function called with
19638 ;; an ARG: switch to the buffer related to the inferior
19639 ;; process.
19640 (funcall (intern (concat "org-babel-prep-session:" lang))
19641 session params)))))
19642 (keyword
19643 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19644 (find-file
19645 (org-remove-double-quotes
19646 (car (org-split-string (org-element-property :value element)))))
19647 (user-error "No special environment to edit here")))
19648 (table
19649 (if (eq (org-element-property :type element) 'table.el)
19650 (org-edit-src-code)
19651 (call-interactively 'org-table-edit-formulas)))
19652 ;; Only Org tables contain `table-row' type elements.
19653 (table-row (call-interactively 'org-table-edit-formulas))
19654 ((example-block export-block) (org-edit-src-code))
19655 (fixed-width (org-edit-fixed-width-region))
19656 (otherwise
19657 ;; No notable element at point. Though, we may be at a link,
19658 ;; which is an object. Thus, scan deeper.
19659 (if (eq (org-element-type (org-element-context element)) 'link)
19660 (call-interactively 'ffap)
19661 (user-error "No special environment to edit here"))))))
19663 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19664 (defun org-ctrl-c-ctrl-c (&optional arg)
19665 "Set tags in headline, or update according to changed information at point.
19667 This command does many different things, depending on context:
19669 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19670 this is what we do.
19672 - If the cursor is on a statistics cookie, update it.
19674 - If the cursor is in a headline, prompt for tags and insert them
19675 into the current line, aligned to `org-tags-column'. When called
19676 with prefix arg, realign all tags in the current buffer.
19678 - If the cursor is in one of the special #+KEYWORD lines, this
19679 triggers scanning the buffer for these lines and updating the
19680 information.
19682 - If the cursor is inside a table, realign the table. This command
19683 works even if the automatic table editor has been turned off.
19685 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19686 the entire table.
19688 - If the cursor is at a footnote reference or definition, jump to
19689 the corresponding definition or references, respectively.
19691 - If the cursor is a the beginning of a dynamic block, update it.
19693 - If the current buffer is a capture buffer, close note and file it.
19695 - If the cursor is on a <<<target>>>, update radio targets and
19696 corresponding links in this buffer.
19698 - If the cursor is on a numbered item in a plain list, renumber the
19699 ordered list.
19701 - If the cursor is on a checkbox, toggle it.
19703 - If the cursor is on a code block, evaluate it. The variable
19704 `org-confirm-babel-evaluate' can be used to control prompting
19705 before code block evaluation, by default every code block
19706 evaluation requires confirmation. Code block evaluation can be
19707 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19708 (interactive "P")
19709 (cond
19710 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19711 org-occur-highlights
19712 org-latex-fragment-image-overlays)
19713 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19714 (org-remove-occur-highlights)
19715 (org-remove-latex-fragment-image-overlays)
19716 (message "Temporary highlights/overlays removed from current buffer"))
19717 ((and (local-variable-p 'org-finish-function (current-buffer))
19718 (fboundp org-finish-function))
19719 (funcall org-finish-function))
19720 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19722 (let* ((context (org-element-context)) (type (org-element-type context)))
19723 ;; Test if point is within a blank line.
19724 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19725 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19726 (user-error "C-c C-c can do nothing useful at this location"))
19727 ;; For convenience: at the first line of a paragraph on the
19728 ;; same line as an item, apply function on that item instead.
19729 (when (eq type 'paragraph)
19730 (let ((parent (org-element-property :parent context)))
19731 (when (and (eq (org-element-type parent) 'item)
19732 (= (point-at-bol) (org-element-property :begin parent)))
19733 (setq context parent type 'item))))
19734 ;; Act according to type of element or object at point.
19735 (case type
19736 (clock (org-clock-update-time-maybe))
19737 (dynamic-block
19738 (save-excursion
19739 (goto-char (org-element-property :post-affiliated context))
19740 (org-update-dblock)))
19741 (footnote-definition
19742 (goto-char (org-element-property :post-affiliated context))
19743 (call-interactively 'org-footnote-action))
19744 (footnote-reference (call-interactively 'org-footnote-action))
19745 ((headline inlinetask)
19746 (save-excursion (goto-char (org-element-property :begin context))
19747 (call-interactively 'org-set-tags)))
19748 (item
19749 ;; At an item: a double C-u set checkbox to "[-]"
19750 ;; unconditionally, whereas a single one will toggle its
19751 ;; presence. Without an universal argument, if the item
19752 ;; has a checkbox, toggle it. Otherwise repair the list.
19753 (let* ((box (org-element-property :checkbox context))
19754 (struct (org-element-property :structure context))
19755 (old-struct (copy-tree struct))
19756 (parents (org-list-parents-alist struct))
19757 (prevs (org-list-prevs-alist struct))
19758 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19759 (org-list-set-checkbox
19760 (org-element-property :begin context) struct
19761 (cond ((equal arg '(16)) "[-]")
19762 ((and (not box) (equal arg '(4))) "[ ]")
19763 ((or (not box) (equal arg '(4))) nil)
19764 ((eq box 'on) "[ ]")
19765 (t "[X]")))
19766 ;; Mimic `org-list-write-struct' but with grabbing
19767 ;; a return value from `org-list-struct-fix-box'.
19768 (org-list-struct-fix-ind struct parents 2)
19769 (org-list-struct-fix-item-end struct)
19770 (org-list-struct-fix-bul struct prevs)
19771 (org-list-struct-fix-ind struct parents)
19772 (let ((block-item
19773 (org-list-struct-fix-box struct parents prevs orderedp)))
19774 (if (and box (equal struct old-struct))
19775 (if (equal arg '(16))
19776 (message "Checkboxes already reset")
19777 (user-error "Cannot toggle this checkbox: %s"
19778 (if (eq box 'on)
19779 "all subitems checked"
19780 "unchecked subitems")))
19781 (org-list-struct-apply-struct struct old-struct)
19782 (org-update-checkbox-count-maybe))
19783 (when block-item
19784 (message "Checkboxes were removed due to empty box at line %d"
19785 (org-current-line block-item))))))
19786 (keyword
19787 (let ((org-inhibit-startup-visibility-stuff t)
19788 (org-startup-align-all-tables nil))
19789 (when (boundp 'org-table-coordinate-overlays)
19790 (mapc 'delete-overlay org-table-coordinate-overlays)
19791 (setq org-table-coordinate-overlays nil))
19792 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19793 (message "Local setup has been refreshed"))
19794 (plain-list
19795 ;; At a plain list, with a double C-u argument, set
19796 ;; checkboxes of each item to "[-]", whereas a single one
19797 ;; will toggle their presence according to the state of the
19798 ;; first item in the list. Without an argument, repair the
19799 ;; list.
19800 (let* ((begin (org-element-property :contents-begin context))
19801 (struct (org-element-property :structure context))
19802 (old-struct (copy-tree struct))
19803 (first-box (save-excursion
19804 (goto-char begin)
19805 (looking-at org-list-full-item-re)
19806 (match-string-no-properties 3)))
19807 (new-box (cond ((equal arg '(16)) "[-]")
19808 ((equal arg '(4)) (unless first-box "[ ]"))
19809 ((equal first-box "[X]") "[ ]")
19810 (t "[X]"))))
19811 (cond
19812 (arg
19813 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19814 (org-list-get-all-items
19815 begin struct (org-list-prevs-alist struct))))
19816 ((and first-box (eq (point) begin))
19817 ;; For convenience, when point is at bol on the first
19818 ;; item of the list and no argument is provided, simply
19819 ;; toggle checkbox of that item, if any.
19820 (org-list-set-checkbox begin struct new-box)))
19821 (org-list-write-struct
19822 struct (org-list-parents-alist struct) old-struct)
19823 (org-update-checkbox-count-maybe)
19824 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19825 ((property-drawer node-property)
19826 (call-interactively 'org-property-action))
19827 ((radio-target target)
19828 (call-interactively 'org-update-radio-target-regexp))
19829 (statistics-cookie
19830 (call-interactively 'org-update-statistics-cookies))
19831 ((table table-cell table-row)
19832 ;; At a table, recalculate every field and align it. Also
19833 ;; send the table if necessary. If the table has
19834 ;; a `table.el' type, just give up. At a table row or
19835 ;; cell, maybe recalculate line but always align table.
19836 (if (eq (org-element-property :type context) 'table.el)
19837 (message "Use C-c ' to edit table.el tables")
19838 (let ((org-enable-table-editor t))
19839 (if (or (eq type 'table)
19840 ;; Check if point is at a TBLFM line.
19841 (and (eq type 'table-row)
19842 (= (point) (org-element-property :end context))))
19843 (save-excursion
19844 (goto-char (org-element-property :contents-begin context))
19845 (org-call-with-arg 'org-table-recalculate (or arg t))
19846 (orgtbl-send-table 'maybe))
19847 (org-table-maybe-eval-formula)
19848 (cond (arg (call-interactively 'org-table-recalculate))
19849 ((org-table-maybe-recalculate-line))
19850 (t (org-table-align)))))))
19851 (timestamp (org-timestamp-change 0 'day))
19852 (otherwise
19853 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19854 (user-error
19855 "C-c C-c can do nothing useful at this location")))))))))
19857 (defun org-mode-restart ()
19858 "Restart Org-mode, to scan again for special lines.
19859 Also updates the keyword regular expressions."
19860 (interactive)
19861 (org-mode)
19862 (message "Org-mode restarted"))
19864 (defun org-kill-note-or-show-branches ()
19865 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19866 (interactive)
19867 (if (not org-finish-function)
19868 (progn
19869 (hide-subtree)
19870 (call-interactively 'show-branches))
19871 (let ((org-note-abort t))
19872 (funcall org-finish-function))))
19874 (defun org-return (&optional indent)
19875 "Goto next table row or insert a newline.
19876 Calls `org-table-next-row' or `newline', depending on context.
19877 See the individual commands for more information."
19878 (interactive)
19879 (let (org-ts-what)
19880 (cond
19881 ((or (bobp) (org-in-src-block-p))
19882 (if indent (newline-and-indent) (newline)))
19883 ((org-at-table-p)
19884 (org-table-justify-field-maybe)
19885 (call-interactively 'org-table-next-row))
19886 ;; when `newline-and-indent' is called within a list, make sure
19887 ;; text moved stays inside the item.
19888 ((and (org-in-item-p) indent)
19889 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19890 (progn
19891 (save-match-data (newline))
19892 (org-indent-line-to (length (match-string 0))))
19893 (let ((ind (org-get-indentation)))
19894 (newline)
19895 (if (org-looking-back org-list-end-re)
19896 (org-indent-line)
19897 (org-indent-line-to ind)))))
19898 ((and org-return-follows-link
19899 (org-at-timestamp-p t)
19900 (not (eq org-ts-what 'after)))
19901 (org-follow-timestamp-link))
19902 ((and org-return-follows-link
19903 (let ((tprop (get-text-property (point) 'face)))
19904 (or (eq tprop 'org-link)
19905 (and (listp tprop) (memq 'org-link tprop)))))
19906 (call-interactively 'org-open-at-point))
19907 ((and (org-at-heading-p)
19908 (looking-at
19909 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19910 (org-show-entry)
19911 (end-of-line 1)
19912 (newline))
19913 (t (if indent (newline-and-indent) (newline))))))
19915 (defun org-return-indent ()
19916 "Goto next table row or insert a newline and indent.
19917 Calls `org-table-next-row' or `newline-and-indent', depending on
19918 context. See the individual commands for more information."
19919 (interactive)
19920 (org-return t))
19922 (defun org-ctrl-c-star ()
19923 "Compute table, or change heading status of lines.
19924 Calls `org-table-recalculate' or `org-toggle-heading',
19925 depending on context."
19926 (interactive)
19927 (cond
19928 ((org-at-table-p)
19929 (call-interactively 'org-table-recalculate))
19931 ;; Convert all lines in region to list items
19932 (call-interactively 'org-toggle-heading))))
19934 (defun org-ctrl-c-minus ()
19935 "Insert separator line in table or modify bullet status of line.
19936 Also turns a plain line or a region of lines into list items.
19937 Calls `org-table-insert-hline', `org-toggle-item', or
19938 `org-cycle-list-bullet', depending on context."
19939 (interactive)
19940 (cond
19941 ((org-at-table-p)
19942 (call-interactively 'org-table-insert-hline))
19943 ((org-region-active-p)
19944 (call-interactively 'org-toggle-item))
19945 ((org-in-item-p)
19946 (call-interactively 'org-cycle-list-bullet))
19948 (call-interactively 'org-toggle-item))))
19950 (defun org-toggle-item (arg)
19951 "Convert headings or normal lines to items, items to normal lines.
19952 If there is no active region, only the current line is considered.
19954 If the first non blank line in the region is an headline, convert
19955 all headlines to items, shifting text accordingly.
19957 If it is an item, convert all items to normal lines.
19959 If it is normal text, change region into an item. With a prefix
19960 argument ARG, change each line in region into an item."
19961 (interactive "P")
19962 (let ((shift-text
19963 (function
19964 ;; Shift text in current section to IND, from point to END.
19965 ;; The function leaves point to END line.
19966 (lambda (ind end)
19967 (let ((min-i 1000) (end (copy-marker end)))
19968 ;; First determine the minimum indentation (MIN-I) of
19969 ;; the text.
19970 (save-excursion
19971 (catch 'exit
19972 (while (< (point) end)
19973 (let ((i (org-get-indentation)))
19974 (cond
19975 ;; Skip blank lines and inline tasks.
19976 ((looking-at "^[ \t]*$"))
19977 ((looking-at org-outline-regexp-bol))
19978 ;; We can't find less than 0 indentation.
19979 ((zerop i) (throw 'exit (setq min-i 0)))
19980 ((< i min-i) (setq min-i i))))
19981 (forward-line))))
19982 ;; Then indent each line so that a line indented to
19983 ;; MIN-I becomes indented to IND. Ignore blank lines
19984 ;; and inline tasks in the process.
19985 (let ((delta (- ind min-i)))
19986 (while (< (point) end)
19987 (unless (or (looking-at "^[ \t]*$")
19988 (looking-at org-outline-regexp-bol))
19989 (org-indent-line-to (+ (org-get-indentation) delta)))
19990 (forward-line)))))))
19991 (skip-blanks
19992 (function
19993 ;; Return beginning of first non-blank line, starting from
19994 ;; line at POS.
19995 (lambda (pos)
19996 (save-excursion
19997 (goto-char pos)
19998 (skip-chars-forward " \r\t\n")
19999 (point-at-bol)))))
20000 beg end)
20001 ;; Determine boundaries of changes.
20002 (if (org-region-active-p)
20003 (setq beg (funcall skip-blanks (region-beginning))
20004 end (copy-marker (region-end)))
20005 (setq beg (funcall skip-blanks (point-at-bol))
20006 end (copy-marker (point-at-eol))))
20007 ;; Depending on the starting line, choose an action on the text
20008 ;; between BEG and END.
20009 (org-with-limited-levels
20010 (save-excursion
20011 (goto-char beg)
20012 (cond
20013 ;; Case 1. Start at an item: de-itemize. Note that it only
20014 ;; happens when a region is active: `org-ctrl-c-minus'
20015 ;; would call `org-cycle-list-bullet' otherwise.
20016 ((org-at-item-p)
20017 (while (< (point) end)
20018 (when (org-at-item-p)
20019 (skip-chars-forward " \t")
20020 (delete-region (point) (match-end 0)))
20021 (forward-line)))
20022 ;; Case 2. Start at an heading: convert to items.
20023 ((org-at-heading-p)
20024 (let* ((bul (org-list-bullet-string "-"))
20025 (bul-len (length bul))
20026 ;; Indentation of the first heading. It should be
20027 ;; relative to the indentation of its parent, if any.
20028 (start-ind (save-excursion
20029 (cond
20030 ((not org-adapt-indentation) 0)
20031 ((not (outline-previous-heading)) 0)
20032 (t (length (match-string 0))))))
20033 ;; Level of first heading. Further headings will be
20034 ;; compared to it to determine hierarchy in the list.
20035 (ref-level (org-reduced-level (org-outline-level))))
20036 (while (< (point) end)
20037 (let* ((level (org-reduced-level (org-outline-level)))
20038 (delta (max 0 (- level ref-level))))
20039 ;; If current headline is less indented than the first
20040 ;; one, set it as reference, in order to preserve
20041 ;; subtrees.
20042 (when (< level ref-level) (setq ref-level level))
20043 (replace-match bul t t)
20044 (org-indent-line-to (+ start-ind (* delta bul-len)))
20045 ;; Ensure all text down to END (or SECTION-END) belongs
20046 ;; to the newly created item.
20047 (let ((section-end (save-excursion
20048 (or (outline-next-heading) (point)))))
20049 (forward-line)
20050 (funcall shift-text
20051 (+ start-ind (* (1+ delta) bul-len))
20052 (min end section-end)))))))
20053 ;; Case 3. Normal line with ARG: turn each non-item line into
20054 ;; an item.
20055 (arg
20056 (while (< (point) end)
20057 (unless (or (org-at-heading-p) (org-at-item-p))
20058 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20059 (replace-match
20060 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20061 (forward-line)))
20062 ;; Case 4. Normal line without ARG: make the first line of
20063 ;; region an item, and shift indentation of others
20064 ;; lines to set them as item's body.
20065 (t (let* ((bul (org-list-bullet-string "-"))
20066 (bul-len (length bul))
20067 (ref-ind (org-get-indentation)))
20068 (skip-chars-forward " \t")
20069 (insert bul)
20070 (forward-line)
20071 (while (< (point) end)
20072 ;; Ensure that lines less indented than first one
20073 ;; still get included in item body.
20074 (funcall shift-text
20075 (+ ref-ind bul-len)
20076 (min end (save-excursion (or (outline-next-heading)
20077 (point)))))
20078 (forward-line)))))))))
20080 (defun org-toggle-heading (&optional nstars)
20081 "Convert headings to normal text, or items or text to headings.
20082 If there is no active region, only the current line is considered.
20084 With a \\[universal-argument] prefix, convert the whole list at
20085 point into heading.
20087 In a region:
20089 - If the first non blank line is an headline, remove the stars
20090 from all headlines in the region.
20092 - If it is a normal line turn each and every normal line (i.e. not an
20093 heading or an item) in the region into a heading.
20095 - If it is a plain list item, turn all plain list items into headings.
20097 When converting a line into a heading, the number of stars is chosen
20098 such that the lines become children of the current entry. However,
20099 when a prefix argument is given, its value determines the number of
20100 stars to add."
20101 (interactive "P")
20102 (let ((skip-blanks
20103 (function
20104 ;; Return beginning of first non-blank line, starting from
20105 ;; line at POS.
20106 (lambda (pos)
20107 (save-excursion
20108 (goto-char pos)
20109 (while (org-at-comment-p) (forward-line))
20110 (skip-chars-forward " \r\t\n")
20111 (point-at-bol)))))
20112 beg end toggled)
20113 ;; Determine boundaries of changes. If a universal prefix has
20114 ;; been given, put the list in a region. If region ends at a bol,
20115 ;; do not consider the last line to be in the region.
20117 (when (and current-prefix-arg (org-at-item-p))
20118 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20119 (org-mark-element))
20121 (if (org-region-active-p)
20122 (setq beg (funcall skip-blanks (region-beginning))
20123 end (copy-marker (save-excursion
20124 (goto-char (region-end))
20125 (if (bolp) (point) (point-at-eol)))))
20126 (setq beg (funcall skip-blanks (point-at-bol))
20127 end (copy-marker (point-at-eol))))
20128 ;; Ensure inline tasks don't count as headings.
20129 (org-with-limited-levels
20130 (save-excursion
20131 (goto-char beg)
20132 (cond
20133 ;; Case 1. Started at an heading: de-star headings.
20134 ((org-at-heading-p)
20135 (while (< (point) end)
20136 (when (org-at-heading-p t)
20137 (looking-at org-outline-regexp) (replace-match "")
20138 (setq toggled t))
20139 (forward-line)))
20140 ;; Case 2. Started at an item: change items into headlines.
20141 ;; One star will be added by `org-list-to-subtree'.
20142 ((org-at-item-p)
20143 (let* ((stars (make-string
20144 (if nstars
20145 ;; subtract the star that will be added again by
20146 ;; `org-list-to-subtree'
20147 (1- (prefix-numeric-value current-prefix-arg))
20148 (or (org-current-level) 0))
20149 ?*))
20150 (add-stars
20151 (cond (nstars "") ; stars from prefix only
20152 ((equal stars "") "") ; before first heading
20153 (org-odd-levels-only "*") ; inside heading, odd
20154 (t "")))) ; inside heading, oddeven
20155 (while (< (point) end)
20156 (when (org-at-item-p)
20157 ;; Pay attention to cases when region ends before list.
20158 (let* ((struct (org-list-struct))
20159 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20160 (save-restriction
20161 (narrow-to-region (point) list-end)
20162 (insert
20163 (org-list-to-subtree
20164 (org-list-parse-list t)
20165 '(:istart (concat stars add-stars (funcall get-stars depth))
20166 :icount (concat stars add-stars (funcall get-stars depth)))))))
20167 (setq toggled t))
20168 (forward-line))))
20169 ;; Case 3. Started at normal text: make every line an heading,
20170 ;; skipping headlines and items.
20171 (t (let* ((stars (make-string
20172 (if nstars
20173 (prefix-numeric-value current-prefix-arg)
20174 (or (org-current-level) 0))
20175 ?*))
20176 (add-stars
20177 (cond (nstars "") ; stars from prefix only
20178 ((equal stars "") "*") ; before first heading
20179 (org-odd-levels-only "**") ; inside heading, odd
20180 (t "*"))) ; inside heading, oddeven
20181 (rpl (concat stars add-stars " ")))
20182 (while (< (point) end)
20183 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20184 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20185 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20186 (forward-line)))))))
20187 (unless toggled (message "Cannot toggle heading from here"))))
20189 (defun org-meta-return (&optional arg)
20190 "Insert a new heading or wrap a region in a table.
20191 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20192 See the individual commands for more information."
20193 (interactive "P")
20194 (cond
20195 ((run-hook-with-args-until-success 'org-metareturn-hook))
20196 ((or (org-at-drawer-p) (org-at-property-p))
20197 (newline-and-indent))
20198 ((org-at-table-p)
20199 (call-interactively 'org-table-wrap-region))
20200 (t (call-interactively 'org-insert-heading))))
20202 ;;; Menu entries
20204 (defsubst org-in-subtree-not-table-p ()
20205 "Are we in a subtree and not in a table?"
20206 (and (not (org-before-first-heading-p))
20207 (not (org-at-table-p))))
20209 ;; Define the Org-mode menus
20210 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20211 '("Tbl"
20212 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20213 ["Next Field" org-cycle (org-at-table-p)]
20214 ["Previous Field" org-shifttab (org-at-table-p)]
20215 ["Next Row" org-return (org-at-table-p)]
20216 "--"
20217 ["Blank Field" org-table-blank-field (org-at-table-p)]
20218 ["Edit Field" org-table-edit-field (org-at-table-p)]
20219 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20220 "--"
20221 ("Column"
20222 ["Move Column Left" org-metaleft (org-at-table-p)]
20223 ["Move Column Right" org-metaright (org-at-table-p)]
20224 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20225 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20226 ("Row"
20227 ["Move Row Up" org-metaup (org-at-table-p)]
20228 ["Move Row Down" org-metadown (org-at-table-p)]
20229 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20230 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20231 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20232 "--"
20233 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20234 ("Rectangle"
20235 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20236 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20237 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20238 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20239 "--"
20240 ("Calculate"
20241 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20242 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20243 ["Edit Formulas" org-edit-special (org-at-table-p)]
20244 "--"
20245 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20246 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20247 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20248 "--"
20249 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20250 "--"
20251 ["Sum Column/Rectangle" org-table-sum
20252 (or (org-at-table-p) (org-region-active-p))]
20253 ["Which Column?" org-table-current-column (org-at-table-p)])
20254 ["Debug Formulas"
20255 org-table-toggle-formula-debugger
20256 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20257 ["Show Col/Row Numbers"
20258 org-table-toggle-coordinate-overlays
20259 :style toggle
20260 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20261 "--"
20262 ["Create" org-table-create (and (not (org-at-table-p))
20263 org-enable-table-editor)]
20264 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20265 ["Import from File" org-table-import (not (org-at-table-p))]
20266 ["Export to File" org-table-export (org-at-table-p)]
20267 "--"
20268 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20270 (easy-menu-define org-org-menu org-mode-map "Org menu"
20271 '("Org"
20272 ("Show/Hide"
20273 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20274 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20275 ["Sparse Tree..." org-sparse-tree t]
20276 ["Reveal Context" org-reveal t]
20277 ["Show All" show-all t]
20278 "--"
20279 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20280 "--"
20281 ["New Heading" org-insert-heading t]
20282 ("Navigate Headings"
20283 ["Up" outline-up-heading t]
20284 ["Next" outline-next-visible-heading t]
20285 ["Previous" outline-previous-visible-heading t]
20286 ["Next Same Level" outline-forward-same-level t]
20287 ["Previous Same Level" outline-backward-same-level t]
20288 "--"
20289 ["Jump" org-goto t])
20290 ("Edit Structure"
20291 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20292 "--"
20293 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20294 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20295 "--"
20296 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20297 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20298 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20299 "--"
20300 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20301 "--"
20302 ["Copy visible text" org-copy-visible t]
20303 "--"
20304 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20305 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20306 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20307 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20308 "--"
20309 ["Sort Region/Children" org-sort t]
20310 "--"
20311 ["Convert to odd levels" org-convert-to-odd-levels t]
20312 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20313 ("Editing"
20314 ["Emphasis..." org-emphasize t]
20315 ["Edit Source Example" org-edit-special t]
20316 "--"
20317 ["Footnote new/jump" org-footnote-action t]
20318 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20319 ("Archive"
20320 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20321 "--"
20322 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20323 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20324 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20326 "--"
20327 ("Hyperlinks"
20328 ["Store Link (Global)" org-store-link t]
20329 ["Find existing link to here" org-occur-link-in-agenda-files t]
20330 ["Insert Link" org-insert-link t]
20331 ["Follow Link" org-open-at-point t]
20332 "--"
20333 ["Next link" org-next-link t]
20334 ["Previous link" org-previous-link t]
20335 "--"
20336 ["Descriptive Links"
20337 org-toggle-link-display
20338 :style radio
20339 :selected org-descriptive-links
20341 ["Literal Links"
20342 org-toggle-link-display
20343 :style radio
20344 :selected (not org-descriptive-links)])
20345 "--"
20346 ("TODO Lists"
20347 ["TODO/DONE/-" org-todo t]
20348 ("Select keyword"
20349 ["Next keyword" org-shiftright (org-at-heading-p)]
20350 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20351 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20352 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20353 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20354 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20355 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20356 "--"
20357 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20358 :selected org-enforce-todo-dependencies :style toggle :active t]
20359 "Settings for tree at point"
20360 ["Do Children sequentially" org-toggle-ordered-property :style radio
20361 :selected (org-entry-get nil "ORDERED")
20362 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20363 ["Do Children parallel" org-toggle-ordered-property :style radio
20364 :selected (not (org-entry-get nil "ORDERED"))
20365 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20366 "--"
20367 ["Set Priority" org-priority t]
20368 ["Priority Up" org-shiftup t]
20369 ["Priority Down" org-shiftdown t]
20370 "--"
20371 ["Get news from all feeds" org-feed-update-all t]
20372 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20373 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20374 ("TAGS and Properties"
20375 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20376 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20377 "--"
20378 ["Set property" org-set-property (not (org-before-first-heading-p))]
20379 ["Column view of properties" org-columns t]
20380 ["Insert Column View DBlock" org-insert-columns-dblock t])
20381 ("Dates and Scheduling"
20382 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20383 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20384 ("Change Date"
20385 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20386 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20387 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20388 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20389 ["Compute Time Range" org-evaluate-time-range t]
20390 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20391 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20392 "--"
20393 ["Custom time format" org-toggle-time-stamp-overlays
20394 :style radio :selected org-display-custom-times]
20395 "--"
20396 ["Goto Calendar" org-goto-calendar t]
20397 ["Date from Calendar" org-date-from-calendar t]
20398 "--"
20399 ["Start/Restart Timer" org-timer-start t]
20400 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20401 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20402 ["Insert Timer String" org-timer t]
20403 ["Insert Timer Item" org-timer-item t])
20404 ("Logging work"
20405 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20406 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20407 ["Clock out" org-clock-out t]
20408 ["Clock cancel" org-clock-cancel t]
20409 "--"
20410 ["Mark as default task" org-clock-mark-default-task t]
20411 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20412 ["Goto running clock" org-clock-goto t]
20413 "--"
20414 ["Display times" org-clock-display t]
20415 ["Create clock table" org-clock-report t]
20416 "--"
20417 ["Record DONE time"
20418 (progn (setq org-log-done (not org-log-done))
20419 (message "Switching to %s will %s record a timestamp"
20420 (car org-done-keywords)
20421 (if org-log-done "automatically" "not")))
20422 :style toggle :selected org-log-done])
20423 "--"
20424 ["Agenda Command..." org-agenda t]
20425 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20426 ("File List for Agenda")
20427 ("Special views current file"
20428 ["TODO Tree" org-show-todo-tree t]
20429 ["Check Deadlines" org-check-deadlines t]
20430 ["Timeline" org-timeline t]
20431 ["Tags/Property tree" org-match-sparse-tree t])
20432 "--"
20433 ["Export/Publish..." org-export-dispatch t]
20434 ("LaTeX"
20435 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20436 :selected org-cdlatex-mode]
20437 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20438 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20439 ["Modify math symbol" org-cdlatex-math-modify
20440 (org-inside-LaTeX-fragment-p)]
20441 ["Insert citation" org-reftex-citation t]
20442 "--"
20443 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20444 "--"
20445 ("MobileOrg"
20446 ["Push Files and Views" org-mobile-push t]
20447 ["Get Captured and Flagged" org-mobile-pull t]
20448 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20449 "--"
20450 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20451 "--"
20452 ("Documentation"
20453 ["Show Version" org-version t]
20454 ["Info Documentation" org-info t])
20455 ("Customize"
20456 ["Browse Org Group" org-customize t]
20457 "--"
20458 ["Expand This Menu" org-create-customize-menu
20459 (fboundp 'customize-menu-create)])
20460 ["Send bug report" org-submit-bug-report t]
20461 "--"
20462 ("Refresh/Reload"
20463 ["Refresh setup current buffer" org-mode-restart t]
20464 ["Reload Org (after update)" org-reload t]
20465 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20468 (defun org-info (&optional node)
20469 "Read documentation for Org-mode in the info system.
20470 With optional NODE, go directly to that node."
20471 (interactive)
20472 (info (format "(org)%s" (or node ""))))
20474 ;;;###autoload
20475 (defun org-submit-bug-report ()
20476 "Submit a bug report on Org-mode via mail.
20478 Don't hesitate to report any problems or inaccurate documentation.
20480 If you don't have setup sending mail from (X)Emacs, please copy the
20481 output buffer into your mail program, as it gives us important
20482 information about your Org-mode version and configuration."
20483 (interactive)
20484 (require 'reporter)
20485 (org-load-modules-maybe)
20486 (org-require-autoloaded-modules)
20487 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20488 (reporter-submit-bug-report
20489 "emacs-orgmode@gnu.org"
20490 (org-version nil 'full)
20491 (let (list)
20492 (save-window-excursion
20493 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20494 (delete-other-windows)
20495 (erase-buffer)
20496 (insert "You are about to submit a bug report to the Org-mode mailing list.
20498 We would like to add your full Org-mode and Outline configuration to the
20499 bug report. This greatly simplifies the work of the maintainer and
20500 other experts on the mailing list.
20502 HOWEVER, some variables you have customized may contain private
20503 information. The names of customers, colleagues, or friends, might
20504 appear in the form of file names, tags, todo states, or search strings.
20505 If you answer yes to the prompt, you might want to check and remove
20506 such private information before sending the email.")
20507 (add-text-properties (point-min) (point-max) '(face org-warning))
20508 (when (yes-or-no-p "Include your Org-mode configuration ")
20509 (mapatoms
20510 (lambda (v)
20511 (and (boundp v)
20512 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20513 (or (and (symbol-value v)
20514 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20515 (and
20516 (get v 'custom-type) (get v 'standard-value)
20517 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20518 (push v list)))))
20519 (kill-buffer (get-buffer "*Warn about privacy*"))
20520 list))
20521 nil nil
20522 "Remember to cover the basics, that is, what you expected to happen and
20523 what in fact did happen. You don't know how to make a good report? See
20525 http://orgmode.org/manual/Feedback.html#Feedback
20527 Your bug report will be posted to the Org-mode mailing list.
20528 ------------------------------------------------------------------------")
20529 (save-excursion
20530 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20531 (replace-match "\\1Bug: \\3 [\\2]")))))
20534 (defun org-install-agenda-files-menu ()
20535 (let ((bl (buffer-list)))
20536 (save-excursion
20537 (while bl
20538 (set-buffer (pop bl))
20539 (if (derived-mode-p 'org-mode) (setq bl nil)))
20540 (when (derived-mode-p 'org-mode)
20541 (easy-menu-change
20542 '("Org") "File List for Agenda"
20543 (append
20544 (list
20545 ["Edit File List" (org-edit-agenda-file-list) t]
20546 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20547 ["Remove Current File from List" org-remove-file t]
20548 ["Cycle through agenda files" org-cycle-agenda-files t]
20549 ["Occur in all agenda files" org-occur-in-agenda-files t]
20550 "--")
20551 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20553 ;;;; Documentation
20555 (defun org-require-autoloaded-modules ()
20556 (interactive)
20557 (mapc 'require
20558 '(org-agenda org-archive org-attach org-clock org-colview org-id
20559 org-remember org-table org-timer)))
20561 ;;;###autoload
20562 (defun org-reload (&optional uncompiled)
20563 "Reload all org lisp files.
20564 With prefix arg UNCOMPILED, load the uncompiled versions."
20565 (interactive "P")
20566 (require 'loadhist)
20567 (let* ((org-dir (org-find-library-dir "org"))
20568 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20569 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20570 (remove-re (mapconcat 'identity
20571 (mapcar (lambda (f) (concat "^" f "$"))
20572 (list (if (featurep 'xemacs)
20573 "org-colview"
20574 "org-colview-xemacs")
20575 "org" "org-loaddefs" "org-version"))
20576 "\\|"))
20577 (feats (delete-dups
20578 (mapcar 'file-name-sans-extension
20579 (mapcar 'file-name-nondirectory
20580 (delq nil
20581 (mapcar 'feature-file
20582 features))))))
20583 (lfeat (append
20584 (sort
20585 (setq feats
20586 (delq nil (mapcar
20587 (lambda (f)
20588 (if (and (string-match feature-re f)
20589 (not (string-match remove-re f)))
20590 f nil))
20591 feats)))
20592 'string-lessp)
20593 (list "org-version" "org")))
20594 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20595 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20596 load-uncore load-misses)
20597 (setq load-misses
20598 (delq 't
20599 (mapcar (lambda (f)
20600 (or (org-load-noerror-mustsuffix (concat org-dir f))
20601 (and (string= org-dir contrib-dir)
20602 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20603 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20604 (add-to-list 'load-uncore f 'append)
20607 lfeat)))
20608 (if load-uncore
20609 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20610 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20611 (if load-misses
20612 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20613 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20614 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20616 ;;;###autoload
20617 (defun org-customize ()
20618 "Call the customize function with org as argument."
20619 (interactive)
20620 (org-load-modules-maybe)
20621 (org-require-autoloaded-modules)
20622 (customize-browse 'org))
20624 (defun org-create-customize-menu ()
20625 "Create a full customization menu for Org-mode, insert it into the menu."
20626 (interactive)
20627 (org-load-modules-maybe)
20628 (org-require-autoloaded-modules)
20629 (if (fboundp 'customize-menu-create)
20630 (progn
20631 (easy-menu-change
20632 '("Org") "Customize"
20633 `(["Browse Org group" org-customize t]
20634 "--"
20635 ,(customize-menu-create 'org)
20636 ["Set" Custom-set t]
20637 ["Save" Custom-save t]
20638 ["Reset to Current" Custom-reset-current t]
20639 ["Reset to Saved" Custom-reset-saved t]
20640 ["Reset to Standard Settings" Custom-reset-standard t]))
20641 (message "\"Org\"-menu now contains full customization menu"))
20642 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20644 ;;;; Miscellaneous stuff
20646 ;;; Generally useful functions
20648 (defun org-get-at-bol (property)
20649 "Get text property PROPERTY at beginning of line."
20650 (get-text-property (point-at-bol) property))
20652 (defun org-find-text-property-in-string (prop s)
20653 "Return the first non-nil value of property PROP in string S."
20654 (or (get-text-property 0 prop s)
20655 (get-text-property (or (next-single-property-change 0 prop s) 0)
20656 prop s)))
20658 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20659 "Display the given MESSAGE as a warning."
20660 (if (fboundp 'display-warning)
20661 (display-warning 'org message
20662 (if (featurep 'xemacs) 'warning :warning))
20663 (let ((buf (get-buffer-create "*Org warnings*")))
20664 (with-current-buffer buf
20665 (goto-char (point-max))
20666 (insert "Warning (Org): " message)
20667 (unless (bolp)
20668 (newline)))
20669 (display-buffer buf)
20670 (sit-for 0))))
20672 (defun org-eval (form)
20673 "Eval FORM and return result."
20674 (condition-case error
20675 (eval form)
20676 (error (format "%%![Error: %s]" error))))
20678 (defun org-in-clocktable-p ()
20679 "Check if the cursor is in a clocktable."
20680 (let ((pos (point)) start)
20681 (save-excursion
20682 (end-of-line 1)
20683 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20684 (setq start (match-beginning 0))
20685 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20686 (>= (match-end 0) pos)
20687 start))))
20689 (defun org-in-commented-line ()
20690 "Is point in a line starting with `#'?"
20691 (equal (char-after (point-at-bol)) ?#))
20693 (defun org-in-indented-comment-line ()
20694 "Is point in a line starting with `#' after some white space?"
20695 (save-excursion
20696 (save-match-data
20697 (goto-char (point-at-bol))
20698 (looking-at "[ \t]*#"))))
20700 (defun org-in-verbatim-emphasis ()
20701 (save-match-data
20702 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20704 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20705 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20706 (if (and marker (marker-buffer marker)
20707 (buffer-live-p (marker-buffer marker)))
20708 (progn
20709 (org-pop-to-buffer-same-window (marker-buffer marker))
20710 (if (or (> marker (point-max)) (< marker (point-min)))
20711 (widen))
20712 (goto-char marker)
20713 (org-show-context 'org-goto))
20714 (if bookmark
20715 (bookmark-jump bookmark)
20716 (error "Cannot find location"))))
20718 (defun org-quote-csv-field (s)
20719 "Quote field for inclusion in CSV material."
20720 (if (string-match "[\",]" s)
20721 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20724 (defun org-force-self-insert (N)
20725 "Needed to enforce self-insert under remapping."
20726 (interactive "p")
20727 (self-insert-command N))
20729 (defun org-string-width (s)
20730 "Compute width of string, ignoring invisible characters.
20731 This ignores character with invisibility property `org-link', and also
20732 characters with property `org-cwidth', because these will become invisible
20733 upon the next fontification round."
20734 (let (b l)
20735 (when (or (eq t buffer-invisibility-spec)
20736 (assq 'org-link buffer-invisibility-spec))
20737 (while (setq b (text-property-any 0 (length s)
20738 'invisible 'org-link s))
20739 (setq s (concat (substring s 0 b)
20740 (substring s (or (next-single-property-change
20741 b 'invisible s) (length s)))))))
20742 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20743 (setq s (concat (substring s 0 b)
20744 (substring s (or (next-single-property-change
20745 b 'org-cwidth s) (length s))))))
20746 (setq l (string-width s) b -1)
20747 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20748 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20751 (defun org-shorten-string (s maxlength)
20752 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20753 If the string is shorter or has length MAXLENGTH, just return the
20754 original string. If it is longer, the functions finds a space in the
20755 string, breaks this string off at that locations and adds three dots
20756 as ellipsis. Including the ellipsis, the string will not be longer
20757 than MAXLENGTH. If finding a good breaking point in the string does
20758 not work, the string is just chopped off in the middle of a word
20759 if necessary."
20760 (if (<= (length s) maxlength)
20762 (let* ((n (max (- maxlength 4) 1))
20763 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20764 (if (string-match re s)
20765 (concat (match-string 1 s) "...")
20766 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20768 (defun org-get-indentation (&optional line)
20769 "Get the indentation of the current line, interpreting tabs.
20770 When LINE is given, assume it represents a line and compute its indentation."
20771 (if line
20772 (if (string-match "^ *" (org-remove-tabs line))
20773 (match-end 0))
20774 (save-excursion
20775 (beginning-of-line 1)
20776 (skip-chars-forward " \t")
20777 (current-column))))
20779 (defun org-get-string-indentation (s)
20780 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20781 (let ((n -1) (i 0) (w tab-width) c)
20782 (catch 'exit
20783 (while (< (setq n (1+ n)) (length s))
20784 (setq c (aref s n))
20785 (cond ((= c ?\ ) (setq i (1+ i)))
20786 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20787 (t (throw 'exit t)))))
20790 (defun org-remove-tabs (s &optional width)
20791 "Replace tabulators in S with spaces.
20792 Assumes that s is a single line, starting in column 0."
20793 (setq width (or width tab-width))
20794 (while (string-match "\t" s)
20795 (setq s (replace-match
20796 (make-string
20797 (- (* width (/ (+ (match-beginning 0) width) width))
20798 (match-beginning 0)) ?\ )
20799 t t s)))
20802 (defun org-fix-indentation (line ind)
20803 "Fix indentation in LINE.
20804 IND is a cons cell with target and minimum indentation.
20805 If the current indentation in LINE is smaller than the minimum,
20806 leave it alone. If it is larger than ind, set it to the target."
20807 (let* ((l (org-remove-tabs line))
20808 (i (org-get-indentation l))
20809 (i1 (car ind)) (i2 (cdr ind)))
20810 (if (>= i i2) (setq l (substring line i2)))
20811 (if (> i1 0)
20812 (concat (make-string i1 ?\ ) l)
20813 l)))
20815 (defun org-remove-indentation (code &optional n)
20816 "Remove the maximum common indentation from the lines in CODE.
20817 N may optionally be the number of spaces to remove."
20818 (with-temp-buffer
20819 (insert code)
20820 (org-do-remove-indentation n)
20821 (buffer-string)))
20823 (defun org-do-remove-indentation (&optional n)
20824 "Remove the maximum common indentation from the buffer."
20825 (untabify (point-min) (point-max))
20826 (let ((min 10000) re)
20827 (if n
20828 (setq min n)
20829 (goto-char (point-min))
20830 (while (re-search-forward "^ *[^ \n]" nil t)
20831 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20832 (unless (or (= min 0) (= min 10000))
20833 (setq re (format "^ \\{%d\\}" min))
20834 (goto-char (point-min))
20835 (while (re-search-forward re nil t)
20836 (replace-match "")
20837 (end-of-line 1))
20838 min)))
20840 (defun org-fill-template (template alist)
20841 "Find each %key of ALIST in TEMPLATE and replace it."
20842 (let ((case-fold-search nil)
20843 entry key value)
20844 (setq alist (sort (copy-sequence alist)
20845 (lambda (a b) (< (length (car a)) (length (car b))))))
20846 (while (setq entry (pop alist))
20847 (setq template
20848 (replace-regexp-in-string
20849 (concat "%" (regexp-quote (car entry)))
20850 (or (cdr entry) "") template t t)))
20851 template))
20853 (defun org-base-buffer (buffer)
20854 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20855 (if (not buffer)
20856 buffer
20857 (or (buffer-base-buffer buffer)
20858 buffer)))
20860 (defun org-trim (s)
20861 "Remove whitespace at beginning and end of string."
20862 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20863 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20866 (defun org-wrap (string &optional width lines)
20867 "Wrap string to either a number of lines, or a width in characters.
20868 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20869 that costs. If there is a word longer than WIDTH, the text is actually
20870 wrapped to the length of that word.
20871 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20872 many lines, whatever width that takes.
20873 The return value is a list of lines, without newlines at the end."
20874 (let* ((words (org-split-string string "[ \t\n]+"))
20875 (maxword (apply 'max (mapcar 'org-string-width words)))
20876 w ll)
20877 (cond (width
20878 (org-do-wrap words (max maxword width)))
20879 (lines
20880 (setq w maxword)
20881 (setq ll (org-do-wrap words maxword))
20882 (if (<= (length ll) lines)
20884 (setq ll words)
20885 (while (> (length ll) lines)
20886 (setq w (1+ w))
20887 (setq ll (org-do-wrap words w)))
20888 ll))
20889 (t (error "Cannot wrap this")))))
20891 (defun org-do-wrap (words width)
20892 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20893 (let (lines line)
20894 (while words
20895 (setq line (pop words))
20896 (while (and words (< (+ (length line) (length (car words))) width))
20897 (setq line (concat line " " (pop words))))
20898 (setq lines (push line lines)))
20899 (nreverse lines)))
20901 (defun org-split-string (string &optional separators)
20902 "Splits STRING into substrings at SEPARATORS.
20903 No empty strings are returned if there are matches at the beginning
20904 and end of string."
20905 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20906 (start 0)
20907 notfirst
20908 (list nil))
20909 (while (and (string-match rexp string
20910 (if (and notfirst
20911 (= start (match-beginning 0))
20912 (< start (length string)))
20913 (1+ start) start))
20914 (< (match-beginning 0) (length string)))
20915 (setq notfirst t)
20916 (or (eq (match-beginning 0) 0)
20917 (and (eq (match-beginning 0) (match-end 0))
20918 (eq (match-beginning 0) start))
20919 (setq list
20920 (cons (substring string start (match-beginning 0))
20921 list)))
20922 (setq start (match-end 0)))
20923 (or (eq start (length string))
20924 (setq list
20925 (cons (substring string start)
20926 list)))
20927 (nreverse list)))
20929 (defun org-quote-vert (s)
20930 "Replace \"|\" with \"\\vert\"."
20931 (while (string-match "|" s)
20932 (setq s (replace-match "\\vert" t t s)))
20935 (defun org-uuidgen-p (s)
20936 "Is S an ID created by UUIDGEN?"
20937 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20939 (defun org-in-src-block-p (&optional inside)
20940 "Whether point is in a code source block.
20941 When INSIDE is non-nil, don't consider we are within a src block
20942 when point is at #+BEGIN_SRC or #+END_SRC."
20943 (let ((case-fold-search t) ov)
20944 (or (and (setq ov (overlays-at (point)))
20945 (memq 'org-block-background
20946 (overlay-properties (car ov))))
20947 (and (not inside)
20948 (save-match-data
20949 (save-excursion
20950 (beginning-of-line)
20951 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20953 (defun org-context ()
20954 "Return a list of contexts of the current cursor position.
20955 If several contexts apply, all are returned.
20956 Each context entry is a list with a symbol naming the context, and
20957 two positions indicating start and end of the context. Possible
20958 contexts are:
20960 :headline anywhere in a headline
20961 :headline-stars on the leading stars in a headline
20962 :todo-keyword on a TODO keyword (including DONE) in a headline
20963 :tags on the TAGS in a headline
20964 :priority on the priority cookie in a headline
20965 :item on the first line of a plain list item
20966 :item-bullet on the bullet/number of a plain list item
20967 :checkbox on the checkbox in a plain list item
20968 :table in an org-mode table
20969 :table-special on a special filed in a table
20970 :table-table in a table.el table
20971 :clocktable in a clocktable
20972 :src-block in a source block
20973 :link on a hyperlink
20974 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20975 :target on a <<target>>
20976 :radio-target on a <<<radio-target>>>
20977 :latex-fragment on a LaTeX fragment
20978 :latex-preview on a LaTeX fragment with overlaid preview image
20980 This function expects the position to be visible because it uses font-lock
20981 faces as a help to recognize the following contexts: :table-special, :link,
20982 and :keyword."
20983 (let* ((f (get-text-property (point) 'face))
20984 (faces (if (listp f) f (list f)))
20985 (case-fold-search t)
20986 (p (point)) clist o)
20987 ;; First the large context
20988 (cond
20989 ((org-at-heading-p t)
20990 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20991 (when (progn
20992 (beginning-of-line 1)
20993 (looking-at org-todo-line-tags-regexp))
20994 (push (org-point-in-group p 1 :headline-stars) clist)
20995 (push (org-point-in-group p 2 :todo-keyword) clist)
20996 (push (org-point-in-group p 4 :tags) clist))
20997 (goto-char p)
20998 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20999 (if (looking-at "\\[#[A-Z0-9]\\]")
21000 (push (org-point-in-group p 0 :priority) clist)))
21002 ((org-at-item-p)
21003 (push (org-point-in-group p 2 :item-bullet) clist)
21004 (push (list :item (point-at-bol)
21005 (save-excursion (org-end-of-item) (point)))
21006 clist)
21007 (and (org-at-item-checkbox-p)
21008 (push (org-point-in-group p 0 :checkbox) clist)))
21010 ((org-at-table-p)
21011 (push (list :table (org-table-begin) (org-table-end)) clist)
21012 (if (memq 'org-formula faces)
21013 (push (list :table-special
21014 (previous-single-property-change p 'face)
21015 (next-single-property-change p 'face)) clist)))
21016 ((org-at-table-p 'any)
21017 (push (list :table-table) clist)))
21018 (goto-char p)
21020 (let ((case-fold-search t))
21021 ;; New the "medium" contexts: clocktables, source blocks
21022 (cond ((org-in-clocktable-p)
21023 (push (list :clocktable
21024 (and (or (looking-at "#\\+BEGIN: clocktable")
21025 (search-backward "#+BEGIN: clocktable" nil t))
21026 (match-beginning 0))
21027 (and (re-search-forward "#\\+END:?" nil t)
21028 (match-end 0))) clist))
21029 ((org-in-src-block-p)
21030 (push (list :src-block
21031 (and (or (looking-at "#\\+BEGIN_SRC")
21032 (search-backward "#+BEGIN_SRC" nil t))
21033 (match-beginning 0))
21034 (and (search-forward "#+END_SRC" nil t)
21035 (match-beginning 0))) clist))))
21036 (goto-char p)
21038 ;; Now the small context
21039 (cond
21040 ((org-at-timestamp-p)
21041 (push (org-point-in-group p 0 :timestamp) clist))
21042 ((memq 'org-link faces)
21043 (push (list :link
21044 (previous-single-property-change p 'face)
21045 (next-single-property-change p 'face)) clist))
21046 ((memq 'org-special-keyword faces)
21047 (push (list :keyword
21048 (previous-single-property-change p 'face)
21049 (next-single-property-change p 'face)) clist))
21050 ((org-at-target-p)
21051 (push (org-point-in-group p 0 :target) clist)
21052 (goto-char (1- (match-beginning 0)))
21053 (if (looking-at org-radio-target-regexp)
21054 (push (org-point-in-group p 0 :radio-target) clist))
21055 (goto-char p))
21056 ((setq o (car (delq nil
21057 (mapcar
21058 (lambda (x)
21059 (if (memq x org-latex-fragment-image-overlays) x))
21060 (overlays-at (point))))))
21061 (push (list :latex-fragment
21062 (overlay-start o) (overlay-end o)) clist)
21063 (push (list :latex-preview
21064 (overlay-start o) (overlay-end o)) clist))
21065 ((org-inside-LaTeX-fragment-p)
21066 ;; FIXME: positions wrong.
21067 (push (list :latex-fragment (point) (point)) clist)))
21069 (setq clist (nreverse (delq nil clist)))
21070 clist))
21072 ;; FIXME: Compare with at-regexp-p Do we need both?
21073 (defun org-in-regexp (re &optional nlines visually)
21074 "Check if point is inside a match of regexp.
21075 Normally only the current line is checked, but you can include NLINES extra
21076 lines both before and after point into the search.
21077 If VISUALLY is set, require that the cursor is not after the match but
21078 really on, so that the block visually is on the match."
21079 (catch 'exit
21080 (let ((pos (point))
21081 (eol (point-at-eol (+ 1 (or nlines 0))))
21082 (inc (if visually 1 0)))
21083 (save-excursion
21084 (beginning-of-line (- 1 (or nlines 0)))
21085 (while (re-search-forward re eol t)
21086 (if (and (<= (match-beginning 0) pos)
21087 (>= (+ inc (match-end 0)) pos))
21088 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21090 (defun org-at-regexp-p (regexp)
21091 "Is point inside a match of REGEXP in the current line?"
21092 (catch 'exit
21093 (save-excursion
21094 (let ((pos (point)) (end (point-at-eol)))
21095 (beginning-of-line 1)
21096 (while (re-search-forward regexp end t)
21097 (if (and (<= (match-beginning 0) pos)
21098 (>= (match-end 0) pos))
21099 (throw 'exit t)))
21100 nil))))
21102 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21103 "Non-nil when point is between matches of START-RE and END-RE.
21105 Also return a non-nil value when point is on one of the matches.
21107 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21108 buffer positions. Default values are the positions of headlines
21109 surrounding the point.
21111 The functions returns a cons cell whose car (resp. cdr) is the
21112 position before START-RE (resp. after END-RE)."
21113 (save-match-data
21114 (let ((pos (point))
21115 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21116 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21117 beg end)
21118 (save-excursion
21119 ;; Point is on a block when on START-RE or if START-RE can be
21120 ;; found before it...
21121 (and (or (org-at-regexp-p start-re)
21122 (re-search-backward start-re limit-up t))
21123 (setq beg (match-beginning 0))
21124 ;; ... and END-RE after it...
21125 (goto-char (match-end 0))
21126 (re-search-forward end-re limit-down t)
21127 (> (setq end (match-end 0)) pos)
21128 ;; ... without another START-RE in-between.
21129 (goto-char (match-beginning 0))
21130 (not (re-search-backward start-re (1+ beg) t))
21131 ;; Return value.
21132 (cons beg end))))))
21134 (defun org-in-block-p (names)
21135 "Non-nil when point belongs to a block whose name belongs to NAMES.
21137 NAMES is a list of strings containing names of blocks.
21139 Return first block name matched, or nil. Beware that in case of
21140 nested blocks, the returned name may not belong to the closest
21141 block from point."
21142 (save-match-data
21143 (catch 'exit
21144 (let ((case-fold-search t)
21145 (lim-up (save-excursion (outline-previous-heading)))
21146 (lim-down (save-excursion (outline-next-heading))))
21147 (mapc (lambda (name)
21148 (let ((n (regexp-quote name)))
21149 (when (org-between-regexps-p
21150 (concat "^[ \t]*#\\+begin_" n)
21151 (concat "^[ \t]*#\\+end_" n)
21152 lim-up lim-down)
21153 (throw 'exit n))))
21154 names))
21155 nil)))
21157 (defun org-occur-in-agenda-files (regexp &optional nlines)
21158 "Call `multi-occur' with buffers for all agenda files."
21159 (interactive "sOrg-files matching: \np")
21160 (let* ((files (org-agenda-files))
21161 (tnames (mapcar 'file-truename files))
21162 (extra org-agenda-text-search-extra-files)
21164 (when (eq (car extra) 'agenda-archives)
21165 (setq extra (cdr extra))
21166 (setq files (org-add-archive-files files)))
21167 (while (setq f (pop extra))
21168 (unless (member (file-truename f) tnames)
21169 (add-to-list 'files f 'append)
21170 (add-to-list 'tnames (file-truename f) 'append)))
21171 (multi-occur
21172 (mapcar (lambda (x)
21173 (with-current-buffer
21174 (or (get-file-buffer x) (find-file-noselect x))
21175 (widen)
21176 (current-buffer)))
21177 files)
21178 regexp)))
21180 (if (boundp 'occur-mode-find-occurrence-hook)
21181 ;; Emacs 23
21182 (add-hook 'occur-mode-find-occurrence-hook
21183 (lambda ()
21184 (when (derived-mode-p 'org-mode)
21185 (org-reveal))))
21186 ;; Emacs 22
21187 (defadvice occur-mode-goto-occurrence
21188 (after org-occur-reveal activate)
21189 (and (derived-mode-p 'org-mode) (org-reveal)))
21190 (defadvice occur-mode-goto-occurrence-other-window
21191 (after org-occur-reveal activate)
21192 (and (derived-mode-p 'org-mode) (org-reveal)))
21193 (defadvice occur-mode-display-occurrence
21194 (after org-occur-reveal activate)
21195 (when (derived-mode-p 'org-mode)
21196 (let ((pos (occur-mode-find-occurrence)))
21197 (with-current-buffer (marker-buffer pos)
21198 (save-excursion
21199 (goto-char pos)
21200 (org-reveal)))))))
21202 (defun org-occur-link-in-agenda-files ()
21203 "Create a link and search for it in the agendas.
21204 The link is not stored in `org-stored-links', it is just created
21205 for the search purpose."
21206 (interactive)
21207 (let ((link (condition-case nil
21208 (org-store-link nil)
21209 (error "Unable to create a link to here"))))
21210 (org-occur-in-agenda-files (regexp-quote link))))
21212 (defun org-reverse-string (string)
21213 "Return the reverse of STRING."
21214 (apply 'string (reverse (string-to-list string))))
21216 (defun org-uniquify (list)
21217 "Remove duplicate elements from LIST."
21218 (let (res)
21219 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21220 res))
21222 (defun org-delete-all (elts list)
21223 "Remove all elements in ELTS from LIST."
21224 (while elts
21225 (setq list (delete (pop elts) list)))
21226 list)
21228 (defun org-count (cl-item cl-seq)
21229 "Count the number of occurrences of ITEM in SEQ.
21230 Taken from `count' in cl-seq.el with all keyword arguments removed."
21231 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21232 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21233 (while (< cl-start cl-end)
21234 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21235 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21236 (setq cl-start (1+ cl-start)))
21237 cl-count))
21239 (defun org-remove-if (predicate seq)
21240 "Remove everything from SEQ that fulfills PREDICATE."
21241 (let (res e)
21242 (while seq
21243 (setq e (pop seq))
21244 (if (not (funcall predicate e)) (push e res)))
21245 (nreverse res)))
21247 (defun org-remove-if-not (predicate seq)
21248 "Remove everything from SEQ that does not fulfill PREDICATE."
21249 (let (res e)
21250 (while seq
21251 (setq e (pop seq))
21252 (if (funcall predicate e) (push e res)))
21253 (nreverse res)))
21255 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21256 "Reduce two-argument FUNCTION across SEQ.
21257 Taken from `reduce' in cl-seq.el with all keyword arguments but
21258 \":initial-value\" removed."
21259 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21260 (cadr (memq :initial-value cl-keys)))
21261 (cl-seq (pop cl-seq))
21262 (t (funcall cl-func)))))
21263 (while cl-seq
21264 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21265 cl-accum))
21267 (defun org-back-over-empty-lines ()
21268 "Move backwards over whitespace, to the beginning of the first empty line.
21269 Returns the number of empty lines passed."
21270 (let ((pos (point)))
21271 (if (cdr (assoc 'heading org-blank-before-new-entry))
21272 (skip-chars-backward " \t\n\r")
21273 (unless (eobp)
21274 (forward-line -1)))
21275 (beginning-of-line 2)
21276 (goto-char (min (point) pos))
21277 (count-lines (point) pos)))
21279 (defun org-skip-whitespace ()
21280 (skip-chars-forward " \t\n\r"))
21282 (defun org-point-in-group (point group &optional context)
21283 "Check if POINT is in match-group GROUP.
21284 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21285 match. If the match group does not exist or point is not inside it,
21286 return nil."
21287 (and (match-beginning group)
21288 (>= point (match-beginning group))
21289 (<= point (match-end group))
21290 (if context
21291 (list context (match-beginning group) (match-end group))
21292 t)))
21294 (defun org-switch-to-buffer-other-window (&rest args)
21295 "Switch to buffer in a second window on the current frame.
21296 In particular, do not allow pop-up frames.
21297 Returns the newly created buffer."
21298 (org-no-popups
21299 (apply 'switch-to-buffer-other-window args)))
21301 (defun org-combine-plists (&rest plists)
21302 "Create a single property list from all plists in PLISTS.
21303 The process starts by copying the first list, and then setting properties
21304 from the other lists. Settings in the last list are the most significant
21305 ones and overrule settings in the other lists."
21306 (let ((rtn (copy-sequence (pop plists)))
21307 p v ls)
21308 (while plists
21309 (setq ls (pop plists))
21310 (while ls
21311 (setq p (pop ls) v (pop ls))
21312 (setq rtn (plist-put rtn p v))))
21313 rtn))
21315 (defun org-replace-escapes (string table)
21316 "Replace %-escapes in STRING with values in TABLE.
21317 TABLE is an association list with keys like \"%a\" and string values.
21318 The sequences in STRING may contain normal field width and padding information,
21319 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21320 so values can contain further %-escapes if they are define later in TABLE."
21321 (let ((tbl (copy-alist table))
21322 (case-fold-search nil)
21323 (pchg 0)
21324 e re rpl)
21325 (while (setq e (pop tbl))
21326 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21327 (when (and (cdr e) (string-match re (cdr e)))
21328 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21329 (safe "SREF"))
21330 (add-text-properties 0 3 (list 'sref sref) safe)
21331 (setcdr e (replace-match safe t t (cdr e)))))
21332 (while (string-match re string)
21333 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21334 (cdr e)))
21335 (setq string (replace-match rpl t t string))))
21336 (while (setq pchg (next-property-change pchg string))
21337 (let ((sref (get-text-property pchg 'sref string)))
21338 (when (and sref (string-match "SREF" string pchg))
21339 (setq string (replace-match sref t t string)))))
21340 string))
21342 (defun org-sublist (list start end)
21343 "Return a section of LIST, from START to END.
21344 Counting starts at 1."
21345 (let (rtn (c start))
21346 (setq list (nthcdr (1- start) list))
21347 (while (and list (<= c end))
21348 (push (pop list) rtn)
21349 (setq c (1+ c)))
21350 (nreverse rtn)))
21352 (defun org-find-base-buffer-visiting (file)
21353 "Like `find-buffer-visiting' but always return the base buffer and
21354 not an indirect buffer."
21355 (let ((buf (or (get-file-buffer file)
21356 (find-buffer-visiting file))))
21357 (if buf
21358 (or (buffer-base-buffer buf) buf)
21359 nil)))
21361 (defun org-image-file-name-regexp (&optional extensions)
21362 "Return regexp matching the file names of images.
21363 If EXTENSIONS is given, only match these."
21364 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21365 (image-file-name-regexp)
21366 (let ((image-file-name-extensions
21367 (or extensions
21368 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21369 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21370 (concat "\\."
21371 (regexp-opt (nconc (mapcar 'upcase
21372 image-file-name-extensions)
21373 image-file-name-extensions)
21375 "\\'"))))
21377 (defun org-file-image-p (file &optional extensions)
21378 "Return non-nil if FILE is an image."
21379 (save-match-data
21380 (string-match (org-image-file-name-regexp extensions) file)))
21382 (defun org-get-cursor-date (&optional with-time)
21383 "Return the date at cursor in as a time.
21384 This works in the calendar and in the agenda, anywhere else it just
21385 returns the current time.
21386 If WITH-TIME is non-nil, returns the time of the event at point (in
21387 the agenda) or the current time of the day."
21388 (let (date day defd tp tm hod mod)
21389 (when with-time
21390 (setq tp (get-text-property (point) 'time))
21391 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21392 (setq hod (string-to-number (match-string 1 tp))
21393 mod (string-to-number (match-string 2 tp))))
21394 (or tp (setq hod (nth 2 (decode-time (current-time)))
21395 mod (nth 1 (decode-time (current-time))))))
21396 (cond
21397 ((eq major-mode 'calendar-mode)
21398 (setq date (calendar-cursor-to-date)
21399 defd (encode-time 0 (or mod 0) (or hod 0)
21400 (nth 1 date) (nth 0 date) (nth 2 date))))
21401 ((eq major-mode 'org-agenda-mode)
21402 (setq day (get-text-property (point) 'day))
21403 (if day
21404 (setq date (calendar-gregorian-from-absolute day)
21405 defd (encode-time 0 (or mod 0) (or hod 0)
21406 (nth 1 date) (nth 0 date) (nth 2 date))))))
21407 (or defd (current-time))))
21409 (defun org-mark-subtree (&optional up)
21410 "Mark the current subtree.
21411 This puts point at the start of the current subtree, and mark at
21412 the end. If a numeric prefix UP is given, move up into the
21413 hierarchy of headlines by UP levels before marking the subtree."
21414 (interactive "P")
21415 (org-with-limited-levels
21416 (cond ((org-at-heading-p) (beginning-of-line))
21417 ((org-before-first-heading-p) (error "Not in a subtree"))
21418 (t (outline-previous-visible-heading 1))))
21419 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21420 (if (org-called-interactively-p 'any)
21421 (call-interactively 'org-mark-element)
21422 (org-mark-element)))
21425 ;;; Indentation
21427 (defun org-indent-line ()
21428 "Indent line depending on context."
21429 (interactive)
21430 (let* ((pos (point))
21431 (itemp (org-at-item-p))
21432 (case-fold-search t)
21433 (org-drawer-regexp (or org-drawer-regexp "\000"))
21434 (inline-task-p (and (featurep 'org-inlinetask)
21435 (org-inlinetask-in-task-p)))
21436 (inline-re (and inline-task-p
21437 (org-inlinetask-outline-regexp)))
21438 column)
21439 (if (and orgstruct-is-++ (eq pos (point)))
21440 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21441 (indent-according-to-mode))
21442 (beginning-of-line 1)
21443 (cond
21444 ;; Headings
21445 ((looking-at org-outline-regexp) (setq column 0))
21446 ;; Footnote definition
21447 ((looking-at org-footnote-definition-re) (setq column 0))
21448 ;; Literal examples
21449 ((looking-at "[ \t]*:\\( \\|$\\)")
21450 (setq column (org-get-indentation))) ; do nothing
21451 ;; Lists
21452 ((ignore-errors (goto-char (org-in-item-p)))
21453 (setq column (if itemp
21454 (org-get-indentation)
21455 (org-list-item-body-column (point))))
21456 (goto-char pos))
21457 ;; Drawers
21458 ((and (looking-at "[ \t]*:END:")
21459 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21460 (save-excursion
21461 (goto-char (1- (match-beginning 1)))
21462 (setq column (current-column))))
21463 ;; Special blocks
21464 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21465 (save-excursion
21466 (re-search-backward
21467 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21468 (setq column (org-get-indentation (match-string 0))))
21469 ((and (not (looking-at "[ \t]*#\\+begin_"))
21470 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21471 (save-excursion
21472 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21473 (setq column
21474 (cond ((equal (downcase (match-string 1)) "src")
21475 ;; src blocks: let `org-edit-src-exit' handle them
21476 (org-get-indentation))
21477 ((equal (downcase (match-string 1)) "example")
21478 (max (org-get-indentation)
21479 (org-get-indentation (match-string 0))))
21481 (org-get-indentation (match-string 0))))))
21482 ;; This line has nothing special, look at the previous relevant
21483 ;; line to compute indentation
21485 (beginning-of-line 0)
21486 (while (and (not (bobp))
21487 (not (looking-at org-table-line-regexp))
21488 (not (looking-at org-drawer-regexp))
21489 ;; When point started in an inline task, do not move
21490 ;; above task starting line.
21491 (not (and inline-task-p (looking-at inline-re)))
21492 ;; Skip drawers, blocks, empty lines, verbatim,
21493 ;; comments, tables, footnotes definitions, lists,
21494 ;; inline tasks.
21495 (or (and (looking-at "[ \t]*:END:")
21496 (re-search-backward org-drawer-regexp nil t))
21497 (and (looking-at "[ \t]*#\\+end_")
21498 (re-search-backward "[ \t]*#\\+begin_"nil t))
21499 (looking-at "[ \t]*[\n:#|]")
21500 (looking-at org-footnote-definition-re)
21501 (and (ignore-errors (goto-char (org-in-item-p)))
21502 (goto-char
21503 (org-list-get-top-point (org-list-struct))))
21504 (and (not inline-task-p)
21505 (featurep 'org-inlinetask)
21506 (org-inlinetask-in-task-p)
21507 (or (org-inlinetask-goto-beginning) t))))
21508 (beginning-of-line 0))
21509 (cond
21510 ;; There was an heading above.
21511 ((looking-at "\\*+[ \t]+")
21512 (if (not org-adapt-indentation)
21513 (setq column 0)
21514 (goto-char (match-end 0))
21515 (setq column (current-column))))
21516 ;; A drawer had started and is unfinished
21517 ((looking-at org-drawer-regexp)
21518 (goto-char (1- (match-beginning 1)))
21519 (setq column (current-column)))
21520 ;; Else, nothing noticeable found: get indentation and go on.
21521 (t (setq column (org-get-indentation))))))
21522 ;; Now apply indentation and move cursor accordingly
21523 (goto-char pos)
21524 (if (<= (current-column) (current-indentation))
21525 (org-indent-line-to column)
21526 (save-excursion (org-indent-line-to column)))
21527 ;; Special polishing for properties, see `org-property-format'
21528 (setq column (current-column))
21529 (beginning-of-line 1)
21530 (if (looking-at
21531 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21532 (replace-match (concat (match-string 1)
21533 (format org-property-format
21534 (match-string 2) (match-string 3)))
21535 t t))
21536 (org-move-to-column column))))
21538 (defun org-indent-drawer ()
21539 "Indent the drawer at point."
21540 (interactive)
21541 (let ((p (point))
21542 (e (and (save-excursion (re-search-forward ":END:" nil t))
21543 (match-end 0)))
21544 (folded
21545 (save-excursion
21546 (end-of-line)
21547 (when (overlays-at (point))
21548 (member 'invisible (overlay-properties
21549 (car (overlays-at (point)))))))))
21550 (when folded (org-cycle))
21551 (indent-for-tab-command)
21552 (while (and (move-beginning-of-line 2) (< (point) e))
21553 (indent-for-tab-command))
21554 (goto-char p)
21555 (when folded (org-cycle)))
21556 (message "Drawer at point indented"))
21558 (defun org-indent-block ()
21559 "Indent the block at point."
21560 (interactive)
21561 (let ((p (point))
21562 (case-fold-search t)
21563 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21564 (match-end 0)))
21565 (folded
21566 (save-excursion
21567 (end-of-line)
21568 (when (overlays-at (point))
21569 (member 'invisible (overlay-properties
21570 (car (overlays-at (point)))))))))
21571 (when folded (org-cycle))
21572 (indent-for-tab-command)
21573 (while (and (move-beginning-of-line 2) (< (point) e))
21574 (indent-for-tab-command))
21575 (goto-char p)
21576 (when folded (org-cycle)))
21577 (message "Block at point indented"))
21579 (defun org-indent-region (start end)
21580 "Indent region."
21581 (interactive "r")
21582 (save-excursion
21583 (let ((line-end (org-current-line end)))
21584 (goto-char start)
21585 (while (< (org-current-line) line-end)
21586 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21587 (t (call-interactively 'org-indent-line)))
21588 (move-beginning-of-line 2)))))
21591 ;;; Filling
21593 ;; We use our own fill-paragraph and auto-fill functions.
21595 ;; `org-fill-paragraph' relies on adaptive filling and context
21596 ;; checking. Appropriate `fill-prefix' is computed with
21597 ;; `org-adaptive-fill-function'.
21599 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21600 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21601 ;; `org-adaptive-fill-function' value. Internally,
21602 ;; `org-comment-line-break-function' breaks the line.
21604 ;; `org-setup-filling' installs filling and auto-filling related
21605 ;; variables during `org-mode' initialization.
21607 (defun org-setup-filling ()
21608 (interactive)
21609 ;; Prevent auto-fill from inserting unwanted new items.
21610 (when (boundp 'fill-nobreak-predicate)
21611 (org-set-local
21612 'fill-nobreak-predicate
21613 (org-uniquify
21614 (append fill-nobreak-predicate
21615 '(org-fill-paragraph-separate-nobreak-p
21616 org-fill-line-break-nobreak-p
21617 org-fill-paragraph-with-timestamp-nobreak-p)))))
21618 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21619 (org-set-local 'auto-fill-inhibit-regexp nil)
21620 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21621 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21622 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21624 (defvar org-element-paragraph-separate) ; org-element.el
21625 (defun org-fill-paragraph-separate-nobreak-p ()
21626 "Non-nil when a line break at point would insert a new item."
21627 (looking-at (substring org-element-paragraph-separate 1)))
21629 (defun org-fill-line-break-nobreak-p ()
21630 "Non-nil when a line break at point would create an Org line break."
21631 (save-excursion
21632 (skip-chars-backward "[ \t]")
21633 (skip-chars-backward "\\\\")
21634 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21636 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21637 "Non-nil when a line break at point would insert a new item."
21638 (and (org-at-timestamp-p t)
21639 (not (looking-at org-ts-regexp-both))))
21641 (declare-function message-in-body-p "message" ())
21642 (defvar orgtbl-line-start-regexp) ; From org-table.el
21643 (defun org-adaptive-fill-function ()
21644 "Compute a fill prefix for the current line.
21645 Return fill prefix, as a string, or nil if current line isn't
21646 meant to be filled."
21647 (let (prefix)
21648 (catch 'exit
21649 (when (derived-mode-p 'message-mode)
21650 (save-excursion
21651 (beginning-of-line)
21652 (cond ((or (not (message-in-body-p))
21653 (looking-at orgtbl-line-start-regexp))
21654 (throw 'exit nil))
21655 ((looking-at message-cite-prefix-regexp)
21656 (throw 'exit (match-string-no-properties 0)))
21657 ((looking-at org-outline-regexp)
21658 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21659 (org-with-wide-buffer
21660 (let* ((p (line-beginning-position))
21661 (element (save-excursion (beginning-of-line)
21662 (org-element-at-point)))
21663 (type (org-element-type element))
21664 (post-affiliated (org-element-property :post-affiliated element)))
21665 (unless (and post-affiliated (< p post-affiliated))
21666 (case type
21667 (comment (looking-at "[ \t]*# ?") (match-string 0))
21668 (footnote-definition "")
21669 ((item plain-list)
21670 (make-string (org-list-item-body-column
21671 (or post-affiliated
21672 (org-element-property :begin element)))
21673 ? ))
21674 (paragraph
21675 ;; Fill prefix is usually the same as the current line,
21676 ;; except if the paragraph is at the beginning of an item.
21677 (let ((parent (org-element-property :parent element)))
21678 (cond ((eq (org-element-type parent) 'item)
21679 (make-string (org-list-item-body-column
21680 (org-element-property :begin parent))
21681 ? ))
21682 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21683 (match-string 0))
21684 (t ""))))
21685 (comment-block
21686 ;; Only fill contents if P is within block boundaries.
21687 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21688 (forward-line)
21689 (point)))
21690 (cend (save-excursion
21691 (goto-char (org-element-property :end element))
21692 (skip-chars-backward " \r\t\n")
21693 (line-beginning-position))))
21694 (when (and (>= p cbeg) (< p cend))
21695 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21696 (match-string 0)
21697 "")))))))))))
21699 (declare-function message-goto-body "message" ())
21700 (defvar message-cite-prefix-regexp) ; From message.el
21701 (defvar org-element-all-objects) ; From org-element.el
21702 (defun org-fill-paragraph (&optional justify)
21703 "Fill element at point, when applicable.
21705 This function only applies to comment blocks, comments, example
21706 blocks and paragraphs. Also, as a special case, re-align table
21707 when point is at one.
21709 If JUSTIFY is non-nil (interactively, with prefix argument),
21710 justify as well. If `sentence-end-double-space' is non-nil, then
21711 period followed by one space does not end a sentence, so don't
21712 break a line there. The variable `fill-column' controls the
21713 width for filling.
21715 For convenience, when point is at a plain list, an item or
21716 a footnote definition, try to fill the first paragraph within."
21717 (interactive)
21718 (if (and (derived-mode-p 'message-mode)
21719 (or (not (message-in-body-p))
21720 (save-excursion (move-beginning-of-line 1)
21721 (looking-at message-cite-prefix-regexp))))
21722 ;; First ensure filling is correct in message-mode.
21723 (let ((fill-paragraph-function
21724 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21725 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21726 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21727 (paragraph-separate
21728 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21729 (fill-paragraph nil))
21730 (save-excursion
21731 ;; Move to end of line in order to get the first paragraph
21732 ;; within a plain list or a footnote definition.
21733 (end-of-line)
21734 (let ((element (org-element-at-point)))
21735 ;; First check if point is in a blank line at the beginning of
21736 ;; the buffer. In that case, ignore filling.
21737 (if (< (point) (org-element-property :begin element)) t
21738 (case (org-element-type element)
21739 ;; Use major mode filling function is src blocks.
21740 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21741 ;; Align Org tables, leave table.el tables as-is.
21742 (table-row (org-table-align) t)
21743 (table
21744 (when (eq (org-element-property :type element) 'org)
21745 (org-table-align))
21747 (paragraph
21748 ;; Paragraphs may contain `line-break' type objects.
21749 (let ((beg (max (point-min)
21750 (org-element-property :contents-begin element)))
21751 (end (min (point-max)
21752 (org-element-property :contents-end element))))
21753 ;; Do nothing if point is at an affiliated keyword.
21754 (if (< (point) beg) t
21755 (when (derived-mode-p 'message-mode)
21756 ;; In `message-mode', do not fill following
21757 ;; citation in current paragraph nor text before
21758 ;; message body.
21759 (let ((body-start (save-excursion (message-goto-body))))
21760 (when body-start (setq beg (max body-start beg))))
21761 (when (save-excursion
21762 (re-search-forward
21763 (concat "^" message-cite-prefix-regexp) end t))
21764 (setq end (match-beginning 0))))
21765 ;; Fill paragraph, taking line breaks into
21766 ;; consideration. For that, slice the paragraph
21767 ;; using line breaks as separators, and fill the
21768 ;; parts in reverse order to avoid messing with
21769 ;; markers.
21770 (save-excursion
21771 (goto-char end)
21772 (mapc
21773 (lambda (pos)
21774 (fill-region-as-paragraph pos (point) justify)
21775 (goto-char pos))
21776 ;; Find the list of ending positions for line
21777 ;; breaks in the current paragraph. Add paragraph
21778 ;; beginning to include first slice.
21779 (nreverse
21780 (cons
21782 (org-element-map
21783 (org-element--parse-objects
21784 beg end nil org-element-all-objects)
21785 'line-break
21786 (lambda (lb) (org-element-property :end lb)))))))
21787 t)))
21788 ;; Contents of `comment-block' type elements should be
21789 ;; filled as plain text, but only if point is within block
21790 ;; markers.
21791 (comment-block
21792 (let* ((case-fold-search t)
21793 (beg (save-excursion
21794 (goto-char (org-element-property :begin element))
21795 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21796 (forward-line)
21797 (point)))
21798 (end (save-excursion
21799 (goto-char (org-element-property :end element))
21800 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21801 (line-beginning-position))))
21802 (when (and (>= (point) beg) (< (point) end))
21803 (fill-region-as-paragraph
21804 (save-excursion
21805 (end-of-line)
21806 (re-search-backward "^[ \t]*$" beg 'move)
21807 (line-beginning-position))
21808 (save-excursion
21809 (beginning-of-line)
21810 (re-search-forward "^[ \t]*$" end 'move)
21811 (line-beginning-position))
21812 justify)))
21814 ;; Fill comments.
21815 (comment (fill-comment-paragraph justify))
21816 ;; Ignore every other element.
21817 (otherwise t)))))))
21819 (defun org-auto-fill-function ()
21820 "Auto-fill function."
21821 ;; Check if auto-filling is meaningful.
21822 (let ((fc (current-fill-column)))
21823 (when (and fc (> (current-column) fc))
21824 (let* ((fill-prefix (org-adaptive-fill-function))
21825 ;; Enforce empty fill prefix, if required. Otherwise, it
21826 ;; will be computed again.
21827 (adaptive-fill-mode (not (equal fill-prefix ""))))
21828 (when fill-prefix (do-auto-fill))))))
21830 (defun org-comment-line-break-function (&optional soft)
21831 "Break line at point and indent, continuing comment if within one.
21832 The inserted newline is marked hard if variable
21833 `use-hard-newlines' is true, unless optional argument SOFT is
21834 non-nil."
21835 (if soft (insert-and-inherit ?\n) (newline 1))
21836 (save-excursion (forward-char -1) (delete-horizontal-space))
21837 (delete-horizontal-space)
21838 (indent-to-left-margin)
21839 (insert-before-markers-and-inherit fill-prefix))
21842 ;;; Comments
21844 ;; Org comments syntax is quite complex. It requires the entire line
21845 ;; to be just a comment. Also, even with the right syntax at the
21846 ;; beginning of line, some some elements (i.e. verse-block or
21847 ;; example-block) don't accept comments. Usual Emacs comment commands
21848 ;; cannot cope with those requirements. Therefore, Org replaces them.
21850 ;; Org still relies on `comment-dwim', but cannot trust
21851 ;; `comment-only-p'. So, `comment-region-function' and
21852 ;; `uncomment-region-function' both point
21853 ;; to`org-comment-or-uncomment-region'. Eventually,
21854 ;; `org-insert-comment' takes care of insertion of comments at the
21855 ;; beginning of line.
21857 ;; `org-setup-comments-handling' install comments related variables
21858 ;; during `org-mode' initialization.
21860 (defun org-setup-comments-handling ()
21861 (interactive)
21862 (org-set-local 'comment-use-syntax nil)
21863 (org-set-local 'comment-start "# ")
21864 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21865 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21866 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21867 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21869 (defun org-insert-comment ()
21870 "Insert an empty comment above current line.
21871 If the line is empty, insert comment at its beginning."
21872 (beginning-of-line)
21873 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21874 (org-indent-line)
21875 (insert "# "))
21877 (defvar comment-empty-lines) ; From newcomment.el.
21878 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21879 "Comment or uncomment each non-blank line in the region.
21880 Uncomment each non-blank line between BEG and END if it only
21881 contains commented lines. Otherwise, comment them."
21882 (save-restriction
21883 ;; Restrict region
21884 (narrow-to-region (save-excursion (goto-char beg)
21885 (skip-chars-forward " \r\t\n" end)
21886 (line-beginning-position))
21887 (save-excursion (goto-char end)
21888 (skip-chars-backward " \r\t\n" beg)
21889 (line-end-position)))
21890 (let ((uncommentp
21891 ;; UNCOMMENTP is non-nil when every non blank line between
21892 ;; BEG and END is a comment.
21893 (save-excursion
21894 (goto-char (point-min))
21895 (while (and (not (eobp))
21896 (let ((element (org-element-at-point)))
21897 (and (eq (org-element-type element) 'comment)
21898 (goto-char (min (point-max)
21899 (org-element-property
21900 :end element)))))))
21901 (eobp))))
21902 (if uncommentp
21903 ;; Only blank lines and comments in region: uncomment it.
21904 (save-excursion
21905 (goto-char (point-min))
21906 (while (not (eobp))
21907 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21908 (replace-match "" nil nil nil 1))
21909 (forward-line)))
21910 ;; Comment each line in region.
21911 (let ((min-indent (point-max)))
21912 ;; First find the minimum indentation across all lines.
21913 (save-excursion
21914 (goto-char (point-min))
21915 (while (and (not (eobp)) (not (zerop min-indent)))
21916 (unless (looking-at "[ \t]*$")
21917 (setq min-indent (min min-indent (current-indentation))))
21918 (forward-line)))
21919 ;; Then loop over all lines.
21920 (save-excursion
21921 (goto-char (point-min))
21922 (while (not (eobp))
21923 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21924 (org-move-to-column min-indent t)
21925 (insert comment-start))
21926 (forward-line))))))))
21929 ;;; Planning
21931 ;; This section contains tools to operate on timestamp objects, as
21932 ;; returned by, e.g. `org-element-context'.
21934 (defun org-timestamp-has-time-p (timestamp)
21935 "Non-nil when TIMESTAMP has a time specified."
21936 (org-element-property :hour-start timestamp))
21938 (defun org-timestamp-format (timestamp format &optional end utc)
21939 "Format a TIMESTAMP element into a string.
21941 FORMAT is a format specifier to be passed to
21942 `format-time-string'.
21944 When optional argument END is non-nil, use end of date-range or
21945 time-range, if possible.
21947 When optional argument UTC is non-nil, time will be expressed as
21948 Universal Time."
21949 (format-time-string
21950 format
21951 (apply 'encode-time
21952 (cons 0
21953 (mapcar
21954 (lambda (prop) (or (org-element-property prop timestamp) 0))
21955 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21956 '(:minute-start :hour-start :day-start :month-start
21957 :year-start)))))
21958 utc))
21960 (defun org-timestamp-split-range (timestamp &optional end)
21961 "Extract a timestamp object from a date or time range.
21963 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21964 the end of the range. Otherwise, extract its start.
21966 Return a new timestamp object sharing the same parent as
21967 TIMESTAMP."
21968 (let ((type (org-element-property :type timestamp)))
21969 (if (memq type '(active inactive diary)) timestamp
21970 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21971 ;; Set new type.
21972 (org-element-put-property
21973 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21974 ;; Copy start properties over end properties if END is
21975 ;; non-nil. Otherwise, copy end properties over `start' ones.
21976 (let ((p-alist '((:minute-start . :minute-end)
21977 (:hour-start . :hour-end)
21978 (:day-start . :day-end)
21979 (:month-start . :month-end)
21980 (:year-start . :year-end))))
21981 (dolist (p-cell p-alist)
21982 (org-element-put-property
21983 split-ts
21984 (funcall (if end 'car 'cdr) p-cell)
21985 (org-element-property
21986 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21987 ;; Eventually refresh `:raw-value'.
21988 (org-element-put-property split-ts :raw-value nil)
21989 (org-element-put-property
21990 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21992 (defun org-timestamp-translate (timestamp &optional boundary)
21993 "Apply `org-translate-time' on a TIMESTAMP object.
21994 When optional argument BOUNDARY is non-nil, it is either the
21995 symbol `start' or `end'. In this case, only translate the
21996 starting or ending part of TIMESTAMP if it is a date or time
21997 range. Otherwise, translate both parts."
21998 (if (and (not boundary)
21999 (memq (org-element-property :type timestamp)
22000 '(active-range inactive-range)))
22001 (concat
22002 (org-translate-time
22003 (org-element-property :raw-value
22004 (org-timestamp-split-range timestamp)))
22005 "--"
22006 (org-translate-time
22007 (org-element-property :raw-value
22008 (org-timestamp-split-range timestamp t))))
22009 (org-translate-time
22010 (org-element-property
22011 :raw-value
22012 (if (not boundary) timestamp
22013 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22017 ;;; Other stuff.
22019 (defun org-toggle-fixed-width-section (arg)
22020 "Toggle the fixed-width export.
22021 If there is no active region, the QUOTE keyword at the current headline is
22022 inserted or removed. When present, it causes the text between this headline
22023 and the next to be exported as fixed-width text, and unmodified.
22024 If there is an active region, this command adds or removes a colon as the
22025 first character of this line. If the first character of a line is a colon,
22026 this line is also exported in fixed-width font."
22027 (interactive "P")
22028 (let* ((cc 0)
22029 (regionp (org-region-active-p))
22030 (beg (if regionp (region-beginning) (point)))
22031 (end (if regionp (region-end)))
22032 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22033 (case-fold-search nil)
22034 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22035 off)
22036 (if regionp
22037 (save-excursion
22038 (goto-char beg)
22039 (setq cc (current-column))
22040 (beginning-of-line 1)
22041 (setq off (looking-at re))
22042 (while (> nlines 0)
22043 (setq nlines (1- nlines))
22044 (beginning-of-line 1)
22045 (cond
22046 (arg
22047 (org-move-to-column cc t)
22048 (insert ": \n")
22049 (forward-line -1))
22050 ((and off (looking-at re))
22051 (replace-match "" t t nil 1))
22052 ((not off) (org-move-to-column cc t) (insert ": ")))
22053 (forward-line 1)))
22054 (save-excursion
22055 (org-back-to-heading)
22056 (cond
22057 ((looking-at (format org-heading-keyword-regexp-format
22058 org-quote-string))
22059 (goto-char (match-end 1))
22060 (looking-at (concat " +" org-quote-string))
22061 (replace-match "" t t)
22062 (when (eolp) (insert " ")))
22063 ((looking-at org-outline-regexp)
22064 (goto-char (match-end 0))
22065 (insert org-quote-string " ")))))))
22067 (defun org-reftex-citation ()
22068 "Use reftex-citation to insert a citation into the buffer.
22069 This looks for a line like
22071 #+BIBLIOGRAPHY: foo plain option:-d
22073 and derives from it that foo.bib is the bibliography file relevant
22074 for this document. It then installs the necessary environment for RefTeX
22075 to work in this buffer and calls `reftex-citation' to insert a citation
22076 into the buffer.
22078 Export of such citations to both LaTeX and HTML is handled by the contributed
22079 package org-exp-bibtex by Taru Karttunen."
22080 (interactive)
22081 (let ((reftex-docstruct-symbol 'rds)
22082 (reftex-cite-format "\\cite{%l}")
22083 rds bib)
22084 (save-excursion
22085 (save-restriction
22086 (widen)
22087 (let ((case-fold-search t)
22088 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22089 (if (not (save-excursion
22090 (or (re-search-forward re nil t)
22091 (re-search-backward re nil t))))
22092 (error "No bibliography defined in file")
22093 (setq bib (concat (match-string 1) ".bib")
22094 rds (list (list 'bib bib)))))))
22095 (call-interactively 'reftex-citation)))
22097 ;;;; Functions extending outline functionality
22099 (defun org-beginning-of-line (&optional arg)
22100 "Go to the beginning of the current line. If that is invisible, continue
22101 to a visible line beginning. This makes the function of C-a more intuitive.
22102 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22103 first attempt, and only move to after the tags when the cursor is already
22104 beyond the end of the headline."
22105 (interactive "P")
22106 (let ((pos (point))
22107 (special (if (consp org-special-ctrl-a/e)
22108 (car org-special-ctrl-a/e)
22109 org-special-ctrl-a/e))
22110 refpos)
22111 (if (org-bound-and-true-p visual-line-mode)
22112 (beginning-of-visual-line 1)
22113 (beginning-of-line 1))
22114 (if (and arg (fboundp 'move-beginning-of-line))
22115 (call-interactively 'move-beginning-of-line)
22116 (if (bobp)
22118 (backward-char 1)
22119 (if (org-truely-invisible-p)
22120 (while (and (not (bobp)) (org-truely-invisible-p))
22121 (backward-char 1)
22122 (beginning-of-line 1))
22123 (forward-char 1))))
22124 (when special
22125 (cond
22126 ((and (looking-at org-complex-heading-regexp)
22127 (= (char-after (match-end 1)) ?\ ))
22128 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22129 (point-at-eol)))
22130 (goto-char
22131 (if (eq special t)
22132 (cond ((> pos refpos) refpos)
22133 ((= pos (point)) refpos)
22134 (t (point)))
22135 (cond ((> pos (point)) (point))
22136 ((not (eq last-command this-command)) (point))
22137 (t refpos)))))
22138 ((org-at-item-p)
22139 ;; Being at an item and not looking at an the item means point
22140 ;; was previously moved to beginning of a visual line, which
22141 ;; doesn't contain the item. Therefore, do nothing special,
22142 ;; just stay here.
22143 (when (looking-at org-list-full-item-re)
22144 ;; Set special position at first white space character after
22145 ;; bullet, and check-box, if any.
22146 (let ((after-bullet
22147 (let ((box (match-end 3)))
22148 (if (not box) (match-end 1)
22149 (let ((after (char-after box)))
22150 (if (and after (= after ? )) (1+ box) box))))))
22151 ;; Special case: Move point to special position when
22152 ;; currently after it or at beginning of line.
22153 (if (eq special t)
22154 (when (or (> pos after-bullet) (= (point) pos))
22155 (goto-char after-bullet))
22156 ;; Reversed case: Move point to special position when
22157 ;; point was already at beginning of line and command is
22158 ;; repeated.
22159 (when (and (= (point) pos) (eq last-command this-command))
22160 (goto-char after-bullet))))))))
22161 (org-no-warnings
22162 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22164 (defun org-end-of-line (&optional arg)
22165 "Go to the end of the line.
22166 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22167 tags on the first attempt, and only move to after the tags when
22168 the cursor is already beyond the end of the headline."
22169 (interactive "P")
22170 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22171 org-special-ctrl-a/e))
22172 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22173 'end-of-visual-line)
22174 ((fboundp 'move-end-of-line) 'move-end-of-line)
22175 (t 'end-of-line))))
22176 (if (or (not special) arg) (call-interactively move-fun)
22177 (let* ((element (save-excursion (beginning-of-line)
22178 (org-element-at-point)))
22179 (type (org-element-type element)))
22180 (cond
22181 ((memq type '(headline inlinetask))
22182 (let ((pos (point)))
22183 (beginning-of-line 1)
22184 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22185 (if (eq special t)
22186 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22187 (goto-char (match-beginning 1))
22188 (goto-char (match-end 0)))
22189 (if (or (< pos (match-end 0))
22190 (not (eq this-command last-command)))
22191 (goto-char (match-end 0))
22192 (goto-char (match-beginning 1))))
22193 (call-interactively move-fun))))
22194 ((org-element-property :hiddenp element)
22195 ;; If element is hidden, `move-end-of-line' would put point
22196 ;; after it. Use `end-of-line' to stay on current line.
22197 (call-interactively 'end-of-line))
22198 (t (call-interactively move-fun)))))
22199 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22201 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22202 (define-key org-mode-map "\C-e" 'org-end-of-line)
22204 (defun org-backward-sentence (&optional arg)
22205 "Go to beginning of sentence, or beginning of table field.
22206 This will call `backward-sentence' or `org-table-beginning-of-field',
22207 depending on context."
22208 (interactive "P")
22209 (cond
22210 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22211 (t (call-interactively 'backward-sentence))))
22213 (defun org-forward-sentence (&optional arg)
22214 "Go to end of sentence, or end of table field.
22215 This will call `forward-sentence' or `org-table-end-of-field',
22216 depending on context."
22217 (interactive "P")
22218 (cond
22219 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22220 (t (call-interactively 'forward-sentence))))
22222 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22223 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22225 (defun org-kill-line (&optional arg)
22226 "Kill line, to tags or end of line."
22227 (interactive "P")
22228 (cond
22229 ((or (not org-special-ctrl-k)
22230 (bolp)
22231 (not (org-at-heading-p)))
22232 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22233 org-ctrl-k-protect-subtree)
22234 (if (or (eq org-ctrl-k-protect-subtree 'error)
22235 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22236 (error "C-k aborted - would kill hidden subtree")))
22237 (call-interactively
22238 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22239 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22240 (kill-region (point) (match-beginning 1))
22241 (org-set-tags nil t))
22242 (t (kill-region (point) (point-at-eol)))))
22244 (define-key org-mode-map "\C-k" 'org-kill-line)
22246 (defun org-yank (&optional arg)
22247 "Yank. If the kill is a subtree, treat it specially.
22248 This command will look at the current kill and check if is a single
22249 subtree, or a series of subtrees[1]. If it passes the test, and if the
22250 cursor is at the beginning of a line or after the stars of a currently
22251 empty headline, then the yank is handled specially. How exactly depends
22252 on the value of the following variables, both set by default.
22254 org-yank-folded-subtrees
22255 When set, the subtree(s) will be folded after insertion, but only
22256 if doing so would now swallow text after the yanked text.
22258 org-yank-adjusted-subtrees
22259 When set, the subtree will be promoted or demoted in order to
22260 fit into the local outline tree structure, which means that the level
22261 will be adjusted so that it becomes the smaller one of the two
22262 *visible* surrounding headings.
22264 Any prefix to this command will cause `yank' to be called directly with
22265 no special treatment. In particular, a simple \\[universal-argument] prefix \
22266 will just
22267 plainly yank the text as it is.
22269 \[1] The test checks if the first non-white line is a heading
22270 and if there are no other headings with fewer stars."
22271 (interactive "P")
22272 (org-yank-generic 'yank arg))
22274 (defun org-yank-generic (command arg)
22275 "Perform some yank-like command.
22277 This function implements the behavior described in the `org-yank'
22278 documentation. However, it has been generalized to work for any
22279 interactive command with similar behavior."
22281 ;; pretend to be command COMMAND
22282 (setq this-command command)
22284 (if arg
22285 (call-interactively command)
22287 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22288 (and (org-kill-is-subtree-p)
22289 (or (bolp)
22290 (and (looking-at "[ \t]*$")
22291 (string-match
22292 "\\`\\*+\\'"
22293 (buffer-substring (point-at-bol) (point)))))))
22294 swallowp)
22295 (cond
22296 ((and subtreep org-yank-folded-subtrees)
22297 (let ((beg (point))
22298 end)
22299 (if (and subtreep org-yank-adjusted-subtrees)
22300 (org-paste-subtree nil nil 'for-yank)
22301 (call-interactively command))
22303 (setq end (point))
22304 (goto-char beg)
22305 (when (and (bolp) subtreep
22306 (not (setq swallowp
22307 (org-yank-folding-would-swallow-text beg end))))
22308 (org-with-limited-levels
22309 (or (looking-at org-outline-regexp)
22310 (re-search-forward org-outline-regexp-bol end t))
22311 (while (and (< (point) end) (looking-at org-outline-regexp))
22312 (hide-subtree)
22313 (org-cycle-show-empty-lines 'folded)
22314 (condition-case nil
22315 (outline-forward-same-level 1)
22316 (error (goto-char end))))))
22317 (when swallowp
22318 (message
22319 "Inserted text not folded because that would swallow text"))
22321 (goto-char end)
22322 (skip-chars-forward " \t\n\r")
22323 (beginning-of-line 1)
22324 (push-mark beg 'nomsg)))
22325 ((and subtreep org-yank-adjusted-subtrees)
22326 (let ((beg (point-at-bol)))
22327 (org-paste-subtree nil nil 'for-yank)
22328 (push-mark beg 'nomsg)))
22330 (call-interactively command))))))
22332 (defun org-yank-folding-would-swallow-text (beg end)
22333 "Would hide-subtree at BEG swallow any text after END?"
22334 (let (level)
22335 (org-with-limited-levels
22336 (save-excursion
22337 (goto-char beg)
22338 (when (or (looking-at org-outline-regexp)
22339 (re-search-forward org-outline-regexp-bol end t))
22340 (setq level (org-outline-level)))
22341 (goto-char end)
22342 (skip-chars-forward " \t\r\n\v\f")
22343 (if (or (eobp)
22344 (and (bolp) (looking-at org-outline-regexp)
22345 (<= (org-outline-level) level)))
22346 nil ; Nothing would be swallowed
22347 t))))) ; something would swallow
22349 (define-key org-mode-map "\C-y" 'org-yank)
22351 (defun org-truely-invisible-p ()
22352 "Check if point is at a character currently not visible.
22353 This version does not only check the character property, but also
22354 `visible-mode'."
22355 ;; Early versions of noutline don't have `outline-invisible-p'.
22356 (if (org-bound-and-true-p visible-mode)
22358 (outline-invisible-p)))
22360 (defun org-invisible-p2 ()
22361 "Check if point is at a character currently not visible."
22362 (save-excursion
22363 (if (and (eolp) (not (bobp))) (backward-char 1))
22364 ;; Early versions of noutline don't have `outline-invisible-p'.
22365 (outline-invisible-p)))
22367 (defun org-back-to-heading (&optional invisible-ok)
22368 "Call `outline-back-to-heading', but provide a better error message."
22369 (condition-case nil
22370 (outline-back-to-heading invisible-ok)
22371 (error (error "Before first headline at position %d in buffer %s"
22372 (point) (current-buffer)))))
22374 (defun org-before-first-heading-p ()
22375 "Before first heading?"
22376 (save-excursion
22377 (end-of-line)
22378 (null (re-search-backward org-outline-regexp-bol nil t))))
22380 (defun org-at-heading-p (&optional ignored)
22381 (outline-on-heading-p t))
22382 ;; Compatibility alias with Org versions < 7.8.03
22383 (defalias 'org-on-heading-p 'org-at-heading-p)
22385 (defun org-at-comment-p nil
22386 "Is cursor in a line starting with a # character?"
22387 (save-excursion
22388 (beginning-of-line)
22389 (looking-at "^#")))
22391 (defun org-at-drawer-p nil
22392 "Is cursor at a drawer keyword?"
22393 (save-excursion
22394 (move-beginning-of-line 1)
22395 (looking-at org-drawer-regexp)))
22397 (defun org-at-block-p nil
22398 "Is cursor at a block keyword?"
22399 (save-excursion
22400 (move-beginning-of-line 1)
22401 (looking-at org-block-regexp)))
22403 (defun org-point-at-end-of-empty-headline ()
22404 "If point is at the end of an empty headline, return t, else nil.
22405 If the heading only contains a TODO keyword, it is still still considered
22406 empty."
22407 (and (looking-at "[ \t]*$")
22408 (when org-todo-line-regexp
22409 (save-excursion
22410 (beginning-of-line 1)
22411 (let ((case-fold-search nil))
22412 (looking-at org-todo-line-regexp)
22413 (string= (match-string 3) ""))))))
22415 (defun org-at-heading-or-item-p ()
22416 (or (org-at-heading-p) (org-at-item-p)))
22418 (defun org-at-target-p ()
22419 (or (org-in-regexp org-radio-target-regexp)
22420 (org-in-regexp org-target-regexp)))
22421 ;; Compatibility alias with Org versions < 7.8.03
22422 (defalias 'org-on-target-p 'org-at-target-p)
22424 (defun org-up-heading-all (arg)
22425 "Move to the heading line of which the present line is a subheading.
22426 This function considers both visible and invisible heading lines.
22427 With argument, move up ARG levels."
22428 (if (fboundp 'outline-up-heading-all)
22429 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22430 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22432 (defun org-up-heading-safe ()
22433 "Move to the heading line of which the present line is a subheading.
22434 This version will not throw an error. It will return the level of the
22435 headline found, or nil if no higher level is found.
22437 Also, this function will be a lot faster than `outline-up-heading',
22438 because it relies on stars being the outline starters. This can really
22439 make a significant difference in outlines with very many siblings."
22440 (let (start-level re)
22441 (org-back-to-heading t)
22442 (setq start-level (funcall outline-level))
22443 (if (equal start-level 1)
22445 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22446 (if (re-search-backward re nil t)
22447 (funcall outline-level)))))
22449 (defun org-first-sibling-p ()
22450 "Is this heading the first child of its parents?"
22451 (interactive)
22452 (let ((re org-outline-regexp-bol)
22453 level l)
22454 (unless (org-at-heading-p t)
22455 (error "Not at a heading"))
22456 (setq level (funcall outline-level))
22457 (save-excursion
22458 (if (not (re-search-backward re nil t))
22460 (setq l (funcall outline-level))
22461 (< l level)))))
22463 (defun org-goto-sibling (&optional previous)
22464 "Goto the next sibling, even if it is invisible.
22465 When PREVIOUS is set, go to the previous sibling instead. Returns t
22466 when a sibling was found. When none is found, return nil and don't
22467 move point."
22468 (let ((fun (if previous 're-search-backward 're-search-forward))
22469 (pos (point))
22470 (re org-outline-regexp-bol)
22471 level l)
22472 (when (condition-case nil (org-back-to-heading t) (error nil))
22473 (setq level (funcall outline-level))
22474 (catch 'exit
22475 (or previous (forward-char 1))
22476 (while (funcall fun re nil t)
22477 (setq l (funcall outline-level))
22478 (when (< l level) (goto-char pos) (throw 'exit nil))
22479 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22480 (goto-char pos)
22481 nil))))
22483 (defun org-show-siblings ()
22484 "Show all siblings of the current headline."
22485 (save-excursion
22486 (while (org-goto-sibling) (org-flag-heading nil)))
22487 (save-excursion
22488 (while (org-goto-sibling 'previous)
22489 (org-flag-heading nil))))
22491 (defun org-goto-first-child ()
22492 "Goto the first child, even if it is invisible.
22493 Return t when a child was found. Otherwise don't move point and
22494 return nil."
22495 (let (level (pos (point)) (re org-outline-regexp-bol))
22496 (when (condition-case nil (org-back-to-heading t) (error nil))
22497 (setq level (outline-level))
22498 (forward-char 1)
22499 (if (and (re-search-forward re nil t) (> (outline-level) level))
22500 (progn (goto-char (match-beginning 0)) t)
22501 (goto-char pos) nil))))
22503 (defun org-show-hidden-entry ()
22504 "Show an entry where even the heading is hidden."
22505 (save-excursion
22506 (org-show-entry)))
22508 (defun org-flag-heading (flag &optional entry)
22509 "Flag the current heading. FLAG non-nil means make invisible.
22510 When ENTRY is non-nil, show the entire entry."
22511 (save-excursion
22512 (org-back-to-heading t)
22513 ;; Check if we should show the entire entry
22514 (if entry
22515 (progn
22516 (org-show-entry)
22517 (save-excursion
22518 (and (outline-next-heading)
22519 (org-flag-heading nil))))
22520 (outline-flag-region (max (point-min) (1- (point)))
22521 (save-excursion (outline-end-of-heading) (point))
22522 flag))))
22524 (defun org-get-next-sibling ()
22525 "Move to next heading of the same level, and return point.
22526 If there is no such heading, return nil.
22527 This is like outline-next-sibling, but invisible headings are ok."
22528 (let ((level (funcall outline-level)))
22529 (outline-next-heading)
22530 (while (and (not (eobp)) (> (funcall outline-level) level))
22531 (outline-next-heading))
22532 (if (or (eobp) (< (funcall outline-level) level))
22534 (point))))
22536 (defun org-get-last-sibling ()
22537 "Move to previous heading of the same level, and return point.
22538 If there is no such heading, return nil."
22539 (let ((opoint (point))
22540 (level (funcall outline-level)))
22541 (outline-previous-heading)
22542 (when (and (/= (point) opoint) (outline-on-heading-p t))
22543 (while (and (> (funcall outline-level) level)
22544 (not (bobp)))
22545 (outline-previous-heading))
22546 (if (< (funcall outline-level) level)
22548 (point)))))
22550 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22551 "Goto to the end of a subtree."
22552 ;; This contains an exact copy of the original function, but it uses
22553 ;; `org-back-to-heading', to make it work also in invisible
22554 ;; trees. And is uses an invisible-ok argument.
22555 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22556 ;; Furthermore, when used inside Org, finding the end of a large subtree
22557 ;; with many children and grandchildren etc, this can be much faster
22558 ;; than the outline version.
22559 (org-back-to-heading invisible-ok)
22560 (let ((first t)
22561 (level (funcall outline-level)))
22562 (if (and (derived-mode-p 'org-mode) (< level 1000))
22563 ;; A true heading (not a plain list item), in Org-mode
22564 ;; This means we can easily find the end by looking
22565 ;; only for the right number of stars. Using a regexp to do
22566 ;; this is so much faster than using a Lisp loop.
22567 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22568 (forward-char 1)
22569 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22570 ;; something else, do it the slow way
22571 (while (and (not (eobp))
22572 (or first (> (funcall outline-level) level)))
22573 (setq first nil)
22574 (outline-next-heading)))
22575 (unless to-heading
22576 (if (memq (preceding-char) '(?\n ?\^M))
22577 (progn
22578 ;; Go to end of line before heading
22579 (forward-char -1)
22580 (if (memq (preceding-char) '(?\n ?\^M))
22581 ;; leave blank line before heading
22582 (forward-char -1))))))
22583 (point))
22585 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22586 "Use Org version in org-mode, for dramatic speed-up."
22587 (if (derived-mode-p 'org-mode)
22588 (progn
22589 (org-end-of-subtree nil t)
22590 (unless (eobp) (backward-char 1)))
22591 ad-do-it))
22593 (defun org-end-of-meta-data-and-drawers ()
22594 "Jump to the first text after meta data and drawers in the current entry.
22595 This will move over empty lines, lines with planning time stamps,
22596 clocking lines, and drawers."
22597 (org-back-to-heading t)
22598 (let ((end (save-excursion (outline-next-heading) (point)))
22599 (re (concat "\\(" org-drawer-regexp "\\)"
22600 "\\|" "[ \t]*" org-keyword-time-regexp)))
22601 (forward-line 1)
22602 (while (re-search-forward re end t)
22603 (if (not (match-end 1))
22604 ;; empty or planning line
22605 (forward-line 1)
22606 ;; a drawer, find the end
22607 (re-search-forward "^[ \t]*:END:" end 'move)
22608 (forward-line 1)))
22609 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22610 (point)))
22612 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22613 "Move forward to the ARG'th subheading at same level as this one.
22614 Stop at the first and last subheadings of a superior heading.
22615 Normally this only looks at visible headings, but when INVISIBLE-OK is
22616 non-nil it will also look at invisible ones."
22617 (interactive "p")
22618 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22619 (if (and arg (< arg 0))
22620 (goto-char (point-min))
22621 (outline-next-heading))
22622 (org-at-heading-p)
22623 (let ((level (- (match-end 0) (match-beginning 0) 1))
22624 (f (if (and arg (< arg 0))
22625 're-search-backward
22626 're-search-forward))
22627 (count (if arg (abs arg) 1))
22628 (result (point)))
22629 (forward-char (if (and arg (< arg 0)) -1 1))
22630 (while (and (> count 0)
22631 (funcall f org-outline-regexp-bol nil 'move))
22632 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22633 (cond ((< l level) (setq count 0))
22634 ((and (= l level)
22635 (or invisible-ok
22636 (progn
22637 (goto-char (line-beginning-position))
22638 (not (outline-invisible-p)))))
22639 (setq count (1- count))
22640 (when (eq l level)
22641 (setq result (point)))))))
22642 (goto-char result))
22643 (beginning-of-line 1)))
22645 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22646 "Move backward to the ARG'th subheading at same level as this one.
22647 Stop at the first and last subheadings of a superior heading."
22648 (interactive "p")
22649 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22651 (defun org-next-block (arg &optional backward block-regexp)
22652 "Jump to the next block.
22653 With a prefix argument ARG, jump forward ARG many source blocks.
22654 When BACKWARD is non-nil, jump to the previous block.
22655 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22656 (interactive "p")
22657 (let ((re (or block-regexp org-block-regexp))
22658 (re-search-fn (or (and backward 're-search-backward)
22659 're-search-forward)))
22660 (if (looking-at re) (forward-char 1))
22661 (condition-case nil
22662 (funcall re-search-fn re nil nil arg)
22663 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22664 (goto-char (match-beginning 0)) (org-show-context)))
22666 (defun org-previous-block (arg &optional block-regexp)
22667 "Jump to the previous block.
22668 With a prefix argument ARG, jump backward ARG many source blocks.
22669 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22670 (interactive "p")
22671 (org-next-block arg t block-regexp))
22673 (defun org-forward-element ()
22674 "Move forward by one element.
22675 Move to the next element at the same level, when possible."
22676 (interactive)
22677 (cond ((eobp) (error "Cannot move further down"))
22678 ((org-with-limited-levels (org-at-heading-p))
22679 (let ((origin (point)))
22680 (goto-char (org-end-of-subtree nil t))
22681 (unless (org-with-limited-levels (org-at-heading-p))
22682 (goto-char origin)
22683 (error "Cannot move further down"))))
22685 (let* ((elem (org-element-at-point))
22686 (end (org-element-property :end elem))
22687 (parent (org-element-property :parent elem)))
22688 (if (and parent (= (org-element-property :contents-end parent) end))
22689 (goto-char (org-element-property :end parent))
22690 (goto-char end))))))
22692 (defun org-backward-element ()
22693 "Move backward by one element.
22694 Move to the previous element at the same level, when possible."
22695 (interactive)
22696 (cond ((bobp) (error "Cannot move further up"))
22697 ((org-with-limited-levels (org-at-heading-p))
22698 ;; At an headline, move to the previous one, if any, or stay
22699 ;; here.
22700 (let ((origin (point)))
22701 (org-with-limited-levels (org-backward-heading-same-level 1))
22702 ;; When current headline has no sibling above, move to its
22703 ;; parent.
22704 (when (= (point) origin)
22705 (or (org-with-limited-levels (org-up-heading-safe))
22706 (progn (goto-char origin)
22707 (error "Cannot move further up"))))))
22709 (let* ((trail (org-element-at-point 'keep-trail))
22710 (elem (car trail))
22711 (prev-elem (nth 1 trail))
22712 (beg (org-element-property :begin elem)))
22713 (cond
22714 ;; Move to beginning of current element if point isn't
22715 ;; there already.
22716 ((/= (point) beg) (goto-char beg))
22717 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22718 ((org-before-first-heading-p) (goto-char (point-min)))
22719 (t (org-back-to-heading)))))))
22721 (defun org-up-element ()
22722 "Move to upper element."
22723 (interactive)
22724 (if (org-with-limited-levels (org-at-heading-p))
22725 (unless (org-up-heading-safe) (error "No surrounding element"))
22726 (let* ((elem (org-element-at-point))
22727 (parent (org-element-property :parent elem)))
22728 (if parent (goto-char (org-element-property :begin parent))
22729 (if (org-with-limited-levels (org-before-first-heading-p))
22730 (error "No surrounding element")
22731 (org-with-limited-levels (org-back-to-heading)))))))
22733 (defvar org-element-greater-elements)
22734 (defun org-down-element ()
22735 "Move to inner element."
22736 (interactive)
22737 (let ((element (org-element-at-point)))
22738 (cond
22739 ((memq (org-element-type element) '(plain-list table))
22740 (goto-char (org-element-property :contents-begin element))
22741 (forward-char))
22742 ((memq (org-element-type element) org-element-greater-elements)
22743 ;; If contents are hidden, first disclose them.
22744 (when (org-element-property :hiddenp element) (org-cycle))
22745 (goto-char (or (org-element-property :contents-begin element)
22746 (error "No content for this element"))))
22747 (t (error "No inner element")))))
22749 (defun org-drag-element-backward ()
22750 "Move backward element at point."
22751 (interactive)
22752 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22753 (let* ((trail (org-element-at-point 'keep-trail))
22754 (elem (car trail))
22755 (prev-elem (nth 1 trail)))
22756 ;; Error out if no previous element or previous element is
22757 ;; a parent of the current one.
22758 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22759 (error "Cannot drag element backward")
22760 (let ((pos (point)))
22761 (org-element-swap-A-B prev-elem elem)
22762 (goto-char (+ (org-element-property :begin prev-elem)
22763 (- pos (org-element-property :begin elem)))))))))
22765 (defun org-drag-element-forward ()
22766 "Move forward element at point."
22767 (interactive)
22768 (let* ((pos (point))
22769 (elem (org-element-at-point)))
22770 (when (= (point-max) (org-element-property :end elem))
22771 (error "Cannot drag element forward"))
22772 (goto-char (org-element-property :end elem))
22773 (let ((next-elem (org-element-at-point)))
22774 (when (or (org-element-nested-p elem next-elem)
22775 (and (eq (org-element-type next-elem) 'headline)
22776 (not (eq (org-element-type elem) 'headline))))
22777 (goto-char pos)
22778 (error "Cannot drag element forward"))
22779 ;; Compute new position of point: it's shifted by NEXT-ELEM
22780 ;; body's length (without final blanks) and by the length of
22781 ;; blanks between ELEM and NEXT-ELEM.
22782 (let ((size-next (- (save-excursion
22783 (goto-char (org-element-property :end next-elem))
22784 (skip-chars-backward " \r\t\n")
22785 (forward-line)
22786 ;; Small correction if buffer doesn't end
22787 ;; with a newline character.
22788 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22789 (org-element-property :begin next-elem)))
22790 (size-blank (- (org-element-property :end elem)
22791 (save-excursion
22792 (goto-char (org-element-property :end elem))
22793 (skip-chars-backward " \r\t\n")
22794 (forward-line)
22795 (point)))))
22796 (org-element-swap-A-B elem next-elem)
22797 (goto-char (+ pos size-next size-blank))))))
22799 (defun org-drag-line-forward (arg)
22800 "Drag the line at point ARG lines forward."
22801 (interactive "p")
22802 (dotimes (n (abs arg))
22803 (let ((c (current-column)))
22804 (if (< 0 arg)
22805 (progn
22806 (beginning-of-line 2)
22807 (transpose-lines 1)
22808 (beginning-of-line 0))
22809 (transpose-lines 1)
22810 (beginning-of-line -1))
22811 (org-move-to-column c))))
22813 (defun org-drag-line-backward (arg)
22814 "Drag the line at point ARG lines backward."
22815 (interactive "p")
22816 (org-drag-line-forward (- arg)))
22818 (defun org-mark-element ()
22819 "Put point at beginning of this element, mark at end.
22821 Interactively, if this command is repeated or (in Transient Mark
22822 mode) if the mark is active, it marks the next element after the
22823 ones already marked."
22824 (interactive)
22825 (let (deactivate-mark)
22826 (if (and (org-called-interactively-p 'any)
22827 (or (and (eq last-command this-command) (mark t))
22828 (and transient-mark-mode mark-active)))
22829 (set-mark
22830 (save-excursion
22831 (goto-char (mark))
22832 (goto-char (org-element-property :end (org-element-at-point)))))
22833 (let ((element (org-element-at-point)))
22834 (end-of-line)
22835 (push-mark (org-element-property :end element) t t)
22836 (goto-char (org-element-property :begin element))))))
22838 (defun org-narrow-to-element ()
22839 "Narrow buffer to current element."
22840 (interactive)
22841 (let ((elem (org-element-at-point)))
22842 (cond
22843 ((eq (car elem) 'headline)
22844 (narrow-to-region
22845 (org-element-property :begin elem)
22846 (org-element-property :end elem)))
22847 ((memq (car elem) org-element-greater-elements)
22848 (narrow-to-region
22849 (org-element-property :contents-begin elem)
22850 (org-element-property :contents-end elem)))
22852 (narrow-to-region
22853 (org-element-property :begin elem)
22854 (org-element-property :end elem))))))
22856 (defun org-transpose-element ()
22857 "Transpose current and previous elements, keeping blank lines between.
22858 Point is moved after both elements."
22859 (interactive)
22860 (org-skip-whitespace)
22861 (let ((end (org-element-property :end (org-element-at-point))))
22862 (org-drag-element-backward)
22863 (goto-char end)))
22865 (defun org-unindent-buffer ()
22866 "Un-indent the visible part of the buffer.
22867 Relative indentation (between items, inside blocks, etc.) isn't
22868 modified."
22869 (interactive)
22870 (unless (eq major-mode 'org-mode)
22871 (error "Cannot un-indent a buffer not in Org mode"))
22872 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22873 unindent-tree ; For byte-compiler.
22874 (unindent-tree
22875 (function
22876 (lambda (contents)
22877 (mapc
22878 (lambda (element)
22879 (if (memq (org-element-type element) '(headline section))
22880 (funcall unindent-tree (org-element-contents element))
22881 (save-excursion
22882 (save-restriction
22883 (narrow-to-region
22884 (org-element-property :begin element)
22885 (org-element-property :end element))
22886 (org-do-remove-indentation)))))
22887 (reverse contents))))))
22888 (funcall unindent-tree (org-element-contents parse-tree))))
22890 (defun org-show-subtree ()
22891 "Show everything after this heading at deeper levels."
22892 (interactive)
22893 (outline-flag-region
22894 (point)
22895 (save-excursion
22896 (org-end-of-subtree t t))
22897 nil))
22899 (defun org-show-entry ()
22900 "Show the body directly following this heading.
22901 Show the heading too, if it is currently invisible."
22902 (interactive)
22903 (save-excursion
22904 (condition-case nil
22905 (progn
22906 (org-back-to-heading t)
22907 (outline-flag-region
22908 (max (point-min) (1- (point)))
22909 (save-excursion
22910 (if (re-search-forward
22911 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22912 (match-beginning 1)
22913 (point-max)))
22914 nil)
22915 (org-cycle-hide-drawers 'children))
22916 (error nil))))
22918 (defun org-make-options-regexp (kwds &optional extra)
22919 "Make a regular expression for keyword lines."
22920 (concat
22921 "^#\\+\\("
22922 (mapconcat 'regexp-quote kwds "\\|")
22923 (if extra (concat "\\|" extra))
22924 "\\):[ \t]*\\(.*\\)"))
22926 ;; Make isearch reveal the necessary context
22927 (defun org-isearch-end ()
22928 "Reveal context after isearch exits."
22929 (when isearch-success ; only if search was successful
22930 (if (featurep 'xemacs)
22931 ;; Under XEmacs, the hook is run in the correct place,
22932 ;; we directly show the context.
22933 (org-show-context 'isearch)
22934 ;; In Emacs the hook runs *before* restoring the overlays.
22935 ;; So we have to use a one-time post-command-hook to do this.
22936 ;; (Emacs 22 has a special variable, see function `org-mode')
22937 (unless (and (boundp 'isearch-mode-end-hook-quit)
22938 isearch-mode-end-hook-quit)
22939 ;; Only when the isearch was not quitted.
22940 (org-add-hook 'post-command-hook 'org-isearch-post-command
22941 'append 'local)))))
22943 (defun org-isearch-post-command ()
22944 "Remove self from hook, and show context."
22945 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22946 (org-show-context 'isearch))
22949 ;;;; Integration with and fixes for other packages
22951 ;;; Imenu support
22953 (defvar org-imenu-markers nil
22954 "All markers currently used by Imenu.")
22955 (make-variable-buffer-local 'org-imenu-markers)
22957 (defun org-imenu-new-marker (&optional pos)
22958 "Return a new marker for use by Imenu, and remember the marker."
22959 (let ((m (make-marker)))
22960 (move-marker m (or pos (point)))
22961 (push m org-imenu-markers)
22964 (defun org-imenu-get-tree ()
22965 "Produce the index for Imenu."
22966 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22967 (setq org-imenu-markers nil)
22968 (let* ((n org-imenu-depth)
22969 (re (concat "^" (org-get-limited-outline-regexp)))
22970 (subs (make-vector (1+ n) nil))
22971 (last-level 0)
22972 m level head)
22973 (save-excursion
22974 (save-restriction
22975 (widen)
22976 (goto-char (point-max))
22977 (while (re-search-backward re nil t)
22978 (setq level (org-reduced-level (funcall outline-level)))
22979 (when (and (<= level n)
22980 (looking-at org-complex-heading-regexp))
22981 (setq head (org-link-display-format
22982 (org-match-string-no-properties 4))
22983 m (org-imenu-new-marker))
22984 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22985 (if (>= level last-level)
22986 (push (cons head m) (aref subs level))
22987 (push (cons head (aref subs (1+ level))) (aref subs level))
22988 (loop for i from (1+ level) to n do (aset subs i nil)))
22989 (setq last-level level)))))
22990 (aref subs 1)))
22992 (eval-after-load "imenu"
22993 '(progn
22994 (add-hook 'imenu-after-jump-hook
22995 (lambda ()
22996 (if (derived-mode-p 'org-mode)
22997 (org-show-context 'org-goto))))))
22999 (defun org-link-display-format (link)
23000 "Replace a link with either the description, or the link target
23001 if no description is present"
23002 (save-match-data
23003 (if (string-match org-bracket-link-analytic-regexp link)
23004 (replace-match (if (match-end 5)
23005 (match-string 5 link)
23006 (concat (match-string 1 link)
23007 (match-string 3 link)))
23008 nil t link)
23009 link)))
23011 (defun org-toggle-link-display ()
23012 "Toggle the literal or descriptive display of links."
23013 (interactive)
23014 (if org-descriptive-links
23015 (progn (org-remove-from-invisibility-spec '(org-link))
23016 (org-restart-font-lock)
23017 (setq org-descriptive-links nil))
23018 (progn (add-to-invisibility-spec '(org-link))
23019 (org-restart-font-lock)
23020 (setq org-descriptive-links t))))
23022 ;; Speedbar support
23024 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23025 "Overlay marking the agenda restriction line in speedbar.")
23026 (overlay-put org-speedbar-restriction-lock-overlay
23027 'face 'org-agenda-restriction-lock)
23028 (overlay-put org-speedbar-restriction-lock-overlay
23029 'help-echo "Agendas are currently limited to this item.")
23030 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23032 (defun org-speedbar-set-agenda-restriction ()
23033 "Restrict future agenda commands to the location at point in speedbar.
23034 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23035 (interactive)
23036 (require 'org-agenda)
23037 (let (p m tp np dir txt)
23038 (cond
23039 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23040 'org-imenu t))
23041 (setq m (get-text-property p 'org-imenu-marker))
23042 (with-current-buffer (marker-buffer m)
23043 (goto-char m)
23044 (org-agenda-set-restriction-lock 'subtree)))
23045 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23046 'speedbar-function 'speedbar-find-file))
23047 (setq tp (previous-single-property-change
23048 (1+ p) 'speedbar-function)
23049 np (next-single-property-change
23050 tp 'speedbar-function)
23051 dir (speedbar-line-directory)
23052 txt (buffer-substring-no-properties (or tp (point-min))
23053 (or np (point-max))))
23054 (with-current-buffer (find-file-noselect
23055 (let ((default-directory dir))
23056 (expand-file-name txt)))
23057 (unless (derived-mode-p 'org-mode)
23058 (error "Cannot restrict to non-Org-mode file"))
23059 (org-agenda-set-restriction-lock 'file)))
23060 (t (error "Don't know how to restrict Org-mode's agenda")))
23061 (move-overlay org-speedbar-restriction-lock-overlay
23062 (point-at-bol) (point-at-eol))
23063 (setq current-prefix-arg nil)
23064 (org-agenda-maybe-redo)))
23066 (eval-after-load "speedbar"
23067 '(progn
23068 (speedbar-add-supported-extension ".org")
23069 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23070 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23071 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23072 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23073 (add-hook 'speedbar-visiting-tag-hook
23074 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23076 ;;; Fixes and Hacks for problems with other packages
23078 ;; Make flyspell not check words in links, to not mess up our keymap
23079 (defvar org-element-affiliated-keywords) ; From org-element.el
23080 (defvar org-element-block-name-alist) ; From org-element.el
23081 (defun org-mode-flyspell-verify ()
23082 "Don't let flyspell put overlays at active buttons, or on
23083 {todo,all-time,additional-option-like}-keywords."
23084 (let ((pos (max (1- (point)) (point-min)))
23085 (word (thing-at-point 'word)))
23086 (and (not (get-text-property pos 'keymap))
23087 (not (get-text-property pos 'org-no-flyspell))
23088 (not (member word org-todo-keywords-1))
23089 (not (member word org-all-time-keywords))
23090 (not (member word org-options-keywords))
23091 (not (member word (mapcar 'car org-startup-options)))
23092 (not (member-ignore-case word org-element-affiliated-keywords))
23093 (not (member-ignore-case word (org-get-export-keywords)))
23094 (not (member-ignore-case
23095 word (mapcar 'car org-element-block-name-alist)))
23096 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23098 (defun org-remove-flyspell-overlays-in (beg end)
23099 "Remove flyspell overlays in region."
23100 (and (org-bound-and-true-p flyspell-mode)
23101 (fboundp 'flyspell-delete-region-overlays)
23102 (flyspell-delete-region-overlays beg end))
23103 (add-text-properties beg end '(org-no-flyspell t)))
23105 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23106 (eval-after-load "bookmark"
23107 '(if (boundp 'bookmark-after-jump-hook)
23108 ;; We can use the hook
23109 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23110 ;; Hook not available, use advice
23111 (defadvice bookmark-jump (after org-make-visible activate)
23112 "Make the position visible."
23113 (org-bookmark-jump-unhide))))
23115 ;; Make sure saveplace shows the location if it was hidden
23116 (eval-after-load "saveplace"
23117 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23118 "Make the position visible."
23119 (org-bookmark-jump-unhide)))
23121 ;; Make sure ecb shows the location if it was hidden
23122 (eval-after-load "ecb"
23123 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23124 "Make hierarchy visible when jumping into location from ECB tree buffer."
23125 (if (derived-mode-p 'org-mode)
23126 (org-show-context))))
23128 (defun org-bookmark-jump-unhide ()
23129 "Unhide the current position, to show the bookmark location."
23130 (and (derived-mode-p 'org-mode)
23131 (or (outline-invisible-p)
23132 (save-excursion (goto-char (max (point-min) (1- (point))))
23133 (outline-invisible-p)))
23134 (org-show-context 'bookmark-jump)))
23136 ;; Make session.el ignore our circular variable
23137 (eval-after-load "session"
23138 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23140 ;;;; Experimental code
23142 (defun org-closed-in-range ()
23143 "Sparse tree of items closed in a certain time range.
23144 Still experimental, may disappear in the future."
23145 (interactive)
23146 ;; Get the time interval from the user.
23147 (let* ((time1 (org-float-time
23148 (org-read-date nil 'to-time nil "Starting date: ")))
23149 (time2 (org-float-time
23150 (org-read-date nil 'to-time nil "End date:")))
23151 ;; callback function
23152 (callback (lambda ()
23153 (let ((time
23154 (org-float-time
23155 (apply 'encode-time
23156 (org-parse-time-string
23157 (match-string 1))))))
23158 ;; check if time in interval
23159 (and (>= time time1) (<= time time2))))))
23160 ;; make tree, check each match with the callback
23161 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23163 ;;;; Finish up
23165 (provide 'org)
23167 (run-hooks 'org-load-hook)
23169 ;;; org.el ends here