org-agenda.el (org-agenda-write): Don't copy headlines' subtrees when writing to...
[org-mode.git] / lisp / org.el
blob4b649a0003059ae8f32e3fa2f766825e610f9e28
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 (autoload 'org-element-at-point "org-element")
141 (autoload 'org-element-type "org-element")
143 (declare-function org-element--parse-objects "org-element"
144 (beg end acc restriction))
145 (declare-function org-element-at-point "org-element" (&optional keep-trail))
146 (declare-function org-element-contents "org-element" (element))
147 (declare-function org-element-context "org-element" (&optional element))
148 (declare-function org-element-interpret-data "org-element"
149 (data &optional parent))
150 (declare-function org-element-map "org-element"
151 (data types fun &optional info first-match no-recursion))
152 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
153 (declare-function org-element-parse-buffer "org-element"
154 (&optional granularity visible-only))
155 (declare-function org-element-property "org-element" (property element))
156 (declare-function org-element-put-property "org-element"
157 (element property value))
158 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
159 (declare-function org-element--parse-objects "org-element"
160 (beg end acc restriction))
161 (declare-function org-element-parse-buffer "org-element"
162 (&optional granularity visible-only))
163 (declare-function org-element-interpret-data "org-element"
164 (data &optional parent))
166 ;; load languages based on value of `org-babel-load-languages'
167 (defvar org-babel-load-languages)
169 ;;;###autoload
170 (defun org-babel-do-load-languages (sym value)
171 "Load the languages defined in `org-babel-load-languages'."
172 (set-default sym value)
173 (mapc (lambda (pair)
174 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
175 (if active
176 (progn
177 (require (intern (concat "ob-" lang))))
178 (progn
179 (funcall 'fmakunbound
180 (intern (concat "org-babel-execute:" lang)))
181 (funcall 'fmakunbound
182 (intern (concat "org-babel-expand-body:" lang)))))))
183 org-babel-load-languages))
185 (defcustom org-babel-load-languages '((emacs-lisp . t))
186 "Languages which can be evaluated in Org-mode buffers.
187 This list can be used to load support for any of the languages
188 below, note that each language will depend on a different set of
189 system executables and/or Emacs modes. When a language is
190 \"loaded\", then code blocks in that language can be evaluated
191 with `org-babel-execute-src-block' bound by default to C-c
192 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
193 be set to remove code block evaluation from the C-c C-c
194 keybinding. By default only Emacs Lisp (which has no
195 requirements) is loaded."
196 :group 'org-babel
197 :set 'org-babel-do-load-languages
198 :version "24.1"
199 :type '(alist :tag "Babel Languages"
200 :key-type
201 (choice
202 (const :tag "Awk" awk)
203 (const :tag "C" C)
204 (const :tag "R" R)
205 (const :tag "Asymptote" asymptote)
206 (const :tag "Calc" calc)
207 (const :tag "Clojure" clojure)
208 (const :tag "CSS" css)
209 (const :tag "Ditaa" ditaa)
210 (const :tag "Dot" dot)
211 (const :tag "Emacs Lisp" emacs-lisp)
212 (const :tag "Fortran" fortran)
213 (const :tag "Gnuplot" gnuplot)
214 (const :tag "Haskell" haskell)
215 (const :tag "IO" io)
216 (const :tag "Java" java)
217 (const :tag "Javascript" js)
218 (const :tag "LaTeX" latex)
219 (const :tag "Ledger" ledger)
220 (const :tag "Lilypond" lilypond)
221 (const :tag "Lisp" lisp)
222 (const :tag "Makefile" makefile)
223 (const :tag "Maxima" maxima)
224 (const :tag "Matlab" matlab)
225 (const :tag "Mscgen" mscgen)
226 (const :tag "Ocaml" ocaml)
227 (const :tag "Octave" octave)
228 (const :tag "Org" org)
229 (const :tag "Perl" perl)
230 (const :tag "Pico Lisp" picolisp)
231 (const :tag "PlantUML" plantuml)
232 (const :tag "Python" python)
233 (const :tag "Ruby" ruby)
234 (const :tag "Sass" sass)
235 (const :tag "Scala" scala)
236 (const :tag "Scheme" scheme)
237 (const :tag "Screen" screen)
238 (const :tag "Shell Script" sh)
239 (const :tag "Shen" shen)
240 (const :tag "Sql" sql)
241 (const :tag "Sqlite" sqlite))
242 :value-type (boolean :tag "Activate" :value t)))
244 ;;;; Customization variables
245 (defcustom org-clone-delete-id nil
246 "Remove ID property of clones of a subtree.
247 When non-nil, clones of a subtree don't inherit the ID property.
248 Otherwise they inherit the ID property with a new unique
249 identifier."
250 :type 'boolean
251 :version "24.1"
252 :group 'org-id)
254 ;;; Version
255 (org-check-version)
257 ;;;###autoload
258 (defun org-version (&optional here full message)
259 "Show the org-mode version in the echo area.
260 With prefix argument HERE, insert it at point.
261 When FULL is non-nil, use a verbose version string.
262 When MESSAGE is non-nil, display a message with the version."
263 (interactive "P")
264 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
265 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
266 (load-suffixes (list ".el"))
267 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
268 (org-trash (or
269 (and (fboundp 'org-release) (fboundp 'org-git-version))
270 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
271 (load-suffixes save-load-suffixes)
272 (org-version (org-release))
273 (git-version (org-git-version))
274 (version (format "Org-mode version %s (%s @ %s)"
275 org-version
276 git-version
277 (if org-install-dir
278 (if (string= org-dir org-install-dir)
279 org-install-dir
280 (concat "mixed installation! " org-install-dir " and " org-dir))
281 "org-loaddefs.el can not be found!")))
282 (_version (if full version org-version)))
283 (if (org-called-interactively-p 'interactive)
284 (if here
285 (insert version)
286 (message version))
287 (if message (message _version))
288 _version)))
290 (defconst org-version (org-version))
292 ;;; Compatibility constants
294 ;;; The custom variables
296 (defgroup org nil
297 "Outline-based notes management and organizer."
298 :tag "Org"
299 :group 'outlines
300 :group 'calendar)
302 (defcustom org-mode-hook nil
303 "Mode hook for Org-mode, run after the mode was turned on."
304 :group 'org
305 :type 'hook)
307 (defcustom org-load-hook nil
308 "Hook that is run after org.el has been loaded."
309 :group 'org
310 :type 'hook)
312 (defcustom org-log-buffer-setup-hook nil
313 "Hook that is run after an Org log buffer is created."
314 :group 'org
315 :version "24.1"
316 :type 'hook)
318 (defvar org-modules) ; defined below
319 (defvar org-modules-loaded nil
320 "Have the modules been loaded already?")
322 (defun org-load-modules-maybe (&optional force)
323 "Load all extensions listed in `org-modules'."
324 (when (or force (not org-modules-loaded))
325 (mapc (lambda (ext)
326 (condition-case nil (require ext)
327 (error (message "Problems while trying to load feature `%s'" ext))))
328 org-modules)
329 (setq org-modules-loaded t)))
331 (defun org-set-modules (var value)
332 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
333 (set var value)
334 (when (featurep 'org)
335 (org-load-modules-maybe 'force)))
337 (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)
338 "Modules that should always be loaded together with org.el.
340 If a description starts with <C>, the file is not part of Emacs
341 and loading it will require that you have downloaded and properly
342 installed the Org mode distribution.
344 You can also use this system to load external packages (i.e. neither Org
345 core modules, nor modules from the CONTRIB directory). Just add symbols
346 to the end of the list. If the package is called org-xyz.el, then you need
347 to add the symbol `xyz', and the package must have a call to:
349 \(provide 'org-xyz)
351 For export specific modules, see also `org-export-backends'."
352 :group 'org
353 :set 'org-set-modules
354 :type
355 '(set :greedy t
356 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
357 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
358 (const :tag " crypt: Encryption of subtrees" org-crypt)
359 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
360 (const :tag " docview: Links to doc-view buffers" org-docview)
361 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
362 (const :tag " id: Global IDs for identifying entries" org-id)
363 (const :tag " info: Links to Info nodes" org-info)
364 (const :tag " habit: Track your consistency with habits" org-habit)
365 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
366 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
367 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
368 (const :tag " mew Links to Mew folders/messages" org-mew)
369 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
370 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
371 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
372 (const :tag " vm: Links to VM folders/messages" org-vm)
373 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
374 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
375 (const :tag " mouse: Additional mouse support" org-mouse)
377 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
378 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
379 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
380 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
381 (const :tag "C collector: Collect properties into tables" org-collector)
382 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
383 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
384 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
385 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
386 (const :tag "C eval: Include command output as text" org-eval)
387 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
388 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
389 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
390 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
391 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
393 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
395 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
396 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
397 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
398 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
399 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
400 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
401 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
402 (const :tag "C mtags: Support for muse-like tags" org-mtags)
403 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
404 (const :tag "C registry: A registry for Org-mode links" org-registry)
405 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
406 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
407 (const :tag "C secretary: Team management with org-mode" org-secretary)
408 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
409 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
410 (const :tag "C track: Keep up with Org-mode development" org-track)
411 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
412 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
413 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
415 (defvar org-export-registered-backends) ; From ox.el
416 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
417 (defcustom org-export-backends '(ascii html icalendar latex)
418 "List of export back-ends that should be always available.
420 If a description starts with <C>, the file is not part of Emacs
421 and loading it will require that you have downloaded and properly
422 installed the Org mode distribution.
424 Unlike to `org-modules', libraries in this list will not be
425 loaded along with Org, but only once the export framework is
426 needed.
428 This variable needs to be set before org.el is loaded. If you
429 need to make a change while Emacs is running, use the customize
430 interface or run the following code, , where VALUE stands for the
431 new value of the variable, after updating it:
433 \(progn
434 \(setq org-export-registered-backends
435 \(org-remove-if-not
436 \(lambda (backend)
437 \(or (memq backend val)
438 \(catch 'parentp
439 \(mapc
440 \(lambda (b)
441 \(and (org-export-derived-backend-p b (car backend))
442 \(throw 'parentp t)))
443 val)
444 nil)))
445 org-export-registered-backends))
446 \(let ((new-list (mapcar 'car org-export-registered-backends)))
447 \(dolist (backend val)
448 \(cond
449 \((not (load (format \"ox-%s\" backend) t t))
450 \(message \"Problems while trying to load export back-end `%s'\"
451 backend))
452 \((not (memq backend new-list)) (push backend new-list))))
453 \(set-default var new-list)))
455 Adding a back-end to this list will also pull the back-end it
456 depends on, if any."
457 :group 'org
458 :group 'org-export
459 :set (lambda (var val)
460 (if (not (featurep 'ox)) (set-default var val)
461 ;; Any back-end not required anymore (not present in VAL and not
462 ;; a parent of any back-end in the new value) is removed from the
463 ;; list of registered back-ends.
464 (setq org-export-registered-backends
465 (org-remove-if-not
466 (lambda (backend)
467 (or (memq backend val)
468 (catch 'parentp
469 (mapc
470 (lambda (b)
471 (and (org-export-derived-backend-p b (car backend))
472 (throw 'parentp t)))
473 val)
474 nil)))
475 org-export-registered-backends))
476 ;; Now build NEW-LIST of both new back-ends and required
477 ;; parents.
478 (let ((new-list (mapcar 'car org-export-registered-backends)))
479 (dolist (backend val)
480 (cond
481 ((not (load (format "ox-%s" backend) t t))
482 (message "Problems while trying to load export back-end `%s'"
483 backend))
484 ((not (memq backend new-list)) (push backend new-list))))
485 ;; Set VAR to that list with fixed dependencies.
486 (set-default var new-list))))
487 :type '(set :greedy t
488 (const :tag " ascii Export buffer to ASCII format" ascii)
489 (const :tag " beamer Export buffer to Beamer presentation" beamer)
490 (const :tag " html Export buffer to HTML format" html)
491 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
492 (const :tag " latex Export buffer to LaTeX format" latex)
493 (const :tag " man Export buffer to MAN format" man)
494 (const :tag " md Export buffer to Markdown format" md)
495 (const :tag " odt Export buffer to ODT format" odt)
496 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
497 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
498 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
499 (const :tag "C groff Export buffer to Groff format" groff)
500 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
502 (eval-after-load 'ox
503 '(mapc
504 (lambda (backend)
505 (condition-case nil (require (intern (format "ox-%s" backend)))
506 (error (message "Problems while trying to load export back-end `%s'"
507 backend))))
508 org-export-backends))
510 (defcustom org-support-shift-select nil
511 "Non-nil means make shift-cursor commands select text when possible.
513 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
514 start selecting a region, or enlarge regions started in this way.
515 In Org-mode, in special contexts, these same keys are used for
516 other purposes, important enough to compete with shift selection.
517 Org tries to balance these needs by supporting `shift-select-mode'
518 outside these special contexts, under control of this variable.
520 The default of this variable is nil, to avoid confusing behavior. Shifted
521 cursor keys will then execute Org commands in the following contexts:
522 - on a headline, changing TODO state (left/right) and priority (up/down)
523 - on a time stamp, changing the time
524 - in a plain list item, changing the bullet type
525 - in a property definition line, switching between allowed values
526 - in the BEGIN line of a clock table (changing the time block).
527 Outside these contexts, the commands will throw an error.
529 When this variable is t and the cursor is not in a special
530 context, Org-mode will support shift-selection for making and
531 enlarging regions. To make this more effective, the bullet
532 cycling will no longer happen anywhere in an item line, but only
533 if the cursor is exactly on the bullet.
535 If you set this variable to the symbol `always', then the keys
536 will not be special in headlines, property lines, and item lines,
537 to make shift selection work there as well. If this is what you
538 want, you can use the following alternative commands: `C-c C-t'
539 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
540 can be used to switch TODO sets, `C-c -' to cycle item bullet
541 types, and properties can be edited by hand or in column view.
543 However, when the cursor is on a timestamp, shift-cursor commands
544 will still edit the time stamp - this is just too good to give up.
546 XEmacs user should have this variable set to nil, because
547 `shift-select-mode' is in Emacs 23 or later only."
548 :group 'org
549 :type '(choice
550 (const :tag "Never" nil)
551 (const :tag "When outside special context" t)
552 (const :tag "Everywhere except timestamps" always)))
554 (defcustom org-loop-over-headlines-in-active-region nil
555 "Shall some commands act upon headlines in the active region?
557 When set to `t', some commands will be performed in all headlines
558 within the active region.
560 When set to `start-level', some commands will be performed in all
561 headlines within the active region, provided that these headlines
562 are of the same level than the first one.
564 When set to a string, those commands will be performed on the
565 matching headlines within the active region. Such string must be
566 a tags/property/todo match as it is used in the agenda tags view.
568 The list of commands is: `org-schedule', `org-deadline',
569 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
570 `org-archive-to-archive-sibling'. The archiving commands skip
571 already archived entries."
572 :type '(choice (const :tag "Don't loop" nil)
573 (const :tag "All headlines in active region" t)
574 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
575 (string :tag "Tags/Property/Todo matcher"))
576 :version "24.1"
577 :group 'org-todo
578 :group 'org-archive)
580 (defgroup org-startup nil
581 "Options concerning startup of Org-mode."
582 :tag "Org Startup"
583 :group 'org)
585 (defcustom org-startup-folded t
586 "Non-nil means entering Org-mode will switch to OVERVIEW.
587 This can also be configured on a per-file basis by adding one of
588 the following lines anywhere in the buffer:
590 #+STARTUP: fold (or `overview', this is equivalent)
591 #+STARTUP: nofold (or `showall', this is equivalent)
592 #+STARTUP: content
593 #+STARTUP: showeverything"
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-insert-mode-line-in-empty-file nil
678 "Non-nil means insert the first line setting Org-mode in empty files.
679 When the function `org-mode' is called interactively in an empty file, this
680 normally means that the file name does not automatically trigger Org-mode.
681 To ensure that the file will always be in Org-mode in the future, a
682 line enforcing Org-mode will be inserted into the buffer, if this option
683 has been set."
684 :group 'org-startup
685 :type 'boolean)
687 (defcustom org-replace-disputed-keys nil
688 "Non-nil means use alternative key bindings for some keys.
689 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
690 These keys are also used by other packages like shift-selection-mode'
691 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
692 If you want to use Org-mode together with one of these other modes,
693 or more generally if you would like to move some Org-mode commands to
694 other keys, set this variable and configure the keys with the variable
695 `org-disputed-keys'.
697 This option is only relevant at load-time of Org-mode, and must be set
698 *before* org.el is loaded. Changing it requires a restart of Emacs to
699 become effective."
700 :group 'org-startup
701 :type 'boolean)
703 (defcustom org-use-extra-keys nil
704 "Non-nil means use extra key sequence definitions for certain commands.
705 This happens automatically if you run XEmacs or if `window-system'
706 is nil. This variable lets you do the same manually. You must
707 set it before loading org.
709 Example: on Carbon Emacs 22 running graphically, with an external
710 keyboard on a Powerbook, the default way of setting M-left might
711 not work for either Alt or ESC. Setting this variable will make
712 it work for ESC."
713 :group 'org-startup
714 :type 'boolean)
716 (if (fboundp 'defvaralias)
717 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
719 (defcustom org-disputed-keys
720 '(([(shift up)] . [(meta p)])
721 ([(shift down)] . [(meta n)])
722 ([(shift left)] . [(meta -)])
723 ([(shift right)] . [(meta +)])
724 ([(control shift right)] . [(meta shift +)])
725 ([(control shift left)] . [(meta shift -)]))
726 "Keys for which Org-mode and other modes compete.
727 This is an alist, cars are the default keys, second element specifies
728 the alternative to use when `org-replace-disputed-keys' is t.
730 Keys can be specified in any syntax supported by `define-key'.
731 The value of this option takes effect only at Org-mode's startup,
732 therefore you'll have to restart Emacs to apply it after changing."
733 :group 'org-startup
734 :type 'alist)
736 (defun org-key (key)
737 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
738 Or return the original if not disputed.
739 Also apply the translations defined in `org-xemacs-key-equivalents'."
740 (when org-replace-disputed-keys
741 (let* ((nkey (key-description key))
742 (x (org-find-if (lambda (x)
743 (equal (key-description (car x)) nkey))
744 org-disputed-keys)))
745 (setq key (if x (cdr x) key))))
746 (when (featurep 'xemacs)
747 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
748 key)
750 (defun org-find-if (predicate seq)
751 (catch 'exit
752 (while seq
753 (if (funcall predicate (car seq))
754 (throw 'exit (car seq))
755 (pop seq)))))
757 (defun org-defkey (keymap key def)
758 "Define a key, possibly translated, as returned by `org-key'."
759 (define-key keymap (org-key key) def))
761 (defcustom org-ellipsis nil
762 "The ellipsis to use in the Org-mode outline.
763 When nil, just use the standard three dots. When a string, use that instead,
764 When a face, use the standard 3 dots, but with the specified face.
765 The change affects only Org-mode (which will then use its own display table).
766 Changing this requires executing `M-x org-mode' in a buffer to become
767 effective."
768 :group 'org-startup
769 :type '(choice (const :tag "Default" nil)
770 (face :tag "Face" :value org-warning)
771 (string :tag "String" :value "...#")))
773 (defvar org-display-table nil
774 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
776 (defgroup org-keywords nil
777 "Keywords in Org-mode."
778 :tag "Org Keywords"
779 :group 'org)
781 (defcustom org-deadline-string "DEADLINE:"
782 "String to mark deadline entries.
783 A deadline is this string, followed by a time stamp. Should be a word,
784 terminated by a colon. You can insert a schedule keyword and
785 a timestamp with \\[org-deadline].
786 Changes become only effective after restarting Emacs."
787 :group 'org-keywords
788 :type 'string)
790 (defcustom org-scheduled-string "SCHEDULED:"
791 "String to mark scheduled TODO entries.
792 A schedule is this string, followed by a time stamp. Should be a word,
793 terminated by a colon. You can insert a schedule keyword and
794 a timestamp with \\[org-schedule].
795 Changes become only effective after restarting Emacs."
796 :group 'org-keywords
797 :type 'string)
799 (defcustom org-closed-string "CLOSED:"
800 "String used as the prefix for timestamps logging closing a TODO entry."
801 :group 'org-keywords
802 :type 'string)
804 (defcustom org-clock-string "CLOCK:"
805 "String used as prefix for timestamps clocking work hours on an item."
806 :group 'org-keywords
807 :type 'string)
809 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
810 org-scheduled-string "\\|"
811 org-deadline-string "\\|"
812 org-closed-string "\\|"
813 org-clock-string "\\)")
814 "Matches a line with planning or clock info.")
816 (defcustom org-comment-string "COMMENT"
817 "Entries starting with this keyword will never be exported.
818 An entry can be toggled between COMMENT and normal with
819 \\[org-toggle-comment].
820 Changes become only effective after restarting Emacs."
821 :group 'org-keywords
822 :type 'string)
824 (defcustom org-quote-string "QUOTE"
825 "Entries starting with this keyword will be exported in fixed-width font.
826 Quoting applies only to the text in the entry following the headline, and does
827 not extend beyond the next headline, even if that is lower level.
828 An entry can be toggled between QUOTE and normal with
829 \\[org-toggle-fixed-width-section]."
830 :group 'org-keywords
831 :type 'string)
833 (defconst org-repeat-re
834 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
835 "Regular expression for specifying repeated events.
836 After a match, group 1 contains the repeat expression.")
838 (defgroup org-structure nil
839 "Options concerning the general structure of Org-mode files."
840 :tag "Org Structure"
841 :group 'org)
843 (defgroup org-reveal-location nil
844 "Options about how to make context of a location visible."
845 :tag "Org Reveal Location"
846 :group 'org-structure)
848 (defconst org-context-choice
849 '(choice
850 (const :tag "Always" t)
851 (const :tag "Never" nil)
852 (repeat :greedy t :tag "Individual contexts"
853 (cons
854 (choice :tag "Context"
855 (const agenda)
856 (const org-goto)
857 (const occur-tree)
858 (const tags-tree)
859 (const link-search)
860 (const mark-goto)
861 (const bookmark-jump)
862 (const isearch)
863 (const default))
864 (boolean))))
865 "Contexts for the reveal options.")
867 (defcustom org-show-hierarchy-above '((default . t))
868 "Non-nil means show full hierarchy when revealing a location.
869 Org-mode often shows locations in an org-mode file which might have
870 been invisible before. When this is set, the hierarchy of headings
871 above the exposed location is shown.
872 Turning this off for example for sparse trees makes them very compact.
873 Instead of t, this can also be an alist specifying this option for different
874 contexts. Valid contexts are
875 agenda when exposing an entry from the agenda
876 org-goto when using the command `org-goto' on key C-c C-j
877 occur-tree when using the command `org-occur' on key C-c /
878 tags-tree when constructing a sparse tree based on tags matches
879 link-search when exposing search matches associated with a link
880 mark-goto when exposing the jump goal of a mark
881 bookmark-jump when exposing a bookmark location
882 isearch when exiting from an incremental search
883 default default for all contexts not set explicitly"
884 :group 'org-reveal-location
885 :type org-context-choice)
887 (defcustom org-show-following-heading '((default . nil))
888 "Non-nil means show following heading when revealing a location.
889 Org-mode often shows locations in an org-mode file which might have
890 been invisible before. When this is set, the heading following the
891 match is shown.
892 Turning this off for example for sparse trees makes them very compact,
893 but makes it harder to edit the location of the match. In such a case,
894 use the command \\[org-reveal] to show more context.
895 Instead of t, this can also be an alist specifying this option for different
896 contexts. See `org-show-hierarchy-above' for valid contexts."
897 :group 'org-reveal-location
898 :type org-context-choice)
900 (defcustom org-show-siblings '((default . nil) (isearch t))
901 "Non-nil means show all sibling heading when revealing a location.
902 Org-mode often shows locations in an org-mode file which might have
903 been invisible before. When this is set, the sibling of the current entry
904 heading are all made visible. If `org-show-hierarchy-above' is t,
905 the same happens on each level of the hierarchy above the current entry.
907 By default this is on for the isearch context, off for all other contexts.
908 Turning this off for example for sparse trees makes them very compact,
909 but makes it harder to edit the location of the match. In such a case,
910 use the command \\[org-reveal] to show more context.
911 Instead of t, this can also be an alist specifying this option for different
912 contexts. See `org-show-hierarchy-above' for valid contexts."
913 :group 'org-reveal-location
914 :type org-context-choice)
916 (defcustom org-show-entry-below '((default . nil))
917 "Non-nil means show the entry below a headline when revealing a location.
918 Org-mode often shows locations in an org-mode file which might have
919 been invisible before. When this is set, the text below the headline that is
920 exposed is also shown.
922 By default this is off for all contexts.
923 Instead of t, this can also be an alist specifying this option for different
924 contexts. See `org-show-hierarchy-above' for valid contexts."
925 :group 'org-reveal-location
926 :type org-context-choice)
928 (defcustom org-indirect-buffer-display 'other-window
929 "How should indirect tree buffers be displayed?
930 This applies to indirect buffers created with the commands
931 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
932 Valid values are:
933 current-window Display in the current window
934 other-window Just display in another window.
935 dedicated-frame Create one new frame, and re-use it each time.
936 new-frame Make a new frame each time. Note that in this case
937 previously-made indirect buffers are kept, and you need to
938 kill these buffers yourself."
939 :group 'org-structure
940 :group 'org-agenda-windows
941 :type '(choice
942 (const :tag "In current window" current-window)
943 (const :tag "In current frame, other window" other-window)
944 (const :tag "Each time a new frame" new-frame)
945 (const :tag "One dedicated frame" dedicated-frame)))
947 (defcustom org-use-speed-commands nil
948 "Non-nil means activate single letter commands at beginning of a headline.
949 This may also be a function to test for appropriate locations where speed
950 commands should be active."
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Never" nil)
954 (const :tag "At beginning of headline stars" t)
955 (function)))
957 (defcustom org-speed-commands-user nil
958 "Alist of additional speed commands.
959 This list will be checked before `org-speed-commands-default'
960 when the variable `org-use-speed-commands' is non-nil
961 and when the cursor is at the beginning of a headline.
962 The car if each entry is a string with a single letter, which must
963 be assigned to `self-insert-command' in the global map.
964 The cdr is either a command to be called interactively, a function
965 to be called, or a form to be evaluated.
966 An entry that is just a list with a single string will be interpreted
967 as a descriptive headline that will be added when listing the speed
968 commands in the Help buffer using the `?' speed command."
969 :group 'org-structure
970 :type '(repeat :value ("k" . ignore)
971 (choice :value ("k" . ignore)
972 (list :tag "Descriptive Headline" (string :tag "Headline"))
973 (cons :tag "Letter and Command"
974 (string :tag "Command letter")
975 (choice
976 (function)
977 (sexp))))))
979 (defgroup org-cycle nil
980 "Options concerning visibility cycling in Org-mode."
981 :tag "Org Cycle"
982 :group 'org-structure)
984 (defcustom org-cycle-skip-children-state-if-no-children t
985 "Non-nil means skip CHILDREN state in entries that don't have any."
986 :group 'org-cycle
987 :type 'boolean)
989 (defcustom org-cycle-max-level nil
990 "Maximum level which should still be subject to visibility cycling.
991 Levels higher than this will, for cycling, be treated as text, not a headline.
992 When `org-odd-levels-only' is set, a value of N in this variable actually
993 means 2N-1 stars as the limiting headline.
994 When nil, cycle all levels.
995 Note that the limiting level of cycling is also influenced by
996 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
997 `org-inlinetask-min-level' is, cycling will be limited to levels one less
998 than its value."
999 :group 'org-cycle
1000 :type '(choice
1001 (const :tag "No limit" nil)
1002 (integer :tag "Maximum level")))
1004 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1005 "Names of drawers. Drawers are not opened by cycling on the headline above.
1006 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1007 this:
1008 :DRAWERNAME:
1009 .....
1010 :END:
1011 The drawer \"PROPERTIES\" is special for capturing properties through
1012 the property API.
1014 Drawers can be defined on the per-file basis with a line like:
1016 #+DRAWERS: HIDDEN STATE PROPERTIES"
1017 :group 'org-structure
1018 :group 'org-cycle
1019 :type '(repeat (string :tag "Drawer Name")))
1021 (defcustom org-hide-block-startup nil
1022 "Non-nil means entering Org-mode will fold all blocks.
1023 This can also be set in on a per-file basis with
1025 #+STARTUP: hideblocks
1026 #+STARTUP: showblocks"
1027 :group 'org-startup
1028 :group 'org-cycle
1029 :type 'boolean)
1031 (defcustom org-cycle-global-at-bob nil
1032 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1033 This makes it possible to do global cycling without having to use S-TAB or
1034 \\[universal-argument] TAB. For this special case to work, the first line
1035 of the buffer must not be a headline -- it may be empty or some other text.
1036 When used in this way, `org-cycle-hook' is disabled temporarily to make
1037 sure the cursor stays at the beginning of the buffer. When this option is
1038 nil, don't do anything special at the beginning of the buffer."
1039 :group 'org-cycle
1040 :type 'boolean)
1042 (defcustom org-cycle-level-after-item/entry-creation t
1043 "Non-nil means cycle entry level or item indentation in new empty entries.
1045 When the cursor is at the end of an empty headline, i.e with only stars
1046 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1047 and then all possible ancestor states, before returning to the original state.
1048 This makes data entry extremely fast: M-RET to create a new headline,
1049 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1051 When the cursor is at the end of an empty plain list item, one TAB will
1052 make it a subitem, two or more tabs will back up to make this an item
1053 higher up in the item hierarchy."
1054 :group 'org-cycle
1055 :type 'boolean)
1057 (defcustom org-cycle-emulate-tab t
1058 "Where should `org-cycle' emulate TAB.
1059 nil Never
1060 white Only in completely white lines
1061 whitestart Only at the beginning of lines, before the first non-white char
1062 t Everywhere except in headlines
1063 exc-hl-bol Everywhere except at the start of a headline
1064 If TAB is used in a place where it does not emulate TAB, the current subtree
1065 visibility is cycled."
1066 :group 'org-cycle
1067 :type '(choice (const :tag "Never" nil)
1068 (const :tag "Only in completely white lines" white)
1069 (const :tag "Before first char in a line" whitestart)
1070 (const :tag "Everywhere except in headlines" t)
1071 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1074 (defcustom org-cycle-separator-lines 2
1075 "Number of empty lines needed to keep an empty line between collapsed trees.
1076 If you leave an empty line between the end of a subtree and the following
1077 headline, this empty line is hidden when the subtree is folded.
1078 Org-mode will leave (exactly) one empty line visible if the number of
1079 empty lines is equal or larger to the number given in this variable.
1080 So the default 2 means at least 2 empty lines after the end of a subtree
1081 are needed to produce free space between a collapsed subtree and the
1082 following headline.
1084 If the number is negative, and the number of empty lines is at least -N,
1085 all empty lines are shown.
1087 Special case: when 0, never leave empty lines in collapsed view."
1088 :group 'org-cycle
1089 :type 'integer)
1090 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1092 (defcustom org-pre-cycle-hook nil
1093 "Hook that is run before visibility cycling is happening.
1094 The function(s) in this hook must accept a single argument which indicates
1095 the new state that will be set right after running this hook. The
1096 argument is a symbol. Before a global state change, it can have the values
1097 `overview', `content', or `all'. Before a local state change, it can have
1098 the values `folded', `children', or `subtree'."
1099 :group 'org-cycle
1100 :type 'hook)
1102 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1103 org-cycle-hide-drawers
1104 org-cycle-hide-inline-tasks
1105 org-cycle-show-empty-lines
1106 org-optimize-window-after-visibility-change)
1107 "Hook that is run after `org-cycle' has changed the buffer visibility.
1108 The function(s) in this hook must accept a single argument which indicates
1109 the new state that was set by the most recent `org-cycle' command. The
1110 argument is a symbol. After a global state change, it can have the values
1111 `overview', `contents', or `all'. After a local state change, it can have
1112 the values `folded', `children', or `subtree'."
1113 :group 'org-cycle
1114 :type 'hook)
1116 (defgroup org-edit-structure nil
1117 "Options concerning structure editing in Org-mode."
1118 :tag "Org Edit Structure"
1119 :group 'org-structure)
1121 (defcustom org-odd-levels-only nil
1122 "Non-nil means skip even levels and only use odd levels for the outline.
1123 This has the effect that two stars are being added/taken away in
1124 promotion/demotion commands. It also influences how levels are
1125 handled by the exporters.
1126 Changing it requires restart of `font-lock-mode' to become effective
1127 for fontification also in regions already fontified.
1128 You may also set this on a per-file basis by adding one of the following
1129 lines to the buffer:
1131 #+STARTUP: odd
1132 #+STARTUP: oddeven"
1133 :group 'org-edit-structure
1134 :group 'org-appearance
1135 :type 'boolean)
1137 (defcustom org-adapt-indentation t
1138 "Non-nil means adapt indentation to outline node level.
1140 When this variable is set, Org assumes that you write outlines by
1141 indenting text in each node to align with the headline (after the stars).
1142 The following issues are influenced by this variable:
1144 - When this is set and the *entire* text in an entry is indented, the
1145 indentation is increased by one space in a demotion command, and
1146 decreased by one in a promotion command. If any line in the entry
1147 body starts with text at column 0, indentation is not changed at all.
1149 - Property drawers and planning information is inserted indented when
1150 this variable s set. When nil, they will not be indented.
1152 - TAB indents a line relative to context. The lines below a headline
1153 will be indented when this variable is set.
1155 Note that this is all about true indentation, by adding and removing
1156 space characters. See also `org-indent.el' which does level-dependent
1157 indentation in a virtual way, i.e. at display time in Emacs."
1158 :group 'org-edit-structure
1159 :type 'boolean)
1161 (defcustom org-special-ctrl-a/e nil
1162 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1164 When t, `C-a' will bring back the cursor to the beginning of the
1165 headline text, i.e. after the stars and after a possible TODO
1166 keyword. In an item, this will be the position after bullet and
1167 check-box, if any. When the cursor is already at that position,
1168 another `C-a' will bring it to the beginning of the line.
1170 `C-e' will jump to the end of the headline, ignoring the presence
1171 of tags in the headline. A second `C-e' will then jump to the
1172 true end of the line, after any tags. This also means that, when
1173 this variable is non-nil, `C-e' also will never jump beyond the
1174 end of the heading of a folded section, i.e. not after the
1175 ellipses.
1177 When set to the symbol `reversed', the first `C-a' or `C-e' works
1178 normally, going to the true line boundary first. Only a directly
1179 following, identical keypress will bring the cursor to the
1180 special positions.
1182 This may also be a cons cell where the behavior for `C-a' and
1183 `C-e' is set separately."
1184 :group 'org-edit-structure
1185 :type '(choice
1186 (const :tag "off" nil)
1187 (const :tag "on: after stars/bullet and before tags first" t)
1188 (const :tag "reversed: true line boundary first" reversed)
1189 (cons :tag "Set C-a and C-e separately"
1190 (choice :tag "Special C-a"
1191 (const :tag "off" nil)
1192 (const :tag "on: after stars/bullet first" t)
1193 (const :tag "reversed: before stars/bullet first" reversed))
1194 (choice :tag "Special C-e"
1195 (const :tag "off" nil)
1196 (const :tag "on: before tags first" t)
1197 (const :tag "reversed: after tags first" reversed)))))
1198 (if (fboundp 'defvaralias)
1199 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1201 (defcustom org-special-ctrl-k nil
1202 "Non-nil means `C-k' will behave specially in headlines.
1203 When nil, `C-k' will call the default `kill-line' command.
1204 When t, the following will happen while the cursor is in the headline:
1206 - When the cursor is at the beginning of a headline, kill the entire
1207 line and possible the folded subtree below the line.
1208 - When in the middle of the headline text, kill the headline up to the tags.
1209 - When after the headline text, kill the tags."
1210 :group 'org-edit-structure
1211 :type 'boolean)
1213 (defcustom org-ctrl-k-protect-subtree nil
1214 "Non-nil means, do not delete a hidden subtree with C-k.
1215 When set to the symbol `error', simply throw an error when C-k is
1216 used to kill (part-of) a headline that has hidden text behind it.
1217 Any other non-nil value will result in a query to the user, if it is
1218 OK to kill that hidden subtree. When nil, kill without remorse."
1219 :group 'org-edit-structure
1220 :version "24.1"
1221 :type '(choice
1222 (const :tag "Do not protect hidden subtrees" nil)
1223 (const :tag "Protect hidden subtrees with a security query" t)
1224 (const :tag "Never kill a hidden subtree with C-k" error)))
1226 (defcustom org-catch-invisible-edits nil
1227 "Check if in invisible region before inserting or deleting a character.
1228 Valid values are:
1230 nil Do not check, so just do invisible edits.
1231 error Throw an error and do nothing.
1232 show Make point visible, and do the requested edit.
1233 show-and-error Make point visible, then throw an error and abort the edit.
1234 smart Make point visible, and do insertion/deletion if it is
1235 adjacent to visible text and the change feels predictable.
1236 Never delete a previously invisible character or add in the
1237 middle or right after an invisible region. Basically, this
1238 allows insertion and backward-delete right before ellipses.
1239 FIXME: maybe in this case we should not even show?"
1240 :group 'org-edit-structure
1241 :version "24.1"
1242 :type '(choice
1243 (const :tag "Do not check" nil)
1244 (const :tag "Throw error when trying to edit" error)
1245 (const :tag "Unhide, but do not do the edit" show-and-error)
1246 (const :tag "Show invisible part and do the edit" show)
1247 (const :tag "Be smart and do the right thing" smart)))
1249 (defcustom org-yank-folded-subtrees t
1250 "Non-nil means when yanking subtrees, fold them.
1251 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1252 it starts with a heading and all other headings in it are either children
1253 or siblings, then fold all the subtrees. However, do this only if no
1254 text after the yank would be swallowed into a folded tree by this action."
1255 :group 'org-edit-structure
1256 :type 'boolean)
1258 (defcustom org-yank-adjusted-subtrees nil
1259 "Non-nil means when yanking subtrees, adjust the level.
1260 With this setting, `org-paste-subtree' is used to insert the subtree, see
1261 this function for details."
1262 :group 'org-edit-structure
1263 :type 'boolean)
1265 (defcustom org-M-RET-may-split-line '((default . t))
1266 "Non-nil means M-RET will split the line at the cursor position.
1267 When nil, it will go to the end of the line before making a
1268 new line.
1269 You may also set this option in a different way for different
1270 contexts. Valid contexts are:
1272 headline when creating a new headline
1273 item when creating a new item
1274 table in a table field
1275 default the value to be used for all contexts not explicitly
1276 customized"
1277 :group 'org-structure
1278 :group 'org-table
1279 :type '(choice
1280 (const :tag "Always" t)
1281 (const :tag "Never" nil)
1282 (repeat :greedy t :tag "Individual contexts"
1283 (cons
1284 (choice :tag "Context"
1285 (const headline)
1286 (const item)
1287 (const table)
1288 (const default))
1289 (boolean)))))
1292 (defcustom org-insert-heading-respect-content nil
1293 "Non-nil means insert new headings after the current subtree.
1294 When nil, the new heading is created directly after the current line.
1295 The commands \\[org-insert-heading-respect-content] and
1296 \\[org-insert-todo-heading-respect-content] turn this variable on
1297 for the duration of the command."
1298 :group 'org-structure
1299 :type 'boolean)
1301 (defcustom org-blank-before-new-entry '((heading . auto)
1302 (plain-list-item . auto))
1303 "Should `org-insert-heading' leave a blank line before new heading/item?
1304 The value is an alist, with `heading' and `plain-list-item' as CAR,
1305 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1306 which case Org will look at the surrounding headings/items and try to
1307 make an intelligent decision whether to insert a blank line or not.
1309 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1310 set, the setting here is ignored and no empty line is inserted, to avoid
1311 breaking the list structure."
1312 :group 'org-edit-structure
1313 :type '(list
1314 (cons (const heading)
1315 (choice (const :tag "Never" nil)
1316 (const :tag "Always" t)
1317 (const :tag "Auto" auto)))
1318 (cons (const plain-list-item)
1319 (choice (const :tag "Never" nil)
1320 (const :tag "Always" t)
1321 (const :tag "Auto" auto)))))
1323 (defcustom org-insert-heading-hook nil
1324 "Hook being run after inserting a new heading."
1325 :group 'org-edit-structure
1326 :type 'hook)
1328 (defcustom org-enable-fixed-width-editor t
1329 "Non-nil means lines starting with \":\" are treated as fixed-width.
1330 This currently only means they are never auto-wrapped.
1331 When nil, such lines will be treated like ordinary lines.
1332 See also the QUOTE keyword."
1333 :group 'org-edit-structure
1334 :type 'boolean)
1336 (defcustom org-goto-auto-isearch t
1337 "Non-nil means typing characters in `org-goto' starts incremental search.
1338 When nil, you can use these keybindings to navigate the buffer:
1340 q Quit the org-goto interface
1341 n Go to the next visible heading
1342 p Go to the previous visible heading
1343 f Go one heading forward on same level
1344 b Go one heading backward on same level
1345 u Go one heading up"
1346 :group 'org-edit-structure
1347 :type 'boolean)
1349 (defgroup org-sparse-trees nil
1350 "Options concerning sparse trees in Org-mode."
1351 :tag "Org Sparse Trees"
1352 :group 'org-structure)
1354 (defcustom org-highlight-sparse-tree-matches t
1355 "Non-nil means highlight all matches that define a sparse tree.
1356 The highlights will automatically disappear the next time the buffer is
1357 changed by an edit command."
1358 :group 'org-sparse-trees
1359 :type 'boolean)
1361 (defcustom org-remove-highlights-with-change t
1362 "Non-nil means any change to the buffer will remove temporary highlights.
1363 Such highlights are created by `org-occur' and `org-clock-display'.
1364 When nil, `C-c C-c needs to be used to get rid of the highlights.
1365 The highlights created by `org-preview-latex-fragment' always need
1366 `C-c C-c' to be removed."
1367 :group 'org-sparse-trees
1368 :group 'org-time
1369 :type 'boolean)
1372 (defcustom org-occur-hook '(org-first-headline-recenter)
1373 "Hook that is run after `org-occur' has constructed a sparse tree.
1374 This can be used to recenter the window to show as much of the structure
1375 as possible."
1376 :group 'org-sparse-trees
1377 :type 'hook)
1379 (defgroup org-imenu-and-speedbar nil
1380 "Options concerning imenu and speedbar in Org-mode."
1381 :tag "Org Imenu and Speedbar"
1382 :group 'org-structure)
1384 (defcustom org-imenu-depth 2
1385 "The maximum level for Imenu access to Org-mode headlines.
1386 This also applied for speedbar access."
1387 :group 'org-imenu-and-speedbar
1388 :type 'integer)
1390 (defgroup org-table nil
1391 "Options concerning tables in Org-mode."
1392 :tag "Org Table"
1393 :group 'org)
1395 (defcustom org-enable-table-editor 'optimized
1396 "Non-nil means lines starting with \"|\" are handled by the table editor.
1397 When nil, such lines will be treated like ordinary lines.
1399 When equal to the symbol `optimized', the table editor will be optimized to
1400 do the following:
1401 - Automatic overwrite mode in front of whitespace in table fields.
1402 This makes the structure of the table stay in tact as long as the edited
1403 field does not exceed the column width.
1404 - Minimize the number of realigns. Normally, the table is aligned each time
1405 TAB or RET are pressed to move to another field. With optimization this
1406 happens only if changes to a field might have changed the column width.
1407 Optimization requires replacing the functions `self-insert-command',
1408 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1409 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1410 very good at guessing when a re-align will be necessary, but you can always
1411 force one with \\[org-ctrl-c-ctrl-c].
1413 If you would like to use the optimized version in Org-mode, but the
1414 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1416 This variable can be used to turn on and off the table editor during a session,
1417 but in order to toggle optimization, a restart is required.
1419 See also the variable `org-table-auto-blank-field'."
1420 :group 'org-table
1421 :type '(choice
1422 (const :tag "off" nil)
1423 (const :tag "on" t)
1424 (const :tag "on, optimized" optimized)))
1426 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1427 (version<= emacs-version "24.1"))
1428 "Non-nil means cluster self-insert commands for undo when possible.
1429 If this is set, then, like in the Emacs command loop, 20 consecutive
1430 characters will be undone together.
1431 This is configurable, because there is some impact on typing performance."
1432 :group 'org-table
1433 :type 'boolean)
1435 (defcustom org-table-tab-recognizes-table.el t
1436 "Non-nil means TAB will automatically notice a table.el table.
1437 When it sees such a table, it moves point into it and - if necessary -
1438 calls `table-recognize-table'."
1439 :group 'org-table-editing
1440 :type 'boolean)
1442 (defgroup org-link nil
1443 "Options concerning links in Org-mode."
1444 :tag "Org Link"
1445 :group 'org)
1447 (defvar org-link-abbrev-alist-local nil
1448 "Buffer-local version of `org-link-abbrev-alist', which see.
1449 The value of this is taken from the #+LINK lines.")
1450 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1452 (defcustom org-link-abbrev-alist nil
1453 "Alist of link abbreviations.
1454 The car of each element is a string, to be replaced at the start of a link.
1455 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1456 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1458 [[linkkey:tag][description]]
1460 The 'linkkey' must be a word word, starting with a letter, followed
1461 by letters, numbers, '-' or '_'.
1463 If REPLACE is a string, the tag will simply be appended to create the link.
1464 If the string contains \"%s\", the tag will be inserted there. If the string
1465 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1466 at that point (see the function `url-hexify-string'). If the string contains
1467 the specifier \"%(my-function)\", then the custom function `my-function' will
1468 be invoked: this function takes the tag as its only argument and must return
1469 a string.
1471 REPLACE may also be a function that will be called with the tag as the
1472 only argument to create the link, which should be returned as a string.
1474 See the manual for examples."
1475 :group 'org-link
1476 :type '(repeat
1477 (cons
1478 (string :tag "Protocol")
1479 (choice
1480 (string :tag "Format")
1481 (function)))))
1483 (defcustom org-descriptive-links t
1484 "Non-nil means Org will display descriptive links.
1485 E.g. [[http://orgmode.org][Org website]] will be displayed as
1486 \"Org Website\", hiding the link itself and just displaying its
1487 description. When set to `nil', Org will display the full links
1488 literally.
1490 You can interactively set the value of this variable by calling
1491 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1492 :group 'org-link
1493 :type 'boolean)
1495 (defcustom org-link-file-path-type 'adaptive
1496 "How the path name in file links should be stored.
1497 Valid values are:
1499 relative Relative to the current directory, i.e. the directory of the file
1500 into which the link is being inserted.
1501 absolute Absolute path, if possible with ~ for home directory.
1502 noabbrev Absolute path, no abbreviation of home directory.
1503 adaptive Use relative path for files in the current directory and sub-
1504 directories of it. For other files, use an absolute path."
1505 :group 'org-link
1506 :type '(choice
1507 (const relative)
1508 (const absolute)
1509 (const noabbrev)
1510 (const adaptive)))
1512 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1513 "Types of links that should be activated in Org-mode files.
1514 This is a list of symbols, each leading to the activation of a certain link
1515 type. In principle, it does not hurt to turn on most link types - there may
1516 be a small gain when turning off unused link types. The types are:
1518 bracket The recommended [[link][description]] or [[link]] links with hiding.
1519 angle Links in angular brackets that may contain whitespace like
1520 <bbdb:Carsten Dominik>.
1521 plain Plain links in normal text, no whitespace, like http://google.com.
1522 radio Text that is matched by a radio target, see manual for details.
1523 tag Tag settings in a headline (link to tag search).
1524 date Time stamps (link to calendar).
1525 footnote Footnote labels.
1527 Changing this variable requires a restart of Emacs to become effective."
1528 :group 'org-link
1529 :type '(set :greedy t
1530 (const :tag "Double bracket links" bracket)
1531 (const :tag "Angular bracket links" angle)
1532 (const :tag "Plain text links" plain)
1533 (const :tag "Radio target matches" radio)
1534 (const :tag "Tags" tag)
1535 (const :tag "Timestamps" date)
1536 (const :tag "Footnotes" footnote)))
1538 (defcustom org-make-link-description-function nil
1539 "Function to use for generating link descriptions from links.
1540 When nil, the link location will be used. This function must take
1541 two parameters: the first one is the link, the second one is the
1542 description generated by `org-insert-link'. The function should
1543 return the description to use."
1544 :group 'org-link
1545 :type 'function)
1547 (defgroup org-link-store nil
1548 "Options concerning storing links in Org-mode."
1549 :tag "Org Store Link"
1550 :group 'org-link)
1552 (defcustom org-url-hexify-p t
1553 "When non-nil, hexify URL when creating a link."
1554 :type 'boolean
1555 :version "24.3"
1556 :group 'org-link-store)
1558 (defcustom org-email-link-description-format "Email %c: %.30s"
1559 "Format of the description part of a link to an email or usenet message.
1560 The following %-escapes will be replaced by corresponding information:
1562 %F full \"From\" field
1563 %f name, taken from \"From\" field, address if no name
1564 %T full \"To\" field
1565 %t first name in \"To\" field, address if no name
1566 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1567 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1568 %s subject
1569 %d date
1570 %m message-id.
1572 You may use normal field width specification between the % and the letter.
1573 This is for example useful to limit the length of the subject.
1575 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1576 :group 'org-link-store
1577 :type 'string)
1579 (defcustom org-from-is-user-regexp
1580 (let (r1 r2)
1581 (when (and user-mail-address (not (string= user-mail-address "")))
1582 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1583 (when (and user-full-name (not (string= user-full-name "")))
1584 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1585 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1586 "Regexp matched against the \"From:\" header of an email or usenet message.
1587 It should match if the message is from the user him/herself."
1588 :group 'org-link-store
1589 :type 'regexp)
1591 (defcustom org-context-in-file-links t
1592 "Non-nil means file links from `org-store-link' contain context.
1593 A search string will be added to the file name with :: as separator and
1594 used to find the context when the link is activated by the command
1595 `org-open-at-point'. When this option is t, the entire active region
1596 will be placed in the search string of the file link. If set to a
1597 positive integer, only the first n lines of context will be stored.
1599 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1600 negates this setting for the duration of the command."
1601 :group 'org-link-store
1602 :type '(choice boolean integer))
1604 (defcustom org-keep-stored-link-after-insertion nil
1605 "Non-nil means keep link in list for entire session.
1607 The command `org-store-link' adds a link pointing to the current
1608 location to an internal list. These links accumulate during a session.
1609 The command `org-insert-link' can be used to insert links into any
1610 Org-mode file (offering completion for all stored links). When this
1611 option is nil, every link which has been inserted once using \\[org-insert-link]
1612 will be removed from the list, to make completing the unused links
1613 more efficient."
1614 :group 'org-link-store
1615 :type 'boolean)
1617 (defgroup org-link-follow nil
1618 "Options concerning following links in Org-mode."
1619 :tag "Org Follow Link"
1620 :group 'org-link)
1622 (defcustom org-link-translation-function nil
1623 "Function to translate links with different syntax to Org syntax.
1624 This can be used to translate links created for example by the Planner
1625 or emacs-wiki packages to Org syntax.
1626 The function must accept two parameters, a TYPE containing the link
1627 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1628 which is everything after the link protocol. It should return a cons
1629 with possibly modified values of type and path.
1630 Org contains a function for this, so if you set this variable to
1631 `org-translate-link-from-planner', you should be able follow many
1632 links created by planner."
1633 :group 'org-link-follow
1634 :type 'function)
1636 (defcustom org-follow-link-hook nil
1637 "Hook that is run after a link has been followed."
1638 :group 'org-link-follow
1639 :type 'hook)
1641 (defcustom org-tab-follows-link nil
1642 "Non-nil means on links TAB will follow the link.
1643 Needs to be set before org.el is loaded.
1644 This really should not be used, it does not make sense, and the
1645 implementation is bad."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-return-follows-link nil
1650 "Non-nil means on links RET will follow the link."
1651 :group 'org-link-follow
1652 :type 'boolean)
1654 (defcustom org-mouse-1-follows-link
1655 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1656 "Non-nil means mouse-1 on a link will follow the link.
1657 A longer mouse click will still set point. Does not work on XEmacs.
1658 Needs to be set before org.el is loaded."
1659 :group 'org-link-follow
1660 :type 'boolean)
1662 (defcustom org-mark-ring-length 4
1663 "Number of different positions to be recorded in the ring.
1664 Changing this requires a restart of Emacs to work correctly."
1665 :group 'org-link-follow
1666 :type 'integer)
1668 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1669 "Non-nil means internal links in Org files must exactly match a headline.
1670 When nil, the link search tries to match a phrase with all words
1671 in the search text."
1672 :group 'org-link-follow
1673 :version "24.1"
1674 :type '(choice
1675 (const :tag "Use fuzzy text search" nil)
1676 (const :tag "Match only exact headline" t)
1677 (const :tag "Match exact headline or query to create it"
1678 query-to-create)))
1680 (defcustom org-link-frame-setup
1681 '((vm . vm-visit-folder-other-frame)
1682 (vm-imap . vm-visit-imap-folder-other-frame)
1683 (gnus . org-gnus-no-new-news)
1684 (file . find-file-other-window)
1685 (wl . wl-other-frame))
1686 "Setup the frame configuration for following links.
1687 When following a link with Emacs, it may often be useful to display
1688 this link in another window or frame. This variable can be used to
1689 set this up for the different types of links.
1690 For VM, use any of
1691 `vm-visit-folder'
1692 `vm-visit-folder-other-window'
1693 `vm-visit-folder-other-frame'
1694 For Gnus, use any of
1695 `gnus'
1696 `gnus-other-frame'
1697 `org-gnus-no-new-news'
1698 For FILE, use any of
1699 `find-file'
1700 `find-file-other-window'
1701 `find-file-other-frame'
1702 For Wanderlust use any of
1703 `wl'
1704 `wl-other-frame'
1705 For the calendar, use the variable `calendar-setup'.
1706 For BBDB, it is currently only possible to display the matches in
1707 another window."
1708 :group 'org-link-follow
1709 :type '(list
1710 (cons (const vm)
1711 (choice
1712 (const vm-visit-folder)
1713 (const vm-visit-folder-other-window)
1714 (const vm-visit-folder-other-frame)))
1715 (cons (const gnus)
1716 (choice
1717 (const gnus)
1718 (const gnus-other-frame)
1719 (const org-gnus-no-new-news)))
1720 (cons (const file)
1721 (choice
1722 (const find-file)
1723 (const find-file-other-window)
1724 (const find-file-other-frame)))
1725 (cons (const wl)
1726 (choice
1727 (const wl)
1728 (const wl-other-frame)))))
1730 (defcustom org-display-internal-link-with-indirect-buffer nil
1731 "Non-nil means use indirect buffer to display infile links.
1732 Activating internal links (from one location in a file to another location
1733 in the same file) normally just jumps to the location. When the link is
1734 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1735 is displayed in
1736 another window. When this option is set, the other window actually displays
1737 an indirect buffer clone of the current buffer, to avoid any visibility
1738 changes to the current buffer."
1739 :group 'org-link-follow
1740 :type 'boolean)
1742 (defcustom org-open-non-existing-files nil
1743 "Non-nil means `org-open-file' will open non-existing files.
1744 When nil, an error will be generated.
1745 This variable applies only to external applications because they
1746 might choke on non-existing files. If the link is to a file that
1747 will be opened in Emacs, the variable is ignored."
1748 :group 'org-link-follow
1749 :type 'boolean)
1751 (defcustom org-open-directory-means-index-dot-org nil
1752 "Non-nil means a link to a directory really means to index.org.
1753 When nil, following a directory link will run dired or open a finder/explorer
1754 window on that directory."
1755 :group 'org-link-follow
1756 :type 'boolean)
1758 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1759 "Function and arguments to call for following mailto links.
1760 This is a list with the first element being a Lisp function, and the
1761 remaining elements being arguments to the function. In string arguments,
1762 %a will be replaced by the address, and %s will be replaced by the subject
1763 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1764 :group 'org-link-follow
1765 :type '(choice
1766 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1767 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1768 (const :tag "message-mail" (message-mail "%a" "%s"))
1769 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1771 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1772 "Non-nil means ask for confirmation before executing shell links.
1773 Shell links can be dangerous: just think about a link
1775 [[shell:rm -rf ~/*][Google Search]]
1777 This link would show up in your Org-mode document as \"Google Search\",
1778 but really it would remove your entire home directory.
1779 Therefore we advise against setting this variable to nil.
1780 Just change it to `y-or-n-p' if you want to confirm with a
1781 single keystroke rather than having to type \"yes\"."
1782 :group 'org-link-follow
1783 :type '(choice
1784 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1785 (const :tag "with y-or-n (faster)" y-or-n-p)
1786 (const :tag "no confirmation (dangerous)" nil)))
1787 (put 'org-confirm-shell-link-function
1788 'safe-local-variable
1789 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1791 (defcustom org-confirm-shell-link-not-regexp ""
1792 "A regexp to skip confirmation for shell links."
1793 :group 'org-link-follow
1794 :version "24.1"
1795 :type 'regexp)
1797 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1798 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1799 Elisp links can be dangerous: just think about a link
1801 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1803 This link would show up in your Org-mode document as \"Google Search\",
1804 but really it would remove your entire home directory.
1805 Therefore we advise against setting this variable to nil.
1806 Just change it to `y-or-n-p' if you want to confirm with a
1807 single keystroke rather than having to type \"yes\"."
1808 :group 'org-link-follow
1809 :type '(choice
1810 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1811 (const :tag "with y-or-n (faster)" y-or-n-p)
1812 (const :tag "no confirmation (dangerous)" nil)))
1813 (put 'org-confirm-shell-link-function
1814 'safe-local-variable
1815 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1817 (defcustom org-confirm-elisp-link-not-regexp ""
1818 "A regexp to skip confirmation for Elisp links."
1819 :group 'org-link-follow
1820 :version "24.1"
1821 :type 'regexp)
1823 (defconst org-file-apps-defaults-gnu
1824 '((remote . emacs)
1825 (system . mailcap)
1826 (t . mailcap))
1827 "Default file applications on a UNIX or GNU/Linux system.
1828 See `org-file-apps'.")
1830 (defconst org-file-apps-defaults-macosx
1831 '((remote . emacs)
1832 (t . "open %s")
1833 (system . "open %s")
1834 ("ps.gz" . "gv %s")
1835 ("eps.gz" . "gv %s")
1836 ("dvi" . "xdvi %s")
1837 ("fig" . "xfig %s"))
1838 "Default file applications on a MacOS X system.
1839 The system \"open\" is known as a default, but we use X11 applications
1840 for some files for which the OS does not have a good default.
1841 See `org-file-apps'.")
1843 (defconst org-file-apps-defaults-windowsnt
1844 (list
1845 '(remote . emacs)
1846 (cons t
1847 (list (if (featurep 'xemacs)
1848 'mswindows-shell-execute
1849 'w32-shell-execute)
1850 "open" 'file))
1851 (cons 'system
1852 (list (if (featurep 'xemacs)
1853 'mswindows-shell-execute
1854 'w32-shell-execute)
1855 "open" 'file)))
1856 "Default file applications on a Windows NT system.
1857 The system \"open\" is used for most files.
1858 See `org-file-apps'.")
1860 (defcustom org-file-apps
1862 (auto-mode . emacs)
1863 ("\\.mm\\'" . default)
1864 ("\\.x?html?\\'" . default)
1865 ("\\.pdf\\'" . default)
1867 "External applications for opening `file:path' items in a document.
1868 Org-mode uses system defaults for different file types, but
1869 you can use this variable to set the application for a given file
1870 extension. The entries in this list are cons cells where the car identifies
1871 files and the cdr the corresponding command. Possible values for the
1872 file identifier are
1873 \"string\" A string as a file identifier can be interpreted in different
1874 ways, depending on its contents:
1876 - Alphanumeric characters only:
1877 Match links with this file extension.
1878 Example: (\"pdf\" . \"evince %s\")
1879 to open PDFs with evince.
1881 - Regular expression: Match links where the
1882 filename matches the regexp. If you want to
1883 use groups here, use shy groups.
1885 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1886 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1887 to open *.html and *.xhtml with firefox.
1889 - Regular expression which contains (non-shy) groups:
1890 Match links where the whole link, including \"::\", and
1891 anything after that, matches the regexp.
1892 In a custom command string, %1, %2, etc. are replaced with
1893 the parts of the link that were matched by the groups.
1894 For backwards compatibility, if a command string is given
1895 that does not use any of the group matches, this case is
1896 handled identically to the second one (i.e. match against
1897 file name only).
1898 In a custom lisp form, you can access the group matches with
1899 (match-string n link).
1901 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1902 to open [[file:document.pdf::5]] with evince at page 5.
1904 `directory' Matches a directory
1905 `remote' Matches a remote file, accessible through tramp or efs.
1906 Remote files most likely should be visited through Emacs
1907 because external applications cannot handle such paths.
1908 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1909 so all files Emacs knows how to handle. Using this with
1910 command `emacs' will open most files in Emacs. Beware that this
1911 will also open html files inside Emacs, unless you add
1912 (\"html\" . default) to the list as well.
1913 t Default for files not matched by any of the other options.
1914 `system' The system command to open files, like `open' on Windows
1915 and Mac OS X, and mailcap under GNU/Linux. This is the command
1916 that will be selected if you call `C-c C-o' with a double
1917 \\[universal-argument] \\[universal-argument] prefix.
1919 Possible values for the command are:
1920 `emacs' The file will be visited by the current Emacs process.
1921 `default' Use the default application for this file type, which is the
1922 association for t in the list, most likely in the system-specific
1923 part.
1924 This can be used to overrule an unwanted setting in the
1925 system-specific variable.
1926 `system' Use the system command for opening files, like \"open\".
1927 This command is specified by the entry whose car is `system'.
1928 Most likely, the system-specific version of this variable
1929 does define this command, but you can overrule/replace it
1930 here.
1931 string A command to be executed by a shell; %s will be replaced
1932 by the path to the file.
1933 sexp A Lisp form which will be evaluated. The file path will
1934 be available in the Lisp variable `file'.
1935 For more examples, see the system specific constants
1936 `org-file-apps-defaults-macosx'
1937 `org-file-apps-defaults-windowsnt'
1938 `org-file-apps-defaults-gnu'."
1939 :group 'org-link-follow
1940 :type '(repeat
1941 (cons (choice :value ""
1942 (string :tag "Extension")
1943 (const :tag "System command to open files" system)
1944 (const :tag "Default for unrecognized files" t)
1945 (const :tag "Remote file" remote)
1946 (const :tag "Links to a directory" directory)
1947 (const :tag "Any files that have Emacs modes"
1948 auto-mode))
1949 (choice :value ""
1950 (const :tag "Visit with Emacs" emacs)
1951 (const :tag "Use default" default)
1952 (const :tag "Use the system command" system)
1953 (string :tag "Command")
1954 (sexp :tag "Lisp form")))))
1956 (defcustom org-doi-server-url "http://dx.doi.org/"
1957 "The URL of the DOI server."
1958 :type 'string
1959 :version "24.3"
1960 :group 'org-link-follow)
1962 (defgroup org-refile nil
1963 "Options concerning refiling entries in Org-mode."
1964 :tag "Org Refile"
1965 :group 'org)
1967 (defcustom org-directory "~/org"
1968 "Directory with org files.
1969 This is just a default location to look for Org files. There is no need
1970 at all to put your files into this directory. It is only used in the
1971 following situations:
1973 1. When a capture template specifies a target file that is not an
1974 absolute path. The path will then be interpreted relative to
1975 `org-directory'
1976 2. When a capture note is filed away in an interactive way (when exiting the
1977 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1978 with `org-directory' as the default path."
1979 :group 'org-refile
1980 :group 'org-remember
1981 :group 'org-capture
1982 :type 'directory)
1984 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1985 "Default target for storing notes.
1986 Used as a fall back file for org-remember.el and org-capture.el, for
1987 templates that do not specify a target file."
1988 :group 'org-refile
1989 :group 'org-remember
1990 :group 'org-capture
1991 :type '(choice
1992 (const :tag "Default from remember-data-file" nil)
1993 file))
1995 (defcustom org-goto-interface 'outline
1996 "The default interface to be used for `org-goto'.
1997 Allowed values are:
1998 outline The interface shows an outline of the relevant file
1999 and the correct heading is found by moving through
2000 the outline or by searching with incremental search.
2001 outline-path-completion Headlines in the current buffer are offered via
2002 completion. This is the interface also used by
2003 the refile command."
2004 :group 'org-refile
2005 :type '(choice
2006 (const :tag "Outline" outline)
2007 (const :tag "Outline-path-completion" outline-path-completion)))
2009 (defcustom org-goto-max-level 5
2010 "Maximum target level when running `org-goto' with refile interface."
2011 :group 'org-refile
2012 :type 'integer)
2014 (defcustom org-reverse-note-order nil
2015 "Non-nil means store new notes at the beginning of a file or entry.
2016 When nil, new notes will be filed to the end of a file or entry.
2017 This can also be a list with cons cells of regular expressions that
2018 are matched against file names, and values."
2019 :group 'org-remember
2020 :group 'org-capture
2021 :group 'org-refile
2022 :type '(choice
2023 (const :tag "Reverse always" t)
2024 (const :tag "Reverse never" nil)
2025 (repeat :tag "By file name regexp"
2026 (cons regexp boolean))))
2028 (defcustom org-log-refile nil
2029 "Information to record when a task is refiled.
2031 Possible values are:
2033 nil Don't add anything
2034 time Add a time stamp to the task
2035 note Prompt for a note and add it with template `org-log-note-headings'
2037 This option can also be set with on a per-file-basis with
2039 #+STARTUP: nologrefile
2040 #+STARTUP: logrefile
2041 #+STARTUP: lognoterefile
2043 You can have local logging settings for a subtree by setting the LOGGING
2044 property to one or more of these keywords.
2046 When bulk-refiling from the agenda, the value `note' is forbidden and
2047 will temporarily be changed to `time'."
2048 :group 'org-refile
2049 :group 'org-progress
2050 :version "24.1"
2051 :type '(choice
2052 (const :tag "No logging" nil)
2053 (const :tag "Record timestamp" time)
2054 (const :tag "Record timestamp with note." note)))
2056 (defcustom org-refile-targets nil
2057 "Targets for refiling entries with \\[org-refile].
2058 This is a list of cons cells. Each cell contains:
2059 - a specification of the files to be considered, either a list of files,
2060 or a symbol whose function or variable value will be used to retrieve
2061 a file name or a list of file names. If you use `org-agenda-files' for
2062 that, all agenda files will be scanned for targets. Nil means consider
2063 headings in the current buffer.
2064 - A specification of how to find candidate refile targets. This may be
2065 any of:
2066 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2067 This tag has to be present in all target headlines, inheritance will
2068 not be considered.
2069 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2070 todo keyword.
2071 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2072 headlines that are refiling targets.
2073 - a cons cell (:level . N). Any headline of level N is considered a target.
2074 Note that, when `org-odd-levels-only' is set, level corresponds to
2075 order in hierarchy, not to the number of stars.
2076 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2077 Note that, when `org-odd-levels-only' is set, level corresponds to
2078 order in hierarchy, not to the number of stars.
2080 Each element of this list generates a set of possible targets.
2081 The union of these sets is presented (with completion) to
2082 the user by `org-refile'.
2084 You can set the variable `org-refile-target-verify-function' to a function
2085 to verify each headline found by the simple criteria above.
2087 When this variable is nil, all top-level headlines in the current buffer
2088 are used, equivalent to the value `((nil . (:level . 1))'."
2089 :group 'org-refile
2090 :type '(repeat
2091 (cons
2092 (choice :value org-agenda-files
2093 (const :tag "All agenda files" org-agenda-files)
2094 (const :tag "Current buffer" nil)
2095 (function) (variable) (file))
2096 (choice :tag "Identify target headline by"
2097 (cons :tag "Specific tag" (const :value :tag) (string))
2098 (cons :tag "TODO keyword" (const :value :todo) (string))
2099 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2100 (cons :tag "Level number" (const :value :level) (integer))
2101 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2103 (defcustom org-refile-target-verify-function nil
2104 "Function to verify if the headline at point should be a refile target.
2105 The function will be called without arguments, with point at the
2106 beginning of the headline. It should return t and leave point
2107 where it is if the headline is a valid target for refiling.
2109 If the target should not be selected, the function must return nil.
2110 In addition to this, it may move point to a place from where the search
2111 should be continued. For example, the function may decide that the entire
2112 subtree of the current entry should be excluded and move point to the end
2113 of the subtree."
2114 :group 'org-refile
2115 :type 'function)
2117 (defcustom org-refile-use-cache nil
2118 "Non-nil means cache refile targets to speed up the process.
2119 The cache for a particular file will be updated automatically when
2120 the buffer has been killed, or when any of the marker used for flagging
2121 refile targets no longer points at a live buffer.
2122 If you have added new entries to a buffer that might themselves be targets,
2123 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2124 find that easier, `C-u C-u C-u C-c C-w'."
2125 :group 'org-refile
2126 :version "24.1"
2127 :type 'boolean)
2129 (defcustom org-refile-use-outline-path nil
2130 "Non-nil means provide refile targets as paths.
2131 So a level 3 headline will be available as level1/level2/level3.
2133 When the value is `file', also include the file name (without directory)
2134 into the path. In this case, you can also stop the completion after
2135 the file name, to get entries inserted as top level in the file.
2137 When `full-file-path', include the full file path."
2138 :group 'org-refile
2139 :type '(choice
2140 (const :tag "Not" nil)
2141 (const :tag "Yes" t)
2142 (const :tag "Start with file name" file)
2143 (const :tag "Start with full file path" full-file-path)))
2145 (defcustom org-outline-path-complete-in-steps t
2146 "Non-nil means complete the outline path in hierarchical steps.
2147 When Org-mode uses the refile interface to select an outline path
2148 \(see variable `org-refile-use-outline-path'), the completion of
2149 the path can be done is a single go, or if can be done in steps down
2150 the headline hierarchy. Going in steps is probably the best if you
2151 do not use a special completion package like `ido' or `icicles'.
2152 However, when using these packages, going in one step can be very
2153 fast, while still showing the whole path to the entry."
2154 :group 'org-refile
2155 :type 'boolean)
2157 (defcustom org-refile-allow-creating-parent-nodes nil
2158 "Non-nil means allow to create new nodes as refile targets.
2159 New nodes are then created by adding \"/new node name\" to the completion
2160 of an existing node. When the value of this variable is `confirm',
2161 new node creation must be confirmed by the user (recommended)
2162 When nil, the completion must match an existing entry.
2164 Note that, if the new heading is not seen by the criteria
2165 listed in `org-refile-targets', multiple instances of the same
2166 heading would be created by trying again to file under the new
2167 heading."
2168 :group 'org-refile
2169 :type '(choice
2170 (const :tag "Never" nil)
2171 (const :tag "Always" t)
2172 (const :tag "Prompt for confirmation" confirm)))
2174 (defcustom org-refile-active-region-within-subtree nil
2175 "Non-nil means also refile active region within a subtree.
2177 By default `org-refile' doesn't allow refiling regions if they
2178 don't contain a set of subtrees, but it might be convenient to
2179 do so sometimes: in that case, the first line of the region is
2180 converted to a headline before refiling."
2181 :group 'org-refile
2182 :version "24.1"
2183 :type 'boolean)
2185 (defgroup org-todo nil
2186 "Options concerning TODO items in Org-mode."
2187 :tag "Org TODO"
2188 :group 'org)
2190 (defgroup org-progress nil
2191 "Options concerning Progress logging in Org-mode."
2192 :tag "Org Progress"
2193 :group 'org-time)
2195 (defvar org-todo-interpretation-widgets
2196 '((:tag "Sequence (cycling hits every state)" sequence)
2197 (:tag "Type (cycling directly to DONE)" type))
2198 "The available interpretation symbols for customizing `org-todo-keywords'.
2199 Interested libraries should add to this list.")
2201 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2202 "List of TODO entry keyword sequences and their interpretation.
2203 \\<org-mode-map>This is a list of sequences.
2205 Each sequence starts with a symbol, either `sequence' or `type',
2206 indicating if the keywords should be interpreted as a sequence of
2207 action steps, or as different types of TODO items. The first
2208 keywords are states requiring action - these states will select a headline
2209 for inclusion into the global TODO list Org-mode produces. If one of
2210 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2211 signify that no further action is necessary. If \"|\" is not found,
2212 the last keyword is treated as the only DONE state of the sequence.
2214 The command \\[org-todo] cycles an entry through these states, and one
2215 additional state where no keyword is present. For details about this
2216 cycling, see the manual.
2218 TODO keywords and interpretation can also be set on a per-file basis with
2219 the special #+SEQ_TODO and #+TYP_TODO lines.
2221 Each keyword can optionally specify a character for fast state selection
2222 \(in combination with the variable `org-use-fast-todo-selection')
2223 and specifiers for state change logging, using the same syntax that
2224 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2225 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2226 indicates to record a time stamp each time this state is selected.
2228 Each keyword may also specify if a timestamp or a note should be
2229 recorded when entering or leaving the state, by adding additional
2230 characters in the parenthesis after the keyword. This looks like this:
2231 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2232 record only the time of the state change. With X and Y being either
2233 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2234 Y when leaving the state if and only if the *target* state does not
2235 define X. You may omit any of the fast-selection key or X or /Y,
2236 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2238 For backward compatibility, this variable may also be just a list
2239 of keywords. In this case the interpretation (sequence or type) will be
2240 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2241 :group 'org-todo
2242 :group 'org-keywords
2243 :type '(choice
2244 (repeat :tag "Old syntax, just keywords"
2245 (string :tag "Keyword"))
2246 (repeat :tag "New syntax"
2247 (cons
2248 (choice
2249 :tag "Interpretation"
2250 ;;Quick and dirty way to see
2251 ;;`org-todo-interpretations'. This takes the
2252 ;;place of item arguments
2253 :convert-widget
2254 (lambda (widget)
2255 (widget-put widget
2256 :args (mapcar
2257 #'(lambda (x)
2258 (widget-convert
2259 (cons 'const x)))
2260 org-todo-interpretation-widgets))
2261 widget))
2262 (repeat
2263 (string :tag "Keyword"))))))
2265 (defvar org-todo-keywords-1 nil
2266 "All TODO and DONE keywords active in a buffer.")
2267 (make-variable-buffer-local 'org-todo-keywords-1)
2268 (defvar org-todo-keywords-for-agenda nil)
2269 (defvar org-done-keywords-for-agenda nil)
2270 (defvar org-drawers-for-agenda nil)
2271 (defvar org-todo-keyword-alist-for-agenda nil)
2272 (defvar org-tag-alist-for-agenda nil)
2273 (defvar org-agenda-contributing-files nil)
2274 (defvar org-not-done-keywords nil)
2275 (make-variable-buffer-local 'org-not-done-keywords)
2276 (defvar org-done-keywords nil)
2277 (make-variable-buffer-local 'org-done-keywords)
2278 (defvar org-todo-heads nil)
2279 (make-variable-buffer-local 'org-todo-heads)
2280 (defvar org-todo-sets nil)
2281 (make-variable-buffer-local 'org-todo-sets)
2282 (defvar org-todo-log-states nil)
2283 (make-variable-buffer-local 'org-todo-log-states)
2284 (defvar org-todo-kwd-alist nil)
2285 (make-variable-buffer-local 'org-todo-kwd-alist)
2286 (defvar org-todo-key-alist nil)
2287 (make-variable-buffer-local 'org-todo-key-alist)
2288 (defvar org-todo-key-trigger nil)
2289 (make-variable-buffer-local 'org-todo-key-trigger)
2291 (defcustom org-todo-interpretation 'sequence
2292 "Controls how TODO keywords are interpreted.
2293 This variable is in principle obsolete and is only used for
2294 backward compatibility, if the interpretation of todo keywords is
2295 not given already in `org-todo-keywords'. See that variable for
2296 more information."
2297 :group 'org-todo
2298 :group 'org-keywords
2299 :type '(choice (const sequence)
2300 (const type)))
2302 (defcustom org-use-fast-todo-selection t
2303 "Non-nil means use the fast todo selection scheme with C-c C-t.
2304 This variable describes if and under what circumstances the cycling
2305 mechanism for TODO keywords will be replaced by a single-key, direct
2306 selection scheme.
2308 When nil, fast selection is never used.
2310 When the symbol `prefix', it will be used when `org-todo' is called
2311 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2312 `C-u t' in an agenda buffer.
2314 When t, fast selection is used by default. In this case, the prefix
2315 argument forces cycling instead.
2317 In all cases, the special interface is only used if access keys have
2318 actually been assigned by the user, i.e. if keywords in the configuration
2319 are followed by a letter in parenthesis, like TODO(t)."
2320 :group 'org-todo
2321 :type '(choice
2322 (const :tag "Never" nil)
2323 (const :tag "By default" t)
2324 (const :tag "Only with C-u C-c C-t" prefix)))
2326 (defcustom org-provide-todo-statistics t
2327 "Non-nil means update todo statistics after insert and toggle.
2328 ALL-HEADLINES means update todo statistics by including headlines
2329 with no TODO keyword as well, counting them as not done.
2330 A list of TODO keywords means the same, but skip keywords that are
2331 not in this list.
2333 When this is set, todo statistics is updated in the parent of the
2334 current entry each time a todo state is changed."
2335 :group 'org-todo
2336 :type '(choice
2337 (const :tag "Yes, only for TODO entries" t)
2338 (const :tag "Yes, including all entries" 'all-headlines)
2339 (repeat :tag "Yes, for TODOs in this list"
2340 (string :tag "TODO keyword"))
2341 (other :tag "No TODO statistics" nil)))
2343 (defcustom org-hierarchical-todo-statistics t
2344 "Non-nil means TODO statistics covers just direct children.
2345 When nil, all entries in the subtree are considered.
2346 This has only an effect if `org-provide-todo-statistics' is set.
2347 To set this to nil for only a single subtree, use a COOKIE_DATA
2348 property and include the word \"recursive\" into the value."
2349 :group 'org-todo
2350 :type 'boolean)
2352 (defcustom org-after-todo-state-change-hook nil
2353 "Hook which is run after the state of a TODO item was changed.
2354 The new state (a string with a TODO keyword, or nil) is available in the
2355 Lisp variable `org-state'."
2356 :group 'org-todo
2357 :type 'hook)
2359 (defvar org-blocker-hook nil
2360 "Hook for functions that are allowed to block a state change.
2362 Functions in this hook should not modify the buffer.
2363 Each function gets as its single argument a property list,
2364 see `org-trigger-hook' for more information about this list.
2366 If any of the functions in this hook returns nil, the state change
2367 is blocked.")
2369 (defvar org-trigger-hook nil
2370 "Hook for functions that are triggered by a state change.
2372 Each function gets as its single argument a property list with at
2373 least the following elements:
2375 (:type type-of-change :position pos-at-entry-start
2376 :from old-state :to new-state)
2378 Depending on the type, more properties may be present.
2380 This mechanism is currently implemented for:
2382 TODO state changes
2383 ------------------
2384 :type todo-state-change
2385 :from previous state (keyword as a string), or nil, or a symbol
2386 'todo' or 'done', to indicate the general type of state.
2387 :to new state, like in :from")
2389 (defcustom org-enforce-todo-dependencies nil
2390 "Non-nil means undone TODO entries will block switching the parent to DONE.
2391 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2392 be blocked if any prior sibling is not yet done.
2393 Finally, if the parent is blocked because of ordered siblings of its own,
2394 the child will also be blocked."
2395 :set (lambda (var val)
2396 (set var val)
2397 (if val
2398 (add-hook 'org-blocker-hook
2399 'org-block-todo-from-children-or-siblings-or-parent)
2400 (remove-hook 'org-blocker-hook
2401 'org-block-todo-from-children-or-siblings-or-parent)))
2402 :group 'org-todo
2403 :type 'boolean)
2405 (defcustom org-enforce-todo-checkbox-dependencies nil
2406 "Non-nil means unchecked boxes will block switching the parent to DONE.
2407 When this is nil, checkboxes have no influence on switching TODO states.
2408 When non-nil, you first need to check off all check boxes before the TODO
2409 entry can be switched to DONE.
2410 This variable needs to be set before org.el is loaded, and you need to
2411 restart Emacs after a change to make the change effective. The only way
2412 to change is while Emacs is running is through the customize interface."
2413 :set (lambda (var val)
2414 (set var val)
2415 (if val
2416 (add-hook 'org-blocker-hook
2417 'org-block-todo-from-checkboxes)
2418 (remove-hook 'org-blocker-hook
2419 'org-block-todo-from-checkboxes)))
2420 :group 'org-todo
2421 :type 'boolean)
2423 (defcustom org-treat-insert-todo-heading-as-state-change nil
2424 "Non-nil means inserting a TODO heading is treated as state change.
2425 So when the command \\[org-insert-todo-heading] is used, state change
2426 logging will apply if appropriate. When nil, the new TODO item will
2427 be inserted directly, and no logging will take place."
2428 :group 'org-todo
2429 :type 'boolean)
2431 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2432 "Non-nil means switching TODO states with S-cursor counts as state change.
2433 This is the default behavior. However, setting this to nil allows a
2434 convenient way to select a TODO state and bypass any logging associated
2435 with that."
2436 :group 'org-todo
2437 :type 'boolean)
2439 (defcustom org-todo-state-tags-triggers nil
2440 "Tag changes that should be triggered by TODO state changes.
2441 This is a list. Each entry is
2443 (state-change (tag . flag) .......)
2445 State-change can be a string with a state, and empty string to indicate the
2446 state that has no TODO keyword, or it can be one of the symbols `todo'
2447 or `done', meaning any not-done or done state, respectively."
2448 :group 'org-todo
2449 :group 'org-tags
2450 :type '(repeat
2451 (cons (choice :tag "When changing to"
2452 (const :tag "Not-done state" todo)
2453 (const :tag "Done state" done)
2454 (string :tag "State"))
2455 (repeat
2456 (cons :tag "Tag action"
2457 (string :tag "Tag")
2458 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2460 (defcustom org-log-done nil
2461 "Information to record when a task moves to the DONE state.
2463 Possible values are:
2465 nil Don't add anything, just change the keyword
2466 time Add a time stamp to the task
2467 note Prompt for a note and add it with template `org-log-note-headings'
2469 This option can also be set with on a per-file-basis with
2471 #+STARTUP: nologdone
2472 #+STARTUP: logdone
2473 #+STARTUP: lognotedone
2475 You can have local logging settings for a subtree by setting the LOGGING
2476 property to one or more of these keywords."
2477 :group 'org-todo
2478 :group 'org-progress
2479 :type '(choice
2480 (const :tag "No logging" nil)
2481 (const :tag "Record CLOSED timestamp" time)
2482 (const :tag "Record CLOSED timestamp with note." note)))
2484 ;; Normalize old uses of org-log-done.
2485 (cond
2486 ((eq org-log-done t) (setq org-log-done 'time))
2487 ((and (listp org-log-done) (memq 'done org-log-done))
2488 (setq org-log-done 'note)))
2490 (defcustom org-log-reschedule nil
2491 "Information to record when the scheduling date of a tasks is modified.
2493 Possible values are:
2495 nil Don't add anything, just change the date
2496 time Add a time stamp to the task
2497 note Prompt for a note and add it with template `org-log-note-headings'
2499 This option can also be set with on a per-file-basis with
2501 #+STARTUP: nologreschedule
2502 #+STARTUP: logreschedule
2503 #+STARTUP: lognotereschedule"
2504 :group 'org-todo
2505 :group 'org-progress
2506 :type '(choice
2507 (const :tag "No logging" nil)
2508 (const :tag "Record timestamp" time)
2509 (const :tag "Record timestamp with note." note)))
2511 (defcustom org-log-redeadline nil
2512 "Information to record when the deadline date of a tasks is modified.
2514 Possible values are:
2516 nil Don't add anything, just change the date
2517 time Add a time stamp to the task
2518 note Prompt for a note and add it with template `org-log-note-headings'
2520 This option can also be set with on a per-file-basis with
2522 #+STARTUP: nologredeadline
2523 #+STARTUP: logredeadline
2524 #+STARTUP: lognoteredeadline
2526 You can have local logging settings for a subtree by setting the LOGGING
2527 property to one or more of these keywords."
2528 :group 'org-todo
2529 :group 'org-progress
2530 :type '(choice
2531 (const :tag "No logging" nil)
2532 (const :tag "Record timestamp" time)
2533 (const :tag "Record timestamp with note." note)))
2535 (defcustom org-log-note-clock-out nil
2536 "Non-nil means record a note when clocking out of an item.
2537 This can also be configured on a per-file basis by adding one of
2538 the following lines anywhere in the buffer:
2540 #+STARTUP: lognoteclock-out
2541 #+STARTUP: nolognoteclock-out"
2542 :group 'org-todo
2543 :group 'org-progress
2544 :type 'boolean)
2546 (defcustom org-log-done-with-time t
2547 "Non-nil means the CLOSED time stamp will contain date and time.
2548 When nil, only the date will be recorded."
2549 :group 'org-progress
2550 :type 'boolean)
2552 (defcustom org-log-note-headings
2553 '((done . "CLOSING NOTE %t")
2554 (state . "State %-12s from %-12S %t")
2555 (note . "Note taken on %t")
2556 (reschedule . "Rescheduled from %S on %t")
2557 (delschedule . "Not scheduled, was %S on %t")
2558 (redeadline . "New deadline from %S on %t")
2559 (deldeadline . "Removed deadline, was %S on %t")
2560 (refile . "Refiled on %t")
2561 (clock-out . ""))
2562 "Headings for notes added to entries.
2563 The value is an alist, with the car being a symbol indicating the note
2564 context, and the cdr is the heading to be used. The heading may also be the
2565 empty string.
2566 %t in the heading will be replaced by a time stamp.
2567 %T will be an active time stamp instead the default inactive one
2568 %d will be replaced by a short-format time stamp.
2569 %D will be replaced by an active short-format time stamp.
2570 %s will be replaced by the new TODO state, in double quotes.
2571 %S will be replaced by the old TODO state, in double quotes.
2572 %u will be replaced by the user name.
2573 %U will be replaced by the full user name.
2575 In fact, it is not a good idea to change the `state' entry, because
2576 agenda log mode depends on the format of these entries."
2577 :group 'org-todo
2578 :group 'org-progress
2579 :type '(list :greedy t
2580 (cons (const :tag "Heading when closing an item" done) string)
2581 (cons (const :tag
2582 "Heading when changing todo state (todo sequence only)"
2583 state) string)
2584 (cons (const :tag "Heading when just taking a note" note) string)
2585 (cons (const :tag "Heading when clocking out" clock-out) string)
2586 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2587 (cons (const :tag "Heading when rescheduling" reschedule) string)
2588 (cons (const :tag "Heading when changing deadline" redeadline) string)
2589 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2590 (cons (const :tag "Heading when refiling" refile) string)))
2592 (unless (assq 'note org-log-note-headings)
2593 (push '(note . "%t") org-log-note-headings))
2595 (defcustom org-log-into-drawer nil
2596 "Non-nil means insert state change notes and time stamps into a drawer.
2597 When nil, state changes notes will be inserted after the headline and
2598 any scheduling and clock lines, but not inside a drawer.
2600 The value of this variable should be the name of the drawer to use.
2601 LOGBOOK is proposed as the default drawer for this purpose, you can
2602 also set this to a string to define the drawer of your choice.
2604 A value of t is also allowed, representing \"LOGBOOK\".
2606 A value of t or nil can also be set with on a per-file-basis with
2608 #+STARTUP: logdrawer
2609 #+STARTUP: nologdrawer
2611 If this variable is set, `org-log-state-notes-insert-after-drawers'
2612 will be ignored.
2614 You can set the property LOG_INTO_DRAWER to overrule this setting for
2615 a subtree."
2616 :group 'org-todo
2617 :group 'org-progress
2618 :type '(choice
2619 (const :tag "Not into a drawer" nil)
2620 (const :tag "LOGBOOK" t)
2621 (string :tag "Other")))
2623 (if (fboundp 'defvaralias)
2624 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2626 (defun org-log-into-drawer ()
2627 "Return the value of `org-log-into-drawer', but let properties overrule.
2628 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2629 used instead of the default value."
2630 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2631 (cond
2632 ((not p) org-log-into-drawer)
2633 ((equal p "nil") nil)
2634 ((equal p "t") "LOGBOOK")
2635 (t p))))
2637 (defcustom org-log-state-notes-insert-after-drawers nil
2638 "Non-nil means insert state change notes after any drawers in entry.
2639 Only the drawers that *immediately* follow the headline and the
2640 deadline/scheduled line are skipped.
2641 When nil, insert notes right after the heading and perhaps the line
2642 with deadline/scheduling if present.
2644 This variable will have no effect if `org-log-into-drawer' is
2645 set."
2646 :group 'org-todo
2647 :group 'org-progress
2648 :type 'boolean)
2650 (defcustom org-log-states-order-reversed t
2651 "Non-nil means the latest state note will be directly after heading.
2652 When nil, the state change notes will be ordered according to time.
2654 This option can also be set with on a per-file-basis with
2656 #+STARTUP: logstatesreversed
2657 #+STARTUP: nologstatesreversed"
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-todo-repeat-to-state nil
2663 "The TODO state to which a repeater should return the repeating task.
2664 By default this is the first task in a TODO sequence, or the previous state
2665 in a TODO_TYP set. But you can specify another task here.
2666 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2667 :group 'org-todo
2668 :version "24.1"
2669 :type '(choice (const :tag "Head of sequence" nil)
2670 (string :tag "Specific state")))
2672 (defcustom org-log-repeat 'time
2673 "Non-nil means record moving through the DONE state when triggering repeat.
2674 An auto-repeating task is immediately switched back to TODO when
2675 marked DONE. If you are not logging state changes (by adding \"@\"
2676 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2677 record a closing note, there will be no record of the task moving
2678 through DONE. This variable forces taking a note anyway.
2680 nil Don't force a record
2681 time Record a time stamp
2682 note Prompt for a note and add it with template `org-log-note-headings'
2684 This option can also be set with on a per-file-basis with
2686 #+STARTUP: nologrepeat
2687 #+STARTUP: logrepeat
2688 #+STARTUP: lognoterepeat
2690 You can have local logging settings for a subtree by setting the LOGGING
2691 property to one or more of these keywords."
2692 :group 'org-todo
2693 :group 'org-progress
2694 :type '(choice
2695 (const :tag "Don't force a record" nil)
2696 (const :tag "Force recording the DONE state" time)
2697 (const :tag "Force recording a note with the DONE state" note)))
2700 (defgroup org-priorities nil
2701 "Priorities in Org-mode."
2702 :tag "Org Priorities"
2703 :group 'org-todo)
2705 (defcustom org-enable-priority-commands t
2706 "Non-nil means priority commands are active.
2707 When nil, these commands will be disabled, so that you never accidentally
2708 set a priority."
2709 :group 'org-priorities
2710 :type 'boolean)
2712 (defcustom org-highest-priority ?A
2713 "The highest priority of TODO items. A character like ?A, ?B etc.
2714 Must have a smaller ASCII number than `org-lowest-priority'."
2715 :group 'org-priorities
2716 :type 'character)
2718 (defcustom org-lowest-priority ?C
2719 "The lowest priority of TODO items. A character like ?A, ?B etc.
2720 Must have a larger ASCII number than `org-highest-priority'."
2721 :group 'org-priorities
2722 :type 'character)
2724 (defcustom org-default-priority ?B
2725 "The default priority of TODO items.
2726 This is the priority an item gets if no explicit priority is given.
2727 When starting to cycle on an empty priority the first step in the cycle
2728 depends on `org-priority-start-cycle-with-default'. The resulting first
2729 step priority must not exceed the range from `org-highest-priority' to
2730 `org-lowest-priority' which means that `org-default-priority' has to be
2731 in this range exclusive or inclusive the range boundaries. Else the
2732 first step refuses to set the default and the second will fall back
2733 to (depending on the command used) the highest or lowest priority."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-priority-start-cycle-with-default t
2738 "Non-nil means start with default priority when starting to cycle.
2739 When this is nil, the first step in the cycle will be (depending on the
2740 command used) one higher or lower than the default priority.
2741 See also `org-default-priority'."
2742 :group 'org-priorities
2743 :type 'boolean)
2745 (defcustom org-get-priority-function nil
2746 "Function to extract the priority from a string.
2747 The string is normally the headline. If this is nil Org computes the
2748 priority from the priority cookie like [#A] in the headline. It returns
2749 an integer, increasing by 1000 for each priority level.
2750 The user can set a different function here, which should take a string
2751 as an argument and return the numeric priority."
2752 :group 'org-priorities
2753 :version "24.1"
2754 :type 'function)
2756 (defgroup org-time nil
2757 "Options concerning time stamps and deadlines in Org-mode."
2758 :tag "Org Time"
2759 :group 'org)
2761 (defcustom org-insert-labeled-timestamps-at-point nil
2762 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2763 When nil, these labeled time stamps are forces into the second line of an
2764 entry, just after the headline. When scheduling from the global TODO list,
2765 the time stamp will always be forced into the second line."
2766 :group 'org-time
2767 :type 'boolean)
2769 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2770 "Formats for `format-time-string' which are used for time stamps.
2771 It is not recommended to change this constant.")
2773 (defcustom org-time-stamp-rounding-minutes '(0 5)
2774 "Number of minutes to round time stamps to.
2775 These are two values, the first applies when first creating a time stamp.
2776 The second applies when changing it with the commands `S-up' and `S-down'.
2777 When changing the time stamp, this means that it will change in steps
2778 of N minutes, as given by the second value.
2780 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2781 numbers should be factors of 60, so for example 5, 10, 15.
2783 When this is larger than 1, you can still force an exact time stamp by using
2784 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2785 and by using a prefix arg to `S-up/down' to specify the exact number
2786 of minutes to shift."
2787 :group 'org-time
2788 :get #'(lambda (var) ; Make sure both elements are there
2789 (if (integerp (default-value var))
2790 (list (default-value var) 5)
2791 (default-value var)))
2792 :type '(list
2793 (integer :tag "when inserting times")
2794 (integer :tag "when modifying times")))
2796 ;; Normalize old customizations of this variable.
2797 (when (integerp org-time-stamp-rounding-minutes)
2798 (setq org-time-stamp-rounding-minutes
2799 (list org-time-stamp-rounding-minutes
2800 org-time-stamp-rounding-minutes)))
2802 (defcustom org-display-custom-times nil
2803 "Non-nil means overlay custom formats over all time stamps.
2804 The formats are defined through the variable `org-time-stamp-custom-formats'.
2805 To turn this on on a per-file basis, insert anywhere in the file:
2806 #+STARTUP: customtime"
2807 :group 'org-time
2808 :set 'set-default
2809 :type 'sexp)
2810 (make-variable-buffer-local 'org-display-custom-times)
2812 (defcustom org-time-stamp-custom-formats
2813 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2814 "Custom formats for time stamps. See `format-time-string' for the syntax.
2815 These are overlaid over the default ISO format if the variable
2816 `org-display-custom-times' is set. Time like %H:%M should be at the
2817 end of the second format. The custom formats are also honored by export
2818 commands, if custom time display is turned on at the time of export."
2819 :group 'org-time
2820 :type 'sexp)
2822 (defun org-time-stamp-format (&optional long inactive)
2823 "Get the right format for a time string."
2824 (let ((f (if long (cdr org-time-stamp-formats)
2825 (car org-time-stamp-formats))))
2826 (if inactive
2827 (concat "[" (substring f 1 -1) "]")
2828 f)))
2830 (defcustom org-time-clocksum-format
2831 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2832 "The format string used when creating CLOCKSUM lines.
2833 This is also used when Org mode generates a time duration.
2835 The value can be a single format string containing two
2836 %-sequences, which will be filled with the number of hours and
2837 minutes in that order.
2839 Alternatively, the value can be a plist associating any of the
2840 keys :years, :months, :weeks, :days, :hours or :minutes with
2841 format strings. The time duration is formatted using only the
2842 time components that are needed and concatenating the results.
2843 If a time unit in absent, it falls back to the next smallest
2844 unit.
2846 The keys :require-years, :require-months, :require-days,
2847 :require-weeks, :require-hours, :require-minutes are also
2848 meaningful. A non-nil value for these keys indicates that the
2849 corresponding time component should always be included, even if
2850 its value is 0.
2853 For example,
2855 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2856 :require-minutes t)
2858 means durations longer than a day will be expressed in days,
2859 hours and minutes, and durations less than a day will always be
2860 expressed in hours and minutes (even for durations less than an
2861 hour).
2863 The value
2865 \(:days \"%dd\" :minutes \"%dm\")
2867 means durations longer than a day will be expressed in days and
2868 minutes, and durations less than a day will be expressed entirely
2869 in minutes (even for durations longer than an hour)."
2870 :group 'org-time
2871 :group 'org-clock
2872 :version "24.3"
2873 :type '(choice (string :tag "Format string")
2874 (set :tag "Plist"
2875 (group :inline t (const :tag "Years" :years)
2876 (string :tag "Format string"))
2877 (group :inline t
2878 (const :tag "Always show years" :require-years)
2879 (const t))
2880 (group :inline t (const :tag "Months" :months)
2881 (string :tag "Format string"))
2882 (group :inline t
2883 (const :tag "Always show months" :require-months)
2884 (const t))
2885 (group :inline t (const :tag "Weeks" :weeks)
2886 (string :tag "Format string"))
2887 (group :inline t
2888 (const :tag "Always show weeks" :require-weeks)
2889 (const t))
2890 (group :inline t (const :tag "Days" :days)
2891 (string :tag "Format string"))
2892 (group :inline t
2893 (const :tag "Always show days" :require-days)
2894 (const t))
2895 (group :inline t (const :tag "Hours" :hours)
2896 (string :tag "Format string"))
2897 (group :inline t
2898 (const :tag "Always show hours" :require-hours)
2899 (const t))
2900 (group :inline t (const :tag "Minutes" :minutes)
2901 (string :tag "Format string"))
2902 (group :inline t
2903 (const :tag "Always show minutes" :require-minutes)
2904 (const t)))))
2906 (defcustom org-time-clocksum-use-fractional nil
2907 "When non-nil, \\[org-clock-display] uses fractional times.
2908 See `org-time-clocksum-format' for more on time clock formats."
2909 :group 'org-time
2910 :group 'org-clock
2911 :version "24.3"
2912 :type 'boolean)
2914 (defcustom org-time-clocksum-use-effort-durations t
2915 "When non-nil, \\[org-clock-display] uses effort durations.
2916 E.g. by default, one day is considered to be a 8 hours effort,
2917 so a task that has been clocked for 16 hours will be displayed
2918 as during 2 days in the clock display or in the clocktable.
2920 See `org-effort-durations' on how to set effort durations
2921 and `org-time-clocksum-format' for more on time clock formats."
2922 :group 'org-time
2923 :group 'org-clock
2924 :version "24.3"
2925 :type 'boolean)
2927 (defcustom org-time-clocksum-fractional-format "%.2f"
2928 "The format string used when creating CLOCKSUM lines,
2929 or when Org mode generates a time duration, if
2930 `org-time-clocksum-use-fractional' is enabled.
2932 The value can be a single format string containing one
2933 %-sequence, which will be filled with the number of hours as
2934 a float.
2936 Alternatively, the value can be a plist associating any of the
2937 keys :years, :months, :weeks, :days, :hours or :minutes with
2938 a format string. The time duration is formatted using the
2939 largest time unit which gives a non-zero integer part. If all
2940 specified formats have zero integer part, the smallest time unit
2941 is used."
2942 :group 'org-time
2943 :type '(choice (string :tag "Format string")
2944 (set (group :inline t (const :tag "Years" :years)
2945 (string :tag "Format string"))
2946 (group :inline t (const :tag "Months" :months)
2947 (string :tag "Format string"))
2948 (group :inline t (const :tag "Weeks" :weeks)
2949 (string :tag "Format string"))
2950 (group :inline t (const :tag "Days" :days)
2951 (string :tag "Format string"))
2952 (group :inline t (const :tag "Hours" :hours)
2953 (string :tag "Format string"))
2954 (group :inline t (const :tag "Minutes" :minutes)
2955 (string :tag "Format string")))))
2957 (defcustom org-deadline-warning-days 14
2958 "Number of days before expiration during which a deadline becomes active.
2959 This variable governs the display in sparse trees and in the agenda.
2960 When 0 or negative, it means use this number (the absolute value of it)
2961 even if a deadline has a different individual lead time specified.
2963 Custom commands can set this variable in the options section."
2964 :group 'org-time
2965 :group 'org-agenda-daily/weekly
2966 :type 'integer)
2968 (defcustom org-scheduled-delay-days 0
2969 "Number of days before a scheduled item becomes active.
2970 This variable governs the display in sparse trees and in the agenda.
2971 The default value (i.e. 0) means: don't delay scheduled item.
2972 When negative, it means use this number (the absolute value of it)
2973 even if a scheduled item has a different individual delay time
2974 specified.
2976 Custom commands can set this variable in the options section."
2977 :group 'org-time
2978 :group 'org-agenda-daily/weekly
2979 :version "24.3"
2980 :type 'integer)
2982 (defcustom org-read-date-prefer-future t
2983 "Non-nil means assume future for incomplete date input from user.
2984 This affects the following situations:
2985 1. The user gives a month but not a year.
2986 For example, if it is April and you enter \"feb 2\", this will be read
2987 as Feb 2, *next* year. \"May 5\", however, will be this year.
2988 2. The user gives a day, but no month.
2989 For example, if today is the 15th, and you enter \"3\", Org-mode will
2990 read this as the third of *next* month. However, if you enter \"17\",
2991 it will be considered as *this* month.
2993 If you set this variable to the symbol `time', then also the following
2994 will work:
2996 3. If the user gives a time.
2997 If the time is before now, it will be interpreted as tomorrow.
2999 Currently none of this works for ISO week specifications.
3001 When this option is nil, the current day, month and year will always be
3002 used as defaults.
3004 See also `org-agenda-jump-prefer-future'."
3005 :group 'org-time
3006 :type '(choice
3007 (const :tag "Never" nil)
3008 (const :tag "Check month and day" t)
3009 (const :tag "Check month, day, and time" time)))
3011 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3012 "Should the agenda jump command prefer the future for incomplete dates?
3013 The default is to do the same as configured in `org-read-date-prefer-future'.
3014 But you can also set a deviating value here.
3015 This may t or nil, or the symbol `org-read-date-prefer-future'."
3016 :group 'org-agenda
3017 :group 'org-time
3018 :version "24.1"
3019 :type '(choice
3020 (const :tag "Use org-read-date-prefer-future"
3021 org-read-date-prefer-future)
3022 (const :tag "Never" nil)
3023 (const :tag "Always" t)))
3025 (defcustom org-read-date-force-compatible-dates t
3026 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3028 Depending on the system Emacs is running on, certain dates cannot
3029 be represented with the type used internally to represent time.
3030 Dates between 1970-1-1 and 2038-1-1 can always be represented
3031 correctly. Some systems allow for earlier dates, some for later,
3032 some for both. One way to find out it to insert any date into an
3033 Org buffer, putting the cursor on the year and hitting S-up and
3034 S-down to test the range.
3036 When this variable is set to t, the date/time prompt will not let
3037 you specify dates outside the 1970-2037 range, so it is certain that
3038 these dates will work in whatever version of Emacs you are
3039 running, and also that you can move a file from one Emacs implementation
3040 to another. WHenever Org is forcing the year for you, it will display
3041 a message and beep.
3043 When this variable is nil, Org will check if the date is
3044 representable in the specific Emacs implementation you are using.
3045 If not, it will force a year, usually the current year, and beep
3046 to remind you. Currently this setting is not recommended because
3047 the likelihood that you will open your Org files in an Emacs that
3048 has limited date range is not negligible.
3050 A workaround for this problem is to use diary sexp dates for time
3051 stamps outside of this range."
3052 :group 'org-time
3053 :version "24.1"
3054 :type 'boolean)
3056 (defcustom org-read-date-display-live t
3057 "Non-nil means display current interpretation of date prompt live.
3058 This display will be in an overlay, in the minibuffer."
3059 :group 'org-time
3060 :type 'boolean)
3062 (defcustom org-read-date-popup-calendar t
3063 "Non-nil means pop up a calendar when prompting for a date.
3064 In the calendar, the date can be selected with mouse-1. However, the
3065 minibuffer will also be active, and you can simply enter the date as well.
3066 When nil, only the minibuffer will be available."
3067 :group 'org-time
3068 :type 'boolean)
3069 (if (fboundp 'defvaralias)
3070 (defvaralias 'org-popup-calendar-for-date-prompt
3071 'org-read-date-popup-calendar))
3073 (make-obsolete-variable
3074 'org-read-date-minibuffer-setup-hook
3075 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3076 (defcustom org-read-date-minibuffer-setup-hook nil
3077 "Hook to be used to set up keys for the date/time interface.
3078 Add key definitions to `minibuffer-local-map', which will be a
3079 temporary copy.
3081 WARNING: This option is obsolete, you should use
3082 `org-read-date-minibuffer-local-map' to set up keys."
3083 :group 'org-time
3084 :type 'hook)
3086 (defcustom org-extend-today-until 0
3087 "The hour when your day really ends. Must be an integer.
3088 This has influence for the following applications:
3089 - When switching the agenda to \"today\". It it is still earlier than
3090 the time given here, the day recognized as TODAY is actually yesterday.
3091 - When a date is read from the user and it is still before the time given
3092 here, the current date and time will be assumed to be yesterday, 23:59.
3093 Also, timestamps inserted in capture templates follow this rule.
3095 IMPORTANT: This is a feature whose implementation is and likely will
3096 remain incomplete. Really, it is only here because past midnight seems to
3097 be the favorite working time of John Wiegley :-)"
3098 :group 'org-time
3099 :type 'integer)
3101 (defcustom org-use-effective-time nil
3102 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3103 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3104 \"effective time\" of any timestamps between midnight and 8am will be
3105 23:59 of the previous day."
3106 :group 'org-time
3107 :version "24.1"
3108 :type 'boolean)
3110 (defcustom org-use-last-clock-out-time-as-effective-time nil
3111 "When non-nil, use the last clock out time for `org-todo'.
3112 Note that this option has precedence over the combined use of
3113 `org-use-effective-time' and `org-extend-today-until'."
3114 :group 'org-time
3115 ;; :version "24.3"
3116 :type 'boolean)
3118 (defcustom org-edit-timestamp-down-means-later nil
3119 "Non-nil means S-down will increase the time in a time stamp.
3120 When nil, S-up will increase."
3121 :group 'org-time
3122 :type 'boolean)
3124 (defcustom org-calendar-follow-timestamp-change t
3125 "Non-nil means make the calendar window follow timestamp changes.
3126 When a timestamp is modified and the calendar window is visible, it will be
3127 moved to the new date."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defgroup org-tags nil
3132 "Options concerning tags in Org-mode."
3133 :tag "Org Tags"
3134 :group 'org)
3136 (defcustom org-tag-alist nil
3137 "List of tags allowed in Org-mode files.
3138 When this list is nil, Org-mode will base TAG input on what is already in the
3139 buffer.
3140 The value of this variable is an alist, the car of each entry must be a
3141 keyword as a string, the cdr may be a character that is used to select
3142 that tag through the fast-tag-selection interface.
3143 See the manual for details."
3144 :group 'org-tags
3145 :type '(repeat
3146 (choice
3147 (cons (string :tag "Tag name")
3148 (character :tag "Access char"))
3149 (list :tag "Start radio group"
3150 (const :startgroup)
3151 (option (string :tag "Group description")))
3152 (list :tag "End radio group"
3153 (const :endgroup)
3154 (option (string :tag "Group description")))
3155 (const :tag "New line" (:newline)))))
3157 (defcustom org-tag-persistent-alist nil
3158 "List of tags that will always appear in all Org-mode files.
3159 This is in addition to any in buffer settings or customizations
3160 of `org-tag-alist'.
3161 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3162 The value of this variable is an alist, the car of each entry must be a
3163 keyword as a string, the cdr may be a character that is used to select
3164 that tag through the fast-tag-selection interface.
3165 See the manual for details.
3166 To disable these tags on a per-file basis, insert anywhere in the file:
3167 #+STARTUP: noptag"
3168 :group 'org-tags
3169 :type '(repeat
3170 (choice
3171 (cons (string :tag "Tag name")
3172 (character :tag "Access char"))
3173 (const :tag "Start radio group" (:startgroup))
3174 (const :tag "End radio group" (:endgroup))
3175 (const :tag "New line" (:newline)))))
3177 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3178 "If non-nil, always offer completion for all tags of all agenda files.
3179 Instead of customizing this variable directly, you might want to
3180 set it locally for capture buffers, because there no list of
3181 tags in that file can be created dynamically (there are none).
3183 (add-hook 'org-capture-mode-hook
3184 (lambda ()
3185 (set (make-local-variable
3186 'org-complete-tags-always-offer-all-agenda-tags)
3187 t)))"
3188 :group 'org-tags
3189 :version "24.1"
3190 :type 'boolean)
3192 (defvar org-file-tags nil
3193 "List of tags that can be inherited by all entries in the file.
3194 The tags will be inherited if the variable `org-use-tag-inheritance'
3195 says they should be.
3196 This variable is populated from #+FILETAGS lines.")
3198 (defcustom org-use-fast-tag-selection 'auto
3199 "Non-nil means use fast tag selection scheme.
3200 This is a special interface to select and deselect tags with single keys.
3201 When nil, fast selection is never used.
3202 When the symbol `auto', fast selection is used if and only if selection
3203 characters for tags have been configured, either through the variable
3204 `org-tag-alist' or through a #+TAGS line in the buffer.
3205 When t, fast selection is always used and selection keys are assigned
3206 automatically if necessary."
3207 :group 'org-tags
3208 :type '(choice
3209 (const :tag "Always" t)
3210 (const :tag "Never" nil)
3211 (const :tag "When selection characters are configured" 'auto)))
3213 (defcustom org-fast-tag-selection-single-key nil
3214 "Non-nil means fast tag selection exits after first change.
3215 When nil, you have to press RET to exit it.
3216 During fast tag selection, you can toggle this flag with `C-c'.
3217 This variable can also have the value `expert'. In this case, the window
3218 displaying the tags menu is not even shown, until you press C-c again."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "No" nil)
3222 (const :tag "Yes" t)
3223 (const :tag "Expert" expert)))
3225 (defvar org-fast-tag-selection-include-todo nil
3226 "Non-nil means fast tags selection interface will also offer TODO states.
3227 This is an undocumented feature, you should not rely on it.")
3229 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3230 "The column to which tags should be indented in a headline.
3231 If this number is positive, it specifies the column. If it is negative,
3232 it means that the tags should be flushright to that column. For example,
3233 -80 works well for a normal 80 character screen.
3234 When 0, place tags directly after headline text, with only one space in
3235 between."
3236 :group 'org-tags
3237 :type 'integer)
3239 (defcustom org-auto-align-tags t
3240 "Non-nil keeps tags aligned when modifying headlines.
3241 Some operations (i.e. demoting) change the length of a headline and
3242 therefore shift the tags around. With this option turned on, after
3243 each such operation the tags are again aligned to `org-tags-column'."
3244 :group 'org-tags
3245 :type 'boolean)
3247 (defcustom org-use-tag-inheritance t
3248 "Non-nil means tags in levels apply also for sublevels.
3249 When nil, only the tags directly given in a specific line apply there.
3250 This may also be a list of tags that should be inherited, or a regexp that
3251 matches tags that should be inherited. Additional control is possible
3252 with the variable `org-tags-exclude-from-inheritance' which gives an
3253 explicit list of tags to be excluded from inheritance, even if the value of
3254 `org-use-tag-inheritance' would select it for inheritance.
3256 If this option is t, a match early-on in a tree can lead to a large
3257 number of matches in the subtree when constructing the agenda or creating
3258 a sparse tree. If you only want to see the first match in a tree during
3259 a search, check out the variable `org-tags-match-list-sublevels'."
3260 :group 'org-tags
3261 :type '(choice
3262 (const :tag "Not" nil)
3263 (const :tag "Always" t)
3264 (repeat :tag "Specific tags" (string :tag "Tag"))
3265 (regexp :tag "Tags matched by regexp")))
3267 (defcustom org-tags-exclude-from-inheritance nil
3268 "List of tags that should never be inherited.
3269 This is a way to exclude a few tags from inheritance. For way to do
3270 the opposite, to actively allow inheritance for selected tags,
3271 see the variable `org-use-tag-inheritance'."
3272 :group 'org-tags
3273 :type '(repeat (string :tag "Tag")))
3275 (defun org-tag-inherit-p (tag)
3276 "Check if TAG is one that should be inherited."
3277 (cond
3278 ((member tag org-tags-exclude-from-inheritance) nil)
3279 ((eq org-use-tag-inheritance t) t)
3280 ((not org-use-tag-inheritance) nil)
3281 ((stringp org-use-tag-inheritance)
3282 (string-match org-use-tag-inheritance tag))
3283 ((listp org-use-tag-inheritance)
3284 (member tag org-use-tag-inheritance))
3285 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3287 (defcustom org-tags-match-list-sublevels t
3288 "Non-nil means list also sublevels of headlines matching a search.
3289 This variable applies to tags/property searches, and also to stuck
3290 projects because this search is based on a tags match as well.
3292 When set to the symbol `indented', sublevels are indented with
3293 leading dots.
3295 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3296 the sublevels of a headline matching a tag search often also match
3297 the same search. Listing all of them can create very long lists.
3298 Setting this variable to nil causes subtrees of a match to be skipped.
3300 This variable is semi-obsolete and probably should always be true. It
3301 is better to limit inheritance to certain tags using the variables
3302 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3303 :group 'org-tags
3304 :type '(choice
3305 (const :tag "No, don't list them" nil)
3306 (const :tag "Yes, do list them" t)
3307 (const :tag "List them, indented with leading dots" indented)))
3309 (defcustom org-tags-sort-function nil
3310 "When set, tags are sorted using this function as a comparator."
3311 :group 'org-tags
3312 :type '(choice
3313 (const :tag "No sorting" nil)
3314 (const :tag "Alphabetical" string<)
3315 (const :tag "Reverse alphabetical" string>)
3316 (function :tag "Custom function" nil)))
3318 (defvar org-tags-history nil
3319 "History of minibuffer reads for tags.")
3320 (defvar org-last-tags-completion-table nil
3321 "The last used completion table for tags.")
3322 (defvar org-after-tags-change-hook nil
3323 "Hook that is run after the tags in a line have changed.")
3325 (defgroup org-properties nil
3326 "Options concerning properties in Org-mode."
3327 :tag "Org Properties"
3328 :group 'org)
3330 (defcustom org-property-format "%-10s %s"
3331 "How property key/value pairs should be formatted by `indent-line'.
3332 When `indent-line' hits a property definition, it will format the line
3333 according to this format, mainly to make sure that the values are
3334 lined-up with respect to each other."
3335 :group 'org-properties
3336 :type 'string)
3338 (defcustom org-properties-postprocess-alist nil
3339 "Alist of properties and functions to adjust inserted values.
3340 Elements of this alist must be of the form
3342 ([string] [function])
3344 where [string] must be a property name and [function] must be a
3345 lambda expression: this lambda expression must take one argument,
3346 the value to adjust, and return the new value as a string.
3348 For example, this element will allow the property \"Remaining\"
3349 to be updated wrt the relation between the \"Effort\" property
3350 and the clock summary:
3352 ((\"Remaining\" (lambda(value)
3353 (let ((clocksum (org-clock-sum-current-item))
3354 (effort (org-duration-string-to-minutes
3355 (org-entry-get (point) \"Effort\"))))
3356 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3357 :group 'org-properties
3358 :version "24.1"
3359 :type '(alist :key-type (string :tag "Property")
3360 :value-type (function :tag "Function")))
3362 (defcustom org-use-property-inheritance nil
3363 "Non-nil means properties apply also for sublevels.
3365 This setting is chiefly used during property searches. Turning it on can
3366 cause significant overhead when doing a search, which is why it is not
3367 on by default.
3369 When nil, only the properties directly given in the current entry count.
3370 When t, every property is inherited. The value may also be a list of
3371 properties that should have inheritance, or a regular expression matching
3372 properties that should be inherited.
3374 However, note that some special properties use inheritance under special
3375 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3376 and the properties ending in \"_ALL\" when they are used as descriptor
3377 for valid values of a property.
3379 Note for programmers:
3380 When querying an entry with `org-entry-get', you can control if inheritance
3381 should be used. By default, `org-entry-get' looks only at the local
3382 properties. You can request inheritance by setting the inherit argument
3383 to t (to force inheritance) or to `selective' (to respect the setting
3384 in this variable)."
3385 :group 'org-properties
3386 :type '(choice
3387 (const :tag "Not" nil)
3388 (const :tag "Always" t)
3389 (repeat :tag "Specific properties" (string :tag "Property"))
3390 (regexp :tag "Properties matched by regexp")))
3392 (defun org-property-inherit-p (property)
3393 "Check if PROPERTY is one that should be inherited."
3394 (cond
3395 ((eq org-use-property-inheritance t) t)
3396 ((not org-use-property-inheritance) nil)
3397 ((stringp org-use-property-inheritance)
3398 (string-match org-use-property-inheritance property))
3399 ((listp org-use-property-inheritance)
3400 (member property org-use-property-inheritance))
3401 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3403 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3404 "The default column format, if no other format has been defined.
3405 This variable can be set on the per-file basis by inserting a line
3407 #+COLUMNS: %25ITEM ....."
3408 :group 'org-properties
3409 :type 'string)
3411 (defcustom org-columns-ellipses ".."
3412 "The ellipses to be used when a field in column view is truncated.
3413 When this is the empty string, as many characters as possible are shown,
3414 but then there will be no visual indication that the field has been truncated.
3415 When this is a string of length N, the last N characters of a truncated
3416 field are replaced by this string. If the column is narrower than the
3417 ellipses string, only part of the ellipses string will be shown."
3418 :group 'org-properties
3419 :type 'string)
3421 (defcustom org-columns-modify-value-for-display-function nil
3422 "Function that modifies values for display in column view.
3423 For example, it can be used to cut out a certain part from a time stamp.
3424 The function must take 2 arguments:
3426 column-title The title of the column (*not* the property name)
3427 value The value that should be modified.
3429 The function should return the value that should be displayed,
3430 or nil if the normal value should be used."
3431 :group 'org-properties
3432 :type 'function)
3434 (defcustom org-effort-property "Effort"
3435 "The property that is being used to keep track of effort estimates.
3436 Effort estimates given in this property need to have the format H:MM."
3437 :group 'org-properties
3438 :group 'org-progress
3439 :type '(string :tag "Property"))
3441 (defconst org-global-properties-fixed
3442 '(("VISIBILITY_ALL" . "folded children content all")
3443 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3444 "List of property/value pairs that can be inherited by any entry.
3446 These are fixed values, for the preset properties. The user variable
3447 that can be used to add to this list is `org-global-properties'.
3449 The entries in this list are cons cells where the car is a property
3450 name and cdr is a string with the value. If the value represents
3451 multiple items like an \"_ALL\" property, separate the items by
3452 spaces.")
3454 (defcustom org-global-properties nil
3455 "List of property/value pairs that can be inherited by any entry.
3457 This list will be combined with the constant `org-global-properties-fixed'.
3459 The entries in this list are cons cells where the car is a property
3460 name and cdr is a string with the value.
3462 You can set buffer-local values for the same purpose in the variable
3463 `org-file-properties' this by adding lines like
3465 #+PROPERTY: NAME VALUE"
3466 :group 'org-properties
3467 :type '(repeat
3468 (cons (string :tag "Property")
3469 (string :tag "Value"))))
3471 (defvar org-file-properties nil
3472 "List of property/value pairs that can be inherited by any entry.
3473 Valid for the current buffer.
3474 This variable is populated from #+PROPERTY lines.")
3475 (make-variable-buffer-local 'org-file-properties)
3477 (defgroup org-agenda nil
3478 "Options concerning agenda views in Org-mode."
3479 :tag "Org Agenda"
3480 :group 'org)
3482 (defvar org-category nil
3483 "Variable used by org files to set a category for agenda display.
3484 Such files should use a file variable to set it, for example
3486 # -*- mode: org; org-category: \"ELisp\"
3488 or contain a special line
3490 #+CATEGORY: ELisp
3492 If the file does not specify a category, then file's base name
3493 is used instead.")
3494 (make-variable-buffer-local 'org-category)
3495 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3497 (defcustom org-agenda-files nil
3498 "The files to be used for agenda display.
3499 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3500 \\[org-remove-file]. You can also use customize to edit the list.
3502 If an entry is a directory, all files in that directory that are matched by
3503 `org-agenda-file-regexp' will be part of the file list.
3505 If the value of the variable is not a list but a single file name, then
3506 the list of agenda files is actually stored and maintained in that file, one
3507 agenda file per line. In this file paths can be given relative to
3508 `org-directory'. Tilde expansion and environment variable substitution
3509 are also made."
3510 :group 'org-agenda
3511 :type '(choice
3512 (repeat :tag "List of files and directories" file)
3513 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3515 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3516 "Regular expression to match files for `org-agenda-files'.
3517 If any element in the list in that variable contains a directory instead
3518 of a normal file, all files in that directory that are matched by this
3519 regular expression will be included."
3520 :group 'org-agenda
3521 :type 'regexp)
3523 (defcustom org-agenda-text-search-extra-files nil
3524 "List of extra files to be searched by text search commands.
3525 These files will be search in addition to the agenda files by the
3526 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3527 Note that these files will only be searched for text search commands,
3528 not for the other agenda views like todo lists, tag searches or the weekly
3529 agenda. This variable is intended to list notes and possibly archive files
3530 that should also be searched by these two commands.
3531 In fact, if the first element in the list is the symbol `agenda-archives',
3532 than all archive files of all agenda files will be added to the search
3533 scope."
3534 :group 'org-agenda
3535 :type '(set :greedy t
3536 (const :tag "Agenda Archives" agenda-archives)
3537 (repeat :inline t (file))))
3539 (if (fboundp 'defvaralias)
3540 (defvaralias 'org-agenda-multi-occur-extra-files
3541 'org-agenda-text-search-extra-files))
3543 (defcustom org-agenda-skip-unavailable-files nil
3544 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3545 A nil value means to remove them, after a query, from the list."
3546 :group 'org-agenda
3547 :type 'boolean)
3549 (defcustom org-calendar-to-agenda-key [?c]
3550 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3551 The command `org-calendar-goto-agenda' will be bound to this key. The
3552 default is the character `c' because then `c' can be used to switch back and
3553 forth between agenda and calendar."
3554 :group 'org-agenda
3555 :type 'sexp)
3557 (defcustom org-calendar-insert-diary-entry-key [?i]
3558 "The key to be installed in `calendar-mode-map' for adding diary entries.
3559 This option is irrelevant until `org-agenda-diary-file' has been configured
3560 to point to an Org-mode file. When that is the case, the command
3561 `org-agenda-diary-entry' will be bound to the key given here, by default
3562 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3563 if you want to continue doing this, you need to change this to a different
3564 key."
3565 :group 'org-agenda
3566 :type 'sexp)
3568 (defcustom org-agenda-diary-file 'diary-file
3569 "File to which to add new entries with the `i' key in agenda and calendar.
3570 When this is the symbol `diary-file', the functionality in the Emacs
3571 calendar will be used to add entries to the `diary-file'. But when this
3572 points to a file, `org-agenda-diary-entry' will be used instead."
3573 :group 'org-agenda
3574 :type '(choice
3575 (const :tag "The standard Emacs diary file" diary-file)
3576 (file :tag "Special Org file diary entries")))
3578 (eval-after-load "calendar"
3579 '(progn
3580 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3581 'org-calendar-goto-agenda)
3582 (add-hook 'calendar-mode-hook
3583 (lambda ()
3584 (unless (eq org-agenda-diary-file 'diary-file)
3585 (define-key calendar-mode-map
3586 org-calendar-insert-diary-entry-key
3587 'org-agenda-diary-entry))))))
3589 (defgroup org-latex nil
3590 "Options for embedding LaTeX code into Org-mode."
3591 :tag "Org LaTeX"
3592 :group 'org)
3594 (defcustom org-format-latex-options
3595 '(:foreground default :background default :scale 1.0
3596 :html-foreground "Black" :html-background "Transparent"
3597 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3598 "Options for creating images from LaTeX fragments.
3599 This is a property list with the following properties:
3600 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3601 `default' means use the foreground of the default face.
3602 `auto' means use the foreground from the text face.
3603 :background the background color, or \"Transparent\".
3604 `default' means use the background of the default face.
3605 `auto' means use the background from the text face.
3606 :scale a scaling factor for the size of the images, to get more pixels
3607 :html-foreground, :html-background, :html-scale
3608 the same numbers for HTML export.
3609 :matchers a list indicating which matchers should be used to
3610 find LaTeX fragments. Valid members of this list are:
3611 \"begin\" find environments
3612 \"$1\" find single characters surrounded by $.$
3613 \"$\" find math expressions surrounded by $...$
3614 \"$$\" find math expressions surrounded by $$....$$
3615 \"\\(\" find math expressions surrounded by \\(...\\)
3616 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3617 :group 'org-latex
3618 :type 'plist)
3620 (defcustom org-format-latex-signal-error t
3621 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3622 When nil, just push out a message."
3623 :group 'org-latex
3624 :version "24.1"
3625 :type 'boolean)
3627 (defcustom org-latex-to-mathml-jar-file nil
3628 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3629 Use this to specify additional executable file say a jar file.
3631 When using MathToWeb as the converter, specify the full-path to
3632 your mathtoweb.jar file."
3633 :group 'org-latex
3634 :version "24.1"
3635 :type '(choice
3636 (const :tag "None" nil)
3637 (file :tag "JAR file" :must-match t)))
3639 (defcustom org-latex-to-mathml-convert-command nil
3640 "Command to convert LaTeX fragments to MathML.
3641 Replace format-specifiers in the command as noted below and use
3642 `shell-command' to convert LaTeX to MathML.
3643 %j: Executable file in fully expanded form as specified by
3644 `org-latex-to-mathml-jar-file'.
3645 %I: Input LaTeX file in fully expanded form
3646 %o: Output MathML file
3647 This command is used by `org-create-math-formula'.
3649 When using MathToWeb as the converter, set this to
3650 \"java -jar %j -unicode -force -df %o %I\"."
3651 :group 'org-latex
3652 :version "24.1"
3653 :type '(choice
3654 (const :tag "None" nil)
3655 (string :tag "\nShell command")))
3657 (defcustom org-latex-create-formula-image-program 'dvipng
3658 "Program to convert LaTeX fragments with.
3660 dvipng Process the LaTeX fragments to dvi file, then convert
3661 dvi files to png files using dvipng.
3662 This will also include processing of non-math environments.
3663 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3664 to convert pdf files to png files"
3665 :group 'org-latex
3666 :version "24.1"
3667 :type '(choice
3668 (const :tag "dvipng" dvipng)
3669 (const :tag "imagemagick" imagemagick)))
3671 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3672 "Path to store latex preview images.
3673 A relative path here creates many directories relative to the
3674 processed org files paths. An absolute path puts all preview
3675 images at the same place."
3676 :group 'org-latex
3677 :version "24.3"
3678 :type 'string)
3680 (defun org-format-latex-mathml-available-p ()
3681 "Return t if `org-latex-to-mathml-convert-command' is usable."
3682 (save-match-data
3683 (when (and (boundp 'org-latex-to-mathml-convert-command)
3684 org-latex-to-mathml-convert-command)
3685 (let ((executable (car (split-string
3686 org-latex-to-mathml-convert-command))))
3687 (when (executable-find executable)
3688 (if (string-match
3689 "%j" org-latex-to-mathml-convert-command)
3690 (file-readable-p org-latex-to-mathml-jar-file)
3691 t))))))
3693 (defcustom org-format-latex-header "\\documentclass{article}
3694 \\usepackage[usenames]{color}
3695 \\usepackage{amsmath}
3696 \\usepackage[mathscr]{eucal}
3697 \\pagestyle{empty} % do not remove
3698 \[PACKAGES]
3699 \[DEFAULT-PACKAGES]
3700 % The settings below are copied from fullpage.sty
3701 \\setlength{\\textwidth}{\\paperwidth}
3702 \\addtolength{\\textwidth}{-3cm}
3703 \\setlength{\\oddsidemargin}{1.5cm}
3704 \\addtolength{\\oddsidemargin}{-2.54cm}
3705 \\setlength{\\evensidemargin}{\\oddsidemargin}
3706 \\setlength{\\textheight}{\\paperheight}
3707 \\addtolength{\\textheight}{-\\headheight}
3708 \\addtolength{\\textheight}{-\\headsep}
3709 \\addtolength{\\textheight}{-\\footskip}
3710 \\addtolength{\\textheight}{-3cm}
3711 \\setlength{\\topmargin}{1.5cm}
3712 \\addtolength{\\topmargin}{-2.54cm}"
3713 "The document header used for processing LaTeX fragments.
3714 It is imperative that this header make sure that no page number
3715 appears on the page. The package defined in the variables
3716 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3717 will either replace the placeholder \"[PACKAGES]\" in this
3718 header, or they will be appended."
3719 :group 'org-latex
3720 :type 'string)
3722 (defun org-set-packages-alist (var val)
3723 "Set the packages alist and make sure it has 3 elements per entry."
3724 (set var (mapcar (lambda (x)
3725 (if (and (consp x) (= (length x) 2))
3726 (list (car x) (nth 1 x) t)
3728 val)))
3730 (defun org-get-packages-alist (var)
3731 "Get the packages alist and make sure it has 3 elements per entry."
3732 (mapcar (lambda (x)
3733 (if (and (consp x) (= (length x) 2))
3734 (list (car x) (nth 1 x) t)
3736 (default-value var)))
3738 (defcustom org-latex-default-packages-alist
3739 '(("AUTO" "inputenc" t)
3740 ("T1" "fontenc" t)
3741 ("" "fixltx2e" nil)
3742 ("" "graphicx" t)
3743 ("" "longtable" nil)
3744 ("" "float" nil)
3745 ("" "wrapfig" nil)
3746 ("" "soul" t)
3747 ("" "textcomp" t)
3748 ("" "marvosym" t)
3749 ("" "wasysym" t)
3750 ("" "latexsym" t)
3751 ("" "amssymb" t)
3752 ("" "hyperref" nil)
3753 "\\tolerance=1000")
3754 "Alist of default packages to be inserted in the header.
3756 Change this only if one of the packages here causes an
3757 incompatibility with another package you are using.
3759 The packages in this list are needed by one part or another of
3760 Org mode to function properly:
3762 - inputenc, fontenc: for basic font and character selection
3763 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3764 symbols used for interpreting the entities in `org-entities'.
3765 You can skip some of these packages if you don't use any of the
3766 symbols in it.
3767 - graphicx: for including images
3768 - float, wrapfig: for figure placement
3769 - longtable: for long tables
3770 - hyperref: for cross references
3772 Therefore you should not modify this variable unless you know
3773 what you are doing. The one reason to change it anyway is that
3774 you might be loading some other package that conflicts with one
3775 of the default packages. Each cell is of the format
3776 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3777 the package also needs to be included when compiling LaTeX
3778 snippets into images for inclusion into non-LaTeX output."
3779 :group 'org-latex
3780 :group 'org-export-latex
3781 :set 'org-set-packages-alist
3782 :get 'org-get-packages-alist
3783 :version "24.1"
3784 :type '(repeat
3785 (choice
3786 (list :tag "options/package pair"
3787 (string :tag "options")
3788 (string :tag "package")
3789 (boolean :tag "Snippet"))
3790 (string :tag "A line of LaTeX"))))
3792 (defcustom org-latex-packages-alist nil
3793 "Alist of packages to be inserted in every LaTeX header.
3795 These will be inserted after `org-latex-default-packages-alist'.
3796 Each cell is of the format:
3798 \(\"options\" \"package\" snippet-flag)
3800 SNIPPET-FLAG, when t, indicates that this package is also needed
3801 when turning LaTeX snippets into images for inclusion into
3802 non-LaTeX output.
3804 Make sure that you only list packages here which:
3806 - you want in every file
3807 - do not conflict with the setup in `org-format-latex-header'.
3808 - do not conflict with the default packages in
3809 `org-latex-default-packages-alist'."
3810 :group 'org-latex
3811 :group 'org-export-latex
3812 :set 'org-set-packages-alist
3813 :get 'org-get-packages-alist
3814 :type '(repeat
3815 (choice
3816 (list :tag "options/package pair"
3817 (string :tag "options")
3818 (string :tag "package")
3819 (boolean :tag "Snippet"))
3820 (string :tag "A line of LaTeX"))))
3822 (defgroup org-appearance nil
3823 "Settings for Org-mode appearance."
3824 :tag "Org Appearance"
3825 :group 'org)
3827 (defcustom org-level-color-stars-only nil
3828 "Non-nil means fontify only the stars in each headline.
3829 When nil, the entire headline is fontified.
3830 Changing it requires restart of `font-lock-mode' to become effective
3831 also in regions already fontified."
3832 :group 'org-appearance
3833 :type 'boolean)
3835 (defcustom org-hide-leading-stars nil
3836 "Non-nil means hide the first N-1 stars in a headline.
3837 This works by using the face `org-hide' for these stars. This
3838 face is white for a light background, and black for a dark
3839 background. You may have to customize the face `org-hide' to
3840 make this work.
3841 Changing it requires restart of `font-lock-mode' to become effective
3842 also in regions already fontified.
3843 You may also set this on a per-file basis by adding one of the following
3844 lines to the buffer:
3846 #+STARTUP: hidestars
3847 #+STARTUP: showstars"
3848 :group 'org-appearance
3849 :type 'boolean)
3851 (defcustom org-hidden-keywords nil
3852 "List of symbols corresponding to keywords to be hidden the org buffer.
3853 For example, a value '(title) for this list will make the document's title
3854 appear in the buffer without the initial #+TITLE: keyword."
3855 :group 'org-appearance
3856 :version "24.1"
3857 :type '(set (const :tag "#+AUTHOR" author)
3858 (const :tag "#+DATE" date)
3859 (const :tag "#+EMAIL" email)
3860 (const :tag "#+TITLE" title)))
3862 (defcustom org-custom-properties nil
3863 "List of properties (as strings) with a special meaning.
3864 The default use of these custom properties is to let the user
3865 hide them with `org-toggle-custom-properties-visibility'."
3866 :group 'org-properties
3867 :group 'org-appearance
3868 :version "24.3"
3869 :type '(repeat (string :tag "Property Name")))
3871 (defcustom org-fontify-done-headline nil
3872 "Non-nil means change the face of a headline if it is marked DONE.
3873 Normally, only the TODO/DONE keyword indicates the state of a headline.
3874 When this is non-nil, the headline after the keyword is set to the
3875 `org-headline-done' as an additional indication."
3876 :group 'org-appearance
3877 :type 'boolean)
3879 (defcustom org-fontify-emphasized-text t
3880 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3881 Changing this variable requires a restart of Emacs to take effect."
3882 :group 'org-appearance
3883 :type 'boolean)
3885 (defcustom org-fontify-whole-heading-line nil
3886 "Non-nil means fontify the whole line for headings.
3887 This is useful when setting a background color for the
3888 org-level-* faces."
3889 :group 'org-appearance
3890 :type 'boolean)
3892 (defcustom org-hide-emphasis-markers nil
3893 "Non-nil mean font-lock should hide the emphasis marker characters."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-pretty-entities nil
3898 "Non-nil means show entities as UTF8 characters.
3899 When nil, the \\name form remains in the buffer."
3900 :group 'org-appearance
3901 :version "24.1"
3902 :type 'boolean)
3904 (defcustom org-pretty-entities-include-sub-superscripts t
3905 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3906 :group 'org-appearance
3907 :version "24.1"
3908 :type 'boolean)
3910 (defvar org-emph-re nil
3911 "Regular expression for matching emphasis.
3912 After a match, the match groups contain these elements:
3913 0 The match of the full regular expression, including the characters
3914 before and after the proper match
3915 1 The character before the proper match, or empty at beginning of line
3916 2 The proper match, including the leading and trailing markers
3917 3 The leading marker like * or /, indicating the type of highlighting
3918 4 The text between the emphasis markers, not including the markers
3919 5 The character after the match, empty at the end of a line")
3920 (defvar org-verbatim-re nil
3921 "Regular expression for matching verbatim text.")
3922 (defvar org-emphasis-regexp-components) ; defined just below
3923 (defvar org-emphasis-alist) ; defined just below
3924 (defun org-set-emph-re (var val)
3925 "Set variable and compute the emphasis regular expression."
3926 (set var val)
3927 (when (and (boundp 'org-emphasis-alist)
3928 (boundp 'org-emphasis-regexp-components)
3929 org-emphasis-alist org-emphasis-regexp-components)
3930 (let* ((e org-emphasis-regexp-components)
3931 (pre (car e))
3932 (post (nth 1 e))
3933 (border (nth 2 e))
3934 (body (nth 3 e))
3935 (nl (nth 4 e))
3936 (body1 (concat body "*?"))
3937 (markers (mapconcat 'car org-emphasis-alist ""))
3938 (vmarkers (mapconcat
3939 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3940 org-emphasis-alist "")))
3941 ;; make sure special characters appear at the right position in the class
3942 (if (string-match "\\^" markers)
3943 (setq markers (concat (replace-match "" t t markers) "^")))
3944 (if (string-match "-" markers)
3945 (setq markers (concat (replace-match "" t t markers) "-")))
3946 (if (string-match "\\^" vmarkers)
3947 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3948 (if (string-match "-" vmarkers)
3949 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3950 (if (> nl 0)
3951 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3952 (int-to-string nl) "\\}")))
3953 ;; Make the regexp
3954 (setq org-emph-re
3955 (concat "\\([" pre "]\\|^\\)"
3956 "\\("
3957 "\\([" markers "]\\)"
3958 "\\("
3959 "[^" border "]\\|"
3960 "[^" border "]"
3961 body1
3962 "[^" border "]"
3963 "\\)"
3964 "\\3\\)"
3965 "\\([" post "]\\|$\\)"))
3966 (setq org-verbatim-re
3967 (concat "\\([" pre "]\\|^\\)"
3968 "\\("
3969 "\\([" vmarkers "]\\)"
3970 "\\("
3971 "[^" border "]\\|"
3972 "[^" border "]"
3973 body1
3974 "[^" border "]"
3975 "\\)"
3976 "\\3\\)"
3977 "\\([" post "]\\|$\\)")))))
3979 (defcustom org-emphasis-regexp-components
3980 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3981 "Components used to build the regular expression for emphasis.
3982 This is a list with five entries. Terminology: In an emphasis string
3983 like \" *strong word* \", we call the initial space PREMATCH, the final
3984 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3985 and \"trong wor\" is the body. The different components in this variable
3986 specify what is allowed/forbidden in each part:
3988 pre Chars allowed as prematch. Beginning of line will be allowed too.
3989 post Chars allowed as postmatch. End of line will be allowed too.
3990 border The chars *forbidden* as border characters.
3991 body-regexp A regexp like \".\" to match a body character. Don't use
3992 non-shy groups here, and don't allow newline here.
3993 newline The maximum number of newlines allowed in an emphasis exp.
3995 Use customize to modify this, or restart Emacs after changing it."
3996 :group 'org-appearance
3997 :set 'org-set-emph-re
3998 :type '(list
3999 (sexp :tag "Allowed chars in pre ")
4000 (sexp :tag "Allowed chars in post ")
4001 (sexp :tag "Forbidden chars in border ")
4002 (sexp :tag "Regexp for body ")
4003 (integer :tag "number of newlines allowed")
4004 (option (boolean :tag "Please ignore this button"))))
4006 (defcustom org-emphasis-alist
4007 `(("*" bold "<b>" "</b>")
4008 ("/" italic "<i>" "</i>")
4009 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4010 ("=" org-code "<code>" "</code>" verbatim)
4011 ("~" org-verbatim "<code>" "</code>" verbatim)
4012 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4013 "<del>" "</del>")
4015 "Special syntax for emphasized text.
4016 Text starting and ending with a special character will be emphasized, for
4017 example *bold*, _underlined_ and /italic/. This variable sets the marker
4018 characters, the face to be used by font-lock for highlighting in Org-mode
4019 Emacs buffers, and the HTML tags to be used for this.
4020 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4021 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4022 Use customize to modify this, or restart Emacs after changing it."
4023 :group 'org-appearance
4024 :set 'org-set-emph-re
4025 :type '(repeat
4026 (list
4027 (string :tag "Marker character")
4028 (choice
4029 (face :tag "Font-lock-face")
4030 (plist :tag "Face property list"))
4031 (string :tag "HTML start tag")
4032 (string :tag "HTML end tag")
4033 (option (const verbatim)))))
4035 (defvar org-syntax-table
4036 (let ((st (make-syntax-table)))
4037 (mapc (lambda(c) (modify-syntax-entry
4038 (string-to-char (car c)) "w p" st))
4039 org-emphasis-alist)
4040 st))
4042 (defvar org-protecting-blocks
4043 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4044 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4045 This is needed for font-lock setup.")
4047 ;;; Miscellaneous options
4049 (defgroup org-completion nil
4050 "Completion in Org-mode."
4051 :tag "Org Completion"
4052 :group 'org)
4054 (defcustom org-completion-use-ido nil
4055 "Non-nil means use ido completion wherever possible.
4056 Note that `ido-mode' must be active for this variable to be relevant.
4057 If you decide to turn this variable on, you might well want to turn off
4058 `org-outline-path-complete-in-steps'.
4059 See also `org-completion-use-iswitchb'."
4060 :group 'org-completion
4061 :type 'boolean)
4063 (defcustom org-completion-use-iswitchb nil
4064 "Non-nil means use iswitchb completion wherever possible.
4065 Note that `iswitchb-mode' must be active for this variable to be relevant.
4066 If you decide to turn this variable on, you might well want to turn off
4067 `org-outline-path-complete-in-steps'.
4068 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4069 :group 'org-completion
4070 :type 'boolean)
4072 (defcustom org-completion-fallback-command 'hippie-expand
4073 "The expansion command called by \\[pcomplete] in normal context.
4074 Normal means, no org-mode-specific context."
4075 :group 'org-completion
4076 :type 'function)
4078 ;;; Functions and variables from their packages
4079 ;; Declared here to avoid compiler warnings
4081 ;; XEmacs only
4082 (defvar outline-mode-menu-heading)
4083 (defvar outline-mode-menu-show)
4084 (defvar outline-mode-menu-hide)
4085 (defvar zmacs-regions) ; XEmacs regions
4087 ;; Emacs only
4088 (defvar mark-active)
4090 ;; Various packages
4091 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4092 (declare-function calendar-forward-day "cal-move" (arg))
4093 (declare-function calendar-goto-date "cal-move" (date))
4094 (declare-function calendar-goto-today "cal-move" ())
4095 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4096 (defvar calc-embedded-close-formula)
4097 (defvar calc-embedded-open-formula)
4098 (declare-function cdlatex-tab "ext:cdlatex" ())
4099 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4100 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4101 (defvar font-lock-unfontify-region-function)
4102 (declare-function iswitchb-read-buffer "iswitchb"
4103 (prompt &optional default require-match start matches-set))
4104 (defvar iswitchb-temp-buflist)
4105 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4106 (defvar org-agenda-tags-todo-honor-ignore-options)
4107 (declare-function org-agenda-skip "org-agenda" ())
4108 (declare-function
4109 org-agenda-format-item "org-agenda"
4110 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4111 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4112 (declare-function org-agenda-change-all-lines "org-agenda"
4113 (newhead hdmarker &optional fixface just-this))
4114 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4115 (declare-function org-agenda-maybe-redo "org-agenda" ())
4116 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4117 (beg end))
4118 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4119 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4120 "org-agenda" (&optional end))
4121 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4122 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4123 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4124 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4125 (declare-function org-indent-mode "org-indent" (&optional arg))
4126 (declare-function parse-time-string "parse-time" (string))
4127 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4128 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4129 (defvar remember-data-file)
4130 (defvar texmathp-why)
4131 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4132 (declare-function table--at-cell-p "table" (position &optional object at-column))
4134 (defvar org-latex-regexps)
4136 ;;; Autoload and prepare some org modules
4138 ;; Some table stuff that needs to be defined here, because it is used
4139 ;; by the functions setting up org-mode or checking for table context.
4141 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4142 "Detect an org-type or table-type table.")
4143 (defconst org-table-line-regexp "^[ \t]*|"
4144 "Detect an org-type table line.")
4145 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4146 "Detect an org-type table line.")
4147 (defconst org-table-hline-regexp "^[ \t]*|-"
4148 "Detect an org-type table hline.")
4149 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4150 "Detect a table-type table hline.")
4151 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4152 "Detect the first line outside a table when searching from within it.
4153 This works for both table types.")
4155 ;; Autoload the functions in org-table.el that are needed by functions here.
4157 (eval-and-compile
4158 (org-autoload "org-table"
4159 '(org-table-begin org-table-blank-field org-table-end)))
4161 ;;;###autoload
4162 (defun turn-on-orgtbl ()
4163 "Unconditionally turn on `orgtbl-mode'."
4164 (require 'org-table)
4165 (orgtbl-mode 1))
4167 (defun org-at-table-p (&optional table-type)
4168 "Return t if the cursor is inside an org-type table.
4169 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4170 (if org-enable-table-editor
4171 (save-excursion
4172 (beginning-of-line 1)
4173 (looking-at (if table-type org-table-any-line-regexp
4174 org-table-line-regexp)))
4175 nil))
4176 (defsubst org-table-p () (org-at-table-p))
4178 (defun org-at-table.el-p ()
4179 "Return t if and only if we are at a table.el table."
4180 (and (org-at-table-p 'any)
4181 (save-excursion
4182 (goto-char (org-table-begin 'any))
4183 (looking-at org-table1-hline-regexp))))
4184 (defun org-table-recognize-table.el ()
4185 "If there is a table.el table nearby, recognize it and move into it."
4186 (if org-table-tab-recognizes-table.el
4187 (if (org-at-table.el-p)
4188 (progn
4189 (beginning-of-line 1)
4190 (if (looking-at org-table-dataline-regexp)
4192 (if (looking-at org-table1-hline-regexp)
4193 (progn
4194 (beginning-of-line 2)
4195 (if (looking-at org-table-any-border-regexp)
4196 (beginning-of-line -1)))))
4197 (if (re-search-forward "|" (org-table-end t) t)
4198 (progn
4199 (require 'table)
4200 (if (table--at-cell-p (point))
4202 (message "recognizing table.el table...")
4203 (table-recognize-table)
4204 (message "recognizing table.el table...done")))
4205 (error "This should not happen"))
4207 nil)
4208 nil))
4210 (defun org-at-table-hline-p ()
4211 "Return t if the cursor is inside a hline in a table."
4212 (if org-enable-table-editor
4213 (save-excursion
4214 (beginning-of-line 1)
4215 (looking-at org-table-hline-regexp))
4216 nil))
4218 (defvar org-table-clean-did-remove-column nil)
4220 (defun org-table-map-tables (function &optional quietly)
4221 "Apply FUNCTION to the start of all tables in the buffer."
4222 (save-excursion
4223 (save-restriction
4224 (widen)
4225 (goto-char (point-min))
4226 (while (re-search-forward org-table-any-line-regexp nil t)
4227 (unless quietly
4228 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4229 (beginning-of-line 1)
4230 (when (and (looking-at org-table-line-regexp)
4231 ;; Exclude tables in src/example/verbatim/clocktable blocks
4232 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4233 (save-excursion (funcall function))
4234 (or (looking-at org-table-line-regexp)
4235 (forward-char 1)))
4236 (re-search-forward org-table-any-border-regexp nil 1))))
4237 (unless quietly (message "Mapping tables: done")))
4239 ;; Declare and autoload functions from ox.el and al.
4241 (declare-function org-export-get-environment "ox"
4242 (&optional backend subtreep ext-plist))
4243 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4245 ;; Declare and autoload functions from org-agenda.el
4247 (eval-and-compile
4248 (org-autoload "org-agenda"
4249 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4251 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4252 (declare-function org-clock-update-mode-line "org-clock" ())
4253 (declare-function org-resolve-clocks "org-clock"
4254 (&optional also-non-dangling-p prompt last-valid))
4255 (defvar org-clock-start-time)
4256 (defvar org-clock-marker (make-marker)
4257 "Marker recording the last clock-in.")
4258 (defvar org-clock-hd-marker (make-marker)
4259 "Marker recording the last clock-in, but the headline position.")
4260 (defvar org-clock-heading ""
4261 "The heading of the current clock entry.")
4262 (defun org-clock-is-active ()
4263 "Return non-nil if clock is currently running.
4264 The return value is actually the clock marker."
4265 (marker-buffer org-clock-marker))
4267 (eval-and-compile
4268 (org-autoload "org-clock" '(org-clock-remove-overlays
4269 org-clock-update-time-maybe
4270 org-clocktable-shift)))
4272 (defun org-check-running-clock ()
4273 "Check if the current buffer contains the running clock.
4274 If yes, offer to stop it and to save the buffer with the changes."
4275 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4276 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4277 (buffer-name))))
4278 (org-clock-out)
4279 (when (y-or-n-p "Save changed buffer?")
4280 (save-buffer))))
4282 (defun org-clocktable-try-shift (dir n)
4283 "Check if this line starts a clock table, if yes, shift the time block."
4284 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4285 (org-clocktable-shift dir n)))
4287 ;;;###autoload
4288 (defun org-clock-persistence-insinuate ()
4289 "Set up hooks for clock persistence."
4290 (require 'org-clock)
4291 (add-hook 'org-mode-hook 'org-clock-load)
4292 (add-hook 'kill-emacs-hook 'org-clock-save))
4294 ;; Define the variable already here, to make sure we have it.
4295 (defvar org-indent-mode nil
4296 "Non-nil if Org-Indent mode is enabled.
4297 Use the command `org-indent-mode' to change this variable.")
4299 ;; Autoload archiving code
4300 ;; The stuff that is needed for cycling and tags has to be defined here.
4302 (defgroup org-archive nil
4303 "Options concerning archiving in Org-mode."
4304 :tag "Org Archive"
4305 :group 'org-structure)
4307 (defcustom org-archive-location "%s_archive::"
4308 "The location where subtrees should be archived.
4310 The value of this variable is a string, consisting of two parts,
4311 separated by a double-colon. The first part is a filename and
4312 the second part is a headline.
4314 When the filename is omitted, archiving happens in the same file.
4315 %s in the filename will be replaced by the current file
4316 name (without the directory part). Archiving to a different file
4317 is useful to keep archived entries from contributing to the
4318 Org-mode Agenda.
4320 The archived entries will be filed as subtrees of the specified
4321 headline. When the headline is omitted, the subtrees are simply
4322 filed away at the end of the file, as top-level entries. Also in
4323 the heading you can use %s to represent the file name, this can be
4324 useful when using the same archive for a number of different files.
4326 Here are a few examples:
4327 \"%s_archive::\"
4328 If the current file is Projects.org, archive in file
4329 Projects.org_archive, as top-level trees. This is the default.
4331 \"::* Archived Tasks\"
4332 Archive in the current file, under the top-level headline
4333 \"* Archived Tasks\".
4335 \"~/org/archive.org::\"
4336 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4338 \"~/org/archive.org::* From %s\"
4339 Archive in file ~/org/archive.org (absolute path), under headlines
4340 \"From FILENAME\" where file name is the current file name.
4342 \"~/org/datetree.org::datetree/* Finished Tasks\"
4343 The \"datetree/\" string is special, signifying to archive
4344 items to the datetree. Items are placed in either the CLOSED
4345 date of the item, or the current date if there is no CLOSED date.
4346 The heading will be a subentry to the current date. There doesn't
4347 need to be a heading, but there always needs to be a slash after
4348 datetree. For example, to store archived items directly in the
4349 datetree, use \"~/org/datetree.org::datetree/\".
4351 \"basement::** Finished Tasks\"
4352 Archive in file ./basement (relative path), as level 3 trees
4353 below the level 2 heading \"** Finished Tasks\".
4355 You may set this option on a per-file basis by adding to the buffer a
4356 line like
4358 #+ARCHIVE: basement::** Finished Tasks
4360 You may also define it locally for a subtree by setting an ARCHIVE property
4361 in the entry. If such a property is found in an entry, or anywhere up
4362 the hierarchy, it will be used."
4363 :group 'org-archive
4364 :type 'string)
4366 (defcustom org-archive-tag "ARCHIVE"
4367 "The tag that marks a subtree as archived.
4368 An archived subtree does not open during visibility cycling, and does
4369 not contribute to the agenda listings.
4370 After changing this, font-lock must be restarted in the relevant buffers to
4371 get the proper fontification."
4372 :group 'org-archive
4373 :group 'org-keywords
4374 :type 'string)
4376 (defcustom org-agenda-skip-archived-trees t
4377 "Non-nil means the agenda will skip any items located in archived trees.
4378 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4379 variable is no longer recommended, you should leave it at the value t.
4380 Instead, use the key `v' to cycle the archives-mode in the agenda."
4381 :group 'org-archive
4382 :group 'org-agenda-skip
4383 :type 'boolean)
4385 (defcustom org-columns-skip-archived-trees t
4386 "Non-nil means ignore archived trees when creating column view."
4387 :group 'org-archive
4388 :group 'org-properties
4389 :type 'boolean)
4391 (defcustom org-cycle-open-archived-trees nil
4392 "Non-nil means `org-cycle' will open archived trees.
4393 An archived tree is a tree marked with the tag ARCHIVE.
4394 When nil, archived trees will stay folded. You can still open them with
4395 normal outline commands like `show-all', but not with the cycling commands."
4396 :group 'org-archive
4397 :group 'org-cycle
4398 :type 'boolean)
4400 (defcustom org-sparse-tree-open-archived-trees nil
4401 "Non-nil means sparse tree construction shows matches in archived trees.
4402 When nil, matches in these trees are highlighted, but the trees are kept in
4403 collapsed state."
4404 :group 'org-archive
4405 :group 'org-sparse-trees
4406 :type 'boolean)
4408 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4409 "The default date type when building a sparse tree.
4410 When this is nil, a date is a scheduled or a deadline timestamp.
4411 Otherwise, these types are allowed:
4413 all: all timestamps
4414 active: only active timestamps (<...>)
4415 inactive: only inactive timestamps (<...)
4416 scheduled: only scheduled timestamps
4417 deadline: only deadline timestamps"
4418 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4419 (const :tag "All timestamps" all)
4420 (const :tag "Only active timestamps" active)
4421 (const :tag "Only inactive timestamps" inactive)
4422 (const :tag "Only scheduled timestamps" scheduled)
4423 (const :tag "Only deadline timestamps" deadline))
4424 :version "24.3"
4425 :group 'org-sparse-trees)
4427 (defun org-cycle-hide-archived-subtrees (state)
4428 "Re-hide all archived subtrees after a visibility state change."
4429 (when (and (not org-cycle-open-archived-trees)
4430 (not (memq state '(overview folded))))
4431 (save-excursion
4432 (let* ((globalp (memq state '(contents all)))
4433 (beg (if globalp (point-min) (point)))
4434 (end (if globalp (point-max) (org-end-of-subtree t))))
4435 (org-hide-archived-subtrees beg end)
4436 (goto-char beg)
4437 (if (looking-at (concat ".*:" org-archive-tag ":"))
4438 (message "%s" (substitute-command-keys
4439 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4441 (defun org-force-cycle-archived ()
4442 "Cycle subtree even if it is archived."
4443 (interactive)
4444 (setq this-command 'org-cycle)
4445 (let ((org-cycle-open-archived-trees t))
4446 (call-interactively 'org-cycle)))
4448 (defun org-hide-archived-subtrees (beg end)
4449 "Re-hide all archived subtrees after a visibility state change."
4450 (save-excursion
4451 (let* ((re (concat ":" org-archive-tag ":")))
4452 (goto-char beg)
4453 (while (re-search-forward re end t)
4454 (when (org-at-heading-p)
4455 (org-flag-subtree t)
4456 (org-end-of-subtree t))))))
4458 (declare-function outline-end-of-heading "outline" ())
4459 (declare-function outline-flag-region "outline" (from to flag))
4460 (defun org-flag-subtree (flag)
4461 (save-excursion
4462 (org-back-to-heading t)
4463 (outline-end-of-heading)
4464 (outline-flag-region (point)
4465 (progn (org-end-of-subtree t) (point))
4466 flag)))
4468 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4470 (eval-and-compile
4471 (org-autoload "org-archive"
4472 '(org-add-archive-files)))
4474 ;; Autoload Column View Code
4476 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4477 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4478 (declare-function org-columns-compute "org-colview" (property))
4480 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4481 '(org-columns-number-to-string
4482 org-columns-get-format-and-top-level
4483 org-columns-compute
4484 org-columns-remove-overlays))
4486 ;; Autoload ID code
4488 (declare-function org-id-store-link "org-id")
4489 (declare-function org-id-locations-load "org-id")
4490 (declare-function org-id-locations-save "org-id")
4491 (defvar org-id-track-globally)
4492 (org-autoload "org-id"
4493 '(org-id-new
4494 org-id-copy
4495 org-id-get-with-outline-path-completion
4496 org-id-get-with-outline-drilling))
4498 ;;; Variables for pre-computed regular expressions, all buffer local
4500 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4501 "Matches first line of a hidden block.")
4502 (make-variable-buffer-local 'org-drawer-regexp)
4503 (defvar org-todo-regexp nil
4504 "Matches any of the TODO state keywords.")
4505 (make-variable-buffer-local 'org-todo-regexp)
4506 (defvar org-not-done-regexp nil
4507 "Matches any of the TODO state keywords except the last one.")
4508 (make-variable-buffer-local 'org-not-done-regexp)
4509 (defvar org-not-done-heading-regexp nil
4510 "Matches a TODO headline that is not done.")
4511 (make-variable-buffer-local 'org-not-done-regexp)
4512 (defvar org-todo-line-regexp nil
4513 "Matches a headline and puts TODO state into group 2 if present.")
4514 (make-variable-buffer-local 'org-todo-line-regexp)
4515 (defvar org-complex-heading-regexp nil
4516 "Matches a headline and puts everything into groups:
4517 group 1: the stars
4518 group 2: The todo keyword, maybe
4519 group 3: Priority cookie
4520 group 4: True headline
4521 group 5: Tags")
4522 (make-variable-buffer-local 'org-complex-heading-regexp)
4523 (defvar org-complex-heading-regexp-format nil
4524 "Printf format to make regexp to match an exact headline.
4525 This regexp will match the headline of any node which has the
4526 exact headline text that is put into the format, but may have any
4527 TODO state, priority and tags.")
4528 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4529 (defvar org-todo-line-tags-regexp nil
4530 "Matches a headline and puts TODO state into group 2 if present.
4531 Also put tags into group 4 if tags are present.")
4532 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4533 (defvar org-ds-keyword-length 12
4534 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4535 (make-variable-buffer-local 'org-ds-keyword-length)
4536 (defvar org-deadline-regexp nil
4537 "Matches the DEADLINE keyword.")
4538 (make-variable-buffer-local 'org-deadline-regexp)
4539 (defvar org-deadline-time-regexp nil
4540 "Matches the DEADLINE keyword together with a time stamp.")
4541 (make-variable-buffer-local 'org-deadline-time-regexp)
4542 (defvar org-deadline-line-regexp nil
4543 "Matches the DEADLINE keyword and the rest of the line.")
4544 (make-variable-buffer-local 'org-deadline-line-regexp)
4545 (defvar org-scheduled-regexp nil
4546 "Matches the SCHEDULED keyword.")
4547 (make-variable-buffer-local 'org-scheduled-regexp)
4548 (defvar org-scheduled-time-regexp nil
4549 "Matches the SCHEDULED keyword together with a time stamp.")
4550 (make-variable-buffer-local 'org-scheduled-time-regexp)
4551 (defvar org-closed-time-regexp nil
4552 "Matches the CLOSED keyword together with a time stamp.")
4553 (make-variable-buffer-local 'org-closed-time-regexp)
4555 (defvar org-keyword-time-regexp nil
4556 "Matches any of the 4 keywords, together with the time stamp.")
4557 (make-variable-buffer-local 'org-keyword-time-regexp)
4558 (defvar org-keyword-time-not-clock-regexp nil
4559 "Matches any of the 3 keywords, together with the time stamp.")
4560 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4561 (defvar org-maybe-keyword-time-regexp nil
4562 "Matches a timestamp, possibly preceded by a keyword.")
4563 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4564 (defvar org-all-time-keywords nil
4565 "List of time keywords.")
4566 (make-variable-buffer-local 'org-all-time-keywords)
4568 (defconst org-plain-time-of-day-regexp
4569 (concat
4570 "\\(\\<[012]?[0-9]"
4571 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4572 "\\(--?"
4573 "\\(\\<[012]?[0-9]"
4574 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4575 "\\)?")
4576 "Regular expression to match a plain time or time range.
4577 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4578 groups carry important information:
4579 0 the full match
4580 1 the first time, range or not
4581 8 the second time, if it is a range.")
4583 (defconst org-plain-time-extension-regexp
4584 (concat
4585 "\\(\\<[012]?[0-9]"
4586 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4587 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4588 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4589 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4590 groups carry important information:
4591 0 the full match
4592 7 hours of duration
4593 9 minutes of duration")
4595 (defconst org-stamp-time-of-day-regexp
4596 (concat
4597 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4598 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4599 "\\(--?"
4600 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4601 "Regular expression to match a timestamp time or time range.
4602 After a match, the following groups carry important information:
4603 0 the full match
4604 1 date plus weekday, for back referencing to make sure both times are on the same day
4605 2 the first time, range or not
4606 4 the second time, if it is a range.")
4608 (defconst org-startup-options
4609 '(("fold" org-startup-folded t)
4610 ("overview" org-startup-folded t)
4611 ("nofold" org-startup-folded nil)
4612 ("showall" org-startup-folded nil)
4613 ("showeverything" org-startup-folded showeverything)
4614 ("content" org-startup-folded content)
4615 ("indent" org-startup-indented t)
4616 ("noindent" org-startup-indented nil)
4617 ("hidestars" org-hide-leading-stars t)
4618 ("showstars" org-hide-leading-stars nil)
4619 ("odd" org-odd-levels-only t)
4620 ("oddeven" org-odd-levels-only nil)
4621 ("align" org-startup-align-all-tables t)
4622 ("noalign" org-startup-align-all-tables nil)
4623 ("inlineimages" org-startup-with-inline-images t)
4624 ("noinlineimages" org-startup-with-inline-images nil)
4625 ("customtime" org-display-custom-times t)
4626 ("logdone" org-log-done time)
4627 ("lognotedone" org-log-done note)
4628 ("nologdone" org-log-done nil)
4629 ("lognoteclock-out" org-log-note-clock-out t)
4630 ("nolognoteclock-out" org-log-note-clock-out nil)
4631 ("logrepeat" org-log-repeat state)
4632 ("lognoterepeat" org-log-repeat note)
4633 ("logdrawer" org-log-into-drawer t)
4634 ("nologdrawer" org-log-into-drawer nil)
4635 ("logstatesreversed" org-log-states-order-reversed t)
4636 ("nologstatesreversed" org-log-states-order-reversed nil)
4637 ("nologrepeat" org-log-repeat nil)
4638 ("logreschedule" org-log-reschedule time)
4639 ("lognotereschedule" org-log-reschedule note)
4640 ("nologreschedule" org-log-reschedule nil)
4641 ("logredeadline" org-log-redeadline time)
4642 ("lognoteredeadline" org-log-redeadline note)
4643 ("nologredeadline" org-log-redeadline nil)
4644 ("logrefile" org-log-refile time)
4645 ("lognoterefile" org-log-refile note)
4646 ("nologrefile" org-log-refile nil)
4647 ("fninline" org-footnote-define-inline t)
4648 ("nofninline" org-footnote-define-inline nil)
4649 ("fnlocal" org-footnote-section nil)
4650 ("fnauto" org-footnote-auto-label t)
4651 ("fnprompt" org-footnote-auto-label nil)
4652 ("fnconfirm" org-footnote-auto-label confirm)
4653 ("fnplain" org-footnote-auto-label plain)
4654 ("fnadjust" org-footnote-auto-adjust t)
4655 ("nofnadjust" org-footnote-auto-adjust nil)
4656 ("constcgs" constants-unit-system cgs)
4657 ("constSI" constants-unit-system SI)
4658 ("noptag" org-tag-persistent-alist nil)
4659 ("hideblocks" org-hide-block-startup t)
4660 ("nohideblocks" org-hide-block-startup nil)
4661 ("beamer" org-startup-with-beamer-mode t)
4662 ("entitiespretty" org-pretty-entities t)
4663 ("entitiesplain" org-pretty-entities nil))
4664 "Variable associated with STARTUP options for org-mode.
4665 Each element is a list of three items: the startup options (as written
4666 in the #+STARTUP line), the corresponding variable, and the value to set
4667 this variable to if the option is found. An optional forth element PUSH
4668 means to push this value onto the list in the variable.")
4670 (defun org-update-property-plist (key val props)
4671 "Update PROPS with KEY and VAL."
4672 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4673 (key (if appending (substring key 0 (- (length key) 1)) key))
4674 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4675 (previous (cdr (assoc key props))))
4676 (if appending
4677 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4678 (cons (cons key val) remainder))))
4680 (defconst org-block-regexp
4681 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4682 "Regular expression for hiding blocks.")
4683 (defconst org-heading-keyword-regexp-format
4684 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4685 "Printf format for a regexp matching an headline with some keyword.
4686 This regexp will match the headline of any node which has the
4687 exact keyword that is put into the format. The keyword isn't in
4688 any group by default, but the stars and the body are.")
4689 (defconst org-heading-keyword-maybe-regexp-format
4690 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4691 "Printf format for a regexp matching an headline, possibly with some keyword.
4692 This regexp can match any headline with the specified keyword, or
4693 without a keyword. The keyword isn't in any group by default,
4694 but the stars and the body are.")
4696 (defun org-set-regexps-and-options ()
4697 "Precompute regular expressions for current buffer."
4698 (when (derived-mode-p 'org-mode)
4699 (org-set-local 'org-todo-kwd-alist nil)
4700 (org-set-local 'org-todo-key-alist nil)
4701 (org-set-local 'org-todo-key-trigger nil)
4702 (org-set-local 'org-todo-keywords-1 nil)
4703 (org-set-local 'org-done-keywords nil)
4704 (org-set-local 'org-todo-heads nil)
4705 (org-set-local 'org-todo-sets nil)
4706 (org-set-local 'org-todo-log-states nil)
4707 (org-set-local 'org-file-properties nil)
4708 (org-set-local 'org-file-tags nil)
4709 (let ((re (org-make-options-regexp
4710 '("CATEGORY" "TODO" "COLUMNS"
4711 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4712 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4713 "OPTIONS")
4714 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4715 (splitre "[ \t]+")
4716 (scripts org-use-sub-superscripts)
4717 kwds kws0 kwsa key log value cat arch tags const links hw dws
4718 tail sep kws1 prio props ftags drawers beamer-p
4719 ext-setup-or-nil setup-contents (start 0))
4720 (save-excursion
4721 (save-restriction
4722 (widen)
4723 (goto-char (point-min))
4724 (while (or (and ext-setup-or-nil
4725 (string-match re ext-setup-or-nil start)
4726 (setq start (match-end 0)))
4727 (and (setq ext-setup-or-nil nil start 0)
4728 (re-search-forward re nil t)))
4729 (setq key (upcase (match-string 1 ext-setup-or-nil))
4730 value (org-match-string-no-properties 2 ext-setup-or-nil))
4731 (if (stringp value) (setq value (org-trim value)))
4732 (cond
4733 ((equal key "CATEGORY")
4734 (setq cat value))
4735 ((member key '("SEQ_TODO" "TODO"))
4736 (push (cons 'sequence (org-split-string value splitre)) kwds))
4737 ((equal key "TYP_TODO")
4738 (push (cons 'type (org-split-string value splitre)) kwds))
4739 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4740 ;; general TODO-like setup
4741 (push (cons (intern (downcase (match-string 1 key)))
4742 (org-split-string value splitre)) kwds))
4743 ((equal key "TAGS")
4744 (setq tags (append tags (if tags '("\\n") nil)
4745 (org-split-string value splitre))))
4746 ((equal key "COLUMNS")
4747 (org-set-local 'org-columns-default-format value))
4748 ((equal key "LINK")
4749 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4750 (push (cons (match-string 1 value)
4751 (org-trim (match-string 2 value)))
4752 links)))
4753 ((equal key "PRIORITIES")
4754 (setq prio (org-split-string value " +")))
4755 ((equal key "PROPERTY")
4756 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4757 (setq props (org-update-property-plist (match-string 1 value)
4758 (match-string 2 value)
4759 props))))
4760 ((equal key "FILETAGS")
4761 (when (string-match "\\S-" value)
4762 (setq ftags
4763 (append
4764 ftags
4765 (apply 'append
4766 (mapcar (lambda (x) (org-split-string x ":"))
4767 (org-split-string value)))))))
4768 ((equal key "DRAWERS")
4769 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4770 ((equal key "CONSTANTS")
4771 (setq const (append const (org-split-string value splitre))))
4772 ((equal key "STARTUP")
4773 (let ((opts (org-split-string value splitre))
4774 l var val)
4775 (while (setq l (pop opts))
4776 (when (setq l (assoc l org-startup-options))
4777 (setq var (nth 1 l) val (nth 2 l))
4778 (if (not (nth 3 l))
4779 (set (make-local-variable var) val)
4780 (if (not (listp (symbol-value var)))
4781 (set (make-local-variable var) nil))
4782 (set (make-local-variable var) (symbol-value var))
4783 (add-to-list var val))))))
4784 ((equal key "ARCHIVE")
4785 (setq arch value)
4786 (remove-text-properties 0 (length arch)
4787 '(face t fontified t) arch))
4788 ((equal key "LATEX_CLASS")
4789 (setq beamer-p (equal value "beamer")))
4790 ((equal key "OPTIONS")
4791 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4792 (setq scripts (read (match-string 2 value)))))
4793 ((equal key "SETUPFILE")
4794 (setq setup-contents (org-file-contents
4795 (expand-file-name
4796 (org-remove-double-quotes value))
4797 'noerror))
4798 (if (not ext-setup-or-nil)
4799 (setq ext-setup-or-nil setup-contents start 0)
4800 (setq ext-setup-or-nil
4801 (concat (substring ext-setup-or-nil 0 start)
4802 "\n" setup-contents "\n"
4803 (substring ext-setup-or-nil start)))))))
4804 ;; search for property blocks
4805 (goto-char (point-min))
4806 (while (re-search-forward org-block-regexp nil t)
4807 (when (equal "PROPERTY" (upcase (match-string 1)))
4808 (setq value (replace-regexp-in-string
4809 "[\n\r]" " " (match-string 4)))
4810 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4811 (setq props (org-update-property-plist (match-string 1 value)
4812 (match-string 2 value)
4813 props)))))))
4814 (org-set-local 'org-use-sub-superscripts scripts)
4815 (when cat
4816 (org-set-local 'org-category (intern cat))
4817 (push (cons "CATEGORY" cat) props))
4818 (when prio
4819 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4820 (setq prio (mapcar 'string-to-char prio))
4821 (org-set-local 'org-highest-priority (nth 0 prio))
4822 (org-set-local 'org-lowest-priority (nth 1 prio))
4823 (org-set-local 'org-default-priority (nth 2 prio)))
4824 (and props (org-set-local 'org-file-properties (nreverse props)))
4825 (and ftags (org-set-local 'org-file-tags
4826 (mapcar 'org-add-prop-inherited ftags)))
4827 (and drawers (org-set-local 'org-drawers drawers))
4828 (and arch (org-set-local 'org-archive-location arch))
4829 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4830 ;; Process the TODO keywords
4831 (unless kwds
4832 ;; Use the global values as if they had been given locally.
4833 (setq kwds (default-value 'org-todo-keywords))
4834 (if (stringp (car kwds))
4835 (setq kwds (list (cons org-todo-interpretation
4836 (default-value 'org-todo-keywords)))))
4837 (setq kwds (reverse kwds)))
4838 (setq kwds (nreverse kwds))
4839 (let (inter kws kw)
4840 (while (setq kws (pop kwds))
4841 (let ((kws (or
4842 (run-hook-with-args-until-success
4843 'org-todo-setup-filter-hook kws)
4844 kws)))
4845 (setq inter (pop kws) sep (member "|" kws)
4846 kws0 (delete "|" (copy-sequence kws))
4847 kwsa nil
4848 kws1 (mapcar
4849 (lambda (x)
4850 ;; 1 2
4851 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4852 (progn
4853 (setq kw (match-string 1 x)
4854 key (and (match-end 2) (match-string 2 x))
4855 log (org-extract-log-state-settings x))
4856 (push (cons kw (and key (string-to-char key))) kwsa)
4857 (and log (push log org-todo-log-states))
4859 (error "Invalid TODO keyword %s" x)))
4860 kws0)
4861 kwsa (if kwsa (append '((:startgroup))
4862 (nreverse kwsa)
4863 '((:endgroup))))
4864 hw (car kws1)
4865 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4866 tail (list inter hw (car dws) (org-last dws))))
4867 (add-to-list 'org-todo-heads hw 'append)
4868 (push kws1 org-todo-sets)
4869 (setq org-done-keywords (append org-done-keywords dws nil))
4870 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4871 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4872 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4873 (setq org-todo-sets (nreverse org-todo-sets)
4874 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4875 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4876 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4877 ;; Process the constants
4878 (when const
4879 (let (e cst)
4880 (while (setq e (pop const))
4881 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4882 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4883 (setq org-table-formula-constants-local cst)))
4885 ;; Process the tags.
4886 (when tags
4887 (let (e tgs)
4888 (while (setq e (pop tags))
4889 (cond
4890 ((equal e "{") (push '(:startgroup) tgs))
4891 ((equal e "}") (push '(:endgroup) tgs))
4892 ((equal e "\\n") (push '(:newline) tgs))
4893 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4894 (push (cons (match-string 1 e)
4895 (string-to-char (match-string 2 e)))
4896 tgs))
4897 (t (push (list e) tgs))))
4898 (org-set-local 'org-tag-alist nil)
4899 (while (setq e (pop tgs))
4900 (or (and (stringp (car e))
4901 (assoc (car e) org-tag-alist))
4902 (push e org-tag-alist)))))
4904 ;; Compute the regular expressions and other local variables.
4905 ;; Using `org-outline-regexp-bol' would complicate them much,
4906 ;; because of the fixed white space at the end of that string.
4907 (if (not org-done-keywords)
4908 (setq org-done-keywords (and org-todo-keywords-1
4909 (list (org-last org-todo-keywords-1)))))
4910 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4911 (length org-scheduled-string)
4912 (length org-clock-string)
4913 (length org-closed-string)))
4914 org-drawer-regexp
4915 (concat "^[ \t]*:\\("
4916 (mapconcat 'regexp-quote org-drawers "\\|")
4917 "\\):[ \t]*$")
4918 org-not-done-keywords
4919 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4920 org-todo-regexp
4921 (concat "\\("
4922 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4923 "\\)")
4924 org-not-done-regexp
4925 (concat "\\("
4926 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4927 "\\)")
4928 org-not-done-heading-regexp
4929 (format org-heading-keyword-regexp-format org-not-done-regexp)
4930 org-todo-line-regexp
4931 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4932 org-complex-heading-regexp
4933 (concat "^\\(\\*+\\)"
4934 "\\(?: +" org-todo-regexp "\\)?"
4935 "\\(?: +\\(\\[#.\\]\\)\\)?"
4936 "\\(?: +\\(.*?\\)\\)??"
4937 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4938 "[ \t]*$")
4939 org-complex-heading-regexp-format
4940 (concat "^\\(\\*+\\)"
4941 "\\(?: +" org-todo-regexp "\\)?"
4942 "\\(?: +\\(\\[#.\\]\\)\\)?"
4943 "\\(?: +"
4944 ;; Stats cookies can be stuck to body.
4945 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4946 "\\(%s\\)"
4947 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4948 "\\)"
4949 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4950 "[ \t]*$")
4951 org-todo-line-tags-regexp
4952 (concat "^\\(\\*+\\)"
4953 "\\(?: +" org-todo-regexp "\\)?"
4954 "\\(?: +\\(.*?\\)\\)??"
4955 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4956 "[ \t]*$")
4957 org-deadline-regexp (concat "\\<" org-deadline-string)
4958 org-deadline-time-regexp
4959 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4960 org-deadline-line-regexp
4961 (concat "\\<\\(" org-deadline-string "\\).*")
4962 org-scheduled-regexp
4963 (concat "\\<" org-scheduled-string)
4964 org-scheduled-time-regexp
4965 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4966 org-closed-time-regexp
4967 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4968 org-keyword-time-regexp
4969 (concat "\\<\\(" org-scheduled-string
4970 "\\|" org-deadline-string
4971 "\\|" org-closed-string
4972 "\\|" org-clock-string "\\)"
4973 " *[[<]\\([^]>]+\\)[]>]")
4974 org-keyword-time-not-clock-regexp
4975 (concat "\\<\\(" org-scheduled-string
4976 "\\|" org-deadline-string
4977 "\\|" org-closed-string
4978 "\\)"
4979 " *[[<]\\([^]>]+\\)[]>]")
4980 org-maybe-keyword-time-regexp
4981 (concat "\\(\\<\\(" org-scheduled-string
4982 "\\|" org-deadline-string
4983 "\\|" org-closed-string
4984 "\\|" org-clock-string "\\)\\)?"
4985 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4986 org-all-time-keywords
4987 (mapcar (lambda (w) (substring w 0 -1))
4988 (list org-scheduled-string org-deadline-string
4989 org-clock-string org-closed-string)))
4990 (org-set-font-lock-defaults))))
4992 (defun org-file-contents (file &optional noerror)
4993 "Return the contents of FILE, as a string."
4994 (if (or (not file)
4995 (not (file-readable-p file)))
4996 (if noerror
4997 (progn
4998 (message "Cannot read file \"%s\"" file)
4999 (ding) (sit-for 2)
5001 (error "Cannot read file \"%s\"" file))
5002 (with-temp-buffer
5003 (insert-file-contents file)
5004 (buffer-string))))
5006 (defun org-extract-log-state-settings (x)
5007 "Extract the log state setting from a TODO keyword string.
5008 This will extract info from a string like \"WAIT(w@/!)\"."
5009 (let (kw key log1 log2)
5010 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5011 (setq kw (match-string 1 x)
5012 key (and (match-end 2) (match-string 2 x))
5013 log1 (and (match-end 3) (match-string 3 x))
5014 log2 (and (match-end 4) (match-string 4 x)))
5015 (and (or log1 log2)
5016 (list kw
5017 (and log1 (if (equal log1 "!") 'time 'note))
5018 (and log2 (if (equal log2 "!") 'time 'note)))))))
5020 (defun org-remove-keyword-keys (list)
5021 "Remove a pair of parenthesis at the end of each string in LIST."
5022 (mapcar (lambda (x)
5023 (if (string-match "(.*)$" x)
5024 (substring x 0 (match-beginning 0))
5026 list))
5028 (defun org-assign-fast-keys (alist)
5029 "Assign fast keys to a keyword-key alist.
5030 Respect keys that are already there."
5031 (let (new e (alt ?0))
5032 (while (setq e (pop alist))
5033 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5034 (cdr e)) ;; Key already assigned.
5035 (push e new)
5036 (let ((clist (string-to-list (downcase (car e))))
5037 (used (append new alist)))
5038 (when (= (car clist) ?@)
5039 (pop clist))
5040 (while (and clist (rassoc (car clist) used))
5041 (pop clist))
5042 (unless clist
5043 (while (rassoc alt used)
5044 (incf alt)))
5045 (push (cons (car e) (or (car clist) alt)) new))))
5046 (nreverse new)))
5048 ;;; Some variables used in various places
5050 (defvar org-window-configuration nil
5051 "Used in various places to store a window configuration.")
5052 (defvar org-selected-window nil
5053 "Used in various places to store a window configuration.")
5054 (defvar org-finish-function nil
5055 "Function to be called when `C-c C-c' is used.
5056 This is for getting out of special buffers like capture.")
5059 ;; FIXME: Occasionally check by commenting these, to make sure
5060 ;; no other functions uses these, forgetting to let-bind them.
5061 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5062 (defvar org-last-state)
5063 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5065 ;; Defined somewhere in this file, but used before definition.
5066 (defvar org-entities) ;; defined in org-entities.el
5067 (defvar org-struct-menu)
5068 (defvar org-org-menu)
5069 (defvar org-tbl-menu)
5071 ;;;; Define the Org-mode
5073 ;; We use a before-change function to check if a table might need
5074 ;; an update.
5075 (defvar org-table-may-need-update t
5076 "Indicates that a table might need an update.
5077 This variable is set by `org-before-change-function'.
5078 `org-table-align' sets it back to nil.")
5079 (defun org-before-change-function (beg end)
5080 "Every change indicates that a table might need an update."
5081 (setq org-table-may-need-update t))
5082 (defvar org-mode-map)
5083 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5084 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5085 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5086 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5087 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5088 (defvar org-table-buffer-is-an nil)
5090 (defvar bidi-paragraph-direction)
5091 (defvar buffer-face-mode-face)
5093 (require 'outline)
5094 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5095 (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"))
5096 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5098 ;; Other stuff we need.
5099 (require 'time-date)
5100 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5101 (require 'easymenu)
5102 (require 'overlay)
5104 ;; (require 'org-macs) moved higher up in the file before it is first used
5105 (require 'org-entities)
5106 ;; (require 'org-compat) moved higher up in the file before it is first used
5107 (require 'org-faces)
5108 (require 'org-list)
5109 (require 'org-pcomplete)
5110 (require 'org-src)
5111 (require 'org-footnote)
5113 ;; babel
5114 (require 'ob)
5116 ;;;###autoload
5117 (define-derived-mode org-mode outline-mode "Org"
5118 "Outline-based notes management and organizer, alias
5119 \"Carsten's outline-mode for keeping track of everything.\"
5121 Org-mode develops organizational tasks around a NOTES file which
5122 contains information about projects as plain text. Org-mode is
5123 implemented on top of outline-mode, which is ideal to keep the content
5124 of large files well structured. It supports ToDo items, deadlines and
5125 time stamps, which magically appear in the diary listing of the Emacs
5126 calendar. Tables are easily created with a built-in table editor.
5127 Plain text URL-like links connect to websites, emails (VM), Usenet
5128 messages (Gnus), BBDB entries, and any files related to the project.
5129 For printing and sharing of notes, an Org-mode file (or a part of it)
5130 can be exported as a structured ASCII or HTML file.
5132 The following commands are available:
5134 \\{org-mode-map}"
5136 ;; Get rid of Outline menus, they are not needed
5137 ;; Need to do this here because define-derived-mode sets up
5138 ;; the keymap so late. Still, it is a waste to call this each time
5139 ;; we switch another buffer into org-mode.
5140 (if (featurep 'xemacs)
5141 (when (boundp 'outline-mode-menu-heading)
5142 ;; Assume this is Greg's port, it uses easymenu
5143 (easy-menu-remove outline-mode-menu-heading)
5144 (easy-menu-remove outline-mode-menu-show)
5145 (easy-menu-remove outline-mode-menu-hide))
5146 (define-key org-mode-map [menu-bar headings] 'undefined)
5147 (define-key org-mode-map [menu-bar hide] 'undefined)
5148 (define-key org-mode-map [menu-bar show] 'undefined))
5150 (org-load-modules-maybe)
5151 (easy-menu-add org-org-menu)
5152 (easy-menu-add org-tbl-menu)
5153 (org-install-agenda-files-menu)
5154 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5155 (add-to-invisibility-spec '(org-cwidth))
5156 (add-to-invisibility-spec '(org-hide-block . t))
5157 (when (featurep 'xemacs)
5158 (org-set-local 'line-move-ignore-invisible t))
5159 (org-set-local 'outline-regexp org-outline-regexp)
5160 (org-set-local 'outline-level 'org-outline-level)
5161 (setq bidi-paragraph-direction 'left-to-right)
5162 (when (and org-ellipsis
5163 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5164 (fboundp 'make-glyph-code))
5165 (unless org-display-table
5166 (setq org-display-table (make-display-table)))
5167 (set-display-table-slot
5168 org-display-table 4
5169 (vconcat (mapcar
5170 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5171 org-ellipsis)))
5172 (if (stringp org-ellipsis) org-ellipsis "..."))))
5173 (setq buffer-display-table org-display-table))
5174 (org-set-regexps-and-options)
5175 (when (and org-tag-faces (not org-tags-special-faces-re))
5176 ;; tag faces set outside customize.... force initialization.
5177 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5178 ;; Calc embedded
5179 (org-set-local 'calc-embedded-open-mode "# ")
5180 (modify-syntax-entry ?@ "w")
5181 (modify-syntax-entry ?\" "\"")
5182 (if org-startup-truncated (setq truncate-lines t))
5183 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5184 (org-set-local 'font-lock-unfontify-region-function
5185 'org-unfontify-region)
5186 ;; Activate before-change-function
5187 (org-set-local 'org-table-may-need-update t)
5188 (org-add-hook 'before-change-functions 'org-before-change-function nil
5189 'local)
5190 ;; Check for running clock before killing a buffer
5191 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5192 ;; Initialize macros templates.
5193 (org-macro-initialize-templates)
5194 ;; Initialize radio targets.
5195 (org-update-radio-target-regexp)
5196 ;; Indentation.
5197 (org-set-local 'indent-line-function 'org-indent-line)
5198 (org-set-local 'indent-region-function 'org-indent-region)
5199 ;; Filling and auto-filling.
5200 (org-setup-filling)
5201 ;; Comments.
5202 (org-setup-comments-handling)
5203 ;; Beginning/end of defun
5204 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5205 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5206 ;; Next error for sparse trees
5207 (org-set-local 'next-error-function 'org-occur-next-match)
5208 ;; Make sure dependence stuff works reliably, even for users who set it
5209 ;; too late :-(
5210 (if org-enforce-todo-dependencies
5211 (add-hook 'org-blocker-hook
5212 'org-block-todo-from-children-or-siblings-or-parent)
5213 (remove-hook 'org-blocker-hook
5214 'org-block-todo-from-children-or-siblings-or-parent))
5215 (if org-enforce-todo-checkbox-dependencies
5216 (add-hook 'org-blocker-hook
5217 'org-block-todo-from-checkboxes)
5218 (remove-hook 'org-blocker-hook
5219 'org-block-todo-from-checkboxes))
5221 ;; Align options lines
5222 (org-set-local
5223 'align-mode-rules-list
5224 '((org-in-buffer-settings
5225 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5226 (modes . '(org-mode)))))
5228 ;; Imenu
5229 (org-set-local 'imenu-create-index-function
5230 'org-imenu-get-tree)
5232 ;; Make isearch reveal context
5233 (if (or (featurep 'xemacs)
5234 (not (boundp 'outline-isearch-open-invisible-function)))
5235 ;; Emacs 21 and XEmacs make use of the hook
5236 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5237 ;; Emacs 22 deals with this through a special variable
5238 (org-set-local 'outline-isearch-open-invisible-function
5239 (lambda (&rest ignore) (org-show-context 'isearch))))
5241 ;; Setup the pcomplete hooks
5242 (set (make-local-variable 'pcomplete-command-completion-function)
5243 'org-pcomplete-initial)
5244 (set (make-local-variable 'pcomplete-command-name-function)
5245 'org-command-at-point)
5246 (set (make-local-variable 'pcomplete-default-completion-function)
5247 'ignore)
5248 (set (make-local-variable 'pcomplete-parse-arguments-function)
5249 'org-parse-arguments)
5250 (set (make-local-variable 'pcomplete-termination-string) "")
5251 (when (>= emacs-major-version 23)
5252 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5254 ;; If empty file that did not turn on org-mode automatically, make it to.
5255 (if (and org-insert-mode-line-in-empty-file
5256 (org-called-interactively-p 'any)
5257 (= (point-min) (point-max)))
5258 (insert "# -*- mode: org -*-\n\n"))
5259 (unless org-inhibit-startup
5260 (and org-startup-with-beamer-mode (org-beamer-mode))
5261 (when org-startup-align-all-tables
5262 (let ((bmp (buffer-modified-p)))
5263 (org-table-map-tables 'org-table-align 'quietly)
5264 (set-buffer-modified-p bmp)))
5265 (when org-startup-with-inline-images
5266 (org-display-inline-images))
5267 (unless org-inhibit-startup-visibility-stuff
5268 (org-set-startup-visibility)))
5269 ;; Try to set org-hide correctly
5270 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5272 (when (fboundp 'abbrev-table-put)
5273 (abbrev-table-put org-mode-abbrev-table
5274 :parents (list text-mode-abbrev-table)))
5276 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5279 (defun org-find-invisible-foreground ()
5280 (let ((candidates (remove
5281 "unspecified-bg"
5282 (nconc
5283 (list (face-background 'default)
5284 (face-background 'org-default))
5285 (mapcar
5286 (lambda (alist)
5287 (when (boundp alist)
5288 (cdr (assoc 'background-color (symbol-value alist)))))
5289 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5290 (list (face-foreground 'org-hide))))))
5291 (car (remove nil candidates))))
5293 (defun org-current-time (&optional rounding-minutes)
5294 "Current time, possibly rounded to ROUNDING-MINUTES.
5295 When ROUNDING-MINUTES is not an integer, fall back on the car of
5296 `org-time-stamp-rounding-minutes'."
5297 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5298 (car org-time-stamp-rounding-minutes)))
5299 (time (decode-time)))
5300 (if (> r 1)
5301 (apply 'encode-time
5302 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5303 (nthcdr 2 time)))
5304 (current-time))))
5306 (defun org-today ()
5307 "Return today date, considering `org-extend-today-until'."
5308 (time-to-days
5309 (time-subtract (current-time)
5310 (list 0 (* 3600 org-extend-today-until) 0))))
5312 ;;;; Font-Lock stuff, including the activators
5314 (defvar org-mouse-map (make-sparse-keymap))
5315 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5316 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5317 (when org-mouse-1-follows-link
5318 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5319 (when org-tab-follows-link
5320 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5321 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5323 (require 'font-lock)
5325 (defconst org-non-link-chars "]\t\n\r<>")
5326 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5327 "shell" "elisp" "doi" "message"))
5328 (defvar org-link-types-re nil
5329 "Matches a link that has a url-like prefix like \"http:\"")
5330 (defvar org-link-re-with-space nil
5331 "Matches a link with spaces, optional angular brackets around it.")
5332 (defvar org-link-re-with-space2 nil
5333 "Matches a link with spaces, optional angular brackets around it.")
5334 (defvar org-link-re-with-space3 nil
5335 "Matches a link with spaces, only for internal part in bracket links.")
5336 (defvar org-angle-link-re nil
5337 "Matches link with angular brackets, spaces are allowed.")
5338 (defvar org-plain-link-re nil
5339 "Matches plain link, without spaces.")
5340 (defvar org-bracket-link-regexp nil
5341 "Matches a link in double brackets.")
5342 (defvar org-bracket-link-analytic-regexp nil
5343 "Regular expression used to analyze links.
5344 Here is what the match groups contain after a match:
5345 1: http:
5346 2: http
5347 3: path
5348 4: [desc]
5349 5: desc")
5350 (defvar org-bracket-link-analytic-regexp++ nil
5351 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5352 (defvar org-any-link-re nil
5353 "Regular expression matching any link.")
5355 (defconst org-match-sexp-depth 3
5356 "Number of stacked braces for sub/superscript matching.")
5358 (defun org-create-multibrace-regexp (left right n)
5359 "Create a regular expression which will match a balanced sexp.
5360 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5361 as single character strings.
5362 The regexp returned will match the entire expression including the
5363 delimiters. It will also define a single group which contains the
5364 match except for the outermost delimiters. The maximum depth of
5365 stacked delimiters is N. Escaping delimiters is not possible."
5366 (let* ((nothing (concat "[^" left right "]*?"))
5367 (or "\\|")
5368 (re nothing)
5369 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5370 (while (> n 1)
5371 (setq n (1- n)
5372 re (concat re or next)
5373 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5374 (concat left "\\(" re "\\)" right)))
5376 (defvar org-match-substring-regexp
5377 (concat
5378 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5379 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5380 "\\|"
5381 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5382 "\\|"
5383 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5384 "The regular expression matching a sub- or superscript.")
5386 (defvar org-match-substring-with-braces-regexp
5387 (concat
5388 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5389 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5390 "\\)")
5391 "The regular expression matching a sub- or superscript, forcing braces.")
5393 (defun org-make-link-regexps ()
5394 "Update the link regular expressions.
5395 This should be called after the variable `org-link-types' has changed."
5396 (setq org-link-types-re
5397 (concat
5398 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5399 org-link-re-with-space
5400 (concat
5401 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5402 "\\([^" org-non-link-chars " ]"
5403 "[^" org-non-link-chars "]*"
5404 "[^" org-non-link-chars " ]\\)>?")
5405 org-link-re-with-space2
5406 (concat
5407 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5408 "\\([^" org-non-link-chars " ]"
5409 "[^\t\n\r]*"
5410 "[^" org-non-link-chars " ]\\)>?")
5411 org-link-re-with-space3
5412 (concat
5413 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5414 "\\([^" org-non-link-chars " ]"
5415 "[^\t\n\r]*\\)")
5416 org-angle-link-re
5417 (concat
5418 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5419 "\\([^" org-non-link-chars " ]"
5420 "[^" org-non-link-chars "]*"
5421 "\\)>")
5422 org-plain-link-re
5423 (concat
5424 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5425 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5426 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5427 org-bracket-link-regexp
5428 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5429 org-bracket-link-analytic-regexp
5430 (concat
5431 "\\[\\["
5432 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5433 "\\([^]]+\\)"
5434 "\\]"
5435 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5436 "\\]")
5437 org-bracket-link-analytic-regexp++
5438 (concat
5439 "\\[\\["
5440 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5441 "\\([^]]+\\)"
5442 "\\]"
5443 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5444 "\\]")
5445 org-any-link-re
5446 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5447 org-angle-link-re "\\)\\|\\("
5448 org-plain-link-re "\\)")))
5450 (org-make-link-regexps)
5452 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5453 "Regular expression for fast time stamp matching.")
5454 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5455 "Regular expression for fast time stamp matching.")
5456 (defconst org-ts-regexp0
5457 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5458 "Regular expression matching time strings for analysis.
5459 This one does not require the space after the date, so it can be used
5460 on a string that terminates immediately after the date.")
5461 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5462 "Regular expression matching time strings for analysis.")
5463 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5464 "Regular expression matching time stamps, with groups.")
5465 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5466 "Regular expression matching time stamps (also [..]), with groups.")
5467 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5468 "Regular expression matching a time stamp range.")
5469 (defconst org-tr-regexp-both
5470 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5471 "Regular expression matching a time stamp range.")
5472 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5473 org-ts-regexp "\\)?")
5474 "Regular expression matching a time stamp or time stamp range.")
5475 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5476 org-ts-regexp-both "\\)?")
5477 "Regular expression matching a time stamp or time stamp range.
5478 The time stamps may be either active or inactive.")
5480 (defvar org-emph-face nil)
5482 (defun org-do-emphasis-faces (limit)
5483 "Run through the buffer and add overlays to emphasized strings."
5484 (let (rtn a)
5485 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5486 (if (not (= (char-after (match-beginning 3))
5487 (char-after (match-beginning 4))))
5488 (progn
5489 (setq rtn t)
5490 (setq a (assoc (match-string 3) org-emphasis-alist))
5491 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5492 'face
5493 (nth 1 a))
5494 (and (nth 4 a)
5495 (org-remove-flyspell-overlays-in
5496 (match-beginning 0) (match-end 0)))
5497 (add-text-properties (match-beginning 2) (match-end 2)
5498 '(font-lock-multiline t org-emphasis t))
5499 (when org-hide-emphasis-markers
5500 (add-text-properties (match-end 4) (match-beginning 5)
5501 '(invisible org-link))
5502 (add-text-properties (match-beginning 3) (match-end 3)
5503 '(invisible org-link)))))
5504 (backward-char 1))
5505 rtn))
5507 (defun org-emphasize (&optional char)
5508 "Insert or change an emphasis, i.e. a font like bold or italic.
5509 If there is an active region, change that region to a new emphasis.
5510 If there is no region, just insert the marker characters and position
5511 the cursor between them.
5512 CHAR should be either the marker character, or the first character of the
5513 HTML tag associated with that emphasis. If CHAR is a space, the means
5514 to remove the emphasis of the selected region.
5515 If char is not given (for example in an interactive call) it
5516 will be prompted for."
5517 (interactive)
5518 (let ((eal org-emphasis-alist) e det
5519 (erc org-emphasis-regexp-components)
5520 (prompt "")
5521 (string "") beg end move tag c s)
5522 (if (org-region-active-p)
5523 (setq beg (region-beginning) end (region-end)
5524 string (buffer-substring beg end))
5525 (setq move t))
5527 (while (setq e (pop eal))
5528 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5529 c (aref tag 0))
5530 (push (cons c (string-to-char (car e))) det)
5531 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5532 (substring tag 1)))))
5533 (setq det (nreverse det))
5534 (unless char
5535 (message "%s" (concat "Emphasis marker or tag:" prompt))
5536 (setq char (read-char-exclusive)))
5537 (setq char (or (cdr (assoc char det)) char))
5538 (if (equal char ?\ )
5539 (setq s "" move nil)
5540 (unless (assoc (char-to-string char) org-emphasis-alist)
5541 (error "No such emphasis marker: \"%c\"" char))
5542 (setq s (char-to-string char)))
5543 (while (and (> (length string) 1)
5544 (equal (substring string 0 1) (substring string -1))
5545 (assoc (substring string 0 1) org-emphasis-alist))
5546 (setq string (substring string 1 -1)))
5547 (setq string (concat s string s))
5548 (if beg (delete-region beg end))
5549 (unless (or (bolp)
5550 (string-match (concat "[" (nth 0 erc) "\n]")
5551 (char-to-string (char-before (point)))))
5552 (insert " "))
5553 (unless (or (eobp)
5554 (string-match (concat "[" (nth 1 erc) "\n]")
5555 (char-to-string (char-after (point)))))
5556 (insert " ") (backward-char 1))
5557 (insert string)
5558 (and move (backward-char 1))))
5560 (defconst org-nonsticky-props
5561 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5563 (defsubst org-rear-nonsticky-at (pos)
5564 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5566 (defun org-activate-plain-links (limit)
5567 "Run through the buffer and add overlays to links."
5568 (catch 'exit
5569 (let (f hl)
5570 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5571 (not (org-in-src-block-p)))
5572 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5573 (setq f (get-text-property (match-beginning 0) 'face))
5574 (setq hl (org-match-string-no-properties 0))
5575 (if (or (eq f 'org-tag)
5576 (and (listp f) (memq 'org-tag f)))
5578 (add-text-properties (match-beginning 0) (match-end 0)
5579 (list 'mouse-face 'highlight
5580 'face 'org-link
5581 'htmlize-link `(:uri ,hl)
5582 'keymap org-mouse-map))
5583 (org-rear-nonsticky-at (match-end 0)))
5584 t))))
5586 (defun org-activate-code (limit)
5587 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5588 (progn
5589 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5590 (remove-text-properties (match-beginning 0) (match-end 0)
5591 '(display t invisible t intangible t))
5592 t)))
5594 (defcustom org-src-fontify-natively nil
5595 "When non-nil, fontify code in code blocks."
5596 :type 'boolean
5597 :version "24.1"
5598 :group 'org-appearance
5599 :group 'org-babel)
5601 (defcustom org-allow-promoting-top-level-subtree nil
5602 "When non-nil, allow promoting a top level subtree.
5603 The leading star of the top level headline will be replaced
5604 by a #."
5605 :type 'boolean
5606 :version "24.1"
5607 :group 'org-appearance)
5609 (defun org-fontify-meta-lines-and-blocks (limit)
5610 (condition-case nil
5611 (org-fontify-meta-lines-and-blocks-1 limit)
5612 (error (message "org-mode fontification error"))))
5614 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5615 "Fontify #+ lines and blocks, in the correct ways."
5616 (let ((case-fold-search t))
5617 (if (re-search-forward
5618 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5619 limit t)
5620 (let ((beg (match-beginning 0))
5621 (block-start (match-end 0))
5622 (block-end nil)
5623 (lang (match-string 7))
5624 (beg1 (line-beginning-position 2))
5625 (dc1 (downcase (match-string 2)))
5626 (dc3 (downcase (match-string 3)))
5627 end end1 quoting block-type ovl)
5628 (cond
5629 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5630 ;; a single line of backend-specific content
5631 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5632 (remove-text-properties (match-beginning 0) (match-end 0)
5633 '(display t invisible t intangible t))
5634 (add-text-properties (match-beginning 1) (match-end 3)
5635 '(font-lock-fontified t face org-meta-line))
5636 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5637 '(font-lock-fontified t face org-block))
5638 ; for backend-specific code
5640 ((and (match-end 4) (equal dc3 "+begin"))
5641 ;; Truly a block
5642 (setq block-type (downcase (match-string 5))
5643 quoting (member block-type org-protecting-blocks))
5644 (when (re-search-forward
5645 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5646 nil t) ;; on purpose, we look further than LIMIT
5647 (setq end (min (point-max) (match-end 0))
5648 end1 (min (point-max) (1- (match-beginning 0))))
5649 (setq block-end (match-beginning 0))
5650 (when quoting
5651 (remove-text-properties beg end
5652 '(display t invisible t intangible t)))
5653 (add-text-properties
5654 beg end
5655 '(font-lock-fontified t font-lock-multiline t))
5656 (add-text-properties beg beg1 '(face org-meta-line))
5657 (add-text-properties end1 (min (point-max) (1+ end))
5658 '(face org-meta-line)) ; for end_src
5659 (cond
5660 ((and lang (not (string= lang "")) org-src-fontify-natively)
5661 (org-src-font-lock-fontify-block lang block-start block-end)
5662 ;; remove old background overlays
5663 (mapc (lambda (ov)
5664 (if (eq (overlay-get ov 'face) 'org-block-background)
5665 (delete-overlay ov)))
5666 (overlays-at (/ (+ beg1 block-end) 2)))
5667 ;; add a background overlay
5668 (setq ovl (make-overlay beg1 block-end))
5669 (overlay-put ovl 'face 'org-block-background)
5670 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5671 (quoting
5672 (add-text-properties beg1 (min (point-max) (1+ end1))
5673 '(face org-block))) ; end of source block
5674 ((not org-fontify-quote-and-verse-blocks))
5675 ((string= block-type "quote")
5676 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5677 ((string= block-type "verse")
5678 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5679 (add-text-properties beg beg1 '(face org-block-begin-line))
5680 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5681 '(face org-block-end-line))
5683 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5684 (add-text-properties
5685 beg (match-end 3)
5686 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5687 '(font-lock-fontified t invisible t)
5688 '(font-lock-fontified t face org-document-info-keyword)))
5689 (add-text-properties
5690 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5691 (if (string-equal dc1 "+title:")
5692 '(font-lock-fontified t face org-document-title)
5693 '(font-lock-fontified t face org-document-info))))
5694 ((or (equal dc1 "+results")
5695 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5696 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5697 "+call:" "+header:" "+headers:" "+name:"))
5698 (and (match-end 4) (equal dc3 "+attr")))
5699 (add-text-properties
5700 beg (match-end 0)
5701 '(font-lock-fontified t face org-meta-line))
5703 ((member dc3 '(" " ""))
5704 (add-text-properties
5705 beg (match-end 0)
5706 '(font-lock-fontified t face font-lock-comment-face)))
5707 ((not (member (char-after beg) '(?\ ?\t)))
5708 ;; just any other in-buffer setting, but not indented
5709 (add-text-properties
5710 beg (match-end 0)
5711 '(font-lock-fontified t face org-meta-line))
5713 (t nil))))))
5715 (defun org-activate-angle-links (limit)
5716 "Run through the buffer and add overlays to links."
5717 (if (and (re-search-forward org-angle-link-re limit t)
5718 (not (org-in-src-block-p)))
5719 (progn
5720 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5721 (add-text-properties (match-beginning 0) (match-end 0)
5722 (list 'mouse-face 'highlight
5723 'keymap org-mouse-map))
5724 (org-rear-nonsticky-at (match-end 0))
5725 t)))
5727 (defun org-activate-footnote-links (limit)
5728 "Run through the buffer and add overlays to footnotes."
5729 (let ((fn (org-footnote-next-reference-or-definition limit)))
5730 (when fn
5731 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5732 (org-remove-flyspell-overlays-in beg end)
5733 (add-text-properties beg end
5734 (list 'mouse-face 'highlight
5735 'keymap org-mouse-map
5736 'help-echo
5737 (if (= (point-at-bol) beg)
5738 "Footnote definition"
5739 "Footnote reference")
5740 'font-lock-fontified t
5741 'font-lock-multiline t
5742 'face 'org-footnote))))))
5744 (defun org-activate-bracket-links (limit)
5745 "Run through the buffer and add overlays to bracketed links."
5746 (if (and (re-search-forward org-bracket-link-regexp limit t)
5747 (not (org-in-src-block-p)))
5748 (let* ((hl (org-match-string-no-properties 1))
5749 (help (concat "LINK: " hl))
5750 ;; FIXME: Above we should remove the escapes. But that
5751 ;; requires another match, protecting match data, a lot
5752 ;; of overhead for font-lock.
5753 (ip (org-maybe-intangible
5754 (list 'invisible 'org-link
5755 'keymap org-mouse-map 'mouse-face 'highlight
5756 'font-lock-multiline t 'help-echo help
5757 'htmlize-link `(:uri ,hl))))
5758 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5759 'font-lock-multiline t 'help-echo help
5760 'htmlize-link `(:uri ,hl))))
5761 ;; We need to remove the invisible property here. Table narrowing
5762 ;; may have made some of this invisible.
5763 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5764 (remove-text-properties (match-beginning 0) (match-end 0)
5765 '(invisible nil))
5766 (if (match-end 3)
5767 (progn
5768 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5769 (org-rear-nonsticky-at (match-beginning 3))
5770 (add-text-properties (match-beginning 3) (match-end 3) vp)
5771 (org-rear-nonsticky-at (match-end 3))
5772 (add-text-properties (match-end 3) (match-end 0) ip)
5773 (org-rear-nonsticky-at (match-end 0)))
5774 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5775 (org-rear-nonsticky-at (match-beginning 1))
5776 (add-text-properties (match-beginning 1) (match-end 1) vp)
5777 (org-rear-nonsticky-at (match-end 1))
5778 (add-text-properties (match-end 1) (match-end 0) ip)
5779 (org-rear-nonsticky-at (match-end 0)))
5780 t)))
5782 (defun org-activate-dates (limit)
5783 "Run through the buffer and add overlays to dates."
5784 (if (re-search-forward org-tsr-regexp-both limit t)
5785 (progn
5786 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5787 (add-text-properties (match-beginning 0) (match-end 0)
5788 (list 'mouse-face 'highlight
5789 'keymap org-mouse-map))
5790 (org-rear-nonsticky-at (match-end 0))
5791 (when org-display-custom-times
5792 (if (match-end 3)
5793 (org-display-custom-time (match-beginning 3) (match-end 3)))
5794 (org-display-custom-time (match-beginning 1) (match-end 1)))
5795 t)))
5797 (defvar org-target-link-regexp nil
5798 "Regular expression matching radio targets in plain text.")
5799 (make-variable-buffer-local 'org-target-link-regexp)
5800 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5801 "Regular expression matching a link target.")
5802 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5803 "Regular expression matching a radio target.")
5804 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5805 "Regular expression matching any target.")
5807 (defun org-activate-target-links (limit)
5808 "Run through the buffer and add overlays to target matches."
5809 (when org-target-link-regexp
5810 (let ((case-fold-search t))
5811 (if (re-search-forward org-target-link-regexp 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 'help-echo "Radio target link"
5818 'org-linked-text t))
5819 (org-rear-nonsticky-at (match-end 0))
5820 t)))))
5822 (defun org-update-radio-target-regexp ()
5823 "Find all radio targets in this file and update the regular expression."
5824 (interactive)
5825 (when (memq 'radio org-activate-links)
5826 (setq org-target-link-regexp
5827 (org-make-target-link-regexp (org-all-targets 'radio)))
5828 (org-restart-font-lock)))
5830 (defun org-hide-wide-columns (limit)
5831 (let (s e)
5832 (setq s (text-property-any (point) (or limit (point-max))
5833 'org-cwidth t))
5834 (when s
5835 (setq e (next-single-property-change s 'org-cwidth))
5836 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5837 (goto-char e)
5838 t)))
5840 (defvar org-match-substring-regexp)
5841 (defvar org-match-substring-with-braces-regexp)
5843 (defun org-restart-font-lock ()
5844 "Restart `font-lock-mode', to force refontification."
5845 (when (and (boundp 'font-lock-mode) font-lock-mode)
5846 (font-lock-mode -1)
5847 (font-lock-mode 1)))
5849 (defun org-all-targets (&optional radio)
5850 "Return a list of all targets in this file.
5851 When optional argument RADIO is non-nil, only find radio
5852 targets."
5853 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5854 (save-excursion
5855 (goto-char (point-min))
5856 (while (re-search-forward re nil t)
5857 ;; Make sure point is really within the object.
5858 (backward-char)
5859 (let ((obj (org-element-context)))
5860 (when (memq (org-element-type obj) '(radio-target target))
5861 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5862 rtn)))
5864 (defun org-make-target-link-regexp (targets)
5865 "Make regular expression matching all strings in TARGETS.
5866 The regular expression finds the targets also if there is a line break
5867 between words."
5868 (and targets
5869 (concat
5870 "\\<\\("
5871 (mapconcat
5872 (lambda (x)
5873 (setq x (regexp-quote x))
5874 (while (string-match " +" x)
5875 (setq x (replace-match "\\s-+" t t x)))
5877 targets
5878 "\\|")
5879 "\\)\\>")))
5881 (defun org-activate-tags (limit)
5882 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5883 (progn
5884 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5885 (add-text-properties (match-beginning 1) (match-end 1)
5886 (list 'mouse-face 'highlight
5887 'keymap org-mouse-map))
5888 (org-rear-nonsticky-at (match-end 1))
5889 t)))
5891 (defun org-outline-level ()
5892 "Compute the outline level of the heading at point.
5893 If this is called at a normal headline, the level is the number of stars.
5894 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5895 (save-excursion
5896 (if (not (condition-case nil
5897 (org-back-to-heading t)
5898 (error nil)))
5900 (looking-at org-outline-regexp)
5901 (1- (- (match-end 0) (match-beginning 0))))))
5903 (defvar org-font-lock-keywords nil)
5905 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5906 "Regular expression matching a property line.")
5908 (defvar org-font-lock-hook nil
5909 "Functions to be called for special font lock stuff.")
5911 (defvar org-font-lock-set-keywords-hook nil
5912 "Functions that can manipulate `org-font-lock-extra-keywords'.
5913 This is called after `org-font-lock-extra-keywords' is defined, but before
5914 it is installed to be used by font lock. This can be useful if something
5915 needs to be inserted at a specific position in the font-lock sequence.")
5917 (defun org-font-lock-hook (limit)
5918 "Run `org-font-lock-hook' within LIMIT."
5919 (run-hook-with-args 'org-font-lock-hook limit))
5921 (defun org-set-font-lock-defaults ()
5922 "Set font lock defaults for the current buffer."
5923 (let* ((em org-fontify-emphasized-text)
5924 (lk org-activate-links)
5925 (org-font-lock-extra-keywords
5926 (list
5927 ;; Call the hook
5928 '(org-font-lock-hook)
5929 ;; Headlines
5930 `(,(if org-fontify-whole-heading-line
5931 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5932 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5933 (1 (org-get-level-face 1))
5934 (2 (org-get-level-face 2))
5935 (3 (org-get-level-face 3)))
5936 ;; Table lines
5937 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5938 (1 'org-table t))
5939 ;; Table internals
5940 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5941 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5942 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5943 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5944 ;; Drawers
5945 (list org-drawer-regexp '(0 'org-special-keyword t))
5946 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5947 ;; Properties
5948 (list org-property-re
5949 '(1 'org-special-keyword t)
5950 '(3 'org-property-value t))
5951 ;; Links
5952 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5953 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5954 (if (memq 'plain lk) '(org-activate-plain-links))
5955 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5956 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5957 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5958 (if (memq 'footnote lk) '(org-activate-footnote-links))
5959 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5960 '(org-hide-wide-columns (0 nil append))
5961 ;; TODO keyword
5962 (list (format org-heading-keyword-regexp-format
5963 org-todo-regexp)
5964 '(2 (org-get-todo-face 2) t))
5965 ;; DONE
5966 (if org-fontify-done-headline
5967 (list (format org-heading-keyword-regexp-format
5968 (concat
5969 "\\(?:"
5970 (mapconcat 'regexp-quote org-done-keywords "\\|")
5971 "\\)"))
5972 '(2 'org-headline-done t))
5973 nil)
5974 ;; Priorities
5975 '(org-font-lock-add-priority-faces)
5976 ;; Tags
5977 '(org-font-lock-add-tag-faces)
5978 ;; Special keywords
5979 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5980 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5981 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5982 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5983 ;; Emphasis
5984 (if em
5985 (if (featurep 'xemacs)
5986 '(org-do-emphasis-faces (0 nil append))
5987 '(org-do-emphasis-faces)))
5988 ;; Checkboxes
5989 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5990 1 'org-checkbox prepend)
5991 (if (cdr (assq 'checkbox org-list-automatic-rules))
5992 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5993 (0 (org-get-checkbox-statistics-face) t)))
5994 ;; Description list items
5995 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5996 1 'org-list-dt prepend)
5997 ;; ARCHIVEd headings
5998 (list (concat
5999 org-outline-regexp-bol
6000 "\\(.*:" org-archive-tag ":.*\\)")
6001 '(1 'org-archived prepend))
6002 ;; Specials
6003 '(org-fontify-entities)
6004 '(org-raise-scripts)
6005 ;; Code
6006 '(org-activate-code (1 'org-code t))
6007 ;; COMMENT
6008 (list (format org-heading-keyword-regexp-format
6009 (concat "\\("
6010 org-comment-string "\\|" org-quote-string
6011 "\\)"))
6012 '(2 'org-special-keyword t))
6013 ;; Blocks and meta lines
6014 '(org-fontify-meta-lines-and-blocks)
6016 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6017 (run-hooks 'org-font-lock-set-keywords-hook)
6018 ;; Now set the full font-lock-keywords
6019 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6020 (org-set-local 'font-lock-defaults
6021 '(org-font-lock-keywords t nil nil backward-paragraph))
6022 (kill-local-variable 'font-lock-keywords) nil))
6024 (defun org-toggle-pretty-entities ()
6025 "Toggle the composition display of entities as UTF8 characters."
6026 (interactive)
6027 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6028 (org-restart-font-lock)
6029 (if org-pretty-entities
6030 (message "Entities are displayed as UTF8 characters")
6031 (save-restriction
6032 (widen)
6033 (org-decompose-region (point-min) (point-max))
6034 (message "Entities are displayed plain"))))
6036 (defvar org-custom-properties-overlays nil
6037 "List of overlays used for custom properties.")
6038 (make-variable-buffer-local 'org-custom-properties-overlays)
6040 (defun org-toggle-custom-properties-visibility ()
6041 "Display or hide properties in `org-custom-properties'."
6042 (interactive)
6043 (if org-custom-properties-overlays
6044 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6045 (setq org-custom-properties-overlays nil))
6046 (unless (not org-custom-properties)
6047 (save-excursion
6048 (save-restriction
6049 (widen)
6050 (goto-char (point-min))
6051 (while (re-search-forward org-property-re nil t)
6052 (mapc (lambda(p)
6053 (when (equal p (substring (match-string 1) 1 -1))
6054 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6055 (overlay-put o 'invisible t)
6056 (overlay-put o 'org-custom-property t)
6057 (push o org-custom-properties-overlays))))
6058 org-custom-properties)))))))
6060 (defun org-fontify-entities (limit)
6061 "Find an entity to fontify."
6062 (let (ee)
6063 (when org-pretty-entities
6064 (catch 'match
6065 (while (re-search-forward
6066 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6067 limit t)
6068 (if (and (not (org-in-indented-comment-line))
6069 (setq ee (org-entity-get (match-string 1)))
6070 (= (length (nth 6 ee)) 1))
6071 (let*
6072 ((end (if (equal (match-string 2) "{}")
6073 (match-end 2)
6074 (match-end 1))))
6075 (add-text-properties
6076 (match-beginning 0) end
6077 (list 'font-lock-fontified t))
6078 (compose-region (match-beginning 0) end
6079 (nth 6 ee) nil)
6080 (backward-char 1)
6081 (throw 'match t))))
6082 nil))))
6084 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6085 "Fontify string S like in Org-mode."
6086 (with-temp-buffer
6087 (insert s)
6088 (let ((org-odd-levels-only odd-levels))
6089 (org-mode)
6090 (font-lock-fontify-buffer)
6091 (buffer-string))))
6093 (defvar org-m nil)
6094 (defvar org-l nil)
6095 (defvar org-f nil)
6096 (defun org-get-level-face (n)
6097 "Get the right face for match N in font-lock matching of headlines."
6098 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6099 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6100 (if org-cycle-level-faces
6101 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6102 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6103 (cond
6104 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6105 ((eq n 2) org-f)
6106 (t (if org-level-color-stars-only nil org-f))))
6109 (defun org-get-todo-face (kwd)
6110 "Get the right face for a TODO keyword KWD.
6111 If KWD is a number, get the corresponding match group."
6112 (if (numberp kwd) (setq kwd (match-string kwd)))
6113 (or (org-face-from-face-or-color
6114 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6115 (and (member kwd org-done-keywords) 'org-done)
6116 'org-todo))
6118 (defun org-face-from-face-or-color (context inherit face-or-color)
6119 "Create a face list that inherits INHERIT, but sets the foreground color.
6120 When FACE-OR-COLOR is not a string, just return it."
6121 (if (stringp face-or-color)
6122 (list :inherit inherit
6123 (cdr (assoc context org-faces-easy-properties))
6124 face-or-color)
6125 face-or-color))
6127 (defun org-font-lock-add-tag-faces (limit)
6128 "Add the special tag faces."
6129 (when (and org-tag-faces org-tags-special-faces-re)
6130 (while (re-search-forward org-tags-special-faces-re limit t)
6131 (add-text-properties (match-beginning 1) (match-end 1)
6132 (list 'face (org-get-tag-face 1)
6133 'font-lock-fontified t))
6134 (backward-char 1))))
6136 (defun org-font-lock-add-priority-faces (limit)
6137 "Add the special priority faces."
6138 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6139 (when (save-match-data (org-at-heading-p))
6140 (add-text-properties
6141 (match-beginning 0) (match-end 0)
6142 (list 'face (or (org-face-from-face-or-color
6143 'priority 'org-priority
6144 (cdr (assoc (char-after (match-beginning 1))
6145 org-priority-faces)))
6146 'org-priority)
6147 'font-lock-fontified t)))))
6149 (defun org-get-tag-face (kwd)
6150 "Get the right face for a TODO keyword KWD.
6151 If KWD is a number, get the corresponding match group."
6152 (if (numberp kwd) (setq kwd (match-string kwd)))
6153 (or (org-face-from-face-or-color
6154 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6155 'org-tag))
6157 (defun org-unfontify-region (beg end &optional maybe_loudly)
6158 "Remove fontification and activation overlays from links."
6159 (font-lock-default-unfontify-region beg end)
6160 (let* ((buffer-undo-list t)
6161 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6162 (inhibit-modification-hooks t)
6163 deactivate-mark buffer-file-name buffer-file-truename)
6164 (org-decompose-region beg end)
6165 (remove-text-properties beg end
6166 '(mouse-face t keymap t org-linked-text t
6167 invisible t intangible t
6168 org-no-flyspell t org-emphasis t))
6169 (org-remove-font-lock-display-properties beg end)))
6171 (defconst org-script-display '(((raise -0.3) (height 0.7))
6172 ((raise 0.3) (height 0.7))
6173 ((raise -0.5))
6174 ((raise 0.5)))
6175 "Display properties for showing superscripts and subscripts.")
6177 (defun org-remove-font-lock-display-properties (beg end)
6178 "Remove specific display properties that have been added by font lock.
6179 The will remove the raise properties that are used to show superscripts
6180 and subscripts."
6181 (let (next prop)
6182 (while (< beg end)
6183 (setq next (next-single-property-change beg 'display nil end)
6184 prop (get-text-property beg 'display))
6185 (if (member prop org-script-display)
6186 (put-text-property beg next 'display nil))
6187 (setq beg next))))
6189 (defun org-raise-scripts (limit)
6190 "Add raise properties to sub/superscripts."
6191 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6192 (if (re-search-forward
6193 (if (eq org-use-sub-superscripts t)
6194 org-match-substring-regexp
6195 org-match-substring-with-braces-regexp)
6196 limit t)
6197 (let* ((pos (point)) table-p comment-p
6198 (mpos (match-beginning 3))
6199 (emph-p (get-text-property mpos 'org-emphasis))
6200 (link-p (get-text-property mpos 'mouse-face))
6201 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6202 (goto-char (point-at-bol))
6203 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6204 comment-p (org-looking-at-p "[ \t]*#"))
6205 (goto-char pos)
6206 ;; FIXME: Should we go back one character here, for a_b^c
6207 ;; (goto-char (1- pos)) ;????????????????????
6208 (if (or comment-p emph-p link-p keyw-p)
6210 (put-text-property (match-beginning 3) (match-end 0)
6211 'display
6212 (if (equal (char-after (match-beginning 2)) ?^)
6213 (nth (if table-p 3 1) org-script-display)
6214 (nth (if table-p 2 0) org-script-display)))
6215 (add-text-properties (match-beginning 2) (match-end 2)
6216 (list 'invisible t
6217 'org-dwidth t 'org-dwidth-n 1))
6218 (if (and (eq (char-after (match-beginning 3)) ?{)
6219 (eq (char-before (match-end 3)) ?}))
6220 (progn
6221 (add-text-properties
6222 (match-beginning 3) (1+ (match-beginning 3))
6223 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6224 (add-text-properties
6225 (1- (match-end 3)) (match-end 3)
6226 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6227 t)))))
6229 ;;;; Visibility cycling, including org-goto and indirect buffer
6231 ;;; Cycling
6233 (defvar org-cycle-global-status nil)
6234 (make-variable-buffer-local 'org-cycle-global-status)
6235 (defvar org-cycle-subtree-status nil)
6236 (make-variable-buffer-local 'org-cycle-subtree-status)
6238 (defvar org-inlinetask-min-level)
6240 ;;;###autoload
6241 (defun org-cycle (&optional arg)
6242 "TAB-action and visibility cycling for Org-mode.
6244 This is the command invoked in Org-mode by the TAB key. Its main purpose
6245 is outline visibility cycling, but it also invokes other actions
6246 in special contexts.
6248 - When this function is called with a prefix argument, rotate the entire
6249 buffer through 3 states (global cycling)
6250 1. OVERVIEW: Show only top-level headlines.
6251 2. CONTENTS: Show all headlines of all levels, but no body text.
6252 3. SHOW ALL: Show everything.
6253 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6254 determined by the variable `org-startup-folded', and by any VISIBILITY
6255 properties in the buffer.
6256 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6257 including any drawers.
6259 - When inside a table, re-align the table and move to the next field.
6261 - When point is at the beginning of a headline, rotate the subtree started
6262 by this line through 3 different states (local cycling)
6263 1. FOLDED: Only the main headline is shown.
6264 2. CHILDREN: The main headline and the direct children are shown.
6265 From this state, you can move to one of the children
6266 and zoom in further.
6267 3. SUBTREE: Show the entire subtree, including body text.
6268 If there is no subtree, switch directly from CHILDREN to FOLDED.
6270 - When point is at the beginning of an empty headline and the variable
6271 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6272 of the headline by demoting and promoting it to likely levels. This
6273 speeds up creation document structure by pressing TAB once or several
6274 times right after creating a new headline.
6276 - When there is a numeric prefix, go up to a heading with level ARG, do
6277 a `show-subtree' and return to the previous cursor position. If ARG
6278 is negative, go up that many levels.
6280 - When point is not at the beginning of a headline, execute the global
6281 binding for TAB, which is re-indenting the line. See the option
6282 `org-cycle-emulate-tab' for details.
6284 - Special case: if point is at the beginning of the buffer and there is
6285 no headline in line 1, this function will act as if called with prefix arg
6286 (C-u TAB, same as S-TAB) also when called without prefix arg.
6287 But only if also the variable `org-cycle-global-at-bob' is t."
6288 (interactive "P")
6289 (org-load-modules-maybe)
6290 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6291 (and org-cycle-level-after-item/entry-creation
6292 (or (org-cycle-level)
6293 (org-cycle-item-indentation))))
6294 (let* (message-log-max ; Don't populate the *Messages* buffer
6295 (limit-level
6296 (or org-cycle-max-level
6297 (and (boundp 'org-inlinetask-min-level)
6298 org-inlinetask-min-level
6299 (1- org-inlinetask-min-level))))
6300 (nstars (and limit-level
6301 (if org-odd-levels-only
6302 (and limit-level (1- (* limit-level 2)))
6303 limit-level)))
6304 (org-outline-regexp
6305 (if (not (derived-mode-p 'org-mode))
6306 outline-regexp
6307 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6308 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6309 (not (looking-at org-outline-regexp))))
6310 (org-cycle-hook
6311 (if bob-special
6312 (delq 'org-optimize-window-after-visibility-change
6313 (copy-sequence org-cycle-hook))
6314 org-cycle-hook))
6315 (pos (point)))
6317 (if (or bob-special (equal arg '(4)))
6318 ;; special case: use global cycling
6319 (setq arg t))
6321 (cond
6323 ((equal arg '(16))
6324 (setq last-command 'dummy)
6325 (org-set-startup-visibility)
6326 (message "Startup visibility, plus VISIBILITY properties"))
6328 ((equal arg '(64))
6329 (show-all)
6330 (message "Entire buffer visible, including drawers"))
6332 ;; Table: enter it or move to the next field.
6333 ((org-at-table-p 'any)
6334 (if (org-at-table.el-p)
6335 (message "Use C-c ' to edit table.el tables")
6336 (if arg (org-table-edit-field t)
6337 (org-table-justify-field-maybe)
6338 (call-interactively 'org-table-next-field))))
6340 ((run-hook-with-args-until-success
6341 'org-tab-after-check-for-table-hook))
6343 ;; Global cycling: delegate to `org-cycle-internal-global'.
6344 ((eq arg t) (org-cycle-internal-global))
6346 ;; Drawers: delegate to `org-flag-drawer'.
6347 ((and org-drawers org-drawer-regexp
6348 (save-excursion
6349 (beginning-of-line 1)
6350 (looking-at org-drawer-regexp)))
6351 (org-flag-drawer ; toggle block visibility
6352 (not (get-char-property (match-end 0) 'invisible))))
6354 ;; Show-subtree, ARG levels up from here.
6355 ((integerp arg)
6356 (save-excursion
6357 (org-back-to-heading)
6358 (outline-up-heading (if (< arg 0) (- arg)
6359 (- (funcall outline-level) arg)))
6360 (org-show-subtree)))
6362 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6363 ((and (featurep 'org-inlinetask)
6364 (org-inlinetask-at-task-p)
6365 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6366 (org-inlinetask-toggle-visibility))
6368 ((org-try-cdlatex-tab))
6370 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6371 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6372 (save-excursion (beginning-of-line 1)
6373 (looking-at org-outline-regexp)))
6374 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6375 (org-cycle-internal-local))
6377 ;; From there: TAB emulation and template completion.
6378 (buffer-read-only (org-back-to-heading))
6380 ((run-hook-with-args-until-success
6381 'org-tab-after-check-for-cycling-hook))
6383 ((org-try-structure-completion))
6385 ((run-hook-with-args-until-success
6386 'org-tab-before-tab-emulation-hook))
6388 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6389 (or (not (bolp))
6390 (not (looking-at org-outline-regexp))))
6391 (call-interactively (global-key-binding "\t")))
6393 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6394 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6395 (or (and (eq org-cycle-emulate-tab 'white)
6396 (= (match-end 0) (point-at-eol)))
6397 (and (eq org-cycle-emulate-tab 'whitestart)
6398 (>= (match-end 0) pos))))
6400 (eq org-cycle-emulate-tab t))
6401 (call-interactively (global-key-binding "\t")))
6403 (t (save-excursion
6404 (org-back-to-heading)
6405 (org-cycle)))))))
6407 (defun org-cycle-internal-global ()
6408 "Do the global cycling action."
6409 ;; Hack to avoid display of messages for .org attachments in Gnus
6410 (let (message-log-max ; Don't populate the *Messages* buffer
6411 (ga (string-match "\\*fontification" (buffer-name))))
6412 (cond
6413 ((and (eq last-command this-command)
6414 (eq org-cycle-global-status 'overview))
6415 ;; We just created the overview - now do table of contents
6416 ;; This can be slow in very large buffers, so indicate action
6417 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6418 (unless ga (message "CONTENTS..."))
6419 (org-content)
6420 (unless ga (message "CONTENTS...done"))
6421 (setq org-cycle-global-status 'contents)
6422 (run-hook-with-args 'org-cycle-hook 'contents))
6424 ((and (eq last-command this-command)
6425 (eq org-cycle-global-status 'contents))
6426 ;; We just showed the table of contents - now show everything
6427 (run-hook-with-args 'org-pre-cycle-hook 'all)
6428 (show-all)
6429 (unless ga (message "SHOW ALL"))
6430 (setq org-cycle-global-status 'all)
6431 (run-hook-with-args 'org-cycle-hook 'all))
6434 ;; Default action: go to overview
6435 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6436 (org-overview)
6437 (unless ga (message "OVERVIEW"))
6438 (setq org-cycle-global-status 'overview)
6439 (run-hook-with-args 'org-cycle-hook 'overview)))))
6441 (defun org-cycle-internal-local ()
6442 "Do the local cycling action."
6443 (let (message-log-max ; Don't populate the *Messages* buffer
6444 (goal-column 0) eoh eol eos has-children children-skipped struct)
6445 ;; First, determine end of headline (EOH), end of subtree or item
6446 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6447 (save-excursion
6448 (if (org-at-item-p)
6449 (progn
6450 (beginning-of-line)
6451 (setq struct (org-list-struct))
6452 (setq eoh (point-at-eol))
6453 (setq eos (org-list-get-item-end-before-blank (point) struct))
6454 (setq has-children (org-list-has-child-p (point) struct)))
6455 (org-back-to-heading)
6456 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6457 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6458 (setq has-children
6459 (or (save-excursion
6460 (let ((level (funcall outline-level)))
6461 (outline-next-heading)
6462 (and (org-at-heading-p t)
6463 (> (funcall outline-level) level))))
6464 (save-excursion
6465 (org-list-search-forward (org-item-beginning-re) eos t)))))
6466 ;; Determine end invisible part of buffer (EOL)
6467 (beginning-of-line 2)
6468 ;; XEmacs doesn't have `next-single-char-property-change'
6469 (if (featurep 'xemacs)
6470 (while (and (not (eobp)) ;; this is like `next-line'
6471 (get-char-property (1- (point)) 'invisible))
6472 (beginning-of-line 2))
6473 (while (and (not (eobp)) ;; this is like `next-line'
6474 (get-char-property (1- (point)) 'invisible))
6475 (goto-char (next-single-char-property-change (point) 'invisible))
6476 (and (eolp) (beginning-of-line 2))))
6477 (setq eol (point)))
6478 ;; Find out what to do next and set `this-command'
6479 (cond
6480 ((= eos eoh)
6481 ;; Nothing is hidden behind this heading
6482 (unless (org-before-first-heading-p)
6483 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6484 (message "EMPTY ENTRY")
6485 (setq org-cycle-subtree-status nil)
6486 (save-excursion
6487 (goto-char eos)
6488 (outline-next-heading)
6489 (if (outline-invisible-p) (org-flag-heading nil))))
6490 ((and (or (>= eol eos)
6491 (not (string-match "\\S-" (buffer-substring eol eos))))
6492 (or has-children
6493 (not (setq children-skipped
6494 org-cycle-skip-children-state-if-no-children))))
6495 ;; Entire subtree is hidden in one line: children view
6496 (unless (org-before-first-heading-p)
6497 (run-hook-with-args 'org-pre-cycle-hook 'children))
6498 (if (org-at-item-p)
6499 (org-list-set-item-visibility (point-at-bol) struct 'children)
6500 (org-show-entry)
6501 (org-with-limited-levels (show-children))
6502 ;; FIXME: This slows down the func way too much.
6503 ;; How keep drawers hidden in subtree anyway?
6504 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6505 ;; (org-cycle-hide-drawers 'subtree))
6507 ;; Fold every list in subtree to top-level items.
6508 (when (eq org-cycle-include-plain-lists 'integrate)
6509 (save-excursion
6510 (org-back-to-heading)
6511 (while (org-list-search-forward (org-item-beginning-re) eos t)
6512 (beginning-of-line 1)
6513 (let* ((struct (org-list-struct))
6514 (prevs (org-list-prevs-alist struct))
6515 (end (org-list-get-bottom-point struct)))
6516 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6517 (org-list-get-all-items (point) struct prevs))
6518 (goto-char end))))))
6519 (message "CHILDREN")
6520 (save-excursion
6521 (goto-char eos)
6522 (outline-next-heading)
6523 (if (outline-invisible-p) (org-flag-heading nil)))
6524 (setq org-cycle-subtree-status 'children)
6525 (unless (org-before-first-heading-p)
6526 (run-hook-with-args 'org-cycle-hook 'children)))
6527 ((or children-skipped
6528 (and (eq last-command this-command)
6529 (eq org-cycle-subtree-status 'children)))
6530 ;; We just showed the children, or no children are there,
6531 ;; now show everything.
6532 (unless (org-before-first-heading-p)
6533 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6534 (outline-flag-region eoh eos nil)
6535 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6536 (setq org-cycle-subtree-status 'subtree)
6537 (unless (org-before-first-heading-p)
6538 (run-hook-with-args 'org-cycle-hook 'subtree)))
6540 ;; Default action: hide the subtree.
6541 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6542 (outline-flag-region eoh eos t)
6543 (message "FOLDED")
6544 (setq org-cycle-subtree-status 'folded)
6545 (unless (org-before-first-heading-p)
6546 (run-hook-with-args 'org-cycle-hook 'folded))))))
6548 ;;;###autoload
6549 (defun org-global-cycle (&optional arg)
6550 "Cycle the global visibility. For details see `org-cycle'.
6551 With \\[universal-argument] prefix arg, switch to startup visibility.
6552 With a numeric prefix, show all headlines up to that level."
6553 (interactive "P")
6554 (let ((org-cycle-include-plain-lists
6555 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6556 (cond
6557 ((integerp arg)
6558 (show-all)
6559 (hide-sublevels arg)
6560 (setq org-cycle-global-status 'contents))
6561 ((equal arg '(4))
6562 (org-set-startup-visibility)
6563 (message "Startup visibility, plus VISIBILITY properties."))
6565 (org-cycle '(4))))))
6567 (defun org-set-startup-visibility ()
6568 "Set the visibility required by startup options and properties."
6569 (cond
6570 ((eq org-startup-folded t)
6571 (org-cycle '(4)))
6572 ((eq org-startup-folded 'content)
6573 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6574 (org-cycle '(4)) (org-cycle '(4)))))
6575 (unless (eq org-startup-folded 'showeverything)
6576 (if org-hide-block-startup (org-hide-block-all))
6577 (org-set-visibility-according-to-property 'no-cleanup)
6578 (org-cycle-hide-archived-subtrees 'all)
6579 (org-cycle-hide-drawers 'all)
6580 (org-cycle-show-empty-lines t)))
6582 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6583 "Switch subtree visibilities according to :VISIBILITY: property."
6584 (interactive)
6585 (let (org-show-entry-below state)
6586 (save-excursion
6587 (goto-char (point-min))
6588 (while (re-search-forward
6589 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6590 nil t)
6591 (setq state (match-string 1))
6592 (save-excursion
6593 (org-back-to-heading t)
6594 (hide-subtree)
6595 (org-reveal)
6596 (cond
6597 ((equal state '("fold" "folded"))
6598 (hide-subtree))
6599 ((equal state "children")
6600 (org-show-hidden-entry)
6601 (show-children))
6602 ((equal state "content")
6603 (save-excursion
6604 (save-restriction
6605 (org-narrow-to-subtree)
6606 (org-content))))
6607 ((member state '("all" "showall"))
6608 (show-subtree)))))
6609 (unless no-cleanup
6610 (org-cycle-hide-archived-subtrees 'all)
6611 (org-cycle-hide-drawers 'all)
6612 (org-cycle-show-empty-lines 'all)))))
6614 ;; This function uses outline-regexp instead of the more fundamental
6615 ;; org-outline-regexp so that org-cycle-global works outside of Org
6616 ;; buffers, where outline-regexp is needed.
6617 (defun org-overview ()
6618 "Switch to overview mode, showing only top-level headlines.
6619 Really, this shows all headlines with level equal or greater than the level
6620 of the first headline in the buffer. This is important, because if the
6621 first headline is not level one, then (hide-sublevels 1) gives confusing
6622 results."
6623 (interactive)
6624 (let ((level (save-excursion
6625 (goto-char (point-min))
6626 (if (re-search-forward (concat "^" outline-regexp) nil t)
6627 (progn
6628 (goto-char (match-beginning 0))
6629 (funcall outline-level))))))
6630 (and level (hide-sublevels level))))
6632 (defun org-content (&optional arg)
6633 "Show all headlines in the buffer, like a table of contents.
6634 With numerical argument N, show content up to level N."
6635 (interactive "P")
6636 (save-excursion
6637 ;; Visit all headings and show their offspring
6638 (and (integerp arg) (org-overview))
6639 (goto-char (point-max))
6640 (catch 'exit
6641 (while (and (progn (condition-case nil
6642 (outline-previous-visible-heading 1)
6643 (error (goto-char (point-min))))
6645 (looking-at org-outline-regexp))
6646 (if (integerp arg)
6647 (show-children (1- arg))
6648 (show-branches))
6649 (if (bobp) (throw 'exit nil))))))
6652 (defun org-optimize-window-after-visibility-change (state)
6653 "Adjust the window after a change in outline visibility.
6654 This function is the default value of the hook `org-cycle-hook'."
6655 (when (get-buffer-window (current-buffer))
6656 (cond
6657 ((eq state 'content) nil)
6658 ((eq state 'all) nil)
6659 ((eq state 'folded) nil)
6660 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6661 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6663 (defun org-remove-empty-overlays-at (pos)
6664 "Remove outline overlays that do not contain non-white stuff."
6665 (mapc
6666 (lambda (o)
6667 (and (eq 'outline (overlay-get o 'invisible))
6668 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6669 (overlay-end o))))
6670 (delete-overlay o)))
6671 (overlays-at pos)))
6673 (defun org-clean-visibility-after-subtree-move ()
6674 "Fix visibility issues after moving a subtree."
6675 ;; First, find a reasonable region to look at:
6676 ;; Start two siblings above, end three below
6677 (let* ((beg (save-excursion
6678 (and (org-get-last-sibling)
6679 (org-get-last-sibling))
6680 (point)))
6681 (end (save-excursion
6682 (and (org-get-next-sibling)
6683 (org-get-next-sibling)
6684 (org-get-next-sibling))
6685 (if (org-at-heading-p)
6686 (point-at-eol)
6687 (point))))
6688 (level (looking-at "\\*+"))
6689 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6690 (save-excursion
6691 (save-restriction
6692 (narrow-to-region beg end)
6693 (when re
6694 ;; Properly fold already folded siblings
6695 (goto-char (point-min))
6696 (while (re-search-forward re nil t)
6697 (if (and (not (outline-invisible-p))
6698 (save-excursion
6699 (goto-char (point-at-eol)) (outline-invisible-p)))
6700 (hide-entry))))
6701 (org-cycle-show-empty-lines 'overview)
6702 (org-cycle-hide-drawers 'overview)))))
6704 (defun org-cycle-show-empty-lines (state)
6705 "Show empty lines above all visible headlines.
6706 The region to be covered depends on STATE when called through
6707 `org-cycle-hook'. Lisp program can use t for STATE to get the
6708 entire buffer covered. Note that an empty line is only shown if there
6709 are at least `org-cycle-separator-lines' empty lines before the headline."
6710 (when (not (= org-cycle-separator-lines 0))
6711 (save-excursion
6712 (let* ((n (abs org-cycle-separator-lines))
6713 (re (cond
6714 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6715 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6716 (t (let ((ns (number-to-string (- n 2))))
6717 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6718 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6719 beg end b e)
6720 (cond
6721 ((memq state '(overview contents t))
6722 (setq beg (point-min) end (point-max)))
6723 ((memq state '(children folded))
6724 (setq beg (point) end (progn (org-end-of-subtree t t)
6725 (beginning-of-line 2)
6726 (point)))))
6727 (when beg
6728 (goto-char beg)
6729 (while (re-search-forward re end t)
6730 (unless (get-char-property (match-end 1) 'invisible)
6731 (setq e (match-end 1))
6732 (if (< org-cycle-separator-lines 0)
6733 (setq b (save-excursion
6734 (goto-char (match-beginning 0))
6735 (org-back-over-empty-lines)
6736 (if (save-excursion
6737 (goto-char (max (point-min) (1- (point))))
6738 (org-at-heading-p))
6739 (1- (point))
6740 (point))))
6741 (setq b (match-beginning 1)))
6742 (outline-flag-region b e nil)))))))
6743 ;; Never hide empty lines at the end of the file.
6744 (save-excursion
6745 (goto-char (point-max))
6746 (outline-previous-heading)
6747 (outline-end-of-heading)
6748 (if (and (looking-at "[ \t\n]+")
6749 (= (match-end 0) (point-max)))
6750 (outline-flag-region (point) (match-end 0) nil))))
6752 (defun org-show-empty-lines-in-parent ()
6753 "Move to the parent and re-show empty lines before visible headlines."
6754 (save-excursion
6755 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6756 (org-cycle-show-empty-lines context))))
6758 (defun org-files-list ()
6759 "Return `org-agenda-files' list, plus all open org-mode files.
6760 This is useful for operations that need to scan all of a user's
6761 open and agenda-wise Org files."
6762 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6763 (dolist (buf (buffer-list))
6764 (with-current-buffer buf
6765 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6766 (let ((file (expand-file-name (buffer-file-name))))
6767 (unless (member file files)
6768 (push file files))))))
6769 files))
6771 (defsubst org-entry-beginning-position ()
6772 "Return the beginning position of the current entry."
6773 (save-excursion (outline-back-to-heading t) (point)))
6775 (defsubst org-entry-end-position ()
6776 "Return the end position of the current entry."
6777 (save-excursion (outline-next-heading) (point)))
6779 (defun org-cycle-hide-drawers (state)
6780 "Re-hide all drawers after a visibility state change."
6781 (when (and (derived-mode-p 'org-mode)
6782 (not (memq state '(overview folded contents))))
6783 (save-excursion
6784 (let* ((globalp (memq state '(contents all)))
6785 (beg (if globalp (point-min) (point)))
6786 (end (if globalp (point-max)
6787 (if (eq state 'children)
6788 (save-excursion (outline-next-heading) (point))
6789 (org-end-of-subtree t)))))
6790 (goto-char beg)
6791 (while (re-search-forward org-drawer-regexp end t)
6792 (org-flag-drawer t))))))
6794 (defun org-cycle-hide-inline-tasks (state)
6795 "Re-hide inline task when switching to 'contents visibility state."
6796 (when (and (eq state 'contents)
6797 (boundp 'org-inlinetask-min-level)
6798 org-inlinetask-min-level)
6799 (hide-sublevels (1- org-inlinetask-min-level))))
6801 (defun org-flag-drawer (flag)
6802 "When FLAG is non-nil, hide the drawer we are within.
6803 Otherwise make it visible."
6804 (save-excursion
6805 (beginning-of-line 1)
6806 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6807 (let ((b (match-end 0)))
6808 (if (re-search-forward
6809 "^[ \t]*:END:"
6810 (save-excursion (outline-next-heading) (point)) t)
6811 (outline-flag-region b (point-at-eol) flag)
6812 (error ":END: line missing at position %s" b))))))
6814 (defun org-subtree-end-visible-p ()
6815 "Is the end of the current subtree visible?"
6816 (pos-visible-in-window-p
6817 (save-excursion (org-end-of-subtree t) (point))))
6819 (defun org-first-headline-recenter (&optional N)
6820 "Move cursor to the first headline and recenter the headline.
6821 Optional argument N means put the headline into the Nth line of the window."
6822 (goto-char (point-min))
6823 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6824 (beginning-of-line)
6825 (recenter (prefix-numeric-value N))))
6827 ;;; Saving and restoring visibility
6829 (defun org-outline-overlay-data (&optional use-markers)
6830 "Return a list of the locations of all outline overlays.
6831 These are overlays with the `invisible' property value `outline'.
6832 The return value is a list of cons cells, with start and stop
6833 positions for each overlay.
6834 If USE-MARKERS is set, return the positions as markers."
6835 (let (beg end)
6836 (save-excursion
6837 (save-restriction
6838 (widen)
6839 (delq nil
6840 (mapcar (lambda (o)
6841 (when (eq (overlay-get o 'invisible) 'outline)
6842 (setq beg (overlay-start o)
6843 end (overlay-end o))
6844 (and beg end (> end beg)
6845 (if use-markers
6846 (cons (move-marker (make-marker) beg)
6847 (move-marker (make-marker) end))
6848 (cons beg end)))))
6849 (overlays-in (point-min) (point-max))))))))
6851 (defun org-set-outline-overlay-data (data)
6852 "Create visibility overlays for all positions in DATA.
6853 DATA should have been made by `org-outline-overlay-data'."
6854 (let (o)
6855 (save-excursion
6856 (save-restriction
6857 (widen)
6858 (show-all)
6859 (mapc (lambda (c)
6860 (outline-flag-region (car c) (cdr c) t))
6861 data)))))
6863 ;;; Folding of blocks
6865 (defvar org-hide-block-overlays nil
6866 "Overlays hiding blocks.")
6867 (make-variable-buffer-local 'org-hide-block-overlays)
6869 (defun org-block-map (function &optional start end)
6870 "Call FUNCTION at the head of all source blocks in the current buffer.
6871 Optional arguments START and END can be used to limit the range."
6872 (let ((start (or start (point-min)))
6873 (end (or end (point-max))))
6874 (save-excursion
6875 (goto-char start)
6876 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6877 (save-excursion
6878 (save-match-data
6879 (goto-char (match-beginning 0))
6880 (funcall function)))))))
6882 (defun org-hide-block-toggle-all ()
6883 "Toggle the visibility of all blocks in the current buffer."
6884 (org-block-map #'org-hide-block-toggle))
6886 (defun org-hide-block-all ()
6887 "Fold all blocks in the current buffer."
6888 (interactive)
6889 (org-show-block-all)
6890 (org-block-map #'org-hide-block-toggle-maybe))
6892 (defun org-show-block-all ()
6893 "Unfold all blocks in the current buffer."
6894 (interactive)
6895 (mapc 'delete-overlay org-hide-block-overlays)
6896 (setq org-hide-block-overlays nil))
6898 (defun org-hide-block-toggle-maybe ()
6899 "Toggle visibility of block at point."
6900 (interactive)
6901 (let ((case-fold-search t))
6902 (if (save-excursion
6903 (beginning-of-line 1)
6904 (looking-at org-block-regexp))
6905 (progn (org-hide-block-toggle)
6906 t) ;; to signal that we took action
6907 nil))) ;; to signal that we did not
6909 (defun org-hide-block-toggle (&optional force)
6910 "Toggle the visibility of the current block."
6911 (interactive)
6912 (save-excursion
6913 (beginning-of-line)
6914 (if (re-search-forward org-block-regexp nil t)
6915 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6916 (end (match-end 0)) ;; end of entire body
6918 (if (memq t (mapcar (lambda (overlay)
6919 (eq (overlay-get overlay 'invisible)
6920 'org-hide-block))
6921 (overlays-at start)))
6922 (if (or (not force) (eq force 'off))
6923 (mapc (lambda (ov)
6924 (when (member ov org-hide-block-overlays)
6925 (setq org-hide-block-overlays
6926 (delq ov org-hide-block-overlays)))
6927 (when (eq (overlay-get ov 'invisible)
6928 'org-hide-block)
6929 (delete-overlay ov)))
6930 (overlays-at start)))
6931 (setq ov (make-overlay start end))
6932 (overlay-put ov 'invisible 'org-hide-block)
6933 ;; make the block accessible to isearch
6934 (overlay-put
6935 ov 'isearch-open-invisible
6936 (lambda (ov)
6937 (when (member ov org-hide-block-overlays)
6938 (setq org-hide-block-overlays
6939 (delq ov org-hide-block-overlays)))
6940 (when (eq (overlay-get ov 'invisible)
6941 'org-hide-block)
6942 (delete-overlay ov))))
6943 (push ov org-hide-block-overlays)))
6944 (error "Not looking at a source block"))))
6946 ;; org-tab-after-check-for-cycling-hook
6947 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6948 ;; Remove overlays when changing major mode
6949 (add-hook 'org-mode-hook
6950 (lambda () (org-add-hook 'change-major-mode-hook
6951 'org-show-block-all 'append 'local)))
6953 ;;; Org-goto
6955 (defvar org-goto-window-configuration nil)
6956 (defvar org-goto-marker nil)
6957 (defvar org-goto-map)
6958 (defun org-goto-map ()
6959 "Set the keymap `org-goto'."
6960 (setq org-goto-map
6961 (let ((map (make-sparse-keymap)))
6962 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6963 mouse-drag-region universal-argument org-occur))
6964 cmd)
6965 (while (setq cmd (pop cmds))
6966 (substitute-key-definition cmd cmd map global-map)))
6967 (suppress-keymap map)
6968 (org-defkey map "\C-m" 'org-goto-ret)
6969 (org-defkey map [(return)] 'org-goto-ret)
6970 (org-defkey map [(left)] 'org-goto-left)
6971 (org-defkey map [(right)] 'org-goto-right)
6972 (org-defkey map [(control ?g)] 'org-goto-quit)
6973 (org-defkey map "\C-i" 'org-cycle)
6974 (org-defkey map [(tab)] 'org-cycle)
6975 (org-defkey map [(down)] 'outline-next-visible-heading)
6976 (org-defkey map [(up)] 'outline-previous-visible-heading)
6977 (if org-goto-auto-isearch
6978 (if (fboundp 'define-key-after)
6979 (define-key-after map [t] 'org-goto-local-auto-isearch)
6980 nil)
6981 (org-defkey map "q" 'org-goto-quit)
6982 (org-defkey map "n" 'outline-next-visible-heading)
6983 (org-defkey map "p" 'outline-previous-visible-heading)
6984 (org-defkey map "f" 'outline-forward-same-level)
6985 (org-defkey map "b" 'outline-backward-same-level)
6986 (org-defkey map "u" 'outline-up-heading))
6987 (org-defkey map "/" 'org-occur)
6988 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6989 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6990 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6991 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6992 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6993 map)))
6995 (defconst org-goto-help
6996 "Browse buffer copy, to find location or copy text.%s
6997 RET=jump to location C-g=quit and return to previous location
6998 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7000 (defvar org-goto-start-pos) ; dynamically scoped parameter
7002 ;; FIXME: Docstring does not mention both interfaces
7003 (defun org-goto (&optional alternative-interface)
7004 "Look up a different location in the current file, keeping current visibility.
7006 When you want look-up or go to a different location in a
7007 document, the fastest way is often to fold the entire buffer and
7008 then dive into the tree. This method has the disadvantage, that
7009 the previous location will be folded, which may not be what you
7010 want.
7012 This command works around this by showing a copy of the current
7013 buffer in an indirect buffer, in overview mode. You can dive
7014 into the tree in that copy, use org-occur and incremental search
7015 to find a location. When pressing RET or `Q', the command
7016 returns to the original buffer in which the visibility is still
7017 unchanged. After RET it will also jump to the location selected
7018 in the indirect buffer and expose the headline hierarchy above.
7020 With a prefix argument, use the alternative interface: e.g. if
7021 `org-goto-interface' is 'outline use 'outline-path-completion."
7022 (interactive "P")
7023 (org-goto-map)
7024 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7025 (org-refile-use-outline-path t)
7026 (org-refile-target-verify-function nil)
7027 (interface
7028 (if (not alternative-interface)
7029 org-goto-interface
7030 (if (eq org-goto-interface 'outline)
7031 'outline-path-completion
7032 'outline)))
7033 (org-goto-start-pos (point))
7034 (selected-point
7035 (if (eq interface 'outline)
7036 (car (org-get-location (current-buffer) org-goto-help))
7037 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7038 (org-refile-check-position pa)
7039 (nth 3 pa)))))
7040 (if selected-point
7041 (progn
7042 (org-mark-ring-push org-goto-start-pos)
7043 (goto-char selected-point)
7044 (if (or (outline-invisible-p) (org-invisible-p2))
7045 (org-show-context 'org-goto)))
7046 (message "Quit"))))
7048 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7049 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7050 (defvar org-goto-local-auto-isearch-map) ; defined below
7052 (defun org-get-location (buf help)
7053 "Let the user select a location in the Org-mode buffer BUF.
7054 This function uses a recursive edit. It returns the selected position
7055 or nil."
7056 (org-no-popups
7057 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7058 (isearch-hide-immediately nil)
7059 (isearch-search-fun-function
7060 (lambda () 'org-goto-local-search-headings))
7061 (org-goto-selected-point org-goto-exit-command))
7062 (save-excursion
7063 (save-window-excursion
7064 (delete-other-windows)
7065 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7066 (org-pop-to-buffer-same-window
7067 (condition-case nil
7068 (make-indirect-buffer (current-buffer) "*org-goto*")
7069 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7070 (with-output-to-temp-buffer "*Org Help*"
7071 (princ (format help (if org-goto-auto-isearch
7072 " Just type for auto-isearch."
7073 " n/p/f/b/u to navigate, q to quit."))))
7074 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7075 (setq buffer-read-only nil)
7076 (let ((org-startup-truncated t)
7077 (org-startup-folded nil)
7078 (org-startup-align-all-tables nil))
7079 (org-mode)
7080 (org-overview))
7081 (setq buffer-read-only t)
7082 (if (and (boundp 'org-goto-start-pos)
7083 (integer-or-marker-p org-goto-start-pos))
7084 (let ((org-show-hierarchy-above t)
7085 (org-show-siblings t)
7086 (org-show-following-heading t))
7087 (goto-char org-goto-start-pos)
7088 (and (outline-invisible-p) (org-show-context)))
7089 (goto-char (point-min)))
7090 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7091 (message "Select location and press RET")
7092 (use-local-map org-goto-map)
7093 (recursive-edit)))
7094 (kill-buffer "*org-goto*")
7095 (cons org-goto-selected-point org-goto-exit-command))))
7097 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7098 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7099 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7100 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7102 (defun org-goto-local-search-headings (string bound noerror)
7103 "Search and make sure that any matches are in headlines."
7104 (catch 'return
7105 (while (if isearch-forward
7106 (search-forward string bound noerror)
7107 (search-backward string bound noerror))
7108 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7109 (and (member :headline context)
7110 (not (member :tags context))))
7111 (throw 'return (point))))))
7113 (defun org-goto-local-auto-isearch ()
7114 "Start isearch."
7115 (interactive)
7116 (goto-char (point-min))
7117 (let ((keys (this-command-keys)))
7118 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7119 (isearch-mode t)
7120 (isearch-process-search-char (string-to-char keys)))))
7122 (defun org-goto-ret (&optional arg)
7123 "Finish `org-goto' by going to the new location."
7124 (interactive "P")
7125 (setq org-goto-selected-point (point)
7126 org-goto-exit-command 'return)
7127 (throw 'exit nil))
7129 (defun org-goto-left ()
7130 "Finish `org-goto' by going to the new location."
7131 (interactive)
7132 (if (org-at-heading-p)
7133 (progn
7134 (beginning-of-line 1)
7135 (setq org-goto-selected-point (point)
7136 org-goto-exit-command 'left)
7137 (throw 'exit nil))
7138 (error "Not on a heading")))
7140 (defun org-goto-right ()
7141 "Finish `org-goto' by going to the new location."
7142 (interactive)
7143 (if (org-at-heading-p)
7144 (progn
7145 (setq org-goto-selected-point (point)
7146 org-goto-exit-command 'right)
7147 (throw 'exit nil))
7148 (error "Not on a heading")))
7150 (defun org-goto-quit ()
7151 "Finish `org-goto' without cursor motion."
7152 (interactive)
7153 (setq org-goto-selected-point nil)
7154 (setq org-goto-exit-command 'quit)
7155 (throw 'exit nil))
7157 ;;; Indirect buffer display of subtrees
7159 (defvar org-indirect-dedicated-frame nil
7160 "This is the frame being used for indirect tree display.")
7161 (defvar org-last-indirect-buffer nil)
7163 (defun org-tree-to-indirect-buffer (&optional arg)
7164 "Create indirect buffer and narrow it to current subtree.
7165 With a numerical prefix ARG, go up to this level and then take that tree.
7166 If ARG is negative, go up that many levels.
7168 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7169 indirect buffer previously made with this command, to avoid proliferation of
7170 indirect buffers. However, when you call the command with a \
7171 \\[universal-argument] prefix, or
7172 when `org-indirect-buffer-display' is `new-frame', the last buffer
7173 is kept so that you can work with several indirect buffers at the same time.
7174 If `org-indirect-buffer-display' is `dedicated-frame', the \
7175 \\[universal-argument] prefix also
7176 requests that a new frame be made for the new buffer, so that the dedicated
7177 frame is not changed."
7178 (interactive "P")
7179 (let ((cbuf (current-buffer))
7180 (cwin (selected-window))
7181 (pos (point))
7182 beg end level heading ibuf)
7183 (save-excursion
7184 (org-back-to-heading t)
7185 (when (numberp arg)
7186 (setq level (org-outline-level))
7187 (if (< arg 0) (setq arg (+ level arg)))
7188 (while (> (setq level (org-outline-level)) arg)
7189 (org-up-heading-safe)))
7190 (setq beg (point)
7191 heading (org-get-heading))
7192 (org-end-of-subtree t t)
7193 (if (org-at-heading-p) (backward-char 1))
7194 (setq end (point)))
7195 (if (and (buffer-live-p org-last-indirect-buffer)
7196 (not (eq org-indirect-buffer-display 'new-frame))
7197 (not arg))
7198 (kill-buffer org-last-indirect-buffer))
7199 (setq ibuf (org-get-indirect-buffer cbuf)
7200 org-last-indirect-buffer ibuf)
7201 (cond
7202 ((or (eq org-indirect-buffer-display 'new-frame)
7203 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7204 (select-frame (make-frame))
7205 (delete-other-windows)
7206 (org-pop-to-buffer-same-window ibuf)
7207 (org-set-frame-title heading))
7208 ((eq org-indirect-buffer-display 'dedicated-frame)
7209 (raise-frame
7210 (select-frame (or (and org-indirect-dedicated-frame
7211 (frame-live-p org-indirect-dedicated-frame)
7212 org-indirect-dedicated-frame)
7213 (setq org-indirect-dedicated-frame (make-frame)))))
7214 (delete-other-windows)
7215 (org-pop-to-buffer-same-window ibuf)
7216 (org-set-frame-title (concat "Indirect: " heading)))
7217 ((eq org-indirect-buffer-display 'current-window)
7218 (org-pop-to-buffer-same-window ibuf))
7219 ((eq org-indirect-buffer-display 'other-window)
7220 (pop-to-buffer ibuf))
7221 (t (error "Invalid value")))
7222 (if (featurep 'xemacs)
7223 (save-excursion (org-mode) (turn-on-font-lock)))
7224 (narrow-to-region beg end)
7225 (show-all)
7226 (goto-char pos)
7227 (run-hook-with-args 'org-cycle-hook 'all)
7228 (and (window-live-p cwin) (select-window cwin))))
7230 (defun org-get-indirect-buffer (&optional buffer)
7231 (setq buffer (or buffer (current-buffer)))
7232 (let ((n 1) (base (buffer-name buffer)) bname)
7233 (while (buffer-live-p
7234 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7235 (setq n (1+ n)))
7236 (condition-case nil
7237 (make-indirect-buffer buffer bname 'clone)
7238 (error (make-indirect-buffer buffer bname)))))
7240 (defun org-set-frame-title (title)
7241 "Set the title of the current frame to the string TITLE."
7242 ;; FIXME: how to name a single frame in XEmacs???
7243 (unless (featurep 'xemacs)
7244 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7246 ;;;; Structure editing
7248 ;;; Inserting headlines
7250 (defun org-previous-line-empty-p ()
7251 (save-excursion
7252 (and (not (bobp))
7253 (or (beginning-of-line 0) t)
7254 (save-match-data
7255 (looking-at "[ \t]*$")))))
7257 (defun org-insert-heading (&optional force-heading invisible-ok)
7258 "Insert a new heading or item with same depth at point.
7259 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7260 If point is at the beginning of a headline, insert a sibling before the
7261 current headline. If point is not at the beginning, split the line,
7262 create the new headline with the text in the current line after point
7263 \(but see also the variable `org-M-RET-may-split-line').
7265 With a double prefix arg, force the heading to be inserted at the
7266 end of the parent subtree.
7268 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7269 This is important for non-interactive uses of the command."
7270 (interactive "P")
7271 (if (or (= (buffer-size) 0)
7272 (and (not (save-excursion
7273 (and (ignore-errors (org-back-to-heading invisible-ok))
7274 (org-at-heading-p))))
7275 (or force-heading (not (org-in-item-p)))))
7276 (progn
7277 (insert "\n* ")
7278 (run-hooks 'org-insert-heading-hook))
7279 (when (or force-heading (not (org-insert-item)))
7280 (let* ((empty-line-p nil)
7281 (level nil)
7282 (on-heading (org-at-heading-p))
7283 (head (save-excursion
7284 (condition-case nil
7285 (progn
7286 (org-back-to-heading invisible-ok)
7287 (when (and (not on-heading)
7288 (featurep 'org-inlinetask)
7289 (integerp org-inlinetask-min-level)
7290 (>= (length (match-string 0))
7291 org-inlinetask-min-level))
7292 ;; Find a heading level before the inline task
7293 (while (and (setq level (org-up-heading-safe))
7294 (>= level org-inlinetask-min-level)))
7295 (if (org-at-heading-p)
7296 (org-back-to-heading invisible-ok)
7297 (error "This should not happen")))
7298 (setq empty-line-p (org-previous-line-empty-p))
7299 (match-string 0))
7300 (error "*"))))
7301 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7302 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7303 pos hide-previous previous-pos)
7304 (cond
7305 ((and (org-at-heading-p) (bolp)
7306 (or (bobp)
7307 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7308 ;; insert before the current line
7309 (open-line (if blank 2 1)))
7310 ((and (bolp)
7311 (not org-insert-heading-respect-content)
7312 (or (bobp)
7313 (save-excursion
7314 (backward-char 1) (not (outline-invisible-p)))))
7315 ;; insert right here
7316 nil)
7318 ;; somewhere in the line
7319 (save-excursion
7320 (setq previous-pos (point-at-bol))
7321 (end-of-line)
7322 (setq hide-previous (outline-invisible-p)))
7323 (and org-insert-heading-respect-content (org-show-subtree))
7324 (let ((split
7325 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7326 (save-excursion
7327 (let ((p (point)))
7328 (goto-char (point-at-bol))
7329 (and (looking-at org-complex-heading-regexp)
7330 (match-beginning 4)
7331 (> p (match-beginning 4)))))))
7332 tags pos)
7333 (cond
7334 (org-insert-heading-respect-content
7335 (if (not (equal force-heading '(16)))
7336 (org-end-of-subtree nil t)
7337 (org-up-heading-safe)
7338 (org-end-of-subtree nil t))
7339 (when (featurep 'org-inlinetask)
7340 (while (and (not (eobp))
7341 (looking-at "\\(\\*+\\)[ \t]+")
7342 (>= (length (match-string 1))
7343 org-inlinetask-min-level))
7344 (org-end-of-subtree nil t)))
7345 (or (bolp) (newline))
7346 (or (org-previous-line-empty-p)
7347 (and blank (newline)))
7348 (open-line 1))
7349 ((org-at-heading-p)
7350 (when hide-previous
7351 (show-children)
7352 (org-show-entry))
7353 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7354 (setq tags (and (match-end 2) (match-string 2)))
7355 (and (match-end 1)
7356 (delete-region (match-beginning 1) (match-end 1)))
7357 (setq pos (point-at-bol))
7358 (or split (end-of-line 1))
7359 (delete-horizontal-space)
7360 (if (string-match "\\`\\*+\\'"
7361 (buffer-substring (point-at-bol) (point)))
7362 (insert " "))
7363 (newline (if blank 2 1))
7364 (when tags
7365 (save-excursion
7366 (goto-char pos)
7367 (end-of-line 1)
7368 (insert " " tags)
7369 (org-set-tags nil 'align))))
7371 (or split (end-of-line 1))
7372 (newline (if blank 2 1)))))))
7373 (insert head) (just-one-space)
7374 (setq pos (point))
7375 (end-of-line 1)
7376 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7377 (when (and org-insert-heading-respect-content hide-previous)
7378 (save-excursion
7379 (goto-char previous-pos)
7380 (hide-subtree)))
7381 (run-hooks 'org-insert-heading-hook)))))
7383 (defun org-get-heading (&optional no-tags no-todo)
7384 "Return the heading of the current entry, without the stars.
7385 When NO-TAGS is non-nil, don't include tags.
7386 When NO-TODO is non-nil, don't include TODO keywords."
7387 (save-excursion
7388 (org-back-to-heading t)
7389 (cond
7390 ((and no-tags no-todo)
7391 (looking-at org-complex-heading-regexp)
7392 (match-string 4))
7393 (no-tags
7394 (looking-at (concat org-outline-regexp
7395 "\\(.*?\\)"
7396 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7397 (match-string 1))
7398 (no-todo
7399 (looking-at org-todo-line-regexp)
7400 (match-string 3))
7401 (t (looking-at org-heading-regexp)
7402 (match-string 2)))))
7404 (defun org-heading-components ()
7405 "Return the components of the current heading.
7406 This is a list with the following elements:
7407 - the level as an integer
7408 - the reduced level, different if `org-odd-levels-only' is set.
7409 - the TODO keyword, or nil
7410 - the priority character, like ?A, or nil if no priority is given
7411 - the headline text itself, or the tags string if no headline text
7412 - the tags string, or nil."
7413 (save-excursion
7414 (org-back-to-heading t)
7415 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7416 (list (length (match-string 1))
7417 (org-reduced-level (length (match-string 1)))
7418 (org-match-string-no-properties 2)
7419 (and (match-end 3) (aref (match-string 3) 2))
7420 (org-match-string-no-properties 4)
7421 (org-match-string-no-properties 5)))))
7423 (defun org-get-entry ()
7424 "Get the entry text, after heading, entire subtree."
7425 (save-excursion
7426 (org-back-to-heading t)
7427 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7429 (defun org-insert-heading-after-current ()
7430 "Insert a new heading with same level as current, after current subtree."
7431 (interactive)
7432 (org-back-to-heading)
7433 (org-insert-heading)
7434 (org-move-subtree-down)
7435 (end-of-line 1))
7437 (defun org-insert-heading-respect-content ()
7438 (interactive)
7439 (let ((org-insert-heading-respect-content t))
7440 (org-insert-heading t)))
7442 (defun org-insert-todo-heading-respect-content (&optional force-state)
7443 (interactive "P")
7444 (let ((org-insert-heading-respect-content t))
7445 (org-insert-todo-heading force-state t)))
7447 (defun org-insert-todo-heading (arg &optional force-heading)
7448 "Insert a new heading with the same level and TODO state as current heading.
7449 If the heading has no TODO state, or if the state is DONE, use the first
7450 state (TODO by default). Also one prefix arg, force first state. With two
7451 prefix args, force inserting at the end of the parent subtree."
7452 (interactive "P")
7453 (when (or force-heading (not (org-insert-item 'checkbox)))
7454 (org-insert-heading (or (and (equal arg '(16)) '(16))
7455 force-heading))
7456 (save-excursion
7457 (org-back-to-heading)
7458 (outline-previous-heading)
7459 (looking-at org-todo-line-regexp))
7460 (let*
7461 ((new-mark-x
7462 (if (or arg
7463 (not (match-beginning 2))
7464 (member (match-string 2) org-done-keywords))
7465 (car org-todo-keywords-1)
7466 (match-string 2)))
7467 (new-mark
7469 (run-hook-with-args-until-success
7470 'org-todo-get-default-hook new-mark-x nil)
7471 new-mark-x)))
7472 (beginning-of-line 1)
7473 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7474 (if org-treat-insert-todo-heading-as-state-change
7475 (org-todo new-mark)
7476 (insert new-mark " "))))
7477 (when org-provide-todo-statistics
7478 (org-update-parent-todo-statistics))))
7480 (defun org-insert-subheading (arg)
7481 "Insert a new subheading and demote it.
7482 Works for outline headings and for plain lists alike."
7483 (interactive "P")
7484 (org-insert-heading arg)
7485 (cond
7486 ((org-at-heading-p) (org-do-demote))
7487 ((org-at-item-p) (org-indent-item))))
7489 (defun org-insert-todo-subheading (arg)
7490 "Insert a new subheading with TODO keyword or checkbox and demote it.
7491 Works for outline headings and for plain lists alike."
7492 (interactive "P")
7493 (org-insert-todo-heading arg)
7494 (cond
7495 ((org-at-heading-p) (org-do-demote))
7496 ((org-at-item-p) (org-indent-item))))
7498 ;;; Promotion and Demotion
7500 (defvar org-after-demote-entry-hook nil
7501 "Hook run after an entry has been demoted.
7502 The cursor will be at the beginning of the entry.
7503 When a subtree is being demoted, the hook will be called for each node.")
7505 (defvar org-after-promote-entry-hook nil
7506 "Hook run after an entry has been promoted.
7507 The cursor will be at the beginning of the entry.
7508 When a subtree is being promoted, the hook will be called for each node.")
7510 (defun org-promote-subtree ()
7511 "Promote the entire subtree.
7512 See also `org-promote'."
7513 (interactive)
7514 (save-excursion
7515 (org-with-limited-levels (org-map-tree 'org-promote)))
7516 (org-fix-position-after-promote))
7518 (defun org-demote-subtree ()
7519 "Demote the entire subtree. See `org-demote'.
7520 See also `org-promote'."
7521 (interactive)
7522 (save-excursion
7523 (org-with-limited-levels (org-map-tree 'org-demote)))
7524 (org-fix-position-after-promote))
7527 (defun org-do-promote ()
7528 "Promote the current heading higher up the tree.
7529 If the region is active in `transient-mark-mode', promote all headings
7530 in the region."
7531 (interactive)
7532 (save-excursion
7533 (if (org-region-active-p)
7534 (org-map-region 'org-promote (region-beginning) (region-end))
7535 (org-promote)))
7536 (org-fix-position-after-promote))
7538 (defun org-do-demote ()
7539 "Demote the current heading lower down the tree.
7540 If the region is active in `transient-mark-mode', demote all headings
7541 in the region."
7542 (interactive)
7543 (save-excursion
7544 (if (org-region-active-p)
7545 (org-map-region 'org-demote (region-beginning) (region-end))
7546 (org-demote)))
7547 (org-fix-position-after-promote))
7549 (defun org-fix-position-after-promote ()
7550 "Make sure that after pro/demotion cursor position is right."
7551 (let ((pos (point)))
7552 (when (save-excursion
7553 (beginning-of-line 1)
7554 (looking-at org-todo-line-regexp)
7555 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7556 (cond ((eobp) (insert " "))
7557 ((eolp) (insert " "))
7558 ((equal (char-after) ?\ ) (forward-char 1))))))
7560 (defun org-current-level ()
7561 "Return the level of the current entry, or nil if before the first headline.
7562 The level is the number of stars at the beginning of the headline."
7563 (save-excursion
7564 (org-with-limited-levels
7565 (if (ignore-errors (org-back-to-heading t))
7566 (funcall outline-level)))))
7568 (defun org-get-previous-line-level ()
7569 "Return the outline depth of the last headline before the current line.
7570 Returns 0 for the first headline in the buffer, and nil if before the
7571 first headline."
7572 (let ((current-level (org-current-level))
7573 (prev-level (when (> (line-number-at-pos) 1)
7574 (save-excursion
7575 (beginning-of-line 0)
7576 (org-current-level)))))
7577 (cond ((null current-level) nil) ; Before first headline
7578 ((null prev-level) 0) ; At first headline
7579 (prev-level))))
7581 (defun org-reduced-level (l)
7582 "Compute the effective level of a heading.
7583 This takes into account the setting of `org-odd-levels-only'."
7584 (cond
7585 ((zerop l) 0)
7586 (org-odd-levels-only (1+ (floor (/ l 2))))
7587 (t l)))
7589 (defun org-level-increment ()
7590 "Return the number of stars that will be added or removed at a
7591 time to headlines when structure editing, based on the value of
7592 `org-odd-levels-only'."
7593 (if org-odd-levels-only 2 1))
7595 (defun org-get-valid-level (level &optional change)
7596 "Rectify a level change under the influence of `org-odd-levels-only'
7597 LEVEL is a current level, CHANGE is by how much the level should be
7598 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7599 even level numbers will become the next higher odd number."
7600 (if org-odd-levels-only
7601 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7602 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7603 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7604 (max 1 (+ level (or change 0)))))
7606 (if (boundp 'define-obsolete-function-alias)
7607 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7608 (define-obsolete-function-alias 'org-get-legal-level
7609 'org-get-valid-level)
7610 (define-obsolete-function-alias 'org-get-legal-level
7611 'org-get-valid-level "23.1")))
7613 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7614 ;; ̀org-with-limited-levels'
7615 (defun org-promote ()
7616 "Promote the current heading higher up the tree.
7617 If the region is active in `transient-mark-mode', promote all headings
7618 in the region."
7619 (org-back-to-heading t)
7620 (let* ((level (save-match-data (funcall outline-level)))
7621 (after-change-functions (remove 'flyspell-after-change-function
7622 after-change-functions))
7623 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7624 (diff (abs (- level (length up-head) -1))))
7625 (cond ((and (= level 1) org-called-with-limited-levels
7626 org-allow-promoting-top-level-subtree)
7627 (replace-match "# " nil t))
7628 ((= level 1)
7629 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7630 (t (replace-match up-head nil t)))
7631 ;; Fixup tag positioning
7632 (unless (= level 1)
7633 (and org-auto-align-tags (org-set-tags nil t))
7634 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7635 (run-hooks 'org-after-promote-entry-hook)))
7637 (defun org-demote ()
7638 "Demote the current heading lower down the tree.
7639 If the region is active in `transient-mark-mode', demote all headings
7640 in the region."
7641 (org-back-to-heading t)
7642 (let* ((level (save-match-data (funcall outline-level)))
7643 (after-change-functions (remove 'flyspell-after-change-function
7644 after-change-functions))
7645 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7646 (diff (abs (- level (length down-head) -1))))
7647 (replace-match down-head nil t)
7648 ;; Fixup tag positioning
7649 (and org-auto-align-tags (org-set-tags nil t))
7650 (if org-adapt-indentation (org-fixup-indentation diff))
7651 (run-hooks 'org-after-demote-entry-hook)))
7653 (defun org-cycle-level ()
7654 "Cycle the level of an empty headline through possible states.
7655 This goes first to child, then to parent, level, then up the hierarchy.
7656 After top level, it switches back to sibling level."
7657 (interactive)
7658 (let ((org-adapt-indentation nil))
7659 (when (org-point-at-end-of-empty-headline)
7660 (setq this-command 'org-cycle-level) ; Only needed for caching
7661 (let ((cur-level (org-current-level))
7662 (prev-level (org-get-previous-line-level)))
7663 (cond
7664 ;; If first headline in file, promote to top-level.
7665 ((= prev-level 0)
7666 (loop repeat (/ (- cur-level 1) (org-level-increment))
7667 do (org-do-promote)))
7668 ;; If same level as prev, demote one.
7669 ((= prev-level cur-level)
7670 (org-do-demote))
7671 ;; If parent is top-level, promote to top level if not already.
7672 ((= prev-level 1)
7673 (loop repeat (/ (- cur-level 1) (org-level-increment))
7674 do (org-do-promote)))
7675 ;; If top-level, return to prev-level.
7676 ((= cur-level 1)
7677 (loop repeat (/ (- prev-level 1) (org-level-increment))
7678 do (org-do-demote)))
7679 ;; If less than prev-level, promote one.
7680 ((< cur-level prev-level)
7681 (org-do-promote))
7682 ;; If deeper than prev-level, promote until higher than
7683 ;; prev-level.
7684 ((> cur-level prev-level)
7685 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7686 do (org-do-promote))))
7687 t))))
7689 (defun org-map-tree (fun)
7690 "Call FUN for every heading underneath the current one."
7691 (org-back-to-heading)
7692 (let ((level (funcall outline-level)))
7693 (save-excursion
7694 (funcall fun)
7695 (while (and (progn
7696 (outline-next-heading)
7697 (> (funcall outline-level) level))
7698 (not (eobp)))
7699 (funcall fun)))))
7701 (defun org-map-region (fun beg end)
7702 "Call FUN for every heading between BEG and END."
7703 (let ((org-ignore-region t))
7704 (save-excursion
7705 (setq end (copy-marker end))
7706 (goto-char beg)
7707 (if (and (re-search-forward org-outline-regexp-bol nil t)
7708 (< (point) end))
7709 (funcall fun))
7710 (while (and (progn
7711 (outline-next-heading)
7712 (< (point) end))
7713 (not (eobp)))
7714 (funcall fun)))))
7716 (defvar org-property-end-re) ; silence byte-compiler
7717 (defun org-fixup-indentation (diff)
7718 "Change the indentation in the current entry by DIFF.
7719 However, if any line in the current entry has no indentation, or if it
7720 would end up with no indentation after the change, nothing at all is done."
7721 (save-excursion
7722 (let ((end (save-excursion (outline-next-heading)
7723 (point-marker)))
7724 (prohibit (if (> diff 0)
7725 "^\\S-"
7726 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7727 col)
7728 (unless (save-excursion (end-of-line 1)
7729 (re-search-forward prohibit end t))
7730 (while (and (< (point) end)
7731 (re-search-forward "^[ \t]+" end t))
7732 (goto-char (match-end 0))
7733 (setq col (current-column))
7734 (if (< diff 0) (replace-match ""))
7735 (org-indent-to-column (+ diff col))))
7736 (move-marker end nil))))
7738 (defun org-convert-to-odd-levels ()
7739 "Convert an org-mode file with all levels allowed to one with odd levels.
7740 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7741 level 5 etc."
7742 (interactive)
7743 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7744 (let ((outline-level 'org-outline-level)
7745 (org-odd-levels-only nil) n)
7746 (save-excursion
7747 (goto-char (point-min))
7748 (while (re-search-forward "^\\*\\*+ " nil t)
7749 (setq n (- (length (match-string 0)) 2))
7750 (while (>= (setq n (1- n)) 0)
7751 (org-demote))
7752 (end-of-line 1))))))
7754 (defun org-convert-to-oddeven-levels ()
7755 "Convert an org-mode file with only odd levels to one with odd/even levels.
7756 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7757 file contains a section with an even level, conversion would
7758 destroy the structure of the file. An error is signaled in this
7759 case."
7760 (interactive)
7761 (goto-char (point-min))
7762 ;; First check if there are no even levels
7763 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7764 (org-show-context t)
7765 (error "Not all levels are odd in this file. Conversion not possible"))
7766 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7767 (let ((outline-regexp org-outline-regexp)
7768 (outline-level 'org-outline-level)
7769 (org-odd-levels-only nil) n)
7770 (save-excursion
7771 (goto-char (point-min))
7772 (while (re-search-forward "^\\*\\*+ " nil t)
7773 (setq n (/ (1- (length (match-string 0))) 2))
7774 (while (>= (setq n (1- n)) 0)
7775 (org-promote))
7776 (end-of-line 1))))))
7778 (defun org-tr-level (n)
7779 "Make N odd if required."
7780 (if org-odd-levels-only (1+ (/ n 2)) n))
7782 ;;; Vertical tree motion, cutting and pasting of subtrees
7784 (defun org-move-subtree-up (&optional arg)
7785 "Move the current subtree up past ARG headlines of the same level."
7786 (interactive "p")
7787 (org-move-subtree-down (- (prefix-numeric-value arg))))
7789 (defun org-move-subtree-down (&optional arg)
7790 "Move the current subtree down past ARG headlines of the same level."
7791 (interactive "p")
7792 (setq arg (prefix-numeric-value arg))
7793 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7794 'org-get-last-sibling))
7795 (ins-point (make-marker))
7796 (cnt (abs arg))
7797 (col (current-column))
7798 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7799 ;; Select the tree
7800 (org-back-to-heading)
7801 (setq beg0 (point))
7802 (save-excursion
7803 (setq ne-beg (org-back-over-empty-lines))
7804 (setq beg (point)))
7805 (save-match-data
7806 (save-excursion (outline-end-of-heading)
7807 (setq folded (outline-invisible-p)))
7808 (outline-end-of-subtree))
7809 (outline-next-heading)
7810 (setq ne-end (org-back-over-empty-lines))
7811 (setq end (point))
7812 (goto-char beg0)
7813 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7814 ;; include less whitespace
7815 (save-excursion
7816 (goto-char beg)
7817 (forward-line (- ne-beg ne-end))
7818 (setq beg (point))))
7819 ;; Find insertion point, with error handling
7820 (while (> cnt 0)
7821 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7822 (progn (goto-char beg0)
7823 (error "Cannot move past superior level or buffer limit")))
7824 (setq cnt (1- cnt)))
7825 (if (> arg 0)
7826 ;; Moving forward - still need to move over subtree
7827 (progn (org-end-of-subtree t t)
7828 (save-excursion
7829 (org-back-over-empty-lines)
7830 (or (bolp) (newline)))))
7831 (setq ne-ins (org-back-over-empty-lines))
7832 (move-marker ins-point (point))
7833 (setq txt (buffer-substring beg end))
7834 (org-save-markers-in-region beg end)
7835 (delete-region beg end)
7836 (org-remove-empty-overlays-at beg)
7837 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7838 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7839 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7840 (let ((bbb (point)))
7841 (insert-before-markers txt)
7842 (org-reinstall-markers-in-region bbb)
7843 (move-marker ins-point bbb))
7844 (or (bolp) (insert "\n"))
7845 (setq ins-end (point))
7846 (goto-char ins-point)
7847 (org-skip-whitespace)
7848 (when (and (< arg 0)
7849 (org-first-sibling-p)
7850 (> ne-ins ne-beg))
7851 ;; Move whitespace back to beginning
7852 (save-excursion
7853 (goto-char ins-end)
7854 (let ((kill-whole-line t))
7855 (kill-line (- ne-ins ne-beg)) (point)))
7856 (insert (make-string (- ne-ins ne-beg) ?\n)))
7857 (move-marker ins-point nil)
7858 (if folded
7859 (hide-subtree)
7860 (org-show-entry)
7861 (show-children)
7862 (org-cycle-hide-drawers 'children))
7863 (org-clean-visibility-after-subtree-move)
7864 ;; move back to the initial column we were at
7865 (move-to-column col)))
7867 (defvar org-subtree-clip ""
7868 "Clipboard for cut and paste of subtrees.
7869 This is actually only a copy of the kill, because we use the normal kill
7870 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7872 (defvar org-subtree-clip-folded nil
7873 "Was the last copied subtree folded?
7874 This is used to fold the tree back after pasting.")
7876 (defun org-cut-subtree (&optional n)
7877 "Cut the current subtree into the clipboard.
7878 With prefix arg N, cut this many sequential subtrees.
7879 This is a short-hand for marking the subtree and then cutting it."
7880 (interactive "p")
7881 (org-copy-subtree n 'cut))
7883 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7884 "Cut the current subtree into the clipboard.
7885 With prefix arg N, cut this many sequential subtrees.
7886 This is a short-hand for marking the subtree and then copying it.
7887 If CUT is non-nil, actually cut the subtree.
7888 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7889 of some markers in the region, even if CUT is non-nil. This is
7890 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7891 (interactive "p")
7892 (let (beg end folded (beg0 (point)))
7893 (if (org-called-interactively-p 'any)
7894 (org-back-to-heading nil) ; take what looks like a subtree
7895 (org-back-to-heading t)) ; take what is really there
7896 (setq beg (point))
7897 (skip-chars-forward " \t\r\n")
7898 (save-match-data
7899 (if nosubtrees
7900 (outline-next-heading)
7901 (save-excursion (outline-end-of-heading)
7902 (setq folded (outline-invisible-p)))
7903 (condition-case nil
7904 (org-forward-heading-same-level (1- n) t)
7905 (error nil))
7906 (org-end-of-subtree t t)))
7907 (setq end (point))
7908 (goto-char beg0)
7909 (when (> end beg)
7910 (setq org-subtree-clip-folded folded)
7911 (when (or cut force-store-markers)
7912 (org-save-markers-in-region beg end))
7913 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7914 (setq org-subtree-clip (current-kill 0))
7915 (message "%s: Subtree(s) with %d characters"
7916 (if cut "Cut" "Copied")
7917 (length org-subtree-clip)))))
7919 (defun org-paste-subtree (&optional level tree for-yank)
7920 "Paste the clipboard as a subtree, with modification of headline level.
7921 The entire subtree is promoted or demoted in order to match a new headline
7922 level.
7924 If the cursor is at the beginning of a headline, the same level as
7925 that headline is used to paste the tree.
7927 If not, the new level is derived from the *visible* headings
7928 before and after the insertion point, and taken to be the inferior headline
7929 level of the two. So if the previous visible heading is level 3 and the
7930 next is level 4 (or vice versa), level 4 will be used for insertion.
7931 This makes sure that the subtree remains an independent subtree and does
7932 not swallow low level entries.
7934 You can also force a different level, either by using a numeric prefix
7935 argument, or by inserting the heading marker by hand. For example, if the
7936 cursor is after \"*****\", then the tree will be shifted to level 5.
7938 If optional TREE is given, use this text instead of the kill ring.
7940 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7941 move back over whitespace before inserting, and move point to the end of
7942 the inserted text when done."
7943 (interactive "P")
7944 (setq tree (or tree (and kill-ring (current-kill 0))))
7945 (unless (org-kill-is-subtree-p tree)
7946 (error "%s"
7947 (substitute-command-keys
7948 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7949 (org-with-limited-levels
7950 (let* ((visp (not (outline-invisible-p)))
7951 (txt tree)
7952 (^re_ "\\(\\*+\\)[ \t]*")
7953 (old-level (if (string-match org-outline-regexp-bol txt)
7954 (- (match-end 0) (match-beginning 0) 1)
7955 -1))
7956 (force-level (cond (level (prefix-numeric-value level))
7957 ((and (looking-at "[ \t]*$")
7958 (string-match
7959 "^\\*+$" (buffer-substring
7960 (point-at-bol) (point))))
7961 (- (match-end 1) (match-beginning 1)))
7962 ((and (bolp)
7963 (looking-at org-outline-regexp))
7964 (- (match-end 0) (point) 1))))
7965 (previous-level (save-excursion
7966 (condition-case nil
7967 (progn
7968 (outline-previous-visible-heading 1)
7969 (if (looking-at ^re_)
7970 (- (match-end 0) (match-beginning 0) 1)
7972 (error 1))))
7973 (next-level (save-excursion
7974 (condition-case nil
7975 (progn
7976 (or (looking-at org-outline-regexp)
7977 (outline-next-visible-heading 1))
7978 (if (looking-at ^re_)
7979 (- (match-end 0) (match-beginning 0) 1)
7981 (error 1))))
7982 (new-level (or force-level (max previous-level next-level)))
7983 (shift (if (or (= old-level -1)
7984 (= new-level -1)
7985 (= old-level new-level))
7987 (- new-level old-level)))
7988 (delta (if (> shift 0) -1 1))
7989 (func (if (> shift 0) 'org-demote 'org-promote))
7990 (org-odd-levels-only nil)
7991 beg end newend)
7992 ;; Remove the forced level indicator
7993 (if force-level
7994 (delete-region (point-at-bol) (point)))
7995 ;; Paste
7996 (beginning-of-line (if (bolp) 1 2))
7997 (setq beg (point))
7998 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7999 (insert-before-markers txt)
8000 (unless (string-match "\n\\'" txt) (insert "\n"))
8001 (setq newend (point))
8002 (org-reinstall-markers-in-region beg)
8003 (setq end (point))
8004 (goto-char beg)
8005 (skip-chars-forward " \t\n\r")
8006 (setq beg (point))
8007 (if (and (outline-invisible-p) visp)
8008 (save-excursion (outline-show-heading)))
8009 ;; Shift if necessary
8010 (unless (= shift 0)
8011 (save-restriction
8012 (narrow-to-region beg end)
8013 (while (not (= shift 0))
8014 (org-map-region func (point-min) (point-max))
8015 (setq shift (+ delta shift)))
8016 (goto-char (point-min))
8017 (setq newend (point-max))))
8018 (when (or (org-called-interactively-p 'interactive) for-yank)
8019 (message "Clipboard pasted as level %d subtree" new-level))
8020 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8021 kill-ring
8022 (eq org-subtree-clip (current-kill 0))
8023 org-subtree-clip-folded)
8024 ;; The tree was folded before it was killed/copied
8025 (hide-subtree))
8026 (and for-yank (goto-char newend)))))
8028 (defun org-kill-is-subtree-p (&optional txt)
8029 "Check if the current kill is an outline subtree, or a set of trees.
8030 Returns nil if kill does not start with a headline, or if the first
8031 headline level is not the largest headline level in the tree.
8032 So this will actually accept several entries of equal levels as well,
8033 which is OK for `org-paste-subtree'.
8034 If optional TXT is given, check this string instead of the current kill."
8035 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8036 (re (org-get-limited-outline-regexp))
8037 (^re (concat "^" re))
8038 (start-level (and kill
8039 (string-match
8040 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8041 kill)
8042 (- (match-end 2) (match-beginning 2) 1)))
8043 (start (1+ (or (match-beginning 2) -1))))
8044 (if (not start-level)
8045 (progn
8046 nil) ;; does not even start with a heading
8047 (catch 'exit
8048 (while (setq start (string-match ^re kill (1+ start)))
8049 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8050 (throw 'exit nil)))
8051 t))))
8053 (defvar org-markers-to-move nil
8054 "Markers that should be moved with a cut-and-paste operation.
8055 Those markers are stored together with their positions relative to
8056 the start of the region.")
8058 (defun org-save-markers-in-region (beg end)
8059 "Check markers in region.
8060 If these markers are between BEG and END, record their position relative
8061 to BEG, so that after moving the block of text, we can put the markers back
8062 into place.
8063 This function gets called just before an entry or tree gets cut from the
8064 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8065 called immediately, to move the markers with the entries."
8066 (setq org-markers-to-move nil)
8067 (when (featurep 'org-clock)
8068 (org-clock-save-markers-for-cut-and-paste beg end))
8069 (when (featurep 'org-agenda)
8070 (org-agenda-save-markers-for-cut-and-paste beg end)))
8072 (defun org-check-and-save-marker (marker beg end)
8073 "Check if MARKER is between BEG and END.
8074 If yes, remember the marker and the distance to BEG."
8075 (when (and (marker-buffer marker)
8076 (equal (marker-buffer marker) (current-buffer)))
8077 (if (and (>= marker beg) (< marker end))
8078 (push (cons marker (- marker beg)) org-markers-to-move))))
8080 (defun org-reinstall-markers-in-region (beg)
8081 "Move all remembered markers to their position relative to BEG."
8082 (mapc (lambda (x)
8083 (move-marker (car x) (+ beg (cdr x))))
8084 org-markers-to-move)
8085 (setq org-markers-to-move nil))
8087 (defun org-narrow-to-subtree ()
8088 "Narrow buffer to the current subtree."
8089 (interactive)
8090 (save-excursion
8091 (save-match-data
8092 (org-with-limited-levels
8093 (narrow-to-region
8094 (progn (org-back-to-heading t) (point))
8095 (progn (org-end-of-subtree t t)
8096 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8097 (point)))))))
8099 (defun org-narrow-to-block ()
8100 "Narrow buffer to the current block."
8101 (interactive)
8102 (let* ((case-fold-search t)
8103 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8104 "^[ \t]*#\\+end_.*")))
8105 (if blockp
8106 (narrow-to-region (car blockp) (cdr blockp))
8107 (error "Not in a block"))))
8109 (eval-when-compile
8110 (defvar org-property-drawer-re))
8112 (defvar org-property-start-re) ;; defined below
8113 (defun org-clone-subtree-with-time-shift (n &optional shift)
8114 "Clone the task (subtree) at point N times.
8115 The clones will be inserted as siblings.
8117 In interactive use, the user will be prompted for the number of
8118 clones to be produced, and for a time SHIFT, which may be a
8119 repeater as used in time stamps, for example `+3d'.
8121 When a valid repeater is given and the entry contains any time
8122 stamps, the clones will become a sequence in time, with time
8123 stamps in the subtree shifted for each clone produced. If SHIFT
8124 is nil or the empty string, time stamps will be left alone. The
8125 ID property of the original subtree is removed.
8127 If the original subtree did contain time stamps with a repeater,
8128 the following will happen:
8129 - the repeater will be removed in each clone
8130 - an additional clone will be produced, with the current, unshifted
8131 date(s) in the entry.
8132 - the original entry will be placed *after* all the clones, with
8133 repeater intact.
8134 - the start days in the repeater in the original entry will be shifted
8135 to past the last clone.
8136 In this way you can spell out a number of instances of a repeating task,
8137 and still retain the repeater to cover future instances of the task."
8138 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8139 (let (beg end template task idprop
8140 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8141 (drawer-re org-drawer-regexp))
8142 (if (not (and (integerp n) (> n 0)))
8143 (error "Invalid number of replications %s" n))
8144 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8145 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8146 shift)))
8147 (error "Invalid shift specification %s" shift))
8148 (when doshift
8149 (setq shift-n (string-to-number (match-string 1 shift))
8150 shift-what (cdr (assoc (match-string 2 shift)
8151 '(("d" . day) ("w" . week)
8152 ("m" . month) ("y" . year))))))
8153 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8154 (setq nmin 1 nmax n)
8155 (org-back-to-heading t)
8156 (setq beg (point))
8157 (setq idprop (org-entry-get nil "ID"))
8158 (org-end-of-subtree t t)
8159 (or (bolp) (insert "\n"))
8160 (setq end (point))
8161 (setq template (buffer-substring beg end))
8162 (when (and doshift
8163 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8164 (delete-region beg end)
8165 (setq end beg)
8166 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8167 (goto-char end)
8168 (loop for n from nmin to nmax do
8169 ;; prepare clone
8170 (with-temp-buffer
8171 (insert template)
8172 (org-mode)
8173 (goto-char (point-min))
8174 (org-show-subtree)
8175 (and idprop (if org-clone-delete-id
8176 (org-entry-delete nil "ID")
8177 (org-id-get-create t)))
8178 (unless (= n 0)
8179 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8180 (kill-whole-line))
8181 (goto-char (point-min))
8182 (while (re-search-forward drawer-re nil t)
8183 (mapc (lambda (d)
8184 (org-remove-empty-drawer-at d (point))) org-drawers)))
8185 (goto-char (point-min))
8186 (when doshift
8187 (while (re-search-forward org-ts-regexp-both nil t)
8188 (org-timestamp-change (* n shift-n) shift-what))
8189 (unless (= n n-no-remove)
8190 (goto-char (point-min))
8191 (while (re-search-forward org-ts-regexp nil t)
8192 (save-excursion
8193 (goto-char (match-beginning 0))
8194 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8195 (delete-region (match-beginning 1) (match-end 1)))))))
8196 (setq task (buffer-string)))
8197 (insert task))
8198 (goto-char beg)))
8200 ;;; Outline Sorting
8202 (defun org-sort (with-case)
8203 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8204 Optional argument WITH-CASE means sort case-sensitively."
8205 (interactive "P")
8206 (cond
8207 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8208 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8210 (org-call-with-arg 'org-sort-entries with-case))))
8212 (defun org-sort-remove-invisible (s)
8213 (remove-text-properties 0 (length s) org-rm-props s)
8214 (while (string-match org-bracket-link-regexp s)
8215 (setq s (replace-match (if (match-end 2)
8216 (match-string 3 s)
8217 (match-string 1 s)) t t s)))
8220 (defvar org-priority-regexp) ; defined later in the file
8222 (defvar org-after-sorting-entries-or-items-hook nil
8223 "Hook that is run after a bunch of entries or items have been sorted.
8224 When children are sorted, the cursor is in the parent line when this
8225 hook gets called. When a region or a plain list is sorted, the cursor
8226 will be in the first entry of the sorted region/list.")
8228 (defun org-sort-entries
8229 (&optional with-case sorting-type getkey-func compare-func property)
8230 "Sort entries on a certain level of an outline tree.
8231 If there is an active region, the entries in the region are sorted.
8232 Else, if the cursor is before the first entry, sort the top-level items.
8233 Else, the children of the entry at point are sorted.
8235 Sorting can be alphabetically, numerically, by date/time as given by
8236 a time stamp, by a property or by priority.
8238 The command prompts for the sorting type unless it has been given to the
8239 function through the SORTING-TYPE argument, which needs to be a character,
8240 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8241 precise meaning of each character:
8243 n Numerically, by converting the beginning of the entry/item to a number.
8244 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8245 o By order of TODO keywords.
8246 t By date/time, either the first active time stamp in the entry, or, if
8247 none exist, by the first inactive one.
8248 s By the scheduled date/time.
8249 d By deadline date/time.
8250 c By creation time, which is assumed to be the first inactive time stamp
8251 at the beginning of a line.
8252 p By priority according to the cookie.
8253 r By the value of a property.
8255 Capital letters will reverse the sort order.
8257 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8258 called with point at the beginning of the record. It must return either
8259 a string or a number that should serve as the sorting key for that record.
8261 Comparing entries ignores case by default. However, with an optional argument
8262 WITH-CASE, the sorting considers case as well."
8263 (interactive "P")
8264 (let ((case-func (if with-case 'identity 'downcase))
8265 (cmstr
8266 ;; The clock marker is lost when using `sort-subr', let's
8267 ;; store the clocking string.
8268 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8269 (save-excursion
8270 (goto-char org-clock-marker)
8271 (looking-back "^.*") (match-string-no-properties 0))))
8272 start beg end stars re re2
8273 txt what tmp)
8274 ;; Find beginning and end of region to sort
8275 (cond
8276 ((org-region-active-p)
8277 ;; we will sort the region
8278 (setq end (region-end)
8279 what "region")
8280 (goto-char (region-beginning))
8281 (if (not (org-at-heading-p)) (outline-next-heading))
8282 (setq start (point)))
8283 ((or (org-at-heading-p)
8284 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8285 ;; we will sort the children of the current headline
8286 (org-back-to-heading)
8287 (setq start (point)
8288 end (progn (org-end-of-subtree t t)
8289 (or (bolp) (insert "\n"))
8290 (org-back-over-empty-lines)
8291 (point))
8292 what "children")
8293 (goto-char start)
8294 (show-subtree)
8295 (outline-next-heading))
8297 ;; we will sort the top-level entries in this file
8298 (goto-char (point-min))
8299 (or (org-at-heading-p) (outline-next-heading))
8300 (setq start (point))
8301 (goto-char (point-max))
8302 (beginning-of-line 1)
8303 (when (looking-at ".*?\\S-")
8304 ;; File ends in a non-white line
8305 (end-of-line 1)
8306 (insert "\n"))
8307 (setq end (point-max))
8308 (setq what "top-level")
8309 (goto-char start)
8310 (show-all)))
8312 (setq beg (point))
8313 (if (>= beg end) (error "Nothing to sort"))
8315 (looking-at "\\(\\*+\\)")
8316 (setq stars (match-string 1)
8317 re (concat "^" (regexp-quote stars) " +")
8318 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8319 txt (buffer-substring beg end))
8320 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8321 (if (and (not (equal stars "*")) (string-match re2 txt))
8322 (error "Region to sort contains a level above the first entry"))
8324 (unless sorting-type
8325 (message
8326 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8327 [t]ime [s]cheduled [d]eadline [c]reated
8328 A/N/P/R/O/F/T/S/D/C means reversed:"
8329 what)
8330 (setq sorting-type (read-char-exclusive))
8332 (unless getkey-func
8333 (and (= (downcase sorting-type) ?f)
8334 (setq getkey-func
8335 (org-icompleting-read "Sort using function: "
8336 obarray 'fboundp t nil nil))
8337 (setq getkey-func (intern getkey-func))))
8339 (and (= (downcase sorting-type) ?r)
8340 (not property)
8341 (setq property
8342 (org-icompleting-read "Property: "
8343 (mapcar 'list (org-buffer-property-keys t))
8344 nil t))))
8346 (message "Sorting entries...")
8348 (save-restriction
8349 (narrow-to-region start end)
8350 (let ((dcst (downcase sorting-type))
8351 (case-fold-search nil)
8352 (now (current-time)))
8353 (sort-subr
8354 (/= dcst sorting-type)
8355 ;; This function moves to the beginning character of the "record" to
8356 ;; be sorted.
8357 (lambda nil
8358 (if (re-search-forward re nil t)
8359 (goto-char (match-beginning 0))
8360 (goto-char (point-max))))
8361 ;; This function moves to the last character of the "record" being
8362 ;; sorted.
8363 (lambda nil
8364 (save-match-data
8365 (condition-case nil
8366 (outline-forward-same-level 1)
8367 (error
8368 (goto-char (point-max))))))
8369 ;; This function returns the value that gets sorted against.
8370 (lambda nil
8371 (cond
8372 ((= dcst ?n)
8373 (if (looking-at org-complex-heading-regexp)
8374 (string-to-number (match-string 4))
8375 nil))
8376 ((= dcst ?a)
8377 (if (looking-at org-complex-heading-regexp)
8378 (funcall case-func (match-string 4))
8379 nil))
8380 ((= dcst ?t)
8381 (let ((end (save-excursion (outline-next-heading) (point))))
8382 (if (or (re-search-forward org-ts-regexp end t)
8383 (re-search-forward org-ts-regexp-both end t))
8384 (org-time-string-to-seconds (match-string 0))
8385 (org-float-time now))))
8386 ((= dcst ?c)
8387 (let ((end (save-excursion (outline-next-heading) (point))))
8388 (if (re-search-forward
8389 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8390 end t)
8391 (org-time-string-to-seconds (match-string 0))
8392 (org-float-time now))))
8393 ((= dcst ?s)
8394 (let ((end (save-excursion (outline-next-heading) (point))))
8395 (if (re-search-forward org-scheduled-time-regexp end t)
8396 (org-time-string-to-seconds (match-string 1))
8397 (org-float-time now))))
8398 ((= dcst ?d)
8399 (let ((end (save-excursion (outline-next-heading) (point))))
8400 (if (re-search-forward org-deadline-time-regexp end t)
8401 (org-time-string-to-seconds (match-string 1))
8402 (org-float-time now))))
8403 ((= dcst ?p)
8404 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8405 (string-to-char (match-string 2))
8406 org-default-priority))
8407 ((= dcst ?r)
8408 (or (org-entry-get nil property) ""))
8409 ((= dcst ?o)
8410 (if (looking-at org-complex-heading-regexp)
8411 (- 9999 (length (member (match-string 2)
8412 org-todo-keywords-1)))))
8413 ((= dcst ?f)
8414 (if getkey-func
8415 (progn
8416 (setq tmp (funcall getkey-func))
8417 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8418 tmp)
8419 (error "Invalid key function `%s'" getkey-func)))
8420 (t (error "Invalid sorting type `%c'" sorting-type))))
8422 (cond
8423 ((= dcst ?a) 'string<)
8424 ((= dcst ?f) compare-func)
8425 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8426 (run-hooks 'org-after-sorting-entries-or-items-hook)
8427 ;; Reset the clock marker if needed
8428 (when cmstr
8429 (save-excursion
8430 (goto-char start)
8431 (search-forward cmstr nil t)
8432 (move-marker org-clock-marker (point))))
8433 (message "Sorting entries...done")))
8435 (defun org-do-sort (table what &optional with-case sorting-type)
8436 "Sort TABLE of WHAT according to SORTING-TYPE.
8437 The user will be prompted for the SORTING-TYPE if the call to this
8438 function does not specify it. WHAT is only for the prompt, to indicate
8439 what is being sorted. The sorting key will be extracted from
8440 the car of the elements of the table.
8441 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8442 (unless sorting-type
8443 (message
8444 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8445 what)
8446 (setq sorting-type (read-char-exclusive)))
8447 (let ((dcst (downcase sorting-type))
8448 extractfun comparefun)
8449 ;; Define the appropriate functions
8450 (cond
8451 ((= dcst ?n)
8452 (setq extractfun 'string-to-number
8453 comparefun (if (= dcst sorting-type) '< '>)))
8454 ((= dcst ?a)
8455 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8456 (lambda(x) (downcase (org-sort-remove-invisible x))))
8457 comparefun (if (= dcst sorting-type)
8458 'string<
8459 (lambda (a b) (and (not (string< a b))
8460 (not (string= a b)))))))
8461 ((= dcst ?t)
8462 (setq extractfun
8463 (lambda (x)
8464 (if (or (string-match org-ts-regexp x)
8465 (string-match org-ts-regexp-both x))
8466 (org-float-time
8467 (org-time-string-to-time (match-string 0 x)))
8469 comparefun (if (= dcst sorting-type) '< '>)))
8470 (t (error "Invalid sorting type `%c'" sorting-type)))
8472 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8473 table)
8474 (lambda (a b) (funcall comparefun (car a) (car b))))))
8477 ;;; The orgstruct minor mode
8479 ;; Define a minor mode which can be used in other modes in order to
8480 ;; integrate the org-mode structure editing commands.
8482 ;; This is really a hack, because the org-mode structure commands use
8483 ;; keys which normally belong to the major mode. Here is how it
8484 ;; works: The minor mode defines all the keys necessary to operate the
8485 ;; structure commands, but wraps the commands into a function which
8486 ;; tests if the cursor is currently at a headline or a plain list
8487 ;; item. If that is the case, the structure command is used,
8488 ;; temporarily setting many Org-mode variables like regular
8489 ;; expressions for filling etc. However, when any of those keys is
8490 ;; used at a different location, function uses `key-binding' to look
8491 ;; up if the key has an associated command in another currently active
8492 ;; keymap (minor modes, major mode, global), and executes that
8493 ;; command. There might be problems if any of the keys is otherwise
8494 ;; used as a prefix key.
8496 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8497 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8498 ;; addresses this by checking explicitly for both bindings.
8500 (defvar orgstruct-mode-map (make-sparse-keymap)
8501 "Keymap for the minor `orgstruct-mode'.")
8503 (defvar org-local-vars nil
8504 "List of local variables, for use by `orgstruct-mode'.")
8506 ;;;###autoload
8507 (define-minor-mode orgstruct-mode
8508 "Toggle the minor mode `orgstruct-mode'.
8509 This mode is for using Org-mode structure commands in other
8510 modes. The following keys behave as if Org-mode were active, if
8511 the cursor is on a headline, or on a plain list item (both as
8512 defined by Org-mode).
8514 M-up Move entry/item up
8515 M-down Move entry/item down
8516 M-left Promote
8517 M-right Demote
8518 M-S-up Move entry/item up
8519 M-S-down Move entry/item down
8520 M-S-left Promote subtree
8521 M-S-right Demote subtree
8522 M-q Fill paragraph and items like in Org-mode
8523 C-c ^ Sort entries
8524 C-c - Cycle list bullet
8525 TAB Cycle item visibility
8526 M-RET Insert new heading/item
8527 S-M-RET Insert new TODO heading / Checkbox item
8528 C-c C-c Set tags / toggle checkbox"
8529 nil " OrgStruct" nil
8530 (org-load-modules-maybe)
8531 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8533 ;;;###autoload
8534 (defun turn-on-orgstruct ()
8535 "Unconditionally turn on `orgstruct-mode'."
8536 (orgstruct-mode 1))
8538 (defvar org-fb-vars nil)
8539 (make-variable-buffer-local 'org-fb-vars)
8540 (defun orgstruct++-mode (&optional arg)
8541 "Toggle `orgstruct-mode', the enhanced version of it.
8542 In addition to setting orgstruct-mode, this also exports all
8543 indentation and autofilling variables from org-mode into the
8544 buffer. It will also recognize item context in multiline items."
8545 (interactive "P")
8546 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8547 (if (< arg 1)
8548 (progn (orgstruct-mode -1)
8549 (mapc (lambda(v)
8550 (org-set-local (car v)
8551 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8552 org-fb-vars))
8553 (orgstruct-mode 1)
8554 (setq org-fb-vars nil)
8555 (let (var val)
8556 (mapc
8557 (lambda (x)
8558 (when (string-match
8559 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8560 (symbol-name (car x)))
8561 (setq var (car x) val (nth 1 x))
8562 (push (list var `(quote ,(eval var))) org-fb-vars)
8563 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8564 org-local-vars)
8565 (org-set-local 'orgstruct-is-++ t))))
8567 (defvar orgstruct-is-++ nil
8568 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8569 (make-variable-buffer-local 'orgstruct-is-++)
8571 ;;;###autoload
8572 (defun turn-on-orgstruct++ ()
8573 "Unconditionally turn on `orgstruct++-mode'."
8574 (orgstruct++-mode 1))
8576 (defun orgstruct-error ()
8577 "Error when there is no default binding for a structure key."
8578 (interactive)
8579 (error "This key has no function outside structure elements"))
8581 (defun orgstruct-setup ()
8582 "Setup orgstruct keymaps."
8583 (let ((nfunc 0)
8584 (bindings
8585 (list
8586 '([(meta up)] org-metaup)
8587 '([(meta down)] org-metadown)
8588 '([(meta left)] org-metaleft)
8589 '([(meta right)] org-metaright)
8590 '([(meta shift up)] org-shiftmetaup)
8591 '([(meta shift down)] org-shiftmetadown)
8592 '([(meta shift left)] org-shiftmetaleft)
8593 '([(meta shift right)] org-shiftmetaright)
8594 '([?\e (up)] org-metaup)
8595 '([?\e (down)] org-metadown)
8596 '([?\e (left)] org-metaleft)
8597 '([?\e (right)] org-metaright)
8598 '([?\e (shift up)] org-shiftmetaup)
8599 '([?\e (shift down)] org-shiftmetadown)
8600 '([?\e (shift left)] org-shiftmetaleft)
8601 '([?\e (shift right)] org-shiftmetaright)
8602 '([(shift up)] org-shiftup)
8603 '([(shift down)] org-shiftdown)
8604 '([(shift left)] org-shiftleft)
8605 '([(shift right)] org-shiftright)
8606 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8607 '("\M-q" fill-paragraph)
8608 '("\C-c^" org-sort)
8609 '("\C-c-" org-cycle-list-bullet)))
8610 elt key fun cmd)
8611 (while (setq elt (pop bindings))
8612 (setq nfunc (1+ nfunc))
8613 (setq key (org-key (car elt))
8614 fun (nth 1 elt)
8615 cmd (orgstruct-make-binding fun nfunc key))
8616 (org-defkey orgstruct-mode-map key cmd))
8618 ;; Prevent an error for users who forgot to make autoloads
8619 (require 'org-element)
8621 ;; Special treatment needed for TAB and RET
8622 (org-defkey orgstruct-mode-map [(tab)]
8623 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8624 (org-defkey orgstruct-mode-map "\C-i"
8625 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8627 (org-defkey orgstruct-mode-map "\M-\C-m"
8628 (orgstruct-make-binding 'org-insert-heading 105
8629 "\M-\C-m" [(meta return)]))
8630 (org-defkey orgstruct-mode-map [(meta return)]
8631 (orgstruct-make-binding 'org-insert-heading 106
8632 [(meta return)] "\M-\C-m"))
8634 (org-defkey orgstruct-mode-map [(shift meta return)]
8635 (orgstruct-make-binding 'org-insert-todo-heading 107
8636 [(meta return)] "\M-\C-m"))
8638 (org-defkey orgstruct-mode-map "\e\C-m"
8639 (orgstruct-make-binding 'org-insert-heading 108
8640 "\e\C-m" [?\e (return)]))
8641 (org-defkey orgstruct-mode-map [?\e (return)]
8642 (orgstruct-make-binding 'org-insert-heading 109
8643 [?\e (return)] "\e\C-m"))
8644 (org-defkey orgstruct-mode-map [?\e (shift return)]
8645 (orgstruct-make-binding 'org-insert-todo-heading 110
8646 [?\e (return)] "\e\C-m"))
8648 (unless org-local-vars
8649 (setq org-local-vars (org-get-local-variables)))
8653 (defun orgstruct-make-binding (fun n &rest keys)
8654 "Create a function for binding in the structure minor mode.
8655 FUN is the command to call inside a table. N is used to create a unique
8656 command name. KEYS are keys that should be checked in for a command
8657 to execute outside of tables."
8658 (eval
8659 (list 'defun
8660 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8661 '(arg)
8662 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8663 "Outside of structure, run the binding of `"
8664 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8665 "'.")
8666 '(interactive "p")
8667 (list 'if
8668 `(org-context-p 'headline 'item
8669 (and orgstruct-is-++
8670 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8671 'item-body))
8672 (list 'org-run-like-in-org-mode (list 'quote fun))
8673 (list 'let '(orgstruct-mode)
8674 (list 'call-interactively
8675 (append '(or)
8676 (mapcar (lambda (k)
8677 (list 'key-binding k))
8678 keys)
8679 '('orgstruct-error))))))))
8681 (defun org-contextualize-keys (alist contexts)
8682 "Return valid elements in ALIST depending on CONTEXTS.
8684 `org-agenda-custom-commands' or `org-capture-templates' are the
8685 values used for ALIST, and `org-agenda-custom-commands-contexts'
8686 or `org-capture-templates-contexts' are the associated contexts
8687 definitions."
8688 (let ((contexts
8689 ;; normalize contexts
8690 (mapcar
8691 (lambda(c) (cond ((listp (cadr c))
8692 (list (car c) (car c) (cadr c)))
8693 ((string= "" (cadr c))
8694 (list (car c) (car c) (caddr c)))
8695 (t c))) contexts))
8696 (a alist) c r s)
8697 ;; loop over all commands or templates
8698 (while (setq c (pop a))
8699 (let (vrules repl)
8700 (cond
8701 ((not (assoc (car c) contexts))
8702 (push c r))
8703 ((and (assoc (car c) contexts)
8704 (setq vrules (org-contextualize-validate-key
8705 (car c) contexts)))
8706 (mapc (lambda (vr)
8707 (when (not (equal (car vr) (cadr vr)))
8708 (setq repl vr))) vrules)
8709 (if (not repl) (push c r)
8710 (push (cadr repl) s)
8711 (push
8712 (cons (car c)
8713 (cdr (or (assoc (cadr repl) alist)
8714 (error "Undefined key `%s' as contextual replacement for `%s'"
8715 (cadr repl) (car c)))))
8716 r))))))
8717 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8718 (delq
8720 (delete-dups
8721 (mapcar (lambda (x)
8722 (let ((tpl (car x)))
8723 (when (not (delq
8725 (mapcar (lambda(y)
8726 (equal y tpl)) s))) x)))
8727 (reverse r))))))
8729 (defun org-contextualize-validate-key (key contexts)
8730 "Check CONTEXTS for agenda or capture KEY."
8731 (let (r rr res)
8732 (while (setq r (pop contexts))
8733 (mapc
8734 (lambda (rr)
8735 (when
8736 (and (equal key (car r))
8737 (if (functionp rr) (funcall rr)
8738 (or (and (eq (car rr) 'in-file)
8739 (buffer-file-name)
8740 (string-match (cdr rr) (buffer-file-name)))
8741 (and (eq (car rr) 'in-mode)
8742 (string-match (cdr rr) (symbol-name major-mode)))
8743 (and (eq (car rr) 'in-buffer)
8744 (string-match (cdr rr) (buffer-name)))
8745 (when (and (eq (car rr) 'not-in-file)
8746 (buffer-file-name))
8747 (not (string-match (cdr rr) (buffer-file-name))))
8748 (when (eq (car rr) 'not-in-mode)
8749 (not (string-match (cdr rr) (symbol-name major-mode))))
8750 (when (eq (car rr) 'not-in-buffer)
8751 (not (string-match (cdr rr) (buffer-name)))))))
8752 (push r res)))
8753 (car (last r))))
8754 (delete-dups (delq nil res))))
8756 (defun org-context-p (&rest contexts)
8757 "Check if local context is any of CONTEXTS.
8758 Possible values in the list of contexts are `table', `headline', and `item'."
8759 (let ((pos (point)))
8760 (goto-char (point-at-bol))
8761 (prog1 (or (and (memq 'table contexts)
8762 (looking-at "[ \t]*|"))
8763 (and (memq 'headline contexts)
8764 (looking-at org-outline-regexp))
8765 (and (memq 'item contexts)
8766 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8767 (and (memq 'item-body contexts)
8768 (org-in-item-p)))
8769 (goto-char pos))))
8771 (defun org-get-local-variables ()
8772 "Return a list of all local variables in an Org mode buffer."
8773 (let (varlist)
8774 (with-current-buffer (get-buffer-create "*Org tmp*")
8775 (erase-buffer)
8776 (org-mode)
8777 (setq varlist (buffer-local-variables)))
8778 (kill-buffer "*Org tmp*")
8779 (delq nil
8780 (mapcar
8781 (lambda (x)
8782 (setq x
8783 (if (symbolp x)
8784 (list x)
8785 (list (car x) (list 'quote (cdr x)))))
8786 (if (string-match
8787 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8788 (symbol-name (car x)))
8789 x nil))
8790 varlist))))
8792 (defun org-clone-local-variables (from-buffer &optional regexp)
8793 "Clone local variables from FROM-BUFFER.
8794 Optional argument REGEXP selects variables to clone."
8795 (mapc
8796 (lambda (pair)
8797 (and (symbolp (car pair))
8798 (or (null regexp)
8799 (string-match regexp (symbol-name (car pair))))
8800 (set (make-local-variable (car pair))
8801 (cdr pair))))
8802 (buffer-local-variables from-buffer)))
8804 ;;;###autoload
8805 (defun org-run-like-in-org-mode (cmd)
8806 "Run a command, pretending that the current buffer is in Org-mode.
8807 This will temporarily bind local variables that are typically bound in
8808 Org-mode to the values they have in Org-mode, and then interactively
8809 call CMD."
8810 (org-load-modules-maybe)
8811 (unless org-local-vars
8812 (setq org-local-vars (org-get-local-variables)))
8813 (eval (list 'let org-local-vars
8814 (list 'call-interactively (list 'quote cmd)))))
8816 ;;;; Archiving
8818 (defun org-get-category (&optional pos force-refresh)
8819 "Get the category applying to position POS."
8820 (save-match-data
8821 (if force-refresh (org-refresh-category-properties))
8822 (let ((pos (or pos (point))))
8823 (or (get-text-property pos 'org-category)
8824 (progn (org-refresh-category-properties)
8825 (get-text-property pos 'org-category))))))
8827 (defun org-refresh-category-properties ()
8828 "Refresh category text properties in the buffer."
8829 (let ((case-fold-search t)
8830 (inhibit-read-only t)
8831 (def-cat (cond
8832 ((null org-category)
8833 (if buffer-file-name
8834 (file-name-sans-extension
8835 (file-name-nondirectory buffer-file-name))
8836 "???"))
8837 ((symbolp org-category) (symbol-name org-category))
8838 (t org-category)))
8839 beg end cat pos optionp)
8840 (org-unmodified
8841 (save-excursion
8842 (save-restriction
8843 (widen)
8844 (goto-char (point-min))
8845 (put-text-property (point) (point-max) 'org-category def-cat)
8846 (while (re-search-forward
8847 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8848 (setq pos (match-end 0)
8849 optionp (equal (char-after (match-beginning 0)) ?#)
8850 cat (org-trim (match-string 2)))
8851 (if optionp
8852 (setq beg (point-at-bol) end (point-max))
8853 (org-back-to-heading t)
8854 (setq beg (point) end (org-end-of-subtree t t)))
8855 (put-text-property beg end 'org-category cat)
8856 (put-text-property beg end 'org-category-position beg)
8857 (goto-char pos)))))))
8859 (defun org-refresh-properties (dprop tprop)
8860 "Refresh buffer text properties.
8861 DPROP is the drawer property and TPROP is the corresponding text
8862 property to set."
8863 (let ((case-fold-search t)
8864 (inhibit-read-only t) p)
8865 (org-unmodified
8866 (save-excursion
8867 (save-restriction
8868 (widen)
8869 (goto-char (point-min))
8870 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8871 (setq p (org-match-string-no-properties 1))
8872 (save-excursion
8873 (org-back-to-heading t)
8874 (put-text-property
8875 (point-at-bol) (point-at-eol) tprop p))))))))
8878 ;;;; Link Stuff
8880 ;;; Link abbreviations
8882 (defun org-link-expand-abbrev (link)
8883 "Apply replacements as defined in `org-link-abbrev-alist'."
8884 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8885 (let* ((key (match-string 1 link))
8886 (as (or (assoc key org-link-abbrev-alist-local)
8887 (assoc key org-link-abbrev-alist)))
8888 (tag (and (match-end 2) (match-string 3 link)))
8889 rpl)
8890 (if (not as)
8891 link
8892 (setq rpl (cdr as))
8893 (cond
8894 ((symbolp rpl) (funcall rpl tag))
8895 ((string-match "%(\\([^)]+\\))" rpl)
8896 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8897 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8898 ((string-match "%h" rpl)
8899 (replace-match (url-hexify-string (or tag "")) t t rpl))
8900 (t (concat rpl tag)))))
8901 link))
8903 ;;; Storing and inserting links
8905 (defvar org-insert-link-history nil
8906 "Minibuffer history for links inserted with `org-insert-link'.")
8908 (defvar org-stored-links nil
8909 "Contains the links stored with `org-store-link'.")
8911 (defvar org-store-link-plist nil
8912 "Plist with info about the most recently link created with `org-store-link'.")
8914 (defvar org-link-protocols nil
8915 "Link protocols added to Org-mode using `org-add-link-type'.")
8917 (defvar org-store-link-functions nil
8918 "List of functions that are called to create and store a link.
8919 Each function will be called in turn until one returns a non-nil
8920 value. Each function should check if it is responsible for creating
8921 this link (for example by looking at the major mode).
8922 If not, it must exit and return nil.
8923 If yes, it should return a non-nil value after a calling
8924 `org-store-link-props' with a list of properties and values.
8925 Special properties are:
8927 :type The link prefix, like \"http\". This must be given.
8928 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8929 This is obligatory as well.
8930 :description Optional default description for the second pair
8931 of brackets in an Org-mode link. The user can still change
8932 this when inserting this link into an Org-mode buffer.
8934 In addition to these, any additional properties can be specified
8935 and then used in capture templates.")
8937 (defun org-add-link-type (type &optional follow export)
8938 "Add TYPE to the list of `org-link-types'.
8939 Re-compute all regular expressions depending on `org-link-types'
8941 FOLLOW and EXPORT are two functions.
8943 FOLLOW should take the link path as the single argument and do whatever
8944 is necessary to follow the link, for example find a file or display
8945 a mail message.
8947 EXPORT should format the link path for export to one of the export formats.
8948 It should be a function accepting three arguments:
8950 path the path of the link, the text after the prefix (like \"http:\")
8951 desc the description of the link, if any, or a description added by
8952 org-export-normalize-links if there is none
8953 format the export format, a symbol like `html' or `latex' or `ascii'..
8955 The function may use the FORMAT information to return different values
8956 depending on the format. The return value will be put literally into
8957 the exported file. If the return value is nil, this means Org should
8958 do what it normally does with links which do not have EXPORT defined.
8960 Org-mode has a built-in default for exporting links. If you are happy with
8961 this default, there is no need to define an export function for the link
8962 type. For a simple example of an export function, see `org-bbdb.el'."
8963 (add-to-list 'org-link-types type t)
8964 (org-make-link-regexps)
8965 (if (assoc type org-link-protocols)
8966 (setcdr (assoc type org-link-protocols) (list follow export))
8967 (push (list type follow export) org-link-protocols)))
8969 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8970 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8972 ;;;###autoload
8973 (defun org-store-link (arg)
8974 "\\<org-mode-map>Store an org-link to the current location.
8975 This link is added to `org-stored-links' and can later be inserted
8976 into an org-buffer with \\[org-insert-link].
8978 For some link types, a prefix arg is interpreted.
8979 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8980 For file links, arg negates `org-context-in-file-links'.
8982 A double prefix arg force skipping storing functions that are not
8983 part of Org's core."
8984 (interactive "P")
8985 (org-load-modules-maybe)
8986 (setq org-store-link-plist nil) ; reset
8987 (org-with-limited-levels
8988 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8989 (cond
8990 ((and (not (equal arg '(16)))
8991 (setq sfuns
8992 (delq
8993 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8994 org-store-link-functions))
8995 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8996 (or (and (cdr sfuns)
8997 (funcall (intern
8998 (completing-read "Which function for creating the link? "
8999 sfunsn t (car sfunsn)))))
9000 (funcall (caar sfuns)))
9001 (setq link (plist-get org-store-link-plist :link)
9002 desc (or (plist-get org-store-link-plist :description) link))))
9003 ((org-src-edit-buffer-p)
9004 (let (label gc)
9005 (while (or (not label)
9006 (save-excursion
9007 (save-restriction
9008 (widen)
9009 (goto-char (point-min))
9010 (re-search-forward
9011 (regexp-quote (format org-coderef-label-format label))
9012 nil t))))
9013 (when label (message "Label exists already") (sit-for 2))
9014 (setq label (read-string "Code line label: " label)))
9015 (end-of-line 1)
9016 (setq link (format org-coderef-label-format label))
9017 (setq gc (- 79 (length link)))
9018 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9019 (insert link)
9020 (setq link (concat "(" label ")") desc nil)))
9022 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9023 ;; We are in the agenda, link to referenced location
9024 (let ((m (or (get-text-property (point) 'org-hd-marker)
9025 (get-text-property (point) 'org-marker))))
9026 (when m
9027 (org-with-point-at m
9028 (setq agenda-link
9029 (if (org-called-interactively-p 'any)
9030 (call-interactively 'org-store-link)
9031 (org-store-link nil)))))))
9033 ((eq major-mode 'calendar-mode)
9034 (let ((cd (calendar-cursor-to-date)))
9035 (setq link
9036 (format-time-string
9037 (car org-time-stamp-formats)
9038 (apply 'encode-time
9039 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9040 nil nil nil))))
9041 (org-store-link-props :type "calendar" :date cd)))
9043 ((eq major-mode 'help-mode)
9044 (setq link (concat "help:" (save-excursion
9045 (goto-char (point-min))
9046 (looking-at "^[^ ]+")
9047 (match-string 0))))
9048 (org-store-link-props :type "help"))
9050 ((eq major-mode 'w3-mode)
9051 (setq cpltxt (if (and (buffer-name)
9052 (not (string-match "Untitled" (buffer-name))))
9053 (buffer-name)
9054 (url-view-url t))
9055 link (url-view-url t))
9056 (org-store-link-props :type "w3" :url (url-view-url t)))
9058 ((setq search (run-hook-with-args-until-success
9059 'org-create-file-search-functions))
9060 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9061 "::" search))
9062 (setq cpltxt (or description link)))
9064 ((eq major-mode 'image-mode)
9065 (setq cpltxt (concat "file:"
9066 (abbreviate-file-name buffer-file-name))
9067 link cpltxt)
9068 (org-store-link-props :type "image" :file buffer-file-name))
9070 ((eq major-mode 'dired-mode)
9071 ;; link to the file in the current line
9072 (let ((file (dired-get-filename nil t)))
9073 (setq file (if file
9074 (abbreviate-file-name
9075 (expand-file-name (dired-get-filename nil t)))
9076 ;; otherwise, no file so use current directory.
9077 default-directory))
9078 (setq cpltxt (concat "file:" file)
9079 link cpltxt)))
9081 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9082 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9083 (cond
9084 ((org-in-regexp "<<\\(.*?\\)>>")
9085 (setq cpltxt
9086 (concat "file:"
9087 (abbreviate-file-name
9088 (buffer-file-name (buffer-base-buffer)))
9089 "::" (match-string 1))
9090 link cpltxt))
9091 ((and (featurep 'org-id)
9092 (or (eq org-id-link-to-org-use-id t)
9093 (and (org-called-interactively-p 'any)
9094 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9095 (and (eq org-id-link-to-org-use-id
9096 'create-if-interactive-and-no-custom-id)
9097 (not custom-id))))
9098 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9099 ;; We can make a link using the ID.
9100 (setq link (condition-case nil
9101 (prog1 (org-id-store-link)
9102 (setq desc (plist-get org-store-link-plist :description)))
9103 (error
9104 ;; probably before first headline, link to file only
9105 (concat "file:"
9106 (abbreviate-file-name
9107 (buffer-file-name (buffer-base-buffer))))))))
9109 ;; Just link to current headline
9110 (setq cpltxt (concat "file:"
9111 (abbreviate-file-name
9112 (buffer-file-name (buffer-base-buffer)))))
9113 ;; Add a context search string
9114 (when (org-xor org-context-in-file-links arg)
9115 (let* ((ee (org-element-at-point))
9116 (et (org-element-type ee))
9117 (ev (plist-get (cadr ee) :value)))
9118 (setq txt (cond
9119 ((org-at-heading-p) nil)
9120 ((eq et 'keyword) ev)
9121 ((org-region-active-p)
9122 (buffer-substring (region-beginning) (region-end)))))
9123 (when (or (null txt) (string-match "\\S-" txt))
9124 (setq cpltxt
9125 (concat cpltxt "::"
9126 (condition-case nil
9127 (org-make-org-heading-search-string txt)
9128 (error "")))
9129 desc (or (and (eq et 'keyword) ev)
9130 (nth 4 (ignore-errors (org-heading-components)))
9131 "NONE")))))
9132 (if (string-match "::\\'" cpltxt)
9133 (setq cpltxt (substring cpltxt 0 -2)))
9134 (setq link cpltxt))))
9136 ((buffer-file-name (buffer-base-buffer))
9137 ;; Just link to this file here.
9138 (setq cpltxt (concat "file:"
9139 (abbreviate-file-name
9140 (buffer-file-name (buffer-base-buffer)))))
9141 ;; Add a context string
9142 (when (org-xor org-context-in-file-links arg)
9143 (setq txt (if (org-region-active-p)
9144 (buffer-substring (region-beginning) (region-end))
9145 (buffer-substring (point-at-bol) (point-at-eol))))
9146 ;; Only use search option if there is some text.
9147 (when (string-match "\\S-" txt)
9148 (setq cpltxt
9149 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9150 desc "NONE")))
9151 (setq link cpltxt))
9153 ((org-called-interactively-p 'interactive)
9154 (user-error "No method for storing a link from this buffer"))
9156 (t (setq link nil)))
9158 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9159 (setq link (or link cpltxt)
9160 desc (or desc cpltxt))
9161 (cond ((equal desc "NONE") (setq desc nil))
9162 ((string-match org-bracket-link-regexp desc)
9163 (setq desc (replace-regexp-in-string
9164 org-bracket-link-regexp
9165 (concat "\\3" (if (equal (length (match-string 0 desc))
9166 (length desc)) "*" "")) desc))))
9168 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9169 (progn
9170 (setq org-stored-links
9171 (cons (list link desc) org-stored-links))
9172 (message "Stored: %s" (or desc link))
9173 (when custom-id
9174 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9175 "::#" custom-id))
9176 (setq org-stored-links
9177 (cons (list link desc) org-stored-links))))
9178 (or agenda-link (and link (org-make-link-string link desc)))))))
9180 (defun org-store-link-props (&rest plist)
9181 "Store link properties, extract names and addresses."
9182 (let (x adr)
9183 (when (setq x (plist-get plist :from))
9184 (setq adr (mail-extract-address-components x))
9185 (setq plist (plist-put plist :fromname (car adr)))
9186 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9187 (when (setq x (plist-get plist :to))
9188 (setq adr (mail-extract-address-components x))
9189 (setq plist (plist-put plist :toname (car adr)))
9190 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9191 (let ((from (plist-get plist :from))
9192 (to (plist-get plist :to)))
9193 (when (and from to org-from-is-user-regexp)
9194 (setq plist
9195 (plist-put plist :fromto
9196 (if (string-match org-from-is-user-regexp from)
9197 (concat "to %t")
9198 (concat "from %f"))))))
9199 (setq org-store-link-plist plist))
9201 (defun org-add-link-props (&rest plist)
9202 "Add these properties to the link property list."
9203 (let (key value)
9204 (while plist
9205 (setq key (pop plist) value (pop plist))
9206 (setq org-store-link-plist
9207 (plist-put org-store-link-plist key value)))))
9209 (defun org-email-link-description (&optional fmt)
9210 "Return the description part of an email link.
9211 This takes information from `org-store-link-plist' and formats it
9212 according to FMT (default from `org-email-link-description-format')."
9213 (setq fmt (or fmt org-email-link-description-format))
9214 (let* ((p org-store-link-plist)
9215 (to (plist-get p :toaddress))
9216 (from (plist-get p :fromaddress))
9217 (table
9218 (list
9219 (cons "%c" (plist-get p :fromto))
9220 (cons "%F" (plist-get p :from))
9221 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9222 (cons "%T" (plist-get p :to))
9223 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9224 (cons "%s" (plist-get p :subject))
9225 (cons "%d" (plist-get p :date))
9226 (cons "%m" (plist-get p :message-id)))))
9227 (when (string-match "%c" fmt)
9228 ;; Check if the user wrote this message
9229 (if (and org-from-is-user-regexp from to
9230 (save-match-data (string-match org-from-is-user-regexp from)))
9231 (setq fmt (replace-match "to %t" t t fmt))
9232 (setq fmt (replace-match "from %f" t t fmt))))
9233 (org-replace-escapes fmt table)))
9235 (defun org-make-org-heading-search-string (&optional string)
9236 "Make search string for the current headline or STRING."
9237 (let ((s (or string
9238 (and (derived-mode-p 'org-mode)
9239 (save-excursion
9240 (org-back-to-heading t)
9241 (plist-get (cadr (org-element-at-point))
9242 :raw-value)))))
9243 (lines org-context-in-file-links))
9244 (or string (setq s (concat "*" s))) ; Add * for headlines
9245 (when (and string (integerp lines) (> lines 0))
9246 (let ((slines (org-split-string s "\n")))
9247 (when (< lines (length slines))
9248 (setq s (mapconcat
9249 'identity
9250 (reverse (nthcdr (- (length slines) lines)
9251 (reverse slines))) "\n")))))
9252 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9254 (defun org-make-link-string (link &optional description)
9255 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9256 (unless (string-match "\\S-" link)
9257 (error "Empty link"))
9258 (when (and description
9259 (stringp description)
9260 (not (string-match "\\S-" description)))
9261 (setq description nil))
9262 (when (stringp description)
9263 ;; Remove brackets from the description, they are fatal.
9264 (while (string-match "\\[" description)
9265 (setq description (replace-match "{" t t description)))
9266 (while (string-match "\\]" description)
9267 (setq description (replace-match "}" t t description))))
9268 (when (equal link description)
9269 ;; No description needed, it is identical
9270 (setq description nil))
9271 (when (and (not description)
9272 (not (string-match (org-image-file-name-regexp) link))
9273 (not (equal link (org-link-escape link))))
9274 (setq description (org-extract-attributes link)))
9275 (setq link
9276 (cond ((string-match (org-image-file-name-regexp) link) link)
9277 ((string-match org-link-types-re link)
9278 (concat (match-string 1 link)
9279 (org-link-escape (substring link (match-end 1)))))
9280 (t (org-link-escape link))))
9281 (concat "[[" link "]"
9282 (if description (concat "[" description "]") "")
9283 "]"))
9285 (defconst org-link-escape-chars
9286 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9287 "List of characters that should be escaped in link.
9288 This is the list that is used for internal purposes.")
9290 (defconst org-link-escape-chars-browser
9291 '(?\ )
9292 "List of escapes for characters that are problematic in links.
9293 This is the list that is used before handing over to the browser.")
9295 (defun org-link-escape (text &optional table merge)
9296 "Return percent escaped representation of TEXT.
9297 TEXT is a string with the text to escape.
9298 Optional argument TABLE is a list with characters that should be
9299 escaped. When nil, `org-link-escape-chars' is used.
9300 If optional argument MERGE is set, merge TABLE into
9301 `org-link-escape-chars'."
9302 (cond
9303 ((and table merge)
9304 (mapc (lambda (defchr)
9305 (unless (member defchr table)
9306 (setq table (cons defchr table)))) org-link-escape-chars))
9307 ((null table)
9308 (setq table org-link-escape-chars)))
9309 (mapconcat
9310 (lambda (char)
9311 (if (or (member char table)
9312 (and (or (< char 32) (= char 37) (> char 126))
9313 org-url-hexify-p))
9314 (mapconcat (lambda (sequence-element)
9315 (format "%%%.2X" sequence-element))
9316 (or (encode-coding-char char 'utf-8)
9317 (error "Unable to percent escape character: %s"
9318 (char-to-string char))) "")
9319 (char-to-string char))) text ""))
9321 (defun org-link-unescape (str)
9322 "Unhex hexified Unicode strings as returned from the JavaScript function
9323 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9324 (unless (and (null str) (string= "" str))
9325 (let ((pos 0) (case-fold-search t) unhexed)
9326 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9327 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9328 (setq str (replace-match unhexed t t str))
9329 (setq pos (+ pos (length unhexed))))))
9330 str)
9332 (defun org-link-unescape-compound (hex)
9333 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9334 Note: this function also decodes single byte encodings like
9335 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9336 (save-match-data
9337 (let* ((bytes (cdr (split-string hex "%")))
9338 (ret "")
9339 (eat 0)
9340 (sum 0))
9341 (while bytes
9342 (let* ((val (string-to-number (pop bytes) 16))
9343 (shift-xor
9344 (if (= 0 eat)
9345 (cond
9346 ((>= val 252) (cons 6 252))
9347 ((>= val 248) (cons 5 248))
9348 ((>= val 240) (cons 4 240))
9349 ((>= val 224) (cons 3 224))
9350 ((>= val 192) (cons 2 192))
9351 (t (cons 0 0)))
9352 (cons 6 128))))
9353 (if (>= val 192) (setq eat (car shift-xor)))
9354 (setq val (logxor val (cdr shift-xor)))
9355 (setq sum (+ (lsh sum (car shift-xor)) val))
9356 (if (> eat 0) (setq eat (- eat 1)))
9357 (cond
9358 ((= 0 eat) ;multi byte
9359 (setq ret (concat ret (org-char-to-string sum)))
9360 (setq sum 0))
9361 ((not bytes) ; single byte(s)
9362 (setq ret (org-link-unescape-single-byte-sequence hex))))
9363 )) ;; end (while bytes
9364 ret )))
9366 (defun org-link-unescape-single-byte-sequence (hex)
9367 "Unhexify hex-encoded single byte character sequences."
9368 (mapconcat (lambda (byte)
9369 (char-to-string (string-to-number byte 16)))
9370 (cdr (split-string hex "%")) ""))
9372 (defun org-xor (a b)
9373 "Exclusive or."
9374 (if a (not b) b))
9376 (defun org-fixup-message-id-for-http (s)
9377 "Replace special characters in a message id, so it can be used in an http query."
9378 (when (string-match "%" s)
9379 (setq s (mapconcat (lambda (c)
9380 (if (eq c ?%)
9381 "%25"
9382 (char-to-string c)))
9383 s "")))
9384 (while (string-match "<" s)
9385 (setq s (replace-match "%3C" t t s)))
9386 (while (string-match ">" s)
9387 (setq s (replace-match "%3E" t t s)))
9388 (while (string-match "@" s)
9389 (setq s (replace-match "%40" t t s)))
9392 (defun org-link-prettify (link)
9393 "Return a human-readable representation of LINK.
9394 The car of LINK must be a raw link the cdr of LINK must be either
9395 a link description or nil."
9396 (let ((desc (or (cadr link) "<no description>")))
9397 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9398 "<" (car link) ">")))
9400 ;;;###autoload
9401 (defun org-insert-link-global ()
9402 "Insert a link like Org-mode does.
9403 This command can be called in any mode to insert a link in Org-mode syntax."
9404 (interactive)
9405 (org-load-modules-maybe)
9406 (org-run-like-in-org-mode 'org-insert-link))
9408 (defun org-insert-all-links (&optional keep)
9409 "Insert all links in `org-stored-links'."
9410 (interactive "P")
9411 (let ((links (copy-sequence org-stored-links)) l)
9412 (while (setq l (if keep (pop links) (pop org-stored-links)))
9413 (insert "- ")
9414 (org-insert-link nil (car l) (cadr l))
9415 (insert "\n"))))
9417 (defun org-link-fontify-links-to-this-file ()
9418 "Fontify links to the current file in `org-stored-links'."
9419 (let ((f (buffer-file-name)) a b)
9420 (setq a (mapcar (lambda(l)
9421 (let ((ll (car l)))
9422 (when (and (string-match "^file:\\(.+\\)::" ll)
9423 (equal f (expand-file-name (match-string 1 ll))))
9424 ll)))
9425 org-stored-links))
9426 (when (featurep 'org-id)
9427 (setq b (mapcar (lambda(l)
9428 (let ((ll (car l)))
9429 (when (and (string-match "^id:\\(.+\\)$" ll)
9430 (equal f (expand-file-name
9431 (or (org-id-find-id-file
9432 (match-string 1 ll)) ""))))
9433 ll)))
9434 org-stored-links)))
9435 (mapcar (lambda(l)
9436 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9437 (delq nil (append a b)))))
9439 (defvar org-link-links-in-this-file nil)
9440 (defun org-insert-link (&optional complete-file link-location default-description)
9441 "Insert a link. At the prompt, enter the link.
9443 Completion can be used to insert any of the link protocol prefixes like
9444 http or ftp in use.
9446 The history can be used to select a link previously stored with
9447 `org-store-link'. When the empty string is entered (i.e. if you just
9448 press RET at the prompt), the link defaults to the most recently
9449 stored link. As SPC triggers completion in the minibuffer, you need to
9450 use M-SPC or C-q SPC to force the insertion of a space character.
9452 You will also be prompted for a description, and if one is given, it will
9453 be displayed in the buffer instead of the link.
9455 If there is already a link at point, this command will allow you to edit link
9456 and description parts.
9458 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9459 be selected using completion. The path to the file will be relative to the
9460 current directory if the file is in the current directory or a subdirectory.
9461 Otherwise, the link will be the absolute path as completed in the minibuffer
9462 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9463 option `org-link-file-path-type'.
9465 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9466 the current directory or below.
9468 With three \\[universal-argument] prefixes, negate the meaning of
9469 `org-keep-stored-link-after-insertion'.
9471 If `org-make-link-description-function' is non-nil, this function will be
9472 called with the link target, and the result will be the default
9473 link description.
9475 If the LINK-LOCATION parameter is non-nil, this value will be
9476 used as the link location instead of reading one interactively.
9478 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9479 be used as the default description."
9480 (interactive "P")
9481 (let* ((wcf (current-window-configuration))
9482 (origbuf (current-buffer))
9483 (region (if (org-region-active-p)
9484 (buffer-substring (region-beginning) (region-end))))
9485 (remove (and region (list (region-beginning) (region-end))))
9486 (desc region)
9487 tmphist ; byte-compile incorrectly complains about this
9488 (link link-location)
9489 (abbrevs org-link-abbrev-alist-local)
9490 entry file all-prefixes auto-desc)
9491 (cond
9492 (link-location) ; specified by arg, just use it.
9493 ((org-in-regexp org-bracket-link-regexp 1)
9494 ;; We do have a link at point, and we are going to edit it.
9495 (setq remove (list (match-beginning 0) (match-end 0)))
9496 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9497 (setq link (read-string "Link: "
9498 (org-link-unescape
9499 (org-match-string-no-properties 1)))))
9500 ((or (org-in-regexp org-angle-link-re)
9501 (org-in-regexp org-plain-link-re))
9502 ;; Convert to bracket link
9503 (setq remove (list (match-beginning 0) (match-end 0))
9504 link (read-string "Link: "
9505 (org-remove-angle-brackets (match-string 0)))))
9506 ((member complete-file '((4) (16)))
9507 ;; Completing read for file names.
9508 (setq link (org-file-complete-link complete-file)))
9510 ;; Read link, with completion for stored links.
9511 (org-link-fontify-links-to-this-file)
9512 (org-switch-to-buffer-other-window "*Org Links*")
9513 (with-current-buffer "*Org Links*"
9514 (erase-buffer)
9515 (insert "Insert a link.
9516 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9517 (when org-stored-links
9518 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9519 (insert (mapconcat 'org-link-prettify
9520 (reverse org-stored-links) "\n")))
9521 (goto-char (point-min)))
9522 (let ((cw (selected-window)))
9523 (select-window (get-buffer-window "*Org Links*" 'visible))
9524 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9525 (unless (pos-visible-in-window-p (point-max))
9526 (org-fit-window-to-buffer))
9527 (and (window-live-p cw) (select-window cw)))
9528 ;; Fake a link history, containing the stored links.
9529 (setq tmphist (append (mapcar 'car org-stored-links)
9530 org-insert-link-history))
9531 (setq all-prefixes (append (mapcar 'car abbrevs)
9532 (mapcar 'car org-link-abbrev-alist)
9533 org-link-types))
9534 (unwind-protect
9535 (progn
9536 (setq link
9537 (org-completing-read
9538 "Link: "
9539 (append
9540 (mapcar (lambda (x) (concat x ":"))
9541 all-prefixes)
9542 (mapcar 'car org-stored-links))
9543 nil nil nil
9544 'tmphist
9545 (caar org-stored-links)))
9546 (if (not (string-match "\\S-" link))
9547 (error "No link selected"))
9548 (mapc (lambda(l)
9549 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9550 org-stored-links)
9551 (if (or (member link all-prefixes)
9552 (and (equal ":" (substring link -1))
9553 (member (substring link 0 -1) all-prefixes)
9554 (setq link (substring link 0 -1))))
9555 (setq link (with-current-buffer origbuf
9556 (org-link-try-special-completion link)))))
9557 (set-window-configuration wcf)
9558 (kill-buffer "*Org Links*"))
9559 (setq entry (assoc link org-stored-links))
9560 (or entry (push link org-insert-link-history))
9561 (setq desc (or desc (nth 1 entry)))))
9563 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9564 (not org-keep-stored-link-after-insertion))
9565 (setq org-stored-links (delq (assoc link org-stored-links)
9566 org-stored-links)))
9568 (if (string-match org-plain-link-re link)
9569 ;; URL-like link, normalize the use of angular brackets.
9570 (setq link (org-remove-angle-brackets link)))
9572 ;; Check if we are linking to the current file with a search
9573 ;; option If yes, simplify the link by using only the search
9574 ;; option.
9575 (when (and buffer-file-name
9576 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9577 (let* ((path (match-string 1 link))
9578 (case-fold-search nil)
9579 (search (match-string 2 link)))
9580 (save-match-data
9581 (if (equal (file-truename buffer-file-name) (file-truename path))
9582 ;; We are linking to this same file, with a search option
9583 (setq link search)))))
9585 ;; Check if we can/should use a relative path. If yes, simplify the link
9586 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9587 (let* ((type (match-string 1 link))
9588 (path (match-string 2 link))
9589 (origpath path)
9590 (case-fold-search nil))
9591 (cond
9592 ((or (eq org-link-file-path-type 'absolute)
9593 (equal complete-file '(16)))
9594 (setq path (abbreviate-file-name (expand-file-name path))))
9595 ((eq org-link-file-path-type 'noabbrev)
9596 (setq path (expand-file-name path)))
9597 ((eq org-link-file-path-type 'relative)
9598 (setq path (file-relative-name path)))
9600 (save-match-data
9601 (if (string-match (concat "^" (regexp-quote
9602 (expand-file-name
9603 (file-name-as-directory
9604 default-directory))))
9605 (expand-file-name path))
9606 ;; We are linking a file with relative path name.
9607 (setq path (substring (expand-file-name path)
9608 (match-end 0)))
9609 (setq path (abbreviate-file-name (expand-file-name path)))))))
9610 (setq link (concat type path))
9611 (if (equal desc origpath)
9612 (setq desc path))))
9614 (if org-make-link-description-function
9615 (setq desc
9616 (or (condition-case nil
9617 (funcall org-make-link-description-function link desc)
9618 (error (progn (message "Can't get link description from `%s'"
9619 (symbol-name org-make-link-description-function))
9620 (sit-for 2) nil)))
9621 (read-string "Description: " default-description)))
9622 (if default-description (setq desc default-description)
9623 (setq desc (or (and auto-desc desc)
9624 (read-string "Description: " desc)))))
9626 (unless (string-match "\\S-" desc) (setq desc nil))
9627 (if remove (apply 'delete-region remove))
9628 (insert (org-make-link-string link desc))))
9630 (defun org-link-try-special-completion (type)
9631 "If there is completion support for link type TYPE, offer it."
9632 (let ((fun (intern (concat "org-" type "-complete-link"))))
9633 (if (functionp fun)
9634 (funcall fun)
9635 (read-string "Link (no completion support): " (concat type ":")))))
9637 (defun org-file-complete-link (&optional arg)
9638 "Create a file link using completion."
9639 (let (file link)
9640 (setq file (org-iread-file-name "File: "))
9641 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9642 (pwd1 (file-name-as-directory (abbreviate-file-name
9643 (expand-file-name ".")))))
9644 (cond
9645 ((equal arg '(16))
9646 (setq link (concat
9647 "file:"
9648 (abbreviate-file-name (expand-file-name file)))))
9649 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9650 (setq link (concat "file:" (match-string 1 file))))
9651 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9652 (expand-file-name file))
9653 (setq link (concat
9654 "file:" (match-string 1 (expand-file-name file)))))
9655 (t (setq link (concat "file:" file)))))
9656 link))
9658 (defun org-iread-file-name (&rest args)
9659 "Read-file-name using `ido-mode' speedup if available.
9660 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9661 See `read-file-name' for a description of parameters."
9662 (org-without-partial-completion
9663 (if (and org-completion-use-ido
9664 (fboundp 'ido-read-file-name)
9665 (boundp 'ido-mode) ido-mode
9666 (listp (second args)))
9667 (let ((ido-enter-matching-directory nil))
9668 (apply 'ido-read-file-name args))
9669 (apply 'read-file-name args))))
9671 (defun org-completing-read (&rest args)
9672 "Completing-read with SPACE being a normal character."
9673 (let ((enable-recursive-minibuffers t)
9674 (minibuffer-local-completion-map
9675 (copy-keymap minibuffer-local-completion-map)))
9676 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9677 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9678 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9679 (apply 'org-icompleting-read args)))
9681 (defun org-completing-read-no-i (&rest args)
9682 (let (org-completion-use-ido org-completion-use-iswitchb)
9683 (apply 'org-completing-read args)))
9685 (defun org-iswitchb-completing-read (prompt choices &rest args)
9686 "Use iswitch as a completing-read replacement to choose from choices.
9687 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9688 from."
9689 (let* ((iswitchb-use-virtual-buffers nil)
9690 (iswitchb-make-buflist-hook
9691 (lambda ()
9692 (setq iswitchb-temp-buflist choices))))
9693 (iswitchb-read-buffer prompt)))
9695 (defun org-icompleting-read (&rest args)
9696 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9697 (org-without-partial-completion
9698 (if (and org-completion-use-ido
9699 (fboundp 'ido-completing-read)
9700 (boundp 'ido-mode) ido-mode
9701 (listp (second args)))
9702 (let ((ido-enter-matching-directory nil))
9703 (apply 'ido-completing-read (concat (car args))
9704 (if (consp (car (nth 1 args)))
9705 (mapcar 'car (nth 1 args))
9706 (nth 1 args))
9707 (cddr args)))
9708 (if (and org-completion-use-iswitchb
9709 (boundp 'iswitchb-mode) iswitchb-mode
9710 (listp (second args)))
9711 (apply 'org-iswitchb-completing-read (concat (car args))
9712 (if (consp (car (nth 1 args)))
9713 (mapcar 'car (nth 1 args))
9714 (nth 1 args))
9715 (cddr args))
9716 (apply 'completing-read args)))))
9718 (defun org-extract-attributes (s)
9719 "Extract the attributes cookie from a string and set as text property."
9720 (let (a attr (start 0) key value)
9721 (save-match-data
9722 (when (string-match "{{\\([^}]+\\)}}$" s)
9723 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9724 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9725 (setq key (match-string 1 a) value (match-string 2 a)
9726 start (match-end 0)
9727 attr (plist-put attr (intern key) value))))
9728 (org-add-props s nil 'org-attr attr))
9731 (defun org-extract-attributes-from-string (tag)
9732 (let (key value attr)
9733 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9734 (setq key (match-string 1 tag) value (match-string 2 tag)
9735 tag (replace-match "" t t tag)
9736 attr (plist-put attr (intern key) value)))
9737 (cons tag attr)))
9739 (defun org-attributes-to-string (plist)
9740 "Format a property list into an HTML attribute list."
9741 (let ((s "") key value)
9742 (while plist
9743 (setq key (pop plist) value (pop plist))
9744 (and value
9745 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9748 ;;; Opening/following a link
9750 (defvar org-link-search-failed nil)
9752 (defvar org-open-link-functions nil
9753 "Hook for functions finding a plain text link.
9754 These functions must take a single argument, the link content.
9755 They will be called for links that look like [[link text][description]]
9756 when LINK TEXT does not have a protocol like \"http:\" and does not look
9757 like a filename (e.g. \"./blue.png\").
9759 These functions will be called *before* Org attempts to resolve the
9760 link by doing text searches in the current buffer - so if you want a
9761 link \"[[target]]\" to still find \"<<target>>\", your function should
9762 handle this as a special case.
9764 When the function does handle the link, it must return a non-nil value.
9765 If it decides that it is not responsible for this link, it must return
9766 nil to indicate that that Org-mode can continue with other options
9767 like exact and fuzzy text search.")
9769 (defun org-next-link ()
9770 "Move forward to the next link.
9771 If the link is in hidden text, expose it."
9772 (interactive)
9773 (when (and org-link-search-failed (eq this-command last-command))
9774 (goto-char (point-min))
9775 (message "Link search wrapped back to beginning of buffer"))
9776 (setq org-link-search-failed nil)
9777 (let* ((pos (point))
9778 (ct (org-context))
9779 (a (assoc :link ct)))
9780 (if a (goto-char (nth 2 a)))
9781 (if (re-search-forward org-any-link-re nil t)
9782 (progn
9783 (goto-char (match-beginning 0))
9784 (if (outline-invisible-p) (org-show-context)))
9785 (goto-char pos)
9786 (setq org-link-search-failed t)
9787 (error "No further link found"))))
9789 (defun org-previous-link ()
9790 "Move backward to the previous link.
9791 If the link is in hidden text, expose it."
9792 (interactive)
9793 (when (and org-link-search-failed (eq this-command last-command))
9794 (goto-char (point-max))
9795 (message "Link search wrapped back to end of buffer"))
9796 (setq org-link-search-failed nil)
9797 (let* ((pos (point))
9798 (ct (org-context))
9799 (a (assoc :link ct)))
9800 (if a (goto-char (nth 1 a)))
9801 (if (re-search-backward org-any-link-re nil t)
9802 (progn
9803 (goto-char (match-beginning 0))
9804 (if (outline-invisible-p) (org-show-context)))
9805 (goto-char pos)
9806 (setq org-link-search-failed t)
9807 (error "No further link found"))))
9809 (defun org-translate-link (s)
9810 "Translate a link string if a translation function has been defined."
9811 (if (and org-link-translation-function
9812 (fboundp org-link-translation-function)
9813 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9814 (progn
9815 (setq s (funcall org-link-translation-function
9816 (match-string 1 s) (match-string 2 s)))
9817 (concat (car s) ":" (cdr s)))
9820 (defun org-translate-link-from-planner (type path)
9821 "Translate a link from Emacs Planner syntax so that Org can follow it.
9822 This is still an experimental function, your mileage may vary."
9823 (cond
9824 ((member type '("http" "https" "news" "ftp"))
9825 ;; standard Internet links are the same.
9826 nil)
9827 ((and (equal type "irc") (string-match "^//" path))
9828 ;; Planner has two / at the beginning of an irc link, we have 1.
9829 ;; We should have zero, actually....
9830 (setq path (substring path 1)))
9831 ((and (equal type "lisp") (string-match "^/" path))
9832 ;; Planner has a slash, we do not.
9833 (setq type "elisp" path (substring path 1)))
9834 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9835 ;; A typical message link. Planner has the id after the final slash,
9836 ;; we separate it with a hash mark
9837 (setq path (concat (match-string 1 path) "#"
9838 (org-remove-angle-brackets (match-string 2 path)))))
9840 (cons type path))
9842 (defun org-find-file-at-mouse (ev)
9843 "Open file link or URL at mouse."
9844 (interactive "e")
9845 (mouse-set-point ev)
9846 (org-open-at-point 'in-emacs))
9848 (defun org-open-at-mouse (ev)
9849 "Open file link or URL at mouse.
9850 See the docstring of `org-open-file' for details."
9851 (interactive "e")
9852 (mouse-set-point ev)
9853 (if (eq major-mode 'org-agenda-mode)
9854 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9855 (org-open-at-point))
9857 (defvar org-window-config-before-follow-link nil
9858 "The window configuration before following a link.
9859 This is saved in case the need arises to restore it.")
9861 (defvar org-open-link-marker (make-marker)
9862 "Marker pointing to the location where `org-open-at-point; was called.")
9864 ;;;###autoload
9865 (defun org-open-at-point-global ()
9866 "Follow a link like Org-mode does.
9867 This command can be called in any mode to follow a link that has
9868 Org-mode syntax."
9869 (interactive)
9870 (org-run-like-in-org-mode 'org-open-at-point))
9872 ;;;###autoload
9873 (defun org-open-link-from-string (s &optional arg reference-buffer)
9874 "Open a link in the string S, as if it was in Org-mode."
9875 (interactive "sLink: \nP")
9876 (let ((reference-buffer (or reference-buffer (current-buffer))))
9877 (with-temp-buffer
9878 (let ((org-inhibit-startup (not reference-buffer)))
9879 (org-mode)
9880 (insert s)
9881 (goto-char (point-min))
9882 (when reference-buffer
9883 (setq org-link-abbrev-alist-local
9884 (with-current-buffer reference-buffer
9885 org-link-abbrev-alist-local)))
9886 (org-open-at-point arg reference-buffer)))))
9888 (defvar org-open-at-point-functions nil
9889 "Hook that is run when following a link at point.
9891 Functions in this hook must return t if they identify and follow
9892 a link at point. If they don't find anything interesting at point,
9893 they must return nil.")
9895 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9896 (defun org-open-at-point (&optional arg reference-buffer)
9897 "Open link at or after point.
9898 If there is no link at point, this function will search forward up to
9899 the end of the current line.
9900 Normally, files will be opened by an appropriate application. If the
9901 optional prefix argument ARG is non-nil, Emacs will visit the file.
9902 With a double prefix argument, try to open outside of Emacs, in the
9903 application the system uses for this file type."
9904 (interactive "P")
9905 ;; if in a code block, then open the block's results
9906 (unless (call-interactively #'org-babel-open-src-block-result)
9907 (org-load-modules-maybe)
9908 (move-marker org-open-link-marker (point))
9909 (setq org-window-config-before-follow-link (current-window-configuration))
9910 (org-remove-occur-highlights nil nil t)
9911 (cond
9912 ((and (org-at-heading-p)
9913 (not (org-at-timestamp-p t))
9914 (not (org-in-regexp
9915 (concat org-plain-link-re "\\|"
9916 org-bracket-link-regexp "\\|"
9917 org-angle-link-re "\\|"
9918 "[ \t]:[^ \t\n]+:[ \t]*$")))
9919 (not (get-text-property (point) 'org-linked-text)))
9920 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9921 (lk0 (car lkall))
9922 (lk (if (stringp lk0) (list lk0) lk0))
9923 (lkend (cdr lkall)))
9924 (mapcar (lambda(l)
9925 (search-forward l nil lkend)
9926 (goto-char (match-beginning 0))
9927 (org-open-at-point))
9928 lk))
9929 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9930 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9931 ((and (org-at-timestamp-p t)
9932 (not (org-in-regexp org-bracket-link-regexp)))
9933 (org-follow-timestamp-link))
9934 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9935 (not (org-in-regexp org-any-link-re)))
9936 (org-footnote-action))
9938 (let (type path link line search (pos (point)))
9939 (catch 'match
9940 (save-excursion
9941 (skip-chars-forward "^]\n\r")
9942 (when (org-in-regexp org-bracket-link-regexp 1)
9943 (setq link (org-extract-attributes
9944 (org-link-unescape (org-match-string-no-properties 1))))
9945 (while (string-match " *\n *" link)
9946 (setq link (replace-match " " t t link)))
9947 (setq link (org-link-expand-abbrev link))
9948 (cond
9949 ((or (file-name-absolute-p link)
9950 (string-match "^\\.\\.?/" link))
9951 (setq type "file" path link))
9952 ((string-match org-link-re-with-space3 link)
9953 (setq type (match-string 1 link) path (match-string 2 link)))
9954 ((string-match "^help:+\\(.+\\)" link)
9955 (setq type "help" path (match-string 1 link)))
9956 (t (setq type "thisfile" path link)))
9957 (throw 'match t)))
9959 (when (get-text-property (point) 'org-linked-text)
9960 (setq type "thisfile"
9961 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9962 (1+ (point)) (point))
9963 path (buffer-substring
9964 (or (previous-single-property-change pos 'org-linked-text)
9965 (point-min))
9966 (or (next-single-property-change pos 'org-linked-text)
9967 (point-max))))
9968 (throw 'match t))
9970 (save-excursion
9971 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9972 (when (or (org-in-regexp org-angle-link-re)
9973 (and plinkpos (goto-char (car plinkpos))
9974 (save-match-data (not (looking-back "\\[\\[")))))
9975 (setq type (match-string 1)
9976 path (org-link-unescape (match-string 2)))
9977 (throw 'match t))))
9978 (save-excursion
9979 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9980 (setq type "tags"
9981 path (match-string 1))
9982 (while (string-match ":" path)
9983 (setq path (replace-match "+" t t path)))
9984 (throw 'match t)))
9985 (when (org-in-regexp "<\\([^><\n]+\\)>")
9986 (setq type "tree-match"
9987 path (match-string 1))
9988 (throw 'match t)))
9989 (unless path
9990 (user-error "No link found"))
9992 ;; switch back to reference buffer
9993 ;; needed when if called in a temporary buffer through
9994 ;; org-open-link-from-string
9995 (with-current-buffer (or reference-buffer (current-buffer))
9997 ;; Remove any trailing spaces in path
9998 (if (string-match " +\\'" path)
9999 (setq path (replace-match "" t t path)))
10000 (if (and org-link-translation-function
10001 (fboundp org-link-translation-function))
10002 ;; Check if we need to translate the link
10003 (let ((tmp (funcall org-link-translation-function type path)))
10004 (setq type (car tmp) path (cdr tmp))))
10006 (cond
10008 ((assoc type org-link-protocols)
10009 (funcall (nth 1 (assoc type org-link-protocols)) path))
10011 ((equal type "help")
10012 (let ((f-or-v (intern path)))
10013 (cond ((fboundp f-or-v)
10014 (describe-function f-or-v))
10015 ((boundp f-or-v)
10016 (describe-variable f-or-v))
10017 (t (error "Not a known function or variable")))))
10019 ((equal type "mailto")
10020 (let ((cmd (car org-link-mailto-program))
10021 (args (cdr org-link-mailto-program)) args1
10022 (address path) (subject "") a)
10023 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10024 (setq address (match-string 1 path)
10025 subject (org-link-escape (match-string 2 path))))
10026 (while args
10027 (cond
10028 ((not (stringp (car args))) (push (pop args) args1))
10029 (t (setq a (pop args))
10030 (if (string-match "%a" a)
10031 (setq a (replace-match address t t a)))
10032 (if (string-match "%s" a)
10033 (setq a (replace-match subject t t a)))
10034 (push a args1))))
10035 (apply cmd (nreverse args1))))
10037 ((member type '("http" "https" "ftp" "news"))
10038 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10039 (org-link-escape
10040 path org-link-escape-chars-browser)
10041 path))))
10043 ((string= type "doi")
10044 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10045 (org-link-escape
10046 path org-link-escape-chars-browser)
10047 path))))
10049 ((member type '("message"))
10050 (browse-url (concat type ":" path)))
10052 ((string= type "tags")
10053 (org-tags-view arg path))
10055 ((string= type "tree-match")
10056 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10058 ((string= type "file")
10059 (if (string-match "::\\([0-9]+\\)\\'" path)
10060 (setq line (string-to-number (match-string 1 path))
10061 path (substring path 0 (match-beginning 0)))
10062 (if (string-match "::\\(.+\\)\\'" path)
10063 (setq search (match-string 1 path)
10064 path (substring path 0 (match-beginning 0)))))
10065 (if (string-match "[*?{]" (file-name-nondirectory path))
10066 (dired path)
10067 (org-open-file path arg line search)))
10069 ((string= type "shell")
10070 (let ((buf (generate-new-buffer "*Org Shell Output"))
10071 (cmd path))
10072 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10073 (string-match org-confirm-shell-link-not-regexp cmd))
10074 (not org-confirm-shell-link-function)
10075 (funcall org-confirm-shell-link-function
10076 (format "Execute \"%s\" in shell? "
10077 (org-add-props cmd nil
10078 'face 'org-warning))))
10079 (progn
10080 (message "Executing %s" cmd)
10081 (shell-command cmd buf)
10082 (if (featurep 'midnight)
10083 (setq clean-buffer-list-kill-buffer-names
10084 (cons buf clean-buffer-list-kill-buffer-names))))
10085 (error "Abort"))))
10087 ((string= type "elisp")
10088 (let ((cmd path))
10089 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10090 (string-match org-confirm-elisp-link-not-regexp cmd))
10091 (not org-confirm-elisp-link-function)
10092 (funcall org-confirm-elisp-link-function
10093 (format "Execute \"%s\" as elisp? "
10094 (org-add-props cmd nil
10095 'face 'org-warning))))
10096 (message "%s => %s" cmd
10097 (if (equal (string-to-char cmd) ?\()
10098 (eval (read cmd))
10099 (call-interactively (read cmd))))
10100 (error "Abort"))))
10102 ((and (string= type "thisfile")
10103 (run-hook-with-args-until-success
10104 'org-open-link-functions path)))
10106 ((string= type "thisfile")
10107 (if arg
10108 (switch-to-buffer-other-window
10109 (org-get-buffer-for-internal-link (current-buffer)))
10110 (org-mark-ring-push))
10111 (let ((cmd `(org-link-search
10112 ,path
10113 ,(cond ((equal arg '(4)) ''occur)
10114 ((equal arg '(16)) ''org-occur))
10115 ,pos)))
10116 (condition-case nil (let ((org-link-search-inhibit-query t))
10117 (eval cmd))
10118 (error (progn (widen) (eval cmd))))))
10120 (t (browse-url-at-point)))))))
10121 (move-marker org-open-link-marker nil)
10122 (run-hook-with-args 'org-follow-link-hook)))
10124 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10125 "Offer links in the current entry and return the selected link.
10126 If there is only one link, return it.
10127 If NTH is an integer, return the NTH link found.
10128 If ZERO is a string, check also this string for a link, and if
10129 there is one, return it."
10130 (with-current-buffer buffer
10131 (save-excursion
10132 (save-restriction
10133 (widen)
10134 (goto-char marker)
10135 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10136 "\\(" org-angle-link-re "\\)\\|"
10137 "\\(" org-plain-link-re "\\)"))
10138 (cnt ?0)
10139 (in-emacs (if (integerp nth) nil nth))
10140 have-zero end links link c)
10141 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10142 (push (match-string 0 zero) links)
10143 (setq cnt (1- cnt) have-zero t))
10144 (save-excursion
10145 (org-back-to-heading t)
10146 (setq end (save-excursion (outline-next-heading) (point)))
10147 (while (re-search-forward re end t)
10148 (push (match-string 0) links))
10149 (setq links (org-uniquify (reverse links))))
10150 (cond
10151 ((null links)
10152 (message "No links"))
10153 ((equal (length links) 1)
10154 (setq link (car links)))
10155 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10156 (setq link (nth (if have-zero nth (1- nth)) links)))
10157 (t ; we have to select a link
10158 (save-excursion
10159 (save-window-excursion
10160 (delete-other-windows)
10161 (with-output-to-temp-buffer "*Select Link*"
10162 (mapc (lambda (l)
10163 (if (not (string-match org-bracket-link-regexp l))
10164 (princ (format "[%c] %s\n" (incf cnt)
10165 (org-remove-angle-brackets l)))
10166 (if (match-end 3)
10167 (princ (format "[%c] %s (%s)\n" (incf cnt)
10168 (match-string 3 l) (match-string 1 l)))
10169 (princ (format "[%c] %s\n" (incf cnt)
10170 (match-string 1 l))))))
10171 links))
10172 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10173 (message "Select link to open, RET to open all:")
10174 (setq c (read-char-exclusive))
10175 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10176 (when (equal c ?q) (error "Abort"))
10177 (if (equal c ?\C-m)
10178 (setq link links)
10179 (setq nth (- c ?0))
10180 (if have-zero (setq nth (1+ nth)))
10181 (unless (and (integerp nth) (>= (length links) nth))
10182 (error "Invalid link selection"))
10183 (setq link (nth (1- nth) links)))))
10184 (cons link end))))))
10186 ;; Add special file links that specify the way of opening
10188 (org-add-link-type "file+sys" 'org-open-file-with-system)
10189 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10190 (defun org-open-file-with-system (path)
10191 "Open file at PATH using the system way of opening it."
10192 (org-open-file path 'system))
10193 (defun org-open-file-with-emacs (path)
10194 "Open file at PATH in Emacs."
10195 (org-open-file path 'emacs))
10198 ;;; File search
10200 (defvar org-create-file-search-functions nil
10201 "List of functions to construct the right search string for a file link.
10202 These functions are called in turn with point at the location to
10203 which the link should point.
10205 A function in the hook should first test if it would like to
10206 handle this file type, for example by checking the `major-mode'
10207 or the file extension. If it decides not to handle this file, it
10208 should just return nil to give other functions a chance. If it
10209 does handle the file, it must return the search string to be used
10210 when following the link. The search string will be part of the
10211 file link, given after a double colon, and `org-open-at-point'
10212 will automatically search for it. If special measures must be
10213 taken to make the search successful, another function should be
10214 added to the companion hook `org-execute-file-search-functions',
10215 which see.
10217 A function in this hook may also use `setq' to set the variable
10218 `description' to provide a suggestion for the descriptive text to
10219 be used for this link when it gets inserted into an Org-mode
10220 buffer with \\[org-insert-link].")
10222 (defvar org-execute-file-search-functions nil
10223 "List of functions to execute a file search triggered by a link.
10225 Functions added to this hook must accept a single argument, the
10226 search string that was part of the file link, the part after the
10227 double colon. The function must first check if it would like to
10228 handle this search, for example by checking the `major-mode' or
10229 the file extension. If it decides not to handle this search, it
10230 should just return nil to give other functions a chance. If it
10231 does handle the search, it must return a non-nil value to keep
10232 other functions from trying.
10234 Each function can access the current prefix argument through the
10235 variable `current-prefix-argument'. Note that a single prefix is
10236 used to force opening a link in Emacs, so it may be good to only
10237 use a numeric or double prefix to guide the search function.
10239 In case this is needed, a function in this hook can also restore
10240 the window configuration before `org-open-at-point' was called using:
10242 (set-window-configuration org-window-config-before-follow-link)")
10244 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10245 (defun org-link-search (s &optional type avoid-pos stealth)
10246 "Search for a link search option.
10247 If S is surrounded by forward slashes, it is interpreted as a
10248 regular expression. In org-mode files, this will create an `org-occur'
10249 sparse tree. In ordinary files, `occur' will be used to list matches.
10250 If the current buffer is in `dired-mode', grep will be used to search
10251 in all files. If AVOID-POS is given, ignore matches near that position.
10253 When optional argument STEALTH is non-nil, do not modify
10254 visibility around point, thus ignoring
10255 `org-show-hierarchy-above', `org-show-following-heading' and
10256 `org-show-siblings' variables."
10257 (let ((case-fold-search t)
10258 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10259 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10260 (append '(("") (" ") ("\t") ("\n"))
10261 org-emphasis-alist)
10262 "\\|") "\\)"))
10263 (pos (point))
10264 (pre nil) (post nil)
10265 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10266 (cond
10267 ;; First check if there are any special search functions
10268 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10269 ;; Now try the builtin stuff
10270 ((and (equal (string-to-char s0) ?#)
10271 (> (length s0) 1)
10272 (save-excursion
10273 (goto-char (point-min))
10274 (and
10275 (re-search-forward
10276 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10277 (setq type 'dedicated
10278 pos (match-beginning 0))))
10279 ;; There is an exact target for this
10280 (goto-char pos)
10281 (org-back-to-heading t)))
10282 ((save-excursion
10283 (goto-char (point-min))
10284 (and
10285 (re-search-forward
10286 (concat "<<" (regexp-quote s0) ">>") nil t)
10287 (setq type 'dedicated
10288 pos (match-beginning 0))))
10289 ;; There is an exact target for this
10290 (goto-char pos))
10291 ((save-excursion
10292 (goto-char (point-min))
10293 (and
10294 (re-search-forward
10295 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10296 (setq type 'dedicated pos (match-beginning 0))))
10297 ;; Found an invisible target.
10298 (goto-char pos))
10299 ((save-excursion
10300 (goto-char (point-min))
10301 (and
10302 (re-search-forward
10303 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10304 (setq type 'dedicated pos (match-beginning 0))))
10305 ;; Found an element with a matching #+name affiliated keyword.
10306 (goto-char pos))
10307 ((and (string-match "^(\\(.*\\))$" s0)
10308 (save-excursion
10309 (goto-char (point-min))
10310 (and
10311 (re-search-forward
10312 (concat "[^[]" (regexp-quote
10313 (format org-coderef-label-format
10314 (match-string 1 s0))))
10315 nil t)
10316 (setq type 'dedicated
10317 pos (1+ (match-beginning 0))))))
10318 ;; There is a coderef target for this
10319 (goto-char pos))
10320 ((string-match "^/\\(.*\\)/$" s)
10321 ;; A regular expression
10322 (cond
10323 ((derived-mode-p 'org-mode)
10324 (org-occur (match-string 1 s)))
10325 ;;((eq major-mode 'dired-mode)
10326 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10327 (t (org-do-occur (match-string 1 s)))))
10328 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10329 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10330 (goto-char (point-min))
10331 (cond
10332 ((let (case-fold-search)
10333 (re-search-forward (format org-complex-heading-regexp-format
10334 (regexp-quote s))
10335 nil t))
10336 ;; OK, found a match
10337 (setq type 'dedicated)
10338 (goto-char (match-beginning 0)))
10339 ((and (not org-link-search-inhibit-query)
10340 (eq org-link-search-must-match-exact-headline 'query-to-create)
10341 (y-or-n-p "No match - create this as a new heading? "))
10342 (goto-char (point-max))
10343 (or (bolp) (newline))
10344 (insert "* " s "\n")
10345 (beginning-of-line 0))
10347 (goto-char pos)
10348 (error "No match"))))
10350 ;; A normal search string
10351 (when (equal (string-to-char s) ?*)
10352 ;; Anchor on headlines, post may include tags.
10353 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10354 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10355 s (substring s 1)))
10356 (remove-text-properties
10357 0 (length s)
10358 '(face nil mouse-face nil keymap nil fontified nil) s)
10359 ;; Make a series of regular expressions to find a match
10360 (setq words (org-split-string s "[ \n\r\t]+")
10362 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10363 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10364 "\\)" markers)
10365 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10366 re2a (concat "[ \t\r\n]" re2a_)
10367 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10368 re4 (concat "[^a-zA-Z_]" re4_)
10370 re1 (concat pre re2 post)
10371 re3 (concat pre (if pre re4_ re4) post)
10372 re5 (concat pre ".*" re4)
10373 re2 (concat pre re2)
10374 re2a (concat pre (if pre re2a_ re2a))
10375 re4 (concat pre (if pre re4_ re4))
10376 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10377 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10378 re5 "\\)"
10380 (cond
10381 ((eq type 'org-occur) (org-occur reall))
10382 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10383 (t (goto-char (point-min))
10384 (setq type 'fuzzy)
10385 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10386 (org-search-not-self 1 re1 nil t)
10387 (org-search-not-self 1 re2 nil t)
10388 (org-search-not-self 1 re2a nil t)
10389 (org-search-not-self 1 re3 nil t)
10390 (org-search-not-self 1 re4 nil t)
10391 (org-search-not-self 1 re5 nil t)
10393 (goto-char (match-beginning 1))
10394 (goto-char pos)
10395 (error "No match"))))))
10396 (and (derived-mode-p 'org-mode)
10397 (not stealth)
10398 (org-show-context 'link-search))
10399 type))
10401 (defun org-search-not-self (group &rest args)
10402 "Execute `re-search-forward', but only accept matches that do not
10403 enclose the position of `org-open-link-marker'."
10404 (let ((m org-open-link-marker))
10405 (catch 'exit
10406 (while (apply 're-search-forward args)
10407 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10408 (goto-char (match-end group))
10409 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10410 (> (match-beginning 0) (marker-position m))
10411 (< (match-end 0) (marker-position m)))
10412 (save-match-data
10413 (or (not (org-in-regexp
10414 org-bracket-link-analytic-regexp 1))
10415 (not (match-end 4)) ; no description
10416 (and (<= (match-beginning 4) (point))
10417 (>= (match-end 4) (point))))))
10418 (throw 'exit (point))))))))
10420 (defun org-get-buffer-for-internal-link (buffer)
10421 "Return a buffer to be used for displaying the link target of internal links."
10422 (cond
10423 ((not org-display-internal-link-with-indirect-buffer)
10424 buffer)
10425 ((string-match "(Clone)$" (buffer-name buffer))
10426 (message "Buffer is already a clone, not making another one")
10427 ;; we also do not modify visibility in this case
10428 buffer)
10429 (t ; make a new indirect buffer for displaying the link
10430 (let* ((bn (buffer-name buffer))
10431 (ibn (concat bn "(Clone)"))
10432 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10433 (with-current-buffer ib (org-overview))
10434 ib))))
10436 (defun org-do-occur (regexp &optional cleanup)
10437 "Call the Emacs command `occur'.
10438 If CLEANUP is non-nil, remove the printout of the regular expression
10439 in the *Occur* buffer. This is useful if the regex is long and not useful
10440 to read."
10441 (occur regexp)
10442 (when cleanup
10443 (let ((cwin (selected-window)) win beg end)
10444 (when (setq win (get-buffer-window "*Occur*"))
10445 (select-window win))
10446 (goto-char (point-min))
10447 (when (re-search-forward "match[a-z]+" nil t)
10448 (setq beg (match-end 0))
10449 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10450 (setq end (1- (match-beginning 0)))))
10451 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10452 (goto-char (point-min))
10453 (select-window cwin))))
10455 ;;; The mark ring for links jumps
10457 (defvar org-mark-ring nil
10458 "Mark ring for positions before jumps in Org-mode.")
10459 (defvar org-mark-ring-last-goto nil
10460 "Last position in the mark ring used to go back.")
10461 ;; Fill and close the ring
10462 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10463 (loop for i from 1 to org-mark-ring-length do
10464 (push (make-marker) org-mark-ring))
10465 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10466 org-mark-ring)
10468 (defun org-mark-ring-push (&optional pos buffer)
10469 "Put the current position or POS into the mark ring and rotate it."
10470 (interactive)
10471 (setq pos (or pos (point)))
10472 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10473 (move-marker (car org-mark-ring)
10474 (or pos (point))
10475 (or buffer (current-buffer)))
10476 (message "%s"
10477 (substitute-command-keys
10478 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10480 (defun org-mark-ring-goto (&optional n)
10481 "Jump to the previous position in the mark ring.
10482 With prefix arg N, jump back that many stored positions. When
10483 called several times in succession, walk through the entire ring.
10484 Org-mode commands jumping to a different position in the current file,
10485 or to another Org-mode file, automatically push the old position
10486 onto the ring."
10487 (interactive "p")
10488 (let (p m)
10489 (if (eq last-command this-command)
10490 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10491 (setq p org-mark-ring))
10492 (setq org-mark-ring-last-goto p)
10493 (setq m (car p))
10494 (org-pop-to-buffer-same-window (marker-buffer m))
10495 (goto-char m)
10496 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10498 (defun org-remove-angle-brackets (s)
10499 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10500 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10502 (defun org-add-angle-brackets (s)
10503 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10504 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10506 (defun org-remove-double-quotes (s)
10507 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10508 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10511 ;;; Following specific links
10513 (defun org-follow-timestamp-link ()
10514 "Open an agenda view for the time-stamp date/range at point."
10515 (cond
10516 ((org-at-date-range-p t)
10517 (let ((org-agenda-start-on-weekday)
10518 (t1 (match-string 1))
10519 (t2 (match-string 2)) tt1 tt2)
10520 (setq tt1 (time-to-days (org-time-string-to-time t1))
10521 tt2 (time-to-days (org-time-string-to-time t2)))
10522 (let ((org-agenda-buffer-tmp-name
10523 (format "*Org Agenda(a:%s)"
10524 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10525 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10526 ((org-at-timestamp-p t)
10527 (let ((org-agenda-buffer-tmp-name
10528 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10529 (org-agenda-list nil (time-to-days (org-time-string-to-time
10530 (substring (match-string 1) 0 10)))
10531 1)))
10532 (t (error "This should not happen"))))
10535 ;;; Following file links
10536 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10537 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10538 (declare-function mailcap-mime-info
10539 "mailcap" (string &optional request no-decode))
10540 (defvar org-wait nil)
10541 (defun org-open-file (path &optional in-emacs line search)
10542 "Open the file at PATH.
10543 First, this expands any special file name abbreviations. Then the
10544 configuration variable `org-file-apps' is checked if it contains an
10545 entry for this file type, and if yes, the corresponding command is launched.
10547 If no application is found, Emacs simply visits the file.
10549 With optional prefix argument IN-EMACS, Emacs will visit the file.
10550 With a double \\[universal-argument] \\[universal-argument] \
10551 prefix arg, Org tries to avoid opening in Emacs
10552 and to use an external application to visit the file.
10554 Optional LINE specifies a line to go to, optional SEARCH a string
10555 to search for. If LINE or SEARCH is given, the file will be
10556 opened in Emacs, unless an entry from org-file-apps that makes
10557 use of groups in a regexp matches.
10559 If you want to change the way frames are used when following a
10560 link, please customize `org-link-frame-setup'.
10562 If the file does not exist, an error is thrown."
10563 (let* ((file (if (equal path "")
10564 buffer-file-name
10565 (substitute-in-file-name (expand-file-name path))))
10566 (file-apps (append org-file-apps (org-default-apps)))
10567 (apps (org-remove-if
10568 'org-file-apps-entry-match-against-dlink-p file-apps))
10569 (apps-dlink (org-remove-if-not
10570 'org-file-apps-entry-match-against-dlink-p file-apps))
10571 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10572 (dirp (if remp nil (file-directory-p file)))
10573 (file (if (and dirp org-open-directory-means-index-dot-org)
10574 (concat (file-name-as-directory file) "index.org")
10575 file))
10576 (a-m-a-p (assq 'auto-mode apps))
10577 (dfile (downcase file))
10578 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10579 (link (cond ((and (eq line nil)
10580 (eq search nil))
10581 file)
10582 (line
10583 (concat file "::" (number-to-string line)))
10584 (search
10585 (concat file "::" search))))
10586 (dlink (downcase link))
10587 (old-buffer (current-buffer))
10588 (old-pos (point))
10589 (old-mode major-mode)
10590 ext cmd link-match-data)
10591 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10592 (setq ext (match-string 1 dfile))
10593 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10594 (setq ext (match-string 1 dfile))))
10595 (cond
10596 ((member in-emacs '((16) system))
10597 (setq cmd (cdr (assoc 'system apps))))
10598 (in-emacs (setq cmd 'emacs))
10600 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10601 (and dirp (cdr (assoc 'directory apps)))
10602 ; first, try matching against apps-dlink
10603 ; if we get a match here, store the match data for later
10604 (let ((match (assoc-default dlink apps-dlink
10605 'string-match)))
10606 (if match
10607 (progn (setq link-match-data (match-data))
10608 match)
10609 (progn (setq in-emacs (or in-emacs line search))
10610 nil))) ; if we have no match in apps-dlink,
10611 ; always open the file in emacs if line or search
10612 ; is given (for backwards compatibility)
10613 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10614 'string-match)
10615 (cdr (assoc ext apps))
10616 (cdr (assoc t apps))))))
10617 (when (eq cmd 'system)
10618 (setq cmd (cdr (assoc 'system apps))))
10619 (when (eq cmd 'default)
10620 (setq cmd (cdr (assoc t apps))))
10621 (when (eq cmd 'mailcap)
10622 (require 'mailcap)
10623 (mailcap-parse-mailcaps)
10624 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10625 (command (mailcap-mime-info mime-type)))
10626 (if (stringp command)
10627 (setq cmd command)
10628 (setq cmd 'emacs))))
10629 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10630 (not (file-exists-p file))
10631 (not org-open-non-existing-files))
10632 (error "No such file: %s" file))
10633 (cond
10634 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10635 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10636 (while (string-match "['\"]%s['\"]" cmd)
10637 (setq cmd (replace-match "%s" t t cmd)))
10638 (while (string-match "%s" cmd)
10639 (setq cmd (replace-match
10640 (save-match-data
10641 (shell-quote-argument
10642 (convert-standard-filename file)))
10643 t t cmd)))
10645 ;; Replace "%1", "%2" etc. in command with group matches from regex
10646 (save-match-data
10647 (let ((match-index 1)
10648 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10649 (set-match-data link-match-data)
10650 (while (<= match-index number-of-groups)
10651 (let ((regex (concat "%" (number-to-string match-index)))
10652 (replace-with (match-string match-index dlink)))
10653 (while (string-match regex cmd)
10654 (setq cmd (replace-match replace-with t t cmd))))
10655 (setq match-index (+ match-index 1)))))
10657 (save-window-excursion
10658 (message "Running %s...done" cmd)
10659 (start-process-shell-command cmd nil cmd)
10660 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10661 ((or (stringp cmd)
10662 (eq cmd 'emacs))
10663 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10664 (widen)
10665 (if line (org-goto-line line)
10666 (if search (org-link-search search))))
10667 ((consp cmd)
10668 (let ((file (convert-standard-filename file)))
10669 (save-match-data
10670 (set-match-data link-match-data)
10671 (eval cmd))))
10672 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10673 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10674 (or (not (equal old-buffer (current-buffer)))
10675 (not (equal old-pos (point))))
10676 (org-mark-ring-push old-pos old-buffer))))
10678 (defun org-file-apps-entry-match-against-dlink-p (entry)
10679 "This function returns non-nil if `entry' uses a regular
10680 expression which should be matched against the whole link by
10681 org-open-file.
10683 It assumes that is the case when the entry uses a regular
10684 expression which has at least one grouping construct and the
10685 action is either a lisp form or a command string containing
10686 '%1', i.e. using at least one subexpression match as a
10687 parameter."
10688 (let ((selector (car entry))
10689 (action (cdr entry)))
10690 (if (stringp selector)
10691 (and (> (regexp-opt-depth selector) 0)
10692 (or (and (stringp action)
10693 (string-match "%[0-9]" action))
10694 (consp action)))
10695 nil)))
10697 (defun org-default-apps ()
10698 "Return the default applications for this operating system."
10699 (cond
10700 ((eq system-type 'darwin)
10701 org-file-apps-defaults-macosx)
10702 ((eq system-type 'windows-nt)
10703 org-file-apps-defaults-windowsnt)
10704 (t org-file-apps-defaults-gnu)))
10706 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10707 "Convert extensions to regular expressions in the cars of LIST.
10708 Also, weed out any non-string entries, because the return value is used
10709 only for regexp matching.
10710 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10711 point to the symbol `emacs', indicating that the file should
10712 be opened in Emacs."
10713 (append
10714 (delq nil
10715 (mapcar (lambda (x)
10716 (if (not (stringp (car x)))
10718 (if (string-match "\\W" (car x))
10720 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10721 list))
10722 (if add-auto-mode
10723 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10725 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10726 (defun org-file-remote-p (file)
10727 "Test whether FILE specifies a location on a remote system.
10728 Return non-nil if the location is indeed remote.
10730 For example, the filename \"/user@host:/foo\" specifies a location
10731 on the system \"/user@host:\"."
10732 (cond ((fboundp 'file-remote-p)
10733 (file-remote-p file))
10734 ((fboundp 'tramp-handle-file-remote-p)
10735 (tramp-handle-file-remote-p file))
10736 ((and (boundp 'ange-ftp-name-format)
10737 (string-match (car ange-ftp-name-format) file))
10738 t)))
10741 ;;;; Refiling
10743 (defun org-get-org-file ()
10744 "Read a filename, with default directory `org-directory'."
10745 (let ((default (or org-default-notes-file remember-data-file)))
10746 (read-file-name (format "File name [%s]: " default)
10747 (file-name-as-directory org-directory)
10748 default)))
10750 (defun org-notes-order-reversed-p ()
10751 "Check if the current file should receive notes in reversed order."
10752 (cond
10753 ((not org-reverse-note-order) nil)
10754 ((eq t org-reverse-note-order) t)
10755 ((not (listp org-reverse-note-order)) nil)
10756 (t (catch 'exit
10757 (let ((all org-reverse-note-order)
10758 entry)
10759 (while (setq entry (pop all))
10760 (if (string-match (car entry) buffer-file-name)
10761 (throw 'exit (cdr entry))))
10762 nil)))))
10764 (defvar org-refile-target-table nil
10765 "The list of refile targets, created by `org-refile'.")
10767 (defvar org-agenda-new-buffers nil
10768 "Buffers created to visit agenda files.")
10770 (defvar org-refile-cache nil
10771 "Cache for refile targets.")
10773 (defvar org-refile-markers nil
10774 "All the markers used for caching refile locations.")
10776 (defun org-refile-marker (pos)
10777 "Get a new refile marker, but only if caching is in use."
10778 (if (not org-refile-use-cache)
10780 (let ((m (make-marker)))
10781 (move-marker m pos)
10782 (push m org-refile-markers)
10783 m)))
10785 (defun org-refile-cache-clear ()
10786 "Clear the refile cache and disable all the markers."
10787 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10788 (setq org-refile-markers nil)
10789 (setq org-refile-cache nil)
10790 (message "Refile cache has been cleared"))
10792 (defun org-refile-cache-check-set (set)
10793 "Check if all the markers in the cache still have live buffers."
10794 (let (marker)
10795 (catch 'exit
10796 (while (and set (setq marker (nth 3 (pop set))))
10797 ;; if org-refile-use-outline-path is 'file, marker may be nil
10798 (when (and marker (null (marker-buffer marker)))
10799 (message "not found") (sit-for 3)
10800 (throw 'exit nil)))
10801 t)))
10803 (defun org-refile-cache-put (set &rest identifiers)
10804 "Push the refile targets SET into the cache, under IDENTIFIERS."
10805 (let* ((key (sha1 (prin1-to-string identifiers)))
10806 (entry (assoc key org-refile-cache)))
10807 (if entry
10808 (setcdr entry set)
10809 (push (cons key set) org-refile-cache))))
10811 (defun org-refile-cache-get (&rest identifiers)
10812 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10813 (cond
10814 ((not org-refile-cache) nil)
10815 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10817 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10818 org-refile-cache))))
10819 (and set (org-refile-cache-check-set set) set)))))
10821 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10822 "Produce a table with refile targets."
10823 (let ((case-fold-search nil)
10824 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10825 (entries (or org-refile-targets '((nil . (:level . 1)))))
10826 targets tgs txt re files f desc descre fast-path-p level pos0)
10827 (message "Getting targets...")
10828 (with-current-buffer (or default-buffer (current-buffer))
10829 (while (setq entry (pop entries))
10830 (setq files (car entry) desc (cdr entry))
10831 (setq fast-path-p nil)
10832 (cond
10833 ((null files) (setq files (list (current-buffer))))
10834 ((eq files 'org-agenda-files)
10835 (setq files (org-agenda-files 'unrestricted)))
10836 ((and (symbolp files) (fboundp files))
10837 (setq files (funcall files)))
10838 ((and (symbolp files) (boundp files))
10839 (setq files (symbol-value files))))
10840 (if (stringp files) (setq files (list files)))
10841 (cond
10842 ((eq (car desc) :tag)
10843 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10844 ((eq (car desc) :todo)
10845 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10846 ((eq (car desc) :regexp)
10847 (setq descre (cdr desc)))
10848 ((eq (car desc) :level)
10849 (setq descre (concat "^\\*\\{" (number-to-string
10850 (if org-odd-levels-only
10851 (1- (* 2 (cdr desc)))
10852 (cdr desc)))
10853 "\\}[ \t]")))
10854 ((eq (car desc) :maxlevel)
10855 (setq fast-path-p t)
10856 (setq descre (concat "^\\*\\{1," (number-to-string
10857 (if org-odd-levels-only
10858 (1- (* 2 (cdr desc)))
10859 (cdr desc)))
10860 "\\}[ \t]")))
10861 (t (error "Bad refiling target description %s" desc)))
10862 (while (setq f (pop files))
10863 (with-current-buffer
10864 (if (bufferp f) f (org-get-agenda-file-buffer f))
10866 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10867 (progn
10868 (if (bufferp f) (setq f (buffer-file-name
10869 (buffer-base-buffer f))))
10870 (setq f (and f (expand-file-name f)))
10871 (if (eq org-refile-use-outline-path 'file)
10872 (push (list (file-name-nondirectory f) f nil nil) tgs))
10873 (save-excursion
10874 (save-restriction
10875 (widen)
10876 (goto-char (point-min))
10877 (while (re-search-forward descre nil t)
10878 (goto-char (setq pos0 (point-at-bol)))
10879 (catch 'next
10880 (when org-refile-target-verify-function
10881 (save-match-data
10882 (or (funcall org-refile-target-verify-function)
10883 (throw 'next t))))
10884 (when (and (looking-at org-complex-heading-regexp)
10885 (not (member (match-string 4) excluded-entries))
10886 (match-string 4))
10887 (setq level (org-reduced-level
10888 (- (match-end 1) (match-beginning 1)))
10889 txt (org-link-display-format (match-string 4))
10890 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10891 re (format org-complex-heading-regexp-format
10892 (regexp-quote (match-string 4))))
10893 (when org-refile-use-outline-path
10894 (setq txt (mapconcat
10895 'org-protect-slash
10896 (append
10897 (if (eq org-refile-use-outline-path
10898 'file)
10899 (list (file-name-nondirectory
10900 (buffer-file-name
10901 (buffer-base-buffer))))
10902 (if (eq org-refile-use-outline-path
10903 'full-file-path)
10904 (list (buffer-file-name
10905 (buffer-base-buffer)))))
10906 (org-get-outline-path fast-path-p
10907 level txt)
10908 (list txt))
10909 "/")))
10910 (push (list txt f re (org-refile-marker (point)))
10911 tgs)))
10912 (when (= (point) pos0)
10913 ;; verification function has not moved point
10914 (goto-char (point-at-eol))))))))
10915 (when org-refile-use-cache
10916 (org-refile-cache-put tgs (buffer-file-name) descre))
10917 (setq targets (append tgs targets))
10918 ))))
10919 (message "Getting targets...done")
10920 (nreverse targets)))
10922 (defun org-protect-slash (s)
10923 (while (string-match "/" s)
10924 (setq s (replace-match "\\" t t s)))
10927 (defvar org-olpa (make-vector 20 nil))
10929 (defun org-get-outline-path (&optional fastp level heading)
10930 "Return the outline path to the current entry, as a list.
10932 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10933 routine which makes outline path derivations for an entire file,
10934 avoiding backtracing. Refile target collection makes use of that."
10935 (if fastp
10936 (progn
10937 (if (> level 19)
10938 (error "Outline path failure, more than 19 levels"))
10939 (loop for i from level upto 19 do
10940 (aset org-olpa i nil))
10941 (prog1
10942 (delq nil (append org-olpa nil))
10943 (aset org-olpa level heading)))
10944 (let (rtn case-fold-search)
10945 (save-excursion
10946 (save-restriction
10947 (widen)
10948 (while (org-up-heading-safe)
10949 (when (looking-at org-complex-heading-regexp)
10950 (push (org-match-string-no-properties 4) rtn)))
10951 rtn)))))
10953 (defun org-format-outline-path (path &optional width prefix separator)
10954 "Format the outline path PATH for display.
10955 WIDTH is the maximum number of characters that is available.
10956 PREFIX is a prefix to be included in the returned string,
10957 such as the file name.
10958 SEPARATOR is inserted between the different parts of the path,
10959 the default is \"/\"."
10960 (setq width (or width 79))
10961 (if prefix (setq width (- width (length prefix))))
10962 (if (not path)
10963 (or prefix "")
10964 (let* ((nsteps (length path))
10965 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10966 (maxwidth (if (<= total-width width)
10967 10000 ;; everything fits
10968 ;; we need to shorten the level headings
10969 (/ (- width nsteps) nsteps)))
10970 (org-odd-levels-only nil)
10971 (n 0)
10972 (total (1+ (length prefix))))
10973 (setq maxwidth (max maxwidth 10))
10974 (concat prefix
10975 (if prefix (or separator "/"))
10976 (mapconcat
10977 (lambda (h)
10978 (setq n (1+ n))
10979 (if (and (= n nsteps) (< maxwidth 10000))
10980 (setq maxwidth (- total-width total)))
10981 (if (< (length h) maxwidth)
10982 (progn (setq total (+ total (length h) 1)) h)
10983 (setq h (substring h 0 (- maxwidth 2))
10984 total (+ total maxwidth 1))
10985 (if (string-match "[ \t]+\\'" h)
10986 (setq h (substring h 0 (match-beginning 0))))
10987 (setq h (concat h "..")))
10988 (org-add-props h nil 'face
10989 (nth (% (1- n) org-n-level-faces)
10990 org-level-faces))
10992 path (or separator "/"))))))
10994 (defun org-display-outline-path (&optional file current separator just-return-string)
10995 "Display the current outline path in the echo area.
10997 If FILE is non-nil, prepend the output with the file name.
10998 If CURRENT is non-nil, append the current heading to the output.
10999 SEPARATOR is passed through to `org-format-outline-path'. It separates
11000 the different parts of the path and defaults to \"/\".
11001 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11002 (interactive "P")
11003 (let* (case-fold-search
11004 message-log-max ; Don't populate the *Messages* buffer
11005 (bfn (buffer-file-name (buffer-base-buffer)))
11006 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11007 res)
11008 (if current (setq path (append path
11009 (save-excursion
11010 (org-back-to-heading t)
11011 (if (looking-at org-complex-heading-regexp)
11012 (list (match-string 4)))))))
11013 (setq res
11014 (org-format-outline-path
11015 path
11016 (1- (frame-width))
11017 (and file bfn (concat (file-name-nondirectory bfn) separator))
11018 separator))
11019 (if just-return-string
11020 (org-no-properties res)
11021 (message "%s" res))))
11023 (defvar org-refile-history nil
11024 "History for refiling operations.")
11026 (defvar org-after-refile-insert-hook nil
11027 "Hook run after `org-refile' has inserted its stuff at the new location.
11028 Note that this is still *before* the stuff will be removed from
11029 the *old* location.")
11031 (defvar org-capture-last-stored-marker)
11032 (defvar org-refile-keep nil
11033 "Non-nil means `org-refile' will copy instead of refile.")
11035 (defun org-copy ()
11036 "Like `org-refile', but copy."
11037 (interactive)
11038 (let ((org-refile-keep t))
11039 (funcall 'org-refile nil nil nil "Copy")))
11041 (defun org-refile (&optional goto default-buffer rfloc msg)
11042 "Move the entry or entries at point to another heading.
11043 The list of target headings is compiled using the information in
11044 `org-refile-targets', which see.
11046 At the target location, the entry is filed as a subitem of the target
11047 heading. Depending on `org-reverse-note-order', the new subitem will
11048 either be the first or the last subitem.
11050 If there is an active region, all entries in that region will be moved.
11051 However, the region must fulfill the requirement that the first heading
11052 is the first one sets the top-level of the moved text - at most siblings
11053 below it are allowed.
11055 With prefix arg GOTO, the command will only visit the target location
11056 and not actually move anything.
11058 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11059 go to the location where the last refiling operation has put the subtree.
11060 With a prefix argument of `2', refile to the running clock.
11062 RFLOC can be a refile location obtained in a different way.
11064 MSG is a string to replace \"Refile\" in the default prompt with
11065 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11067 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11069 If you are using target caching (see `org-refile-use-cache'),
11070 you have to clear the target cache in order to find new targets.
11071 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11072 prefix argument (`C-u C-u C-u C-c C-w')."
11074 (interactive "P")
11075 (if (member goto '(0 (64)))
11076 (org-refile-cache-clear)
11077 (let* ((actionmsg (or msg "Refile"))
11078 (cbuf (current-buffer))
11079 (regionp (org-region-active-p))
11080 (region-start (and regionp (region-beginning)))
11081 (region-end (and regionp (region-end)))
11082 (region-length (and regionp (- region-end region-start)))
11083 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11084 pos it nbuf file re level reversed)
11085 (setq last-command nil)
11086 (when regionp
11087 (goto-char region-start)
11088 (or (bolp) (goto-char (point-at-bol)))
11089 (setq region-start (point))
11090 (unless (or (org-kill-is-subtree-p
11091 (buffer-substring region-start region-end))
11092 (prog1 org-refile-active-region-within-subtree
11093 (org-toggle-heading)))
11094 (error "The region is not a (sequence of) subtree(s)")))
11095 (if (equal goto '(16))
11096 (org-refile-goto-last-stored)
11097 (when (or
11098 (and (equal goto 2)
11099 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11100 (prog1
11101 (setq it (list (or org-clock-heading "running clock")
11102 (buffer-file-name
11103 (marker-buffer org-clock-hd-marker))
11105 (marker-position org-clock-hd-marker)))
11106 (setq goto nil)))
11107 (setq it (or rfloc
11108 (let (heading-text)
11109 (save-excursion
11110 (unless goto
11111 (org-back-to-heading t)
11112 (setq heading-text
11113 (nth 4 (org-heading-components))))
11115 (org-refile-get-location
11116 (cond (goto "Goto")
11117 (regionp (concat actionmsg " region to"))
11118 (t (concat actionmsg " subtree \""
11119 heading-text "\" to")))
11120 default-buffer
11121 (and (not (equal '(4) goto))
11122 org-refile-allow-creating-parent-nodes)
11123 goto))))))
11124 (setq file (nth 1 it)
11125 re (nth 2 it)
11126 pos (nth 3 it))
11127 (if (and (not goto)
11129 (equal (buffer-file-name) file)
11130 (if regionp
11131 (and (>= pos region-start)
11132 (<= pos region-end))
11133 (and (>= pos (point))
11134 (< pos (save-excursion
11135 (org-end-of-subtree t t))))))
11136 (error "Cannot refile to position inside the tree or region"))
11138 (setq nbuf (or (find-buffer-visiting file)
11139 (find-file-noselect file)))
11140 (if goto
11141 (progn
11142 (org-pop-to-buffer-same-window nbuf)
11143 (goto-char pos)
11144 (org-show-context 'org-goto))
11145 (if regionp
11146 (progn
11147 (org-kill-new (buffer-substring region-start region-end))
11148 (org-save-markers-in-region region-start region-end))
11149 (org-copy-subtree 1 nil t))
11150 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11151 (find-file-noselect file)))
11152 (setq reversed (org-notes-order-reversed-p))
11153 (save-excursion
11154 (save-restriction
11155 (widen)
11156 (if pos
11157 (progn
11158 (goto-char pos)
11159 (looking-at org-outline-regexp)
11160 (setq level (org-get-valid-level (funcall outline-level) 1))
11161 (goto-char
11162 (if reversed
11163 (or (outline-next-heading) (point-max))
11164 (or (save-excursion (org-get-next-sibling))
11165 (org-end-of-subtree t t)
11166 (point-max)))))
11167 (setq level 1)
11168 (if (not reversed)
11169 (goto-char (point-max))
11170 (goto-char (point-min))
11171 (or (outline-next-heading) (goto-char (point-max)))))
11172 (if (not (bolp)) (newline))
11173 (org-paste-subtree level)
11174 (when org-log-refile
11175 (org-add-log-setup 'refile nil nil 'findpos
11176 org-log-refile)
11177 (unless (eq org-log-refile 'note)
11178 (save-excursion (org-add-log-note))))
11179 (and org-auto-align-tags
11180 (let ((org-loop-over-headlines-in-active-region nil))
11181 (org-set-tags nil t)))
11182 (with-demoted-errors
11183 (bookmark-set "org-refile-last-stored"))
11184 ;; If we are refiling for capture, make sure that the
11185 ;; last-capture pointers point here
11186 (when (org-bound-and-true-p org-refile-for-capture)
11187 (with-demoted-errors
11188 (bookmark-set "org-capture-last-stored-marker"))
11189 (move-marker org-capture-last-stored-marker (point)))
11190 (if (fboundp 'deactivate-mark) (deactivate-mark))
11191 (run-hooks 'org-after-refile-insert-hook))))
11192 (unless org-refile-keep
11193 (if regionp
11194 (delete-region (point) (+ (point) region-length))
11195 (org-cut-subtree)))
11196 (when (featurep 'org-inlinetask)
11197 (org-inlinetask-remove-END-maybe))
11198 (setq org-markers-to-move nil)
11199 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11201 (defun org-refile-goto-last-stored ()
11202 "Go to the location where the last refile was stored."
11203 (interactive)
11204 (bookmark-jump "org-refile-last-stored")
11205 (message "This is the location of the last refile"))
11207 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11208 no-exclude)
11209 "Prompt the user for a refile location, using PROMPT.
11210 PROMPT should not be suffixed with a colon and a space, because
11211 this function appends the default value from
11212 `org-refile-history' automatically, if that is not empty.
11213 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11214 this is used for the GOTO interface."
11215 (let ((org-refile-targets org-refile-targets)
11216 (org-refile-use-outline-path org-refile-use-outline-path)
11217 excluded-entries)
11218 (when (and (derived-mode-p 'org-mode)
11219 (not org-refile-use-cache)
11220 (not no-exclude))
11221 (org-map-tree
11222 (lambda()
11223 (setq excluded-entries
11224 (append excluded-entries (list (org-get-heading t t)))))))
11225 (setq org-refile-target-table
11226 (org-refile-get-targets default-buffer excluded-entries)))
11227 (unless org-refile-target-table
11228 (error "No refile targets"))
11229 (let* ((cbuf (current-buffer))
11230 (partial-completion-mode nil)
11231 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11232 (cfunc (if (and org-refile-use-outline-path
11233 org-outline-path-complete-in-steps)
11234 'org-olpath-completing-read
11235 'org-icompleting-read))
11236 (extra (if org-refile-use-outline-path "/" ""))
11237 (cbnex (concat (buffer-name) extra))
11238 (filename (and cfn (expand-file-name cfn)))
11239 (tbl (mapcar
11240 (lambda (x)
11241 (if (and (not (member org-refile-use-outline-path
11242 '(file full-file-path)))
11243 (not (equal filename (nth 1 x))))
11244 (cons (concat (car x) extra " ("
11245 (file-name-nondirectory (nth 1 x)) ")")
11246 (cdr x))
11247 (cons (concat (car x) extra) (cdr x))))
11248 org-refile-target-table))
11249 (completion-ignore-case t)
11250 cdef
11251 (prompt (concat prompt
11252 (or (and (car org-refile-history)
11253 (concat " (default " (car org-refile-history) ")"))
11254 (and (assoc cbnex tbl) (setq cdef cbnex)
11255 (concat " (default " cbnex ")"))) ": "))
11256 pa answ parent-target child parent old-hist)
11257 (setq old-hist org-refile-history)
11258 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11259 nil 'org-refile-history (or cdef (car org-refile-history))))
11260 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11261 (org-refile-check-position pa)
11262 (if pa
11263 (progn
11264 (when (or (not org-refile-history)
11265 (not (eq old-hist org-refile-history))
11266 (not (equal (car pa) (car org-refile-history))))
11267 (setq org-refile-history
11268 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11269 org-refile-history
11270 (cdr org-refile-history))))
11271 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11272 (pop org-refile-history)))
11274 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11275 (progn
11276 (setq parent (match-string 1 answ)
11277 child (match-string 2 answ))
11278 (setq parent-target (or (assoc parent tbl)
11279 (assoc (concat parent "/") tbl)))
11280 (when (and parent-target
11281 (or (eq new-nodes t)
11282 (and (eq new-nodes 'confirm)
11283 (y-or-n-p (format "Create new node \"%s\"? "
11284 child)))))
11285 (org-refile-new-child parent-target child)))
11286 (error "Invalid target location")))))
11288 (declare-function org-string-nw-p "org-macs" (s))
11289 (defun org-refile-check-position (refile-pointer)
11290 "Check if the refile pointer matches the headline to which it points."
11291 (let* ((file (nth 1 refile-pointer))
11292 (re (nth 2 refile-pointer))
11293 (pos (nth 3 refile-pointer))
11294 buffer)
11295 (if (and (not (markerp pos)) (not file))
11296 (error "Please save the buffer to a file before refiling")
11297 (when (org-string-nw-p re)
11298 (setq buffer (if (markerp pos)
11299 (marker-buffer pos)
11300 (or (find-buffer-visiting file)
11301 (find-file-noselect file))))
11302 (with-current-buffer buffer
11303 (save-excursion
11304 (save-restriction
11305 (widen)
11306 (goto-char pos)
11307 (beginning-of-line 1)
11308 (unless (org-looking-at-p re)
11309 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11311 (defun org-refile-new-child (parent-target child)
11312 "Use refile target PARENT-TARGET to add new CHILD below it."
11313 (unless parent-target
11314 (error "Cannot find parent for new node"))
11315 (let ((file (nth 1 parent-target))
11316 (pos (nth 3 parent-target))
11317 level)
11318 (with-current-buffer (or (find-buffer-visiting file)
11319 (find-file-noselect file))
11320 (save-excursion
11321 (save-restriction
11322 (widen)
11323 (if pos
11324 (goto-char pos)
11325 (goto-char (point-max))
11326 (if (not (bolp)) (newline)))
11327 (when (looking-at org-outline-regexp)
11328 (setq level (funcall outline-level))
11329 (org-end-of-subtree t t))
11330 (org-back-over-empty-lines)
11331 (insert "\n" (make-string
11332 (if pos (org-get-valid-level level 1) 1) ?*)
11333 " " child "\n")
11334 (beginning-of-line 0)
11335 (list (concat (car parent-target) "/" child) file "" (point)))))))
11337 (defun org-olpath-completing-read (prompt collection &rest args)
11338 "Read an outline path like a file name."
11339 (let ((thetable collection)
11340 (org-completion-use-ido nil) ; does not work with ido.
11341 (org-completion-use-iswitchb nil)) ; or iswitchb
11342 (apply
11343 'org-icompleting-read prompt
11344 (lambda (string predicate &optional flag)
11345 (let (rtn r f (l (length string)))
11346 (cond
11347 ((eq flag nil)
11348 ;; try completion
11349 (try-completion string thetable))
11350 ((eq flag t)
11351 ;; all-completions
11352 (setq rtn (all-completions string thetable predicate))
11353 (mapcar
11354 (lambda (x)
11355 (setq r (substring x l))
11356 (if (string-match " ([^)]*)$" x)
11357 (setq f (match-string 0 x))
11358 (setq f ""))
11359 (if (string-match "/" r)
11360 (concat string (substring r 0 (match-end 0)) f)
11362 rtn))
11363 ((eq flag 'lambda)
11364 ;; exact match?
11365 (assoc string thetable)))))
11366 args)))
11368 ;;;; Dynamic blocks
11370 (defun org-find-dblock (name)
11371 "Find the first dynamic block with name NAME in the buffer.
11372 If not found, stay at current position and return nil."
11373 (let ((case-fold-search t) pos)
11374 (save-excursion
11375 (goto-char (point-min))
11376 (setq pos (and (re-search-forward
11377 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11378 (match-beginning 0))))
11379 (if pos (goto-char pos))
11380 pos))
11382 (defconst org-dblock-start-re
11383 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11384 "Matches the start line of a dynamic block, with parameters.")
11386 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11387 "Matches the end of a dynamic block.")
11389 (defun org-create-dblock (plist)
11390 "Create a dynamic block section, with parameters taken from PLIST.
11391 PLIST must contain a :name entry which is used as name of the block."
11392 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11393 (end-of-line 1)
11394 (newline))
11395 (let ((col (current-column))
11396 (name (plist-get plist :name)))
11397 (insert "#+BEGIN: " name)
11398 (while plist
11399 (if (eq (car plist) :name)
11400 (setq plist (cddr plist))
11401 (insert " " (prin1-to-string (pop plist)))))
11402 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11403 (beginning-of-line -2)))
11405 (defun org-prepare-dblock ()
11406 "Prepare dynamic block for refresh.
11407 This empties the block, puts the cursor at the insert position and returns
11408 the property list including an extra property :name with the block name."
11409 (unless (looking-at org-dblock-start-re)
11410 (error "Not at a dynamic block"))
11411 (let* ((begdel (1+ (match-end 0)))
11412 (name (org-no-properties (match-string 1)))
11413 (params (append (list :name name)
11414 (read (concat "(" (match-string 3) ")")))))
11415 (save-excursion
11416 (beginning-of-line 1)
11417 (skip-chars-forward " \t")
11418 (setq params (plist-put params :indentation-column (current-column))))
11419 (unless (re-search-forward org-dblock-end-re nil t)
11420 (error "Dynamic block not terminated"))
11421 (setq params
11422 (append params
11423 (list :content (buffer-substring
11424 begdel (match-beginning 0)))))
11425 (delete-region begdel (match-beginning 0))
11426 (goto-char begdel)
11427 (open-line 1)
11428 params))
11430 (defun org-map-dblocks (&optional command)
11431 "Apply COMMAND to all dynamic blocks in the current buffer.
11432 If COMMAND is not given, use `org-update-dblock'."
11433 (let ((cmd (or command 'org-update-dblock)))
11434 (save-excursion
11435 (goto-char (point-min))
11436 (while (re-search-forward org-dblock-start-re nil t)
11437 (goto-char (match-beginning 0))
11438 (save-excursion
11439 (condition-case nil
11440 (funcall cmd)
11441 (error (message "Error during update of dynamic block"))))
11442 (unless (re-search-forward org-dblock-end-re nil t)
11443 (error "Dynamic block not terminated"))))))
11445 (defun org-dblock-update (&optional arg)
11446 "User command for updating dynamic blocks.
11447 Update the dynamic block at point. With prefix ARG, update all dynamic
11448 blocks in the buffer."
11449 (interactive "P")
11450 (if arg
11451 (org-update-all-dblocks)
11452 (or (looking-at org-dblock-start-re)
11453 (org-beginning-of-dblock))
11454 (org-update-dblock)))
11456 (defun org-update-dblock ()
11457 "Update the dynamic block at point.
11458 This means to empty the block, parse for parameters and then call
11459 the correct writing function."
11460 (interactive)
11461 (save-window-excursion
11462 (let* ((pos (point))
11463 (line (org-current-line))
11464 (params (org-prepare-dblock))
11465 (name (plist-get params :name))
11466 (indent (plist-get params :indentation-column))
11467 (cmd (intern (concat "org-dblock-write:" name))))
11468 (message "Updating dynamic block `%s' at line %d..." name line)
11469 (funcall cmd params)
11470 (message "Updating dynamic block `%s' at line %d...done" name line)
11471 (goto-char pos)
11472 (when (and indent (> indent 0))
11473 (setq indent (make-string indent ?\ ))
11474 (save-excursion
11475 (org-beginning-of-dblock)
11476 (forward-line 1)
11477 (while (not (looking-at org-dblock-end-re))
11478 (insert indent)
11479 (beginning-of-line 2))
11480 (when (looking-at org-dblock-end-re)
11481 (and (looking-at "[ \t]+")
11482 (replace-match ""))
11483 (insert indent)))))))
11485 (defun org-beginning-of-dblock ()
11486 "Find the beginning of the dynamic block at point.
11487 Error if there is no such block at point."
11488 (let ((pos (point))
11489 beg)
11490 (end-of-line 1)
11491 (if (and (re-search-backward org-dblock-start-re nil t)
11492 (setq beg (match-beginning 0))
11493 (re-search-forward org-dblock-end-re nil t)
11494 (> (match-end 0) pos))
11495 (goto-char beg)
11496 (goto-char pos)
11497 (error "Not in a dynamic block"))))
11499 (defun org-update-all-dblocks ()
11500 "Update all dynamic blocks in the buffer.
11501 This function can be used in a hook."
11502 (interactive)
11503 (when (derived-mode-p 'org-mode)
11504 (org-map-dblocks 'org-update-dblock)))
11507 ;;;; Completion
11509 (defun org-get-export-keywords ()
11510 "Return a list of all currently understood export keywords.
11511 Export keywords include options, block names, attributes and
11512 keywords relative to each registered export back-end."
11513 (delq nil
11514 (let (keywords)
11515 (mapc
11516 (lambda (back-end)
11517 (let ((props (cdr back-end)))
11518 ;; Back-end name (for keywords, like #+LATEX:)
11519 (push (upcase (symbol-name (car back-end))) keywords)
11520 ;; Back-end options.
11521 (mapc (lambda (option) (push (cadr option) keywords))
11522 (plist-get (cdr back-end) :options-alist))))
11523 (org-bound-and-true-p org-export-registered-backends))
11524 keywords)))
11526 (defconst org-options-keywords
11527 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11528 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11529 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11530 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11531 "TITLE:" "TODO:" "TYP_TODO:"))
11533 (defcustom org-structure-template-alist
11534 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11535 "<src lang=\"?\">\n\n</src>")
11536 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11537 "<example>\n?\n</example>")
11538 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11539 "<quote>\n?\n</quote>")
11540 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11541 "<verse>\n?\n</verse>")
11542 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11543 "<verbatim>\n?\n</verbatim>")
11544 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11545 "<center>\n?\n</center>")
11546 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11547 "<literal style=\"latex\">\n?\n</literal>")
11548 ("L" "#+LaTeX: "
11549 "<literal style=\"latex\">?</literal>")
11550 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11551 "<literal style=\"html\">\n?\n</literal>")
11552 ("H" "#+HTML: "
11553 "<literal style=\"html\">?</literal>")
11554 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11555 ("A" "#+ASCII: ")
11556 ("i" "#+INDEX: ?"
11557 "#+INDEX: ?")
11558 ("I" "#+INCLUDE: %file ?"
11559 "<include file=%file markup=\"?\">"))
11560 "Structure completion elements.
11561 This is a list of abbreviation keys and values. The value gets inserted
11562 if you type `<' followed by the key and then press the completion key,
11563 usually `M-TAB'. %file will be replaced by a file name after prompting
11564 for the file using completion. The cursor will be placed at the position
11565 of the `?` in the template.
11566 There are two templates for each key, the first uses the original Org syntax,
11567 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11568 the default when the /org-mtags.el/ module has been loaded. See also the
11569 variable `org-mtags-prefer-muse-templates'."
11570 :group 'org-completion
11571 :type '(repeat
11572 (string :tag "Key")
11573 (string :tag "Template")
11574 (string :tag "Muse Template")))
11576 (defun org-try-structure-completion ()
11577 "Try to complete a structure template before point.
11578 This looks for strings like \"<e\" on an otherwise empty line and
11579 expands them."
11580 (let ((l (buffer-substring (point-at-bol) (point)))
11582 (when (and (looking-at "[ \t]*$")
11583 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11584 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11585 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11586 (match-beginning 1)) a)
11587 t)))
11589 (defun org-complete-expand-structure-template (start cell)
11590 "Expand a structure template."
11591 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11592 (rpl (nth (if musep 2 1) cell))
11593 (ind ""))
11594 (delete-region start (point))
11595 (when (string-match "\\`#\\+" rpl)
11596 (cond
11597 ((bolp))
11598 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11599 (setq ind (buffer-substring (point-at-bol) (point))))
11600 (t (newline))))
11601 (setq start (point))
11602 (if (string-match "%file" rpl)
11603 (setq rpl (replace-match
11604 (concat
11605 "\""
11606 (save-match-data
11607 (abbreviate-file-name (read-file-name "Include file: ")))
11608 "\"")
11609 t t rpl)))
11610 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11611 (concat "\n" ind)))
11612 (insert rpl)
11613 (if (re-search-backward "\\?" start t) (delete-char 1))))
11615 ;;;; TODO, DEADLINE, Comments
11617 (defun org-toggle-comment ()
11618 "Change the COMMENT state of an entry."
11619 (interactive)
11620 (save-excursion
11621 (org-back-to-heading)
11622 (let (case-fold-search)
11623 (cond
11624 ((looking-at (format org-heading-keyword-regexp-format
11625 org-comment-string))
11626 (goto-char (match-end 1))
11627 (looking-at (concat " +" org-comment-string))
11628 (replace-match "" t t)
11629 (when (eolp) (insert " ")))
11630 ((looking-at org-outline-regexp)
11631 (goto-char (match-end 0))
11632 (insert org-comment-string " "))))))
11634 (defvar org-last-todo-state-is-todo nil
11635 "This is non-nil when the last TODO state change led to a TODO state.
11636 If the last change removed the TODO tag or switched to DONE, then
11637 this is nil.")
11639 (defvar org-setting-tags nil) ; dynamically skipped
11641 (defvar org-todo-setup-filter-hook nil
11642 "Hook for functions that pre-filter todo specs.
11643 Each function takes a todo spec and returns either nil or the spec
11644 transformed into canonical form." )
11646 (defvar org-todo-get-default-hook nil
11647 "Hook for functions that get a default item for todo.
11648 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11649 nil or a string to be used for the todo mark." )
11651 (defvar org-agenda-headline-snapshot-before-repeat)
11653 (defun org-current-effective-time ()
11654 "Return current time adjusted for `org-extend-today-until' variable."
11655 (let* ((ct (org-current-time))
11656 (dct (decode-time ct))
11657 (ct1
11658 (cond
11659 (org-use-last-clock-out-time-as-effective-time
11660 (or (org-clock-get-last-clock-out-time) ct))
11661 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11662 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11663 (t ct))))
11664 ct1))
11666 (defun org-todo-yesterday (&optional arg)
11667 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11668 (interactive "P")
11669 (if (eq major-mode 'org-agenda-mode)
11670 (apply 'org-agenda-todo-yesterday arg)
11671 (let* ((hour (third (decode-time
11672 (org-current-time))))
11673 (org-extend-today-until (1+ hour)))
11674 (org-todo arg))))
11676 (defvar org-block-entry-blocking ""
11677 "First entry preventing the TODO state change.")
11679 (defun org-todo (&optional arg)
11680 "Change the TODO state of an item.
11681 The state of an item is given by a keyword at the start of the heading,
11682 like
11683 *** TODO Write paper
11684 *** DONE Call mom
11686 The different keywords are specified in the variable `org-todo-keywords'.
11687 By default the available states are \"TODO\" and \"DONE\".
11688 So for this example: when the item starts with TODO, it is changed to DONE.
11689 When it starts with DONE, the DONE is removed. And when neither TODO nor
11690 DONE are present, add TODO at the beginning of the heading.
11692 With \\[universal-argument] prefix arg, use completion to determine the new \
11693 state.
11694 With numeric prefix arg, switch to that state.
11695 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11696 keywords (nextset).
11697 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11698 With a numeric prefix arg of 0, inhibit note taking for the change.
11700 For calling through lisp, arg is also interpreted in the following way:
11701 'none -> empty state
11702 \"\"(empty string) -> switch to empty state
11703 'done -> switch to DONE
11704 'nextset -> switch to the next set of keywords
11705 'previousset -> switch to the previous set of keywords
11706 \"WAITING\" -> switch to the specified keyword, but only if it
11707 really is a member of `org-todo-keywords'."
11708 (interactive "P")
11709 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11710 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11711 'region-start-level 'region))
11712 org-loop-over-headlines-in-active-region)
11713 (org-map-entries
11714 `(org-todo ,arg)
11715 org-loop-over-headlines-in-active-region
11716 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11717 (if (equal arg '(16)) (setq arg 'nextset))
11718 (let ((org-blocker-hook org-blocker-hook)
11719 commentp
11720 case-fold-search)
11721 (when (equal arg '(64))
11722 (setq arg nil org-blocker-hook nil))
11723 (when (and org-blocker-hook
11724 (or org-inhibit-blocking
11725 (org-entry-get nil "NOBLOCKING")))
11726 (setq org-blocker-hook nil))
11727 (save-excursion
11728 (catch 'exit
11729 (org-back-to-heading t)
11730 (when (looking-at (concat "^\\*+ " org-comment-string))
11731 (org-toggle-comment)
11732 (setq commentp t))
11733 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11734 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11735 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11736 (let* ((match-data (match-data))
11737 (startpos (point-at-bol))
11738 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11739 (org-log-done org-log-done)
11740 (org-log-repeat org-log-repeat)
11741 (org-todo-log-states org-todo-log-states)
11742 (org-inhibit-logging
11743 (if (equal arg 0)
11744 (progn (setq arg nil) 'note) org-inhibit-logging))
11745 (this (match-string 1))
11746 (hl-pos (match-beginning 0))
11747 (head (org-get-todo-sequence-head this))
11748 (ass (assoc head org-todo-kwd-alist))
11749 (interpret (nth 1 ass))
11750 (done-word (nth 3 ass))
11751 (final-done-word (nth 4 ass))
11752 (org-last-state (or this ""))
11753 (completion-ignore-case t)
11754 (member (member this org-todo-keywords-1))
11755 (tail (cdr member))
11756 (org-state (cond
11757 ((and org-todo-key-trigger
11758 (or (and (equal arg '(4))
11759 (eq org-use-fast-todo-selection 'prefix))
11760 (and (not arg) org-use-fast-todo-selection
11761 (not (eq org-use-fast-todo-selection
11762 'prefix)))))
11763 ;; Use fast selection
11764 (org-fast-todo-selection))
11765 ((and (equal arg '(4))
11766 (or (not org-use-fast-todo-selection)
11767 (not org-todo-key-trigger)))
11768 ;; Read a state with completion
11769 (org-icompleting-read
11770 "State: " (mapcar (lambda(x) (list x))
11771 org-todo-keywords-1)
11772 nil t))
11773 ((eq arg 'right)
11774 (if this
11775 (if tail (car tail) nil)
11776 (car org-todo-keywords-1)))
11777 ((eq arg 'left)
11778 (if (equal member org-todo-keywords-1)
11780 (if this
11781 (nth (- (length org-todo-keywords-1)
11782 (length tail) 2)
11783 org-todo-keywords-1)
11784 (org-last org-todo-keywords-1))))
11785 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11786 (setq arg nil))) ; hack to fall back to cycling
11787 (arg
11788 ;; user or caller requests a specific state
11789 (cond
11790 ((equal arg "") nil)
11791 ((eq arg 'none) nil)
11792 ((eq arg 'done) (or done-word (car org-done-keywords)))
11793 ((eq arg 'nextset)
11794 (or (car (cdr (member head org-todo-heads)))
11795 (car org-todo-heads)))
11796 ((eq arg 'previousset)
11797 (let ((org-todo-heads (reverse org-todo-heads)))
11798 (or (car (cdr (member head org-todo-heads)))
11799 (car org-todo-heads))))
11800 ((car (member arg org-todo-keywords-1)))
11801 ((stringp arg)
11802 (error "State `%s' not valid in this file" arg))
11803 ((nth (1- (prefix-numeric-value arg))
11804 org-todo-keywords-1))))
11805 ((null member) (or head (car org-todo-keywords-1)))
11806 ((equal this final-done-word) nil) ;; -> make empty
11807 ((null tail) nil) ;; -> first entry
11808 ((memq interpret '(type priority))
11809 (if (eq this-command last-command)
11810 (car tail)
11811 (if (> (length tail) 0)
11812 (or done-word (car org-done-keywords))
11813 nil)))
11815 (car tail))))
11816 (org-state (or
11817 (run-hook-with-args-until-success
11818 'org-todo-get-default-hook org-state org-last-state)
11819 org-state))
11820 (next (if org-state (concat " " org-state " ") " "))
11821 (change-plist (list :type 'todo-state-change :from this :to org-state
11822 :position startpos))
11823 dolog now-done-p)
11824 (when org-blocker-hook
11825 (setq org-last-todo-state-is-todo
11826 (not (member this org-done-keywords)))
11827 (unless (save-excursion
11828 (save-match-data
11829 (org-with-wide-buffer
11830 (run-hook-with-args-until-failure
11831 'org-blocker-hook change-plist))))
11832 (if (org-called-interactively-p 'interactive)
11833 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11834 this org-state org-block-entry-blocking)
11835 ;; fail silently
11836 (message "TODO state change from %s to %s blocked (by \"%s\")"
11837 this org-state org-block-entry-blocking)
11838 (throw 'exit nil))))
11839 (store-match-data match-data)
11840 (replace-match next t t)
11841 (unless (pos-visible-in-window-p hl-pos)
11842 (message "TODO state changed to %s" (org-trim next)))
11843 (unless head
11844 (setq head (org-get-todo-sequence-head org-state)
11845 ass (assoc head org-todo-kwd-alist)
11846 interpret (nth 1 ass)
11847 done-word (nth 3 ass)
11848 final-done-word (nth 4 ass)))
11849 (when (memq arg '(nextset previousset))
11850 (message "Keyword-Set %d/%d: %s"
11851 (- (length org-todo-sets) -1
11852 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11853 (length org-todo-sets)
11854 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11855 (setq org-last-todo-state-is-todo
11856 (not (member org-state org-done-keywords)))
11857 (setq now-done-p (and (member org-state org-done-keywords)
11858 (not (member this org-done-keywords))))
11859 (and logging (org-local-logging logging))
11860 (when (and (or org-todo-log-states org-log-done)
11861 (not (eq org-inhibit-logging t))
11862 (not (memq arg '(nextset previousset))))
11863 ;; we need to look at recording a time and note
11864 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11865 (nth 2 (assoc this org-todo-log-states))))
11866 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11867 (setq dolog 'time))
11868 (when (and org-state
11869 (member org-state org-not-done-keywords)
11870 (not (member this org-not-done-keywords)))
11871 ;; This is now a todo state and was not one before
11872 ;; If there was a CLOSED time stamp, get rid of it.
11873 (org-add-planning-info nil nil 'closed))
11874 (when (and now-done-p org-log-done)
11875 ;; It is now done, and it was not done before
11876 (org-add-planning-info 'closed (org-current-effective-time))
11877 (if (and (not dolog) (eq 'note org-log-done))
11878 (org-add-log-setup 'done org-state this 'findpos 'note)))
11879 (when (and org-state dolog)
11880 ;; This is a non-nil state, and we need to log it
11881 (org-add-log-setup 'state org-state this 'findpos dolog)))
11882 ;; Fixup tag positioning
11883 (org-todo-trigger-tag-changes org-state)
11884 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11885 (when org-provide-todo-statistics
11886 (org-update-parent-todo-statistics))
11887 (run-hooks 'org-after-todo-state-change-hook)
11888 (if (and arg (not (member org-state org-done-keywords)))
11889 (setq head (org-get-todo-sequence-head org-state)))
11890 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11891 ;; Do we need to trigger a repeat?
11892 (when now-done-p
11893 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11894 ;; This is for the agenda, take a snapshot of the headline.
11895 (save-match-data
11896 (setq org-agenda-headline-snapshot-before-repeat
11897 (org-get-heading))))
11898 (org-auto-repeat-maybe org-state))
11899 ;; Fixup cursor location if close to the keyword
11900 (if (and (outline-on-heading-p)
11901 (not (bolp))
11902 (save-excursion (beginning-of-line 1)
11903 (looking-at org-todo-line-regexp))
11904 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11905 (progn
11906 (goto-char (or (match-end 2) (match-end 1)))
11907 (and (looking-at " ") (just-one-space))))
11908 (when org-trigger-hook
11909 (save-excursion
11910 (run-hook-with-args 'org-trigger-hook change-plist)))
11911 (when commentp (org-toggle-comment))))))))
11913 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11914 "Block turning an entry into a TODO, using the hierarchy.
11915 This checks whether the current task should be blocked from state
11916 changes. Such blocking occurs when:
11918 1. The task has children which are not all in a completed state.
11920 2. A task has a parent with the property :ORDERED:, and there
11921 are siblings prior to the current task with incomplete
11922 status.
11924 3. The parent of the task is blocked because it has siblings that should
11925 be done first, or is child of a block grandparent TODO entry."
11927 (if (not org-enforce-todo-dependencies)
11928 t ; if locally turned off don't block
11929 (catch 'dont-block
11930 ;; If this is not a todo state change, or if this entry is already DONE,
11931 ;; do not block
11932 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11933 (member (plist-get change-plist :from)
11934 (cons 'done org-done-keywords))
11935 (member (plist-get change-plist :to)
11936 (cons 'todo org-not-done-keywords))
11937 (not (plist-get change-plist :to)))
11938 (throw 'dont-block t))
11939 ;; If this task has children, and any are undone, it's blocked
11940 (save-excursion
11941 (org-back-to-heading t)
11942 (let ((this-level (funcall outline-level)))
11943 (outline-next-heading)
11944 (let ((child-level (funcall outline-level)))
11945 (while (and (not (eobp))
11946 (> child-level this-level))
11947 ;; this todo has children, check whether they are all
11948 ;; completed
11949 (if (and (not (org-entry-is-done-p))
11950 (org-entry-is-todo-p))
11951 (progn (setq org-block-entry-blocking (org-get-heading))
11952 (throw 'dont-block nil)))
11953 (outline-next-heading)
11954 (setq child-level (funcall outline-level))))))
11955 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11956 ;; any previous siblings are undone, it's blocked
11957 (save-excursion
11958 (org-back-to-heading t)
11959 (let* ((pos (point))
11960 (parent-pos (and (org-up-heading-safe) (point))))
11961 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11962 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11963 (forward-line 1)
11964 (re-search-forward org-not-done-heading-regexp pos t))
11965 (setq org-block-entry-blocking (match-string 0))
11966 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11967 ;; Search further up the hierarchy, to see if an ancestor is blocked
11968 (while t
11969 (goto-char parent-pos)
11970 (if (not (looking-at org-not-done-heading-regexp))
11971 (throw 'dont-block t)) ; do not block, parent is not a TODO
11972 (setq pos (point))
11973 (setq parent-pos (and (org-up-heading-safe) (point)))
11974 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11975 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11976 (forward-line 1)
11977 (re-search-forward org-not-done-heading-regexp pos t)
11978 (setq org-block-entry-blocking (org-get-heading)))
11979 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11981 (defcustom org-track-ordered-property-with-tag nil
11982 "Should the ORDERED property also be shown as a tag?
11983 The ORDERED property decides if an entry should require subtasks to be
11984 completed in sequence. Since a property is not very visible, setting
11985 this option means that toggling the ORDERED property with the command
11986 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11987 not relevant for the behavior, but it makes things more visible.
11989 Note that toggling the tag with tags commands will not change the property
11990 and therefore not influence behavior!
11992 This can be t, meaning the tag ORDERED should be used, It can also be a
11993 string to select a different tag for this task."
11994 :group 'org-todo
11995 :type '(choice
11996 (const :tag "No tracking" nil)
11997 (const :tag "Track with ORDERED tag" t)
11998 (string :tag "Use other tag")))
12000 (defun org-toggle-ordered-property ()
12001 "Toggle the ORDERED property of the current entry.
12002 For better visibility, you can track the value of this property with a tag.
12003 See variable `org-track-ordered-property-with-tag'."
12004 (interactive)
12005 (let* ((t1 org-track-ordered-property-with-tag)
12006 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12007 (save-excursion
12008 (org-back-to-heading)
12009 (if (org-entry-get nil "ORDERED")
12010 (progn
12011 (org-delete-property "ORDERED")
12012 (and tag (org-toggle-tag tag 'off))
12013 (message "Subtasks can be completed in arbitrary order"))
12014 (org-entry-put nil "ORDERED" "t")
12015 (and tag (org-toggle-tag tag 'on))
12016 (message "Subtasks must be completed in sequence")))))
12018 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12019 (defun org-block-todo-from-checkboxes (change-plist)
12020 "Block turning an entry into a TODO, using checkboxes.
12021 This checks whether the current task should be blocked from state
12022 changes because there are unchecked boxes in this entry."
12023 (if (not org-enforce-todo-checkbox-dependencies)
12024 t ; if locally turned off don't block
12025 (catch 'dont-block
12026 ;; If this is not a todo state change, or if this entry is already DONE,
12027 ;; do not block
12028 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12029 (member (plist-get change-plist :from)
12030 (cons 'done org-done-keywords))
12031 (member (plist-get change-plist :to)
12032 (cons 'todo org-not-done-keywords))
12033 (not (plist-get change-plist :to)))
12034 (throw 'dont-block t))
12035 ;; If this task has checkboxes that are not checked, it's blocked
12036 (save-excursion
12037 (org-back-to-heading t)
12038 (let ((beg (point)) end)
12039 (outline-next-heading)
12040 (setq end (point))
12041 (goto-char beg)
12042 (if (org-list-search-forward
12043 (concat (org-item-beginning-re)
12044 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12045 "\\[[- ]\\]")
12046 end t)
12047 (progn
12048 (if (boundp 'org-blocked-by-checkboxes)
12049 (setq org-blocked-by-checkboxes t))
12050 (throw 'dont-block nil)))))
12051 t))) ; do not block
12053 (defun org-entry-blocked-p ()
12054 "Is the current entry blocked?"
12055 (org-with-buffer-modified-unmodified
12056 (if (org-entry-get nil "NOBLOCKING")
12057 nil ;; Never block this entry
12058 (not
12059 (run-hook-with-args-until-failure
12060 'org-blocker-hook
12061 (list :type 'todo-state-change
12062 :position (point)
12063 :from 'todo
12064 :to 'done))))))
12066 (defun org-update-statistics-cookies (all)
12067 "Update the statistics cookie, either from TODO or from checkboxes.
12068 This should be called with the cursor in a line with a statistics cookie."
12069 (interactive "P")
12070 (if all
12071 (progn
12072 (org-update-checkbox-count 'all)
12073 (org-map-entries 'org-update-parent-todo-statistics))
12074 (if (not (org-at-heading-p))
12075 (org-update-checkbox-count)
12076 (let ((pos (point-marker))
12077 end l1 l2)
12078 (ignore-errors (org-back-to-heading t))
12079 (if (not (org-at-heading-p))
12080 (org-update-checkbox-count)
12081 (setq l1 (org-outline-level))
12082 (setq end (save-excursion
12083 (outline-next-heading)
12084 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12085 (point)))
12086 (if (and (save-excursion
12087 (re-search-forward
12088 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12089 (not (save-excursion (re-search-forward
12090 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12091 (org-update-checkbox-count)
12092 (if (and l2 (> l2 l1))
12093 (progn
12094 (goto-char end)
12095 (org-update-parent-todo-statistics))
12096 (goto-char pos)
12097 (beginning-of-line 1)
12098 (while (re-search-forward
12099 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12100 (point-at-eol) t)
12101 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12102 (goto-char pos)
12103 (move-marker pos nil)))))
12105 (defvar org-entry-property-inherited-from) ;; defined below
12106 (defun org-update-parent-todo-statistics ()
12107 "Update any statistics cookie in the parent of the current headline.
12108 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12109 the entire subtree and this will travel up the hierarchy and update
12110 statistics everywhere."
12111 (let* ((prop (save-excursion (org-up-heading-safe)
12112 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12113 (recursive (or (not org-hierarchical-todo-statistics)
12114 (and prop (string-match "\\<recursive\\>" prop))))
12115 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12117 (first t)
12118 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12119 level ltoggle l1 new ndel
12120 (cnt-all 0) (cnt-done 0) is-percent kwd
12121 checkbox-beg ov ovs ove cookie-present)
12122 (catch 'exit
12123 (save-excursion
12124 (beginning-of-line 1)
12125 (setq ltoggle (funcall outline-level))
12126 ;; Three situations are to consider:
12128 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12129 ;; to the top-level ancestor on the headline;
12131 ;; 2. If parent has "recursive" property, repeat up to the
12132 ;; headline setting that property, taking inheritance into
12133 ;; account;
12135 ;; 3. Else, move up to direct parent and proceed only once.
12136 (while (and (setq level (org-up-heading-safe))
12137 (or recursive first)
12138 (>= (point) lim))
12139 (setq first nil cookie-present nil)
12140 (unless (and level
12141 (not (string-match
12142 "\\<checkbox\\>"
12143 (downcase (or (org-entry-get nil "COOKIE_DATA")
12144 "")))))
12145 (throw 'exit nil))
12146 (while (re-search-forward box-re (point-at-eol) t)
12147 (setq cnt-all 0 cnt-done 0 cookie-present t)
12148 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12149 (save-match-data
12150 (unless (outline-next-heading) (throw 'exit nil))
12151 (while (and (looking-at org-complex-heading-regexp)
12152 (> (setq l1 (length (match-string 1))) level))
12153 (setq kwd (and (or recursive (= l1 ltoggle))
12154 (match-string 2)))
12155 (if (or (eq org-provide-todo-statistics 'all-headlines)
12156 (and (listp org-provide-todo-statistics)
12157 (or (member kwd org-provide-todo-statistics)
12158 (member kwd org-done-keywords))))
12159 (setq cnt-all (1+ cnt-all))
12160 (if (eq org-provide-todo-statistics t)
12161 (and kwd (setq cnt-all (1+ cnt-all)))))
12162 (and (member kwd org-done-keywords)
12163 (setq cnt-done (1+ cnt-done)))
12164 (outline-next-heading)))
12165 (setq new
12166 (if is-percent
12167 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12168 (format "[%d/%d]" cnt-done cnt-all))
12169 ndel (- (match-end 0) checkbox-beg))
12170 ;; handle overlays when updating cookie from column view
12171 (when (setq ov (car (overlays-at checkbox-beg)))
12172 (setq ovs (overlay-start ov) ove (overlay-end ov))
12173 (delete-overlay ov))
12174 (goto-char checkbox-beg)
12175 (insert new)
12176 (delete-region (point) (+ (point) ndel))
12177 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12178 (when ov (move-overlay ov ovs ove)))
12179 (when cookie-present
12180 (run-hook-with-args 'org-after-todo-statistics-hook
12181 cnt-done (- cnt-all cnt-done))))))
12182 (run-hooks 'org-todo-statistics-hook)))
12184 (defvar org-after-todo-statistics-hook nil
12185 "Hook that is called after a TODO statistics cookie has been updated.
12186 Each function is called with two arguments: the number of not-done entries
12187 and the number of done entries.
12189 For example, the following function, when added to this hook, will switch
12190 an entry to DONE when all children are done, and back to TODO when new
12191 entries are set to a TODO status. Note that this hook is only called
12192 when there is a statistics cookie in the headline!
12194 (defun org-summary-todo (n-done n-not-done)
12195 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12196 (let (org-log-done org-log-states) ; turn off logging
12197 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12200 (defvar org-todo-statistics-hook nil
12201 "Hook that is run whenever Org thinks TODO statistics should be updated.
12202 This hook runs even if there is no statistics cookie present, in which case
12203 `org-after-todo-statistics-hook' would not run.")
12205 (defun org-todo-trigger-tag-changes (state)
12206 "Apply the changes defined in `org-todo-state-tags-triggers'."
12207 (let ((l org-todo-state-tags-triggers)
12208 changes)
12209 (when (or (not state) (equal state ""))
12210 (setq changes (append changes (cdr (assoc "" l)))))
12211 (when (and (stringp state) (> (length state) 0))
12212 (setq changes (append changes (cdr (assoc state l)))))
12213 (when (member state org-not-done-keywords)
12214 (setq changes (append changes (cdr (assoc 'todo l)))))
12215 (when (member state org-done-keywords)
12216 (setq changes (append changes (cdr (assoc 'done l)))))
12217 (dolist (c changes)
12218 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12220 (defun org-local-logging (value)
12221 "Get logging settings from a property VALUE."
12222 (let* (words w a)
12223 ;; directly set the variables, they are already local.
12224 (setq org-log-done nil
12225 org-log-repeat nil
12226 org-todo-log-states nil)
12227 (setq words (org-split-string value))
12228 (while (setq w (pop words))
12229 (cond
12230 ((setq a (assoc w org-startup-options))
12231 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12232 (set (nth 1 a) (nth 2 a))))
12233 ((setq a (org-extract-log-state-settings w))
12234 (and (member (car a) org-todo-keywords-1)
12235 (push a org-todo-log-states)))))))
12237 (defun org-get-todo-sequence-head (kwd)
12238 "Return the head of the TODO sequence to which KWD belongs.
12239 If KWD is not set, check if there is a text property remembering the
12240 right sequence."
12241 (let (p)
12242 (cond
12243 ((not kwd)
12244 (or (get-text-property (point-at-bol) 'org-todo-head)
12245 (progn
12246 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12247 nil (point-at-eol)))
12248 (get-text-property p 'org-todo-head))))
12249 ((not (member kwd org-todo-keywords-1))
12250 (car org-todo-keywords-1))
12251 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12253 (defun org-fast-todo-selection ()
12254 "Fast TODO keyword selection with single keys.
12255 Returns the new TODO keyword, or nil if no state change should occur."
12256 (let* ((fulltable org-todo-key-alist)
12257 (done-keywords org-done-keywords) ;; needed for the faces.
12258 (maxlen (apply 'max (mapcar
12259 (lambda (x)
12260 (if (stringp (car x)) (string-width (car x)) 0))
12261 fulltable)))
12262 (expert nil)
12263 (fwidth (+ maxlen 3 1 3))
12264 (ncol (/ (- (window-width) 4) fwidth))
12265 tg cnt e c tbl
12266 groups ingroup)
12267 (save-excursion
12268 (save-window-excursion
12269 (if expert
12270 (set-buffer (get-buffer-create " *Org todo*"))
12271 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12272 (erase-buffer)
12273 (org-set-local 'org-done-keywords done-keywords)
12274 (setq tbl fulltable cnt 0)
12275 (while (setq e (pop tbl))
12276 (cond
12277 ((equal e '(:startgroup))
12278 (push '() groups) (setq ingroup t)
12279 (when (not (= cnt 0))
12280 (setq cnt 0)
12281 (insert "\n"))
12282 (insert "{ "))
12283 ((equal e '(:endgroup))
12284 (setq ingroup nil cnt 0)
12285 (insert "}\n"))
12286 ((equal e '(:newline))
12287 (when (not (= cnt 0))
12288 (setq cnt 0)
12289 (insert "\n")
12290 (setq e (car tbl))
12291 (while (equal (car tbl) '(:newline))
12292 (insert "\n")
12293 (setq tbl (cdr tbl)))))
12295 (setq tg (car e) c (cdr e))
12296 (if ingroup (push tg (car groups)))
12297 (setq tg (org-add-props tg nil 'face
12298 (org-get-todo-face tg)))
12299 (if (and (= cnt 0) (not ingroup)) (insert " "))
12300 (insert "[" c "] " tg (make-string
12301 (- fwidth 4 (length tg)) ?\ ))
12302 (when (= (setq cnt (1+ cnt)) ncol)
12303 (insert "\n")
12304 (if ingroup (insert " "))
12305 (setq cnt 0)))))
12306 (insert "\n")
12307 (goto-char (point-min))
12308 (if (not expert) (org-fit-window-to-buffer))
12309 (message "[a-z..]:Set [SPC]:clear")
12310 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12311 (cond
12312 ((or (= c ?\C-g)
12313 (and (= c ?q) (not (rassoc c fulltable))))
12314 (setq quit-flag t))
12315 ((= c ?\ ) nil)
12316 ((setq e (rassoc c fulltable) tg (car e))
12318 (t (setq quit-flag t)))))))
12320 (defun org-entry-is-todo-p ()
12321 (member (org-get-todo-state) org-not-done-keywords))
12323 (defun org-entry-is-done-p ()
12324 (member (org-get-todo-state) org-done-keywords))
12326 (defun org-get-todo-state ()
12327 (save-excursion
12328 (org-back-to-heading t)
12329 (and (looking-at org-todo-line-regexp)
12330 (match-end 2)
12331 (match-string 2))))
12333 (defun org-at-date-range-p (&optional inactive-ok)
12334 "Is the cursor inside a date range?"
12335 (interactive)
12336 (save-excursion
12337 (catch 'exit
12338 (let ((pos (point)))
12339 (skip-chars-backward "^[<\r\n")
12340 (skip-chars-backward "<[")
12341 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12342 (>= (match-end 0) pos)
12343 (throw 'exit t))
12344 (skip-chars-backward "^<[\r\n")
12345 (skip-chars-backward "<[")
12346 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12347 (>= (match-end 0) pos)
12348 (throw 'exit t)))
12349 nil)))
12351 (defun org-get-repeat (&optional tagline)
12352 "Check if there is a deadline/schedule with repeater in this entry."
12353 (save-match-data
12354 (save-excursion
12355 (org-back-to-heading t)
12356 (and (re-search-forward (if tagline
12357 (concat tagline "\\s-*" org-repeat-re)
12358 org-repeat-re)
12359 (org-entry-end-position) t)
12360 (match-string-no-properties 1)))))
12362 (defvar org-last-changed-timestamp)
12363 (defvar org-last-inserted-timestamp)
12364 (defvar org-log-post-message)
12365 (defvar org-log-note-purpose)
12366 (defvar org-log-note-how)
12367 (defvar org-log-note-extra)
12368 (defun org-auto-repeat-maybe (done-word)
12369 "Check if the current headline contains a repeated deadline/schedule.
12370 If yes, set TODO state back to what it was and change the base date
12371 of repeating deadline/scheduled time stamps to new date.
12372 This function is run automatically after each state change to a DONE state."
12373 ;; last-state is dynamically scoped into this function
12374 (let* ((repeat (org-get-repeat))
12375 (aa (assoc org-last-state org-todo-kwd-alist))
12376 (interpret (nth 1 aa))
12377 (head (nth 2 aa))
12378 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12379 (msg "Entry repeats: ")
12380 (org-log-done nil)
12381 (org-todo-log-states nil)
12382 re type n what ts time to-state)
12383 (when repeat
12384 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12385 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12386 org-todo-repeat-to-state))
12387 (unless (and to-state (member to-state org-todo-keywords-1))
12388 (setq to-state (if (eq interpret 'type) org-last-state head)))
12389 (org-todo to-state)
12390 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12391 (org-entry-put nil "LAST_REPEAT" (format-time-string
12392 (org-time-stamp-format t t))))
12393 (when org-log-repeat
12394 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12395 (memq 'org-add-log-note post-command-hook))
12396 ;; OK, we are already setup for some record
12397 (if (eq org-log-repeat 'note)
12398 ;; make sure we take a note, not only a time stamp
12399 (setq org-log-note-how 'note))
12400 ;; Set up for taking a record
12401 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12402 org-last-state
12403 'findpos org-log-repeat)))
12404 (org-back-to-heading t)
12405 (org-add-planning-info nil nil 'closed)
12406 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12407 org-deadline-time-regexp "\\)\\|\\("
12408 org-ts-regexp "\\)"))
12409 (while (re-search-forward
12410 re (save-excursion (outline-next-heading) (point)) t)
12411 (setq type (if (match-end 1) org-scheduled-string
12412 (if (match-end 3) org-deadline-string "Plain:"))
12413 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12414 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12415 (setq n (string-to-number (match-string 2 ts))
12416 what (match-string 3 ts))
12417 (if (equal what "w") (setq n (* n 7) what "d"))
12418 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12419 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12420 ;; Preparation, see if we need to modify the start date for the change
12421 (when (match-end 1)
12422 (setq time (save-match-data (org-time-string-to-time ts)))
12423 (cond
12424 ((equal (match-string 1 ts) ".")
12425 ;; Shift starting date to today
12426 (org-timestamp-change
12427 (- (org-today) (time-to-days time))
12428 'day))
12429 ((equal (match-string 1 ts) "+")
12430 (let ((nshiftmax 10) (nshift 0))
12431 (while (or (= nshift 0)
12432 (<= (time-to-days time)
12433 (time-to-days (current-time))))
12434 (when (= (incf nshift) nshiftmax)
12435 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12436 (error "Abort")))
12437 (org-timestamp-change n (cdr (assoc what whata)))
12438 (org-at-timestamp-p t)
12439 (setq ts (match-string 1))
12440 (setq time (save-match-data (org-time-string-to-time ts)))))
12441 (org-timestamp-change (- n) (cdr (assoc what whata)))
12442 ;; rematch, so that we have everything in place for the real shift
12443 (org-at-timestamp-p t)
12444 (setq ts (match-string 1))
12445 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12446 (org-timestamp-change n (cdr (assoc what whata)))
12447 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12448 (setq org-log-post-message msg)
12449 (message "%s" msg))))
12451 (defun org-show-todo-tree (arg)
12452 "Make a compact tree which shows all headlines marked with TODO.
12453 The tree will show the lines where the regexp matches, and all higher
12454 headlines above the match.
12455 With a \\[universal-argument] prefix, prompt for a regexp to match.
12456 With a numeric prefix N, construct a sparse tree for the Nth element
12457 of `org-todo-keywords-1'."
12458 (interactive "P")
12459 (let ((case-fold-search nil)
12460 (kwd-re
12461 (cond ((null arg) org-not-done-regexp)
12462 ((equal arg '(4))
12463 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12464 (mapcar 'list org-todo-keywords-1))))
12465 (concat "\\("
12466 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12467 "\\)\\>")))
12468 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12469 (regexp-quote (nth (1- (prefix-numeric-value arg))
12470 org-todo-keywords-1)))
12471 (t (error "Invalid prefix argument: %s" arg)))))
12472 (message "%d TODO entries found"
12473 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12475 (defun org-deadline (&optional arg time)
12476 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12477 With one universal prefix argument, remove any deadline from the item.
12478 With two universal prefix arguments, prompt for a warning delay.
12479 With argument TIME, set the deadline at the corresponding date. TIME
12480 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12481 (interactive "P")
12482 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12483 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12484 'region-start-level 'region))
12485 org-loop-over-headlines-in-active-region)
12486 (org-map-entries
12487 `(org-deadline ',arg ,time)
12488 org-loop-over-headlines-in-active-region
12489 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12490 (let* ((old-date (org-entry-get nil "DEADLINE"))
12491 (repeater (and old-date
12492 (string-match
12493 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12494 old-date)
12495 (match-string 1 old-date))))
12496 (cond
12497 ((equal arg '(4))
12498 (when (and old-date org-log-redeadline)
12499 (org-add-log-setup 'deldeadline nil old-date 'findpos
12500 org-log-redeadline))
12501 (org-remove-timestamp-with-keyword org-deadline-string)
12502 (message "Item no longer has a deadline."))
12503 ((equal arg '(16))
12504 (save-excursion
12505 (if (re-search-forward
12506 org-deadline-time-regexp
12507 (save-excursion (outline-next-heading) (point)) t)
12508 (let* ((rpl0 (match-string 1))
12509 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12510 (replace-match
12511 (concat org-deadline-string
12512 " <" rpl
12513 (format " -%dd" (abs
12514 (- (time-to-days
12515 (save-match-data
12516 (org-read-date nil t nil "Warn starting from")))
12517 (time-to-days nil))))
12518 ">") t t))
12519 (user-error "No deadline information to update"))))
12521 (org-add-planning-info 'deadline time 'closed)
12522 (when (and old-date org-log-redeadline
12523 (not (equal old-date
12524 (substring org-last-inserted-timestamp 1 -1))))
12525 (org-add-log-setup 'redeadline nil old-date 'findpos
12526 org-log-redeadline))
12527 (when repeater
12528 (save-excursion
12529 (org-back-to-heading t)
12530 (when (re-search-forward (concat org-deadline-string " "
12531 org-last-inserted-timestamp)
12532 (save-excursion
12533 (outline-next-heading) (point)) t)
12534 (goto-char (1- (match-end 0)))
12535 (insert " " repeater)
12536 (setq org-last-inserted-timestamp
12537 (concat (substring org-last-inserted-timestamp 0 -1)
12538 " " repeater
12539 (substring org-last-inserted-timestamp -1))))))
12540 (message "Deadline on %s" org-last-inserted-timestamp))))))
12542 (defun org-schedule (&optional arg time)
12543 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12544 With one universal prefix argument, remove any scheduling date from the item.
12545 With two universal prefix arguments, prompt for a delay cookie.
12546 With argument TIME, scheduled at the corresponding date. TIME can
12547 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12548 (interactive "P")
12549 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12550 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12551 'region-start-level 'region))
12552 org-loop-over-headlines-in-active-region)
12553 (org-map-entries
12554 `(org-schedule ',arg ,time)
12555 org-loop-over-headlines-in-active-region
12556 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12557 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12558 (repeater (and old-date
12559 (string-match
12560 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12561 old-date)
12562 (match-string 1 old-date))))
12563 (cond
12564 ((equal arg '(4))
12565 (progn
12566 (when (and old-date org-log-reschedule)
12567 (org-add-log-setup 'delschedule nil old-date 'findpos
12568 org-log-reschedule))
12569 (org-remove-timestamp-with-keyword org-scheduled-string)
12570 (message "Item is no longer scheduled.")))
12571 ((equal arg '(16))
12572 (save-excursion
12573 (if (re-search-forward
12574 org-scheduled-time-regexp
12575 (save-excursion (outline-next-heading) (point)) t)
12576 (let* ((rpl0 (match-string 1))
12577 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12578 (replace-match
12579 (concat org-scheduled-string
12580 " <" rpl
12581 (format " -%dd" (abs
12582 (- (time-to-days
12583 (save-match-data
12584 (org-read-date nil t nil "Delay until")))
12585 (time-to-days nil))))
12586 ">") t t))
12587 (user-error "No scheduled information to update"))))
12589 (org-add-planning-info 'scheduled time 'closed)
12590 (when (and old-date org-log-reschedule
12591 (not (equal old-date
12592 (substring org-last-inserted-timestamp 1 -1))))
12593 (org-add-log-setup 'reschedule nil old-date 'findpos
12594 org-log-reschedule))
12595 (when repeater
12596 (save-excursion
12597 (org-back-to-heading t)
12598 (when (re-search-forward (concat org-scheduled-string " "
12599 org-last-inserted-timestamp)
12600 (save-excursion
12601 (outline-next-heading) (point)) t)
12602 (goto-char (1- (match-end 0)))
12603 (insert " " repeater)
12604 (setq org-last-inserted-timestamp
12605 (concat (substring org-last-inserted-timestamp 0 -1)
12606 " " repeater
12607 (substring org-last-inserted-timestamp -1))))))
12608 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12610 (defun org-get-scheduled-time (pom &optional inherit)
12611 "Get the scheduled time as a time tuple, of a format suitable
12612 for calling org-schedule with, or if there is no scheduling,
12613 returns nil."
12614 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12615 (when time
12616 (apply 'encode-time (org-parse-time-string time)))))
12618 (defun org-get-deadline-time (pom &optional inherit)
12619 "Get the deadline as a time tuple, of a format suitable for
12620 calling org-deadline with, or if there is no scheduling, returns
12621 nil."
12622 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12623 (when time
12624 (apply 'encode-time (org-parse-time-string time)))))
12626 (defun org-remove-timestamp-with-keyword (keyword)
12627 "Remove all time stamps with KEYWORD in the current entry."
12628 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12629 beg)
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (setq beg (point))
12633 (outline-next-heading)
12634 (while (re-search-backward re beg t)
12635 (replace-match "")
12636 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12637 (equal (char-before) ?\ ))
12638 (backward-delete-char 1)
12639 (if (string-match "^[ \t]*$" (buffer-substring
12640 (point-at-bol) (point-at-eol)))
12641 (delete-region (point-at-bol)
12642 (min (point-max) (1+ (point-at-eol))))))))))
12644 (defun org-add-planning-info (what &optional time &rest remove)
12645 "Insert new timestamp with keyword in the line directly after the headline.
12646 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12647 If non is given, the user is prompted for a date.
12648 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12649 be removed."
12650 (interactive)
12651 (let (org-time-was-given org-end-time-was-given ts
12652 end default-time default-input)
12654 (catch 'exit
12655 (when (and (memq what '(scheduled deadline))
12656 (or (not time)
12657 (and (stringp time)
12658 (string-match "^[-+]+[0-9]" time))))
12659 ;; Try to get a default date/time from existing timestamp
12660 (save-excursion
12661 (org-back-to-heading t)
12662 (setq end (save-excursion (outline-next-heading) (point)))
12663 (when (re-search-forward (if (eq what 'scheduled)
12664 org-scheduled-time-regexp
12665 org-deadline-time-regexp)
12666 end t)
12667 (setq ts (match-string 1)
12668 default-time
12669 (apply 'encode-time (org-parse-time-string ts))
12670 default-input (and ts (org-get-compact-tod ts))))))
12671 (when what
12672 (setq time
12673 (if (stringp time)
12674 ;; This is a string (relative or absolute), set proper date
12675 (apply 'encode-time
12676 (org-read-date-analyze
12677 time default-time (decode-time default-time)))
12678 ;; If necessary, get the time from the user
12679 (or time (org-read-date nil 'to-time nil nil
12680 default-time default-input)))))
12682 (when (and org-insert-labeled-timestamps-at-point
12683 (member what '(scheduled deadline)))
12684 (insert
12685 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12686 (org-insert-time-stamp time org-time-was-given
12687 nil nil nil (list org-end-time-was-given))
12688 (setq what nil))
12689 (save-excursion
12690 (save-restriction
12691 (let (col list elt ts buffer-invisibility-spec)
12692 (org-back-to-heading t)
12693 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12694 (goto-char (match-end 1))
12695 (setq col (current-column))
12696 (goto-char (match-end 0))
12697 (if (eobp) (insert "\n") (forward-char 1))
12698 (when (and (not what)
12699 (not (looking-at
12700 (concat "[ \t]*"
12701 org-keyword-time-not-clock-regexp))))
12702 ;; Nothing to add, nothing to remove...... :-)
12703 (throw 'exit nil))
12704 (if (and (not (looking-at org-outline-regexp))
12705 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12706 "[^\r\n]*"))
12707 (not (equal (match-string 1) org-clock-string)))
12708 (narrow-to-region (match-beginning 0) (match-end 0))
12709 (insert-before-markers "\n")
12710 (backward-char 1)
12711 (narrow-to-region (point) (point))
12712 (and org-adapt-indentation (org-indent-to-column col)))
12713 ;; Check if we have to remove something.
12714 (setq list (cons what remove))
12715 (while list
12716 (setq elt (pop list))
12717 (when (or (and (eq elt 'scheduled)
12718 (re-search-forward org-scheduled-time-regexp nil t))
12719 (and (eq elt 'deadline)
12720 (re-search-forward org-deadline-time-regexp nil t))
12721 (and (eq elt 'closed)
12722 (re-search-forward org-closed-time-regexp nil t)))
12723 (replace-match "")
12724 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12725 (and (looking-at "[ \t]+") (replace-match ""))
12726 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12727 (when what
12728 (insert
12729 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12730 (cond ((eq what 'scheduled) org-scheduled-string)
12731 ((eq what 'deadline) org-deadline-string)
12732 ((eq what 'closed) org-closed-string))
12733 " ")
12734 (setq ts (org-insert-time-stamp
12735 time
12736 (or org-time-was-given
12737 (and (eq what 'closed) org-log-done-with-time))
12738 (eq what 'closed)
12739 nil nil (list org-end-time-was-given)))
12740 (insert
12741 (if (not (or (bolp) (eq (char-before) ?\ )
12742 (memq (char-after) '(32 10))
12743 (eobp))) " " ""))
12744 (end-of-line 1))
12745 (goto-char (point-min))
12746 (widen)
12747 (if (and (looking-at "[ \t]*\n")
12748 (equal (char-before) ?\n))
12749 (delete-region (1- (point)) (point-at-eol)))
12750 ts))))))
12752 (defvar org-log-note-marker (make-marker))
12753 (defvar org-log-note-purpose nil)
12754 (defvar org-log-note-state nil)
12755 (defvar org-log-note-previous-state nil)
12756 (defvar org-log-note-how nil)
12757 (defvar org-log-note-extra nil)
12758 (defvar org-log-note-window-configuration nil)
12759 (defvar org-log-note-return-to (make-marker))
12760 (defvar org-log-note-effective-time nil
12761 "Remembered current time so that dynamically scoped
12762 `org-extend-today-until' affects tha timestamps in state change
12763 log")
12765 (defvar org-log-post-message nil
12766 "Message to be displayed after a log note has been stored.
12767 The auto-repeater uses this.")
12769 (defun org-add-note ()
12770 "Add a note to the current entry.
12771 This is done in the same way as adding a state change note."
12772 (interactive)
12773 (org-add-log-setup 'note nil nil 'findpos nil))
12775 (defvar org-property-end-re)
12776 (defun org-add-log-setup (&optional purpose state prev-state
12777 findpos how extra)
12778 "Set up the post command hook to take a note.
12779 If this is about to TODO state change, the new state is expected in STATE.
12780 When FINDPOS is non-nil, find the correct position for the note in
12781 the current entry. If not, assume that it can be inserted at point.
12782 HOW is an indicator what kind of note should be created.
12783 EXTRA is additional text that will be inserted into the notes buffer."
12784 (let* ((org-log-into-drawer (org-log-into-drawer))
12785 (drawer (cond ((stringp org-log-into-drawer)
12786 org-log-into-drawer)
12787 (org-log-into-drawer "LOGBOOK"))))
12788 (save-restriction
12789 (save-excursion
12790 (when findpos
12791 (org-back-to-heading t)
12792 (narrow-to-region (point) (save-excursion
12793 (outline-next-heading) (point)))
12794 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12795 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12796 "[^\r\n]*\\)?"))
12797 (goto-char (match-end 0))
12798 (cond
12799 (drawer
12800 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12801 nil t)
12802 (progn
12803 (goto-char (match-end 0))
12804 (or org-log-states-order-reversed
12805 (and (re-search-forward org-property-end-re nil t)
12806 (goto-char (1- (match-beginning 0))))))
12807 (insert "\n:" drawer ":\n:END:")
12808 (beginning-of-line 0)
12809 (org-indent-line)
12810 (beginning-of-line 2)
12811 (org-indent-line)
12812 (end-of-line 0)))
12813 ((and org-log-state-notes-insert-after-drawers
12814 (save-excursion
12815 (forward-line) (looking-at org-drawer-regexp)))
12816 (forward-line)
12817 (while (looking-at org-drawer-regexp)
12818 (goto-char (match-end 0))
12819 (re-search-forward org-property-end-re (point-max) t)
12820 (forward-line))
12821 (forward-line -1)))
12822 (unless org-log-states-order-reversed
12823 (and (= (char-after) ?\n) (forward-char 1))
12824 (org-skip-over-state-notes)
12825 (skip-chars-backward " \t\n\r")))
12826 (move-marker org-log-note-marker (point))
12827 (setq org-log-note-purpose purpose
12828 org-log-note-state state
12829 org-log-note-previous-state prev-state
12830 org-log-note-how how
12831 org-log-note-extra extra
12832 org-log-note-effective-time (org-current-effective-time))
12833 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12835 (defun org-skip-over-state-notes ()
12836 "Skip past the list of State notes in an entry."
12837 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12838 (when (ignore-errors (goto-char (org-in-item-p)))
12839 (let* ((struct (org-list-struct))
12840 (prevs (org-list-prevs-alist struct)))
12841 (while (looking-at "[ \t]*- State")
12842 (goto-char (or (org-list-get-next-item (point) struct prevs)
12843 (org-list-get-item-end (point) struct)))))))
12845 (defun org-add-log-note (&optional purpose)
12846 "Pop up a window for taking a note, and add this note later at point."
12847 (remove-hook 'post-command-hook 'org-add-log-note)
12848 (setq org-log-note-window-configuration (current-window-configuration))
12849 (delete-other-windows)
12850 (move-marker org-log-note-return-to (point))
12851 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12852 (goto-char org-log-note-marker)
12853 (org-switch-to-buffer-other-window "*Org Note*")
12854 (erase-buffer)
12855 (if (memq org-log-note-how '(time state))
12856 (let (current-prefix-arg) (org-store-log-note))
12857 (let ((org-inhibit-startup t)) (org-mode))
12858 (insert (format "# Insert note for %s.
12859 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12860 (cond
12861 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12862 ((eq org-log-note-purpose 'done) "closed todo item")
12863 ((eq org-log-note-purpose 'state)
12864 (format "state change from \"%s\" to \"%s\""
12865 (or org-log-note-previous-state "")
12866 (or org-log-note-state "")))
12867 ((eq org-log-note-purpose 'reschedule)
12868 "rescheduling")
12869 ((eq org-log-note-purpose 'delschedule)
12870 "no longer scheduled")
12871 ((eq org-log-note-purpose 'redeadline)
12872 "changing deadline")
12873 ((eq org-log-note-purpose 'deldeadline)
12874 "removing deadline")
12875 ((eq org-log-note-purpose 'refile)
12876 "refiling")
12877 ((eq org-log-note-purpose 'note)
12878 "this entry")
12879 (t (error "This should not happen")))))
12880 (if org-log-note-extra (insert org-log-note-extra))
12881 (org-set-local 'org-finish-function 'org-store-log-note)
12882 (run-hooks 'org-log-buffer-setup-hook)))
12884 (defvar org-note-abort nil) ; dynamically scoped
12885 (defun org-store-log-note ()
12886 "Finish taking a log note, and insert it to where it belongs."
12887 (let ((txt (buffer-string)))
12888 (kill-buffer (current-buffer))
12889 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12890 lines ind bul)
12891 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12892 (setq txt (replace-match "" t t txt)))
12893 (if (string-match "\\s-+\\'" txt)
12894 (setq txt (replace-match "" t t txt)))
12895 (setq lines (org-split-string txt "\n"))
12896 (when (and note (string-match "\\S-" note))
12897 (setq note
12898 (org-replace-escapes
12899 note
12900 (list (cons "%u" (user-login-name))
12901 (cons "%U" user-full-name)
12902 (cons "%t" (format-time-string
12903 (org-time-stamp-format 'long 'inactive)
12904 org-log-note-effective-time))
12905 (cons "%T" (format-time-string
12906 (org-time-stamp-format 'long nil)
12907 org-log-note-effective-time))
12908 (cons "%d" (format-time-string
12909 (org-time-stamp-format nil 'inactive)
12910 org-log-note-effective-time))
12911 (cons "%D" (format-time-string
12912 (org-time-stamp-format nil nil)
12913 org-log-note-effective-time))
12914 (cons "%s" (if org-log-note-state
12915 (concat "\"" org-log-note-state "\"")
12916 ""))
12917 (cons "%S" (if org-log-note-previous-state
12918 (concat "\"" org-log-note-previous-state "\"")
12919 "\"\"")))))
12920 (if lines (setq note (concat note " \\\\")))
12921 (push note lines))
12922 (when (or current-prefix-arg org-note-abort)
12923 (when org-log-into-drawer
12924 (org-remove-empty-drawer-at
12925 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12926 org-log-note-marker))
12927 (setq lines nil))
12928 (when lines
12929 (with-current-buffer (marker-buffer org-log-note-marker)
12930 (save-excursion
12931 (goto-char org-log-note-marker)
12932 (move-marker org-log-note-marker nil)
12933 (end-of-line 1)
12934 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12935 (setq ind (save-excursion
12936 (if (ignore-errors (goto-char (org-in-item-p)))
12937 (let ((struct (org-list-struct)))
12938 (org-list-get-ind
12939 (org-list-get-top-point struct) struct))
12940 (skip-chars-backward " \r\t\n")
12941 (cond
12942 ((and (org-at-heading-p)
12943 org-adapt-indentation)
12944 (1+ (org-current-level)))
12945 ((org-at-heading-p) 0)
12946 (t (org-get-indentation))))))
12947 (setq bul (org-list-bullet-string "-"))
12948 (org-indent-line-to ind)
12949 (insert bul (pop lines))
12950 (let ((ind-body (+ (length bul) ind)))
12951 (while lines
12952 (insert "\n")
12953 (org-indent-line-to ind-body)
12954 (insert (pop lines))))
12955 (message "Note stored")
12956 (org-back-to-heading t)
12957 (org-cycle-hide-drawers 'children))))))
12958 (set-window-configuration org-log-note-window-configuration)
12959 (with-current-buffer (marker-buffer org-log-note-return-to)
12960 (goto-char org-log-note-return-to))
12961 (move-marker org-log-note-return-to nil)
12962 (and org-log-post-message (message "%s" org-log-post-message)))
12964 (defun org-remove-empty-drawer-at (drawer pos)
12965 "Remove an empty drawer DRAWER at position POS.
12966 POS may also be a marker."
12967 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12968 (save-excursion
12969 (save-restriction
12970 (widen)
12971 (goto-char pos)
12972 (if (org-in-regexp
12973 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12974 (replace-match ""))))))
12976 (defvar org-ts-type nil)
12977 (defun org-sparse-tree (&optional arg type)
12978 "Create a sparse tree, prompt for the details.
12979 This command can create sparse trees. You first need to select the type
12980 of match used to create the tree:
12982 t Show all TODO entries.
12983 T Show entries with a specific TODO keyword.
12984 m Show entries selected by a tags/property match.
12985 p Enter a property name and its value (both with completion on existing
12986 names/values) and show entries with that property.
12987 r Show entries matching a regular expression (`/' can be used as well).
12988 b Show deadlines and scheduled items before a date.
12989 a Show deadlines and scheduled items after a date.
12990 d Show deadlines due within `org-deadline-warning-days'.
12991 D Show deadlines and scheduled items between a date range."
12992 (interactive "P")
12993 (let (ans kwd value ts-type)
12994 (setq type (or type org-sparse-tree-default-date-type))
12995 (setq org-ts-type type)
12996 (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"
12997 (cond ((eq type 'all) "all timestamps")
12998 ((eq type 'scheduled) "only scheduled")
12999 ((eq type 'deadline) "only deadline")
13000 ((eq type 'active) "only active timestamps")
13001 ((eq type 'inactive) "only inactive timestamps")
13002 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13003 (t "scheduled/deadline")))
13004 (setq ans (read-char-exclusive))
13005 (cond
13006 ((equal ans ?c)
13007 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13008 ((equal ans ?d)
13009 (call-interactively 'org-check-deadlines))
13010 ((equal ans ?b)
13011 (call-interactively 'org-check-before-date))
13012 ((equal ans ?a)
13013 (call-interactively 'org-check-after-date))
13014 ((equal ans ?D)
13015 (call-interactively 'org-check-dates-range))
13016 ((equal ans ?t)
13017 (call-interactively 'org-show-todo-tree))
13018 ((equal ans ?T)
13019 (org-show-todo-tree '(4)))
13020 ((member ans '(?T ?m))
13021 (call-interactively 'org-match-sparse-tree))
13022 ((member ans '(?p ?P))
13023 (setq kwd (org-icompleting-read "Property: "
13024 (mapcar 'list (org-buffer-property-keys))))
13025 (setq value (org-icompleting-read "Value: "
13026 (mapcar 'list (org-property-values kwd))))
13027 (unless (string-match "\\`{.*}\\'" value)
13028 (setq value (concat "\"" value "\"")))
13029 (org-match-sparse-tree arg (concat kwd "=" value)))
13030 ((member ans '(?r ?R ?/))
13031 (call-interactively 'org-occur))
13032 (t (error "No such sparse tree command \"%c\"" ans)))))
13034 (defvar org-occur-highlights nil
13035 "List of overlays used for occur matches.")
13036 (make-variable-buffer-local 'org-occur-highlights)
13037 (defvar org-occur-parameters nil
13038 "Parameters of the active org-occur calls.
13039 This is a list, each call to org-occur pushes as cons cell,
13040 containing the regular expression and the callback, onto the list.
13041 The list can contain several entries if `org-occur' has been called
13042 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13043 will only contain one set of parameters. When the highlights are
13044 removed (for example with `C-c C-c', or with the next edit (depending
13045 on `org-remove-highlights-with-change'), this variable is emptied
13046 as well.")
13047 (make-variable-buffer-local 'org-occur-parameters)
13049 (defun org-occur (regexp &optional keep-previous callback)
13050 "Make a compact tree which shows all matches of REGEXP.
13051 The tree will show the lines where the regexp matches, and all higher
13052 headlines above the match. It will also show the heading after the match,
13053 to make sure editing the matching entry is easy.
13054 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13055 call to `org-occur' will be kept, to allow stacking of calls to this
13056 command.
13057 If CALLBACK is non-nil, it is a function which is called to confirm
13058 that the match should indeed be shown."
13059 (interactive "sRegexp: \nP")
13060 (when (equal regexp "")
13061 (error "Regexp cannot be empty"))
13062 (unless keep-previous
13063 (org-remove-occur-highlights nil nil t))
13064 (push (cons regexp callback) org-occur-parameters)
13065 (let ((cnt 0))
13066 (save-excursion
13067 (goto-char (point-min))
13068 (if (or (not keep-previous) ; do not want to keep
13069 (not org-occur-highlights)) ; no previous matches
13070 ;; hide everything
13071 (org-overview))
13072 (while (re-search-forward regexp nil t)
13073 (when (or (not callback)
13074 (save-match-data (funcall callback)))
13075 (setq cnt (1+ cnt))
13076 (when org-highlight-sparse-tree-matches
13077 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13078 (org-show-context 'occur-tree))))
13079 (when org-remove-highlights-with-change
13080 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13081 nil 'local))
13082 (unless org-sparse-tree-open-archived-trees
13083 (org-hide-archived-subtrees (point-min) (point-max)))
13084 (run-hooks 'org-occur-hook)
13085 (if (org-called-interactively-p 'interactive)
13086 (message "%d match(es) for regexp %s" cnt regexp))
13087 cnt))
13089 (defun org-occur-next-match (&optional n reset)
13090 "Function for `next-error-function' to find sparse tree matches.
13091 N is the number of matches to move, when negative move backwards.
13092 RESET is entirely ignored - this function always goes back to the
13093 starting point when no match is found."
13094 (let* ((limit (if (< n 0) (point-min) (point-max)))
13095 (search-func (if (< n 0)
13096 'previous-single-char-property-change
13097 'next-single-char-property-change))
13098 (n (abs n))
13099 (pos (point))
13101 (catch 'exit
13102 (while (setq p1 (funcall search-func (point) 'org-type))
13103 (when (equal p1 limit)
13104 (goto-char pos)
13105 (error "No more matches"))
13106 (when (equal (get-char-property p1 'org-type) 'org-occur)
13107 (setq n (1- n))
13108 (when (= n 0)
13109 (goto-char p1)
13110 (throw 'exit (point))))
13111 (goto-char p1))
13112 (goto-char p1)
13113 (error "No more matches"))))
13115 (defun org-show-context (&optional key)
13116 "Make sure point and context are visible.
13117 How much context is shown depends upon the variables
13118 `org-show-hierarchy-above', `org-show-following-heading',
13119 `org-show-entry-below' and `org-show-siblings'."
13120 (let ((heading-p (org-at-heading-p t))
13121 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13122 (following-p (org-get-alist-option org-show-following-heading key))
13123 (entry-p (org-get-alist-option org-show-entry-below key))
13124 (siblings-p (org-get-alist-option org-show-siblings key)))
13125 (catch 'exit
13126 ;; Show heading or entry text
13127 (if (and heading-p (not entry-p))
13128 (org-flag-heading nil) ; only show the heading
13129 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13130 (org-show-hidden-entry))) ; show entire entry
13131 (when following-p
13132 ;; Show next sibling, or heading below text
13133 (save-excursion
13134 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13135 (org-flag-heading nil))))
13136 (when siblings-p (org-show-siblings))
13137 (when hierarchy-p
13138 ;; show all higher headings, possibly with siblings
13139 (save-excursion
13140 (while (and (condition-case nil
13141 (progn (org-up-heading-all 1) t)
13142 (error nil))
13143 (not (bobp)))
13144 (org-flag-heading nil)
13145 (when siblings-p (org-show-siblings))))))))
13147 (defvar org-reveal-start-hook nil
13148 "Hook run before revealing a location.")
13150 (defun org-reveal (&optional siblings)
13151 "Show current entry, hierarchy above it, and the following headline.
13152 This can be used to show a consistent set of context around locations
13153 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13154 not t for the search context.
13156 With optional argument SIBLINGS, on each level of the hierarchy all
13157 siblings are shown. This repairs the tree structure to what it would
13158 look like when opened with hierarchical calls to `org-cycle'.
13159 With double optional argument \\[universal-argument] \\[universal-argument], \
13160 go to the parent and show the
13161 entire tree."
13162 (interactive "P")
13163 (run-hooks 'org-reveal-start-hook)
13164 (let ((org-show-hierarchy-above t)
13165 (org-show-following-heading t)
13166 (org-show-siblings (if siblings t org-show-siblings)))
13167 (org-show-context nil))
13168 (when (equal siblings '(16))
13169 (save-excursion
13170 (when (org-up-heading-safe)
13171 (org-show-subtree)
13172 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13174 (defun org-highlight-new-match (beg end)
13175 "Highlight from BEG to END and mark the highlight is an occur headline."
13176 (let ((ov (make-overlay beg end)))
13177 (overlay-put ov 'face 'secondary-selection)
13178 (overlay-put ov 'org-type 'org-occur)
13179 (push ov org-occur-highlights)))
13181 (defun org-remove-occur-highlights (&optional beg end noremove)
13182 "Remove the occur highlights from the buffer.
13183 BEG and END are ignored. If NOREMOVE is nil, remove this function
13184 from the `before-change-functions' in the current buffer."
13185 (interactive)
13186 (unless org-inhibit-highlight-removal
13187 (mapc 'delete-overlay org-occur-highlights)
13188 (setq org-occur-highlights nil)
13189 (setq org-occur-parameters nil)
13190 (unless noremove
13191 (remove-hook 'before-change-functions
13192 'org-remove-occur-highlights 'local))))
13194 ;;;; Priorities
13196 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13197 "Regular expression matching the priority indicator.")
13199 (defvar org-remove-priority-next-time nil)
13201 (defun org-priority-up ()
13202 "Increase the priority of the current item."
13203 (interactive)
13204 (org-priority 'up))
13206 (defun org-priority-down ()
13207 "Decrease the priority of the current item."
13208 (interactive)
13209 (org-priority 'down))
13211 (defun org-priority (&optional action show)
13212 "Change the priority of an item.
13213 ACTION can be `set', `up', `down', or a character."
13214 (interactive "P")
13215 (if (equal action '(4))
13216 (org-show-priority)
13217 (unless org-enable-priority-commands
13218 (error "Priority commands are disabled"))
13219 (setq action (or action 'set))
13220 (let (current new news have remove)
13221 (save-excursion
13222 (org-back-to-heading t)
13223 (if (looking-at org-priority-regexp)
13224 (setq current (string-to-char (match-string 2))
13225 have t))
13226 (cond
13227 ((eq action 'remove)
13228 (setq remove t new ?\ ))
13229 ((or (eq action 'set)
13230 (if (featurep 'xemacs) (characterp action) (integerp action)))
13231 (if (not (eq action 'set))
13232 (setq new action)
13233 (message "Priority %c-%c, SPC to remove: "
13234 org-highest-priority org-lowest-priority)
13235 (save-match-data
13236 (setq new (read-char-exclusive))))
13237 (if (and (= (upcase org-highest-priority) org-highest-priority)
13238 (= (upcase org-lowest-priority) org-lowest-priority))
13239 (setq new (upcase new)))
13240 (cond ((equal new ?\ ) (setq remove t))
13241 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13242 (error "Priority must be between `%c' and `%c'"
13243 org-highest-priority org-lowest-priority))))
13244 ((eq action 'up)
13245 (setq new (if have
13246 (1- current) ; normal cycling
13247 ;; last priority was empty
13248 (if (eq last-command this-command)
13249 org-lowest-priority ; wrap around empty to lowest
13250 ;; default
13251 (if org-priority-start-cycle-with-default
13252 org-default-priority
13253 (1- org-default-priority))))))
13254 ((eq action 'down)
13255 (setq new (if have
13256 (1+ current) ; normal cycling
13257 ;; last priority was empty
13258 (if (eq last-command this-command)
13259 org-highest-priority ; wrap around empty to highest
13260 ;; default
13261 (if org-priority-start-cycle-with-default
13262 org-default-priority
13263 (1+ org-default-priority))))))
13264 (t (error "Invalid action")))
13265 (if (or (< (upcase new) org-highest-priority)
13266 (> (upcase new) org-lowest-priority))
13267 (if (and (memq action '(up down))
13268 (not have) (not (eq last-command this-command)))
13269 ;; `new' is from default priority
13270 (error
13271 "The default can not be set, see `org-default-priority' why")
13272 ;; normal cycling: `new' is beyond highest/lowest priority
13273 ;; and is wrapped around to the empty priority
13274 (setq remove t)))
13275 (setq news (format "%c" new))
13276 (if have
13277 (if remove
13278 (replace-match "" t t nil 1)
13279 (replace-match news t t nil 2))
13280 (if remove
13281 (error "No priority cookie found in line")
13282 (let ((case-fold-search nil))
13283 (looking-at org-todo-line-regexp))
13284 (if (match-end 2)
13285 (progn
13286 (goto-char (match-end 2))
13287 (insert " [#" news "]"))
13288 (goto-char (match-beginning 3))
13289 (insert "[#" news "] "))))
13290 (org-preserve-lc (org-set-tags nil 'align)))
13291 (if remove
13292 (message "Priority removed")
13293 (message "Priority of current item set to %s" news)))))
13295 (defun org-show-priority ()
13296 "Show the priority of the current item.
13297 This priority is composed of the main priority given with the [#A] cookies,
13298 and by additional input from the age of a schedules or deadline entry."
13299 (interactive)
13300 (let ((pri (if (eq major-mode 'org-agenda-mode)
13301 (org-get-at-bol 'priority)
13302 (save-excursion
13303 (save-match-data
13304 (beginning-of-line)
13305 (and (looking-at org-heading-regexp)
13306 (org-get-priority (match-string 0))))))))
13307 (message "Priority is %d" (if pri pri -1000))))
13309 (defun org-get-priority (s)
13310 "Find priority cookie and return priority."
13311 (save-match-data
13312 (if (functionp org-get-priority-function)
13313 (funcall org-get-priority-function)
13314 (if (not (string-match org-priority-regexp s))
13315 (* 1000 (- org-lowest-priority org-default-priority))
13316 (* 1000 (- org-lowest-priority
13317 (string-to-char (match-string 2 s))))))))
13319 ;;;; Tags
13321 (defvar org-agenda-archives-mode)
13322 (defvar org-map-continue-from nil
13323 "Position from where mapping should continue.
13324 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13326 (defvar org-scanner-tags nil
13327 "The current tag list while the tags scanner is running.")
13328 (defvar org-trust-scanner-tags nil
13329 "Should `org-get-tags-at' use the tags for the scanner.
13330 This is for internal dynamical scoping only.
13331 When this is non-nil, the function `org-get-tags-at' will return the value
13332 of `org-scanner-tags' instead of building the list by itself. This
13333 can lead to large speed-ups when the tags scanner is used in a file with
13334 many entries, and when the list of tags is retrieved, for example to
13335 obtain a list of properties. Building the tags list for each entry in such
13336 a file becomes an N^2 operation - but with this variable set, it scales
13337 as N.")
13339 (defun org-scan-tags (action matcher todo-only &optional start-level)
13340 "Scan headline tags with inheritance and produce output ACTION.
13342 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13343 or `agenda' to produce an entry list for an agenda view. It can also be
13344 a Lisp form or a function that should be called at each matched headline, in
13345 this case the return value is a list of all return values from these calls.
13347 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13348 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13349 only lines with a not-done TODO keyword are included in the output.
13350 This should be the same variable that was scoped into
13351 and set by `org-make-tags-matcher' when it constructed MATCHER.
13353 START-LEVEL can be a string with asterisks, reducing the scope to
13354 headlines matching this string."
13355 (require 'org-agenda)
13356 (let* ((re (concat "^"
13357 (if start-level
13358 ;; Get the correct level to match
13359 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13360 org-outline-regexp)
13361 " *\\(\\<\\("
13362 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13363 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13364 (props (list 'face 'default
13365 'done-face 'org-agenda-done
13366 'undone-face 'default
13367 'mouse-face 'highlight
13368 'org-not-done-regexp org-not-done-regexp
13369 'org-todo-regexp org-todo-regexp
13370 'org-complex-heading-regexp org-complex-heading-regexp
13371 'help-echo
13372 (format "mouse-2 or RET jump to org file %s"
13373 (abbreviate-file-name
13374 (or (buffer-file-name (buffer-base-buffer))
13375 (buffer-name (buffer-base-buffer)))))))
13376 (case-fold-search nil)
13377 (org-map-continue-from nil)
13378 lspos tags tags-list
13379 (tags-alist (list (cons 0 org-file-tags)))
13380 (llast 0) rtn rtn1 level category i txt
13381 todo marker entry priority)
13382 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13383 (setq action (list 'lambda nil action)))
13384 (save-excursion
13385 (goto-char (point-min))
13386 (when (eq action 'sparse-tree)
13387 (org-overview)
13388 (org-remove-occur-highlights))
13389 (while (re-search-forward re nil t)
13390 (setq org-map-continue-from nil)
13391 (catch :skip
13392 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13393 tags (if (match-end 4) (org-match-string-no-properties 4)))
13394 (goto-char (setq lspos (match-beginning 0)))
13395 (setq level (org-reduced-level (org-outline-level))
13396 category (org-get-category))
13397 (setq i llast llast level)
13398 ;; remove tag lists from same and sublevels
13399 (while (>= i level)
13400 (when (setq entry (assoc i tags-alist))
13401 (setq tags-alist (delete entry tags-alist)))
13402 (setq i (1- i)))
13403 ;; add the next tags
13404 (when tags
13405 (setq tags (org-split-string tags ":")
13406 tags-alist
13407 (cons (cons level tags) tags-alist)))
13408 ;; compile tags for current headline
13409 (setq tags-list
13410 (if org-use-tag-inheritance
13411 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13412 tags)
13413 org-scanner-tags tags-list)
13414 (when org-use-tag-inheritance
13415 (setcdr (car tags-alist)
13416 (mapcar (lambda (x)
13417 (setq x (copy-sequence x))
13418 (org-add-prop-inherited x))
13419 (cdar tags-alist))))
13420 (when (and tags org-use-tag-inheritance
13421 (or (not (eq t org-use-tag-inheritance))
13422 org-tags-exclude-from-inheritance))
13423 ;; selective inheritance, remove uninherited ones
13424 (setcdr (car tags-alist)
13425 (org-remove-uninherited-tags (cdar tags-alist))))
13426 (when (and
13428 ;; eval matcher only when the todo condition is OK
13429 (and (or (not todo-only) (member todo org-not-done-keywords))
13430 (let ((case-fold-search t) (org-trust-scanner-tags t))
13431 (eval matcher)))
13433 ;; Call the skipper, but return t if it does not skip,
13434 ;; so that the `and' form continues evaluating
13435 (progn
13436 (unless (eq action 'sparse-tree) (org-agenda-skip))
13439 ;; Check if timestamps are deselecting this entry
13440 (or (not todo-only)
13441 (and (member todo org-not-done-keywords)
13442 (or (not org-agenda-tags-todo-honor-ignore-options)
13443 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13445 ;; select this headline
13446 (cond
13447 ((eq action 'sparse-tree)
13448 (and org-highlight-sparse-tree-matches
13449 (org-get-heading) (match-end 0)
13450 (org-highlight-new-match
13451 (match-beginning 1) (match-end 1)))
13452 (org-show-context 'tags-tree))
13453 ((eq action 'agenda)
13454 (setq txt (org-agenda-format-item
13456 (concat
13457 (if (eq org-tags-match-list-sublevels 'indented)
13458 (make-string (1- level) ?.) "")
13459 (org-get-heading))
13460 level category
13461 tags-list)
13462 priority (org-get-priority txt))
13463 (goto-char lspos)
13464 (setq marker (org-agenda-new-marker))
13465 (org-add-props txt props
13466 'org-marker marker 'org-hd-marker marker 'org-category category
13467 'todo-state todo
13468 'priority priority 'type "tagsmatch")
13469 (push txt rtn))
13470 ((functionp action)
13471 (setq org-map-continue-from nil)
13472 (save-excursion
13473 (setq rtn1 (funcall action))
13474 (push rtn1 rtn)))
13475 (t (error "Invalid action")))
13477 ;; if we are to skip sublevels, jump to end of subtree
13478 (unless org-tags-match-list-sublevels
13479 (org-end-of-subtree t)
13480 (backward-char 1))))
13481 ;; Get the correct position from where to continue
13482 (if org-map-continue-from
13483 (goto-char org-map-continue-from)
13484 (and (= (point) lspos) (end-of-line 1)))))
13485 (when (and (eq action 'sparse-tree)
13486 (not org-sparse-tree-open-archived-trees))
13487 (org-hide-archived-subtrees (point-min) (point-max)))
13488 (nreverse rtn)))
13490 (defun org-remove-uninherited-tags (tags)
13491 "Remove all tags that are not inherited from the list TAGS."
13492 (cond
13493 ((eq org-use-tag-inheritance t)
13494 (if org-tags-exclude-from-inheritance
13495 (org-delete-all org-tags-exclude-from-inheritance tags)
13496 tags))
13497 ((not org-use-tag-inheritance) nil)
13498 ((stringp org-use-tag-inheritance)
13499 (delq nil (mapcar
13500 (lambda (x)
13501 (if (and (string-match org-use-tag-inheritance x)
13502 (not (member x org-tags-exclude-from-inheritance)))
13503 x nil))
13504 tags)))
13505 ((listp org-use-tag-inheritance)
13506 (delq nil (mapcar
13507 (lambda (x)
13508 (if (member x org-use-tag-inheritance) x nil))
13509 tags)))))
13511 (defun org-match-sparse-tree (&optional todo-only match)
13512 "Create a sparse tree according to tags string MATCH.
13513 MATCH can contain positive and negative selection of tags, like
13514 \"+WORK+URGENT-WITHBOSS\".
13515 If optional argument TODO-ONLY is non-nil, only select lines that are
13516 also TODO lines."
13517 (interactive "P")
13518 (org-agenda-prepare-buffers (list (current-buffer)))
13519 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13521 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13523 (defvar org-cached-props nil)
13524 (defun org-cached-entry-get (pom property)
13525 (if (or (eq t org-use-property-inheritance)
13526 (and (stringp org-use-property-inheritance)
13527 (string-match org-use-property-inheritance property))
13528 (and (listp org-use-property-inheritance)
13529 (member property org-use-property-inheritance)))
13530 ;; Caching is not possible, check it directly
13531 (org-entry-get pom property 'inherit)
13532 ;; Get all properties, so that we can do complicated checks easily
13533 (cdr (assoc property (or org-cached-props
13534 (setq org-cached-props
13535 (org-entry-properties pom)))))))
13537 (defun org-global-tags-completion-table (&optional files)
13538 "Return the list of all tags in all agenda buffer/files.
13539 Optional FILES argument is a list of files which can be used
13540 instead of the agenda files."
13541 (save-excursion
13542 (org-uniquify
13543 (delq nil
13544 (apply 'append
13545 (mapcar
13546 (lambda (file)
13547 (set-buffer (find-file-noselect file))
13548 (append (org-get-buffer-tags)
13549 (mapcar (lambda (x) (if (stringp (car-safe x))
13550 (list (car-safe x)) nil))
13551 org-tag-alist)))
13552 (if (and files (car files))
13553 files
13554 (org-agenda-files))))))))
13556 (defun org-make-tags-matcher (match)
13557 "Create the TAGS/TODO matcher form for the selection string MATCH.
13559 The variable `todo-only' is scoped dynamically into this function.
13560 It will be set to t if the matcher restricts matching to TODO entries,
13561 otherwise will not be touched.
13563 Returns a cons of the selection string MATCH and the constructed
13564 lisp form implementing the matcher. The matcher is to be evaluated
13565 at an Org entry, with point on the headline, and returns t if the
13566 entry matches the selection string MATCH. The returned lisp form
13567 references two variables with information about the entry, which
13568 must be bound around the form's evaluation: todo, the TODO keyword
13569 at the entry (or nil of none); and tags-list, the list of all tags
13570 at the entry including inherited ones. Additionally, the category
13571 of the entry (if any) must be specified as the text property
13572 'org-category on the headline.
13574 See also `org-scan-tags'.
13576 (declare (special todo-only))
13577 (unless (boundp 'todo-only)
13578 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13579 (unless match
13580 ;; Get a new match request, with completion
13581 (let ((org-last-tags-completion-table
13582 (org-global-tags-completion-table)))
13583 (setq match (org-completing-read-no-i
13584 "Match: " 'org-tags-completion-function nil nil nil
13585 'org-tags-history))))
13587 ;; Parse the string and create a lisp form
13588 (let ((match0 match)
13589 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13590 minus tag mm
13591 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13592 orterms term orlist re-p str-p level-p level-op time-p
13593 prop-p pn pv po gv rest)
13594 (if (string-match "/+" match)
13595 ;; match contains also a todo-matching request
13596 (progn
13597 (setq tagsmatch (substring match 0 (match-beginning 0))
13598 todomatch (substring match (match-end 0)))
13599 (if (string-match "^!" todomatch)
13600 (setq todo-only t todomatch (substring todomatch 1)))
13601 (if (string-match "^\\s-*$" todomatch)
13602 (setq todomatch nil)))
13603 ;; only matching tags
13604 (setq tagsmatch match todomatch nil))
13606 ;; Make the tags matcher
13607 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13608 (setq tagsmatcher t)
13609 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13610 (while (setq term (pop orterms))
13611 (while (and (equal (substring term -1) "\\") orterms)
13612 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13613 (while (string-match re term)
13614 (setq rest (substring term (match-end 0))
13615 minus (and (match-end 1)
13616 (equal (match-string 1 term) "-"))
13617 tag (save-match-data (replace-regexp-in-string
13618 "\\\\-" "-"
13619 (match-string 2 term)))
13620 re-p (equal (string-to-char tag) ?{)
13621 level-p (match-end 4)
13622 prop-p (match-end 5)
13623 mm (cond
13624 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13625 (level-p
13626 (setq level-op (org-op-to-function (match-string 3 term)))
13627 `(,level-op level ,(string-to-number
13628 (match-string 4 term))))
13629 (prop-p
13630 (setq pn (match-string 5 term)
13631 po (match-string 6 term)
13632 pv (match-string 7 term)
13633 re-p (equal (string-to-char pv) ?{)
13634 str-p (equal (string-to-char pv) ?\")
13635 time-p (save-match-data
13636 (string-match "^\"[[<].*[]>]\"$" pv))
13637 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13638 (if time-p (setq pv (org-matcher-time pv)))
13639 (setq po (org-op-to-function po (if time-p 'time str-p)))
13640 (cond
13641 ((equal pn "CATEGORY")
13642 (setq gv '(get-text-property (point) 'org-category)))
13643 ((equal pn "TODO")
13644 (setq gv 'todo))
13646 (setq gv `(org-cached-entry-get nil ,pn))))
13647 (if re-p
13648 (if (eq po 'org<>)
13649 `(not (string-match ,pv (or ,gv "")))
13650 `(string-match ,pv (or ,gv "")))
13651 (if str-p
13652 `(,po (or ,gv "") ,pv)
13653 `(,po (string-to-number (or ,gv ""))
13654 ,(string-to-number pv) ))))
13655 (t `(member ,tag tags-list)))
13656 mm (if minus (list 'not mm) mm)
13657 term rest)
13658 (push mm tagsmatcher))
13659 (push (if (> (length tagsmatcher) 1)
13660 (cons 'and tagsmatcher)
13661 (car tagsmatcher))
13662 orlist)
13663 (setq tagsmatcher nil))
13664 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13665 (setq tagsmatcher
13666 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13667 ;; Make the todo matcher
13668 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13669 (setq todomatcher t)
13670 (setq orterms (org-split-string todomatch "|") orlist nil)
13671 (while (setq term (pop orterms))
13672 (while (string-match re term)
13673 (setq minus (and (match-end 1)
13674 (equal (match-string 1 term) "-"))
13675 kwd (match-string 2 term)
13676 re-p (equal (string-to-char kwd) ?{)
13677 term (substring term (match-end 0))
13678 mm (if re-p
13679 `(string-match ,(substring kwd 1 -1) todo)
13680 (list 'equal 'todo kwd))
13681 mm (if minus (list 'not mm) mm))
13682 (push mm todomatcher))
13683 (push (if (> (length todomatcher) 1)
13684 (cons 'and todomatcher)
13685 (car todomatcher))
13686 orlist)
13687 (setq todomatcher nil))
13688 (setq todomatcher (if (> (length orlist) 1)
13689 (cons 'or orlist) (car orlist))))
13691 ;; Return the string and lisp forms of the matcher
13692 (setq matcher (if todomatcher
13693 (list 'and tagsmatcher todomatcher)
13694 tagsmatcher))
13695 (when todo-only
13696 (setq matcher (list 'and '(member todo org-not-done-keywords)
13697 matcher)))
13698 (cons match0 matcher)))
13700 (defun org-op-to-function (op &optional stringp)
13701 "Turn an operator into the appropriate function."
13702 (setq op
13703 (cond
13704 ((equal op "<" ) '(< string< org-time<))
13705 ((equal op ">" ) '(> org-string> org-time>))
13706 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13707 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13708 ((member op '("=" "==")) '(= string= org-time=))
13709 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13710 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13712 (defun org<> (a b) (not (= a b)))
13713 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13714 (defun org-string>= (a b) (not (string< a b)))
13715 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13716 (defun org-string<> (a b) (not (string= a b)))
13717 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13718 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13719 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13720 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13721 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13722 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13723 (defun org-2ft (s)
13724 "Convert S to a floating point time.
13725 If S is already a number, just return it. If it is a string, parse
13726 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13727 (cond
13728 ((numberp s) s)
13729 ((stringp s)
13730 (condition-case nil
13731 (float-time (apply 'encode-time (org-parse-time-string s)))
13732 (error 0.)))
13733 (t 0.)))
13735 (defun org-time-today ()
13736 "Time in seconds today at 0:00.
13737 Returns the float number of seconds since the beginning of the
13738 epoch to the beginning of today (00:00)."
13739 (float-time (apply 'encode-time
13740 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13742 (defun org-matcher-time (s)
13743 "Interpret a time comparison value."
13744 (save-match-data
13745 (cond
13746 ((string= s "<now>") (float-time))
13747 ((string= s "<today>") (org-time-today))
13748 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13749 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13750 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13751 (+ (org-time-today)
13752 (* (string-to-number (match-string 1 s))
13753 (cdr (assoc (match-string 2 s)
13754 '(("d" . 86400.0) ("w" . 604800.0)
13755 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13756 (t (org-2ft s)))))
13758 (defun org-match-any-p (re list)
13759 "Does re match any element of list?"
13760 (setq list (mapcar (lambda (x) (string-match re x)) list))
13761 (delq nil list))
13763 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13764 (defvar org-tags-overlay (make-overlay 1 1))
13765 (org-detach-overlay org-tags-overlay)
13767 (defun org-get-local-tags-at (&optional pos)
13768 "Get a list of tags defined in the current headline."
13769 (org-get-tags-at pos 'local))
13771 (defun org-get-local-tags ()
13772 "Get a list of tags defined in the current headline."
13773 (org-get-tags-at nil 'local))
13775 (defun org-get-tags-at (&optional pos local)
13776 "Get a list of all headline tags applicable at POS.
13777 POS defaults to point. If tags are inherited, the list contains
13778 the targets in the same sequence as the headlines appear, i.e.
13779 the tags of the current headline come last.
13780 When LOCAL is non-nil, only return tags from the current headline,
13781 ignore inherited ones."
13782 (interactive)
13783 (if (and org-trust-scanner-tags
13784 (or (not pos) (equal pos (point)))
13785 (not local))
13786 org-scanner-tags
13787 (let (tags ltags lastpos parent)
13788 (save-excursion
13789 (save-restriction
13790 (widen)
13791 (goto-char (or pos (point)))
13792 (save-match-data
13793 (catch 'done
13794 (condition-case nil
13795 (progn
13796 (org-back-to-heading t)
13797 (while (not (equal lastpos (point)))
13798 (setq lastpos (point))
13799 (when (looking-at
13800 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13801 (setq ltags (org-split-string
13802 (org-match-string-no-properties 1) ":"))
13803 (when parent
13804 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13805 (setq tags (append
13806 (if parent
13807 (org-remove-uninherited-tags ltags)
13808 ltags)
13809 tags)))
13810 (or org-use-tag-inheritance (throw 'done t))
13811 (if local (throw 'done t))
13812 (or (org-up-heading-safe) (error nil))
13813 (setq parent t)))
13814 (error nil)))))
13815 (if local
13816 tags
13817 (reverse (delete-dups
13818 (reverse (append
13819 (org-remove-uninherited-tags
13820 org-file-tags) tags)))))))))
13822 (defun org-add-prop-inherited (s)
13823 (add-text-properties 0 (length s) '(inherited t) s)
13826 (defun org-toggle-tag (tag &optional onoff)
13827 "Toggle the tag TAG for the current line.
13828 If ONOFF is `on' or `off', don't toggle but set to this state."
13829 (let (res current)
13830 (save-excursion
13831 (org-back-to-heading t)
13832 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13833 (point-at-eol) t)
13834 (progn
13835 (setq current (match-string 1))
13836 (replace-match ""))
13837 (setq current ""))
13838 (setq current (nreverse (org-split-string current ":")))
13839 (cond
13840 ((eq onoff 'on)
13841 (setq res t)
13842 (or (member tag current) (push tag current)))
13843 ((eq onoff 'off)
13844 (or (not (member tag current)) (setq current (delete tag current))))
13845 (t (if (member tag current)
13846 (setq current (delete tag current))
13847 (setq res t)
13848 (push tag current))))
13849 (end-of-line 1)
13850 (if current
13851 (progn
13852 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13853 (org-set-tags nil t))
13854 (delete-horizontal-space))
13855 (run-hooks 'org-after-tags-change-hook))
13856 res))
13858 (defun org-align-tags-here (to-col)
13859 ;; Assumes that this is a headline
13860 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13861 (beginning-of-line 1)
13862 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13863 (< pos (match-beginning 2)))
13864 (progn
13865 (setq tags-l (- (match-end 2) (match-beginning 2)))
13866 (goto-char (match-beginning 1))
13867 (insert " ")
13868 (delete-region (point) (1+ (match-beginning 2)))
13869 (setq ncol (max (current-column)
13870 (1+ col)
13871 (if (> to-col 0)
13872 to-col
13873 (- (abs to-col) tags-l))))
13874 (setq p (point))
13875 (insert (make-string (- ncol (current-column)) ?\ ))
13876 (setq ncol (current-column))
13877 (when indent-tabs-mode (tabify p (point-at-eol)))
13878 (org-move-to-column (min ncol col) t))
13879 (goto-char pos))))
13881 (defun org-set-tags-command (&optional arg just-align)
13882 "Call the set-tags command for the current entry."
13883 (interactive "P")
13884 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13885 (org-set-tags arg just-align)
13886 (save-excursion
13887 (org-back-to-heading t)
13888 (org-set-tags arg just-align))))
13890 (defun org-set-tags-to (data)
13891 "Set the tags of the current entry to DATA, replacing the current tags.
13892 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13893 If DATA is nil or the empty string, any tags will be removed."
13894 (interactive "sTags: ")
13895 (setq data
13896 (cond
13897 ((eq data nil) "")
13898 ((equal data "") "")
13899 ((stringp data)
13900 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13901 ":"))
13902 ((listp data)
13903 (concat ":" (mapconcat 'identity data ":") ":"))))
13904 (when data
13905 (save-excursion
13906 (org-back-to-heading t)
13907 (when (looking-at org-complex-heading-regexp)
13908 (if (match-end 5)
13909 (progn
13910 (goto-char (match-beginning 5))
13911 (insert data)
13912 (delete-region (point) (point-at-eol))
13913 (org-set-tags nil 'align))
13914 (goto-char (point-at-eol))
13915 (insert " " data)
13916 (org-set-tags nil 'align)))
13917 (beginning-of-line 1)
13918 (if (looking-at ".*?\\([ \t]+\\)$")
13919 (delete-region (match-beginning 1) (match-end 1))))))
13921 (defun org-align-all-tags ()
13922 "Align the tags i all headings."
13923 (interactive)
13924 (save-excursion
13925 (or (ignore-errors (org-back-to-heading t))
13926 (outline-next-heading))
13927 (if (org-at-heading-p)
13928 (org-set-tags t)
13929 (message "No headings"))))
13931 (defvar org-indent-indentation-per-level)
13932 (defun org-set-tags (&optional arg just-align)
13933 "Set the tags for the current headline.
13934 With prefix ARG, realign all tags in headings in the current buffer."
13935 (interactive "P")
13936 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13937 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13938 'region-start-level 'region))
13939 org-loop-over-headlines-in-active-region)
13940 (org-map-entries
13941 ;; We don't use ARG and JUST-ALIGN here these args are not
13942 ;; useful when looping over headlines
13943 `(org-set-tags)
13944 org-loop-over-headlines-in-active-region
13945 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13946 (let* ((re org-outline-regexp-bol)
13947 (current (unless arg (org-get-tags-string)))
13948 (col (current-column))
13949 (org-setting-tags t)
13950 table current-tags inherited-tags ; computed below when needed
13951 tags p0 c0 c1 rpl di tc level)
13952 (if arg
13953 (save-excursion
13954 (goto-char (point-min))
13955 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13956 (while (re-search-forward re nil t)
13957 (org-set-tags nil t)
13958 (end-of-line 1)))
13959 (message "All tags realigned to column %d" org-tags-column))
13960 (if just-align
13961 (setq tags current)
13962 ;; Get a new set of tags from the user
13963 (save-excursion
13964 (setq table (append org-tag-persistent-alist
13965 (or org-tag-alist (org-get-buffer-tags))
13966 (and
13967 org-complete-tags-always-offer-all-agenda-tags
13968 (org-global-tags-completion-table
13969 (org-agenda-files))))
13970 org-last-tags-completion-table table
13971 current-tags (org-split-string current ":")
13972 inherited-tags (nreverse
13973 (nthcdr (length current-tags)
13974 (nreverse (org-get-tags-at))))
13975 tags
13976 (if (or (eq t org-use-fast-tag-selection)
13977 (and org-use-fast-tag-selection
13978 (delq nil (mapcar 'cdr table))))
13979 (org-fast-tag-selection
13980 current-tags inherited-tags table
13981 (if org-fast-tag-selection-include-todo
13982 org-todo-key-alist))
13983 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13984 (org-trim
13985 (org-icompleting-read "Tags: "
13986 'org-tags-completion-function
13987 nil nil current 'org-tags-history))))))
13988 (while (string-match "[-+&]+" tags)
13989 ;; No boolean logic, just a list
13990 (setq tags (replace-match ":" t t tags))))
13992 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13994 (if org-tags-sort-function
13995 (setq tags (mapconcat 'identity
13996 (sort (org-split-string
13997 tags (org-re "[^[:alnum:]_@#%]+"))
13998 org-tags-sort-function) ":")))
14000 (if (string-match "\\`[\t ]*\\'" tags)
14001 (setq tags "")
14002 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14003 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14005 ;; Insert new tags at the correct column
14006 (beginning-of-line 1)
14007 (setq level (or (and (looking-at org-outline-regexp)
14008 (- (match-end 0) (point) 1))
14010 (cond
14011 ((and (equal current "") (equal tags "")))
14012 ((re-search-forward
14013 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14014 (point-at-eol) t)
14015 (if (equal tags "")
14016 (setq rpl "")
14017 (goto-char (match-beginning 0))
14018 (setq c0 (current-column)
14019 ;; compute offset for the case of org-indent-mode active
14020 di (if org-indent-mode
14021 (* (1- org-indent-indentation-per-level) (1- level))
14023 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14024 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14025 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14026 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14027 (replace-match rpl t t)
14028 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14029 tags)
14030 (t (error "Tags alignment failed")))
14031 (org-move-to-column col)
14032 (unless just-align
14033 (run-hooks 'org-after-tags-change-hook))))))
14035 (defun org-change-tag-in-region (beg end tag off)
14036 "Add or remove TAG for each entry in the region.
14037 This works in the agenda, and also in an org-mode buffer."
14038 (interactive
14039 (list (region-beginning) (region-end)
14040 (let ((org-last-tags-completion-table
14041 (if (derived-mode-p 'org-mode)
14042 (org-get-buffer-tags)
14043 (org-global-tags-completion-table))))
14044 (org-icompleting-read
14045 "Tag: " 'org-tags-completion-function nil nil nil
14046 'org-tags-history))
14047 (progn
14048 (message "[s]et or [r]emove? ")
14049 (equal (read-char-exclusive) ?r))))
14050 (if (fboundp 'deactivate-mark) (deactivate-mark))
14051 (let ((agendap (equal major-mode 'org-agenda-mode))
14052 l1 l2 m buf pos newhead (cnt 0))
14053 (goto-char end)
14054 (setq l2 (1- (org-current-line)))
14055 (goto-char beg)
14056 (setq l1 (org-current-line))
14057 (loop for l from l1 to l2 do
14058 (org-goto-line l)
14059 (setq m (get-text-property (point) 'org-hd-marker))
14060 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14061 (and agendap m))
14062 (setq buf (if agendap (marker-buffer m) (current-buffer))
14063 pos (if agendap m (point)))
14064 (with-current-buffer buf
14065 (save-excursion
14066 (save-restriction
14067 (goto-char pos)
14068 (setq cnt (1+ cnt))
14069 (org-toggle-tag tag (if off 'off 'on))
14070 (setq newhead (org-get-heading)))))
14071 (and agendap (org-agenda-change-all-lines newhead m))))
14072 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14074 (defun org-tags-completion-function (string predicate &optional flag)
14075 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14076 (confirm (lambda (x) (stringp (car x)))))
14077 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14078 (setq s1 (match-string 1 string)
14079 s2 (match-string 2 string))
14080 (setq s1 "" s2 string))
14081 (cond
14082 ((eq flag nil)
14083 ;; try completion
14084 (setq rtn (try-completion s2 ctable confirm))
14085 (if (stringp rtn)
14086 (setq rtn
14087 (concat s1 s2 (substring rtn (length s2))
14088 (if (and org-add-colon-after-tag-completion
14089 (assoc rtn ctable))
14090 ":" ""))))
14091 rtn)
14092 ((eq flag t)
14093 ;; all-completions
14094 (all-completions s2 ctable confirm)
14096 ((eq flag 'lambda)
14097 ;; exact match?
14098 (assoc s2 ctable)))
14101 (defun org-fast-tag-insert (kwd tags face &optional end)
14102 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14103 (insert (format "%-12s" (concat kwd ":"))
14104 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14105 (or end "")))
14107 (defun org-fast-tag-show-exit (flag)
14108 (save-excursion
14109 (org-goto-line 3)
14110 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14111 (replace-match ""))
14112 (when flag
14113 (end-of-line 1)
14114 (org-move-to-column (- (window-width) 19) t)
14115 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14117 (defun org-set-current-tags-overlay (current prefix)
14118 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14119 (if (featurep 'xemacs)
14120 (org-overlay-display org-tags-overlay (concat prefix s)
14121 'secondary-selection)
14122 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14123 (org-overlay-display org-tags-overlay (concat prefix s)))))
14125 (defvar org-last-tag-selection-key nil)
14126 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14127 "Fast tag selection with single keys.
14128 CURRENT is the current list of tags in the headline, INHERITED is the
14129 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14130 possibly with grouping information. TODO-TABLE is a similar table with
14131 TODO keywords, should these have keys assigned to them.
14132 If the keys are nil, a-z are automatically assigned.
14133 Returns the new tags string, or nil to not change the current settings."
14134 (let* ((fulltable (append table todo-table))
14135 (maxlen (apply 'max (mapcar
14136 (lambda (x)
14137 (if (stringp (car x)) (string-width (car x)) 0))
14138 fulltable)))
14139 (buf (current-buffer))
14140 (expert (eq org-fast-tag-selection-single-key 'expert))
14141 (buffer-tags nil)
14142 (fwidth (+ maxlen 3 1 3))
14143 (ncol (/ (- (window-width) 4) fwidth))
14144 (i-face 'org-done)
14145 (c-face 'org-todo)
14146 tg cnt e c char c1 c2 ntable tbl rtn
14147 ov-start ov-end ov-prefix
14148 (exit-after-next org-fast-tag-selection-single-key)
14149 (done-keywords org-done-keywords)
14150 groups ingroup)
14151 (save-excursion
14152 (beginning-of-line 1)
14153 (if (looking-at
14154 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14155 (setq ov-start (match-beginning 1)
14156 ov-end (match-end 1)
14157 ov-prefix "")
14158 (setq ov-start (1- (point-at-eol))
14159 ov-end (1+ ov-start))
14160 (skip-chars-forward "^\n\r")
14161 (setq ov-prefix
14162 (concat
14163 (buffer-substring (1- (point)) (point))
14164 (if (> (current-column) org-tags-column)
14166 (make-string (- org-tags-column (current-column)) ?\ ))))))
14167 (move-overlay org-tags-overlay ov-start ov-end)
14168 (save-window-excursion
14169 (if expert
14170 (set-buffer (get-buffer-create " *Org tags*"))
14171 (delete-other-windows)
14172 (split-window-vertically)
14173 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14174 (erase-buffer)
14175 (org-set-local 'org-done-keywords done-keywords)
14176 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14177 (org-fast-tag-insert "Current" current c-face "\n\n")
14178 (org-fast-tag-show-exit exit-after-next)
14179 (org-set-current-tags-overlay current ov-prefix)
14180 (setq tbl fulltable char ?a cnt 0)
14181 (while (setq e (pop tbl))
14182 (cond
14183 ((equal (car e) :startgroup)
14184 (push '() groups) (setq ingroup t)
14185 (when (not (= cnt 0))
14186 (setq cnt 0)
14187 (insert "\n"))
14188 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14189 ((equal (car e) :endgroup)
14190 (setq ingroup nil cnt 0)
14191 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14192 ((equal e '(:newline))
14193 (when (not (= cnt 0))
14194 (setq cnt 0)
14195 (insert "\n")
14196 (setq e (car tbl))
14197 (while (equal (car tbl) '(:newline))
14198 (insert "\n")
14199 (setq tbl (cdr tbl)))))
14201 (setq tg (copy-sequence (car e)) c2 nil)
14202 (if (cdr e)
14203 (setq c (cdr e))
14204 ;; automatically assign a character.
14205 (setq c1 (string-to-char
14206 (downcase (substring
14207 tg (if (= (string-to-char tg) ?@) 1 0)))))
14208 (if (or (rassoc c1 ntable) (rassoc c1 table))
14209 (while (or (rassoc char ntable) (rassoc char table))
14210 (setq char (1+ char)))
14211 (setq c2 c1))
14212 (setq c (or c2 char)))
14213 (if ingroup (push tg (car groups)))
14214 (setq tg (org-add-props tg nil 'face
14215 (cond
14216 ((not (assoc tg table))
14217 (org-get-todo-face tg))
14218 ((member tg current) c-face)
14219 ((member tg inherited) i-face))))
14220 (if (and (= cnt 0) (not ingroup)) (insert " "))
14221 (insert "[" c "] " tg (make-string
14222 (- fwidth 4 (length tg)) ?\ ))
14223 (push (cons tg c) ntable)
14224 (when (= (setq cnt (1+ cnt)) ncol)
14225 (insert "\n")
14226 (if ingroup (insert " "))
14227 (setq cnt 0)))))
14228 (setq ntable (nreverse ntable))
14229 (insert "\n")
14230 (goto-char (point-min))
14231 (if (not expert) (org-fit-window-to-buffer))
14232 (setq rtn
14233 (catch 'exit
14234 (while t
14235 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14236 (if (not groups) "no " "")
14237 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14238 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14239 (setq org-last-tag-selection-key c)
14240 (cond
14241 ((= c ?\r) (throw 'exit t))
14242 ((= c ?!)
14243 (setq groups (not groups))
14244 (goto-char (point-min))
14245 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14246 ((= c ?\C-c)
14247 (if (not expert)
14248 (org-fast-tag-show-exit
14249 (setq exit-after-next (not exit-after-next)))
14250 (setq expert nil)
14251 (delete-other-windows)
14252 (set-window-buffer (split-window-vertically) " *Org tags*")
14253 (org-switch-to-buffer-other-window " *Org tags*")
14254 (org-fit-window-to-buffer)))
14255 ((or (= c ?\C-g)
14256 (and (= c ?q) (not (rassoc c ntable))))
14257 (org-detach-overlay org-tags-overlay)
14258 (setq quit-flag t))
14259 ((= c ?\ )
14260 (setq current nil)
14261 (if exit-after-next (setq exit-after-next 'now)))
14262 ((= c ?\t)
14263 (condition-case nil
14264 (setq tg (org-icompleting-read
14265 "Tag: "
14266 (or buffer-tags
14267 (with-current-buffer buf
14268 (org-get-buffer-tags)))))
14269 (quit (setq tg "")))
14270 (when (string-match "\\S-" tg)
14271 (add-to-list 'buffer-tags (list tg))
14272 (if (member tg current)
14273 (setq current (delete tg current))
14274 (push tg current)))
14275 (if exit-after-next (setq exit-after-next 'now)))
14276 ((setq e (rassoc c todo-table) tg (car e))
14277 (with-current-buffer buf
14278 (save-excursion (org-todo tg)))
14279 (if exit-after-next (setq exit-after-next 'now)))
14280 ((setq e (rassoc c ntable) tg (car e))
14281 (if (member tg current)
14282 (setq current (delete tg current))
14283 (loop for g in groups do
14284 (if (member tg g)
14285 (mapc (lambda (x)
14286 (setq current (delete x current)))
14287 g)))
14288 (push tg current))
14289 (if exit-after-next (setq exit-after-next 'now))))
14291 ;; Create a sorted list
14292 (setq current
14293 (sort current
14294 (lambda (a b)
14295 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14296 (if (eq exit-after-next 'now) (throw 'exit t))
14297 (goto-char (point-min))
14298 (beginning-of-line 2)
14299 (delete-region (point) (point-at-eol))
14300 (org-fast-tag-insert "Current" current c-face)
14301 (org-set-current-tags-overlay current ov-prefix)
14302 (while (re-search-forward
14303 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14304 (setq tg (match-string 1))
14305 (add-text-properties
14306 (match-beginning 1) (match-end 1)
14307 (list 'face
14308 (cond
14309 ((member tg current) c-face)
14310 ((member tg inherited) i-face)
14311 (t (get-text-property (match-beginning 1) 'face))))))
14312 (goto-char (point-min)))))
14313 (org-detach-overlay org-tags-overlay)
14314 (if rtn
14315 (mapconcat 'identity current ":")
14316 nil))))
14318 (defun org-get-tags-string ()
14319 "Get the TAGS string in the current headline."
14320 (unless (org-at-heading-p t)
14321 (error "Not on a heading"))
14322 (save-excursion
14323 (beginning-of-line 1)
14324 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14325 (org-match-string-no-properties 1)
14326 "")))
14328 (defun org-get-tags ()
14329 "Get the list of tags specified in the current headline."
14330 (org-split-string (org-get-tags-string) ":"))
14332 (defun org-get-buffer-tags ()
14333 "Get a table of all tags used in the buffer, for completion."
14334 (let (tags)
14335 (save-excursion
14336 (goto-char (point-min))
14337 (while (re-search-forward
14338 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14339 (when (equal (char-after (point-at-bol 0)) ?*)
14340 (mapc (lambda (x) (add-to-list 'tags x))
14341 (org-split-string (org-match-string-no-properties 1) ":")))))
14342 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14343 (mapcar 'list tags)))
14345 ;;;; The mapping API
14347 (defun org-map-entries (func &optional match scope &rest skip)
14348 "Call FUNC at each headline selected by MATCH in SCOPE.
14350 FUNC is a function or a lisp form. The function will be called without
14351 arguments, with the cursor positioned at the beginning of the headline.
14352 The return values of all calls to the function will be collected and
14353 returned as a list.
14355 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14356 does not need to preserve point. After evaluation, the cursor will be
14357 moved to the end of the line (presumably of the headline of the
14358 processed entry) and search continues from there. Under some
14359 circumstances, this may not produce the wanted results. For example,
14360 if you have removed (e.g. archived) the current (sub)tree it could
14361 mean that the next entry will be skipped entirely. In such cases, you
14362 can specify the position from where search should continue by making
14363 FUNC set the variable `org-map-continue-from' to the desired buffer
14364 position.
14366 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14367 Only headlines that are matched by this query will be considered during
14368 the iteration. When MATCH is nil or t, all headlines will be
14369 visited by the iteration.
14371 SCOPE determines the scope of this command. It can be any of:
14373 nil The current buffer, respecting the restriction if any
14374 tree The subtree started with the entry at point
14375 region The entries within the active region, if any
14376 region-start-level
14377 The entries within the active region, but only those at
14378 the same level than the first one.
14379 file The current buffer, without restriction
14380 file-with-archives
14381 The current buffer, and any archives associated with it
14382 agenda All agenda files
14383 agenda-with-archives
14384 All agenda files with any archive files associated with them
14385 \(file1 file2 ...)
14386 If this is a list, all files in the list will be scanned
14388 The remaining args are treated as settings for the skipping facilities of
14389 the scanner. The following items can be given here:
14391 archive skip trees with the archive tag.
14392 comment skip trees with the COMMENT keyword
14393 function or Emacs Lisp form:
14394 will be used as value for `org-agenda-skip-function', so whenever
14395 the function returns t, FUNC will not be called for that
14396 entry and search will continue from the point where the
14397 function leaves it.
14399 If your function needs to retrieve the tags including inherited tags
14400 at the *current* entry, you can use the value of the variable
14401 `org-scanner-tags' which will be much faster than getting the value
14402 with `org-get-tags-at'. If your function gets properties with
14403 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14404 to t around the call to `org-entry-properties' to get the same speedup.
14405 Note that if your function moves around to retrieve tags and properties at
14406 a *different* entry, you cannot use these techniques."
14407 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14408 (not (org-region-active-p)))
14409 (let* ((org-agenda-archives-mode nil) ; just to make sure
14410 (org-agenda-skip-archived-trees (memq 'archive skip))
14411 (org-agenda-skip-comment-trees (memq 'comment skip))
14412 (org-agenda-skip-function
14413 (car (org-delete-all '(comment archive) skip)))
14414 (org-tags-match-list-sublevels t)
14415 (start-level (eq scope 'region-start-level))
14416 matcher file res
14417 org-todo-keywords-for-agenda
14418 org-done-keywords-for-agenda
14419 org-todo-keyword-alist-for-agenda
14420 org-drawers-for-agenda
14421 org-tag-alist-for-agenda
14422 todo-only)
14424 (cond
14425 ((eq match t) (setq matcher t))
14426 ((eq match nil) (setq matcher t))
14427 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14429 (save-excursion
14430 (save-restriction
14431 (cond ((eq scope 'tree)
14432 (org-back-to-heading t)
14433 (org-narrow-to-subtree)
14434 (setq scope nil))
14435 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14436 (org-region-active-p))
14437 ;; If needed, set start-level to a string like "2"
14438 (when start-level
14439 (save-excursion
14440 (goto-char (region-beginning))
14441 (unless (org-at-heading-p) (outline-next-heading))
14442 (setq start-level (org-current-level))))
14443 (narrow-to-region (region-beginning)
14444 (save-excursion
14445 (goto-char (region-end))
14446 (unless (and (bolp) (org-at-heading-p))
14447 (outline-next-heading))
14448 (point)))
14449 (setq scope nil)))
14451 (if (not scope)
14452 (progn
14453 (org-agenda-prepare-buffers
14454 (list (buffer-file-name (current-buffer))))
14455 (setq res (org-scan-tags func matcher todo-only start-level)))
14456 ;; Get the right scope
14457 (cond
14458 ((and scope (listp scope) (symbolp (car scope)))
14459 (setq scope (eval scope)))
14460 ((eq scope 'agenda)
14461 (setq scope (org-agenda-files t)))
14462 ((eq scope 'agenda-with-archives)
14463 (setq scope (org-agenda-files t))
14464 (setq scope (org-add-archive-files scope)))
14465 ((eq scope 'file)
14466 (setq scope (list (buffer-file-name))))
14467 ((eq scope 'file-with-archives)
14468 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14469 (org-agenda-prepare-buffers scope)
14470 (while (setq file (pop scope))
14471 (with-current-buffer (org-find-base-buffer-visiting file)
14472 (save-excursion
14473 (save-restriction
14474 (widen)
14475 (goto-char (point-min))
14476 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14477 res)))
14479 ;;;; Properties
14481 ;;; Setting and retrieving properties
14483 (defconst org-special-properties
14484 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14485 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14486 "The special properties valid in Org-mode.
14488 These are properties that are not defined in the property drawer,
14489 but in some other way.")
14491 (defconst org-default-properties
14492 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14493 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14494 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14495 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14496 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14497 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14498 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14499 "Some properties that are used by Org-mode for various purposes.
14500 Being in this list makes sure that they are offered for completion.")
14502 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14503 "Regular expression matching the first line of a property drawer.")
14505 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14506 "Regular expression matching the last line of a property drawer.")
14508 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14509 "Regular expression matching the first line of a property drawer.")
14511 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14512 "Regular expression matching the first line of a property drawer.")
14514 (defconst org-property-drawer-re
14515 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14516 org-property-end-re "\\)\n?")
14517 "Matches an entire property drawer.")
14519 (defconst org-clock-drawer-re
14520 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14521 org-property-end-re "\\)\n?")
14522 "Matches an entire clock drawer.")
14524 (defsubst org-re-property (property)
14525 "Return a regexp matching a PROPERTY line.
14526 Match group 1 will be set to the value."
14527 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14529 (defsubst org-re-property-keyword (property)
14530 "Return a regexp matching a PROPERTY line, possibly with no
14531 value for the property."
14532 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14534 (defun org-property-action ()
14535 "Do an action on properties."
14536 (interactive)
14537 (let (c)
14538 (org-at-property-p)
14539 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14540 (setq c (read-char-exclusive))
14541 (cond
14542 ((equal c ?s)
14543 (call-interactively 'org-set-property))
14544 ((equal c ?d)
14545 (call-interactively 'org-delete-property))
14546 ((equal c ?D)
14547 (call-interactively 'org-delete-property-globally))
14548 ((equal c ?c)
14549 (call-interactively 'org-compute-property-at-point))
14550 (t (error "No such property action %c" c)))))
14552 (defun org-inc-effort ()
14553 "Increment the value of the effort property in the current entry."
14554 (interactive)
14555 (org-set-effort nil t))
14557 (defun org-set-effort (&optional value increment)
14558 "Set the effort property of the current entry.
14559 With numerical prefix arg, use the nth allowed value, 0 stands for the
14560 10th allowed value.
14562 When INCREMENT is non-nil, set the property to the next allowed value."
14563 (interactive "P")
14564 (if (equal value 0) (setq value 10))
14565 (let* ((completion-ignore-case t)
14566 (prop org-effort-property)
14567 (cur (org-entry-get nil prop))
14568 (allowed (org-property-get-allowed-values nil prop 'table))
14569 (existing (mapcar 'list (org-property-values prop)))
14571 (val (cond
14572 ((stringp value) value)
14573 ((and allowed (integerp value))
14574 (or (car (nth (1- value) allowed))
14575 (car (org-last allowed))))
14576 ((and allowed increment)
14577 (or (caadr (member (list cur) allowed))
14578 (error "Allowed effort values are not set")))
14579 (allowed
14580 (message "Select 1-9,0, [RET%s]: %s"
14581 (if cur (concat "=" cur) "")
14582 (mapconcat 'car allowed " "))
14583 (setq rpl (read-char-exclusive))
14584 (if (equal rpl ?\r)
14586 (setq rpl (- rpl ?0))
14587 (if (equal rpl 0) (setq rpl 10))
14588 (if (and (> rpl 0) (<= rpl (length allowed)))
14589 (car (nth (1- rpl) allowed))
14590 (org-completing-read "Effort: " allowed nil))))
14592 (let (org-completion-use-ido org-completion-use-iswitchb)
14593 (org-completing-read
14594 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14595 (concat "[" cur "]") "")
14596 ": ")
14597 existing nil nil "" nil cur))))))
14598 (unless (equal (org-entry-get nil prop) val)
14599 (org-entry-put nil prop val))
14600 (save-excursion
14601 (org-back-to-heading t)
14602 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14603 (message "%s is now %s" prop val)))
14605 (defun org-at-property-p ()
14606 "Is cursor inside a property drawer?"
14607 (save-excursion
14608 (beginning-of-line 1)
14609 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14610 (save-match-data ;; Used by calling procedures
14611 (let ((p (point))
14612 (range (unless (org-before-first-heading-p)
14613 (org-get-property-block))))
14614 (and range (<= (car range) p) (< p (cdr range))))))))
14616 (defun org-get-property-block (&optional beg end force)
14617 "Return the (beg . end) range of the body of the property drawer.
14618 BEG and END are the beginning and end of the current subtree, or of
14619 the part before the first headline. If they are not given, they will
14620 be found. If the drawer does not exist and FORCE is non-nil, create
14621 the drawer."
14622 (catch 'exit
14623 (save-excursion
14624 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14625 (progn (org-back-to-heading t) (point))))
14626 (end (or end (and (not (outline-next-heading)) (point-max))
14627 (point))))
14628 (goto-char beg)
14629 (if (re-search-forward org-property-start-re end t)
14630 (setq beg (1+ (match-end 0)))
14631 (if force
14632 (save-excursion
14633 (org-insert-property-drawer)
14634 (setq end (progn (outline-next-heading) (point))))
14635 (throw 'exit nil))
14636 (goto-char beg)
14637 (if (re-search-forward org-property-start-re end t)
14638 (setq beg (1+ (match-end 0)))))
14639 (if (re-search-forward org-property-end-re end t)
14640 (setq end (match-beginning 0))
14641 (or force (throw 'exit nil))
14642 (goto-char beg)
14643 (setq end beg)
14644 (org-indent-line)
14645 (insert ":END:\n"))
14646 (cons beg end)))))
14648 (defun org-entry-properties (&optional pom which specific)
14649 "Get all properties of the entry at point-or-marker POM.
14650 This includes the TODO keyword, the tags, time strings for deadline,
14651 scheduled, and clocking, and any additional properties defined in the
14652 entry. The return value is an alist, keys may occur multiple times
14653 if the property key was used several times.
14654 POM may also be nil, in which case the current entry is used.
14655 If WHICH is nil or `all', get all properties. If WHICH is
14656 `special' or `standard', only get that subclass. If WHICH
14657 is a string only get exactly this property. SPECIFIC can be a string, the
14658 specific property we are interested in. Specifying it can speed
14659 things up because then unnecessary parsing is avoided."
14660 (setq which (or which 'all))
14661 (org-with-point-at pom
14662 (let ((clockstr (substring org-clock-string 0 -1))
14663 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14664 (case-fold-search nil)
14665 beg end range props sum-props key key1 value string clocksum clocksumt)
14666 (save-excursion
14667 (when (condition-case nil
14668 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14669 (error nil))
14670 (setq beg (point))
14671 (setq sum-props (get-text-property (point) 'org-summaries))
14672 (setq clocksum (get-text-property (point) :org-clock-minutes)
14673 clocksumt (get-text-property (point) :org-clock-minutes-today))
14674 (outline-next-heading)
14675 (setq end (point))
14676 (when (memq which '(all special))
14677 ;; Get the special properties, like TODO and tags
14678 (goto-char beg)
14679 (when (and (or (not specific) (string= specific "TODO"))
14680 (looking-at org-todo-line-regexp) (match-end 2))
14681 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14682 (when (and (or (not specific) (string= specific "PRIORITY"))
14683 (looking-at org-priority-regexp))
14684 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14685 (when (or (not specific) (string= specific "FILE"))
14686 (push (cons "FILE" buffer-file-name) props))
14687 (when (and (or (not specific) (string= specific "TAGS"))
14688 (setq value (org-get-tags-string))
14689 (string-match "\\S-" value))
14690 (push (cons "TAGS" value) props))
14691 (when (and (or (not specific) (string= specific "ALLTAGS"))
14692 (setq value (org-get-tags-at)))
14693 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14694 ":"))
14695 props))
14696 (when (or (not specific) (string= specific "BLOCKED"))
14697 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14698 (when (or (not specific)
14699 (member specific
14700 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14701 "TIMESTAMP" "TIMESTAMP_IA")))
14702 (catch 'match
14703 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14704 (setq key (if (match-end 1)
14705 (substring (org-match-string-no-properties 1)
14706 0 -1))
14707 string (if (equal key clockstr)
14708 (org-trim
14709 (buffer-substring-no-properties
14710 (match-beginning 3) (goto-char
14711 (point-at-eol))))
14712 (substring (org-match-string-no-properties 3)
14713 1 -1)))
14714 ;; Get the correct property name from the key. This is
14715 ;; necessary if the user has configured time keywords.
14716 (setq key1 (concat key ":"))
14717 (cond
14718 ((not key)
14719 (setq key
14720 (if (= (char-after (match-beginning 3)) ?\[)
14721 "TIMESTAMP_IA" "TIMESTAMP")))
14722 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14723 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14724 ((equal key1 org-closed-string) (setq key "CLOSED"))
14725 ((equal key1 org-clock-string) (setq key "CLOCK")))
14726 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14727 (progn
14728 (push (cons key string) props)
14729 ;; no need to search further if match is found
14730 (throw 'match t))
14731 (when (or (equal key "CLOCK") (not (assoc key props)))
14732 (push (cons key string) props)))))))
14734 (when (memq which '(all standard))
14735 ;; Get the standard properties, like :PROP: ...
14736 (setq range (org-get-property-block beg end))
14737 (when range
14738 (goto-char (car range))
14739 (while (re-search-forward
14740 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14741 (cdr range) t)
14742 (setq key (org-match-string-no-properties 1)
14743 value (org-trim (or (org-match-string-no-properties 2) "")))
14744 (unless (member key excluded)
14745 (push (cons key (or value "")) props)))))
14746 (if clocksum
14747 (push (cons "CLOCKSUM"
14748 (org-columns-number-to-string (/ (float clocksum) 60.)
14749 'add_times))
14750 props))
14751 (if clocksumt
14752 (push (cons "CLOCKSUM_T"
14753 (org-columns-number-to-string (/ (float clocksumt) 60.)
14754 'add_times))
14755 props))
14756 (unless (assoc "CATEGORY" props)
14757 (push (cons "CATEGORY" (org-get-category)) props))
14758 (append sum-props (nreverse props)))))))
14760 (defun org-entry-get (pom property &optional inherit literal-nil)
14761 "Get value of PROPERTY for entry or content at point-or-marker POM.
14762 If INHERIT is non-nil and the entry does not have the property,
14763 then also check higher levels of the hierarchy.
14764 If INHERIT is the symbol `selective', use inheritance only if the setting
14765 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14766 If the property is present but empty, the return value is the empty string.
14767 If the property is not present at all, nil is returned.
14769 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14770 do not interpret it as the list atom nil. This is used for inheritance
14771 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14772 (org-with-point-at pom
14773 (if (and inherit (if (eq inherit 'selective)
14774 (org-property-inherit-p property)
14776 (org-entry-get-with-inheritance property literal-nil)
14777 (if (member property org-special-properties)
14778 ;; We need a special property. Use `org-entry-properties' to
14779 ;; retrieve it, but specify the wanted property
14780 (cdr (assoc property (org-entry-properties nil 'special property)))
14781 (let ((range (org-get-property-block)))
14782 (when (and range (not (eq (car range) (cdr range))))
14783 (let* ((props (list (or (assoc property org-file-properties)
14784 (assoc property org-global-properties)
14785 (assoc property org-global-properties-fixed))))
14786 (ap (lambda (key)
14787 (when (re-search-forward
14788 (org-re-property key) (cdr range) t)
14789 (setq props
14790 (org-update-property-plist
14792 (if (match-end 1)
14793 (org-match-string-no-properties 1) "")
14794 props)))))
14795 val)
14796 (goto-char (car range))
14797 (funcall ap property)
14798 (goto-char (car range))
14799 (while (funcall ap (concat property "+")))
14800 (setq val (cdr (assoc property props)))
14801 (when val (if literal-nil val (org-not-nil val))))))))))
14803 (defun org-property-or-variable-value (var &optional inherit)
14804 "Check if there is a property fixing the value of VAR.
14805 If yes, return this value. If not, return the current value of the variable."
14806 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14807 (if (and prop (stringp prop) (string-match "\\S-" prop))
14808 (read prop)
14809 (symbol-value var))))
14811 (defun org-entry-delete (pom property)
14812 "Delete the property PROPERTY from entry at point-or-marker POM."
14813 (org-with-point-at pom
14814 (if (member property org-special-properties)
14815 nil ; cannot delete these properties.
14816 (let ((range (org-get-property-block)))
14817 (if (and range
14818 (goto-char (car range))
14819 (re-search-forward
14820 (org-re-property property)
14821 (cdr range) t))
14822 (progn
14823 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14825 nil)))))
14827 ;; Multi-values properties are properties that contain multiple values
14828 ;; These values are assumed to be single words, separated by whitespace.
14829 (defun org-entry-add-to-multivalued-property (pom property value)
14830 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14831 (let* ((old (org-entry-get pom property))
14832 (values (and old (org-split-string old "[ \t]"))))
14833 (setq value (org-entry-protect-space value))
14834 (unless (member value values)
14835 (setq values (cons value values))
14836 (org-entry-put pom property
14837 (mapconcat 'identity values " ")))))
14839 (defun org-entry-remove-from-multivalued-property (pom property value)
14840 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14841 (let* ((old (org-entry-get pom property))
14842 (values (and old (org-split-string old "[ \t]"))))
14843 (setq value (org-entry-protect-space value))
14844 (when (member value values)
14845 (setq values (delete value values))
14846 (org-entry-put pom property
14847 (mapconcat 'identity values " ")))))
14849 (defun org-entry-member-in-multivalued-property (pom property value)
14850 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14851 (let* ((old (org-entry-get pom property))
14852 (values (and old (org-split-string old "[ \t]"))))
14853 (setq value (org-entry-protect-space value))
14854 (member value values)))
14856 (defun org-entry-get-multivalued-property (pom property)
14857 "Return a list of values in a multivalued property."
14858 (let* ((value (org-entry-get pom property))
14859 (values (and value (org-split-string value "[ \t]"))))
14860 (mapcar 'org-entry-restore-space values)))
14862 (defun org-entry-put-multivalued-property (pom property &rest values)
14863 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14864 VALUES should be a list of strings. Spaces will be protected."
14865 (org-entry-put pom property
14866 (mapconcat 'org-entry-protect-space values " "))
14867 (let* ((value (org-entry-get pom property))
14868 (values (and value (org-split-string value "[ \t]"))))
14869 (mapcar 'org-entry-restore-space values)))
14871 (defun org-entry-protect-space (s)
14872 "Protect spaces and newline in string S."
14873 (while (string-match " " s)
14874 (setq s (replace-match "%20" t t s)))
14875 (while (string-match "\n" s)
14876 (setq s (replace-match "%0A" t t s)))
14879 (defun org-entry-restore-space (s)
14880 "Restore spaces and newline in string S."
14881 (while (string-match "%20" s)
14882 (setq s (replace-match " " t t s)))
14883 (while (string-match "%0A" s)
14884 (setq s (replace-match "\n" t t s)))
14887 (defvar org-entry-property-inherited-from (make-marker)
14888 "Marker pointing to the entry from where a property was inherited.
14889 Each call to `org-entry-get-with-inheritance' will set this marker to the
14890 location of the entry where the inheritance search matched. If there was
14891 no match, the marker will point nowhere.
14892 Note that also `org-entry-get' calls this function, if the INHERIT flag
14893 is set.")
14895 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14896 "Get PROPERTY of entry or content at point, search higher levels if needed.
14897 The search will stop at the first ancestor which has the property defined.
14898 If the value found is \"nil\", return nil to show that the property
14899 should be considered as undefined (this is the meaning of nil here).
14900 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14901 (move-marker org-entry-property-inherited-from nil)
14902 (let (tmp)
14903 (save-excursion
14904 (save-restriction
14905 (widen)
14906 (catch 'ex
14907 (while t
14908 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14909 (or (ignore-errors (org-back-to-heading t))
14910 (goto-char (point-min)))
14911 (move-marker org-entry-property-inherited-from (point))
14912 (throw 'ex tmp))
14913 (or (ignore-errors (org-up-heading-safe))
14914 (throw 'ex nil))))))
14915 (setq tmp (or tmp
14916 (cdr (assoc property org-file-properties))
14917 (cdr (assoc property org-global-properties))
14918 (cdr (assoc property org-global-properties-fixed))))
14919 (if literal-nil tmp (org-not-nil tmp))))
14921 (defvar org-property-changed-functions nil
14922 "Hook called when the value of a property has changed.
14923 Each hook function should accept two arguments, the name of the property
14924 and the new value.")
14926 (defun org-entry-put (pom property value)
14927 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14928 (org-with-point-at pom
14929 (org-back-to-heading t)
14930 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14931 range)
14932 (cond
14933 ((equal property "TODO")
14934 (when (and (stringp value) (string-match "\\S-" value)
14935 (not (member value org-todo-keywords-1)))
14936 (error "\"%s\" is not a valid TODO state" value))
14937 (if (or (not value)
14938 (not (string-match "\\S-" value)))
14939 (setq value 'none))
14940 (org-todo value)
14941 (org-set-tags nil 'align))
14942 ((equal property "PRIORITY")
14943 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14944 (string-to-char value) ?\ ))
14945 (org-set-tags nil 'align))
14946 ((equal property "CLOCKSUM")
14947 (if (not (re-search-forward
14948 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14949 (error "Cannot find a clock log")
14950 (goto-char (- (match-end 1) 2))
14951 (cond
14952 ((eq value 'earlier) (org-timestamp-down))
14953 ((eq value 'later) (org-timestamp-up)))
14954 (org-clock-sum-current-item)))
14955 ((equal property "SCHEDULED")
14956 (if (re-search-forward org-scheduled-time-regexp end t)
14957 (cond
14958 ((eq value 'earlier) (org-timestamp-change -1 'day))
14959 ((eq value 'later) (org-timestamp-change 1 'day))
14960 (t (call-interactively 'org-schedule)))
14961 (call-interactively 'org-schedule)))
14962 ((equal property "DEADLINE")
14963 (if (re-search-forward org-deadline-time-regexp end t)
14964 (cond
14965 ((eq value 'earlier) (org-timestamp-change -1 'day))
14966 ((eq value 'later) (org-timestamp-change 1 'day))
14967 (t (call-interactively 'org-deadline)))
14968 (call-interactively 'org-deadline)))
14969 ((member property org-special-properties)
14970 (error "The %s property can not yet be set with `org-entry-put'"
14971 property))
14972 (t ; a non-special property
14973 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14974 (setq range (org-get-property-block beg end 'force))
14975 (goto-char (car range))
14976 (if (re-search-forward
14977 (org-re-property-keyword property) (cdr range) t)
14978 (progn
14979 (delete-region (match-beginning 0) (match-end 0))
14980 (goto-char (match-beginning 0)))
14981 (goto-char (cdr range))
14982 (insert "\n")
14983 (backward-char 1)
14984 (org-indent-line))
14985 (insert ":" property ":")
14986 (and value (insert " " value))
14987 (org-indent-line)))))
14988 (run-hook-with-args 'org-property-changed-functions property value)))
14990 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14991 "Get all property keys in the current buffer.
14992 With INCLUDE-SPECIALS, also list the special properties that reflect things
14993 like tags and TODO state.
14994 With INCLUDE-DEFAULTS, also include properties that has special meaning
14995 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14996 and others.
14997 With INCLUDE-COLUMNS, also include property names given in COLUMN
14998 formats in the current buffer."
14999 (let (rtn range cfmt s p)
15000 (save-excursion
15001 (save-restriction
15002 (widen)
15003 (goto-char (point-min))
15004 (while (re-search-forward org-property-start-re nil t)
15005 (setq range (org-get-property-block))
15006 (goto-char (car range))
15007 (while (re-search-forward
15008 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15009 (cdr range) t)
15010 (add-to-list 'rtn (org-match-string-no-properties 1)))
15011 (outline-next-heading))))
15013 (when include-specials
15014 (setq rtn (append org-special-properties rtn)))
15016 (when include-defaults
15017 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15018 (add-to-list 'rtn org-effort-property))
15020 (when include-columns
15021 (save-excursion
15022 (save-restriction
15023 (widen)
15024 (goto-char (point-min))
15025 (while (re-search-forward
15026 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15027 nil t)
15028 (setq cfmt (match-string 2) s 0)
15029 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15030 cfmt s)
15031 (setq s (match-end 0)
15032 p (match-string 1 cfmt))
15033 (unless (or (equal p "ITEM")
15034 (member p org-special-properties))
15035 (add-to-list 'rtn (match-string 1 cfmt))))))))
15037 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15039 (defun org-property-values (key)
15040 "Return a list of all values of property KEY in the current buffer."
15041 (save-excursion
15042 (save-restriction
15043 (widen)
15044 (goto-char (point-min))
15045 (let ((re (org-re-property key))
15046 values)
15047 (while (re-search-forward re nil t)
15048 (add-to-list 'values (org-trim (match-string 1))))
15049 (delete "" values)))))
15051 (defun org-insert-property-drawer ()
15052 "Insert a property drawer into the current entry."
15053 (org-back-to-heading t)
15054 (looking-at org-outline-regexp)
15055 (let ((indent (if org-adapt-indentation
15056 (- (match-end 0) (match-beginning 0))
15058 (beg (point))
15059 (re (concat "^[ \t]*" org-keyword-time-regexp))
15060 end hiddenp)
15061 (outline-next-heading)
15062 (setq end (point))
15063 (goto-char beg)
15064 (while (re-search-forward re end t))
15065 (setq hiddenp (outline-invisible-p))
15066 (end-of-line 1)
15067 (and (equal (char-after) ?\n) (forward-char 1))
15068 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15069 (if (member (match-string 1) '("CLOCK:" ":END:"))
15070 ;; just skip this line
15071 (beginning-of-line 2)
15072 ;; Drawer start, find the end
15073 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15074 (beginning-of-line 1)))
15075 (org-skip-over-state-notes)
15076 (skip-chars-backward " \t\n\r")
15077 (if (eq (char-before) ?*) (forward-char 1))
15078 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15079 (beginning-of-line 0)
15080 (org-indent-to-column indent)
15081 (beginning-of-line 2)
15082 (org-indent-to-column indent)
15083 (beginning-of-line 0)
15084 (if hiddenp
15085 (save-excursion
15086 (org-back-to-heading t)
15087 (hide-entry))
15088 (org-flag-drawer t))))
15090 (defun org-insert-drawer (&optional arg drawer)
15091 "Insert a drawer at point.
15093 Optional argument DRAWER, when non-nil, is a string representing
15094 drawer's name. Otherwise, the user is prompted for a name.
15096 If a region is active, insert the drawer around that region
15097 instead.
15099 Point is left between drawer's boundaries."
15100 (interactive "P")
15101 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15102 "LOGBOOK"))
15103 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15104 ;; internally by Org. They are meant to be inserted
15105 ;; automatically.
15106 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15107 ;; Remove system drawers from list. Note: For some reason,
15108 ;; `org-completing-read' ignores the predicate while
15109 ;; `completing-read' handles it fine.
15110 (drawer (if arg "PROPERTIES"
15111 (or drawer
15112 (completing-read
15113 "Drawer: " org-drawers
15114 (lambda (d) (not (member d system-drawers))))))))
15115 (cond
15116 ;; With C-u, fall back on `org-insert-property-drawer'
15117 (arg (org-insert-property-drawer))
15118 ;; With an active region, insert a drawer at point.
15119 ((not (org-region-active-p))
15120 (progn
15121 (unless (bolp) (insert "\n"))
15122 (insert (format ":%s:\n\n:END:\n" drawer))
15123 (forward-line -2)))
15124 ;; Otherwise, insert the drawer at point
15126 (let ((rbeg (region-beginning))
15127 (rend (copy-marker (region-end))))
15128 (unwind-protect
15129 (progn
15130 (goto-char rbeg)
15131 (beginning-of-line)
15132 (when (save-excursion
15133 (re-search-forward org-outline-regexp-bol rend t))
15134 (error "Drawers cannot contain headlines"))
15135 ;; Position point at the beginning of the first
15136 ;; non-blank line in region. Insert drawer's opening
15137 ;; there, then indent it.
15138 (org-skip-whitespace)
15139 (beginning-of-line)
15140 (insert ":" drawer ":\n")
15141 (forward-line -1)
15142 (indent-for-tab-command)
15143 ;; Move point to the beginning of the first blank line
15144 ;; after the last non-blank line in region. Insert
15145 ;; drawer's closing, then indent it.
15146 (goto-char rend)
15147 (skip-chars-backward " \r\t\n")
15148 (insert "\n:END:")
15149 (deactivate-mark t)
15150 (indent-for-tab-command)
15151 (unless (eolp) (insert "\n")))
15152 ;; Clear marker, whatever the outcome of insertion is.
15153 (set-marker rend nil)))))))
15155 (defvar org-property-set-functions-alist nil
15156 "Property set function alist.
15157 Each entry should have the following format:
15159 (PROPERTY . READ-FUNCTION)
15161 The read function will be called with the same argument as
15162 `org-completing-read'.")
15164 (defun org-set-property-function (property)
15165 "Get the function that should be used to set PROPERTY.
15166 This is computed according to `org-property-set-functions-alist'."
15167 (or (cdr (assoc property org-property-set-functions-alist))
15168 'org-completing-read))
15170 (defun org-read-property-value (property)
15171 "Read PROPERTY value from user."
15172 (let* ((completion-ignore-case t)
15173 (allowed (org-property-get-allowed-values nil property 'table))
15174 (cur (org-entry-get nil property))
15175 (prompt (concat property " value"
15176 (if (and cur (string-match "\\S-" cur))
15177 (concat " [" cur "]") "") ": "))
15178 (set-function (org-set-property-function property))
15179 (val (if allowed
15180 (funcall set-function prompt allowed nil
15181 (not (get-text-property 0 'org-unrestricted
15182 (caar allowed))))
15183 (let (org-completion-use-ido org-completion-use-iswitchb)
15184 (funcall set-function prompt
15185 (mapcar 'list (org-property-values property))
15186 nil nil "" nil cur)))))
15187 (if (equal val "")
15189 val)))
15191 (defvar org-last-set-property nil)
15192 (defvar org-last-set-property-value nil)
15193 (defun org-read-property-name ()
15194 "Read a property name."
15195 (let* ((completion-ignore-case t)
15196 (keys (org-buffer-property-keys nil t t))
15197 (default-prop (or (save-excursion
15198 (save-match-data
15199 (beginning-of-line)
15200 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15201 (null (string= (match-string 1) "END"))
15202 (match-string 1))))
15203 org-last-set-property))
15204 (property (org-icompleting-read
15205 (concat "Property"
15206 (if default-prop (concat " [" default-prop "]") "")
15207 ": ")
15208 (mapcar 'list keys)
15209 nil nil nil nil
15210 default-prop)))
15211 (if (member property keys)
15212 property
15213 (or (cdr (assoc (downcase property)
15214 (mapcar (lambda (x) (cons (downcase x) x))
15215 keys)))
15216 property))))
15218 (defun org-set-property-and-value (use-last)
15219 "Allow to set [PROPERTY]: [value] direction from prompt.
15220 When use-default, don't even ask, just use the last
15221 \"[PROPERTY]: [value]\" string from the history."
15222 (interactive "P")
15223 (let* ((completion-ignore-case t)
15224 (pv (or (and use-last org-last-set-property-value)
15225 (org-completing-read
15226 "Enter a \"[Property]: [value]\" pair: "
15227 nil nil nil nil nil
15228 org-last-set-property-value)))
15229 prop val)
15230 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15231 (setq prop (match-string 1 pv)
15232 val (match-string 2 pv))
15233 (org-set-property prop val))))
15235 (defun org-set-property (property value)
15236 "In the current entry, set PROPERTY to VALUE.
15237 When called interactively, this will prompt for a property name, offering
15238 completion on existing and default properties. And then it will prompt
15239 for a value, offering completion either on allowed values (via an inherited
15240 xxx_ALL property) or on existing values in other instances of this property
15241 in the current file."
15242 (interactive (list nil nil))
15243 (let* ((property (or property (org-read-property-name)))
15244 (value (or value (org-read-property-value property)))
15245 (fn (cdr (assoc property org-properties-postprocess-alist))))
15246 (setq org-last-set-property property)
15247 (setq org-last-set-property-value (concat property ": " value))
15248 ;; Possibly postprocess the inserted value:
15249 (when fn (setq value (funcall fn value)))
15250 (unless (equal (org-entry-get nil property) value)
15251 (org-entry-put nil property value))))
15253 (defun org-delete-property (property)
15254 "In the current entry, delete PROPERTY."
15255 (interactive
15256 (let* ((completion-ignore-case t)
15257 (prop (org-icompleting-read "Property: "
15258 (org-entry-properties nil 'standard))))
15259 (list prop)))
15260 (message "Property %s %s" property
15261 (if (org-entry-delete nil property)
15262 "deleted"
15263 "was not present in the entry")))
15265 (defun org-delete-property-globally (property)
15266 "Remove PROPERTY globally, from all entries."
15267 (interactive
15268 (let* ((completion-ignore-case t)
15269 (prop (org-icompleting-read
15270 "Globally remove property: "
15271 (mapcar 'list (org-buffer-property-keys)))))
15272 (list prop)))
15273 (save-excursion
15274 (save-restriction
15275 (widen)
15276 (goto-char (point-min))
15277 (let ((cnt 0))
15278 (while (re-search-forward
15279 (org-re-property property)
15280 nil t)
15281 (setq cnt (1+ cnt))
15282 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15283 (message "Property \"%s\" removed from %d entries" property cnt)))))
15285 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15287 (defun org-compute-property-at-point ()
15288 "Compute the property at point.
15289 This looks for an enclosing column format, extracts the operator and
15290 then applies it to the property in the column format's scope."
15291 (interactive)
15292 (unless (org-at-property-p)
15293 (error "Not at a property"))
15294 (let ((prop (org-match-string-no-properties 2)))
15295 (org-columns-get-format-and-top-level)
15296 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15297 (error "No operator defined for property %s" prop))
15298 (org-columns-compute prop)))
15300 (defvar org-property-allowed-value-functions nil
15301 "Hook for functions supplying allowed values for a specific property.
15302 The functions must take a single argument, the name of the property, and
15303 return a flat list of allowed values. If \":ETC\" is one of
15304 the values, this means that these values are intended as defaults for
15305 completion, but that other values should be allowed too.
15306 The functions must return nil if they are not responsible for this
15307 property.")
15309 (defun org-property-get-allowed-values (pom property &optional table)
15310 "Get allowed values for the property PROPERTY.
15311 When TABLE is non-nil, return an alist that can directly be used for
15312 completion."
15313 (let (vals)
15314 (cond
15315 ((equal property "TODO")
15316 (setq vals (org-with-point-at pom
15317 (append org-todo-keywords-1 '("")))))
15318 ((equal property "PRIORITY")
15319 (let ((n org-lowest-priority))
15320 (while (>= n org-highest-priority)
15321 (push (char-to-string n) vals)
15322 (setq n (1- n)))))
15323 ((member property org-special-properties))
15324 ((setq vals (run-hook-with-args-until-success
15325 'org-property-allowed-value-functions property)))
15327 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15328 (when (and vals (string-match "\\S-" vals))
15329 (setq vals (car (read-from-string (concat "(" vals ")"))))
15330 (setq vals (mapcar (lambda (x)
15331 (cond ((stringp x) x)
15332 ((numberp x) (number-to-string x))
15333 ((symbolp x) (symbol-name x))
15334 (t "???")))
15335 vals)))))
15336 (when (member ":ETC" vals)
15337 (setq vals (remove ":ETC" vals))
15338 (org-add-props (car vals) '(org-unrestricted t)))
15339 (if table (mapcar 'list vals) vals)))
15341 (defun org-property-previous-allowed-value (&optional previous)
15342 "Switch to the next allowed value for this property."
15343 (interactive)
15344 (org-property-next-allowed-value t))
15346 (defun org-property-next-allowed-value (&optional previous)
15347 "Switch to the next allowed value for this property."
15348 (interactive)
15349 (unless (org-at-property-p)
15350 (error "Not at a property"))
15351 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15352 (key (match-string 2))
15353 (value (match-string 3))
15354 (allowed (or (org-property-get-allowed-values (point) key)
15355 (and (member value '("[ ]" "[-]" "[X]"))
15356 '("[ ]" "[X]"))))
15357 nval)
15358 (unless allowed
15359 (error "Allowed values for this property have not been defined"))
15360 (if previous (setq allowed (reverse allowed)))
15361 (if (member value allowed)
15362 (setq nval (car (cdr (member value allowed)))))
15363 (setq nval (or nval (car allowed)))
15364 (if (equal nval value)
15365 (error "Only one allowed value for this property"))
15366 (org-at-property-p)
15367 (replace-match (concat " :" key ": " nval) t t)
15368 (org-indent-line)
15369 (beginning-of-line 1)
15370 (skip-chars-forward " \t")
15371 (when (equal prop org-effort-property)
15372 (save-excursion
15373 (org-back-to-heading t)
15374 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15375 (run-hook-with-args 'org-property-changed-functions key nval)))
15377 (defun org-find-olp (path &optional this-buffer)
15378 "Return a marker pointing to the entry at outline path OLP.
15379 If anything goes wrong, throw an error.
15380 You can wrap this call to catch the error like this:
15382 (condition-case msg
15383 (org-mobile-locate-entry (match-string 4))
15384 (error (nth 1 msg)))
15386 The return value will then be either a string with the error message,
15387 or a marker if everything is OK.
15389 If THIS-BUFFER is set, the outline path does not contain a file,
15390 only headings."
15391 (let* ((file (if this-buffer buffer-file-name (pop path)))
15392 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15393 (level 1)
15394 (lmin 1)
15395 (lmax 1)
15396 limit re end found pos heading cnt flevel)
15397 (unless buffer (error "File not found :%s" file))
15398 (with-current-buffer buffer
15399 (save-excursion
15400 (save-restriction
15401 (widen)
15402 (setq limit (point-max))
15403 (goto-char (point-min))
15404 (while (setq heading (pop path))
15405 (setq re (format org-complex-heading-regexp-format
15406 (regexp-quote heading)))
15407 (setq cnt 0 pos (point))
15408 (while (re-search-forward re end t)
15409 (setq level (- (match-end 1) (match-beginning 1)))
15410 (if (and (>= level lmin) (<= level lmax))
15411 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15412 (when (= cnt 0) (error "Heading not found on level %d: %s"
15413 lmax heading))
15414 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15415 lmax heading))
15416 (goto-char found)
15417 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15418 (setq end (save-excursion (org-end-of-subtree t t))))
15419 (when (org-at-heading-p)
15420 (point-marker)))))))
15422 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15423 "Find node HEADING in BUFFER.
15424 Return a marker to the heading if it was found, or nil if not.
15425 If POS-ONLY is set, return just the position instead of a marker.
15427 The heading text must match exact, but it may have a TODO keyword,
15428 a priority cookie and tags in the standard locations."
15429 (with-current-buffer (or buffer (current-buffer))
15430 (save-excursion
15431 (save-restriction
15432 (widen)
15433 (goto-char (point-min))
15434 (let (case-fold-search)
15435 (if (re-search-forward
15436 (format org-complex-heading-regexp-format
15437 (regexp-quote heading)) nil t)
15438 (if pos-only
15439 (match-beginning 0)
15440 (move-marker (make-marker) (match-beginning 0)))))))))
15442 (defun org-find-exact-heading-in-directory (heading &optional dir)
15443 "Find Org node headline HEADING in all .org files in directory DIR.
15444 When the target headline is found, return a marker to this location."
15445 (let ((files (directory-files (or dir default-directory)
15446 nil "\\`[^.#].*\\.org\\'"))
15447 file visiting m buffer)
15448 (catch 'found
15449 (while (setq file (pop files))
15450 (message "trying %s" file)
15451 (setq visiting (org-find-base-buffer-visiting file))
15452 (setq buffer (or visiting (find-file-noselect file)))
15453 (setq m (org-find-exact-headline-in-buffer
15454 heading buffer))
15455 (when (and (not m) (not visiting)) (kill-buffer buffer))
15456 (and m (throw 'found m))))))
15458 (defun org-find-entry-with-id (ident)
15459 "Locate the entry that contains the ID property with exact value IDENT.
15460 IDENT can be a string, a symbol or a number, this function will search for
15461 the string representation of it.
15462 Return the position where this entry starts, or nil if there is no such entry."
15463 (interactive "sID: ")
15464 (let ((id (cond
15465 ((stringp ident) ident)
15466 ((symbol-name ident) (symbol-name ident))
15467 ((numberp ident) (number-to-string ident))
15468 (t (error "IDENT %s must be a string, symbol or number" ident))))
15469 (case-fold-search nil))
15470 (save-excursion
15471 (save-restriction
15472 (widen)
15473 (goto-char (point-min))
15474 (when (re-search-forward
15475 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15476 nil t)
15477 (org-back-to-heading t)
15478 (point))))))
15480 ;;;; Timestamps
15482 (defvar org-last-changed-timestamp nil)
15483 (defvar org-last-inserted-timestamp nil
15484 "The last time stamp inserted with `org-insert-time-stamp'.")
15485 (defvar org-time-was-given) ; dynamically scoped parameter
15486 (defvar org-end-time-was-given) ; dynamically scoped parameter
15487 (defvar org-ts-what) ; dynamically scoped parameter
15489 (defun org-time-stamp (arg &optional inactive)
15490 "Prompt for a date/time and insert a time stamp.
15491 If the user specifies a time like HH:MM or if this command is
15492 called with at least one prefix argument, the time stamp contains
15493 the date and the time. Otherwise, only the date is be included.
15495 All parts of a date not specified by the user is filled in from
15496 the current date/time. So if you just press return without
15497 typing anything, the time stamp will represent the current
15498 date/time.
15500 If there is already a timestamp at the cursor, it will be
15501 modified.
15503 With two universal prefix arguments, insert an active timestamp
15504 with the current time without prompting the user."
15505 (interactive "P")
15506 (let* ((ts nil)
15507 (default-time
15508 ;; Default time is either today, or, when entering a range,
15509 ;; the range start.
15510 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15511 (save-excursion
15512 (re-search-backward
15513 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15514 (- (point) 20) t)))
15515 (apply 'encode-time (org-parse-time-string (match-string 1)))
15516 (current-time)))
15517 (default-input (and ts (org-get-compact-tod ts)))
15518 (repeater (save-excursion
15519 (save-match-data
15520 (beginning-of-line)
15521 (when (re-search-forward
15522 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15523 (save-excursion (progn (end-of-line) (point))) t)
15524 (match-string 0)))))
15525 org-time-was-given org-end-time-was-given time)
15526 (cond
15527 ((and (org-at-timestamp-p t)
15528 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15529 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15530 (insert "--")
15531 (setq time (let ((this-command this-command))
15532 (org-read-date arg 'totime nil nil
15533 default-time default-input inactive)))
15534 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15535 ((org-at-timestamp-p t)
15536 (setq time (let ((this-command this-command))
15537 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15538 (when (org-at-timestamp-p t) ; just to get the match data
15539 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15540 (replace-match "")
15541 (setq org-last-changed-timestamp
15542 (org-insert-time-stamp
15543 time (or org-time-was-given arg)
15544 inactive nil nil (list org-end-time-was-given)))
15545 (when repeater (goto-char (1- (point))) (insert " " repeater)
15546 (setq org-last-changed-timestamp
15547 (concat (substring org-last-inserted-timestamp 0 -1)
15548 " " repeater ">"))))
15549 (message "Timestamp updated"))
15550 ((equal arg '(16))
15551 (org-insert-time-stamp (current-time) t))
15553 (setq time (let ((this-command this-command))
15554 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15555 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15556 nil nil (list org-end-time-was-given))))))
15558 ;; FIXME: can we use this for something else, like computing time differences?
15559 (defun org-get-compact-tod (s)
15560 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15561 (let* ((t1 (match-string 1 s))
15562 (h1 (string-to-number (match-string 2 s)))
15563 (m1 (string-to-number (match-string 3 s)))
15564 (t2 (and (match-end 4) (match-string 5 s)))
15565 (h2 (and t2 (string-to-number (match-string 6 s))))
15566 (m2 (and t2 (string-to-number (match-string 7 s))))
15567 dh dm)
15568 (if (not t2)
15570 (setq dh (- h2 h1) dm (- m2 m1))
15571 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15572 (concat t1 "+" (number-to-string dh)
15573 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15575 (defun org-time-stamp-inactive (&optional arg)
15576 "Insert an inactive time stamp.
15577 An inactive time stamp is enclosed in square brackets instead of angle
15578 brackets. It is inactive in the sense that it does not trigger agenda entries,
15579 does not link to the calendar and cannot be changed with the S-cursor keys.
15580 So these are more for recording a certain time/date."
15581 (interactive "P")
15582 (org-time-stamp arg 'inactive))
15584 (defvar org-date-ovl (make-overlay 1 1))
15585 (overlay-put org-date-ovl 'face 'org-date-selected)
15586 (org-detach-overlay org-date-ovl)
15588 (defvar org-ans1) ; dynamically scoped parameter
15589 (defvar org-ans2) ; dynamically scoped parameter
15591 (defvar org-plain-time-of-day-regexp) ; defined below
15593 (defvar org-overriding-default-time nil) ; dynamically scoped
15594 (defvar org-read-date-overlay nil)
15595 (defvar org-dcst nil) ; dynamically scoped
15596 (defvar org-read-date-history nil)
15597 (defvar org-read-date-final-answer nil)
15598 (defvar org-read-date-analyze-futurep nil)
15599 (defvar org-read-date-analyze-forced-year nil)
15600 (defvar org-read-date-inactive)
15602 (defvar org-read-date-minibuffer-local-map
15603 (let ((map (make-sparse-keymap)))
15604 (set-keymap-parent map minibuffer-local-map)
15605 (org-defkey map [(meta shift left)]
15606 (lambda () (interactive)
15607 (org-eval-in-calendar '(calendar-backward-month 1))))
15608 (org-defkey map [(meta shift right)]
15609 (lambda () (interactive)
15610 (org-eval-in-calendar '(calendar-forward-month 1))))
15611 (org-defkey map [(meta shift up)]
15612 (lambda () (interactive)
15613 (org-eval-in-calendar '(calendar-backward-year 1))))
15614 (org-defkey map [(meta shift down)]
15615 (lambda () (interactive)
15616 (org-eval-in-calendar '(calendar-forward-year 1))))
15617 (org-defkey map [?\e (shift left)]
15618 (lambda () (interactive)
15619 (org-eval-in-calendar '(calendar-backward-month 1))))
15620 (org-defkey map [?\e (shift right)]
15621 (lambda () (interactive)
15622 (org-eval-in-calendar '(calendar-forward-month 1))))
15623 (org-defkey map [?\e (shift up)]
15624 (lambda () (interactive)
15625 (org-eval-in-calendar '(calendar-backward-year 1))))
15626 (org-defkey map [?\e (shift down)]
15627 (lambda () (interactive)
15628 (org-eval-in-calendar '(calendar-forward-year 1))))
15629 (org-defkey map [(shift up)]
15630 (lambda () (interactive)
15631 (org-eval-in-calendar '(calendar-backward-week 1))))
15632 (org-defkey map [(shift down)]
15633 (lambda () (interactive)
15634 (org-eval-in-calendar '(calendar-forward-week 1))))
15635 (org-defkey map [(shift left)]
15636 (lambda () (interactive)
15637 (org-eval-in-calendar '(calendar-backward-day 1))))
15638 (org-defkey map [(shift right)]
15639 (lambda () (interactive)
15640 (org-eval-in-calendar '(calendar-forward-day 1))))
15641 (org-defkey map "?"
15642 (lambda () (interactive)
15643 (org-eval-in-calendar '(diary-view-entries))
15644 (message "")))
15645 (org-defkey map ">"
15646 (lambda () (interactive)
15647 (org-eval-in-calendar '(scroll-calendar-left 1))))
15648 (org-defkey map "<"
15649 (lambda () (interactive)
15650 (org-eval-in-calendar '(scroll-calendar-right 1))))
15651 (org-defkey map "\C-v"
15652 (lambda () (interactive)
15653 (org-eval-in-calendar
15654 '(calendar-scroll-left-three-months 1))))
15655 (org-defkey map "\M-v"
15656 (lambda () (interactive)
15657 (org-eval-in-calendar
15658 '(calendar-scroll-right-three-months 1))))
15659 map)
15660 "Keymap for minibuffer commands when using `org-read-date'.")
15662 (defun org-read-date (&optional org-with-time to-time from-string prompt
15663 default-time default-input inactive)
15664 "Read a date, possibly a time, and make things smooth for the user.
15665 The prompt will suggest to enter an ISO date, but you can also enter anything
15666 which will at least partially be understood by `parse-time-string'.
15667 Unrecognized parts of the date will default to the current day, month, year,
15668 hour and minute. If this command is called to replace a timestamp at point,
15669 or to enter the second timestamp of a range, the default time is taken
15670 from the existing stamp. Furthermore, the command prefers the future,
15671 so if you are giving a date where the year is not given, and the day-month
15672 combination is already past in the current year, it will assume you
15673 mean next year. For details, see the manual. A few examples:
15675 3-2-5 --> 2003-02-05
15676 feb 15 --> currentyear-02-15
15677 2/15 --> currentyear-02-15
15678 sep 12 9 --> 2009-09-12
15679 12:45 --> today 12:45
15680 22 sept 0:34 --> currentyear-09-22 0:34
15681 12 --> currentyear-currentmonth-12
15682 Fri --> nearest Friday (today or later)
15683 etc.
15685 Furthermore you can specify a relative date by giving, as the *first* thing
15686 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15687 change in days weeks, months, years.
15688 With a single plus or minus, the date is relative to today. With a double
15689 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15690 +4d --> four days from today
15691 +4 --> same as above
15692 +2w --> two weeks from today
15693 ++5 --> five days from default date
15695 The function understands only English month and weekday abbreviations.
15697 While prompting, a calendar is popped up - you can also select the
15698 date with the mouse (button 1). The calendar shows a period of three
15699 months. To scroll it to other months, use the keys `>' and `<'.
15700 If you don't like the calendar, turn it off with
15701 \(setq org-read-date-popup-calendar nil)
15703 With optional argument TO-TIME, the date will immediately be converted
15704 to an internal time.
15705 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15706 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15707 still enter a time, and this function will inform the calling routine
15708 about this change. The calling routine may then choose to change the
15709 format used to insert the time stamp into the buffer to include the time.
15710 With optional argument FROM-STRING, read from this string instead from
15711 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15712 the time/date that is used for everything that is not specified by the
15713 user."
15714 (require 'parse-time)
15715 (let* ((org-time-stamp-rounding-minutes
15716 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15717 (org-dcst org-display-custom-times)
15718 (ct (org-current-time))
15719 (org-def (or org-overriding-default-time default-time ct))
15720 (org-defdecode (decode-time org-def))
15721 (dummy (progn
15722 (when (< (nth 2 org-defdecode) org-extend-today-until)
15723 (setcar (nthcdr 2 org-defdecode) -1)
15724 (setcar (nthcdr 1 org-defdecode) 59)
15725 (setq org-def (apply 'encode-time org-defdecode)
15726 org-defdecode (decode-time org-def)))))
15727 (mouse-autoselect-window nil) ; Don't let the mouse jump
15728 (calendar-frame-setup nil)
15729 (calendar-setup nil)
15730 (calendar-move-hook nil)
15731 (calendar-view-diary-initially-flag nil)
15732 (calendar-view-holidays-initially-flag nil)
15733 (timestr (format-time-string
15734 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15735 (prompt (concat (if prompt (concat prompt " ") "")
15736 (format "Date+time [%s]: " timestr)))
15737 ans (org-ans0 "") org-ans1 org-ans2 final)
15739 (cond
15740 (from-string (setq ans from-string))
15741 (org-read-date-popup-calendar
15742 (save-excursion
15743 (save-window-excursion
15744 (calendar)
15745 (org-eval-in-calendar '(setq cursor-type nil) t)
15746 (unwind-protect
15747 (progn
15748 (calendar-forward-day (- (time-to-days org-def)
15749 (calendar-absolute-from-gregorian
15750 (calendar-current-date))))
15751 (org-eval-in-calendar nil t)
15752 (let* ((old-map (current-local-map))
15753 (map (copy-keymap calendar-mode-map))
15754 (minibuffer-local-map
15755 (copy-keymap org-read-date-minibuffer-local-map)))
15756 (org-defkey map (kbd "RET") 'org-calendar-select)
15757 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15758 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15759 (unwind-protect
15760 (progn
15761 (use-local-map map)
15762 (setq org-read-date-inactive inactive)
15763 (add-hook 'post-command-hook 'org-read-date-display)
15764 (setq org-ans0 (read-string prompt default-input
15765 'org-read-date-history nil))
15766 ;; org-ans0: from prompt
15767 ;; org-ans1: from mouse click
15768 ;; org-ans2: from calendar motion
15769 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15770 (remove-hook 'post-command-hook 'org-read-date-display)
15771 (use-local-map old-map)
15772 (when org-read-date-overlay
15773 (delete-overlay org-read-date-overlay)
15774 (setq org-read-date-overlay nil)))))
15775 (bury-buffer "*Calendar*")))))
15777 (t ; Naked prompt only
15778 (unwind-protect
15779 (setq ans (read-string prompt default-input
15780 'org-read-date-history timestr))
15781 (when org-read-date-overlay
15782 (delete-overlay org-read-date-overlay)
15783 (setq org-read-date-overlay nil)))))
15785 (setq final (org-read-date-analyze ans org-def org-defdecode))
15787 (when org-read-date-analyze-forced-year
15788 (message "Year was forced into %s"
15789 (if org-read-date-force-compatible-dates
15790 "compatible range (1970-2037)"
15791 "range representable on this machine"))
15792 (ding))
15794 ;; One round trip to get rid of 34th of August and stuff like that....
15795 (setq final (decode-time (apply 'encode-time final)))
15797 (setq org-read-date-final-answer ans)
15799 (if to-time
15800 (apply 'encode-time final)
15801 (if (and (boundp 'org-time-was-given) org-time-was-given)
15802 (format "%04d-%02d-%02d %02d:%02d"
15803 (nth 5 final) (nth 4 final) (nth 3 final)
15804 (nth 2 final) (nth 1 final))
15805 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15807 (defvar org-def)
15808 (defvar org-defdecode)
15809 (defvar org-with-time)
15810 (defun org-read-date-display ()
15811 "Display the current date prompt interpretation in the minibuffer."
15812 (when org-read-date-display-live
15813 (when org-read-date-overlay
15814 (delete-overlay org-read-date-overlay))
15815 (when (minibufferp (current-buffer))
15816 (save-excursion
15817 (end-of-line 1)
15818 (while (not (equal (buffer-substring
15819 (max (point-min) (- (point) 4)) (point))
15820 " "))
15821 (insert " ")))
15822 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15823 " " (or org-ans1 org-ans2)))
15824 (org-end-time-was-given nil)
15825 (f (org-read-date-analyze ans org-def org-defdecode))
15826 (fmts (if org-dcst
15827 org-time-stamp-custom-formats
15828 org-time-stamp-formats))
15829 (fmt (if (or org-with-time
15830 (and (boundp 'org-time-was-given) org-time-was-given))
15831 (cdr fmts)
15832 (car fmts)))
15833 (txt (format-time-string fmt (apply 'encode-time f)))
15834 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15835 (txt (concat "=> " txt)))
15836 (when (and org-end-time-was-given
15837 (string-match org-plain-time-of-day-regexp txt))
15838 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15839 org-end-time-was-given
15840 (substring txt (match-end 0)))))
15841 (when org-read-date-analyze-futurep
15842 (setq txt (concat txt " (=>F)")))
15843 (setq org-read-date-overlay
15844 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15845 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15847 (defun org-read-date-analyze (ans org-def org-defdecode)
15848 "Analyze the combined answer of the date prompt."
15849 ;; FIXME: cleanup and comment
15850 (let ((nowdecode (decode-time (current-time)))
15851 delta deltan deltaw deltadef year month day
15852 hour minute second wday pm h2 m2 tl wday1
15853 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15854 (setq org-read-date-analyze-futurep nil
15855 org-read-date-analyze-forced-year nil)
15856 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15857 (setq ans "+0"))
15859 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15860 (setq ans (replace-match "" t t ans)
15861 deltan (car delta)
15862 deltaw (nth 1 delta)
15863 deltadef (nth 2 delta)))
15865 ;; Check if there is an iso week date in there. If yes, store the
15866 ;; info and postpone interpreting it until the rest of the parsing
15867 ;; is done.
15868 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15869 (setq iso-year (if (match-end 1)
15870 (org-small-year-to-year
15871 (string-to-number (match-string 1 ans))))
15872 iso-weekday (if (match-end 3)
15873 (string-to-number (match-string 3 ans)))
15874 iso-week (string-to-number (match-string 2 ans)))
15875 (setq ans (replace-match "" t t ans)))
15877 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15878 (when (string-match
15879 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15880 (setq year (if (match-end 2)
15881 (string-to-number (match-string 2 ans))
15882 (progn (setq kill-year t)
15883 (string-to-number (format-time-string "%Y"))))
15884 month (string-to-number (match-string 3 ans))
15885 day (string-to-number (match-string 4 ans)))
15886 (if (< year 100) (setq year (+ 2000 year)))
15887 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15888 t nil ans)))
15890 ;; Help matching dotted european dates
15891 (when (string-match
15892 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15893 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15894 (setq kill-year t)
15895 (string-to-number (format-time-string "%Y")))
15896 day (string-to-number (match-string 1 ans))
15897 month (string-to-number (match-string 2 ans))
15898 ans (replace-match (format "%04d-%02d-%02d" year month day)
15899 t nil ans)))
15901 ;; Help matching american dates, like 5/30 or 5/30/7
15902 (when (string-match
15903 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15904 (setq year (if (match-end 4)
15905 (string-to-number (match-string 4 ans))
15906 (progn (setq kill-year t)
15907 (string-to-number (format-time-string "%Y"))))
15908 month (string-to-number (match-string 1 ans))
15909 day (string-to-number (match-string 2 ans)))
15910 (if (< year 100) (setq year (+ 2000 year)))
15911 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15912 t nil ans)))
15913 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15914 ;; If there is a time with am/pm, and *no* time without it, we convert
15915 ;; so that matching will be successful.
15916 (loop for i from 1 to 2 do ; twice, for end time as well
15917 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15918 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15919 (setq hour (string-to-number (match-string 1 ans))
15920 minute (if (match-end 3)
15921 (string-to-number (match-string 3 ans))
15923 pm (equal ?p
15924 (string-to-char (downcase (match-string 4 ans)))))
15925 (if (and (= hour 12) (not pm))
15926 (setq hour 0)
15927 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15928 (setq ans (replace-match (format "%02d:%02d" hour minute)
15929 t t ans))))
15931 ;; Check if a time range is given as a duration
15932 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15933 (setq hour (string-to-number (match-string 1 ans))
15934 h2 (+ hour (string-to-number (match-string 3 ans)))
15935 minute (string-to-number (match-string 2 ans))
15936 m2 (+ minute (if (match-end 5) (string-to-number
15937 (match-string 5 ans))0)))
15938 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15939 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15940 t t ans)))
15942 ;; Check if there is a time range
15943 (when (boundp 'org-end-time-was-given)
15944 (setq org-time-was-given nil)
15945 (when (and (string-match org-plain-time-of-day-regexp ans)
15946 (match-end 8))
15947 (setq org-end-time-was-given (match-string 8 ans))
15948 (setq ans (concat (substring ans 0 (match-beginning 7))
15949 (substring ans (match-end 7))))))
15951 (setq tl (parse-time-string ans)
15952 day (or (nth 3 tl) (nth 3 org-defdecode))
15953 month (or (nth 4 tl)
15954 (if (and org-read-date-prefer-future
15955 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15956 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15957 (nth 4 org-defdecode)))
15958 year (or (and (not kill-year) (nth 5 tl))
15959 (if (and org-read-date-prefer-future
15960 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15961 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15962 (nth 5 org-defdecode)))
15963 hour (or (nth 2 tl) (nth 2 org-defdecode))
15964 minute (or (nth 1 tl) (nth 1 org-defdecode))
15965 second (or (nth 0 tl) 0)
15966 wday (nth 6 tl))
15968 (when (and (eq org-read-date-prefer-future 'time)
15969 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15970 (equal day (nth 3 nowdecode))
15971 (equal month (nth 4 nowdecode))
15972 (equal year (nth 5 nowdecode))
15973 (nth 2 tl)
15974 (or (< (nth 2 tl) (nth 2 nowdecode))
15975 (and (= (nth 2 tl) (nth 2 nowdecode))
15976 (nth 1 tl)
15977 (< (nth 1 tl) (nth 1 nowdecode)))))
15978 (setq day (1+ day)
15979 futurep t))
15981 ;; Special date definitions below
15982 (cond
15983 (iso-week
15984 ;; There was an iso week
15985 (require 'cal-iso)
15986 (setq futurep nil)
15987 (setq year (or iso-year year)
15988 day (or iso-weekday wday 1)
15989 wday nil ; to make sure that the trigger below does not match
15990 iso-date (calendar-gregorian-from-absolute
15991 (calendar-absolute-from-iso
15992 (list iso-week day year))))
15993 ; FIXME: Should we also push ISO weeks into the future?
15994 ; (when (and org-read-date-prefer-future
15995 ; (not iso-year)
15996 ; (< (calendar-absolute-from-gregorian iso-date)
15997 ; (time-to-days (current-time))))
15998 ; (setq year (1+ year)
15999 ; iso-date (calendar-gregorian-from-absolute
16000 ; (calendar-absolute-from-iso
16001 ; (list iso-week day year)))))
16002 (setq month (car iso-date)
16003 year (nth 2 iso-date)
16004 day (nth 1 iso-date)))
16005 (deltan
16006 (setq futurep nil)
16007 (unless deltadef
16008 (let ((now (decode-time (current-time))))
16009 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16010 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16011 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16012 ((equal deltaw "m") (setq month (+ month deltan)))
16013 ((equal deltaw "y") (setq year (+ year deltan)))))
16014 ((and wday (not (nth 3 tl)))
16015 ;; Weekday was given, but no day, so pick that day in the week
16016 ;; on or after the derived date.
16017 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16018 (unless (equal wday wday1)
16019 (setq day (+ day (% (- wday wday1 -7) 7))))))
16020 (if (and (boundp 'org-time-was-given)
16021 (nth 2 tl))
16022 (setq org-time-was-given t))
16023 (if (< year 100) (setq year (+ 2000 year)))
16024 ;; Check of the date is representable
16025 (if org-read-date-force-compatible-dates
16026 (progn
16027 (if (< year 1970)
16028 (setq year 1970 org-read-date-analyze-forced-year t))
16029 (if (> year 2037)
16030 (setq year 2037 org-read-date-analyze-forced-year t)))
16031 (condition-case nil
16032 (ignore (encode-time second minute hour day month year))
16033 (error
16034 (setq year (nth 5 org-defdecode))
16035 (setq org-read-date-analyze-forced-year t))))
16036 (setq org-read-date-analyze-futurep futurep)
16037 (list second minute hour day month year)))
16039 (defvar parse-time-weekdays)
16040 (defun org-read-date-get-relative (s today default)
16041 "Check string S for special relative date string.
16042 TODAY and DEFAULT are internal times, for today and for a default.
16043 Return shift list (N what def-flag)
16044 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16045 N is the number of WHATs to shift.
16046 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16047 the DEFAULT date rather than TODAY."
16048 (require 'parse-time)
16049 (when (and
16050 (string-match
16051 (concat
16052 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16053 "\\([0-9]+\\)?"
16054 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16055 "\\([ \t]\\|$\\)") s)
16056 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16057 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16058 (string-to-char (substring (match-string 1 s) -1))
16059 ?+))
16060 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16061 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16062 (what (if (match-end 3) (match-string 3 s) "d"))
16063 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16064 (date (if rel default today))
16065 (wday (nth 6 (decode-time date)))
16066 delta)
16067 (if wday1
16068 (progn
16069 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16070 (if (= dir ?-) (setq delta (- delta 7)))
16071 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16072 (list delta "d" rel))
16073 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16075 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16076 "Turn a user-specified date into the internal representation.
16077 The internal representation needed by the calendar is (month day year).
16078 This is a wrapper to handle the brain-dead convention in calendar that
16079 user function argument order change dependent on argument order."
16080 (if (boundp 'calendar-date-style)
16081 (cond
16082 ((eq calendar-date-style 'american)
16083 (list arg1 arg2 arg3))
16084 ((eq calendar-date-style 'european)
16085 (list arg2 arg1 arg3))
16086 ((eq calendar-date-style 'iso)
16087 (list arg2 arg3 arg1)))
16088 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16089 (if (org-bound-and-true-p european-calendar-style)
16090 (list arg2 arg1 arg3)
16091 (list arg1 arg2 arg3)))))
16093 (defun org-eval-in-calendar (form &optional keepdate)
16094 "Eval FORM in the calendar window and return to current window.
16095 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16096 otherwise stick to the current value of `org-ans2'."
16097 (let ((sf (selected-frame))
16098 (sw (selected-window)))
16099 (select-window (get-buffer-window "*Calendar*" t))
16100 (eval form)
16101 (when (and (not keepdate) (calendar-cursor-to-date))
16102 (let* ((date (calendar-cursor-to-date))
16103 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16104 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16105 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16106 (select-window sw)
16107 (org-select-frame-set-input-focus sf)))
16109 (defun org-calendar-select ()
16110 "Return to `org-read-date' with the date currently selected.
16111 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16112 (interactive)
16113 (when (calendar-cursor-to-date)
16114 (let* ((date (calendar-cursor-to-date))
16115 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16116 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16117 (if (active-minibuffer-window) (exit-minibuffer))))
16119 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16120 "Insert a date stamp for the date given by the internal TIME.
16121 WITH-HM means use the stamp format that includes the time of the day.
16122 INACTIVE means use square brackets instead of angular ones, so that the
16123 stamp will not contribute to the agenda.
16124 PRE and POST are optional strings to be inserted before and after the
16125 stamp.
16126 The command returns the inserted time stamp."
16127 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16128 stamp)
16129 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16130 (insert-before-markers (or pre ""))
16131 (when (listp extra)
16132 (setq extra (car extra))
16133 (if (and (stringp extra)
16134 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16135 (setq extra (format "-%02d:%02d"
16136 (string-to-number (match-string 1 extra))
16137 (string-to-number (match-string 2 extra))))
16138 (setq extra nil)))
16139 (when extra
16140 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16141 (insert-before-markers (setq stamp (format-time-string fmt time)))
16142 (insert-before-markers (or post ""))
16143 (setq org-last-inserted-timestamp stamp)))
16145 (defun org-toggle-time-stamp-overlays ()
16146 "Toggle the use of custom time stamp formats."
16147 (interactive)
16148 (setq org-display-custom-times (not org-display-custom-times))
16149 (unless org-display-custom-times
16150 (let ((p (point-min)) (bmp (buffer-modified-p)))
16151 (while (setq p (next-single-property-change p 'display))
16152 (if (and (get-text-property p 'display)
16153 (eq (get-text-property p 'face) 'org-date))
16154 (remove-text-properties
16155 p (setq p (next-single-property-change p 'display))
16156 '(display t))))
16157 (set-buffer-modified-p bmp)))
16158 (if (featurep 'xemacs)
16159 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16160 (org-restart-font-lock)
16161 (setq org-table-may-need-update t)
16162 (if org-display-custom-times
16163 (message "Time stamps are overlaid with custom format")
16164 (message "Time stamp overlays removed")))
16166 (defun org-display-custom-time (beg end)
16167 "Overlay modified time stamp format over timestamp between BEG and END."
16168 (let* ((ts (buffer-substring beg end))
16169 t1 w1 with-hm tf time str w2 (off 0))
16170 (save-match-data
16171 (setq t1 (org-parse-time-string ts t))
16172 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16173 (setq off (- (match-end 0) (match-beginning 0)))))
16174 (setq end (- end off))
16175 (setq w1 (- end beg)
16176 with-hm (and (nth 1 t1) (nth 2 t1))
16177 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16178 time (org-fix-decoded-time t1)
16179 str (org-add-props
16180 (format-time-string
16181 (substring tf 1 -1) (apply 'encode-time time))
16182 nil 'mouse-face 'highlight)
16183 w2 (length str))
16184 (if (not (= w2 w1))
16185 (add-text-properties (1+ beg) (+ 2 beg)
16186 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16187 (if (featurep 'xemacs)
16188 (progn
16189 (put-text-property beg end 'invisible t)
16190 (put-text-property beg end 'end-glyph (make-glyph str)))
16191 (put-text-property beg end 'display str))))
16193 (defun org-translate-time (string)
16194 "Translate all timestamps in STRING to custom format.
16195 But do this only if the variable `org-display-custom-times' is set."
16196 (when org-display-custom-times
16197 (save-match-data
16198 (let* ((start 0)
16199 (re org-ts-regexp-both)
16200 t1 with-hm inactive tf time str beg end)
16201 (while (setq start (string-match re string start))
16202 (setq beg (match-beginning 0)
16203 end (match-end 0)
16204 t1 (save-match-data
16205 (org-parse-time-string (substring string beg end) t))
16206 with-hm (and (nth 1 t1) (nth 2 t1))
16207 inactive (equal (substring string beg (1+ beg)) "[")
16208 tf (funcall (if with-hm 'cdr 'car)
16209 org-time-stamp-custom-formats)
16210 time (org-fix-decoded-time t1)
16211 str (format-time-string
16212 (concat
16213 (if inactive "[" "<") (substring tf 1 -1)
16214 (if inactive "]" ">"))
16215 (apply 'encode-time time))
16216 string (replace-match str t t string)
16217 start (+ start (length str)))))))
16218 string)
16220 (defun org-fix-decoded-time (time)
16221 "Set 0 instead of nil for the first 6 elements of time.
16222 Don't touch the rest."
16223 (let ((n 0))
16224 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16226 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16228 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16229 "Difference between TIMESTAMP-STRING and now in days.
16230 If SECONDS is non-nil, return the difference in seconds."
16231 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16232 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16233 (funcall fdiff (current-time)))))
16235 (defun org-deadline-close (timestamp-string &optional ndays)
16236 "Is the time in TIMESTAMP-STRING close to the current date?"
16237 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16238 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16239 (not (org-entry-is-done-p))))
16241 (defun org-get-wdays (ts &optional delay zero-delay)
16242 "Get the deadline lead time appropriate for timestring TS.
16243 When DELAY is non-nil, get the delay time for scheduled items
16244 instead of the deadline lead time. When ZERO-DELAY is non-nil
16245 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16246 don't try to find the delay cookie in the scheduled timestamp."
16247 (let ((tv (if delay org-scheduled-delay-days
16248 org-deadline-warning-days)))
16249 (cond
16250 ((or (and delay (< tv 0))
16251 (and delay zero-delay (<= tv 0))
16252 (and (not delay) (<= tv 0)))
16253 ;; Enforce this value no matter what
16254 (- tv))
16255 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16256 ;; lead time is specified.
16257 (floor (* (string-to-number (match-string 1 ts))
16258 (cdr (assoc (match-string 2 ts)
16259 '(("d" . 1) ("w" . 7)
16260 ("m" . 30.4) ("y" . 365.25)
16261 ("h" . 0.041667)))))))
16262 ;; go for the default.
16263 (t tv))))
16265 (defun org-calendar-select-mouse (ev)
16266 "Return to `org-read-date' with the date currently selected.
16267 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16268 (interactive "e")
16269 (mouse-set-point ev)
16270 (when (calendar-cursor-to-date)
16271 (let* ((date (calendar-cursor-to-date))
16272 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16273 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16274 (if (active-minibuffer-window) (exit-minibuffer))))
16276 (defun org-check-deadlines (ndays)
16277 "Check if there are any deadlines due or past due.
16278 A deadline is considered due if it happens within `org-deadline-warning-days'
16279 days from today's date. If the deadline appears in an entry marked DONE,
16280 it is not shown. The prefix arg NDAYS can be used to test that many
16281 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16282 (interactive "P")
16283 (let* ((org-warn-days
16284 (cond
16285 ((equal ndays '(4)) 100000)
16286 (ndays (prefix-numeric-value ndays))
16287 (t (abs org-deadline-warning-days))))
16288 (case-fold-search nil)
16289 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16290 (callback
16291 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16293 (message "%d deadlines past-due or due within %d days"
16294 (org-occur regexp nil callback)
16295 org-warn-days)))
16297 (defsubst org-re-timestamp (type)
16298 "Return a regexp for timestamp TYPE.
16299 Allowed values for TYPE are:
16301 all: all timestamps
16302 active: only active timestamps (<...>)
16303 inactive: only inactive timestamps ([...])
16304 scheduled: only scheduled timestamps
16305 deadline: only deadline timestamps
16307 When TYPE is nil, fall back on returning a regexp that matches
16308 both scheduled and deadline timestamps."
16309 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16310 ((eq type 'active) org-ts-regexp)
16311 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16312 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16313 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16314 ((eq type 'scheduled-or-deadline)
16315 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16317 (defun org-check-before-date (date)
16318 "Check if there are deadlines or scheduled entries before DATE."
16319 (interactive (list (org-read-date)))
16320 (let ((case-fold-search nil)
16321 (regexp (org-re-timestamp org-ts-type))
16322 (callback
16323 (lambda () (time-less-p
16324 (org-time-string-to-time (match-string 1))
16325 (org-time-string-to-time date)))))
16326 (message "%d entries before %s"
16327 (org-occur regexp nil callback) date)))
16329 (defun org-check-after-date (date)
16330 "Check if there are deadlines or scheduled entries after DATE."
16331 (interactive (list (org-read-date)))
16332 (let ((case-fold-search nil)
16333 (regexp (org-re-timestamp org-ts-type))
16334 (callback
16335 (lambda () (not
16336 (time-less-p
16337 (org-time-string-to-time (match-string 1))
16338 (org-time-string-to-time date))))))
16339 (message "%d entries after %s"
16340 (org-occur regexp nil callback) date)))
16342 (defun org-check-dates-range (start-date end-date)
16343 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16344 (interactive (list (org-read-date nil nil nil "Range starts")
16345 (org-read-date nil nil nil "Range end")))
16346 (let ((case-fold-search nil)
16347 (regexp (org-re-timestamp org-ts-type))
16348 (callback
16349 (lambda ()
16350 (let ((match (match-string 1)))
16351 (and
16352 (not (time-less-p
16353 (org-time-string-to-time match)
16354 (org-time-string-to-time start-date)))
16355 (time-less-p
16356 (org-time-string-to-time match)
16357 (org-time-string-to-time end-date)))))))
16358 (message "%d entries between %s and %s"
16359 (org-occur regexp nil callback) start-date end-date)))
16361 (defun org-evaluate-time-range (&optional to-buffer)
16362 "Evaluate a time range by computing the difference between start and end.
16363 Normally the result is just printed in the echo area, but with prefix arg
16364 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16365 If the time range is actually in a table, the result is inserted into the
16366 next column.
16367 For time difference computation, a year is assumed to be exactly 365
16368 days in order to avoid rounding problems."
16369 (interactive "P")
16371 (org-clock-update-time-maybe)
16372 (save-excursion
16373 (unless (org-at-date-range-p t)
16374 (goto-char (point-at-bol))
16375 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16376 (if (not (org-at-date-range-p t))
16377 (error "Not at a time-stamp range, and none found in current line")))
16378 (let* ((ts1 (match-string 1))
16379 (ts2 (match-string 2))
16380 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16381 (match-end (match-end 0))
16382 (time1 (org-time-string-to-time ts1))
16383 (time2 (org-time-string-to-time ts2))
16384 (t1 (org-float-time time1))
16385 (t2 (org-float-time time2))
16386 (diff (abs (- t2 t1)))
16387 (negative (< (- t2 t1) 0))
16388 ;; (ys (floor (* 365 24 60 60)))
16389 (ds (* 24 60 60))
16390 (hs (* 60 60))
16391 (fy "%dy %dd %02d:%02d")
16392 (fy1 "%dy %dd")
16393 (fd "%dd %02d:%02d")
16394 (fd1 "%dd")
16395 (fh "%02d:%02d")
16396 y d h m align)
16397 (if havetime
16398 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16400 d (floor (/ diff ds)) diff (mod diff ds)
16401 h (floor (/ diff hs)) diff (mod diff hs)
16402 m (floor (/ diff 60)))
16403 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16405 d (floor (+ (/ diff ds) 0.5))
16406 h 0 m 0))
16407 (if (not to-buffer)
16408 (message "%s" (org-make-tdiff-string y d h m))
16409 (if (org-at-table-p)
16410 (progn
16411 (goto-char match-end)
16412 (setq align t)
16413 (and (looking-at " *|") (goto-char (match-end 0))))
16414 (goto-char match-end))
16415 (if (looking-at
16416 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16417 (replace-match ""))
16418 (if negative (insert " -"))
16419 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16420 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16421 (insert " " (format fh h m))))
16422 (if align (org-table-align))
16423 (message "Time difference inserted")))))
16425 (defun org-make-tdiff-string (y d h m)
16426 (let ((fmt "")
16427 (l nil))
16428 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16429 l (push y l)))
16430 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16431 l (push d l)))
16432 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16433 l (push h l)))
16434 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16435 l (push m l)))
16436 (apply 'format fmt (nreverse l))))
16438 (defun org-time-string-to-time (s &optional buffer pos)
16439 "Convert a timestamp string into internal time."
16440 (condition-case errdata
16441 (apply 'encode-time (org-parse-time-string s))
16442 (error (error "Bad timestamp `%s'%s\nError was: %s"
16443 s (if (not (and buffer pos))
16445 (format " at %d in buffer `%s'" pos buffer))
16446 (cdr errdata)))))
16448 (defun org-time-string-to-seconds (s)
16449 "Convert a timestamp string to a number of seconds."
16450 (org-float-time (org-time-string-to-time s)))
16452 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16453 "Convert a time stamp to an absolute day number.
16454 If there is a specifier for a cyclic time stamp, get the closest date to
16455 DAYNR.
16456 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16457 The variable date is bound by the calendar when this is called."
16458 (cond
16459 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16460 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16461 daynr
16462 (+ daynr 1000)))
16463 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16464 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16465 (time-to-days (current-time))) (match-string 0 s)
16466 prefer show-all))
16467 (t (time-to-days
16468 (condition-case errdata
16469 (apply 'encode-time (org-parse-time-string s))
16470 (error (error "Bad timestamp `%s'%s\nError was: %s"
16471 s (if (not (and buffer pos))
16473 (format " at %d in buffer `%s'" pos buffer))
16474 (cdr errdata))))))))
16476 (defun org-days-to-iso-week (days)
16477 "Return the iso week number."
16478 (require 'cal-iso)
16479 (car (calendar-iso-from-absolute days)))
16481 (defun org-small-year-to-year (year)
16482 "Convert 2-digit years into 4-digit years.
16483 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16484 The year 2000 cannot be abbreviated. Any year larger than 99
16485 is returned unchanged."
16486 (if (< year 38)
16487 (setq year (+ 2000 year))
16488 (if (< year 100)
16489 (setq year (+ 1900 year))))
16490 year)
16492 (defun org-time-from-absolute (d)
16493 "Return the time corresponding to date D.
16494 D may be an absolute day number, or a calendar-type list (month day year)."
16495 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16496 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16498 (defun org-calendar-holiday ()
16499 "List of holidays, for Diary display in Org-mode."
16500 (require 'holidays)
16501 (let ((hl (funcall
16502 (if (fboundp 'calendar-check-holidays)
16503 'calendar-check-holidays 'check-calendar-holidays) date)))
16504 (if hl (mapconcat 'identity hl "; "))))
16506 (defun org-diary-sexp-entry (sexp entry date)
16507 "Process a SEXP diary ENTRY for DATE."
16508 (require 'diary-lib)
16509 (let ((result (if calendar-debug-sexp
16510 (let ((stack-trace-on-error t))
16511 (eval (car (read-from-string sexp))))
16512 (condition-case nil
16513 (eval (car (read-from-string sexp)))
16514 (error
16515 (beep)
16516 (message "Bad sexp at line %d in %s: %s"
16517 (org-current-line)
16518 (buffer-file-name) sexp)
16519 (sleep-for 2))))))
16520 (cond ((stringp result) (split-string result "; "))
16521 ((and (consp result)
16522 (not (consp (cdr result)))
16523 (stringp (cdr result))) (cdr result))
16524 ((and (consp result)
16525 (stringp (car result))) result)
16526 (result entry))))
16528 (defun org-diary-to-ical-string (frombuf)
16529 "Get iCalendar entries from diary entries in buffer FROMBUF.
16530 This uses the icalendar.el library."
16531 (let* ((tmpdir (if (featurep 'xemacs)
16532 (temp-directory)
16533 temporary-file-directory))
16534 (tmpfile (make-temp-name
16535 (expand-file-name "orgics" tmpdir)))
16536 buf rtn b e)
16537 (with-current-buffer frombuf
16538 (icalendar-export-region (point-min) (point-max) tmpfile)
16539 (setq buf (find-buffer-visiting tmpfile))
16540 (set-buffer buf)
16541 (goto-char (point-min))
16542 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16543 (setq b (match-beginning 0)))
16544 (goto-char (point-max))
16545 (if (re-search-backward "^END:VEVENT" nil t)
16546 (setq e (match-end 0)))
16547 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16548 (kill-buffer buf)
16549 (delete-file tmpfile)
16550 rtn))
16552 (defun org-closest-date (start current change prefer show-all)
16553 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16554 When PREFER is `past', return a date that is either CURRENT or past.
16555 When PREFER is `future', return a date that is either CURRENT or future.
16556 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16557 ;; Make the proper lists from the dates
16558 (catch 'exit
16559 (let ((a1 '(("h" . hour)
16560 ("d" . day)
16561 ("w" . week)
16562 ("m" . month)
16563 ("y" . year)))
16564 (shour (nth 2 (org-parse-time-string start)))
16565 dn dw sday cday n1 n2 n0
16566 d m y y1 y2 date1 date2 nmonths nm ny m2)
16568 (setq start (org-date-to-gregorian start)
16569 current (org-date-to-gregorian
16570 (if show-all
16571 current
16572 (time-to-days (current-time))))
16573 sday (calendar-absolute-from-gregorian start)
16574 cday (calendar-absolute-from-gregorian current))
16576 (if (<= cday sday) (throw 'exit sday))
16578 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16579 (setq dn (string-to-number (match-string 1 change))
16580 dw (cdr (assoc (match-string 2 change) a1)))
16581 (error "Invalid change specifier: %s" change))
16582 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16583 (cond
16584 ((eq dw 'hour)
16585 (let ((missing-hours
16586 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16587 dn)))
16588 (setq n1 (if (zerop missing-hours) cday
16589 (- cday (1+ (floor (/ missing-hours 24)))))
16590 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16591 ((eq dw 'day)
16592 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16593 n2 (+ n1 dn)))
16594 ((eq dw 'year)
16595 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16596 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16597 (setq date1 (list m d y1)
16598 n1 (calendar-absolute-from-gregorian date1)
16599 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16600 n2 (calendar-absolute-from-gregorian date2)))
16601 ((eq dw 'month)
16602 ;; approx number of month between the two dates
16603 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16604 ;; How often does dn fit in there?
16605 (setq d (nth 1 start) m (car start) y (nth 2 start)
16606 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16607 m (+ m nm)
16608 ny (floor (/ m 12))
16609 y (+ y ny)
16610 m (- m (* ny 12)))
16611 (while (> m 12) (setq m (- m 12) y (1+ y)))
16612 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16613 (setq m2 (+ m dn) y2 y)
16614 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16615 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16616 (while (<= n2 cday)
16617 (setq n1 n2 m m2 y y2)
16618 (setq m2 (+ m dn) y2 y)
16619 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16620 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16621 ;; Make sure n1 is the earlier date
16622 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16623 (if show-all
16624 (cond
16625 ((eq prefer 'past) (if (= cday n2) n2 n1))
16626 ((eq prefer 'future) (if (= cday n1) n1 n2))
16627 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16628 (cond
16629 ((eq prefer 'past) (if (= cday n2) n2 n1))
16630 ((eq prefer 'future) (if (= cday n1) n1 n2))
16631 (t (if (= cday n1) n1 n2)))))))
16633 (defun org-date-to-gregorian (date)
16634 "Turn any specification of DATE into a Gregorian date for the calendar."
16635 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16636 ((and (listp date) (= (length date) 3)) date)
16637 ((stringp date)
16638 (setq date (org-parse-time-string date))
16639 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16640 ((listp date)
16641 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16643 (defun org-parse-time-string (s &optional nodefault)
16644 "Parse the standard Org-mode time string.
16645 This should be a lot faster than the normal `parse-time-string'.
16646 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16647 hour and minute fields will be nil if not given."
16648 (cond ((string-match org-ts-regexp0 s)
16649 (list 0
16650 (if (or (match-beginning 8) (not nodefault))
16651 (string-to-number (or (match-string 8 s) "0")))
16652 (if (or (match-beginning 7) (not nodefault))
16653 (string-to-number (or (match-string 7 s) "0")))
16654 (string-to-number (match-string 4 s))
16655 (string-to-number (match-string 3 s))
16656 (string-to-number (match-string 2 s))
16657 nil nil nil))
16658 ((string-match "^<[^>]+>$" s)
16659 (decode-time (seconds-to-time (org-matcher-time s))))
16660 (t (error "Not a standard Org-mode time string: %s" s))))
16662 (defun org-timestamp-up (&optional arg)
16663 "Increase the date item at the cursor by one.
16664 If the cursor is on the year, change the year. If it is on the month,
16665 the day or the time, change that.
16666 With prefix ARG, change by that many units."
16667 (interactive "p")
16668 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16670 (defun org-timestamp-down (&optional arg)
16671 "Decrease the date item at the cursor by one.
16672 If the cursor is on the year, change the year. If it is on the month,
16673 the day or the time, change that.
16674 With prefix ARG, change by that many units."
16675 (interactive "p")
16676 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16678 (defun org-timestamp-up-day (&optional arg)
16679 "Increase the date in the time stamp by one day.
16680 With prefix ARG, change that many days."
16681 (interactive "p")
16682 (if (and (not (org-at-timestamp-p t))
16683 (org-at-heading-p))
16684 (org-todo 'up)
16685 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16687 (defun org-timestamp-down-day (&optional arg)
16688 "Decrease the date in the time stamp by one day.
16689 With prefix ARG, change that many days."
16690 (interactive "p")
16691 (if (and (not (org-at-timestamp-p t))
16692 (org-at-heading-p))
16693 (org-todo 'down)
16694 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16696 (defun org-at-timestamp-p (&optional inactive-ok)
16697 "Determine if the cursor is in or at a timestamp."
16698 (interactive)
16699 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16700 (pos (point))
16701 (ans (or (looking-at tsr)
16702 (save-excursion
16703 (skip-chars-backward "^[<\n\r\t")
16704 (if (> (point) (point-min)) (backward-char 1))
16705 (and (looking-at tsr)
16706 (> (- (match-end 0) pos) -1))))))
16707 (and ans
16708 (boundp 'org-ts-what)
16709 (setq org-ts-what
16710 (cond
16711 ((= pos (match-beginning 0)) 'bracket)
16712 ;; Point is considered to be "on the bracket" whether
16713 ;; it's really on it or right after it.
16714 ((= pos (1- (match-end 0))) 'bracket)
16715 ((= pos (match-end 0)) 'after)
16716 ((org-pos-in-match-range pos 2) 'year)
16717 ((org-pos-in-match-range pos 3) 'month)
16718 ((org-pos-in-match-range pos 7) 'hour)
16719 ((org-pos-in-match-range pos 8) 'minute)
16720 ((or (org-pos-in-match-range pos 4)
16721 (org-pos-in-match-range pos 5)) 'day)
16722 ((and (> pos (or (match-end 8) (match-end 5)))
16723 (< pos (match-end 0)))
16724 (- pos (or (match-end 8) (match-end 5))))
16725 (t 'day))))
16726 ans))
16728 (defun org-toggle-timestamp-type ()
16729 "Toggle the type (<active> or [inactive]) of a time stamp."
16730 (interactive)
16731 (when (org-at-timestamp-p t)
16732 (let ((beg (match-beginning 0)) (end (match-end 0))
16733 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16734 (save-excursion
16735 (goto-char beg)
16736 (while (re-search-forward "[][<>]" end t)
16737 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16738 t t)))
16739 (message "Timestamp is now %sactive"
16740 (if (equal (char-after beg) ?<) "" "in")))))
16742 (defvar org-clock-history) ; defined in org-clock.el
16743 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16744 (defun org-timestamp-change (n &optional what updown)
16745 "Change the date in the time stamp at point.
16746 The date will be changed by N times WHAT. WHAT can be `day', `month',
16747 `year', `minute', `second'. If WHAT is not given, the cursor position
16748 in the timestamp determines what will be changed."
16749 (let ((origin (point)) origin-cat
16750 with-hm inactive
16751 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16752 org-ts-what
16753 extra rem
16754 ts time time0 fixnext clrgx)
16755 (if (not (org-at-timestamp-p t))
16756 (error "Not at a timestamp"))
16757 (if (and (not what) (eq org-ts-what 'bracket))
16758 (org-toggle-timestamp-type)
16759 ;; Point isn't on brackets. Remember the part of the time-stamp
16760 ;; the point was in. Indeed, size of time-stamps may change,
16761 ;; but point must be kept in the same category nonetheless.
16762 (setq origin-cat org-ts-what)
16763 (if (and (not what) (not (eq org-ts-what 'day))
16764 org-display-custom-times
16765 (get-text-property (point) 'display)
16766 (not (get-text-property (1- (point)) 'display)))
16767 (setq org-ts-what 'day))
16768 (setq org-ts-what (or what org-ts-what)
16769 inactive (= (char-after (match-beginning 0)) ?\[)
16770 ts (match-string 0))
16771 (replace-match "")
16772 (if (string-match
16773 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16775 (setq extra (match-string 1 ts)))
16776 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16777 (setq with-hm t))
16778 (setq time0 (org-parse-time-string ts))
16779 (when (and updown
16780 (eq org-ts-what 'minute)
16781 (not current-prefix-arg))
16782 ;; This looks like s-up and s-down. Change by one rounding step.
16783 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16784 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16785 (setcar (cdr time0) (+ (nth 1 time0)
16786 (if (> n 0) (- rem) (- dm rem))))))
16787 (setq time
16788 (encode-time (or (car time0) 0)
16789 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16790 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16791 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16792 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16793 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16794 (nthcdr 6 time0)))
16795 (when (and (member org-ts-what '(hour minute))
16796 extra
16797 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16798 (setq extra (org-modify-ts-extra
16799 extra
16800 (if (eq org-ts-what 'hour) 2 5)
16801 n dm)))
16802 (when (integerp org-ts-what)
16803 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16804 (if (eq what 'calendar)
16805 (let ((cal-date (org-get-date-from-calendar)))
16806 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16807 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16808 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16809 (setcar time0 (or (car time0) 0))
16810 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16811 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16812 (setq time (apply 'encode-time time0))))
16813 ;; Insert the new time-stamp, and ensure point stays in the same
16814 ;; category as before (i.e. not after the last position in that
16815 ;; category).
16816 (let ((pos (point)))
16817 ;; Stay before inserted string. `save-excursion' is of no use.
16818 (setq org-last-changed-timestamp
16819 (org-insert-time-stamp time with-hm inactive nil nil extra))
16820 (goto-char pos))
16821 (save-match-data
16822 (looking-at org-ts-regexp3)
16823 (goto-char (cond
16824 ;; `day' category ends before `hour' if any, or at
16825 ;; the end of the day name.
16826 ((eq origin-cat 'day)
16827 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16828 ((eq origin-cat 'hour) (min (match-end 7) origin))
16829 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16830 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16831 ;; `year' and `month' have both fixed size: point
16832 ;; couldn't have moved into another part.
16833 (t origin))))
16834 ;; Update clock if on a CLOCK line.
16835 (org-clock-update-time-maybe)
16836 ;; Maybe adjust the closest clock in `org-clock-history'
16837 (when org-clock-adjust-closest
16838 (if (not (and (org-at-clock-log-p)
16839 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16840 org-clock-history))))))
16841 (message "No clock to adjust")
16842 (cond ((save-excursion ; fix previous clock?
16843 (re-search-backward org-ts-regexp0 nil t)
16844 (org-looking-back (concat org-clock-string " \\[")))
16845 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16846 ((save-excursion ; fix next clock?
16847 (re-search-backward org-ts-regexp0 nil t)
16848 (looking-at (concat org-ts-regexp0 "\\] =>")))
16849 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16850 (save-window-excursion
16851 ;; Find closest clock to point, adjust the previous/next one in history
16852 (let* ((p (save-excursion (org-back-to-heading t)))
16853 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16854 (clfixnth
16855 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16856 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16857 (if (not clfixpos)
16858 (message "No clock to adjust")
16859 (save-excursion
16860 (org-goto-marker-or-bmk clfixpos)
16861 (org-show-subtree)
16862 (when (re-search-forward clrgx nil t)
16863 (goto-char (match-beginning 1))
16864 (let (org-clock-adjust-closest)
16865 (org-timestamp-change n org-ts-what updown))
16866 (message "Clock adjusted in %s for heading: %s"
16867 (file-name-nondirectory (buffer-file-name))
16868 (org-get-heading t t)))))))))
16869 ;; Try to recenter the calendar window, if any.
16870 (if (and org-calendar-follow-timestamp-change
16871 (get-buffer-window "*Calendar*" t)
16872 (memq org-ts-what '(day month year)))
16873 (org-recenter-calendar (time-to-days time))))))
16875 (defun org-modify-ts-extra (s pos n dm)
16876 "Change the different parts of the lead-time and repeat fields in timestamp."
16877 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16878 ng h m new rem)
16879 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16880 (cond
16881 ((or (org-pos-in-match-range pos 2)
16882 (org-pos-in-match-range pos 3))
16883 (setq m (string-to-number (match-string 3 s))
16884 h (string-to-number (match-string 2 s)))
16885 (if (org-pos-in-match-range pos 2)
16886 (setq h (+ h n))
16887 (setq n (* dm (org-no-warnings (signum n))))
16888 (when (not (= 0 (setq rem (% m dm))))
16889 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16890 (setq m (+ m n)))
16891 (if (< m 0) (setq m (+ m 60) h (1- h)))
16892 (if (> m 59) (setq m (- m 60) h (1+ h)))
16893 (setq h (min 24 (max 0 h)))
16894 (setq ng 1 new (format "-%02d:%02d" h m)))
16895 ((org-pos-in-match-range pos 6)
16896 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16897 ((org-pos-in-match-range pos 5)
16898 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16900 ((org-pos-in-match-range pos 9)
16901 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16902 ((org-pos-in-match-range pos 8)
16903 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16905 (when ng
16906 (setq s (concat
16907 (substring s 0 (match-beginning ng))
16909 (substring s (match-end ng))))))
16912 (defun org-recenter-calendar (date)
16913 "If the calendar is visible, recenter it to DATE."
16914 (let ((cwin (get-buffer-window "*Calendar*" t)))
16915 (when cwin
16916 (let ((calendar-move-hook nil))
16917 (with-selected-window cwin
16918 (calendar-goto-date (if (listp date) date
16919 (calendar-gregorian-from-absolute date))))))))
16921 (defun org-goto-calendar (&optional arg)
16922 "Go to the Emacs calendar at the current date.
16923 If there is a time stamp in the current line, go to that date.
16924 A prefix ARG can be used to force the current date."
16925 (interactive "P")
16926 (let ((tsr org-ts-regexp) diff
16927 (calendar-move-hook nil)
16928 (calendar-view-holidays-initially-flag nil)
16929 (calendar-view-diary-initially-flag nil))
16930 (if (or (org-at-timestamp-p)
16931 (save-excursion
16932 (beginning-of-line 1)
16933 (looking-at (concat ".*" tsr))))
16934 (let ((d1 (time-to-days (current-time)))
16935 (d2 (time-to-days
16936 (org-time-string-to-time (match-string 1)))))
16937 (setq diff (- d2 d1))))
16938 (calendar)
16939 (calendar-goto-today)
16940 (if (and diff (not arg)) (calendar-forward-day diff))))
16942 (defun org-get-date-from-calendar ()
16943 "Return a list (month day year) of date at point in calendar."
16944 (with-current-buffer "*Calendar*"
16945 (save-match-data
16946 (calendar-cursor-to-date))))
16948 (defun org-date-from-calendar ()
16949 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16950 If there is already a time stamp at the cursor position, update it."
16951 (interactive)
16952 (if (org-at-timestamp-p t)
16953 (org-timestamp-change 0 'calendar)
16954 (let ((cal-date (org-get-date-from-calendar)))
16955 (org-insert-time-stamp
16956 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16958 (defcustom org-effort-durations
16959 `(("h" . 60)
16960 ("d" . ,(* 60 8))
16961 ("w" . ,(* 60 8 5))
16962 ("m" . ,(* 60 8 5 4))
16963 ("y" . ,(* 60 8 5 40)))
16964 "Conversion factor to minutes for an effort modifier.
16966 Each entry has the form (MODIFIER . MINUTES).
16968 In an effort string, a number followed by MODIFIER is multiplied
16969 by the specified number of MINUTES to obtain an effort in
16970 minutes.
16972 For example, if the value of this variable is ((\"hours\" . 60)), then an
16973 effort string \"2hours\" is equivalent to 120 minutes."
16974 :group 'org-agenda
16975 :version "24.1"
16976 :type '(alist :key-type (string :tag "Modifier")
16977 :value-type (number :tag "Minutes")))
16979 (defun org-minutes-to-clocksum-string (m)
16980 "Format number of minutes as a clocksum string.
16981 The format is determined by `org-time-clocksum-format',
16982 `org-time-clocksum-use-fractional' and
16983 `org-time-clocksum-fractional-format' and
16984 `org-time-clocksum-use-effort-durations'."
16985 (let ((clocksum "") h d w mo y fmt n)
16986 (setq h (if org-time-clocksum-use-effort-durations
16987 (cdr (assoc "h" org-effort-durations)) 60)
16988 d (if org-time-clocksum-use-effort-durations
16989 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16990 w (if org-time-clocksum-use-effort-durations
16991 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16992 mo (if org-time-clocksum-use-effort-durations
16993 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16994 y (if org-time-clocksum-use-effort-durations
16995 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16996 ;; fractional format
16997 (if org-time-clocksum-use-fractional
16998 (cond
16999 ;; single format string
17000 ((stringp org-time-clocksum-fractional-format)
17001 (format org-time-clocksum-fractional-format (/ m (float h))))
17002 ;; choice of fractional formats for different time units
17003 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17004 (> (/ (truncate m) (* y d h)) 0))
17005 (format fmt (/ m (* y d (float h)))))
17006 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17007 (> (/ (truncate m) (* mo d h)) 0))
17008 (format fmt (/ m (* mo d (float h)))))
17009 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17010 (> (/ (truncate m) (* w d h)) 0))
17011 (format fmt (/ m (* w d (float h)))))
17012 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17013 (> (/ (truncate m) (* d h)) 0))
17014 (format fmt (/ m (* d (float h)))))
17015 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17016 (> (/ (truncate m) h) 0))
17017 (format fmt (/ m (float h))))
17018 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17019 (format fmt m))
17020 ;; fall back to smallest time unit with a format
17021 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17022 (format fmt (/ m (float h))))
17023 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17024 (format fmt (/ m (* d (float h)))))
17025 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17026 (format fmt (/ m (* w d (float h)))))
17027 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17028 (format fmt (/ m (* mo d (float h)))))
17029 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17030 (format fmt (/ m (* y d (float h))))))
17031 ;; standard (non-fractional) format, with single format string
17032 (if (stringp org-time-clocksum-format)
17033 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17034 ;; separate formats components
17035 (and (setq fmt (plist-get org-time-clocksum-format :years))
17036 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17037 (plist-get org-time-clocksum-format :require-years))
17038 (setq clocksum (concat clocksum (format fmt n))
17039 m (- m (* n y d h))))
17040 (and (setq fmt (plist-get org-time-clocksum-format :months))
17041 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17042 (plist-get org-time-clocksum-format :require-months))
17043 (setq clocksum (concat clocksum (format fmt n))
17044 m (- m (* n mo d h))))
17045 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17046 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17047 (plist-get org-time-clocksum-format :require-weeks))
17048 (setq clocksum (concat clocksum (format fmt n))
17049 m (- m (* n w d h))))
17050 (and (setq fmt (plist-get org-time-clocksum-format :days))
17051 (or (> (setq n (/ (truncate m) (* d h))) 0)
17052 (plist-get org-time-clocksum-format :require-days))
17053 (setq clocksum (concat clocksum (format fmt n))
17054 m (- m (* n d h))))
17055 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17056 (or (> (setq n (/ (truncate m) h)) 0)
17057 (plist-get org-time-clocksum-format :require-hours))
17058 (setq clocksum (concat clocksum (format fmt n))
17059 m (- m (* n h))))
17060 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17061 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17062 (setq clocksum (concat clocksum (format fmt m))))
17063 ;; return formatted time duration
17064 clocksum))))
17066 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17067 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17068 "Org mode version 8.0")
17070 (defun org-hours-to-clocksum-string (n)
17071 (org-minutes-to-clocksum-string (* n 60)))
17073 (defun org-hh:mm-string-to-minutes (s)
17074 "Convert a string H:MM to a number of minutes.
17075 If the string is just a number, interpret it as minutes.
17076 In fact, the first hh:mm or number in the string will be taken,
17077 there can be extra stuff in the string.
17078 If no number is found, the return value is 0."
17079 (cond
17080 ((integerp s) s)
17081 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17082 (+ (* (string-to-number (match-string 1 s)) 60)
17083 (string-to-number (match-string 2 s))))
17084 ((string-match "\\([0-9]+\\)" s)
17085 (string-to-number (match-string 1 s)))
17086 (t 0)))
17088 (defcustom org-image-actual-width t
17089 "Should we use the actual width of images when inlining them?
17091 When set to `t', always use the image width.
17093 When set to a number, use imagemagick (when available) to set
17094 the image's width to this value.
17096 When set to a number in a list, try to get the width from the
17097 #+ATTR.* keyword if it matches a width specification like
17098 width=\"[0-9]+\", and fall back on that number if none is found.
17100 When set to nil, try to get the width from an #+ATTR.* keyword
17101 and fall back on the original width if none is found.
17103 This requires Emacs >= 24.1, build with imagemagick support."
17104 :group 'org-appearance
17105 :version "24.3"
17106 :type '(choice
17107 (const :tag "Use the image width" t)
17108 (integer :tag "Use a number of pixels")
17109 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17110 (const :tag "Use #+ATTR* or don't resize" nil)))
17112 (defcustom org-agenda-inhibit-startup t
17113 "Inhibit startup when preparing agenda buffers.
17114 When this variable is `t' (the default), the initialization of
17115 the Org agenda buffers is inhibited: e.g. the visibility state
17116 is not set, the tables are not re-aligned, etc."
17117 :type 'boolean
17118 :version "24.3"
17119 :group 'org-agenda)
17121 (defun org-duration-string-to-minutes (s &optional output-to-string)
17122 "Convert a duration string S to minutes.
17124 A bare number is interpreted as minutes, modifiers can be set by
17125 customizing `org-effort-durations' (which see).
17127 Entries containing a colon are interpreted as H:MM by
17128 `org-hh:mm-string-to-minutes'."
17129 (let ((result 0)
17130 (re (concat "\\([0-9.]+\\) *\\("
17131 (regexp-opt (mapcar 'car org-effort-durations))
17132 "\\)")))
17133 (while (string-match re s)
17134 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17135 (string-to-number (match-string 1 s))))
17136 (setq s (replace-match "" nil t s)))
17137 (setq result (floor result))
17138 (incf result (org-hh:mm-string-to-minutes s))
17139 (if output-to-string (number-to-string result) result)))
17141 ;;;; Files
17143 (defun org-save-all-org-buffers ()
17144 "Save all Org-mode buffers without user confirmation."
17145 (interactive)
17146 (message "Saving all Org-mode buffers...")
17147 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17148 (when (featurep 'org-id) (org-id-locations-save))
17149 (message "Saving all Org-mode buffers... done"))
17151 (defun org-revert-all-org-buffers ()
17152 "Revert all Org-mode buffers.
17153 Prompt for confirmation when there are unsaved changes.
17154 Be sure you know what you are doing before letting this function
17155 overwrite your changes.
17157 This function is useful in a setup where one tracks org files
17158 with a version control system, to revert on one machine after pulling
17159 changes from another. I believe the procedure must be like this:
17161 1. M-x org-save-all-org-buffers
17162 2. Pull changes from the other machine, resolve conflicts
17163 3. M-x org-revert-all-org-buffers"
17164 (interactive)
17165 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17166 (error "Abort"))
17167 (save-excursion
17168 (save-window-excursion
17169 (mapc
17170 (lambda (b)
17171 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17172 (with-current-buffer b buffer-file-name))
17173 (org-pop-to-buffer-same-window b)
17174 (revert-buffer t 'no-confirm)))
17175 (buffer-list))
17176 (when (and (featurep 'org-id) org-id-track-globally)
17177 (org-id-locations-load)))))
17179 ;;;; Agenda files
17181 ;;;###autoload
17182 (defun org-switchb (&optional arg)
17183 "Switch between Org buffers.
17184 With one prefix argument, restrict available buffers to files.
17185 With two prefix arguments, restrict available buffers to agenda files.
17187 Defaults to `iswitchb' for buffer name completion.
17188 Set `org-completion-use-ido' to make it use ido instead."
17189 (interactive "P")
17190 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17191 ((equal arg '(16)) (org-buffer-list 'agenda))
17192 (t (org-buffer-list))))
17193 (org-completion-use-iswitchb org-completion-use-iswitchb)
17194 (org-completion-use-ido org-completion-use-ido))
17195 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17196 (setq org-completion-use-iswitchb t))
17197 (org-pop-to-buffer-same-window
17198 (org-icompleting-read "Org buffer: "
17199 (mapcar 'list (mapcar 'buffer-name blist))
17200 nil t))))
17202 ;;; Define some older names previously used for this functionality
17203 ;;;###autoload
17204 (defalias 'org-ido-switchb 'org-switchb)
17205 ;;;###autoload
17206 (defalias 'org-iswitchb 'org-switchb)
17208 (defun org-buffer-list (&optional predicate exclude-tmp)
17209 "Return a list of Org buffers.
17210 PREDICATE can be `export', `files' or `agenda'.
17212 export restrict the list to Export buffers.
17213 files restrict the list to buffers visiting Org files.
17214 agenda restrict the list to buffers visiting agenda files.
17216 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17217 (let* ((bfn nil)
17218 (agenda-files (and (eq predicate 'agenda)
17219 (mapcar 'file-truename (org-agenda-files t))))
17220 (filter
17221 (cond
17222 ((eq predicate 'files)
17223 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17224 ((eq predicate 'export)
17225 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17226 ((eq predicate 'agenda)
17227 (lambda (b)
17228 (with-current-buffer b
17229 (and (derived-mode-p 'org-mode)
17230 (setq bfn (buffer-file-name b))
17231 (member (file-truename bfn) agenda-files)))))
17232 (t (lambda (b) (with-current-buffer b
17233 (or (derived-mode-p 'org-mode)
17234 (string-match "\*Org .*Export"
17235 (buffer-name b)))))))))
17236 (delq nil
17237 (mapcar
17238 (lambda(b)
17239 (if (and (funcall filter b)
17240 (or (not exclude-tmp)
17241 (not (string-match "tmp" (buffer-name b)))))
17243 nil))
17244 (buffer-list)))))
17246 (defun org-agenda-files (&optional unrestricted archives)
17247 "Get the list of agenda files.
17248 Optional UNRESTRICTED means return the full list even if a restriction
17249 is currently in place.
17250 When ARCHIVES is t, include all archive files that are really being
17251 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17252 `org-agenda-archives-mode' is t."
17253 (let ((files
17254 (cond
17255 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17256 ((stringp org-agenda-files) (org-read-agenda-file-list))
17257 ((listp org-agenda-files) org-agenda-files)
17258 (t (error "Invalid value of `org-agenda-files'")))))
17259 (setq files (apply 'append
17260 (mapcar (lambda (f)
17261 (if (file-directory-p f)
17262 (directory-files
17263 f t org-agenda-file-regexp)
17264 (list f)))
17265 files)))
17266 (when org-agenda-skip-unavailable-files
17267 (setq files (delq nil
17268 (mapcar (function
17269 (lambda (file)
17270 (and (file-readable-p file) file)))
17271 files))))
17272 (when (or (eq archives t)
17273 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17274 (setq files (org-add-archive-files files)))
17275 files))
17277 (defun org-agenda-file-p (&optional file)
17278 "Return non-nil, if FILE is an agenda file.
17279 If FILE is omitted, use the file associated with the current
17280 buffer."
17281 (member (or file (buffer-file-name))
17282 (org-agenda-files t)))
17284 (defun org-edit-agenda-file-list ()
17285 "Edit the list of agenda files.
17286 Depending on setup, this either uses customize to edit the variable
17287 `org-agenda-files', or it visits the file that is holding the list. In the
17288 latter case, the buffer is set up in a way that saving it automatically kills
17289 the buffer and restores the previous window configuration."
17290 (interactive)
17291 (if (stringp org-agenda-files)
17292 (let ((cw (current-window-configuration)))
17293 (find-file org-agenda-files)
17294 (org-set-local 'org-window-configuration cw)
17295 (org-add-hook 'after-save-hook
17296 (lambda ()
17297 (set-window-configuration
17298 (prog1 org-window-configuration
17299 (kill-buffer (current-buffer))))
17300 (org-install-agenda-files-menu)
17301 (message "New agenda file list installed"))
17302 nil 'local)
17303 (message "%s" (substitute-command-keys
17304 "Edit list and finish with \\[save-buffer]")))
17305 (customize-variable 'org-agenda-files)))
17307 (defun org-store-new-agenda-file-list (list)
17308 "Set new value for the agenda file list and save it correctly."
17309 (if (stringp org-agenda-files)
17310 (let ((fe (org-read-agenda-file-list t)) b u)
17311 (while (setq b (find-buffer-visiting org-agenda-files))
17312 (kill-buffer b))
17313 (with-temp-file org-agenda-files
17314 (insert
17315 (mapconcat
17316 (lambda (f) ;; Keep un-expanded entries.
17317 (if (setq u (assoc f fe))
17318 (cdr u)
17320 list "\n")
17321 "\n")))
17322 (let ((org-mode-hook nil) (org-inhibit-startup t)
17323 (org-insert-mode-line-in-empty-file nil))
17324 (setq org-agenda-files list)
17325 (customize-save-variable 'org-agenda-files org-agenda-files))))
17327 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17328 "Read the list of agenda files from a file.
17329 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17330 filenames, used by `org-store-new-agenda-file-list' to write back
17331 un-expanded file names."
17332 (when (file-directory-p org-agenda-files)
17333 (error "`org-agenda-files' cannot be a single directory"))
17334 (when (stringp org-agenda-files)
17335 (with-temp-buffer
17336 (insert-file-contents org-agenda-files)
17337 (mapcar
17338 (lambda (f)
17339 (let ((e (expand-file-name (substitute-in-file-name f)
17340 org-directory)))
17341 (if pair-with-expansion
17342 (cons e f)
17343 e)))
17344 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17346 ;;;###autoload
17347 (defun org-cycle-agenda-files ()
17348 "Cycle through the files in `org-agenda-files'.
17349 If the current buffer visits an agenda file, find the next one in the list.
17350 If the current buffer does not, find the first agenda file."
17351 (interactive)
17352 (let* ((fs (org-agenda-files t))
17353 (files (append fs (list (car fs))))
17354 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17355 file)
17356 (unless files (error "No agenda files"))
17357 (catch 'exit
17358 (while (setq file (pop files))
17359 (if (equal (file-truename file) tcf)
17360 (when (car files)
17361 (find-file (car files))
17362 (throw 'exit t))))
17363 (find-file (car fs)))
17364 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17366 (defun org-agenda-file-to-front (&optional to-end)
17367 "Move/add the current file to the top of the agenda file list.
17368 If the file is not present in the list, it is added to the front. If it is
17369 present, it is moved there. With optional argument TO-END, add/move to the
17370 end of the list."
17371 (interactive "P")
17372 (let ((org-agenda-skip-unavailable-files nil)
17373 (file-alist (mapcar (lambda (x)
17374 (cons (file-truename x) x))
17375 (org-agenda-files t)))
17376 (ctf (file-truename
17377 (or buffer-file-name
17378 (error "Please save the current buffer to a file"))))
17379 x had)
17380 (setq x (assoc ctf file-alist) had x)
17382 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17383 (if to-end
17384 (setq file-alist (append (delq x file-alist) (list x)))
17385 (setq file-alist (cons x (delq x file-alist))))
17386 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17387 (org-install-agenda-files-menu)
17388 (message "File %s to %s of agenda file list"
17389 (if had "moved" "added") (if to-end "end" "front"))))
17391 (defun org-remove-file (&optional file)
17392 "Remove current file from the list of files in variable `org-agenda-files'.
17393 These are the files which are being checked for agenda entries.
17394 Optional argument FILE means use this file instead of the current."
17395 (interactive)
17396 (let* ((org-agenda-skip-unavailable-files nil)
17397 (file (or file buffer-file-name
17398 (error "Current buffer does not visit a file")))
17399 (true-file (file-truename file))
17400 (afile (abbreviate-file-name file))
17401 (files (delq nil (mapcar
17402 (lambda (x)
17403 (if (equal true-file
17404 (file-truename x))
17405 nil x))
17406 (org-agenda-files t)))))
17407 (if (not (= (length files) (length (org-agenda-files t))))
17408 (progn
17409 (org-store-new-agenda-file-list files)
17410 (org-install-agenda-files-menu)
17411 (message "Removed file: %s" afile))
17412 (message "File was not in list: %s (not removed)" afile))))
17414 (defun org-file-menu-entry (file)
17415 (vector file (list 'find-file file) t))
17417 (defun org-check-agenda-file (file)
17418 "Make sure FILE exists. If not, ask user what to do."
17419 (when (not (file-exists-p file))
17420 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17421 (abbreviate-file-name file))
17422 (let ((r (downcase (read-char-exclusive))))
17423 (cond
17424 ((equal r ?r)
17425 (org-remove-file file)
17426 (throw 'nextfile t))
17427 (t (error "Abort"))))))
17429 (defun org-get-agenda-file-buffer (file)
17430 "Get a buffer visiting FILE. If the buffer needs to be created, add
17431 it to the list of buffers which might be released later."
17432 (let ((buf (org-find-base-buffer-visiting file)))
17433 (if buf
17434 buf ; just return it
17435 ;; Make a new buffer and remember it
17436 (setq buf (find-file-noselect file))
17437 (if buf (push buf org-agenda-new-buffers))
17438 buf)))
17440 (defun org-release-buffers (blist)
17441 "Release all buffers in list, asking the user for confirmation when needed.
17442 When a buffer is unmodified, it is just killed. When modified, it is saved
17443 \(if the user agrees) and then killed."
17444 (let (buf file)
17445 (while (setq buf (pop blist))
17446 (setq file (buffer-file-name buf))
17447 (when (and (buffer-modified-p buf)
17448 file
17449 (y-or-n-p (format "Save file %s? " file)))
17450 (with-current-buffer buf (save-buffer)))
17451 (kill-buffer buf))))
17453 (defun org-agenda-prepare-buffers (files)
17454 "Create buffers for all agenda files, protect archived trees and comments."
17455 (interactive)
17456 (let ((pa '(:org-archived t))
17457 (pc '(:org-comment t))
17458 (pall '(:org-archived t :org-comment t))
17459 (inhibit-read-only t)
17460 (org-inhibit-startup org-agenda-inhibit-startup)
17461 (rea (concat ":" org-archive-tag ":"))
17462 bmp file re)
17463 (save-excursion
17464 (save-restriction
17465 (while (setq file (pop files))
17466 (catch 'nextfile
17467 (if (bufferp file)
17468 (set-buffer file)
17469 (org-check-agenda-file file)
17470 (set-buffer (org-get-agenda-file-buffer file)))
17471 (widen)
17472 (setq bmp (buffer-modified-p))
17473 (org-refresh-category-properties)
17474 (org-refresh-properties org-effort-property 'org-effort)
17475 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17476 (setq org-todo-keywords-for-agenda
17477 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17478 (setq org-done-keywords-for-agenda
17479 (append org-done-keywords-for-agenda org-done-keywords))
17480 (setq org-todo-keyword-alist-for-agenda
17481 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17482 (setq org-drawers-for-agenda
17483 (append org-drawers-for-agenda org-drawers))
17484 (setq org-tag-alist-for-agenda
17485 (append org-tag-alist-for-agenda org-tag-alist))
17487 (save-excursion
17488 (remove-text-properties (point-min) (point-max) pall)
17489 (when org-agenda-skip-archived-trees
17490 (goto-char (point-min))
17491 (while (re-search-forward rea nil t)
17492 (if (org-at-heading-p t)
17493 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17494 (goto-char (point-min))
17495 (setq re (format org-heading-keyword-regexp-format
17496 org-comment-string))
17497 (while (re-search-forward re nil t)
17498 (add-text-properties
17499 (match-beginning 0) (org-end-of-subtree t) pc)))
17500 (set-buffer-modified-p bmp)))))
17501 (setq org-todo-keywords-for-agenda
17502 (org-uniquify org-todo-keywords-for-agenda))
17503 (setq org-todo-keyword-alist-for-agenda
17504 (org-uniquify org-todo-keyword-alist-for-agenda)
17505 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17509 ;;;; CDLaTeX minor mode
17511 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17512 "Keymap for the minor `org-cdlatex-mode'.")
17514 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17515 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17516 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17517 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17518 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17520 (defvar org-cdlatex-texmathp-advice-is-done nil
17521 "Flag remembering if we have applied the advice to texmathp already.")
17523 (define-minor-mode org-cdlatex-mode
17524 "Toggle the minor `org-cdlatex-mode'.
17525 This mode supports entering LaTeX environment and math in LaTeX fragments
17526 in Org-mode.
17527 \\{org-cdlatex-mode-map}"
17528 nil " OCDL" nil
17529 (when org-cdlatex-mode
17530 (require 'cdlatex)
17531 (run-hooks 'cdlatex-mode-hook)
17532 (cdlatex-compute-tables))
17533 (unless org-cdlatex-texmathp-advice-is-done
17534 (setq org-cdlatex-texmathp-advice-is-done t)
17535 (defadvice texmathp (around org-math-always-on activate)
17536 "Always return t in org-mode buffers.
17537 This is because we want to insert math symbols without dollars even outside
17538 the LaTeX math segments. If Orgmode thinks that point is actually inside
17539 an embedded LaTeX fragment, let texmathp do its job.
17540 \\[org-cdlatex-mode-map]"
17541 (interactive)
17542 (let (p)
17543 (cond
17544 ((not (derived-mode-p 'org-mode)) ad-do-it)
17545 ((eq this-command 'cdlatex-math-symbol)
17546 (setq ad-return-value t
17547 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17549 (let ((p (org-inside-LaTeX-fragment-p)))
17550 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17551 (setq ad-return-value t
17552 texmathp-why '("Org-mode embedded math" . 0))
17553 (if p ad-do-it)))))))))
17555 (defun turn-on-org-cdlatex ()
17556 "Unconditionally turn on `org-cdlatex-mode'."
17557 (org-cdlatex-mode 1))
17559 (defun org-try-cdlatex-tab ()
17560 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17561 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17562 - inside a LaTeX fragment, or
17563 - after the first word in a line, where an abbreviation expansion could
17564 insert a LaTeX environment."
17565 (when org-cdlatex-mode
17566 (cond
17567 ;; Before any word on the line: No expansion possible.
17568 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17569 ;; Just after first word on the line: Expand it. Make sure it
17570 ;; cannot happen on headlines, though.
17571 ((save-excursion
17572 (skip-chars-backward "a-zA-Z0-9*")
17573 (skip-chars-backward " \t")
17574 (and (bolp) (not (org-at-heading-p))))
17575 (cdlatex-tab) t)
17576 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17578 (defun org-cdlatex-underscore-caret (&optional arg)
17579 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17580 Revert to the normal definition outside of these fragments."
17581 (interactive "P")
17582 (if (org-inside-LaTeX-fragment-p)
17583 (call-interactively 'cdlatex-sub-superscript)
17584 (let (org-cdlatex-mode)
17585 (call-interactively (key-binding (vector last-input-event))))))
17587 (defun org-cdlatex-math-modify (&optional arg)
17588 "Execute `cdlatex-math-modify' in LaTeX fragments.
17589 Revert to the normal definition outside of these fragments."
17590 (interactive "P")
17591 (if (org-inside-LaTeX-fragment-p)
17592 (call-interactively 'cdlatex-math-modify)
17593 (let (org-cdlatex-mode)
17594 (call-interactively (key-binding (vector last-input-event))))))
17598 ;;;; LaTeX fragments
17600 (defvar org-latex-regexps
17601 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17602 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17603 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17604 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17605 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17606 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17607 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17608 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17609 "Regular expressions for matching embedded LaTeX.")
17611 (defun org-inside-LaTeX-fragment-p ()
17612 "Test if point is inside a LaTeX fragment.
17613 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17614 sequence appearing also before point.
17615 Even though the matchers for math are configurable, this function assumes
17616 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17617 delimiters are skipped when they have been removed by customization.
17618 The return value is nil, or a cons cell with the delimiter and the
17619 position of this delimiter.
17621 This function does a reasonably good job, but can locally be fooled by
17622 for example currency specifications. For example it will assume being in
17623 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17624 fragments that are properly closed, but during editing, we have to live
17625 with the uncertainty caused by missing closing delimiters. This function
17626 looks only before point, not after."
17627 (catch 'exit
17628 (let ((pos (point))
17629 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17630 (lim (progn
17631 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17632 (point)))
17633 dd-on str (start 0) m re)
17634 (goto-char pos)
17635 (when dodollar
17636 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17637 re (nth 1 (assoc "$" org-latex-regexps)))
17638 (while (string-match re str start)
17639 (cond
17640 ((= (match-end 0) (length str))
17641 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17642 ((= (match-end 0) (- (length str) 5))
17643 (throw 'exit nil))
17644 (t (setq start (match-end 0))))))
17645 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17646 (goto-char pos)
17647 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17648 (and (match-beginning 2) (throw 'exit nil))
17649 ;; count $$
17650 (while (re-search-backward "\\$\\$" lim t)
17651 (setq dd-on (not dd-on)))
17652 (goto-char pos)
17653 (if dd-on (cons "$$" m))))))
17655 (defun org-inside-latex-macro-p ()
17656 "Is point inside a LaTeX macro or its arguments?"
17657 (save-match-data
17658 (org-in-regexp
17659 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17661 (defvar org-latex-fragment-image-overlays nil
17662 "List of overlays carrying the images of latex fragments.")
17663 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17665 (defun org-remove-latex-fragment-image-overlays ()
17666 "Remove all overlays with LaTeX fragment images in current buffer."
17667 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17668 (setq org-latex-fragment-image-overlays nil))
17670 (defun org-preview-latex-fragment (&optional subtree)
17671 "Preview the LaTeX fragment at point, or all locally or globally.
17672 If the cursor is in a LaTeX fragment, create the image and overlay
17673 it over the source code. If there is no fragment at point, display
17674 all fragments in the current text, from one headline to the next. With
17675 prefix SUBTREE, display all fragments in the current subtree. With a
17676 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17677 the cursor is before the first headline,
17678 display all fragments in the buffer.
17679 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17680 (interactive "P")
17681 (unless buffer-file-name
17682 (error "Can't preview LaTeX fragment in a non-file buffer"))
17683 (org-remove-latex-fragment-image-overlays)
17684 (save-excursion
17685 (save-restriction
17686 (let (beg end at msg)
17687 (cond
17688 ((or (equal subtree '(16))
17689 (not (save-excursion
17690 (re-search-backward org-outline-regexp-bol nil t))))
17691 (setq beg (point-min) end (point-max)
17692 msg "Creating images for buffer...%s"))
17693 ((equal subtree '(4))
17694 (org-back-to-heading)
17695 (setq beg (point) end (org-end-of-subtree t)
17696 msg "Creating images for subtree...%s"))
17698 (if (setq at (org-inside-LaTeX-fragment-p))
17699 (goto-char (max (point-min) (- (cdr at) 2)))
17700 (org-back-to-heading))
17701 (setq beg (point) end (progn (outline-next-heading) (point))
17702 msg (if at "Creating image...%s"
17703 "Creating images for entry...%s"))))
17704 (message msg "")
17705 (narrow-to-region beg end)
17706 (goto-char beg)
17707 (org-format-latex
17708 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17709 (file-name-nondirectory
17710 buffer-file-name)))
17711 default-directory 'overlays msg at 'forbuffer
17712 org-latex-create-formula-image-program)
17713 (message msg "done. Use `C-c C-c' to remove images.")))))
17715 (defun org-format-latex (prefix &optional dir overlays msg at
17716 forbuffer processing-type)
17717 "Replace LaTeX fragments with links to an image, and produce images.
17718 Some of the options can be changed using the variable
17719 `org-format-latex-options'."
17720 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17721 (let* ((prefixnodir (file-name-nondirectory prefix))
17722 (absprefix (expand-file-name prefix dir))
17723 (todir (file-name-directory absprefix))
17724 (opt org-format-latex-options)
17725 (optnew org-format-latex-options)
17726 (matchers (plist-get opt :matchers))
17727 (re-list org-latex-regexps)
17728 (cnt 0) txt hash link beg end re e checkdir
17729 string
17730 m n block-type block linkfile movefile ov)
17731 ;; Check the different regular expressions
17732 (while (setq e (pop re-list))
17733 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17734 block (if block-type "\n\n" ""))
17735 (when (member m matchers)
17736 (goto-char (point-min))
17737 (while (re-search-forward re nil t)
17738 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17739 (or (not overlays)
17740 (not (eq (get-char-property (match-beginning n)
17741 'org-overlay-type)
17742 'org-latex-overlay))))
17743 (cond
17744 ((eq processing-type 'verbatim))
17745 ((eq processing-type 'mathjax)
17746 ;; Prepare for MathJax processing.
17747 (setq string (match-string n))
17748 (when (member m '("$" "$1"))
17749 (save-excursion
17750 (delete-region (match-beginning n) (match-end n))
17751 (goto-char (match-beginning n))
17752 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17753 ((or (eq processing-type 'dvipng)
17754 (eq processing-type 'imagemagick))
17755 ;; Process to an image.
17756 (setq txt (match-string n)
17757 beg (match-beginning n) end (match-end n)
17758 cnt (1+ cnt))
17759 (let ((face (face-at-point))
17760 (fg (plist-get opt :foreground))
17761 (bg (plist-get opt :background))
17762 ;; Ensure full list is printed.
17763 print-length print-level)
17764 (when forbuffer
17765 ;; Get the colors from the face at point.
17766 (goto-char beg)
17767 (when (eq fg 'auto)
17768 (setq fg (face-attribute face :foreground nil 'default)))
17769 (when (eq bg 'auto)
17770 (setq bg (face-attribute face :background nil 'default)))
17771 (setq optnew (copy-sequence opt))
17772 (plist-put optnew :foreground fg)
17773 (plist-put optnew :background bg))
17774 (setq hash (sha1 (prin1-to-string
17775 (list org-format-latex-header
17776 org-latex-default-packages-alist
17777 org-latex-packages-alist
17778 org-format-latex-options
17779 forbuffer txt fg bg)))
17780 linkfile (format "%s_%s.png" prefix hash)
17781 movefile (format "%s_%s.png" absprefix hash)))
17782 (setq link (concat block "[[file:" linkfile "]]" block))
17783 (if msg (message msg cnt))
17784 (goto-char beg)
17785 (unless checkdir ; Ensure the directory exists.
17786 (setq checkdir t)
17787 (or (file-directory-p todir) (make-directory todir t)))
17788 (unless (file-exists-p movefile)
17789 (org-create-formula-image
17790 txt movefile optnew forbuffer processing-type))
17791 (if overlays
17792 (progn
17793 (mapc (lambda (o)
17794 (if (eq (overlay-get o 'org-overlay-type)
17795 'org-latex-overlay)
17796 (delete-overlay o)))
17797 (overlays-in beg end))
17798 (setq ov (make-overlay beg end))
17799 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17800 (if (featurep 'xemacs)
17801 (progn
17802 (overlay-put ov 'invisible t)
17803 (overlay-put
17804 ov 'end-glyph
17805 (make-glyph (vector 'png :file movefile))))
17806 (overlay-put
17807 ov 'display
17808 (list 'image :type 'png :file movefile :ascent 'center)))
17809 (push ov org-latex-fragment-image-overlays)
17810 (goto-char end))
17811 (delete-region beg end)
17812 (insert (org-add-props link
17813 (list 'org-latex-src
17814 (replace-regexp-in-string
17815 "\"" "" txt)
17816 'org-latex-src-embed-type
17817 (if block-type 'paragraph 'character))))))
17818 ((eq processing-type 'mathml)
17819 ;; Process to MathML
17820 (unless (save-match-data (org-format-latex-mathml-available-p))
17821 (error "LaTeX to MathML converter not configured"))
17822 (setq txt (match-string n)
17823 beg (match-beginning n) end (match-end n)
17824 cnt (1+ cnt))
17825 (if msg (message msg cnt))
17826 (goto-char beg)
17827 (delete-region beg end)
17828 (insert (org-format-latex-as-mathml
17829 txt block-type prefix dir)))
17831 (error "Unknown conversion type %s for latex fragments"
17832 processing-type)))))))))
17834 (defun org-create-math-formula (latex-frag &optional mathml-file)
17835 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17836 Use `org-latex-to-mathml-convert-command'. If the conversion is
17837 sucessful, return the portion between \"<math...> </math>\"
17838 elements otherwise return nil. When MATHML-FILE is specified,
17839 write the results in to that file. When invoked as an
17840 interactive command, prompt for LATEX-FRAG, with initial value
17841 set to the current active region and echo the results for user
17842 inspection."
17843 (interactive (list (let ((frag (when (org-region-active-p)
17844 (buffer-substring-no-properties
17845 (region-beginning) (region-end)))))
17846 (read-string "LaTeX Fragment: " frag nil frag))))
17847 (unless latex-frag (error "Invalid latex-frag"))
17848 (let* ((tmp-in-file (file-relative-name
17849 (make-temp-name (expand-file-name "ltxmathml-in"))))
17850 (ignore (write-region latex-frag nil tmp-in-file))
17851 (tmp-out-file (file-relative-name
17852 (make-temp-name (expand-file-name "ltxmathml-out"))))
17853 (cmd (format-spec
17854 org-latex-to-mathml-convert-command
17855 `((?j . ,(shell-quote-argument
17856 (expand-file-name org-latex-to-mathml-jar-file)))
17857 (?I . ,(shell-quote-argument tmp-in-file))
17858 (?o . ,(shell-quote-argument tmp-out-file)))))
17859 mathml shell-command-output)
17860 (when (org-called-interactively-p 'any)
17861 (unless (org-format-latex-mathml-available-p)
17862 (error "LaTeX to MathML converter not configured")))
17863 (message "Running %s" cmd)
17864 (setq shell-command-output (shell-command-to-string cmd))
17865 (setq mathml
17866 (when (file-readable-p tmp-out-file)
17867 (with-current-buffer (find-file-noselect tmp-out-file t)
17868 (goto-char (point-min))
17869 (when (re-search-forward
17870 (concat
17871 (regexp-quote
17872 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17873 "\\(.\\|\n\\)*"
17874 (regexp-quote "</math>")) nil t)
17875 (prog1 (match-string 0) (kill-buffer))))))
17876 (cond
17877 (mathml
17878 (setq mathml
17879 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17880 (when mathml-file
17881 (write-region mathml nil mathml-file))
17882 (when (org-called-interactively-p 'any)
17883 (message mathml)))
17884 ((message "LaTeX to MathML conversion failed")
17885 (message shell-command-output)))
17886 (delete-file tmp-in-file)
17887 (when (file-exists-p tmp-out-file)
17888 (delete-file tmp-out-file))
17889 mathml))
17891 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17892 prefix &optional dir)
17893 "Use `org-create-math-formula' but check local cache first."
17894 (let* ((absprefix (expand-file-name prefix dir))
17895 (print-length nil) (print-level nil)
17896 (formula-id (concat
17897 "formula-"
17898 (sha1
17899 (prin1-to-string
17900 (list latex-frag
17901 org-latex-to-mathml-convert-command)))))
17902 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17903 (formula-cache-dir (file-name-directory formula-cache)))
17905 (unless (file-directory-p formula-cache-dir)
17906 (make-directory formula-cache-dir t))
17908 (unless (file-exists-p formula-cache)
17909 (org-create-math-formula latex-frag formula-cache))
17911 (if (file-exists-p formula-cache)
17912 ;; Successful conversion. Return the link to MathML file.
17913 (org-add-props
17914 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17915 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17916 'org-latex-src-embed-type (if latex-frag-type
17917 'paragraph 'character)))
17918 ;; Failed conversion. Return the LaTeX fragment verbatim
17919 latex-frag)))
17921 (defun org-create-formula-image (string tofile options buffer &optional type)
17922 "Create an image from LaTeX source using dvipng or convert.
17923 This function calls either `org-create-formula-image-with-dvipng'
17924 or `org-create-formula-image-with-imagemagick' depending on the
17925 value of `org-latex-create-formula-image-program' or on the value
17926 of the optional TYPE variable.
17928 Note: ultimately these two function should be combined as they
17929 share a good deal of logic."
17930 (org-check-external-command
17931 "latex" "needed to convert LaTeX fragments to images")
17932 (funcall
17933 (case (or type org-latex-create-formula-image-program)
17934 ('dvipng
17935 (org-check-external-command
17936 "dvipng" "needed to convert LaTeX fragments to images")
17937 #'org-create-formula-image-with-dvipng)
17938 ('imagemagick
17939 (org-check-external-command
17940 "convert" "you need to install imagemagick")
17941 #'org-create-formula-image-with-imagemagick)
17942 (t (error
17943 "invalid value of `org-latex-create-formula-image-program'")))
17944 string tofile options buffer))
17946 ;; This function borrows from Ganesh Swami's latex2png.el
17947 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17948 "This calls dvipng."
17949 (let* ((tmpdir (if (featurep 'xemacs)
17950 (temp-directory)
17951 temporary-file-directory))
17952 (texfilebase (make-temp-name
17953 (expand-file-name "orgtex" tmpdir)))
17954 (texfile (concat texfilebase ".tex"))
17955 (dvifile (concat texfilebase ".dvi"))
17956 (pngfile (concat texfilebase ".png"))
17957 (fnh (if (featurep 'xemacs)
17958 (font-height (face-font 'default))
17959 (face-attribute 'default :height nil)))
17960 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17961 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17962 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17963 "Black"))
17964 (bg (or (plist-get options (if buffer :background :html-background))
17965 "Transparent")))
17966 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17967 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17968 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17969 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17970 (with-temp-file texfile
17971 (require 'ox-latex)
17972 (insert (org-latex-guess-inputenc
17973 (org-splice-latex-header
17974 org-format-latex-header
17975 org-latex-default-packages-alist
17976 org-latex-packages-alist t)))
17977 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17978 (let ((dir default-directory))
17979 (condition-case nil
17980 (progn
17981 (cd tmpdir)
17982 (call-process "latex" nil nil nil texfile))
17983 (error nil))
17984 (cd dir))
17985 (if (not (file-exists-p dvifile))
17986 (progn (message "Failed to create dvi file from %s" texfile) nil)
17987 (condition-case nil
17988 (if (featurep 'xemacs)
17989 (call-process "dvipng" nil nil nil
17990 "-fg" fg "-bg" bg
17991 "-T" "tight"
17992 "-o" pngfile
17993 dvifile)
17994 (call-process "dvipng" nil nil nil
17995 "-fg" fg "-bg" bg
17996 "-D" dpi
17997 ;;"-x" scale "-y" scale
17998 "-T" "tight"
17999 "-o" pngfile
18000 dvifile))
18001 (error nil))
18002 (if (not (file-exists-p pngfile))
18003 (if org-format-latex-signal-error
18004 (error "Failed to create png file from %s" texfile)
18005 (message "Failed to create png file from %s" texfile)
18006 nil)
18007 ;; Use the requested file name and clean up
18008 (copy-file pngfile tofile 'replace)
18009 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18010 (if (file-exists-p (concat texfilebase e))
18011 (delete-file (concat texfilebase e))))
18012 pngfile))))
18014 (defvar org-latex-pdf-process) ; From ox-latex.el
18015 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18016 "This calls convert, which is included into imagemagick."
18017 (let* ((tmpdir (if (featurep 'xemacs)
18018 (temp-directory)
18019 temporary-file-directory))
18020 (texfilebase (make-temp-name
18021 (expand-file-name "orgtex" tmpdir)))
18022 (texfile (concat texfilebase ".tex"))
18023 (pdffile (concat texfilebase ".pdf"))
18024 (pngfile (concat texfilebase ".png"))
18025 (fnh (if (featurep 'xemacs)
18026 (font-height (face-font 'default))
18027 (face-attribute 'default :height nil)))
18028 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18029 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18030 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18031 "black"))
18032 (bg (or (plist-get options (if buffer :background :html-background))
18033 "white")))
18034 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18035 (setq fg (org-latex-color-format fg)))
18036 (if (eq bg 'default) (setq bg (org-latex-color :background))
18037 (setq bg (org-latex-color-format
18038 (if (string= bg "Transparent") "white" bg))))
18039 (with-temp-file texfile
18040 (require 'ox-latex)
18041 (insert (org-latex-guess-inputenc
18042 (org-splice-latex-header
18043 org-format-latex-header
18044 org-latex-default-packages-alist
18045 org-latex-packages-alist t)))
18046 (insert "\n\\begin{document}\n"
18047 "\\definecolor{fg}{rgb}{" fg "}\n"
18048 "\\definecolor{bg}{rgb}{" bg "}\n"
18049 "\n\\pagecolor{bg}\n"
18050 "\n{\\color{fg}\n"
18051 string
18052 "\n}\n"
18053 "\n\\end{document}\n"))
18054 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18055 (condition-case nil
18056 (progn
18057 (cd tmpdir)
18058 (setq cmds org-latex-pdf-process)
18059 (while cmds
18060 (setq latex-frags-cmds (pop cmds))
18061 (if (listp latex-frags-cmds)
18062 (setq cmds nil)
18063 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18064 (while latex-frags-cmds
18065 (setq cmd (pop latex-frags-cmds))
18066 (while (string-match "%b" cmd)
18067 (setq cmd (replace-match
18068 (save-match-data
18069 (shell-quote-argument texfile))
18070 t t cmd)))
18071 (while (string-match "%f" cmd)
18072 (setq cmd (replace-match
18073 (save-match-data
18074 (shell-quote-argument
18075 (file-name-nondirectory texfile)))
18076 t t cmd)))
18077 (while (string-match "%o" cmd)
18078 (setq cmd (replace-match
18079 (save-match-data
18080 (shell-quote-argument
18081 (file-name-directory texfile)))
18082 t t cmd)))
18083 (setq cmd (split-string cmd))
18084 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18085 (error nil))
18086 (cd dir))
18087 (if (not (file-exists-p pdffile))
18088 (progn (message "Failed to create pdf file from %s" texfile) nil)
18089 (condition-case nil
18090 (if (featurep 'xemacs)
18091 (call-process "convert" nil nil nil
18092 "-density" "96"
18093 "-trim"
18094 "-antialias"
18095 pdffile
18096 "-quality" "100"
18097 ;; "-sharpen" "0x1.0"
18098 pngfile)
18099 (call-process "convert" nil nil nil
18100 "-density" dpi
18101 "-trim"
18102 "-antialias"
18103 pdffile
18104 "-quality" "100"
18105 ;; "-sharpen" "0x1.0"
18106 pngfile))
18107 (error nil))
18108 (if (not (file-exists-p pngfile))
18109 (if org-format-latex-signal-error
18110 (error "Failed to create png file from %s" texfile)
18111 (message "Failed to create png file from %s" texfile)
18112 nil)
18113 ;; Use the requested file name and clean up
18114 (copy-file pngfile tofile 'replace)
18115 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18116 (if (file-exists-p (concat texfilebase e))
18117 (delete-file (concat texfilebase e))))
18118 pngfile))))
18120 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18121 "Fill a LaTeX header template TPL.
18122 In the template, the following place holders will be recognized:
18124 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18125 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18126 [PACKAGES] \\usepackage statements for PKG
18127 [NO-PACKAGES] do not include PKG
18128 [EXTRA] the string EXTRA
18129 [NO-EXTRA] do not include EXTRA
18131 For backward compatibility, if both the positive and the negative place
18132 holder is missing, the positive one (without the \"NO-\") will be
18133 assumed to be present at the end of the template.
18134 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18135 EXTRA is a string.
18136 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18137 (let (rpl (end ""))
18138 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18139 (setq rpl (if (or (match-end 1) (not def-pkg))
18140 "" (org-latex-packages-to-string def-pkg snippets-p t))
18141 tpl (replace-match rpl t t tpl))
18142 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18144 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18145 (setq rpl (if (or (match-end 1) (not pkg))
18146 "" (org-latex-packages-to-string pkg snippets-p t))
18147 tpl (replace-match rpl t t tpl))
18148 (if pkg (setq end
18149 (concat end "\n"
18150 (org-latex-packages-to-string pkg snippets-p)))))
18152 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18153 (setq rpl (if (or (match-end 1) (not extra))
18154 "" (concat extra "\n"))
18155 tpl (replace-match rpl t t tpl))
18156 (if (and extra (string-match "\\S-" extra))
18157 (setq end (concat end "\n" extra))))
18159 (if (string-match "\\S-" end)
18160 (concat tpl "\n" end)
18161 tpl)))
18163 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18164 "Turn an alist of packages into a string with the \\usepackage macros."
18165 (setq pkg (mapconcat (lambda(p)
18166 (cond
18167 ((stringp p) p)
18168 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18169 (format "%% Package %s omitted" (cadr p)))
18170 ((equal "" (car p))
18171 (format "\\usepackage{%s}" (cadr p)))
18173 (format "\\usepackage[%s]{%s}"
18174 (car p) (cadr p)))))
18176 "\n"))
18177 (if newline (concat pkg "\n") pkg))
18179 (defun org-dvipng-color (attr)
18180 "Return a RGB color specification for dvipng."
18181 (apply 'format "rgb %s %s %s"
18182 (mapcar 'org-normalize-color
18183 (if (featurep 'xemacs)
18184 (color-rgb-components
18185 (face-property 'default
18186 (cond ((eq attr :foreground) 'foreground)
18187 ((eq attr :background) 'background))))
18188 (color-values (face-attribute 'default attr nil))))))
18190 (defun org-dvipng-color-format (color-name)
18191 "Convert COLOR-NAME to a RGB color value for dvipng."
18192 (apply 'format "rgb %s %s %s"
18193 (mapcar 'org-normalize-color
18194 (color-values color-name))))
18196 (defun org-latex-color (attr)
18197 "Return a RGB color for the LaTeX color package."
18198 (apply 'format "%s,%s,%s"
18199 (mapcar 'org-normalize-color
18200 (if (featurep 'xemacs)
18201 (color-rgb-components
18202 (face-property 'default
18203 (cond ((eq attr :foreground) 'foreground)
18204 ((eq attr :background) 'background))))
18205 (color-values (face-attribute 'default attr nil))))))
18207 (defun org-latex-color-format (color-name)
18208 "Convert COLOR-NAME to a RGB color value."
18209 (apply 'format "%s,%s,%s"
18210 (mapcar 'org-normalize-color
18211 (color-values color-name))))
18213 (defun org-normalize-color (value)
18214 "Return string to be used as color value for an RGB component."
18215 (format "%g" (/ value 65535.0)))
18219 ;; Image display
18221 (defvar org-inline-image-overlays nil)
18222 (make-variable-buffer-local 'org-inline-image-overlays)
18224 (defun org-toggle-inline-images (&optional include-linked)
18225 "Toggle the display of inline images.
18226 INCLUDE-LINKED is passed to `org-display-inline-images'."
18227 (interactive "P")
18228 (if org-inline-image-overlays
18229 (progn
18230 (org-remove-inline-images)
18231 (message "Inline image display turned off"))
18232 (org-display-inline-images include-linked)
18233 (if (and (org-called-interactively-p)
18234 org-inline-image-overlays)
18235 (message "%d images displayed inline"
18236 (length org-inline-image-overlays))
18237 (message "No images to display inline"))))
18239 (defun org-redisplay-inline-images ()
18240 "Refresh the display of inline images."
18241 (interactive)
18242 (if (not org-inline-image-overlays)
18243 (org-toggle-inline-images)
18244 (org-toggle-inline-images)
18245 (org-toggle-inline-images)))
18247 (defun org-display-inline-images (&optional include-linked refresh beg end)
18248 "Display inline images.
18249 Normally only links without a description part are inlined, because this
18250 is how it will work for export. When INCLUDE-LINKED is set, also links
18251 with a description part will be inlined. This can be nice for a quick
18252 look at those images, but it does not reflect what exported files will look
18253 like.
18254 When REFRESH is set, refresh existing images between BEG and END.
18255 This will create new image displays only if necessary.
18256 BEG and END default to the buffer boundaries."
18257 (interactive "P")
18258 (unless refresh
18259 (org-remove-inline-images)
18260 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18261 (save-excursion
18262 (save-restriction
18263 (widen)
18264 (setq beg (or beg (point-min)) end (or end (point-max)))
18265 (goto-char beg)
18266 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18267 (substring (org-image-file-name-regexp) 0 -2)
18268 "\\)\\]" (if include-linked "" "\\]")))
18269 old file ov img type attrwidth width)
18270 (while (re-search-forward re end t)
18271 (setq old (get-char-property-and-overlay (match-beginning 1)
18272 'org-image-overlay)
18273 file (expand-file-name
18274 (concat (or (match-string 3) "") (match-string 4))))
18275 (when (image-type-available-p 'imagemagick)
18276 (setq attrwidth (if (or (listp org-image-actual-width)
18277 (null org-image-actual-width))
18278 (save-excursion
18279 (save-match-data
18280 (when (re-search-backward
18281 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18282 (save-excursion
18283 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18284 (string-to-number (match-string 1))))))
18285 width (cond ((eq org-image-actual-width t) nil)
18286 ((null org-image-actual-width) attrwidth)
18287 ((numberp org-image-actual-width)
18288 org-image-actual-width)
18289 ((listp org-image-actual-width)
18290 (or attrwidth (car org-image-actual-width))))
18291 type (if width 'imagemagick)))
18292 (when (file-exists-p file)
18293 (if (and (car-safe old) refresh)
18294 (image-refresh (overlay-get (cdr old) 'display))
18295 (setq img (save-match-data (create-image file type nil :width width)))
18296 (when img
18297 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18298 (overlay-put ov 'display img)
18299 (overlay-put ov 'face 'default)
18300 (overlay-put ov 'org-image-overlay t)
18301 (overlay-put ov 'modification-hooks
18302 (list 'org-display-inline-remove-overlay))
18303 (push ov org-inline-image-overlays)))))))))
18305 (define-obsolete-function-alias
18306 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18308 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18309 "Remove inline-display overlay if a corresponding region is modified."
18310 (let ((inhibit-modification-hooks t))
18311 (when (and ov after)
18312 (delete ov org-inline-image-overlays)
18313 (delete-overlay ov))))
18315 (defun org-remove-inline-images ()
18316 "Remove inline display of images."
18317 (interactive)
18318 (mapc 'delete-overlay org-inline-image-overlays)
18319 (setq org-inline-image-overlays nil))
18321 ;;;; Key bindings
18323 ;; Outline functions from `outline-mode-prefix-map'
18324 ;; that can be remapped in Org:
18325 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18326 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18327 (define-key org-mode-map [remap outline-forward-same-level]
18328 'org-forward-heading-same-level)
18329 (define-key org-mode-map [remap outline-backward-same-level]
18330 'org-backward-heading-same-level)
18331 (define-key org-mode-map [remap show-branches]
18332 'org-kill-note-or-show-branches)
18333 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18334 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18335 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18337 ;; Outline functions from `outline-mode-prefix-map' that can not
18338 ;; be remapped in Org:
18340 ;; - the column "key binding" shows whether the Outline function is still
18341 ;; available in Org mode on the same key that it has been bound to in
18342 ;; Outline mode:
18343 ;; - "overridden": key used for a different functionality in Org mode
18344 ;; - else: key still bound to the same Outline function in Org mode
18346 ;; | Outline function | key binding | Org replacement |
18347 ;; |------------------------------------+-------------+-----------------------|
18348 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18349 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18350 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18351 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18352 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18353 ;; | `show-entry' | overridden | no replacement |
18354 ;; | `show-children' | `C-c C-i' | visibility cycling |
18355 ;; | `show-branches' | `C-c C-k' | still same function |
18356 ;; | `show-subtree' | overridden | visibility cycling |
18357 ;; | `show-all' | overridden | no replacement |
18358 ;; | `hide-subtree' | overridden | visibility cycling |
18359 ;; | `hide-body' | overridden | no replacement |
18360 ;; | `hide-entry' | overridden | visibility cycling |
18361 ;; | `hide-leaves' | overridden | no replacement |
18362 ;; | `hide-sublevels' | overridden | no replacement |
18363 ;; | `hide-other' | overridden | no replacement |
18365 ;; Make `C-c C-x' a prefix key
18366 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18368 ;; TAB key with modifiers
18369 (org-defkey org-mode-map "\C-i" 'org-cycle)
18370 (org-defkey org-mode-map [(tab)] 'org-cycle)
18371 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18372 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18373 ;; The following line is necessary under Suse GNU/Linux
18374 (unless (featurep 'xemacs)
18375 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18376 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18377 (define-key org-mode-map [backtab] 'org-shifttab)
18379 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18380 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18381 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18383 ;; Cursor keys with modifiers
18384 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18385 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18386 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18387 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18389 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18390 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18391 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18392 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18394 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18395 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18396 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18397 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18399 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18400 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18401 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18402 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18404 ;; Babel keys
18405 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18406 (mapc (lambda (pair)
18407 (define-key org-babel-map (car pair) (cdr pair)))
18408 org-babel-key-bindings)
18410 ;;; Extra keys for tty access.
18411 ;; We only set them when really needed because otherwise the
18412 ;; menus don't show the simple keys
18414 (when (or org-use-extra-keys
18415 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18416 (not window-system))
18417 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18418 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18419 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18420 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18421 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18422 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18423 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18424 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18425 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18426 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18427 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18428 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18429 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18430 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18431 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18432 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18433 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18434 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18435 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18436 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18437 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18438 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18439 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18440 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18441 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18442 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18443 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18444 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18446 ;; All the other keys
18448 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18449 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18450 (if (boundp 'narrow-map)
18451 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18452 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18453 (if (boundp 'narrow-map)
18454 (org-defkey narrow-map "b" 'org-narrow-to-block)
18455 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18456 (if (boundp 'narrow-map)
18457 (org-defkey narrow-map "e" 'org-narrow-to-element)
18458 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18459 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18460 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18461 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18462 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18463 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18464 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18465 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18466 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18467 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18468 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18469 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18470 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18471 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18472 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18473 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18474 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18475 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18476 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18477 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18478 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18479 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18480 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18481 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18482 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18483 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18484 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18485 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18486 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18487 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18488 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18489 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18490 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18491 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18492 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18493 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18494 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18495 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18496 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18497 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18498 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18499 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18500 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18501 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18502 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18503 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18504 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18505 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18506 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18507 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18508 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18509 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18510 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18511 (org-defkey org-mode-map "\C-c^" 'org-sort)
18512 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18513 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18514 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18515 (org-defkey org-mode-map "\C-m" 'org-return)
18516 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18517 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18518 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18519 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18520 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18521 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18522 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18523 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18524 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18525 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18526 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18527 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18528 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18529 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18530 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18531 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18532 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18533 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18534 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18535 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18536 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18537 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18538 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18540 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18541 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18542 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18544 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18545 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18546 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18547 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18548 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18549 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18550 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18551 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18552 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18553 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18554 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18555 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18556 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18557 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18558 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18559 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18560 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18561 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18562 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18563 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18564 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18565 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18566 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18568 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18569 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18570 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18571 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18572 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18574 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18576 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18578 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18579 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18581 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18584 (when (featurep 'xemacs)
18585 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18588 (defconst org-speed-commands-default
18590 ("Outline Navigation")
18591 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18592 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18593 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18594 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18595 ("u" . (org-speed-move-safe 'outline-up-heading))
18596 ("j" . org-goto)
18597 ("g" . (org-refile t))
18598 ("Outline Visibility")
18599 ("c" . org-cycle)
18600 ("C" . org-shifttab)
18601 (" " . org-display-outline-path)
18602 ("=" . org-columns)
18603 ("Outline Structure Editing")
18604 ("U" . org-shiftmetaup)
18605 ("D" . org-shiftmetadown)
18606 ("r" . org-metaright)
18607 ("l" . org-metaleft)
18608 ("R" . org-shiftmetaright)
18609 ("L" . org-shiftmetaleft)
18610 ("i" . (progn (forward-char 1) (call-interactively
18611 'org-insert-heading-respect-content)))
18612 ("^" . org-sort)
18613 ("w" . org-refile)
18614 ("a" . org-archive-subtree-default-with-confirmation)
18615 ("." . org-mark-subtree)
18616 ("#" . org-toggle-comment)
18617 ("Clock Commands")
18618 ("I" . org-clock-in)
18619 ("O" . org-clock-out)
18620 ("Meta Data Editing")
18621 ("t" . org-todo)
18622 ("," . (org-priority))
18623 ("0" . (org-priority ?\ ))
18624 ("1" . (org-priority ?A))
18625 ("2" . (org-priority ?B))
18626 ("3" . (org-priority ?C))
18627 (":" . org-set-tags-command)
18628 ("e" . org-set-effort)
18629 ("E" . org-inc-effort)
18630 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18631 (org-entry-put (point) "APPT_WARNTIME" m)))
18632 ("Agenda Views etc")
18633 ("v" . org-agenda)
18634 ("/" . org-sparse-tree)
18635 ("Misc")
18636 ("o" . org-open-at-point)
18637 ("?" . org-speed-command-help)
18638 ("<" . (org-agenda-set-restriction-lock 'subtree))
18639 (">" . (org-agenda-remove-restriction-lock))
18641 "The default speed commands.")
18643 (defun org-print-speed-command (e)
18644 (if (> (length (car e)) 1)
18645 (progn
18646 (princ "\n")
18647 (princ (car e))
18648 (princ "\n")
18649 (princ (make-string (length (car e)) ?-))
18650 (princ "\n"))
18651 (princ (car e))
18652 (princ " ")
18653 (if (symbolp (cdr e))
18654 (princ (symbol-name (cdr e)))
18655 (prin1 (cdr e)))
18656 (princ "\n")))
18658 (defun org-speed-command-help ()
18659 "Show the available speed commands."
18660 (interactive)
18661 (if (not org-use-speed-commands)
18662 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18663 (with-output-to-temp-buffer "*Help*"
18664 (princ "User-defined Speed commands\n===========================\n")
18665 (mapc 'org-print-speed-command org-speed-commands-user)
18666 (princ "\n")
18667 (princ "Built-in Speed commands\n=======================\n")
18668 (mapc 'org-print-speed-command org-speed-commands-default))
18669 (with-current-buffer "*Help*"
18670 (setq truncate-lines t))))
18672 (defun org-speed-move-safe (cmd)
18673 "Execute CMD, but make sure that the cursor always ends up in a headline.
18674 If not, return to the original position and throw an error."
18675 (interactive)
18676 (let ((pos (point)))
18677 (call-interactively cmd)
18678 (unless (and (bolp) (org-at-heading-p))
18679 (goto-char pos)
18680 (error "Boundary reached while executing %s" cmd))))
18682 (defvar org-self-insert-command-undo-counter 0)
18684 (defvar org-table-auto-blank-field) ; defined in org-table.el
18685 (defvar org-speed-command nil)
18687 (define-obsolete-function-alias
18688 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18690 (defun org-speed-command-activate (keys)
18691 "Hook for activating single-letter speed commands.
18692 `org-speed-commands-default' specifies a minimal command set.
18693 Use `org-speed-commands-user' for further customization."
18694 (when (or (and (bolp) (looking-at org-outline-regexp))
18695 (and (functionp org-use-speed-commands)
18696 (funcall org-use-speed-commands)))
18697 (cdr (assoc keys (append org-speed-commands-user
18698 org-speed-commands-default)))))
18700 (define-obsolete-function-alias
18701 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18703 (defun org-babel-speed-command-activate (keys)
18704 "Hook for activating single-letter code block commands."
18705 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18706 (cdr (assoc keys org-babel-key-bindings))))
18708 (defcustom org-speed-command-hook
18709 '(org-speed-command-default-hook org-babel-speed-command-hook)
18710 "Hook for activating speed commands at strategic locations.
18711 Hook functions are called in sequence until a valid handler is
18712 found.
18714 Each hook takes a single argument, a user-pressed command key
18715 which is also a `self-insert-command' from the global map.
18717 Within the hook, examine the cursor position and the command key
18718 and return nil or a valid handler as appropriate. Handler could
18719 be one of an interactive command, a function, or a form.
18721 Set `org-use-speed-commands' to non-nil value to enable this
18722 hook. The default setting is `org-speed-command-activate'."
18723 :group 'org-structure
18724 :version "24.1"
18725 :type 'hook)
18727 (defun org-self-insert-command (N)
18728 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18729 If the cursor is in a table looking at whitespace, the whitespace is
18730 overwritten, and the table is not marked as requiring realignment."
18731 (interactive "p")
18732 (org-check-before-invisible-edit 'insert)
18733 (cond
18734 ((and org-use-speed-commands
18735 (setq org-speed-command
18736 (run-hook-with-args-until-success
18737 'org-speed-command-hook (this-command-keys))))
18738 (cond
18739 ((commandp org-speed-command)
18740 (setq this-command org-speed-command)
18741 (call-interactively org-speed-command))
18742 ((functionp org-speed-command)
18743 (funcall org-speed-command))
18744 ((and org-speed-command (listp org-speed-command))
18745 (eval org-speed-command))
18746 (t (let (org-use-speed-commands)
18747 (call-interactively 'org-self-insert-command)))))
18748 ((and
18749 (org-table-p)
18750 (progn
18751 ;; check if we blank the field, and if that triggers align
18752 (and (featurep 'org-table) org-table-auto-blank-field
18753 (member last-command
18754 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18755 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18756 ;; got extra space, this field does not determine column width
18757 (let (org-table-may-need-update) (org-table-blank-field))
18758 ;; no extra space, this field may determine column width
18759 (org-table-blank-field)))
18761 (eq N 1)
18762 (looking-at "[^|\n]* |"))
18763 (let (org-table-may-need-update)
18764 (goto-char (1- (match-end 0)))
18765 (backward-delete-char 1)
18766 (goto-char (match-beginning 0))
18767 (self-insert-command N)))
18769 (setq org-table-may-need-update t)
18770 (self-insert-command N)
18771 (org-fix-tags-on-the-fly)
18772 (if org-self-insert-cluster-for-undo
18773 (if (not (eq last-command 'org-self-insert-command))
18774 (setq org-self-insert-command-undo-counter 1)
18775 (if (>= org-self-insert-command-undo-counter 20)
18776 (setq org-self-insert-command-undo-counter 1)
18777 (and (> org-self-insert-command-undo-counter 0)
18778 buffer-undo-list (listp buffer-undo-list)
18779 (not (cadr buffer-undo-list)) ; remove nil entry
18780 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18781 (setq org-self-insert-command-undo-counter
18782 (1+ org-self-insert-command-undo-counter))))))))
18784 (defun org-check-before-invisible-edit (kind)
18785 "Check is editing if kind KIND would be dangerous with invisible text around.
18786 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18787 ;; First, try to get out of here as quickly as possible, to reduce overhead
18788 (if (and org-catch-invisible-edits
18789 (or (not (boundp 'visible-mode)) (not visible-mode))
18790 (or (get-char-property (point) 'invisible)
18791 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18792 ;; OK, we need to take a closer look
18793 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18794 (invisible-before-point (if (bobp) nil (get-char-property
18795 (1- (point)) 'invisible)))
18796 (border-and-ok-direction
18798 ;; Check if we are acting predictably before invisible text
18799 (and invisible-at-point (not invisible-before-point)
18800 (memq kind '(insert delete-backward)))
18801 ;; Check if we are acting predictably after invisible text
18802 ;; This works not well, and I have turned it off. It seems
18803 ;; better to always show and stop after invisible text.
18804 ;; (and (not invisible-at-point) invisible-before-point
18805 ;; (memq kind '(insert delete)))
18807 (when (or (memq invisible-at-point '(outline org-hide-block t))
18808 (memq invisible-before-point '(outline org-hide-block t)))
18809 (if (eq org-catch-invisible-edits 'error)
18810 (error "Editing in invisible areas is prohibited - make visible first"))
18811 (if (and org-custom-properties-overlays
18812 (y-or-n-p "Display invisible properties in this buffer? "))
18813 (org-toggle-custom-properties-visibility)
18814 ;; Make the area visible
18815 (save-excursion
18816 (if invisible-before-point
18817 (goto-char (previous-single-char-property-change
18818 (point) 'invisible)))
18819 (org-cycle))
18820 (cond
18821 ((eq org-catch-invisible-edits 'show)
18822 ;; That's it, we do the edit after showing
18823 (message
18824 "Unfolding invisible region around point before editing")
18825 (sit-for 1))
18826 ((and (eq org-catch-invisible-edits 'smart)
18827 border-and-ok-direction)
18828 (message "Unfolding invisible region around point before editing"))
18830 ;; Don't do the edit, make the user repeat it in full visibility
18831 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18833 (defun org-fix-tags-on-the-fly ()
18834 (when (and (equal (char-after (point-at-bol)) ?*)
18835 (org-at-heading-p))
18836 (org-align-tags-here org-tags-column)))
18838 (defun org-delete-backward-char (N)
18839 "Like `delete-backward-char', insert whitespace at field end in tables.
18840 When deleting backwards, in tables this function will insert whitespace in
18841 front of the next \"|\" separator, to keep the table aligned. The table will
18842 still be marked for re-alignment if the field did fill the entire column,
18843 because, in this case the deletion might narrow the column."
18844 (interactive "p")
18845 (save-match-data
18846 (org-check-before-invisible-edit 'delete-backward)
18847 (if (and (org-table-p)
18848 (eq N 1)
18849 (string-match "|" (buffer-substring (point-at-bol) (point)))
18850 (looking-at ".*?|"))
18851 (let ((pos (point))
18852 (noalign (looking-at "[^|\n\r]* |"))
18853 (c org-table-may-need-update))
18854 (backward-delete-char N)
18855 (if (not overwrite-mode)
18856 (progn
18857 (skip-chars-forward "^|")
18858 (insert " ")
18859 (goto-char (1- pos))))
18860 ;; noalign: if there were two spaces at the end, this field
18861 ;; does not determine the width of the column.
18862 (if noalign (setq org-table-may-need-update c)))
18863 (backward-delete-char N)
18864 (org-fix-tags-on-the-fly))))
18866 (defun org-delete-char (N)
18867 "Like `delete-char', but insert whitespace at field end in tables.
18868 When deleting characters, in tables this function will insert whitespace in
18869 front of the next \"|\" separator, to keep the table aligned. The table will
18870 still be marked for re-alignment if the field did fill the entire column,
18871 because, in this case the deletion might narrow the column."
18872 (interactive "p")
18873 (save-match-data
18874 (org-check-before-invisible-edit 'delete)
18875 (if (and (org-table-p)
18876 (not (bolp))
18877 (not (= (char-after) ?|))
18878 (eq N 1))
18879 (if (looking-at ".*?|")
18880 (let ((pos (point))
18881 (noalign (looking-at "[^|\n\r]* |"))
18882 (c org-table-may-need-update))
18883 (replace-match (concat
18884 (substring (match-string 0) 1 -1)
18885 " |"))
18886 (goto-char pos)
18887 ;; noalign: if there were two spaces at the end, this field
18888 ;; does not determine the width of the column.
18889 (if noalign (setq org-table-may-need-update c)))
18890 (delete-char N))
18891 (delete-char N)
18892 (org-fix-tags-on-the-fly))))
18894 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18895 (put 'org-self-insert-command 'delete-selection t)
18896 (put 'orgtbl-self-insert-command 'delete-selection t)
18897 (put 'org-delete-char 'delete-selection 'supersede)
18898 (put 'org-delete-backward-char 'delete-selection 'supersede)
18899 (put 'org-yank 'delete-selection 'yank)
18901 ;; Make `flyspell-mode' delay after some commands
18902 (put 'org-self-insert-command 'flyspell-delayed t)
18903 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18904 (put 'org-delete-char 'flyspell-delayed t)
18905 (put 'org-delete-backward-char 'flyspell-delayed t)
18907 ;; Make pabbrev-mode expand after org-mode commands
18908 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18909 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18911 ;; How to do this: Measure non-white length of current string
18912 ;; If equal to column width, we should realign.
18914 (defun org-remap (map &rest commands)
18915 "In MAP, remap the functions given in COMMANDS.
18916 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18917 (let (new old)
18918 (while commands
18919 (setq old (pop commands) new (pop commands))
18920 (if (fboundp 'command-remapping)
18921 (org-defkey map (vector 'remap old) new)
18922 (substitute-key-definition old new map global-map)))))
18924 (when (eq org-enable-table-editor 'optimized)
18925 ;; If the user wants maximum table support, we need to hijack
18926 ;; some standard editing functions
18927 (org-remap org-mode-map
18928 'self-insert-command 'org-self-insert-command
18929 'delete-char 'org-delete-char
18930 'delete-backward-char 'org-delete-backward-char)
18931 (org-defkey org-mode-map "|" 'org-force-self-insert))
18933 (defvar org-ctrl-c-ctrl-c-hook nil
18934 "Hook for functions attaching themselves to `C-c C-c'.
18936 This can be used to add additional functionality to the C-c C-c
18937 key which executes context-dependent commands. This hook is run
18938 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18939 run after the last test.
18941 Each function will be called with no arguments. The function
18942 must check if the context is appropriate for it to act. If yes,
18943 it should do its thing and then return a non-nil value. If the
18944 context is wrong, just do nothing and return nil.")
18946 (defvar org-ctrl-c-ctrl-c-final-hook nil
18947 "Hook for functions attaching themselves to `C-c C-c'.
18949 This can be used to add additional functionality to the C-c C-c
18950 key which executes context-dependent commands. This hook is run
18951 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18952 before the first test.
18954 Each function will be called with no arguments. The function
18955 must check if the context is appropriate for it to act. If yes,
18956 it should do its thing and then return a non-nil value. If the
18957 context is wrong, just do nothing and return nil.")
18959 (defvar org-tab-first-hook nil
18960 "Hook for functions to attach themselves to TAB.
18961 See `org-ctrl-c-ctrl-c-hook' for more information.
18962 This hook runs as the first action when TAB is pressed, even before
18963 `org-cycle' messes around with the `outline-regexp' to cater for
18964 inline tasks and plain list item folding.
18965 If any function in this hook returns t, any other actions that
18966 would have been caused by TAB (such as table field motion or visibility
18967 cycling) will not occur.")
18969 (defvar org-tab-after-check-for-table-hook nil
18970 "Hook for functions to attach themselves to TAB.
18971 See `org-ctrl-c-ctrl-c-hook' for more information.
18972 This hook runs after it has been established that the cursor is not in a
18973 table, but before checking if the cursor is in a headline or if global cycling
18974 should be done.
18975 If any function in this hook returns t, not other actions like visibility
18976 cycling will be done.")
18978 (defvar org-tab-after-check-for-cycling-hook nil
18979 "Hook for functions to attach themselves to TAB.
18980 See `org-ctrl-c-ctrl-c-hook' for more information.
18981 This hook runs after it has been established that not table field motion and
18982 not visibility should be done because of current context. This is probably
18983 the place where a package like yasnippets can hook in.")
18985 (defvar org-tab-before-tab-emulation-hook nil
18986 "Hook for functions to attach themselves to TAB.
18987 See `org-ctrl-c-ctrl-c-hook' for more information.
18988 This hook runs after every other options for TAB have been exhausted, but
18989 before indentation and \t insertion takes place.")
18991 (defvar org-metaleft-hook nil
18992 "Hook for functions attaching themselves to `M-left'.
18993 See `org-ctrl-c-ctrl-c-hook' for more information.")
18994 (defvar org-metaright-hook nil
18995 "Hook for functions attaching themselves to `M-right'.
18996 See `org-ctrl-c-ctrl-c-hook' for more information.")
18997 (defvar org-metaup-hook nil
18998 "Hook for functions attaching themselves to `M-up'.
18999 See `org-ctrl-c-ctrl-c-hook' for more information.")
19000 (defvar org-metadown-hook nil
19001 "Hook for functions attaching themselves to `M-down'.
19002 See `org-ctrl-c-ctrl-c-hook' for more information.")
19003 (defvar org-shiftmetaleft-hook nil
19004 "Hook for functions attaching themselves to `M-S-left'.
19005 See `org-ctrl-c-ctrl-c-hook' for more information.")
19006 (defvar org-shiftmetaright-hook nil
19007 "Hook for functions attaching themselves to `M-S-right'.
19008 See `org-ctrl-c-ctrl-c-hook' for more information.")
19009 (defvar org-shiftmetaup-hook nil
19010 "Hook for functions attaching themselves to `M-S-up'.
19011 See `org-ctrl-c-ctrl-c-hook' for more information.")
19012 (defvar org-shiftmetadown-hook nil
19013 "Hook for functions attaching themselves to `M-S-down'.
19014 See `org-ctrl-c-ctrl-c-hook' for more information.")
19015 (defvar org-metareturn-hook nil
19016 "Hook for functions attaching themselves to `M-RET'.
19017 See `org-ctrl-c-ctrl-c-hook' for more information.")
19018 (defvar org-shiftup-hook nil
19019 "Hook for functions attaching themselves to `S-up'.
19020 See `org-ctrl-c-ctrl-c-hook' for more information.")
19021 (defvar org-shiftup-final-hook nil
19022 "Hook for functions attaching themselves to `S-up'.
19023 This one runs after all other options except shift-select have been excluded.
19024 See `org-ctrl-c-ctrl-c-hook' for more information.")
19025 (defvar org-shiftdown-hook nil
19026 "Hook for functions attaching themselves to `S-down'.
19027 See `org-ctrl-c-ctrl-c-hook' for more information.")
19028 (defvar org-shiftdown-final-hook nil
19029 "Hook for functions attaching themselves to `S-down'.
19030 This one runs after all other options except shift-select have been excluded.
19031 See `org-ctrl-c-ctrl-c-hook' for more information.")
19032 (defvar org-shiftleft-hook nil
19033 "Hook for functions attaching themselves to `S-left'.
19034 See `org-ctrl-c-ctrl-c-hook' for more information.")
19035 (defvar org-shiftleft-final-hook nil
19036 "Hook for functions attaching themselves to `S-left'.
19037 This one runs after all other options except shift-select have been excluded.
19038 See `org-ctrl-c-ctrl-c-hook' for more information.")
19039 (defvar org-shiftright-hook nil
19040 "Hook for functions attaching themselves to `S-right'.
19041 See `org-ctrl-c-ctrl-c-hook' for more information.")
19042 (defvar org-shiftright-final-hook nil
19043 "Hook for functions attaching themselves to `S-right'.
19044 This one runs after all other options except shift-select have been excluded.
19045 See `org-ctrl-c-ctrl-c-hook' for more information.")
19047 (defun org-modifier-cursor-error ()
19048 "Throw an error, a modified cursor command was applied in wrong context."
19049 (error "This command is active in special context like tables, headlines or items"))
19051 (defun org-shiftselect-error ()
19052 "Throw an error because Shift-Cursor command was applied in wrong context."
19053 (if (and (boundp 'shift-select-mode) shift-select-mode)
19054 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19055 (error "This command works only in special context like headlines or timestamps")))
19057 (defun org-call-for-shift-select (cmd)
19058 (let ((this-command-keys-shift-translated t))
19059 (call-interactively cmd)))
19061 (defun org-shifttab (&optional arg)
19062 "Global visibility cycling or move to previous table field.
19063 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19064 on context.
19065 See the individual commands for more information."
19066 (interactive "P")
19067 (cond
19068 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19069 ((integerp arg)
19070 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19071 (message "Content view to level: %d" arg)
19072 (org-content (prefix-numeric-value arg2))
19073 (setq org-cycle-global-status 'overview)))
19074 (t (call-interactively 'org-global-cycle))))
19076 (defun org-shiftmetaleft ()
19077 "Promote subtree or delete table column.
19078 Calls `org-promote-subtree', `org-outdent-item-tree', or
19079 `org-table-delete-column', depending on context. See the
19080 individual commands for more information."
19081 (interactive)
19082 (cond
19083 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19084 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19085 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19086 ((if (not (org-region-active-p)) (org-at-item-p)
19087 (save-excursion (goto-char (region-beginning))
19088 (org-at-item-p)))
19089 (call-interactively 'org-outdent-item-tree))
19090 (t (org-modifier-cursor-error))))
19092 (defun org-shiftmetaright ()
19093 "Demote subtree or insert table column.
19094 Calls `org-demote-subtree', `org-indent-item-tree', or
19095 `org-table-insert-column', depending on context. See the
19096 individual commands for more information."
19097 (interactive)
19098 (cond
19099 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19100 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19101 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19102 ((if (not (org-region-active-p)) (org-at-item-p)
19103 (save-excursion (goto-char (region-beginning))
19104 (org-at-item-p)))
19105 (call-interactively 'org-indent-item-tree))
19106 (t (org-modifier-cursor-error))))
19108 (defun org-shiftmetaup (&optional arg)
19109 "Move subtree up or kill table row.
19110 Calls `org-move-subtree-up' or `org-table-kill-row' or
19111 `org-move-item-up' or `org-timestamp-up', depending on context.
19112 See the individual commands for more information."
19113 (interactive "P")
19114 (cond
19115 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19116 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19117 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19118 ((org-at-item-p) (call-interactively 'org-move-item-up))
19119 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19120 (call-interactively 'org-timestamp-up)))
19121 (t (org-modifier-cursor-error))))
19123 (defun org-shiftmetadown (&optional arg)
19124 "Move subtree down or insert table row.
19125 Calls `org-move-subtree-down' or `org-table-insert-row' or
19126 `org-move-item-down' or `org-timestamp-up', depending on context.
19127 See the individual commands for more information."
19128 (interactive "P")
19129 (cond
19130 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19131 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19132 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19133 ((org-at-item-p) (call-interactively 'org-move-item-down))
19134 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19135 (call-interactively 'org-timestamp-down)))
19136 (t (org-modifier-cursor-error))))
19138 (defsubst org-hidden-tree-error ()
19139 (error
19140 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19142 (defun org-metaleft (&optional arg)
19143 "Promote heading or move table column to left.
19144 Calls `org-do-promote' or `org-table-move-column', depending on context.
19145 With no specific context, calls the Emacs default `backward-word'.
19146 See the individual commands for more information."
19147 (interactive "P")
19148 (cond
19149 ((run-hook-with-args-until-success 'org-metaleft-hook))
19150 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19151 ((org-with-limited-levels
19152 (or (org-at-heading-p)
19153 (and (org-region-active-p)
19154 (save-excursion
19155 (goto-char (region-beginning))
19156 (org-at-heading-p)))))
19157 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19158 (call-interactively 'org-do-promote))
19159 ;; At an inline task.
19160 ((org-at-heading-p)
19161 (call-interactively 'org-inlinetask-promote))
19162 ((or (org-at-item-p)
19163 (and (org-region-active-p)
19164 (save-excursion
19165 (goto-char (region-beginning))
19166 (org-at-item-p))))
19167 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19168 (call-interactively 'org-outdent-item))
19169 (t (call-interactively 'backward-word))))
19171 (defun org-metaright (&optional arg)
19172 "Demote a subtree, a list item or move table column to right.
19173 In front of a drawer or a block keyword, indent it correctly.
19174 With no specific context, calls the Emacs default `forward-word'.
19175 See the individual commands for more information."
19176 (interactive "P")
19177 (cond
19178 ((run-hook-with-args-until-success 'org-metaright-hook))
19179 ((org-at-table-p) (call-interactively 'org-table-move-column))
19180 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19181 ((org-at-block-p) (call-interactively 'org-indent-block))
19182 ((org-with-limited-levels
19183 (or (org-at-heading-p)
19184 (and (org-region-active-p)
19185 (save-excursion
19186 (goto-char (region-beginning))
19187 (org-at-heading-p)))))
19188 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19189 (call-interactively 'org-do-demote))
19190 ;; At an inline task.
19191 ((org-at-heading-p)
19192 (call-interactively 'org-inlinetask-demote))
19193 ((or (org-at-item-p)
19194 (and (org-region-active-p)
19195 (save-excursion
19196 (goto-char (region-beginning))
19197 (org-at-item-p))))
19198 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19199 (call-interactively 'org-indent-item))
19200 (t (call-interactively 'forward-word))))
19202 (defun org-check-for-hidden (what)
19203 "Check if there are hidden headlines/items in the current visual line.
19204 WHAT can be either `headlines' or `items'. If the current line is
19205 an outline or item heading and it has a folded subtree below it,
19206 this function returns t, nil otherwise."
19207 (let ((re (cond
19208 ((eq what 'headlines) org-outline-regexp-bol)
19209 ((eq what 'items) (org-item-beginning-re))
19210 (t (error "This should not happen"))))
19211 beg end)
19212 (save-excursion
19213 (catch 'exit
19214 (unless (org-region-active-p)
19215 (setq beg (point-at-bol))
19216 (beginning-of-line 2)
19217 (while (and (not (eobp)) ;; this is like `next-line'
19218 (get-char-property (1- (point)) 'invisible))
19219 (beginning-of-line 2))
19220 (setq end (point))
19221 (goto-char beg)
19222 (goto-char (point-at-eol))
19223 (setq end (max end (point)))
19224 (while (re-search-forward re end t)
19225 (if (get-char-property (match-beginning 0) 'invisible)
19226 (throw 'exit t))))
19227 nil))))
19229 (defun org-metaup (&optional arg)
19230 "Move subtree up or move table row up.
19231 Calls `org-move-subtree-up' or `org-table-move-row' or
19232 `org-move-item-up', depending on context. See the individual commands
19233 for more information."
19234 (interactive "P")
19235 (cond
19236 ((run-hook-with-args-until-success 'org-metaup-hook))
19237 ((org-region-active-p)
19238 (let* ((a (min (region-beginning) (region-end)))
19239 (b (1- (max (region-beginning) (region-end))))
19240 (c (save-excursion (goto-char a)
19241 (move-beginning-of-line 0)))
19242 (d (save-excursion (goto-char a)
19243 (move-end-of-line 0) (point))))
19244 (transpose-regions a b c d)
19245 (goto-char c)))
19246 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19247 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19248 ((org-at-item-p) (call-interactively 'org-move-item-up))
19249 (t (org-drag-element-backward))))
19251 (defun org-metadown (&optional arg)
19252 "Move subtree down or move table row down.
19253 Calls `org-move-subtree-down' or `org-table-move-row' or
19254 `org-move-item-down', depending on context. See the individual
19255 commands for more information."
19256 (interactive "P")
19257 (cond
19258 ((run-hook-with-args-until-success 'org-metadown-hook))
19259 ((org-region-active-p)
19260 (let* ((a (min (region-beginning) (region-end)))
19261 (b (max (region-beginning) (region-end)))
19262 (c (save-excursion (goto-char b)
19263 (move-beginning-of-line 1)))
19264 (d (save-excursion (goto-char b)
19265 (move-end-of-line 1) (1+ (point)))))
19266 (transpose-regions a b c d)
19267 (goto-char d)))
19268 ((org-at-table-p) (call-interactively 'org-table-move-row))
19269 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19270 ((org-at-item-p) (call-interactively 'org-move-item-down))
19271 (t (org-drag-element-forward))))
19273 (defun org-shiftup (&optional arg)
19274 "Increase item in timestamp or increase priority of current headline.
19275 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19276 depending on context. See the individual commands for more information."
19277 (interactive "P")
19278 (cond
19279 ((run-hook-with-args-until-success 'org-shiftup-hook))
19280 ((and org-support-shift-select (org-region-active-p))
19281 (org-call-for-shift-select 'previous-line))
19282 ((org-at-timestamp-p t)
19283 (call-interactively (if org-edit-timestamp-down-means-later
19284 'org-timestamp-down 'org-timestamp-up)))
19285 ((and (not (eq org-support-shift-select 'always))
19286 org-enable-priority-commands
19287 (org-at-heading-p))
19288 (call-interactively 'org-priority-up))
19289 ((and (not org-support-shift-select) (org-at-item-p))
19290 (call-interactively 'org-previous-item))
19291 ((org-clocktable-try-shift 'up arg))
19292 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19293 (org-support-shift-select
19294 (org-call-for-shift-select 'previous-line))
19295 (t (org-shiftselect-error))))
19297 (defun org-shiftdown (&optional arg)
19298 "Decrease item in timestamp or decrease priority of current headline.
19299 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19300 depending on context. See the individual commands for more information."
19301 (interactive "P")
19302 (cond
19303 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19304 ((and org-support-shift-select (org-region-active-p))
19305 (org-call-for-shift-select 'next-line))
19306 ((org-at-timestamp-p t)
19307 (call-interactively (if org-edit-timestamp-down-means-later
19308 'org-timestamp-up 'org-timestamp-down)))
19309 ((and (not (eq org-support-shift-select 'always))
19310 org-enable-priority-commands
19311 (org-at-heading-p))
19312 (call-interactively 'org-priority-down))
19313 ((and (not org-support-shift-select) (org-at-item-p))
19314 (call-interactively 'org-next-item))
19315 ((org-clocktable-try-shift 'down arg))
19316 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19317 (org-support-shift-select
19318 (org-call-for-shift-select 'next-line))
19319 (t (org-shiftselect-error))))
19321 (defun org-shiftright (&optional arg)
19322 "Cycle the thing at point or in the current line, depending on context.
19323 Depending on context, this does one of the following:
19325 - switch a timestamp at point one day into the future
19326 - on a headline, switch to the next TODO keyword.
19327 - on an item, switch entire list to the next bullet type
19328 - on a property line, switch to the next allowed value
19329 - on a clocktable definition line, move time block into the future"
19330 (interactive "P")
19331 (cond
19332 ((run-hook-with-args-until-success 'org-shiftright-hook))
19333 ((and org-support-shift-select (org-region-active-p))
19334 (org-call-for-shift-select 'forward-char))
19335 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19336 ((and (not (eq org-support-shift-select 'always))
19337 (org-at-heading-p))
19338 (let ((org-inhibit-logging
19339 (not org-treat-S-cursor-todo-selection-as-state-change))
19340 (org-inhibit-blocking
19341 (not org-treat-S-cursor-todo-selection-as-state-change)))
19342 (org-call-with-arg 'org-todo 'right)))
19343 ((or (and org-support-shift-select
19344 (not (eq org-support-shift-select 'always))
19345 (org-at-item-bullet-p))
19346 (and (not org-support-shift-select) (org-at-item-p)))
19347 (org-call-with-arg 'org-cycle-list-bullet nil))
19348 ((and (not (eq org-support-shift-select 'always))
19349 (org-at-property-p))
19350 (call-interactively 'org-property-next-allowed-value))
19351 ((org-clocktable-try-shift 'right arg))
19352 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19353 (org-support-shift-select
19354 (org-call-for-shift-select 'forward-char))
19355 (t (org-shiftselect-error))))
19357 (defun org-shiftleft (&optional arg)
19358 "Cycle the thing at point or in the current line, depending on context.
19359 Depending on context, this does one of the following:
19361 - switch a timestamp at point one day into the past
19362 - on a headline, switch to the previous TODO keyword.
19363 - on an item, switch entire list to the previous bullet type
19364 - on a property line, switch to the previous allowed value
19365 - on a clocktable definition line, move time block into the past"
19366 (interactive "P")
19367 (cond
19368 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19369 ((and org-support-shift-select (org-region-active-p))
19370 (org-call-for-shift-select 'backward-char))
19371 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19372 ((and (not (eq org-support-shift-select 'always))
19373 (org-at-heading-p))
19374 (let ((org-inhibit-logging
19375 (not org-treat-S-cursor-todo-selection-as-state-change))
19376 (org-inhibit-blocking
19377 (not org-treat-S-cursor-todo-selection-as-state-change)))
19378 (org-call-with-arg 'org-todo 'left)))
19379 ((or (and org-support-shift-select
19380 (not (eq org-support-shift-select 'always))
19381 (org-at-item-bullet-p))
19382 (and (not org-support-shift-select) (org-at-item-p)))
19383 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19384 ((and (not (eq org-support-shift-select 'always))
19385 (org-at-property-p))
19386 (call-interactively 'org-property-previous-allowed-value))
19387 ((org-clocktable-try-shift 'left arg))
19388 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19389 (org-support-shift-select
19390 (org-call-for-shift-select 'backward-char))
19391 (t (org-shiftselect-error))))
19393 (defun org-shiftcontrolright ()
19394 "Switch to next TODO set."
19395 (interactive)
19396 (cond
19397 ((and org-support-shift-select (org-region-active-p))
19398 (org-call-for-shift-select 'forward-word))
19399 ((and (not (eq org-support-shift-select 'always))
19400 (org-at-heading-p))
19401 (org-call-with-arg 'org-todo 'nextset))
19402 (org-support-shift-select
19403 (org-call-for-shift-select 'forward-word))
19404 (t (org-shiftselect-error))))
19406 (defun org-shiftcontrolleft ()
19407 "Switch to previous TODO set."
19408 (interactive)
19409 (cond
19410 ((and org-support-shift-select (org-region-active-p))
19411 (org-call-for-shift-select 'backward-word))
19412 ((and (not (eq org-support-shift-select 'always))
19413 (org-at-heading-p))
19414 (org-call-with-arg 'org-todo 'previousset))
19415 (org-support-shift-select
19416 (org-call-for-shift-select 'backward-word))
19417 (t (org-shiftselect-error))))
19419 (defun org-shiftcontrolup (&optional n)
19420 "Change timestamps synchronously up in CLOCK log lines.
19421 Optional argument N tells to change by that many units."
19422 (interactive "P")
19423 (cond ((and (not org-support-shift-select)
19424 (org-at-clock-log-p)
19425 (org-at-timestamp-p t))
19426 (org-clock-timestamps-up n))
19427 (t (org-shiftselect-error))))
19429 (defun org-shiftcontroldown (&optional n)
19430 "Change timestamps synchronously down in CLOCK log lines.
19431 Optional argument N tells to change by that many units."
19432 (interactive "P")
19433 (cond ((and (not org-support-shift-select)
19434 (org-at-clock-log-p)
19435 (org-at-timestamp-p t))
19436 (org-clock-timestamps-down n))
19437 (t (org-shiftselect-error))))
19439 (defun org-ctrl-c-ret ()
19440 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19441 (interactive)
19442 (cond
19443 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19444 (t (call-interactively 'org-insert-heading))))
19446 (defun org-find-visible ()
19447 (let ((s (point)))
19448 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19449 (get-char-property s 'invisible)))
19451 (defun org-find-invisible ()
19452 (let ((s (point)))
19453 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19454 (not (get-char-property s 'invisible))))
19457 (defun org-copy-visible (beg end)
19458 "Copy the visible parts of the region."
19459 (interactive "r")
19460 (let (snippets s)
19461 (save-excursion
19462 (save-restriction
19463 (narrow-to-region beg end)
19464 (setq s (goto-char (point-min)))
19465 (while (not (= (point) (point-max)))
19466 (goto-char (org-find-invisible))
19467 (push (buffer-substring s (point)) snippets)
19468 (setq s (goto-char (org-find-visible))))))
19469 (kill-new (apply 'concat (nreverse snippets)))))
19471 (defun org-copy-special ()
19472 "Copy region in table or copy current subtree.
19473 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19474 See the individual commands for more information."
19475 (interactive)
19476 (call-interactively
19477 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19479 (defun org-cut-special ()
19480 "Cut region in table or cut current subtree.
19481 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19482 See the individual commands for more information."
19483 (interactive)
19484 (call-interactively
19485 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19487 (defun org-paste-special (arg)
19488 "Paste rectangular region into table, or past subtree relative to level.
19489 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19490 See the individual commands for more information."
19491 (interactive "P")
19492 (if (org-at-table-p)
19493 (org-table-paste-rectangle)
19494 (org-paste-subtree arg)))
19496 (defsubst org-in-fixed-width-region-p ()
19497 "Is point in a fixed-width region?"
19498 (save-match-data
19499 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19501 (defun org-edit-special (&optional arg)
19502 "Call a special editor for the element at point.
19503 When at a table, call the formula editor with `org-table-edit-formulas'.
19504 When in a source code block, call `org-edit-src-code'.
19505 When in a fixed-width region, call `org-edit-fixed-width-region'.
19506 When at an #+INCLUDE keyword, visit the included file.
19507 On a link, call `ffap' to visit the link at point.
19508 Otherwise, return a user error."
19509 (interactive)
19510 (let ((element (org-element-at-point)))
19511 (case (org-element-type element)
19512 (src-block
19513 (if (not arg) (org-edit-src-code)
19514 (let* ((info (org-babel-get-src-block-info))
19515 (lang (nth 0 info))
19516 (params (nth 2 info))
19517 (session (cdr (assq :session params))))
19518 (if (not session) (org-edit-src-code)
19519 ;; At a src-block with a session and function called with
19520 ;; an ARG: switch to the buffer related to the inferior
19521 ;; process.
19522 (funcall (intern (concat "org-babel-prep-session:" lang))
19523 session params)))))
19524 (keyword
19525 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19526 (find-file
19527 (org-remove-double-quotes
19528 (car (org-split-string (org-element-property :value element)))))
19529 (user-error "No special environment to edit here")))
19530 (table
19531 (if (eq (org-element-property :type element) 'table.el)
19532 (org-edit-src-code)
19533 (call-interactively 'org-table-edit-formulas)))
19534 ;; Only Org tables contain `table-row' type elements.
19535 (table-row (call-interactively 'org-table-edit-formulas))
19536 ((example-block export-block) (org-edit-src-code))
19537 (fixed-width (org-edit-fixed-width-region))
19538 (otherwise
19539 ;; No notable element at point. Though, we may be at a link,
19540 ;; which is an object. Thus, scan deeper.
19541 (if (eq (org-element-type (org-element-context element)) 'link)
19542 (call-interactively 'ffap)
19543 (user-error "No special environment to edit here"))))))
19545 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19546 (defun org-ctrl-c-ctrl-c (&optional arg)
19547 "Set tags in headline, or update according to changed information at point.
19549 This command does many different things, depending on context:
19551 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19552 this is what we do.
19554 - If the cursor is on a statistics cookie, update it.
19556 - If the cursor is in a headline, prompt for tags and insert them
19557 into the current line, aligned to `org-tags-column'. When called
19558 with prefix arg, realign all tags in the current buffer.
19560 - If the cursor is in one of the special #+KEYWORD lines, this
19561 triggers scanning the buffer for these lines and updating the
19562 information.
19564 - If the cursor is inside a table, realign the table. This command
19565 works even if the automatic table editor has been turned off.
19567 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19568 the entire table.
19570 - If the cursor is at a footnote reference or definition, jump to
19571 the corresponding definition or references, respectively.
19573 - If the cursor is a the beginning of a dynamic block, update it.
19575 - If the current buffer is a capture buffer, close note and file it.
19577 - If the cursor is on a <<<target>>>, update radio targets and
19578 corresponding links in this buffer.
19580 - If the cursor is on a numbered item in a plain list, renumber the
19581 ordered list.
19583 - If the cursor is on a checkbox, toggle it.
19585 - If the cursor is on a code block, evaluate it. The variable
19586 `org-confirm-babel-evaluate' can be used to control prompting
19587 before code block evaluation, by default every code block
19588 evaluation requires confirmation. Code block evaluation can be
19589 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19590 (interactive "P")
19591 (cond
19592 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19593 org-occur-highlights
19594 org-latex-fragment-image-overlays)
19595 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19596 (org-remove-occur-highlights)
19597 (org-remove-latex-fragment-image-overlays)
19598 (message "Temporary highlights/overlays removed from current buffer"))
19599 ((and (local-variable-p 'org-finish-function (current-buffer))
19600 (fboundp org-finish-function))
19601 (funcall org-finish-function))
19602 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19604 (let* ((context (org-element-context)) (type (org-element-type context)))
19605 ;; Test if point is within blanks at the end of an element.
19606 (if (save-excursion
19607 (or (not context)
19608 (beginning-of-line)
19609 (and (looking-at "[ \t]*$")
19610 (skip-chars-forward " \r\t\n")
19611 (>= (point) (org-element-property :end context)))))
19612 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19613 (user-error "C-c C-c can do nothing useful at this location"))
19614 ;; For convenience: at the first line of a paragraph on the
19615 ;; same line as an item, apply function on that item instead.
19616 (when (eq type 'paragraph)
19617 (let ((parent (org-element-property :parent context)))
19618 (when (and (eq (org-element-type parent) 'item)
19619 (= (point-at-bol) (org-element-property :begin parent)))
19620 (setq context parent type 'item))))
19621 ;; Act according to type of element or object at point.
19622 (case type
19623 (clock (org-clock-update-time-maybe))
19624 (dynamic-block
19625 (save-excursion
19626 (goto-char (org-element-property :post-affiliated context))
19627 (org-update-dblock)))
19628 (footnote-definition
19629 (goto-char (org-element-property :post-affiliated context))
19630 (call-interactively 'org-footnote-action))
19631 (footnote-reference (call-interactively 'org-footnote-action))
19632 ((headline inlinetask)
19633 (save-excursion (goto-char (org-element-property :begin context))
19634 (call-interactively 'org-set-tags)))
19635 (item
19636 ;; At an item: a double C-u set checkbox to "[-]"
19637 ;; unconditionally, whereas a single one will toggle its
19638 ;; presence. Without an universal argument, if the item
19639 ;; has a checkbox, toggle it. Otherwise repair the list.
19640 (let* ((box (org-element-property :checkbox context))
19641 (struct (org-element-property :structure context))
19642 (old-struct (copy-tree struct))
19643 (parents (org-list-parents-alist struct))
19644 (prevs (org-list-prevs-alist struct))
19645 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19646 (org-list-set-checkbox
19647 (org-element-property :begin context) struct
19648 (cond ((equal arg '(16)) "[-]")
19649 ((and (not box) (equal arg '(4))) "[ ]")
19650 ((or (not box) (equal arg '(4))) nil)
19651 ((eq box 'on) "[ ]")
19652 (t "[X]")))
19653 ;; Mimic `org-list-write-struct' but with grabbing
19654 ;; a return value from `org-list-struct-fix-box'.
19655 (org-list-struct-fix-ind struct parents 2)
19656 (org-list-struct-fix-item-end struct)
19657 (org-list-struct-fix-bul struct prevs)
19658 (org-list-struct-fix-ind struct parents)
19659 (let ((block-item
19660 (org-list-struct-fix-box struct parents prevs orderedp)))
19661 (if (and box (equal struct old-struct))
19662 (if (equal arg '(16))
19663 (message "Checkboxes already reset")
19664 (user-error "Cannot toggle this checkbox: %s"
19665 (if (eq box 'on)
19666 "all subitems checked"
19667 "unchecked subitems")))
19668 (org-list-struct-apply-struct struct old-struct)
19669 (org-update-checkbox-count-maybe))
19670 (when block-item
19671 (message "Checkboxes were removed due to empty box at line %d"
19672 (org-current-line block-item))))))
19673 (keyword
19674 (let ((org-inhibit-startup-visibility-stuff t)
19675 (org-startup-align-all-tables nil))
19676 (when (boundp 'org-table-coordinate-overlays)
19677 (mapc 'delete-overlay org-table-coordinate-overlays)
19678 (setq org-table-coordinate-overlays nil))
19679 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19680 (message "Local setup has been refreshed"))
19681 (plain-list
19682 ;; At a plain list, with a double C-u argument, set
19683 ;; checkboxes of each item to "[-]", whereas a single one
19684 ;; will toggle their presence according to the state of the
19685 ;; first item in the list. Without an argument, repair the
19686 ;; list.
19687 (let* ((begin (org-element-property :contents-begin context))
19688 (struct (org-element-property :structure context))
19689 (old-struct (copy-tree struct))
19690 (first-box (save-excursion
19691 (goto-char begin)
19692 (looking-at org-list-full-item-re)
19693 (match-string-no-properties 3)))
19694 (new-box (cond ((equal arg '(16)) "[-]")
19695 ((equal arg '(4)) (unless first-box "[ ]"))
19696 ((equal first-box "[X]") "[ ]")
19697 (t "[X]"))))
19698 (cond
19699 (arg
19700 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19701 (org-list-get-all-items
19702 begin struct (org-list-prevs-alist struct))))
19703 ((and first-box (eq (point) begin))
19704 ;; For convenience, when point is at bol on the first
19705 ;; item of the list and no argument is provided, simply
19706 ;; toggle checkbox of that item, if any.
19707 (org-list-set-checkbox begin struct new-box)))
19708 (org-list-write-struct
19709 struct (org-list-parents-alist struct) old-struct)
19710 (org-update-checkbox-count-maybe)
19711 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19712 ((property-drawer node-property)
19713 (call-interactively 'org-property-action))
19714 ((radio-target target)
19715 (call-interactively 'org-update-radio-target-regexp))
19716 (statistics-cookie
19717 (call-interactively 'org-update-statistics-cookies))
19718 ((table table-cell table-row)
19719 ;; At a table, recalculate every field and align it. Also
19720 ;; send the table if necessary. If the table has
19721 ;; a `table.el' type, just give up. At a table row or
19722 ;; cell, maybe recalculate line but always align table.
19723 (if (eq (org-element-property :type context) 'table.el)
19724 (message "Use C-c ' to edit table.el tables")
19725 (let ((org-enable-table-editor t))
19726 (if (or (eq type 'table)
19727 ;; Check if point is at a TBLFM line.
19728 (and (eq type 'table-row)
19729 (= (point) (org-element-property :end context))))
19730 (save-excursion
19731 (goto-char (org-element-property :contents-begin context))
19732 (org-call-with-arg 'org-table-recalculate (or arg t))
19733 (orgtbl-send-table 'maybe))
19734 (org-table-maybe-eval-formula)
19735 (cond (arg (call-interactively 'org-table-recalculate))
19736 ((org-table-maybe-recalculate-line))
19737 (t (org-table-align)))))))
19738 (timestamp (org-timestamp-change 0 'day))
19739 (otherwise
19740 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19741 (user-error
19742 "C-c C-c can do nothing useful at this location")))))))))
19744 (defun org-mode-restart ()
19745 "Restart Org-mode, to scan again for special lines.
19746 Also updates the keyword regular expressions."
19747 (interactive)
19748 (org-mode)
19749 (message "Org-mode restarted"))
19751 (defun org-kill-note-or-show-branches ()
19752 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19753 (interactive)
19754 (if (not org-finish-function)
19755 (progn
19756 (hide-subtree)
19757 (call-interactively 'show-branches))
19758 (let ((org-note-abort t))
19759 (funcall org-finish-function))))
19761 (defun org-return (&optional indent)
19762 "Goto next table row or insert a newline.
19763 Calls `org-table-next-row' or `newline', depending on context.
19764 See the individual commands for more information."
19765 (interactive)
19766 (let (org-ts-what)
19767 (cond
19768 ((or (bobp) (org-in-src-block-p))
19769 (if indent (newline-and-indent) (newline)))
19770 ((org-at-table-p)
19771 (org-table-justify-field-maybe)
19772 (call-interactively 'org-table-next-row))
19773 ;; when `newline-and-indent' is called within a list, make sure
19774 ;; text moved stays inside the item.
19775 ((and (org-in-item-p) indent)
19776 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19777 (progn
19778 (save-match-data (newline))
19779 (org-indent-line-to (length (match-string 0))))
19780 (let ((ind (org-get-indentation)))
19781 (newline)
19782 (if (org-looking-back org-list-end-re)
19783 (org-indent-line)
19784 (org-indent-line-to ind)))))
19785 ((and org-return-follows-link
19786 (org-at-timestamp-p t)
19787 (not (eq org-ts-what 'after)))
19788 (org-follow-timestamp-link))
19789 ((and org-return-follows-link
19790 (let ((tprop (get-text-property (point) 'face)))
19791 (or (eq tprop 'org-link)
19792 (and (listp tprop) (memq 'org-link tprop)))))
19793 (call-interactively 'org-open-at-point))
19794 ((and (org-at-heading-p)
19795 (looking-at
19796 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19797 (org-show-entry)
19798 (end-of-line 1)
19799 (newline))
19800 (t (if indent (newline-and-indent) (newline))))))
19802 (defun org-return-indent ()
19803 "Goto next table row or insert a newline and indent.
19804 Calls `org-table-next-row' or `newline-and-indent', depending on
19805 context. See the individual commands for more information."
19806 (interactive)
19807 (org-return t))
19809 (defun org-ctrl-c-star ()
19810 "Compute table, or change heading status of lines.
19811 Calls `org-table-recalculate' or `org-toggle-heading',
19812 depending on context."
19813 (interactive)
19814 (cond
19815 ((org-at-table-p)
19816 (call-interactively 'org-table-recalculate))
19818 ;; Convert all lines in region to list items
19819 (call-interactively 'org-toggle-heading))))
19821 (defun org-ctrl-c-minus ()
19822 "Insert separator line in table or modify bullet status of line.
19823 Also turns a plain line or a region of lines into list items.
19824 Calls `org-table-insert-hline', `org-toggle-item', or
19825 `org-cycle-list-bullet', depending on context."
19826 (interactive)
19827 (cond
19828 ((org-at-table-p)
19829 (call-interactively 'org-table-insert-hline))
19830 ((org-region-active-p)
19831 (call-interactively 'org-toggle-item))
19832 ((org-in-item-p)
19833 (call-interactively 'org-cycle-list-bullet))
19835 (call-interactively 'org-toggle-item))))
19837 (defun org-toggle-item (arg)
19838 "Convert headings or normal lines to items, items to normal lines.
19839 If there is no active region, only the current line is considered.
19841 If the first non blank line in the region is an headline, convert
19842 all headlines to items, shifting text accordingly.
19844 If it is an item, convert all items to normal lines.
19846 If it is normal text, change region into an item. With a prefix
19847 argument ARG, change each line in region into an item."
19848 (interactive "P")
19849 (let ((shift-text
19850 (function
19851 ;; Shift text in current section to IND, from point to END.
19852 ;; The function leaves point to END line.
19853 (lambda (ind end)
19854 (let ((min-i 1000) (end (copy-marker end)))
19855 ;; First determine the minimum indentation (MIN-I) of
19856 ;; the text.
19857 (save-excursion
19858 (catch 'exit
19859 (while (< (point) end)
19860 (let ((i (org-get-indentation)))
19861 (cond
19862 ;; Skip blank lines and inline tasks.
19863 ((looking-at "^[ \t]*$"))
19864 ((looking-at org-outline-regexp-bol))
19865 ;; We can't find less than 0 indentation.
19866 ((zerop i) (throw 'exit (setq min-i 0)))
19867 ((< i min-i) (setq min-i i))))
19868 (forward-line))))
19869 ;; Then indent each line so that a line indented to
19870 ;; MIN-I becomes indented to IND. Ignore blank lines
19871 ;; and inline tasks in the process.
19872 (let ((delta (- ind min-i)))
19873 (while (< (point) end)
19874 (unless (or (looking-at "^[ \t]*$")
19875 (looking-at org-outline-regexp-bol))
19876 (org-indent-line-to (+ (org-get-indentation) delta)))
19877 (forward-line)))))))
19878 (skip-blanks
19879 (function
19880 ;; Return beginning of first non-blank line, starting from
19881 ;; line at POS.
19882 (lambda (pos)
19883 (save-excursion
19884 (goto-char pos)
19885 (skip-chars-forward " \r\t\n")
19886 (point-at-bol)))))
19887 beg end)
19888 ;; Determine boundaries of changes.
19889 (if (org-region-active-p)
19890 (setq beg (funcall skip-blanks (region-beginning))
19891 end (copy-marker (region-end)))
19892 (setq beg (funcall skip-blanks (point-at-bol))
19893 end (copy-marker (point-at-eol))))
19894 ;; Depending on the starting line, choose an action on the text
19895 ;; between BEG and END.
19896 (org-with-limited-levels
19897 (save-excursion
19898 (goto-char beg)
19899 (cond
19900 ;; Case 1. Start at an item: de-itemize. Note that it only
19901 ;; happens when a region is active: `org-ctrl-c-minus'
19902 ;; would call `org-cycle-list-bullet' otherwise.
19903 ((org-at-item-p)
19904 (while (< (point) end)
19905 (when (org-at-item-p)
19906 (skip-chars-forward " \t")
19907 (delete-region (point) (match-end 0)))
19908 (forward-line)))
19909 ;; Case 2. Start at an heading: convert to items.
19910 ((org-at-heading-p)
19911 (let* ((bul (org-list-bullet-string "-"))
19912 (bul-len (length bul))
19913 ;; Indentation of the first heading. It should be
19914 ;; relative to the indentation of its parent, if any.
19915 (start-ind (save-excursion
19916 (cond
19917 ((not org-adapt-indentation) 0)
19918 ((not (outline-previous-heading)) 0)
19919 (t (length (match-string 0))))))
19920 ;; Level of first heading. Further headings will be
19921 ;; compared to it to determine hierarchy in the list.
19922 (ref-level (org-reduced-level (org-outline-level))))
19923 (while (< (point) end)
19924 (let* ((level (org-reduced-level (org-outline-level)))
19925 (delta (max 0 (- level ref-level))))
19926 ;; If current headline is less indented than the first
19927 ;; one, set it as reference, in order to preserve
19928 ;; subtrees.
19929 (when (< level ref-level) (setq ref-level level))
19930 (replace-match bul t t)
19931 (org-indent-line-to (+ start-ind (* delta bul-len)))
19932 ;; Ensure all text down to END (or SECTION-END) belongs
19933 ;; to the newly created item.
19934 (let ((section-end (save-excursion
19935 (or (outline-next-heading) (point)))))
19936 (forward-line)
19937 (funcall shift-text
19938 (+ start-ind (* (1+ delta) bul-len))
19939 (min end section-end)))))))
19940 ;; Case 3. Normal line with ARG: turn each non-item line into
19941 ;; an item.
19942 (arg
19943 (while (< (point) end)
19944 (unless (or (org-at-heading-p) (org-at-item-p))
19945 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19946 (replace-match
19947 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19948 (forward-line)))
19949 ;; Case 4. Normal line without ARG: make the first line of
19950 ;; region an item, and shift indentation of others
19951 ;; lines to set them as item's body.
19952 (t (let* ((bul (org-list-bullet-string "-"))
19953 (bul-len (length bul))
19954 (ref-ind (org-get-indentation)))
19955 (skip-chars-forward " \t")
19956 (insert bul)
19957 (forward-line)
19958 (while (< (point) end)
19959 ;; Ensure that lines less indented than first one
19960 ;; still get included in item body.
19961 (funcall shift-text
19962 (+ ref-ind bul-len)
19963 (min end (save-excursion (or (outline-next-heading)
19964 (point)))))
19965 (forward-line)))))))))
19967 (defun org-toggle-heading (&optional nstars)
19968 "Convert headings to normal text, or items or text to headings.
19969 If there is no active region, only the current line is considered.
19971 With a \\[universal-argument] prefix, convert the whole list at
19972 point into heading.
19974 In a region:
19976 - If the first non blank line is an headline, remove the stars
19977 from all headlines in the region.
19979 - If it is a normal line turn each and every normal line (i.e. not an
19980 heading or an item) in the region into a heading.
19982 - If it is a plain list item, turn all plain list items into headings.
19984 When converting a line into a heading, the number of stars is chosen
19985 such that the lines become children of the current entry. However,
19986 when a prefix argument is given, its value determines the number of
19987 stars to add."
19988 (interactive "P")
19989 (let ((skip-blanks
19990 (function
19991 ;; Return beginning of first non-blank line, starting from
19992 ;; line at POS.
19993 (lambda (pos)
19994 (save-excursion
19995 (goto-char pos)
19996 (while (org-at-comment-p) (forward-line))
19997 (skip-chars-forward " \r\t\n")
19998 (point-at-bol)))))
19999 beg end toggled)
20000 ;; Determine boundaries of changes. If a universal prefix has
20001 ;; been given, put the list in a region. If region ends at a bol,
20002 ;; do not consider the last line to be in the region.
20004 (when (and current-prefix-arg (org-at-item-p))
20005 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20006 (org-mark-element))
20008 (if (org-region-active-p)
20009 (setq beg (funcall skip-blanks (region-beginning))
20010 end (copy-marker (save-excursion
20011 (goto-char (region-end))
20012 (if (bolp) (point) (point-at-eol)))))
20013 (setq beg (funcall skip-blanks (point-at-bol))
20014 end (copy-marker (point-at-eol))))
20015 ;; Ensure inline tasks don't count as headings.
20016 (org-with-limited-levels
20017 (save-excursion
20018 (goto-char beg)
20019 (cond
20020 ;; Case 1. Started at an heading: de-star headings.
20021 ((org-at-heading-p)
20022 (while (< (point) end)
20023 (when (org-at-heading-p t)
20024 (looking-at org-outline-regexp) (replace-match "")
20025 (setq toggled t))
20026 (forward-line)))
20027 ;; Case 2. Started at an item: change items into headlines.
20028 ;; One star will be added by `org-list-to-subtree'.
20029 ((org-at-item-p)
20030 (let* ((stars (make-string
20031 (if nstars
20032 ;; subtract the star that will be added again by
20033 ;; `org-list-to-subtree'
20034 (1- (prefix-numeric-value current-prefix-arg))
20035 (or (org-current-level) 0))
20036 ?*))
20037 (add-stars
20038 (cond (nstars "") ; stars from prefix only
20039 ((equal stars "") "") ; before first heading
20040 (org-odd-levels-only "*") ; inside heading, odd
20041 (t "")))) ; inside heading, oddeven
20042 (while (< (point) end)
20043 (when (org-at-item-p)
20044 ;; Pay attention to cases when region ends before list.
20045 (let* ((struct (org-list-struct))
20046 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20047 (save-restriction
20048 (narrow-to-region (point) list-end)
20049 (insert
20050 (org-list-to-subtree
20051 (org-list-parse-list t)
20052 '(:istart (concat stars add-stars (funcall get-stars depth))
20053 :icount (concat stars add-stars (funcall get-stars depth)))))))
20054 (setq toggled t))
20055 (forward-line))))
20056 ;; Case 3. Started at normal text: make every line an heading,
20057 ;; skipping headlines and items.
20058 (t (let* ((stars (make-string
20059 (if nstars
20060 (prefix-numeric-value current-prefix-arg)
20061 (or (org-current-level) 0))
20062 ?*))
20063 (add-stars
20064 (cond (nstars "") ; stars from prefix only
20065 ((equal stars "") "*") ; before first heading
20066 (org-odd-levels-only "**") ; inside heading, odd
20067 (t "*"))) ; inside heading, oddeven
20068 (rpl (concat stars add-stars " ")))
20069 (while (< (point) end)
20070 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20071 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20072 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20073 (forward-line)))))))
20074 (unless toggled (message "Cannot toggle heading from here"))))
20076 (defun org-meta-return (&optional arg)
20077 "Insert a new heading or wrap a region in a table.
20078 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20079 See the individual commands for more information."
20080 (interactive "P")
20081 (cond
20082 ((run-hook-with-args-until-success 'org-metareturn-hook))
20083 ((or (org-at-drawer-p) (org-at-property-p))
20084 (newline-and-indent))
20085 ((org-at-table-p)
20086 (call-interactively 'org-table-wrap-region))
20087 (t (call-interactively 'org-insert-heading))))
20089 ;;; Menu entries
20091 (defsubst org-in-subtree-not-table-p ()
20092 "Are we in a subtree and not in a table?"
20093 (and (not (org-before-first-heading-p))
20094 (not (org-at-table-p))))
20096 ;; Define the Org-mode menus
20097 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20098 '("Tbl"
20099 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20100 ["Next Field" org-cycle (org-at-table-p)]
20101 ["Previous Field" org-shifttab (org-at-table-p)]
20102 ["Next Row" org-return (org-at-table-p)]
20103 "--"
20104 ["Blank Field" org-table-blank-field (org-at-table-p)]
20105 ["Edit Field" org-table-edit-field (org-at-table-p)]
20106 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20107 "--"
20108 ("Column"
20109 ["Move Column Left" org-metaleft (org-at-table-p)]
20110 ["Move Column Right" org-metaright (org-at-table-p)]
20111 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20112 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20113 ("Row"
20114 ["Move Row Up" org-metaup (org-at-table-p)]
20115 ["Move Row Down" org-metadown (org-at-table-p)]
20116 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20117 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20118 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20119 "--"
20120 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20121 ("Rectangle"
20122 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20123 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20124 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20125 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20126 "--"
20127 ("Calculate"
20128 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20129 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20130 ["Edit Formulas" org-edit-special (org-at-table-p)]
20131 "--"
20132 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20133 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20134 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20135 "--"
20136 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20137 "--"
20138 ["Sum Column/Rectangle" org-table-sum
20139 (or (org-at-table-p) (org-region-active-p))]
20140 ["Which Column?" org-table-current-column (org-at-table-p)])
20141 ["Debug Formulas"
20142 org-table-toggle-formula-debugger
20143 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20144 ["Show Col/Row Numbers"
20145 org-table-toggle-coordinate-overlays
20146 :style toggle
20147 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20148 "--"
20149 ["Create" org-table-create (and (not (org-at-table-p))
20150 org-enable-table-editor)]
20151 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20152 ["Import from File" org-table-import (not (org-at-table-p))]
20153 ["Export to File" org-table-export (org-at-table-p)]
20154 "--"
20155 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20157 (easy-menu-define org-org-menu org-mode-map "Org menu"
20158 '("Org"
20159 ("Show/Hide"
20160 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20161 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20162 ["Sparse Tree..." org-sparse-tree t]
20163 ["Reveal Context" org-reveal t]
20164 ["Show All" show-all t]
20165 "--"
20166 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20167 "--"
20168 ["New Heading" org-insert-heading t]
20169 ("Navigate Headings"
20170 ["Up" outline-up-heading t]
20171 ["Next" outline-next-visible-heading t]
20172 ["Previous" outline-previous-visible-heading t]
20173 ["Next Same Level" outline-forward-same-level t]
20174 ["Previous Same Level" outline-backward-same-level t]
20175 "--"
20176 ["Jump" org-goto t])
20177 ("Edit Structure"
20178 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20179 "--"
20180 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20181 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20182 "--"
20183 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20184 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20185 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20186 "--"
20187 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20188 "--"
20189 ["Copy visible text" org-copy-visible t]
20190 "--"
20191 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20192 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20193 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20194 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20195 "--"
20196 ["Sort Region/Children" org-sort t]
20197 "--"
20198 ["Convert to odd levels" org-convert-to-odd-levels t]
20199 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20200 ("Editing"
20201 ["Emphasis..." org-emphasize t]
20202 ["Edit Source Example" org-edit-special t]
20203 "--"
20204 ["Footnote new/jump" org-footnote-action t]
20205 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20206 ("Archive"
20207 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20208 "--"
20209 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20210 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20211 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20213 "--"
20214 ("Hyperlinks"
20215 ["Store Link (Global)" org-store-link t]
20216 ["Find existing link to here" org-occur-link-in-agenda-files t]
20217 ["Insert Link" org-insert-link t]
20218 ["Follow Link" org-open-at-point t]
20219 "--"
20220 ["Next link" org-next-link t]
20221 ["Previous link" org-previous-link t]
20222 "--"
20223 ["Descriptive Links"
20224 org-toggle-link-display
20225 :style radio
20226 :selected org-descriptive-links
20228 ["Literal Links"
20229 org-toggle-link-display
20230 :style radio
20231 :selected (not org-descriptive-links)])
20232 "--"
20233 ("TODO Lists"
20234 ["TODO/DONE/-" org-todo t]
20235 ("Select keyword"
20236 ["Next keyword" org-shiftright (org-at-heading-p)]
20237 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20238 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20239 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20240 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20241 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20242 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20243 "--"
20244 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20245 :selected org-enforce-todo-dependencies :style toggle :active t]
20246 "Settings for tree at point"
20247 ["Do Children sequentially" org-toggle-ordered-property :style radio
20248 :selected (org-entry-get nil "ORDERED")
20249 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20250 ["Do Children parallel" org-toggle-ordered-property :style radio
20251 :selected (not (org-entry-get nil "ORDERED"))
20252 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20253 "--"
20254 ["Set Priority" org-priority t]
20255 ["Priority Up" org-shiftup t]
20256 ["Priority Down" org-shiftdown t]
20257 "--"
20258 ["Get news from all feeds" org-feed-update-all t]
20259 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20260 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20261 ("TAGS and Properties"
20262 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20263 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20264 "--"
20265 ["Set property" org-set-property (not (org-before-first-heading-p))]
20266 ["Column view of properties" org-columns t]
20267 ["Insert Column View DBlock" org-insert-columns-dblock t])
20268 ("Dates and Scheduling"
20269 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20270 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20271 ("Change Date"
20272 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20273 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20274 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20275 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20276 ["Compute Time Range" org-evaluate-time-range t]
20277 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20278 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20279 "--"
20280 ["Custom time format" org-toggle-time-stamp-overlays
20281 :style radio :selected org-display-custom-times]
20282 "--"
20283 ["Goto Calendar" org-goto-calendar t]
20284 ["Date from Calendar" org-date-from-calendar t]
20285 "--"
20286 ["Start/Restart Timer" org-timer-start t]
20287 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20288 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20289 ["Insert Timer String" org-timer t]
20290 ["Insert Timer Item" org-timer-item t])
20291 ("Logging work"
20292 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20293 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20294 ["Clock out" org-clock-out t]
20295 ["Clock cancel" org-clock-cancel t]
20296 "--"
20297 ["Mark as default task" org-clock-mark-default-task t]
20298 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20299 ["Goto running clock" org-clock-goto t]
20300 "--"
20301 ["Display times" org-clock-display t]
20302 ["Create clock table" org-clock-report t]
20303 "--"
20304 ["Record DONE time"
20305 (progn (setq org-log-done (not org-log-done))
20306 (message "Switching to %s will %s record a timestamp"
20307 (car org-done-keywords)
20308 (if org-log-done "automatically" "not")))
20309 :style toggle :selected org-log-done])
20310 "--"
20311 ["Agenda Command..." org-agenda t]
20312 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20313 ("File List for Agenda")
20314 ("Special views current file"
20315 ["TODO Tree" org-show-todo-tree t]
20316 ["Check Deadlines" org-check-deadlines t]
20317 ["Timeline" org-timeline t]
20318 ["Tags/Property tree" org-match-sparse-tree t])
20319 "--"
20320 ["Export/Publish..." org-export-dispatch t]
20321 ("LaTeX"
20322 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20323 :selected org-cdlatex-mode]
20324 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20325 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20326 ["Modify math symbol" org-cdlatex-math-modify
20327 (org-inside-LaTeX-fragment-p)]
20328 ["Insert citation" org-reftex-citation t]
20329 "--"
20330 ["Template for BEAMER" (progn (require 'ox-beamer)
20331 (org-insert-beamer-options-template)) t])
20332 "--"
20333 ("MobileOrg"
20334 ["Push Files and Views" org-mobile-push t]
20335 ["Get Captured and Flagged" org-mobile-pull t]
20336 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20337 "--"
20338 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20339 "--"
20340 ("Documentation"
20341 ["Show Version" org-version t]
20342 ["Info Documentation" org-info t])
20343 ("Customize"
20344 ["Browse Org Group" org-customize t]
20345 "--"
20346 ["Expand This Menu" org-create-customize-menu
20347 (fboundp 'customize-menu-create)])
20348 ["Send bug report" org-submit-bug-report t]
20349 "--"
20350 ("Refresh/Reload"
20351 ["Refresh setup current buffer" org-mode-restart t]
20352 ["Reload Org (after update)" org-reload t]
20353 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20356 (defun org-info (&optional node)
20357 "Read documentation for Org-mode in the info system.
20358 With optional NODE, go directly to that node."
20359 (interactive)
20360 (info (format "(org)%s" (or node ""))))
20362 ;;;###autoload
20363 (defun org-submit-bug-report ()
20364 "Submit a bug report on Org-mode via mail.
20366 Don't hesitate to report any problems or inaccurate documentation.
20368 If you don't have setup sending mail from (X)Emacs, please copy the
20369 output buffer into your mail program, as it gives us important
20370 information about your Org-mode version and configuration."
20371 (interactive)
20372 (require 'reporter)
20373 (org-load-modules-maybe)
20374 (org-require-autoloaded-modules)
20375 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20376 (reporter-submit-bug-report
20377 "emacs-orgmode@gnu.org"
20378 (org-version nil 'full)
20379 (let (list)
20380 (save-window-excursion
20381 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20382 (delete-other-windows)
20383 (erase-buffer)
20384 (insert "You are about to submit a bug report to the Org-mode mailing list.
20386 We would like to add your full Org-mode and Outline configuration to the
20387 bug report. This greatly simplifies the work of the maintainer and
20388 other experts on the mailing list.
20390 HOWEVER, some variables you have customized may contain private
20391 information. The names of customers, colleagues, or friends, might
20392 appear in the form of file names, tags, todo states, or search strings.
20393 If you answer yes to the prompt, you might want to check and remove
20394 such private information before sending the email.")
20395 (add-text-properties (point-min) (point-max) '(face org-warning))
20396 (when (yes-or-no-p "Include your Org-mode configuration ")
20397 (mapatoms
20398 (lambda (v)
20399 (and (boundp v)
20400 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20401 (or (and (symbol-value v)
20402 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20403 (and
20404 (get v 'custom-type) (get v 'standard-value)
20405 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20406 (push v list)))))
20407 (kill-buffer (get-buffer "*Warn about privacy*"))
20408 list))
20409 nil nil
20410 "Remember to cover the basics, that is, what you expected to happen and
20411 what in fact did happen. You don't know how to make a good report? See
20413 http://orgmode.org/manual/Feedback.html#Feedback
20415 Your bug report will be posted to the Org-mode mailing list.
20416 ------------------------------------------------------------------------")
20417 (save-excursion
20418 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20419 (replace-match "\\1Bug: \\3 [\\2]")))))
20422 (defun org-install-agenda-files-menu ()
20423 (let ((bl (buffer-list)))
20424 (save-excursion
20425 (while bl
20426 (set-buffer (pop bl))
20427 (if (derived-mode-p 'org-mode) (setq bl nil)))
20428 (when (derived-mode-p 'org-mode)
20429 (easy-menu-change
20430 '("Org") "File List for Agenda"
20431 (append
20432 (list
20433 ["Edit File List" (org-edit-agenda-file-list) t]
20434 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20435 ["Remove Current File from List" org-remove-file t]
20436 ["Cycle through agenda files" org-cycle-agenda-files t]
20437 ["Occur in all agenda files" org-occur-in-agenda-files t]
20438 "--")
20439 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20441 ;;;; Documentation
20443 (defun org-require-autoloaded-modules ()
20444 (interactive)
20445 (mapc 'require
20446 '(org-agenda org-archive org-attach org-clock org-colview org-id
20447 org-remember org-table org-timer)))
20449 ;;;###autoload
20450 (defun org-reload (&optional uncompiled)
20451 "Reload all org lisp files.
20452 With prefix arg UNCOMPILED, load the uncompiled versions."
20453 (interactive "P")
20454 (require 'loadhist)
20455 (let* ((org-dir (org-find-library-dir "org"))
20456 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20457 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20458 (remove-re (mapconcat 'identity
20459 (mapcar (lambda (f) (concat "^" f "$"))
20460 (list (if (featurep 'xemacs)
20461 "org-colview"
20462 "org-colview-xemacs")
20463 "org" "org-loaddefs" "org-version"))
20464 "\\|"))
20465 (feats (delete-dups
20466 (mapcar 'file-name-sans-extension
20467 (mapcar 'file-name-nondirectory
20468 (delq nil
20469 (mapcar 'feature-file
20470 features))))))
20471 (lfeat (append
20472 (sort
20473 (setq feats
20474 (delq nil (mapcar
20475 (lambda (f)
20476 (if (and (string-match feature-re f)
20477 (not (string-match remove-re f)))
20478 f nil))
20479 feats)))
20480 'string-lessp)
20481 (list "org-version" "org")))
20482 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20483 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20484 load-uncore load-misses)
20485 (setq load-misses
20486 (delq 't
20487 (mapcar (lambda (f)
20488 (or (org-load-noerror-mustsuffix (concat org-dir f))
20489 (and (string= org-dir contrib-dir)
20490 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20491 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20492 (add-to-list 'load-uncore f 'append)
20495 lfeat)))
20496 (if load-uncore
20497 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20498 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20499 (if load-misses
20500 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20501 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20502 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20504 ;;;###autoload
20505 (defun org-customize ()
20506 "Call the customize function with org as argument."
20507 (interactive)
20508 (org-load-modules-maybe)
20509 (org-require-autoloaded-modules)
20510 (customize-browse 'org))
20512 (defun org-create-customize-menu ()
20513 "Create a full customization menu for Org-mode, insert it into the menu."
20514 (interactive)
20515 (org-load-modules-maybe)
20516 (org-require-autoloaded-modules)
20517 (if (fboundp 'customize-menu-create)
20518 (progn
20519 (easy-menu-change
20520 '("Org") "Customize"
20521 `(["Browse Org group" org-customize t]
20522 "--"
20523 ,(customize-menu-create 'org)
20524 ["Set" Custom-set t]
20525 ["Save" Custom-save t]
20526 ["Reset to Current" Custom-reset-current t]
20527 ["Reset to Saved" Custom-reset-saved t]
20528 ["Reset to Standard Settings" Custom-reset-standard t]))
20529 (message "\"Org\"-menu now contains full customization menu"))
20530 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20532 ;;;; Miscellaneous stuff
20534 ;;; Generally useful functions
20536 (defun org-get-at-bol (property)
20537 "Get text property PROPERTY at beginning of line."
20538 (get-text-property (point-at-bol) property))
20540 (defun org-find-text-property-in-string (prop s)
20541 "Return the first non-nil value of property PROP in string S."
20542 (or (get-text-property 0 prop s)
20543 (get-text-property (or (next-single-property-change 0 prop s) 0)
20544 prop s)))
20546 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20547 "Display the given MESSAGE as a warning."
20548 (if (fboundp 'display-warning)
20549 (display-warning 'org message
20550 (if (featurep 'xemacs) 'warning :warning))
20551 (let ((buf (get-buffer-create "*Org warnings*")))
20552 (with-current-buffer buf
20553 (goto-char (point-max))
20554 (insert "Warning (Org): " message)
20555 (unless (bolp)
20556 (newline)))
20557 (display-buffer buf)
20558 (sit-for 0))))
20560 (defun org-eval (form)
20561 "Eval FORM and return result."
20562 (condition-case error
20563 (eval form)
20564 (error (format "%%![Error: %s]" error))))
20566 (defun org-in-clocktable-p ()
20567 "Check if the cursor is in a clocktable."
20568 (let ((pos (point)) start)
20569 (save-excursion
20570 (end-of-line 1)
20571 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20572 (setq start (match-beginning 0))
20573 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20574 (>= (match-end 0) pos)
20575 start))))
20577 (defun org-in-commented-line ()
20578 "Is point in a line starting with `#'?"
20579 (equal (char-after (point-at-bol)) ?#))
20581 (defun org-in-indented-comment-line ()
20582 "Is point in a line starting with `#' after some white space?"
20583 (save-excursion
20584 (save-match-data
20585 (goto-char (point-at-bol))
20586 (looking-at "[ \t]*#"))))
20588 (defun org-in-verbatim-emphasis ()
20589 (save-match-data
20590 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20592 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20593 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20594 (if (and marker (marker-buffer marker)
20595 (buffer-live-p (marker-buffer marker)))
20596 (progn
20597 (org-pop-to-buffer-same-window (marker-buffer marker))
20598 (if (or (> marker (point-max)) (< marker (point-min)))
20599 (widen))
20600 (goto-char marker)
20601 (org-show-context 'org-goto))
20602 (if bookmark
20603 (bookmark-jump bookmark)
20604 (error "Cannot find location"))))
20606 (defun org-quote-csv-field (s)
20607 "Quote field for inclusion in CSV material."
20608 (if (string-match "[\",]" s)
20609 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20612 (defun org-force-self-insert (N)
20613 "Needed to enforce self-insert under remapping."
20614 (interactive "p")
20615 (self-insert-command N))
20617 (defun org-string-width (s)
20618 "Compute width of string, ignoring invisible characters.
20619 This ignores character with invisibility property `org-link', and also
20620 characters with property `org-cwidth', because these will become invisible
20621 upon the next fontification round."
20622 (let (b l)
20623 (when (or (eq t buffer-invisibility-spec)
20624 (assq 'org-link buffer-invisibility-spec))
20625 (while (setq b (text-property-any 0 (length s)
20626 'invisible 'org-link s))
20627 (setq s (concat (substring s 0 b)
20628 (substring s (or (next-single-property-change
20629 b 'invisible s) (length s)))))))
20630 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20631 (setq s (concat (substring s 0 b)
20632 (substring s (or (next-single-property-change
20633 b 'org-cwidth s) (length s))))))
20634 (setq l (string-width s) b -1)
20635 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20636 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20639 (defun org-shorten-string (s maxlength)
20640 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20641 If the string is shorter or has length MAXLENGTH, just return the
20642 original string. If it is longer, the functions finds a space in the
20643 string, breaks this string off at that locations and adds three dots
20644 as ellipsis. Including the ellipsis, the string will not be longer
20645 than MAXLENGTH. If finding a good breaking point in the string does
20646 not work, the string is just chopped off in the middle of a word
20647 if necessary."
20648 (if (<= (length s) maxlength)
20650 (let* ((n (max (- maxlength 4) 1))
20651 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20652 (if (string-match re s)
20653 (concat (match-string 1 s) "...")
20654 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20656 (defun org-get-indentation (&optional line)
20657 "Get the indentation of the current line, interpreting tabs.
20658 When LINE is given, assume it represents a line and compute its indentation."
20659 (if line
20660 (if (string-match "^ *" (org-remove-tabs line))
20661 (match-end 0))
20662 (save-excursion
20663 (beginning-of-line 1)
20664 (skip-chars-forward " \t")
20665 (current-column))))
20667 (defun org-get-string-indentation (s)
20668 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20669 (let ((n -1) (i 0) (w tab-width) c)
20670 (catch 'exit
20671 (while (< (setq n (1+ n)) (length s))
20672 (setq c (aref s n))
20673 (cond ((= c ?\ ) (setq i (1+ i)))
20674 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20675 (t (throw 'exit t)))))
20678 (defun org-remove-tabs (s &optional width)
20679 "Replace tabulators in S with spaces.
20680 Assumes that s is a single line, starting in column 0."
20681 (setq width (or width tab-width))
20682 (while (string-match "\t" s)
20683 (setq s (replace-match
20684 (make-string
20685 (- (* width (/ (+ (match-beginning 0) width) width))
20686 (match-beginning 0)) ?\ )
20687 t t s)))
20690 (defun org-fix-indentation (line ind)
20691 "Fix indentation in LINE.
20692 IND is a cons cell with target and minimum indentation.
20693 If the current indentation in LINE is smaller than the minimum,
20694 leave it alone. If it is larger than ind, set it to the target."
20695 (let* ((l (org-remove-tabs line))
20696 (i (org-get-indentation l))
20697 (i1 (car ind)) (i2 (cdr ind)))
20698 (if (>= i i2) (setq l (substring line i2)))
20699 (if (> i1 0)
20700 (concat (make-string i1 ?\ ) l)
20701 l)))
20703 (defun org-remove-indentation (code &optional n)
20704 "Remove the maximum common indentation from the lines in CODE.
20705 N may optionally be the number of spaces to remove."
20706 (with-temp-buffer
20707 (insert code)
20708 (org-do-remove-indentation n)
20709 (buffer-string)))
20711 (defun org-do-remove-indentation (&optional n)
20712 "Remove the maximum common indentation from the buffer."
20713 (untabify (point-min) (point-max))
20714 (let ((min 10000) re)
20715 (if n
20716 (setq min n)
20717 (goto-char (point-min))
20718 (while (re-search-forward "^ *[^ \n]" nil t)
20719 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20720 (unless (or (= min 0) (= min 10000))
20721 (setq re (format "^ \\{%d\\}" min))
20722 (goto-char (point-min))
20723 (while (re-search-forward re nil t)
20724 (replace-match "")
20725 (end-of-line 1))
20726 min)))
20728 (defun org-fill-template (template alist)
20729 "Find each %key of ALIST in TEMPLATE and replace it."
20730 (let ((case-fold-search nil)
20731 entry key value)
20732 (setq alist (sort (copy-sequence alist)
20733 (lambda (a b) (< (length (car a)) (length (car b))))))
20734 (while (setq entry (pop alist))
20735 (setq template
20736 (replace-regexp-in-string
20737 (concat "%" (regexp-quote (car entry)))
20738 (or (cdr entry) "") template t t)))
20739 template))
20741 (defun org-base-buffer (buffer)
20742 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20743 (if (not buffer)
20744 buffer
20745 (or (buffer-base-buffer buffer)
20746 buffer)))
20748 (defun org-trim (s)
20749 "Remove whitespace at beginning and end of string."
20750 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20751 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20754 (defun org-wrap (string &optional width lines)
20755 "Wrap string to either a number of lines, or a width in characters.
20756 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20757 that costs. If there is a word longer than WIDTH, the text is actually
20758 wrapped to the length of that word.
20759 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20760 many lines, whatever width that takes.
20761 The return value is a list of lines, without newlines at the end."
20762 (let* ((words (org-split-string string "[ \t\n]+"))
20763 (maxword (apply 'max (mapcar 'org-string-width words)))
20764 w ll)
20765 (cond (width
20766 (org-do-wrap words (max maxword width)))
20767 (lines
20768 (setq w maxword)
20769 (setq ll (org-do-wrap words maxword))
20770 (if (<= (length ll) lines)
20772 (setq ll words)
20773 (while (> (length ll) lines)
20774 (setq w (1+ w))
20775 (setq ll (org-do-wrap words w)))
20776 ll))
20777 (t (error "Cannot wrap this")))))
20779 (defun org-do-wrap (words width)
20780 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20781 (let (lines line)
20782 (while words
20783 (setq line (pop words))
20784 (while (and words (< (+ (length line) (length (car words))) width))
20785 (setq line (concat line " " (pop words))))
20786 (setq lines (push line lines)))
20787 (nreverse lines)))
20789 (defun org-split-string (string &optional separators)
20790 "Splits STRING into substrings at SEPARATORS.
20791 No empty strings are returned if there are matches at the beginning
20792 and end of string."
20793 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20794 (start 0)
20795 notfirst
20796 (list nil))
20797 (while (and (string-match rexp string
20798 (if (and notfirst
20799 (= start (match-beginning 0))
20800 (< start (length string)))
20801 (1+ start) start))
20802 (< (match-beginning 0) (length string)))
20803 (setq notfirst t)
20804 (or (eq (match-beginning 0) 0)
20805 (and (eq (match-beginning 0) (match-end 0))
20806 (eq (match-beginning 0) start))
20807 (setq list
20808 (cons (substring string start (match-beginning 0))
20809 list)))
20810 (setq start (match-end 0)))
20811 (or (eq start (length string))
20812 (setq list
20813 (cons (substring string start)
20814 list)))
20815 (nreverse list)))
20817 (defun org-quote-vert (s)
20818 "Replace \"|\" with \"\\vert\"."
20819 (while (string-match "|" s)
20820 (setq s (replace-match "\\vert" t t s)))
20823 (defun org-uuidgen-p (s)
20824 "Is S an ID created by UUIDGEN?"
20825 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20827 (defun org-in-src-block-p (&optional inside)
20828 "Whether point is in a code source block.
20829 When INSIDE is non-nil, don't consider we are within a src block
20830 when point is at #+BEGIN_SRC or #+END_SRC."
20831 (let ((case-fold-search t) ov)
20832 (or (and (setq ov (overlays-at (point)))
20833 (memq 'org-block-background
20834 (overlay-properties (car ov))))
20835 (and (not inside)
20836 (save-match-data
20837 (save-excursion
20838 (beginning-of-line)
20839 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20841 (defun org-context ()
20842 "Return a list of contexts of the current cursor position.
20843 If several contexts apply, all are returned.
20844 Each context entry is a list with a symbol naming the context, and
20845 two positions indicating start and end of the context. Possible
20846 contexts are:
20848 :headline anywhere in a headline
20849 :headline-stars on the leading stars in a headline
20850 :todo-keyword on a TODO keyword (including DONE) in a headline
20851 :tags on the TAGS in a headline
20852 :priority on the priority cookie in a headline
20853 :item on the first line of a plain list item
20854 :item-bullet on the bullet/number of a plain list item
20855 :checkbox on the checkbox in a plain list item
20856 :table in an org-mode table
20857 :table-special on a special filed in a table
20858 :table-table in a table.el table
20859 :clocktable in a clocktable
20860 :src-block in a source block
20861 :link on a hyperlink
20862 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20863 :target on a <<target>>
20864 :radio-target on a <<<radio-target>>>
20865 :latex-fragment on a LaTeX fragment
20866 :latex-preview on a LaTeX fragment with overlaid preview image
20868 This function expects the position to be visible because it uses font-lock
20869 faces as a help to recognize the following contexts: :table-special, :link,
20870 and :keyword."
20871 (let* ((f (get-text-property (point) 'face))
20872 (faces (if (listp f) f (list f)))
20873 (case-fold-search t)
20874 (p (point)) clist o)
20875 ;; First the large context
20876 (cond
20877 ((org-at-heading-p t)
20878 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20879 (when (progn
20880 (beginning-of-line 1)
20881 (looking-at org-todo-line-tags-regexp))
20882 (push (org-point-in-group p 1 :headline-stars) clist)
20883 (push (org-point-in-group p 2 :todo-keyword) clist)
20884 (push (org-point-in-group p 4 :tags) clist))
20885 (goto-char p)
20886 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20887 (if (looking-at "\\[#[A-Z0-9]\\]")
20888 (push (org-point-in-group p 0 :priority) clist)))
20890 ((org-at-item-p)
20891 (push (org-point-in-group p 2 :item-bullet) clist)
20892 (push (list :item (point-at-bol)
20893 (save-excursion (org-end-of-item) (point)))
20894 clist)
20895 (and (org-at-item-checkbox-p)
20896 (push (org-point-in-group p 0 :checkbox) clist)))
20898 ((org-at-table-p)
20899 (push (list :table (org-table-begin) (org-table-end)) clist)
20900 (if (memq 'org-formula faces)
20901 (push (list :table-special
20902 (previous-single-property-change p 'face)
20903 (next-single-property-change p 'face)) clist)))
20904 ((org-at-table-p 'any)
20905 (push (list :table-table) clist)))
20906 (goto-char p)
20908 (let ((case-fold-search t))
20909 ;; New the "medium" contexts: clocktables, source blocks
20910 (cond ((org-in-clocktable-p)
20911 (push (list :clocktable
20912 (and (or (looking-at "#\\+BEGIN: clocktable")
20913 (search-backward "#+BEGIN: clocktable" nil t))
20914 (match-beginning 0))
20915 (and (re-search-forward "#\\+END:?" nil t)
20916 (match-end 0))) clist))
20917 ((org-in-src-block-p)
20918 (push (list :src-block
20919 (and (or (looking-at "#\\+BEGIN_SRC")
20920 (search-backward "#+BEGIN_SRC" nil t))
20921 (match-beginning 0))
20922 (and (search-forward "#+END_SRC" nil t)
20923 (match-beginning 0))) clist))))
20924 (goto-char p)
20926 ;; Now the small context
20927 (cond
20928 ((org-at-timestamp-p)
20929 (push (org-point-in-group p 0 :timestamp) clist))
20930 ((memq 'org-link faces)
20931 (push (list :link
20932 (previous-single-property-change p 'face)
20933 (next-single-property-change p 'face)) clist))
20934 ((memq 'org-special-keyword faces)
20935 (push (list :keyword
20936 (previous-single-property-change p 'face)
20937 (next-single-property-change p 'face)) clist))
20938 ((org-at-target-p)
20939 (push (org-point-in-group p 0 :target) clist)
20940 (goto-char (1- (match-beginning 0)))
20941 (if (looking-at org-radio-target-regexp)
20942 (push (org-point-in-group p 0 :radio-target) clist))
20943 (goto-char p))
20944 ((setq o (car (delq nil
20945 (mapcar
20946 (lambda (x)
20947 (if (memq x org-latex-fragment-image-overlays) x))
20948 (overlays-at (point))))))
20949 (push (list :latex-fragment
20950 (overlay-start o) (overlay-end o)) clist)
20951 (push (list :latex-preview
20952 (overlay-start o) (overlay-end o)) clist))
20953 ((org-inside-LaTeX-fragment-p)
20954 ;; FIXME: positions wrong.
20955 (push (list :latex-fragment (point) (point)) clist)))
20957 (setq clist (nreverse (delq nil clist)))
20958 clist))
20960 ;; FIXME: Compare with at-regexp-p Do we need both?
20961 (defun org-in-regexp (re &optional nlines visually)
20962 "Check if point is inside a match of regexp.
20963 Normally only the current line is checked, but you can include NLINES extra
20964 lines both before and after point into the search.
20965 If VISUALLY is set, require that the cursor is not after the match but
20966 really on, so that the block visually is on the match."
20967 (catch 'exit
20968 (let ((pos (point))
20969 (eol (point-at-eol (+ 1 (or nlines 0))))
20970 (inc (if visually 1 0)))
20971 (save-excursion
20972 (beginning-of-line (- 1 (or nlines 0)))
20973 (while (re-search-forward re eol t)
20974 (if (and (<= (match-beginning 0) pos)
20975 (>= (+ inc (match-end 0)) pos))
20976 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20978 (defun org-at-regexp-p (regexp)
20979 "Is point inside a match of REGEXP in the current line?"
20980 (catch 'exit
20981 (save-excursion
20982 (let ((pos (point)) (end (point-at-eol)))
20983 (beginning-of-line 1)
20984 (while (re-search-forward regexp end t)
20985 (if (and (<= (match-beginning 0) pos)
20986 (>= (match-end 0) pos))
20987 (throw 'exit t)))
20988 nil))))
20990 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20991 "Non-nil when point is between matches of START-RE and END-RE.
20993 Also return a non-nil value when point is on one of the matches.
20995 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20996 buffer positions. Default values are the positions of headlines
20997 surrounding the point.
20999 The functions returns a cons cell whose car (resp. cdr) is the
21000 position before START-RE (resp. after END-RE)."
21001 (save-match-data
21002 (let ((pos (point))
21003 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21004 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21005 beg end)
21006 (save-excursion
21007 ;; Point is on a block when on START-RE or if START-RE can be
21008 ;; found before it...
21009 (and (or (org-at-regexp-p start-re)
21010 (re-search-backward start-re limit-up t))
21011 (setq beg (match-beginning 0))
21012 ;; ... and END-RE after it...
21013 (goto-char (match-end 0))
21014 (re-search-forward end-re limit-down t)
21015 (> (setq end (match-end 0)) pos)
21016 ;; ... without another START-RE in-between.
21017 (goto-char (match-beginning 0))
21018 (not (re-search-backward start-re (1+ beg) t))
21019 ;; Return value.
21020 (cons beg end))))))
21022 (defun org-in-block-p (names)
21023 "Non-nil when point belongs to a block whose name belongs to NAMES.
21025 NAMES is a list of strings containing names of blocks.
21027 Return first block name matched, or nil. Beware that in case of
21028 nested blocks, the returned name may not belong to the closest
21029 block from point."
21030 (save-match-data
21031 (catch 'exit
21032 (let ((case-fold-search t)
21033 (lim-up (save-excursion (outline-previous-heading)))
21034 (lim-down (save-excursion (outline-next-heading))))
21035 (mapc (lambda (name)
21036 (let ((n (regexp-quote name)))
21037 (when (org-between-regexps-p
21038 (concat "^[ \t]*#\\+begin_" n)
21039 (concat "^[ \t]*#\\+end_" n)
21040 lim-up lim-down)
21041 (throw 'exit n))))
21042 names))
21043 nil)))
21045 (defun org-occur-in-agenda-files (regexp &optional nlines)
21046 "Call `multi-occur' with buffers for all agenda files."
21047 (interactive "sOrg-files matching: \np")
21048 (let* ((files (org-agenda-files))
21049 (tnames (mapcar 'file-truename files))
21050 (extra org-agenda-text-search-extra-files)
21052 (when (eq (car extra) 'agenda-archives)
21053 (setq extra (cdr extra))
21054 (setq files (org-add-archive-files files)))
21055 (while (setq f (pop extra))
21056 (unless (member (file-truename f) tnames)
21057 (add-to-list 'files f 'append)
21058 (add-to-list 'tnames (file-truename f) 'append)))
21059 (multi-occur
21060 (mapcar (lambda (x)
21061 (with-current-buffer
21062 (or (get-file-buffer x) (find-file-noselect x))
21063 (widen)
21064 (current-buffer)))
21065 files)
21066 regexp)))
21068 (if (boundp 'occur-mode-find-occurrence-hook)
21069 ;; Emacs 23
21070 (add-hook 'occur-mode-find-occurrence-hook
21071 (lambda ()
21072 (when (derived-mode-p 'org-mode)
21073 (org-reveal))))
21074 ;; Emacs 22
21075 (defadvice occur-mode-goto-occurrence
21076 (after org-occur-reveal activate)
21077 (and (derived-mode-p 'org-mode) (org-reveal)))
21078 (defadvice occur-mode-goto-occurrence-other-window
21079 (after org-occur-reveal activate)
21080 (and (derived-mode-p 'org-mode) (org-reveal)))
21081 (defadvice occur-mode-display-occurrence
21082 (after org-occur-reveal activate)
21083 (when (derived-mode-p 'org-mode)
21084 (let ((pos (occur-mode-find-occurrence)))
21085 (with-current-buffer (marker-buffer pos)
21086 (save-excursion
21087 (goto-char pos)
21088 (org-reveal)))))))
21090 (defun org-occur-link-in-agenda-files ()
21091 "Create a link and search for it in the agendas.
21092 The link is not stored in `org-stored-links', it is just created
21093 for the search purpose."
21094 (interactive)
21095 (let ((link (condition-case nil
21096 (org-store-link nil)
21097 (error "Unable to create a link to here"))))
21098 (org-occur-in-agenda-files (regexp-quote link))))
21100 (defun org-uniquify (list)
21101 "Remove duplicate elements from LIST."
21102 (let (res)
21103 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21104 res))
21106 (defun org-delete-all (elts list)
21107 "Remove all elements in ELTS from LIST."
21108 (while elts
21109 (setq list (delete (pop elts) list)))
21110 list)
21112 (defun org-count (cl-item cl-seq)
21113 "Count the number of occurrences of ITEM in SEQ.
21114 Taken from `count' in cl-seq.el with all keyword arguments removed."
21115 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21116 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21117 (while (< cl-start cl-end)
21118 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21119 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21120 (setq cl-start (1+ cl-start)))
21121 cl-count))
21123 (defun org-remove-if (predicate seq)
21124 "Remove everything from SEQ that fulfills PREDICATE."
21125 (let (res e)
21126 (while seq
21127 (setq e (pop seq))
21128 (if (not (funcall predicate e)) (push e res)))
21129 (nreverse res)))
21131 (defun org-remove-if-not (predicate seq)
21132 "Remove everything from SEQ that does not fulfill PREDICATE."
21133 (let (res e)
21134 (while seq
21135 (setq e (pop seq))
21136 (if (funcall predicate e) (push e res)))
21137 (nreverse res)))
21139 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21140 "Reduce two-argument FUNCTION across SEQ.
21141 Taken from `reduce' in cl-seq.el with all keyword arguments but
21142 \":initial-value\" removed."
21143 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21144 (cadr (memq :initial-value cl-keys)))
21145 (cl-seq (pop cl-seq))
21146 (t (funcall cl-func)))))
21147 (while cl-seq
21148 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21149 cl-accum))
21151 (defun org-back-over-empty-lines ()
21152 "Move backwards over whitespace, to the beginning of the first empty line.
21153 Returns the number of empty lines passed."
21154 (let ((pos (point)))
21155 (if (cdr (assoc 'heading org-blank-before-new-entry))
21156 (skip-chars-backward " \t\n\r")
21157 (unless (eobp)
21158 (forward-line -1)))
21159 (beginning-of-line 2)
21160 (goto-char (min (point) pos))
21161 (count-lines (point) pos)))
21163 (defun org-skip-whitespace ()
21164 (skip-chars-forward " \t\n\r"))
21166 (defun org-point-in-group (point group &optional context)
21167 "Check if POINT is in match-group GROUP.
21168 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21169 match. If the match group does not exist or point is not inside it,
21170 return nil."
21171 (and (match-beginning group)
21172 (>= point (match-beginning group))
21173 (<= point (match-end group))
21174 (if context
21175 (list context (match-beginning group) (match-end group))
21176 t)))
21178 (defun org-switch-to-buffer-other-window (&rest args)
21179 "Switch to buffer in a second window on the current frame.
21180 In particular, do not allow pop-up frames.
21181 Returns the newly created buffer."
21182 (org-no-popups
21183 (apply 'switch-to-buffer-other-window args)))
21185 (defun org-combine-plists (&rest plists)
21186 "Create a single property list from all plists in PLISTS.
21187 The process starts by copying the first list, and then setting properties
21188 from the other lists. Settings in the last list are the most significant
21189 ones and overrule settings in the other lists."
21190 (let ((rtn (copy-sequence (pop plists)))
21191 p v ls)
21192 (while plists
21193 (setq ls (pop plists))
21194 (while ls
21195 (setq p (pop ls) v (pop ls))
21196 (setq rtn (plist-put rtn p v))))
21197 rtn))
21199 (defun org-replace-escapes (string table)
21200 "Replace %-escapes in STRING with values in TABLE.
21201 TABLE is an association list with keys like \"%a\" and string values.
21202 The sequences in STRING may contain normal field width and padding information,
21203 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21204 so values can contain further %-escapes if they are define later in TABLE."
21205 (let ((tbl (copy-alist table))
21206 (case-fold-search nil)
21207 (pchg 0)
21208 e re rpl)
21209 (while (setq e (pop tbl))
21210 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21211 (when (and (cdr e) (string-match re (cdr e)))
21212 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21213 (safe "SREF"))
21214 (add-text-properties 0 3 (list 'sref sref) safe)
21215 (setcdr e (replace-match safe t t (cdr e)))))
21216 (while (string-match re string)
21217 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21218 (cdr e)))
21219 (setq string (replace-match rpl t t string))))
21220 (while (setq pchg (next-property-change pchg string))
21221 (let ((sref (get-text-property pchg 'sref string)))
21222 (when (and sref (string-match "SREF" string pchg))
21223 (setq string (replace-match sref t t string)))))
21224 string))
21226 (defun org-sublist (list start end)
21227 "Return a section of LIST, from START to END.
21228 Counting starts at 1."
21229 (let (rtn (c start))
21230 (setq list (nthcdr (1- start) list))
21231 (while (and list (<= c end))
21232 (push (pop list) rtn)
21233 (setq c (1+ c)))
21234 (nreverse rtn)))
21236 (defun org-find-base-buffer-visiting (file)
21237 "Like `find-buffer-visiting' but always return the base buffer and
21238 not an indirect buffer."
21239 (let ((buf (or (get-file-buffer file)
21240 (find-buffer-visiting file))))
21241 (if buf
21242 (or (buffer-base-buffer buf) buf)
21243 nil)))
21245 (defun org-image-file-name-regexp (&optional extensions)
21246 "Return regexp matching the file names of images.
21247 If EXTENSIONS is given, only match these."
21248 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21249 (image-file-name-regexp)
21250 (let ((image-file-name-extensions
21251 (or extensions
21252 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21253 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21254 (concat "\\."
21255 (regexp-opt (nconc (mapcar 'upcase
21256 image-file-name-extensions)
21257 image-file-name-extensions)
21259 "\\'"))))
21261 (defun org-file-image-p (file &optional extensions)
21262 "Return non-nil if FILE is an image."
21263 (save-match-data
21264 (string-match (org-image-file-name-regexp extensions) file)))
21266 (defun org-get-cursor-date (&optional with-time)
21267 "Return the date at cursor in as a time.
21268 This works in the calendar and in the agenda, anywhere else it just
21269 returns the current time.
21270 If WITH-TIME is non-nil, returns the time of the event at point (in
21271 the agenda) or the current time of the day."
21272 (let (date day defd tp tm hod mod)
21273 (when with-time
21274 (setq tp (get-text-property (point) 'time))
21275 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21276 (setq hod (string-to-number (match-string 1 tp))
21277 mod (string-to-number (match-string 2 tp))))
21278 (or tp (setq hod (nth 2 (decode-time (current-time)))
21279 mod (nth 1 (decode-time (current-time))))))
21280 (cond
21281 ((eq major-mode 'calendar-mode)
21282 (setq date (calendar-cursor-to-date)
21283 defd (encode-time 0 (or mod 0) (or hod 0)
21284 (nth 1 date) (nth 0 date) (nth 2 date))))
21285 ((eq major-mode 'org-agenda-mode)
21286 (setq day (get-text-property (point) 'day))
21287 (if day
21288 (setq date (calendar-gregorian-from-absolute day)
21289 defd (encode-time 0 (or mod 0) (or hod 0)
21290 (nth 1 date) (nth 0 date) (nth 2 date))))))
21291 (or defd (current-time))))
21293 (defun org-mark-subtree (&optional up)
21294 "Mark the current subtree.
21295 This puts point at the start of the current subtree, and mark at
21296 the end. If a numeric prefix UP is given, move up into the
21297 hierarchy of headlines by UP levels before marking the subtree."
21298 (interactive "P")
21299 (org-with-limited-levels
21300 (cond ((org-at-heading-p) (beginning-of-line))
21301 ((org-before-first-heading-p) (error "Not in a subtree"))
21302 (t (outline-previous-visible-heading 1))))
21303 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21304 (if (org-called-interactively-p 'any)
21305 (call-interactively 'org-mark-element)
21306 (org-mark-element)))
21309 ;;; Macros
21311 ;; Macros are expanded with `org-macro-replace-all', which relies
21312 ;; internally on `org-macro-expand'.
21314 ;; Default templates for expansion are stored in the buffer-local
21315 ;; variable `org-macro-templates'. This variable is updated by
21316 ;; `org-macro-initialize-templates'.
21318 ;; Along with macros defined through #+MACRO: keyword, default
21319 ;; templates include the following hard-coded macros:
21320 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21321 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21323 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21324 ;; {{{title}}} will also be provided.
21327 (defvar org-macro-templates nil
21328 "Alist containing all macro templates in current buffer.
21329 Associations are in the shape of (NAME . TEMPLATE) where NAME
21330 stands for macro's name and template for its replacement value,
21331 both as strings. This is an internal variable. Do not set it
21332 directly, use instead:
21334 #+MACRO: name template")
21335 (make-variable-buffer-local 'org-macro-templates)
21337 (defun org-macro-expand (macro templates)
21338 "Return expanded MACRO, as a string.
21339 MACRO is an object, obtained, for example, with
21340 `org-element-context'. TEMPLATES is an alist of templates used
21341 for expansion. See `org-macro-templates' for a buffer-local
21342 default value. Return nil if no template was found."
21343 (let ((template
21344 ;; Macro names are case-insensitive.
21345 (cdr (assoc-string (org-element-property :key macro) templates t))))
21346 (when template
21347 (let ((value (replace-regexp-in-string
21348 "\\$[0-9]+"
21349 (lambda (arg)
21350 (or (nth (1- (string-to-number (substring arg 1)))
21351 (org-element-property :args macro))
21352 ;; No argument provided: remove
21353 ;; place-holder.
21354 ""))
21355 template)))
21356 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21357 (when (string-match "\\`(eval\\>" value)
21358 (setq value (eval (read value))))
21359 ;; Return string.
21360 (format "%s" (or value ""))))))
21362 (defun org-macro-replace-all (templates)
21363 "Replace all macros in current buffer by their expansion.
21364 TEMPLATES is an alist of templates used for expansion. See
21365 `org-macro-templates' for a buffer-local default value."
21366 (save-excursion
21367 (goto-char (point-min))
21368 (let (record)
21369 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21370 (let ((object (org-element-context)))
21371 (when (eq (org-element-type object) 'macro)
21372 (let* ((value (org-macro-expand object templates))
21373 (begin (org-element-property :begin object))
21374 (signature (list begin
21375 object
21376 (org-element-property :args object))))
21377 ;; Avoid circular dependencies by checking if the same
21378 ;; macro with the same arguments is expanded at the same
21379 ;; position twice.
21380 (if (member signature record)
21381 (error "Circular macro expansion: %s"
21382 (org-element-property :key object))
21383 (when value
21384 (push signature record)
21385 (delete-region
21386 begin
21387 ;; Preserve white spaces after the macro.
21388 (progn (goto-char (org-element-property :end object))
21389 (skip-chars-backward " \t")
21390 (point)))
21391 ;; Leave point before replacement in case of recursive
21392 ;; expansions.
21393 (save-excursion (insert value)))))))))))
21395 (defun org-macro-initialize-templates ()
21396 "Collect macro templates defined in current buffer.
21397 Templates are stored in buffer-local variable
21398 `org-macro-templates'. In addition to buffer-defined macros, the
21399 function installs the following ones: \"property\",
21400 \"time\". and, if the buffer is associated to a file,
21401 \"input-file\" and \"modification-time\"."
21402 (let ((case-fold-search t)
21403 (set-template
21404 (lambda (cell)
21405 ;; Add CELL to `org-macro-templates' if there's no
21406 ;; association matching its name already. Otherwise,
21407 ;; replace old association with the new one in that
21408 ;; variable.
21409 (let ((old-template (assoc (car cell) org-macro-templates)))
21410 (if old-template (setcdr old-template (cdr cell))
21411 (push cell org-macro-templates))))))
21412 ;; Install buffer-local macros.
21413 (org-with-wide-buffer
21414 (goto-char (point-min))
21415 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21416 (let ((element (org-element-at-point)))
21417 (when (eq (org-element-type element) 'keyword)
21418 (let ((value (org-element-property :value element)))
21419 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21420 (funcall set-template
21421 (cons (match-string 1 value)
21422 (or (match-string 2 value) "")))))))))
21423 ;; Install hard-coded macros.
21424 (mapc (lambda (cell) (funcall set-template cell))
21425 (list
21426 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21427 (cons "time" "(eval (format-time-string \"$1\"))")))
21428 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21429 (when (and visited-file (file-exists-p visited-file))
21430 (mapc (lambda (cell) (funcall set-template cell))
21431 (list
21432 (cons "input-file" (file-name-nondirectory visited-file))
21433 (cons "modification-time"
21434 (format "(eval (format-time-string \"$1\" '%s))"
21435 (prin1-to-string
21436 (nth 5 (file-attributes visited-file)))))))))))
21439 ;;; Indentation
21441 (defun org-indent-line ()
21442 "Indent line depending on context."
21443 (interactive)
21444 (let* ((pos (point))
21445 (itemp (org-at-item-p))
21446 (case-fold-search t)
21447 (org-drawer-regexp (or org-drawer-regexp "\000"))
21448 (inline-task-p (and (featurep 'org-inlinetask)
21449 (org-inlinetask-in-task-p)))
21450 (inline-re (and inline-task-p
21451 (org-inlinetask-outline-regexp)))
21452 column)
21453 (if (and orgstruct-is-++ (eq pos (point)))
21454 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21455 (indent-according-to-mode))
21456 (beginning-of-line 1)
21457 (cond
21458 ;; Headings
21459 ((looking-at org-outline-regexp) (setq column 0))
21460 ;; Footnote definition
21461 ((looking-at org-footnote-definition-re) (setq column 0))
21462 ;; Literal examples
21463 ((looking-at "[ \t]*:\\( \\|$\\)")
21464 (setq column (org-get-indentation))) ; do nothing
21465 ;; Lists
21466 ((ignore-errors (goto-char (org-in-item-p)))
21467 (setq column (if itemp
21468 (org-get-indentation)
21469 (org-list-item-body-column (point))))
21470 (goto-char pos))
21471 ;; Drawers
21472 ((and (looking-at "[ \t]*:END:")
21473 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21474 (save-excursion
21475 (goto-char (1- (match-beginning 1)))
21476 (setq column (current-column))))
21477 ;; Special blocks
21478 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21479 (save-excursion
21480 (re-search-backward
21481 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21482 (setq column (org-get-indentation (match-string 0))))
21483 ((and (not (looking-at "[ \t]*#\\+begin_"))
21484 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21485 (save-excursion
21486 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21487 (setq column
21488 (cond ((equal (downcase (match-string 1)) "src")
21489 ;; src blocks: let `org-edit-src-exit' handle them
21490 (org-get-indentation))
21491 ((equal (downcase (match-string 1)) "example")
21492 (max (org-get-indentation)
21493 (org-get-indentation (match-string 0))))
21495 (org-get-indentation (match-string 0))))))
21496 ;; This line has nothing special, look at the previous relevant
21497 ;; line to compute indentation
21499 (beginning-of-line 0)
21500 (while (and (not (bobp))
21501 (not (looking-at org-table-line-regexp))
21502 (not (looking-at org-drawer-regexp))
21503 ;; When point started in an inline task, do not move
21504 ;; above task starting line.
21505 (not (and inline-task-p (looking-at inline-re)))
21506 ;; Skip drawers, blocks, empty lines, verbatim,
21507 ;; comments, tables, footnotes definitions, lists,
21508 ;; inline tasks.
21509 (or (and (looking-at "[ \t]*:END:")
21510 (re-search-backward org-drawer-regexp nil t))
21511 (and (looking-at "[ \t]*#\\+end_")
21512 (re-search-backward "[ \t]*#\\+begin_"nil t))
21513 (looking-at "[ \t]*[\n:#|]")
21514 (looking-at org-footnote-definition-re)
21515 (and (ignore-errors (goto-char (org-in-item-p)))
21516 (goto-char
21517 (org-list-get-top-point (org-list-struct))))
21518 (and (not inline-task-p)
21519 (featurep 'org-inlinetask)
21520 (org-inlinetask-in-task-p)
21521 (or (org-inlinetask-goto-beginning) t))))
21522 (beginning-of-line 0))
21523 (cond
21524 ;; There was an heading above.
21525 ((looking-at "\\*+[ \t]+")
21526 (if (not org-adapt-indentation)
21527 (setq column 0)
21528 (goto-char (match-end 0))
21529 (setq column (current-column))))
21530 ;; A drawer had started and is unfinished
21531 ((looking-at org-drawer-regexp)
21532 (goto-char (1- (match-beginning 1)))
21533 (setq column (current-column)))
21534 ;; Else, nothing noticeable found: get indentation and go on.
21535 (t (setq column (org-get-indentation))))))
21536 ;; Now apply indentation and move cursor accordingly
21537 (goto-char pos)
21538 (if (<= (current-column) (current-indentation))
21539 (org-indent-line-to column)
21540 (save-excursion (org-indent-line-to column)))
21541 ;; Special polishing for properties, see `org-property-format'
21542 (setq column (current-column))
21543 (beginning-of-line 1)
21544 (if (looking-at
21545 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21546 (replace-match (concat (match-string 1)
21547 (format org-property-format
21548 (match-string 2) (match-string 3)))
21549 t t))
21550 (org-move-to-column column))))
21552 (defun org-indent-drawer ()
21553 "Indent the drawer at point."
21554 (interactive)
21555 (let ((p (point))
21556 (e (and (save-excursion (re-search-forward ":END:" nil t))
21557 (match-end 0)))
21558 (folded
21559 (save-excursion
21560 (end-of-line)
21561 (when (overlays-at (point))
21562 (member 'invisible (overlay-properties
21563 (car (overlays-at (point)))))))))
21564 (when folded (org-cycle))
21565 (indent-for-tab-command)
21566 (while (and (move-beginning-of-line 2) (< (point) e))
21567 (indent-for-tab-command))
21568 (goto-char p)
21569 (when folded (org-cycle)))
21570 (message "Drawer at point indented"))
21572 (defun org-indent-block ()
21573 "Indent the block at point."
21574 (interactive)
21575 (let ((p (point))
21576 (case-fold-search t)
21577 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21578 (match-end 0)))
21579 (folded
21580 (save-excursion
21581 (end-of-line)
21582 (when (overlays-at (point))
21583 (member 'invisible (overlay-properties
21584 (car (overlays-at (point)))))))))
21585 (when folded (org-cycle))
21586 (indent-for-tab-command)
21587 (while (and (move-beginning-of-line 2) (< (point) e))
21588 (indent-for-tab-command))
21589 (goto-char p)
21590 (when folded (org-cycle)))
21591 (message "Block at point indented"))
21593 (defun org-indent-region (start end)
21594 "Indent region."
21595 (interactive "r")
21596 (save-excursion
21597 (let ((line-end (org-current-line end)))
21598 (goto-char start)
21599 (while (< (org-current-line) line-end)
21600 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21601 (t (call-interactively 'org-indent-line)))
21602 (move-beginning-of-line 2)))))
21605 ;;; Filling
21607 ;; We use our own fill-paragraph and auto-fill functions.
21609 ;; `org-fill-paragraph' relies on adaptive filling and context
21610 ;; checking. Appropriate `fill-prefix' is computed with
21611 ;; `org-adaptive-fill-function'.
21613 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21614 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21615 ;; `org-adaptive-fill-function' value. Internally,
21616 ;; `org-comment-line-break-function' breaks the line.
21618 ;; `org-setup-filling' installs filling and auto-filling related
21619 ;; variables during `org-mode' initialization.
21621 (defun org-setup-filling ()
21622 (interactive)
21623 ;; Prevent auto-fill from inserting unwanted new items.
21624 (when (boundp 'fill-nobreak-predicate)
21625 (org-set-local
21626 'fill-nobreak-predicate
21627 (org-uniquify
21628 (append fill-nobreak-predicate
21629 '(org-fill-paragraph-separate-nobreak-p
21630 org-fill-line-break-nobreak-p)))))
21631 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21632 (org-set-local 'auto-fill-inhibit-regexp nil)
21633 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21634 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21635 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21637 (defvar org-element-paragraph-separate) ; org-element.el
21638 (defun org-fill-paragraph-separate-nobreak-p ()
21639 "Non-nil when a line break at point would insert a new item."
21640 (looking-at (substring org-element-paragraph-separate 1)))
21642 (defun org-fill-line-break-nobreak-p ()
21643 "Non-nil when a line break at point would create an Org line break."
21644 (save-excursion
21645 (skip-chars-backward "[ \t]")
21646 (skip-chars-backward "\\\\")
21647 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21649 (declare-function message-in-body-p "message" ())
21650 (defvar orgtbl-line-start-regexp) ; From org-table.el
21651 (defun org-adaptive-fill-function ()
21652 "Compute a fill prefix for the current line.
21653 Return fill prefix, as a string, or nil if current line isn't
21654 meant to be filled."
21655 (let (prefix)
21656 (catch 'exit
21657 (when (derived-mode-p 'message-mode)
21658 (save-excursion
21659 (beginning-of-line)
21660 (cond ((or (not (message-in-body-p))
21661 (looking-at orgtbl-line-start-regexp))
21662 (throw 'exit nil))
21663 ((looking-at message-cite-prefix-regexp)
21664 (throw 'exit (match-string-no-properties 0)))
21665 ((looking-at org-outline-regexp)
21666 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21667 (org-with-wide-buffer
21668 (let* ((p (line-beginning-position))
21669 (element (save-excursion (beginning-of-line)
21670 (org-element-at-point)))
21671 (type (org-element-type element))
21672 (post-affiliated (org-element-property :post-affiliated element)))
21673 (unless (and post-affiliated (< p post-affiliated))
21674 (case type
21675 (comment (looking-at "[ \t]*# ?") (match-string 0))
21676 (footnote-definition "")
21677 ((item plain-list)
21678 (make-string (org-list-item-body-column
21679 (or post-affiliated
21680 (org-element-property :begin element)))
21681 ? ))
21682 (paragraph
21683 ;; Fill prefix is usually the same as the current line,
21684 ;; except if the paragraph is at the beginning of an item.
21685 (let ((parent (org-element-property :parent element)))
21686 (cond ((eq (org-element-type parent) 'item)
21687 (make-string (org-list-item-body-column
21688 (org-element-property :begin parent))
21689 ? ))
21690 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21691 (match-string 0))
21692 (t ""))))
21693 (comment-block
21694 ;; Only fill contents if P is within block boundaries.
21695 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21696 (forward-line)
21697 (point)))
21698 (cend (save-excursion
21699 (goto-char (org-element-property :end element))
21700 (skip-chars-backward " \r\t\n")
21701 (line-beginning-position))))
21702 (when (and (>= p cbeg) (< p cend))
21703 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21704 (match-string 0)
21705 "")))))))))))
21707 (declare-function message-goto-body "message" ())
21708 (defvar message-cite-prefix-regexp) ; From message.el
21709 (defvar org-element-all-objects) ; From org-element.el
21710 (defun org-fill-paragraph (&optional justify)
21711 "Fill element at point, when applicable.
21713 This function only applies to comment blocks, comments, example
21714 blocks and paragraphs. Also, as a special case, re-align table
21715 when point is at one.
21717 If JUSTIFY is non-nil (interactively, with prefix argument),
21718 justify as well. If `sentence-end-double-space' is non-nil, then
21719 period followed by one space does not end a sentence, so don't
21720 break a line there. The variable `fill-column' controls the
21721 width for filling.
21723 For convenience, when point is at a plain list, an item or
21724 a footnote definition, try to fill the first paragraph within."
21725 (interactive)
21726 (if (and (derived-mode-p 'message-mode)
21727 (or (not (message-in-body-p))
21728 (save-excursion (move-beginning-of-line 1)
21729 (looking-at message-cite-prefix-regexp))))
21730 ;; First ensure filling is correct in message-mode.
21731 (let ((fill-paragraph-function
21732 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21733 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21734 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21735 (paragraph-separate
21736 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21737 (fill-paragraph nil))
21738 (save-excursion
21739 ;; Move to end of line in order to get the first paragraph
21740 ;; within a plain list or a footnote definition.
21741 (end-of-line)
21742 (let ((element (org-element-at-point)))
21743 ;; First check if point is in a blank line at the beginning of
21744 ;; the buffer. In that case, ignore filling.
21745 (if (< (point) (org-element-property :begin element)) t
21746 (case (org-element-type element)
21747 ;; Use major mode filling function is src blocks.
21748 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21749 ;; Align Org tables, leave table.el tables as-is.
21750 (table-row (org-table-align) t)
21751 (table
21752 (when (eq (org-element-property :type element) 'org)
21753 (org-table-align))
21755 (paragraph
21756 ;; Paragraphs may contain `line-break' type objects.
21757 (let ((beg (max (point-min)
21758 (org-element-property :contents-begin element)))
21759 (end (min (point-max)
21760 (org-element-property :contents-end element))))
21761 ;; Do nothing if point is at an affiliated keyword.
21762 (if (< (point) beg) t
21763 (when (derived-mode-p 'message-mode)
21764 ;; In `message-mode', do not fill following
21765 ;; citation in current paragraph nor text before
21766 ;; message body.
21767 (let ((body-start (save-excursion (message-goto-body))))
21768 (when body-start (setq beg (max body-start beg))))
21769 (when (save-excursion
21770 (re-search-forward
21771 (concat "^" message-cite-prefix-regexp) end t))
21772 (setq end (match-beginning 0))))
21773 ;; Fill paragraph, taking line breaks into
21774 ;; consideration. For that, slice the paragraph
21775 ;; using line breaks as separators, and fill the
21776 ;; parts in reverse order to avoid messing with
21777 ;; markers.
21778 (save-excursion
21779 (goto-char end)
21780 (mapc
21781 (lambda (pos)
21782 (fill-region-as-paragraph pos (point) justify)
21783 (goto-char pos))
21784 ;; Find the list of ending positions for line
21785 ;; breaks in the current paragraph. Add paragraph
21786 ;; beginning to include first slice.
21787 (nreverse
21788 (cons
21790 (org-element-map
21791 (org-element--parse-objects
21792 beg end nil org-element-all-objects)
21793 'line-break
21794 (lambda (lb) (org-element-property :end lb)))))))
21795 t)))
21796 ;; Contents of `comment-block' type elements should be
21797 ;; filled as plain text, but only if point is within block
21798 ;; markers.
21799 (comment-block
21800 (let* ((case-fold-search t)
21801 (beg (save-excursion
21802 (goto-char (org-element-property :begin element))
21803 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21804 (forward-line)
21805 (point)))
21806 (end (save-excursion
21807 (goto-char (org-element-property :end element))
21808 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21809 (line-beginning-position))))
21810 (when (and (>= (point) beg) (< (point) end))
21811 (fill-region-as-paragraph
21812 (save-excursion
21813 (end-of-line)
21814 (re-search-backward "^[ \t]*$" beg 'move)
21815 (line-beginning-position))
21816 (save-excursion
21817 (beginning-of-line)
21818 (re-search-forward "^[ \t]*$" end 'move)
21819 (line-beginning-position))
21820 justify)))
21822 ;; Fill comments.
21823 (comment (fill-comment-paragraph justify))
21824 ;; Ignore every other element.
21825 (otherwise t)))))))
21827 (defun org-auto-fill-function ()
21828 "Auto-fill function."
21829 ;; Check if auto-filling is meaningful.
21830 (let ((fc (current-fill-column)))
21831 (when (and fc (> (current-column) fc))
21832 (let* ((fill-prefix (org-adaptive-fill-function))
21833 ;; Enforce empty fill prefix, if required. Otherwise, it
21834 ;; will be computed again.
21835 (adaptive-fill-mode (not (equal fill-prefix ""))))
21836 (when fill-prefix (do-auto-fill))))))
21838 (defun org-comment-line-break-function (&optional soft)
21839 "Break line at point and indent, continuing comment if within one.
21840 The inserted newline is marked hard if variable
21841 `use-hard-newlines' is true, unless optional argument SOFT is
21842 non-nil."
21843 (if soft (insert-and-inherit ?\n) (newline 1))
21844 (save-excursion (forward-char -1) (delete-horizontal-space))
21845 (delete-horizontal-space)
21846 (indent-to-left-margin)
21847 (insert-before-markers-and-inherit fill-prefix))
21850 ;;; Comments
21852 ;; Org comments syntax is quite complex. It requires the entire line
21853 ;; to be just a comment. Also, even with the right syntax at the
21854 ;; beginning of line, some some elements (i.e. verse-block or
21855 ;; example-block) don't accept comments. Usual Emacs comment commands
21856 ;; cannot cope with those requirements. Therefore, Org replaces them.
21858 ;; Org still relies on `comment-dwim', but cannot trust
21859 ;; `comment-only-p'. So, `comment-region-function' and
21860 ;; `uncomment-region-function' both point
21861 ;; to`org-comment-or-uncomment-region'. Eventually,
21862 ;; `org-insert-comment' takes care of insertion of comments at the
21863 ;; beginning of line.
21865 ;; `org-setup-comments-handling' install comments related variables
21866 ;; during `org-mode' initialization.
21868 (defun org-setup-comments-handling ()
21869 (interactive)
21870 (org-set-local 'comment-use-syntax nil)
21871 (org-set-local 'comment-start "# ")
21872 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21873 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21874 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21875 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21877 (defun org-insert-comment ()
21878 "Insert an empty comment above current line.
21879 If the line is empty, insert comment at its beginning."
21880 (beginning-of-line)
21881 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21882 (org-indent-line)
21883 (insert "# "))
21885 (defvar comment-empty-lines) ; From newcomment.el.
21886 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21887 "Comment or uncomment each non-blank line in the region.
21888 Uncomment each non-blank line between BEG and END if it only
21889 contains commented lines. Otherwise, comment them."
21890 (save-restriction
21891 ;; Restrict region
21892 (narrow-to-region (save-excursion (goto-char beg)
21893 (skip-chars-forward " \r\t\n" end)
21894 (line-beginning-position))
21895 (save-excursion (goto-char end)
21896 (skip-chars-backward " \r\t\n" beg)
21897 (line-end-position)))
21898 (let ((uncommentp
21899 ;; UNCOMMENTP is non-nil when every non blank line between
21900 ;; BEG and END is a comment.
21901 (save-excursion
21902 (goto-char (point-min))
21903 (while (and (not (eobp))
21904 (let ((element (org-element-at-point)))
21905 (and (eq (org-element-type element) 'comment)
21906 (goto-char (min (point-max)
21907 (org-element-property
21908 :end element)))))))
21909 (eobp))))
21910 (if uncommentp
21911 ;; Only blank lines and comments in region: uncomment it.
21912 (save-excursion
21913 (goto-char (point-min))
21914 (while (not (eobp))
21915 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21916 (replace-match "" nil nil nil 1))
21917 (forward-line)))
21918 ;; Comment each line in region.
21919 (let ((min-indent (point-max)))
21920 ;; First find the minimum indentation across all lines.
21921 (save-excursion
21922 (goto-char (point-min))
21923 (while (and (not (eobp)) (not (zerop min-indent)))
21924 (unless (looking-at "[ \t]*$")
21925 (setq min-indent (min min-indent (current-indentation))))
21926 (forward-line)))
21927 ;; Then loop over all lines.
21928 (save-excursion
21929 (goto-char (point-min))
21930 (while (not (eobp))
21931 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21932 (org-move-to-column min-indent t)
21933 (insert comment-start))
21934 (forward-line))))))))
21937 ;;; Planning
21939 ;; This section contains tools to operate on timestamp objects, as
21940 ;; returned by, e.g. `org-element-context'.
21942 (defun org-timestamp-has-time-p (timestamp)
21943 "Non-nil when TIMESTAMP has a time specified."
21944 (org-element-property :hour-start timestamp))
21946 (defun org-timestamp-format (timestamp format &optional end utc)
21947 "Format a TIMESTAMP element into a string.
21949 FORMAT is a format specifier to be passed to
21950 `format-time-string'.
21952 When optional argument END is non-nil, use end of date-range or
21953 time-range, if possible.
21955 When optional argument UTC is non-nil, time will be expressed as
21956 Universal Time."
21957 (format-time-string
21958 format
21959 (apply 'encode-time
21960 (cons 0
21961 (mapcar
21962 (lambda (prop) (or (org-element-property prop timestamp) 0))
21963 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21964 '(:minute-start :hour-start :day-start :month-start
21965 :year-start)))))
21966 utc))
21968 (defun org-timestamp-split-range (timestamp &optional end)
21969 "Extract a timestamp object from a date or time range.
21971 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21972 the end of the range. Otherwise, extract its start.
21974 Return a new timestamp object sharing the same parent as
21975 TIMESTAMP."
21976 (let ((type (org-element-property :type timestamp)))
21977 (if (memq type '(active inactive diary)) timestamp
21978 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21979 ;; Set new type.
21980 (org-element-put-property
21981 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21982 ;; Copy start properties over end properties if END is
21983 ;; non-nil. Otherwise, copy end properties over `start' ones.
21984 (let ((p-alist '((:minute-start . :minute-end)
21985 (:hour-start . :hour-end)
21986 (:day-start . :day-end)
21987 (:month-start . :month-end)
21988 (:year-start . :year-end))))
21989 (dolist (p-cell p-alist)
21990 (org-element-put-property
21991 split-ts
21992 (funcall (if end 'car 'cdr) p-cell)
21993 (org-element-property
21994 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21995 ;; Eventually refresh `:raw-value'.
21996 (org-element-put-property split-ts :raw-value nil)
21997 (org-element-put-property
21998 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22000 (defun org-timestamp-translate (timestamp &optional boundary)
22001 "Apply `org-translate-time' on a TIMESTAMP object.
22002 When optional argument BOUNDARY is non-nil, it is either the
22003 symbol `start' or `end'. In this case, only translate the
22004 starting or ending part of TIMESTAMP if it is a date or time
22005 range. Otherwise, translate both parts."
22006 (if (and (not boundary)
22007 (memq (org-element-property :type timestamp)
22008 '(active-range inactive-range)))
22009 (concat
22010 (org-translate-time
22011 (org-element-property :raw-value
22012 (org-timestamp-split-range timestamp)))
22013 "--"
22014 (org-translate-time
22015 (org-element-property :raw-value
22016 (org-timestamp-split-range timestamp t))))
22017 (org-translate-time
22018 (org-element-property
22019 :raw-value
22020 (if (not boundary) timestamp
22021 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22025 ;;; Other stuff.
22027 (defun org-toggle-fixed-width-section (arg)
22028 "Toggle the fixed-width export.
22029 If there is no active region, the QUOTE keyword at the current headline is
22030 inserted or removed. When present, it causes the text between this headline
22031 and the next to be exported as fixed-width text, and unmodified.
22032 If there is an active region, this command adds or removes a colon as the
22033 first character of this line. If the first character of a line is a colon,
22034 this line is also exported in fixed-width font."
22035 (interactive "P")
22036 (let* ((cc 0)
22037 (regionp (org-region-active-p))
22038 (beg (if regionp (region-beginning) (point)))
22039 (end (if regionp (region-end)))
22040 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22041 (case-fold-search nil)
22042 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22043 off)
22044 (if regionp
22045 (save-excursion
22046 (goto-char beg)
22047 (setq cc (current-column))
22048 (beginning-of-line 1)
22049 (setq off (looking-at re))
22050 (while (> nlines 0)
22051 (setq nlines (1- nlines))
22052 (beginning-of-line 1)
22053 (cond
22054 (arg
22055 (org-move-to-column cc t)
22056 (insert ": \n")
22057 (forward-line -1))
22058 ((and off (looking-at re))
22059 (replace-match "" t t nil 1))
22060 ((not off) (org-move-to-column cc t) (insert ": ")))
22061 (forward-line 1)))
22062 (save-excursion
22063 (org-back-to-heading)
22064 (cond
22065 ((looking-at (format org-heading-keyword-regexp-format
22066 org-quote-string))
22067 (goto-char (match-end 1))
22068 (looking-at (concat " +" org-quote-string))
22069 (replace-match "" t t)
22070 (when (eolp) (insert " ")))
22071 ((looking-at org-outline-regexp)
22072 (goto-char (match-end 0))
22073 (insert org-quote-string " ")))))))
22075 (defun org-reftex-citation ()
22076 "Use reftex-citation to insert a citation into the buffer.
22077 This looks for a line like
22079 #+BIBLIOGRAPHY: foo plain option:-d
22081 and derives from it that foo.bib is the bibliography file relevant
22082 for this document. It then installs the necessary environment for RefTeX
22083 to work in this buffer and calls `reftex-citation' to insert a citation
22084 into the buffer.
22086 Export of such citations to both LaTeX and HTML is handled by the contributed
22087 package org-exp-bibtex by Taru Karttunen."
22088 (interactive)
22089 (let ((reftex-docstruct-symbol 'rds)
22090 (reftex-cite-format "\\cite{%l}")
22091 rds bib)
22092 (save-excursion
22093 (save-restriction
22094 (widen)
22095 (let ((case-fold-search t)
22096 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22097 (if (not (save-excursion
22098 (or (re-search-forward re nil t)
22099 (re-search-backward re nil t))))
22100 (error "No bibliography defined in file")
22101 (setq bib (concat (match-string 1) ".bib")
22102 rds (list (list 'bib bib)))))))
22103 (call-interactively 'reftex-citation)))
22105 ;;;; Functions extending outline functionality
22107 (defun org-beginning-of-line (&optional arg)
22108 "Go to the beginning of the current line. If that is invisible, continue
22109 to a visible line beginning. This makes the function of C-a more intuitive.
22110 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22111 first attempt, and only move to after the tags when the cursor is already
22112 beyond the end of the headline."
22113 (interactive "P")
22114 (let ((pos (point))
22115 (special (if (consp org-special-ctrl-a/e)
22116 (car org-special-ctrl-a/e)
22117 org-special-ctrl-a/e))
22118 refpos)
22119 (if (org-bound-and-true-p visual-line-mode)
22120 (beginning-of-visual-line 1)
22121 (beginning-of-line 1))
22122 (if (and arg (fboundp 'move-beginning-of-line))
22123 (call-interactively 'move-beginning-of-line)
22124 (if (bobp)
22126 (backward-char 1)
22127 (if (org-truely-invisible-p)
22128 (while (and (not (bobp)) (org-truely-invisible-p))
22129 (backward-char 1)
22130 (beginning-of-line 1))
22131 (forward-char 1))))
22132 (when special
22133 (cond
22134 ((and (looking-at org-complex-heading-regexp)
22135 (= (char-after (match-end 1)) ?\ ))
22136 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22137 (point-at-eol)))
22138 (goto-char
22139 (if (eq special t)
22140 (cond ((> pos refpos) refpos)
22141 ((= pos (point)) refpos)
22142 (t (point)))
22143 (cond ((> pos (point)) (point))
22144 ((not (eq last-command this-command)) (point))
22145 (t refpos)))))
22146 ((org-at-item-p)
22147 ;; Being at an item and not looking at an the item means point
22148 ;; was previously moved to beginning of a visual line, which
22149 ;; doesn't contain the item. Therefore, do nothing special,
22150 ;; just stay here.
22151 (when (looking-at org-list-full-item-re)
22152 ;; Set special position at first white space character after
22153 ;; bullet, and check-box, if any.
22154 (let ((after-bullet
22155 (let ((box (match-end 3)))
22156 (if (not box) (match-end 1)
22157 (let ((after (char-after box)))
22158 (if (and after (= after ? )) (1+ box) box))))))
22159 ;; Special case: Move point to special position when
22160 ;; currently after it or at beginning of line.
22161 (if (eq special t)
22162 (when (or (> pos after-bullet) (= (point) pos))
22163 (goto-char after-bullet))
22164 ;; Reversed case: Move point to special position when
22165 ;; point was already at beginning of line and command is
22166 ;; repeated.
22167 (when (and (= (point) pos) (eq last-command this-command))
22168 (goto-char after-bullet))))))))
22169 (org-no-warnings
22170 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22172 (defun org-end-of-line (&optional arg)
22173 "Go to the end of the line.
22174 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22175 tags on the first attempt, and only move to after the tags when
22176 the cursor is already beyond the end of the headline."
22177 (interactive "P")
22178 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22179 org-special-ctrl-a/e))
22180 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22181 'end-of-visual-line)
22182 ((fboundp 'move-end-of-line) 'move-end-of-line)
22183 (t 'end-of-line))))
22184 (if (or (not special) arg) (call-interactively move-fun)
22185 (let* ((element (save-excursion (beginning-of-line)
22186 (org-element-at-point)))
22187 (type (org-element-type element)))
22188 (cond
22189 ((memq type '(headline inlinetask))
22190 (let ((pos (point)))
22191 (beginning-of-line 1)
22192 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22193 (if (eq special t)
22194 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22195 (goto-char (match-beginning 1))
22196 (goto-char (match-end 0)))
22197 (if (or (< pos (match-end 0))
22198 (not (eq this-command last-command)))
22199 (goto-char (match-end 0))
22200 (goto-char (match-beginning 1))))
22201 (call-interactively move-fun))))
22202 ((org-element-property :hiddenp element)
22203 ;; If element is hidden, `move-end-of-line' would put point
22204 ;; after it. Use `end-of-line' to stay on current line.
22205 (call-interactively 'end-of-line))
22206 (t (call-interactively move-fun)))))
22207 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22209 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22210 (define-key org-mode-map "\C-e" 'org-end-of-line)
22212 (defun org-backward-sentence (&optional arg)
22213 "Go to beginning of sentence, or beginning of table field.
22214 This will call `backward-sentence' or `org-table-beginning-of-field',
22215 depending on context."
22216 (interactive "P")
22217 (cond
22218 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22219 (t (call-interactively 'backward-sentence))))
22221 (defun org-forward-sentence (&optional arg)
22222 "Go to end of sentence, or end of table field.
22223 This will call `forward-sentence' or `org-table-end-of-field',
22224 depending on context."
22225 (interactive "P")
22226 (cond
22227 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22228 (t (call-interactively 'forward-sentence))))
22230 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22231 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22233 (defun org-kill-line (&optional arg)
22234 "Kill line, to tags or end of line."
22235 (interactive "P")
22236 (cond
22237 ((or (not org-special-ctrl-k)
22238 (bolp)
22239 (not (org-at-heading-p)))
22240 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22241 org-ctrl-k-protect-subtree)
22242 (if (or (eq org-ctrl-k-protect-subtree 'error)
22243 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22244 (error "C-k aborted - would kill hidden subtree")))
22245 (call-interactively
22246 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22247 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22248 (kill-region (point) (match-beginning 1))
22249 (org-set-tags nil t))
22250 (t (kill-region (point) (point-at-eol)))))
22252 (define-key org-mode-map "\C-k" 'org-kill-line)
22254 (defun org-yank (&optional arg)
22255 "Yank. If the kill is a subtree, treat it specially.
22256 This command will look at the current kill and check if is a single
22257 subtree, or a series of subtrees[1]. If it passes the test, and if the
22258 cursor is at the beginning of a line or after the stars of a currently
22259 empty headline, then the yank is handled specially. How exactly depends
22260 on the value of the following variables, both set by default.
22262 org-yank-folded-subtrees
22263 When set, the subtree(s) will be folded after insertion, but only
22264 if doing so would now swallow text after the yanked text.
22266 org-yank-adjusted-subtrees
22267 When set, the subtree will be promoted or demoted in order to
22268 fit into the local outline tree structure, which means that the level
22269 will be adjusted so that it becomes the smaller one of the two
22270 *visible* surrounding headings.
22272 Any prefix to this command will cause `yank' to be called directly with
22273 no special treatment. In particular, a simple \\[universal-argument] prefix \
22274 will just
22275 plainly yank the text as it is.
22277 \[1] The test checks if the first non-white line is a heading
22278 and if there are no other headings with fewer stars."
22279 (interactive "P")
22280 (org-yank-generic 'yank arg))
22282 (defun org-yank-generic (command arg)
22283 "Perform some yank-like command.
22285 This function implements the behavior described in the `org-yank'
22286 documentation. However, it has been generalized to work for any
22287 interactive command with similar behavior."
22289 ;; pretend to be command COMMAND
22290 (setq this-command command)
22292 (if arg
22293 (call-interactively command)
22295 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22296 (and (org-kill-is-subtree-p)
22297 (or (bolp)
22298 (and (looking-at "[ \t]*$")
22299 (string-match
22300 "\\`\\*+\\'"
22301 (buffer-substring (point-at-bol) (point)))))))
22302 swallowp)
22303 (cond
22304 ((and subtreep org-yank-folded-subtrees)
22305 (let ((beg (point))
22306 end)
22307 (if (and subtreep org-yank-adjusted-subtrees)
22308 (org-paste-subtree nil nil 'for-yank)
22309 (call-interactively command))
22311 (setq end (point))
22312 (goto-char beg)
22313 (when (and (bolp) subtreep
22314 (not (setq swallowp
22315 (org-yank-folding-would-swallow-text beg end))))
22316 (org-with-limited-levels
22317 (or (looking-at org-outline-regexp)
22318 (re-search-forward org-outline-regexp-bol end t))
22319 (while (and (< (point) end) (looking-at org-outline-regexp))
22320 (hide-subtree)
22321 (org-cycle-show-empty-lines 'folded)
22322 (condition-case nil
22323 (outline-forward-same-level 1)
22324 (error (goto-char end))))))
22325 (when swallowp
22326 (message
22327 "Inserted text not folded because that would swallow text"))
22329 (goto-char end)
22330 (skip-chars-forward " \t\n\r")
22331 (beginning-of-line 1)
22332 (push-mark beg 'nomsg)))
22333 ((and subtreep org-yank-adjusted-subtrees)
22334 (let ((beg (point-at-bol)))
22335 (org-paste-subtree nil nil 'for-yank)
22336 (push-mark beg 'nomsg)))
22338 (call-interactively command))))))
22340 (defun org-yank-folding-would-swallow-text (beg end)
22341 "Would hide-subtree at BEG swallow any text after END?"
22342 (let (level)
22343 (org-with-limited-levels
22344 (save-excursion
22345 (goto-char beg)
22346 (when (or (looking-at org-outline-regexp)
22347 (re-search-forward org-outline-regexp-bol end t))
22348 (setq level (org-outline-level)))
22349 (goto-char end)
22350 (skip-chars-forward " \t\r\n\v\f")
22351 (if (or (eobp)
22352 (and (bolp) (looking-at org-outline-regexp)
22353 (<= (org-outline-level) level)))
22354 nil ; Nothing would be swallowed
22355 t))))) ; something would swallow
22357 (define-key org-mode-map "\C-y" 'org-yank)
22359 (defun org-truely-invisible-p ()
22360 "Check if point is at a character currently not visible.
22361 This version does not only check the character property, but also
22362 `visible-mode'."
22363 ;; Early versions of noutline don't have `outline-invisible-p'.
22364 (if (org-bound-and-true-p visible-mode)
22366 (outline-invisible-p)))
22368 (defun org-invisible-p2 ()
22369 "Check if point is at a character currently not visible."
22370 (save-excursion
22371 (if (and (eolp) (not (bobp))) (backward-char 1))
22372 ;; Early versions of noutline don't have `outline-invisible-p'.
22373 (outline-invisible-p)))
22375 (defun org-back-to-heading (&optional invisible-ok)
22376 "Call `outline-back-to-heading', but provide a better error message."
22377 (condition-case nil
22378 (outline-back-to-heading invisible-ok)
22379 (error (error "Before first headline at position %d in buffer %s"
22380 (point) (current-buffer)))))
22382 (defun org-before-first-heading-p ()
22383 "Before first heading?"
22384 (save-excursion
22385 (end-of-line)
22386 (null (re-search-backward org-outline-regexp-bol nil t))))
22388 (defun org-at-heading-p (&optional ignored)
22389 (outline-on-heading-p t))
22390 ;; Compatibility alias with Org versions < 7.8.03
22391 (defalias 'org-on-heading-p 'org-at-heading-p)
22393 (defun org-at-comment-p nil
22394 "Is cursor in a line starting with a # character?"
22395 (save-excursion
22396 (beginning-of-line)
22397 (looking-at "^#")))
22399 (defun org-at-drawer-p nil
22400 "Is cursor at a drawer keyword?"
22401 (save-excursion
22402 (move-beginning-of-line 1)
22403 (looking-at org-drawer-regexp)))
22405 (defun org-at-block-p nil
22406 "Is cursor at a block keyword?"
22407 (save-excursion
22408 (move-beginning-of-line 1)
22409 (looking-at org-block-regexp)))
22411 (defun org-point-at-end-of-empty-headline ()
22412 "If point is at the end of an empty headline, return t, else nil.
22413 If the heading only contains a TODO keyword, it is still still considered
22414 empty."
22415 (and (looking-at "[ \t]*$")
22416 (when org-todo-line-regexp
22417 (save-excursion
22418 (beginning-of-line 1)
22419 (let ((case-fold-search nil))
22420 (looking-at org-todo-line-regexp)
22421 (string= (match-string 3) ""))))))
22423 (defun org-at-heading-or-item-p ()
22424 (or (org-at-heading-p) (org-at-item-p)))
22426 (defun org-at-target-p ()
22427 (or (org-in-regexp org-radio-target-regexp)
22428 (org-in-regexp org-target-regexp)))
22429 ;; Compatibility alias with Org versions < 7.8.03
22430 (defalias 'org-on-target-p 'org-at-target-p)
22432 (defun org-up-heading-all (arg)
22433 "Move to the heading line of which the present line is a subheading.
22434 This function considers both visible and invisible heading lines.
22435 With argument, move up ARG levels."
22436 (if (fboundp 'outline-up-heading-all)
22437 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22438 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22440 (defun org-up-heading-safe ()
22441 "Move to the heading line of which the present line is a subheading.
22442 This version will not throw an error. It will return the level of the
22443 headline found, or nil if no higher level is found.
22445 Also, this function will be a lot faster than `outline-up-heading',
22446 because it relies on stars being the outline starters. This can really
22447 make a significant difference in outlines with very many siblings."
22448 (let (start-level re)
22449 (org-back-to-heading t)
22450 (setq start-level (funcall outline-level))
22451 (if (equal start-level 1)
22453 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22454 (if (re-search-backward re nil t)
22455 (funcall outline-level)))))
22457 (defun org-first-sibling-p ()
22458 "Is this heading the first child of its parents?"
22459 (interactive)
22460 (let ((re org-outline-regexp-bol)
22461 level l)
22462 (unless (org-at-heading-p t)
22463 (error "Not at a heading"))
22464 (setq level (funcall outline-level))
22465 (save-excursion
22466 (if (not (re-search-backward re nil t))
22468 (setq l (funcall outline-level))
22469 (< l level)))))
22471 (defun org-goto-sibling (&optional previous)
22472 "Goto the next sibling, even if it is invisible.
22473 When PREVIOUS is set, go to the previous sibling instead. Returns t
22474 when a sibling was found. When none is found, return nil and don't
22475 move point."
22476 (let ((fun (if previous 're-search-backward 're-search-forward))
22477 (pos (point))
22478 (re org-outline-regexp-bol)
22479 level l)
22480 (when (condition-case nil (org-back-to-heading t) (error nil))
22481 (setq level (funcall outline-level))
22482 (catch 'exit
22483 (or previous (forward-char 1))
22484 (while (funcall fun re nil t)
22485 (setq l (funcall outline-level))
22486 (when (< l level) (goto-char pos) (throw 'exit nil))
22487 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22488 (goto-char pos)
22489 nil))))
22491 (defun org-show-siblings ()
22492 "Show all siblings of the current headline."
22493 (save-excursion
22494 (while (org-goto-sibling) (org-flag-heading nil)))
22495 (save-excursion
22496 (while (org-goto-sibling 'previous)
22497 (org-flag-heading nil))))
22499 (defun org-goto-first-child ()
22500 "Goto the first child, even if it is invisible.
22501 Return t when a child was found. Otherwise don't move point and
22502 return nil."
22503 (let (level (pos (point)) (re org-outline-regexp-bol))
22504 (when (condition-case nil (org-back-to-heading t) (error nil))
22505 (setq level (outline-level))
22506 (forward-char 1)
22507 (if (and (re-search-forward re nil t) (> (outline-level) level))
22508 (progn (goto-char (match-beginning 0)) t)
22509 (goto-char pos) nil))))
22511 (defun org-show-hidden-entry ()
22512 "Show an entry where even the heading is hidden."
22513 (save-excursion
22514 (org-show-entry)))
22516 (defun org-flag-heading (flag &optional entry)
22517 "Flag the current heading. FLAG non-nil means make invisible.
22518 When ENTRY is non-nil, show the entire entry."
22519 (save-excursion
22520 (org-back-to-heading t)
22521 ;; Check if we should show the entire entry
22522 (if entry
22523 (progn
22524 (org-show-entry)
22525 (save-excursion
22526 (and (outline-next-heading)
22527 (org-flag-heading nil))))
22528 (outline-flag-region (max (point-min) (1- (point)))
22529 (save-excursion (outline-end-of-heading) (point))
22530 flag))))
22532 (defun org-get-next-sibling ()
22533 "Move to next heading of the same level, and return point.
22534 If there is no such heading, return nil.
22535 This is like outline-next-sibling, but invisible headings are ok."
22536 (let ((level (funcall outline-level)))
22537 (outline-next-heading)
22538 (while (and (not (eobp)) (> (funcall outline-level) level))
22539 (outline-next-heading))
22540 (if (or (eobp) (< (funcall outline-level) level))
22542 (point))))
22544 (defun org-get-last-sibling ()
22545 "Move to previous heading of the same level, and return point.
22546 If there is no such heading, return nil."
22547 (let ((opoint (point))
22548 (level (funcall outline-level)))
22549 (outline-previous-heading)
22550 (when (and (/= (point) opoint) (outline-on-heading-p t))
22551 (while (and (> (funcall outline-level) level)
22552 (not (bobp)))
22553 (outline-previous-heading))
22554 (if (< (funcall outline-level) level)
22556 (point)))))
22558 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22559 "Goto to the end of a subtree."
22560 ;; This contains an exact copy of the original function, but it uses
22561 ;; `org-back-to-heading', to make it work also in invisible
22562 ;; trees. And is uses an invisible-ok argument.
22563 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22564 ;; Furthermore, when used inside Org, finding the end of a large subtree
22565 ;; with many children and grandchildren etc, this can be much faster
22566 ;; than the outline version.
22567 (org-back-to-heading invisible-ok)
22568 (let ((first t)
22569 (level (funcall outline-level)))
22570 (if (and (derived-mode-p 'org-mode) (< level 1000))
22571 ;; A true heading (not a plain list item), in Org-mode
22572 ;; This means we can easily find the end by looking
22573 ;; only for the right number of stars. Using a regexp to do
22574 ;; this is so much faster than using a Lisp loop.
22575 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22576 (forward-char 1)
22577 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22578 ;; something else, do it the slow way
22579 (while (and (not (eobp))
22580 (or first (> (funcall outline-level) level)))
22581 (setq first nil)
22582 (outline-next-heading)))
22583 (unless to-heading
22584 (if (memq (preceding-char) '(?\n ?\^M))
22585 (progn
22586 ;; Go to end of line before heading
22587 (forward-char -1)
22588 (if (memq (preceding-char) '(?\n ?\^M))
22589 ;; leave blank line before heading
22590 (forward-char -1))))))
22591 (point))
22593 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22594 "Use Org version in org-mode, for dramatic speed-up."
22595 (if (derived-mode-p 'org-mode)
22596 (progn
22597 (org-end-of-subtree nil t)
22598 (unless (eobp) (backward-char 1)))
22599 ad-do-it))
22601 (defun org-end-of-meta-data-and-drawers ()
22602 "Jump to the first text after meta data and drawers in the current entry.
22603 This will move over empty lines, lines with planning time stamps,
22604 clocking lines, and drawers."
22605 (org-back-to-heading t)
22606 (let ((end (save-excursion (outline-next-heading) (point)))
22607 (re (concat "\\(" org-drawer-regexp "\\)"
22608 "\\|" "[ \t]*" org-keyword-time-regexp)))
22609 (forward-line 1)
22610 (while (re-search-forward re end t)
22611 (if (not (match-end 1))
22612 ;; empty or planning line
22613 (forward-line 1)
22614 ;; a drawer, find the end
22615 (re-search-forward "^[ \t]*:END:" end 'move)
22616 (forward-line 1)))
22617 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22618 (point)))
22620 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22621 "Move forward to the arg'th subheading at same level as this one.
22622 Stop at the first and last subheadings of a superior heading.
22623 Normally this only looks at visible headings, but when INVISIBLE-OK is
22624 non-nil it will also look at invisible ones."
22625 (interactive "p")
22626 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22627 (outline-next-heading)
22628 (org-at-heading-p)
22629 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22630 (re (format "^\\*\\{1,%d\\} " level))
22632 (forward-char 1)
22633 (while (> arg 0)
22634 (while (and (re-search-forward re nil 'move)
22635 (setq l (- (match-end 0) (match-beginning 0) 1))
22636 (= l level)
22637 (not invisible-ok)
22638 (progn (backward-char 1) (outline-invisible-p)))
22639 (if (< l level) (setq arg 1)))
22640 (setq arg (1- arg)))
22641 (beginning-of-line 1))))
22643 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22644 "Move backward to the arg'th subheading at same level as this one.
22645 Stop at the first and last subheadings of a superior heading."
22646 (interactive "p")
22647 (if (not (ignore-errors (org-back-to-heading)))
22648 (goto-char (point-min))
22649 (org-at-heading-p)
22650 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22651 (re (format "^\\*\\{1,%d\\} " level))
22653 (while (> arg 0)
22654 (while (and (re-search-backward re nil 'move)
22655 (setq l (- (match-end 0) (match-beginning 0) 1))
22656 (= l level)
22657 (not invisible-ok)
22658 (outline-invisible-p))
22659 (if (< l level) (setq arg 1)))
22660 (setq arg (1- arg))))))
22662 (defun org-forward-element ()
22663 "Move forward by one element.
22664 Move to the next element at the same level, when possible."
22665 (interactive)
22666 (cond ((eobp) (error "Cannot move further down"))
22667 ((org-with-limited-levels (org-at-heading-p))
22668 (let ((origin (point)))
22669 (org-forward-heading-same-level 1)
22670 (unless (org-with-limited-levels (org-at-heading-p))
22671 (goto-char origin)
22672 (error "Cannot move further down"))))
22674 (let* ((elem (org-element-at-point))
22675 (end (org-element-property :end elem))
22676 (parent (org-element-property :parent elem)))
22677 (if (and parent (= (org-element-property :contents-end parent) end))
22678 (goto-char (org-element-property :end parent))
22679 (goto-char end))))))
22681 (defun org-backward-element ()
22682 "Move backward by one element.
22683 Move to the previous element at the same level, when possible."
22684 (interactive)
22685 (cond ((bobp) (error "Cannot move further up"))
22686 ((org-with-limited-levels (org-at-heading-p))
22687 ;; At an headline, move to the previous one, if any, or stay
22688 ;; here.
22689 (let ((origin (point)))
22690 (org-backward-heading-same-level 1)
22691 (unless (org-with-limited-levels (org-at-heading-p))
22692 (goto-char origin)
22693 (error "Cannot move further up"))))
22695 (let* ((trail (org-element-at-point 'keep-trail))
22696 (elem (car trail))
22697 (prev-elem (nth 1 trail))
22698 (beg (org-element-property :begin elem)))
22699 (cond
22700 ;; Move to beginning of current element if point isn't
22701 ;; there already.
22702 ((/= (point) beg) (goto-char beg))
22703 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22704 ((org-before-first-heading-p) (goto-char (point-min)))
22705 (t (org-back-to-heading)))))))
22707 (defun org-up-element ()
22708 "Move to upper element."
22709 (interactive)
22710 (if (org-with-limited-levels (org-at-heading-p))
22711 (unless (org-up-heading-safe) (error "No surrounding element"))
22712 (let* ((elem (org-element-at-point))
22713 (parent (org-element-property :parent elem)))
22714 (if parent (goto-char (org-element-property :begin parent))
22715 (if (org-with-limited-levels (org-before-first-heading-p))
22716 (error "No surrounding element")
22717 (org-with-limited-levels (org-back-to-heading)))))))
22719 (defvar org-element-greater-elements)
22720 (defun org-down-element ()
22721 "Move to inner element."
22722 (interactive)
22723 (let ((element (org-element-at-point)))
22724 (cond
22725 ((memq (org-element-type element) '(plain-list table))
22726 (goto-char (org-element-property :contents-begin element))
22727 (forward-char))
22728 ((memq (org-element-type element) org-element-greater-elements)
22729 ;; If contents are hidden, first disclose them.
22730 (when (org-element-property :hiddenp element) (org-cycle))
22731 (goto-char (or (org-element-property :contents-begin element)
22732 (error "No content for this element"))))
22733 (t (error "No inner element")))))
22735 (defun org-drag-element-backward ()
22736 "Move backward element at point."
22737 (interactive)
22738 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22739 (let* ((trail (org-element-at-point 'keep-trail))
22740 (elem (car trail))
22741 (prev-elem (nth 1 trail)))
22742 ;; Error out if no previous element or previous element is
22743 ;; a parent of the current one.
22744 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22745 (error "Cannot drag element backward")
22746 (let ((pos (point)))
22747 (org-element-swap-A-B prev-elem elem)
22748 (goto-char (+ (org-element-property :begin prev-elem)
22749 (- pos (org-element-property :begin elem)))))))))
22751 (defun org-drag-element-forward ()
22752 "Move forward element at point."
22753 (interactive)
22754 (let* ((pos (point))
22755 (elem (org-element-at-point)))
22756 (when (= (point-max) (org-element-property :end elem))
22757 (error "Cannot drag element forward"))
22758 (goto-char (org-element-property :end elem))
22759 (let ((next-elem (org-element-at-point)))
22760 (when (or (org-element-nested-p elem next-elem)
22761 (and (eq (org-element-type next-elem) 'headline)
22762 (not (eq (org-element-type elem) 'headline))))
22763 (goto-char pos)
22764 (error "Cannot drag element forward"))
22765 ;; Compute new position of point: it's shifted by NEXT-ELEM
22766 ;; body's length (without final blanks) and by the length of
22767 ;; blanks between ELEM and NEXT-ELEM.
22768 (let ((size-next (- (save-excursion
22769 (goto-char (org-element-property :end next-elem))
22770 (skip-chars-backward " \r\t\n")
22771 (forward-line)
22772 ;; Small correction if buffer doesn't end
22773 ;; with a newline character.
22774 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22775 (org-element-property :begin next-elem)))
22776 (size-blank (- (org-element-property :end elem)
22777 (save-excursion
22778 (goto-char (org-element-property :end elem))
22779 (skip-chars-backward " \r\t\n")
22780 (forward-line)
22781 (point)))))
22782 (org-element-swap-A-B elem next-elem)
22783 (goto-char (+ pos size-next size-blank))))))
22785 (defun org-mark-element ()
22786 "Put point at beginning of this element, mark at end.
22788 Interactively, if this command is repeated or (in Transient Mark
22789 mode) if the mark is active, it marks the next element after the
22790 ones already marked."
22791 (interactive)
22792 (let (deactivate-mark)
22793 (if (and (org-called-interactively-p 'any)
22794 (or (and (eq last-command this-command) (mark t))
22795 (and transient-mark-mode mark-active)))
22796 (set-mark
22797 (save-excursion
22798 (goto-char (mark))
22799 (goto-char (org-element-property :end (org-element-at-point)))))
22800 (let ((element (org-element-at-point)))
22801 (end-of-line)
22802 (push-mark (org-element-property :end element) t t)
22803 (goto-char (org-element-property :begin element))))))
22805 (defun org-narrow-to-element ()
22806 "Narrow buffer to current element."
22807 (interactive)
22808 (let ((elem (org-element-at-point)))
22809 (cond
22810 ((eq (car elem) 'headline)
22811 (narrow-to-region
22812 (org-element-property :begin elem)
22813 (org-element-property :end elem)))
22814 ((memq (car elem) org-element-greater-elements)
22815 (narrow-to-region
22816 (org-element-property :contents-begin elem)
22817 (org-element-property :contents-end elem)))
22819 (narrow-to-region
22820 (org-element-property :begin elem)
22821 (org-element-property :end elem))))))
22823 (defun org-transpose-words ()
22824 "Transpose words, using `org-mode' syntax table."
22825 (interactive)
22826 (with-syntax-table org-syntax-table
22827 (call-interactively 'transpose-words)))
22828 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22830 (defun org-transpose-element ()
22831 "Transpose current and previous elements, keeping blank lines between.
22832 Point is moved after both elements."
22833 (interactive)
22834 (org-skip-whitespace)
22835 (let ((end (org-element-property :end (org-element-at-point))))
22836 (org-drag-element-backward)
22837 (goto-char end)))
22839 (defun org-unindent-buffer ()
22840 "Un-indent the visible part of the buffer.
22841 Relative indentation (between items, inside blocks, etc.) isn't
22842 modified."
22843 (interactive)
22844 (unless (eq major-mode 'org-mode)
22845 (error "Cannot un-indent a buffer not in Org mode"))
22846 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22847 unindent-tree ; For byte-compiler.
22848 (unindent-tree
22849 (function
22850 (lambda (contents)
22851 (mapc
22852 (lambda (element)
22853 (if (memq (org-element-type element) '(headline section))
22854 (funcall unindent-tree (org-element-contents element))
22855 (save-excursion
22856 (save-restriction
22857 (narrow-to-region
22858 (org-element-property :begin element)
22859 (org-element-property :end element))
22860 (org-do-remove-indentation)))))
22861 (reverse contents))))))
22862 (funcall unindent-tree (org-element-contents parse-tree))))
22864 (defun org-show-subtree ()
22865 "Show everything after this heading at deeper levels."
22866 (interactive)
22867 (outline-flag-region
22868 (point)
22869 (save-excursion
22870 (org-end-of-subtree t t))
22871 nil))
22873 (defun org-show-entry ()
22874 "Show the body directly following this heading.
22875 Show the heading too, if it is currently invisible."
22876 (interactive)
22877 (save-excursion
22878 (condition-case nil
22879 (progn
22880 (org-back-to-heading t)
22881 (outline-flag-region
22882 (max (point-min) (1- (point)))
22883 (save-excursion
22884 (if (re-search-forward
22885 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22886 (match-beginning 1)
22887 (point-max)))
22888 nil)
22889 (org-cycle-hide-drawers 'children))
22890 (error nil))))
22892 (defun org-make-options-regexp (kwds &optional extra)
22893 "Make a regular expression for keyword lines."
22894 (concat
22895 "^#\\+\\("
22896 (mapconcat 'regexp-quote kwds "\\|")
22897 (if extra (concat "\\|" extra))
22898 "\\):[ \t]*\\(.*\\)"))
22900 ;; Make isearch reveal the necessary context
22901 (defun org-isearch-end ()
22902 "Reveal context after isearch exits."
22903 (when isearch-success ; only if search was successful
22904 (if (featurep 'xemacs)
22905 ;; Under XEmacs, the hook is run in the correct place,
22906 ;; we directly show the context.
22907 (org-show-context 'isearch)
22908 ;; In Emacs the hook runs *before* restoring the overlays.
22909 ;; So we have to use a one-time post-command-hook to do this.
22910 ;; (Emacs 22 has a special variable, see function `org-mode')
22911 (unless (and (boundp 'isearch-mode-end-hook-quit)
22912 isearch-mode-end-hook-quit)
22913 ;; Only when the isearch was not quitted.
22914 (org-add-hook 'post-command-hook 'org-isearch-post-command
22915 'append 'local)))))
22917 (defun org-isearch-post-command ()
22918 "Remove self from hook, and show context."
22919 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22920 (org-show-context 'isearch))
22923 ;;;; Integration with and fixes for other packages
22925 ;;; Imenu support
22927 (defvar org-imenu-markers nil
22928 "All markers currently used by Imenu.")
22929 (make-variable-buffer-local 'org-imenu-markers)
22931 (defun org-imenu-new-marker (&optional pos)
22932 "Return a new marker for use by Imenu, and remember the marker."
22933 (let ((m (make-marker)))
22934 (move-marker m (or pos (point)))
22935 (push m org-imenu-markers)
22938 (defun org-imenu-get-tree ()
22939 "Produce the index for Imenu."
22940 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22941 (setq org-imenu-markers nil)
22942 (let* ((n org-imenu-depth)
22943 (re (concat "^" (org-get-limited-outline-regexp)))
22944 (subs (make-vector (1+ n) nil))
22945 (last-level 0)
22946 m level head)
22947 (save-excursion
22948 (save-restriction
22949 (widen)
22950 (goto-char (point-max))
22951 (while (re-search-backward re nil t)
22952 (setq level (org-reduced-level (funcall outline-level)))
22953 (when (and (<= level n)
22954 (looking-at org-complex-heading-regexp))
22955 (setq head (org-link-display-format
22956 (org-match-string-no-properties 4))
22957 m (org-imenu-new-marker))
22958 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22959 (if (>= level last-level)
22960 (push (cons head m) (aref subs level))
22961 (push (cons head (aref subs (1+ level))) (aref subs level))
22962 (loop for i from (1+ level) to n do (aset subs i nil)))
22963 (setq last-level level)))))
22964 (aref subs 1)))
22966 (eval-after-load "imenu"
22967 '(progn
22968 (add-hook 'imenu-after-jump-hook
22969 (lambda ()
22970 (if (derived-mode-p 'org-mode)
22971 (org-show-context 'org-goto))))))
22973 (defun org-link-display-format (link)
22974 "Replace a link with either the description, or the link target
22975 if no description is present"
22976 (save-match-data
22977 (if (string-match org-bracket-link-analytic-regexp link)
22978 (replace-match (if (match-end 5)
22979 (match-string 5 link)
22980 (concat (match-string 1 link)
22981 (match-string 3 link)))
22982 nil t link)
22983 link)))
22985 (defun org-toggle-link-display ()
22986 "Toggle the literal or descriptive display of links."
22987 (interactive)
22988 (if org-descriptive-links
22989 (progn (org-remove-from-invisibility-spec '(org-link))
22990 (org-restart-font-lock)
22991 (setq org-descriptive-links nil))
22992 (progn (add-to-invisibility-spec '(org-link))
22993 (org-restart-font-lock)
22994 (setq org-descriptive-links t))))
22996 ;; Speedbar support
22998 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22999 "Overlay marking the agenda restriction line in speedbar.")
23000 (overlay-put org-speedbar-restriction-lock-overlay
23001 'face 'org-agenda-restriction-lock)
23002 (overlay-put org-speedbar-restriction-lock-overlay
23003 'help-echo "Agendas are currently limited to this item.")
23004 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23006 (defun org-speedbar-set-agenda-restriction ()
23007 "Restrict future agenda commands to the location at point in speedbar.
23008 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23009 (interactive)
23010 (require 'org-agenda)
23011 (let (p m tp np dir txt)
23012 (cond
23013 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23014 'org-imenu t))
23015 (setq m (get-text-property p 'org-imenu-marker))
23016 (with-current-buffer (marker-buffer m)
23017 (goto-char m)
23018 (org-agenda-set-restriction-lock 'subtree)))
23019 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23020 'speedbar-function 'speedbar-find-file))
23021 (setq tp (previous-single-property-change
23022 (1+ p) 'speedbar-function)
23023 np (next-single-property-change
23024 tp 'speedbar-function)
23025 dir (speedbar-line-directory)
23026 txt (buffer-substring-no-properties (or tp (point-min))
23027 (or np (point-max))))
23028 (with-current-buffer (find-file-noselect
23029 (let ((default-directory dir))
23030 (expand-file-name txt)))
23031 (unless (derived-mode-p 'org-mode)
23032 (error "Cannot restrict to non-Org-mode file"))
23033 (org-agenda-set-restriction-lock 'file)))
23034 (t (error "Don't know how to restrict Org-mode's agenda")))
23035 (move-overlay org-speedbar-restriction-lock-overlay
23036 (point-at-bol) (point-at-eol))
23037 (setq current-prefix-arg nil)
23038 (org-agenda-maybe-redo)))
23040 (eval-after-load "speedbar"
23041 '(progn
23042 (speedbar-add-supported-extension ".org")
23043 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23044 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23045 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23046 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23047 (add-hook 'speedbar-visiting-tag-hook
23048 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23050 ;;; Fixes and Hacks for problems with other packages
23052 ;; Make flyspell not check words in links, to not mess up our keymap
23053 (defvar org-element-affiliated-keywords) ; From org-element.el
23054 (defvar org-element-block-name-alist) ; From org-element.el
23055 (defun org-mode-flyspell-verify ()
23056 "Don't let flyspell put overlays at active buttons, or on
23057 {todo,all-time,additional-option-like}-keywords."
23058 (let ((pos (max (1- (point)) (point-min)))
23059 (word (thing-at-point 'word)))
23060 (and (not (get-text-property pos 'keymap))
23061 (not (get-text-property pos 'org-no-flyspell))
23062 (not (member word org-todo-keywords-1))
23063 (not (member word org-all-time-keywords))
23064 (not (member word org-options-keywords))
23065 (not (member word (mapcar 'car org-startup-options)))
23066 (not (member-ignore-case word org-element-affiliated-keywords))
23067 (not (member-ignore-case word (org-get-export-keywords)))
23068 (not (member-ignore-case
23069 word (mapcar 'car org-element-block-name-alist)))
23070 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23072 (defun org-remove-flyspell-overlays-in (beg end)
23073 "Remove flyspell overlays in region."
23074 (and (org-bound-and-true-p flyspell-mode)
23075 (fboundp 'flyspell-delete-region-overlays)
23076 (flyspell-delete-region-overlays beg end))
23077 (add-text-properties beg end '(org-no-flyspell t)))
23079 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23080 (eval-after-load "bookmark"
23081 '(if (boundp 'bookmark-after-jump-hook)
23082 ;; We can use the hook
23083 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23084 ;; Hook not available, use advice
23085 (defadvice bookmark-jump (after org-make-visible activate)
23086 "Make the position visible."
23087 (org-bookmark-jump-unhide))))
23089 ;; Make sure saveplace shows the location if it was hidden
23090 (eval-after-load "saveplace"
23091 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23092 "Make the position visible."
23093 (org-bookmark-jump-unhide)))
23095 ;; Make sure ecb shows the location if it was hidden
23096 (eval-after-load "ecb"
23097 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23098 "Make hierarchy visible when jumping into location from ECB tree buffer."
23099 (if (derived-mode-p 'org-mode)
23100 (org-show-context))))
23102 (defun org-bookmark-jump-unhide ()
23103 "Unhide the current position, to show the bookmark location."
23104 (and (derived-mode-p 'org-mode)
23105 (or (outline-invisible-p)
23106 (save-excursion (goto-char (max (point-min) (1- (point))))
23107 (outline-invisible-p)))
23108 (org-show-context 'bookmark-jump)))
23110 ;; Make session.el ignore our circular variable
23111 (eval-after-load "session"
23112 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23114 ;;;; Experimental code
23116 (defun org-closed-in-range ()
23117 "Sparse tree of items closed in a certain time range.
23118 Still experimental, may disappear in the future."
23119 (interactive)
23120 ;; Get the time interval from the user.
23121 (let* ((time1 (org-float-time
23122 (org-read-date nil 'to-time nil "Starting date: ")))
23123 (time2 (org-float-time
23124 (org-read-date nil 'to-time nil "End date:")))
23125 ;; callback function
23126 (callback (lambda ()
23127 (let ((time
23128 (org-float-time
23129 (apply 'encode-time
23130 (org-parse-time-string
23131 (match-string 1))))))
23132 ;; check if time in interval
23133 (and (>= time time1) (<= time time2))))))
23134 ;; make tree, check each match with the callback
23135 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23137 ;;;; Finish up
23139 (provide 'org)
23141 (run-hooks 'org-load-hook)
23143 ;;; org.el ends here