ox-taskjuggler: Port TaskJuggler back-end to new export framework
[org-mode.git] / lisp / org.el
blob62bee4eea6adef3a4ab3e5f5564db95e4d983afa
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
497 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
499 (eval-after-load 'ox
500 '(mapc
501 (lambda (backend)
502 (condition-case nil (require (intern (format "ox-%s" backend)))
503 (error (message "Problems while trying to load export back-end `%s'"
504 backend))))
505 org-export-backends))
507 (defcustom org-support-shift-select nil
508 "Non-nil means make shift-cursor commands select text when possible.
510 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
511 start selecting a region, or enlarge regions started in this way.
512 In Org-mode, in special contexts, these same keys are used for
513 other purposes, important enough to compete with shift selection.
514 Org tries to balance these needs by supporting `shift-select-mode'
515 outside these special contexts, under control of this variable.
517 The default of this variable is nil, to avoid confusing behavior. Shifted
518 cursor keys will then execute Org commands in the following contexts:
519 - on a headline, changing TODO state (left/right) and priority (up/down)
520 - on a time stamp, changing the time
521 - in a plain list item, changing the bullet type
522 - in a property definition line, switching between allowed values
523 - in the BEGIN line of a clock table (changing the time block).
524 Outside these contexts, the commands will throw an error.
526 When this variable is t and the cursor is not in a special
527 context, Org-mode will support shift-selection for making and
528 enlarging regions. To make this more effective, the bullet
529 cycling will no longer happen anywhere in an item line, but only
530 if the cursor is exactly on the bullet.
532 If you set this variable to the symbol `always', then the keys
533 will not be special in headlines, property lines, and item lines,
534 to make shift selection work there as well. If this is what you
535 want, you can use the following alternative commands: `C-c C-t'
536 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
537 can be used to switch TODO sets, `C-c -' to cycle item bullet
538 types, and properties can be edited by hand or in column view.
540 However, when the cursor is on a timestamp, shift-cursor commands
541 will still edit the time stamp - this is just too good to give up.
543 XEmacs user should have this variable set to nil, because
544 `shift-select-mode' is in Emacs 23 or later only."
545 :group 'org
546 :type '(choice
547 (const :tag "Never" nil)
548 (const :tag "When outside special context" t)
549 (const :tag "Everywhere except timestamps" always)))
551 (defcustom org-loop-over-headlines-in-active-region nil
552 "Shall some commands act upon headlines in the active region?
554 When set to `t', some commands will be performed in all headlines
555 within the active region.
557 When set to `start-level', some commands will be performed in all
558 headlines within the active region, provided that these headlines
559 are of the same level than the first one.
561 When set to a string, those commands will be performed on the
562 matching headlines within the active region. Such string must be
563 a tags/property/todo match as it is used in the agenda tags view.
565 The list of commands is: `org-schedule', `org-deadline',
566 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
567 `org-archive-to-archive-sibling'. The archiving commands skip
568 already archived entries."
569 :type '(choice (const :tag "Don't loop" nil)
570 (const :tag "All headlines in active region" t)
571 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
572 (string :tag "Tags/Property/Todo matcher"))
573 :version "24.1"
574 :group 'org-todo
575 :group 'org-archive)
577 (defgroup org-startup nil
578 "Options concerning startup of Org-mode."
579 :tag "Org Startup"
580 :group 'org)
582 (defcustom org-startup-folded t
583 "Non-nil means entering Org-mode will switch to OVERVIEW.
584 This can also be configured on a per-file basis by adding one of
585 the following lines anywhere in the buffer:
587 #+STARTUP: fold (or `overview', this is equivalent)
588 #+STARTUP: nofold (or `showall', this is equivalent)
589 #+STARTUP: content
590 #+STARTUP: showeverything
592 By default, this option is ignored when Org opens agenda files
593 for the first time. If you want the agenda to honor the startup
594 option, set `org-agenda-inhibit-startup' to nil."
595 :group 'org-startup
596 :type '(choice
597 (const :tag "nofold: show all" nil)
598 (const :tag "fold: overview" t)
599 (const :tag "content: all headlines" content)
600 (const :tag "show everything, even drawers" showeverything)))
602 (defcustom org-startup-truncated t
603 "Non-nil means entering Org-mode will set `truncate-lines'.
604 This is useful since some lines containing links can be very long and
605 uninteresting. Also tables look terrible when wrapped."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-startup-indented nil
610 "Non-nil means turn on `org-indent-mode' on startup.
611 This can also be configured on a per-file basis by adding one of
612 the following lines anywhere in the buffer:
614 #+STARTUP: indent
615 #+STARTUP: noindent"
616 :group 'org-structure
617 :type '(choice
618 (const :tag "Not" nil)
619 (const :tag "Globally (slow on startup in large files)" t)))
621 (defcustom org-use-sub-superscripts t
622 "Non-nil means interpret \"_\" and \"^\" for display.
623 When this option is turned on, you can use TeX-like syntax for sub- and
624 superscripts. Several characters after \"_\" or \"^\" will be
625 considered as a single item - so grouping with {} is normally not
626 needed. For example, the following things will be parsed as single
627 sub- or superscripts.
629 10^24 or 10^tau several digits will be considered 1 item.
630 10^-12 or 10^-tau a leading sign with digits or a word
631 x^2-y^3 will be read as x^2 - y^3, because items are
632 terminated by almost any nonword/nondigit char.
633 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
635 Still, ambiguity is possible - so when in doubt use {} to enclose
636 the sub/superscript. If you set this variable to the symbol
637 `{}', the braces are *required* in order to trigger
638 interpretations as sub/superscript. This can be helpful in
639 documents that need \"_\" frequently in plain text."
640 :group 'org-startup
641 :version "24.1"
642 :type '(choice
643 (const :tag "Always interpret" t)
644 (const :tag "Only with braces" {})
645 (const :tag "Never interpret" nil)))
647 (defcustom org-startup-with-beamer-mode nil
648 "Non-nil means turn on `org-beamer-mode' on startup.
649 This can also be configured on a per-file basis by adding one of
650 the following lines anywhere in the buffer:
652 #+STARTUP: beamer"
653 :group 'org-startup
654 :version "24.1"
655 :type 'boolean)
657 (defcustom org-startup-align-all-tables nil
658 "Non-nil means align all tables when visiting a file.
659 This is useful when the column width in tables is forced with <N> cookies
660 in table fields. Such tables will look correct only after the first re-align.
661 This can also be configured on a per-file basis by adding one of
662 the following lines anywhere in the buffer:
663 #+STARTUP: align
664 #+STARTUP: noalign"
665 :group 'org-startup
666 :type 'boolean)
668 (defcustom org-startup-with-inline-images nil
669 "Non-nil means show inline images when loading a new Org file.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
672 #+STARTUP: inlineimages
673 #+STARTUP: noinlineimages"
674 :group 'org-startup
675 :version "24.1"
676 :type 'boolean)
678 (defcustom org-startup-with-latex-preview nil
679 "Non-nil means preview LaTeX fragments when loading a new Org file.
681 This can also be configured on a per-file basis by adding one of
682 the followinglines anywhere in the buffer:
683 #+STARTUP: latexpreview
684 #+STARTUP: nolatexpreview"
685 :group 'org-startup
686 :version "24.3"
687 :type 'boolean)
689 (defcustom org-insert-mode-line-in-empty-file nil
690 "Non-nil means insert the first line setting Org-mode in empty files.
691 When the function `org-mode' is called interactively in an empty file, this
692 normally means that the file name does not automatically trigger Org-mode.
693 To ensure that the file will always be in Org-mode in the future, a
694 line enforcing Org-mode will be inserted into the buffer, if this option
695 has been set."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-replace-disputed-keys nil
700 "Non-nil means use alternative key bindings for some keys.
701 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
702 These keys are also used by other packages like shift-selection-mode'
703 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
704 If you want to use Org-mode together with one of these other modes,
705 or more generally if you would like to move some Org-mode commands to
706 other keys, set this variable and configure the keys with the variable
707 `org-disputed-keys'.
709 This option is only relevant at load-time of Org-mode, and must be set
710 *before* org.el is loaded. Changing it requires a restart of Emacs to
711 become effective."
712 :group 'org-startup
713 :type 'boolean)
715 (defcustom org-use-extra-keys nil
716 "Non-nil means use extra key sequence definitions for certain commands.
717 This happens automatically if you run XEmacs or if `window-system'
718 is nil. This variable lets you do the same manually. You must
719 set it before loading org.
721 Example: on Carbon Emacs 22 running graphically, with an external
722 keyboard on a Powerbook, the default way of setting M-left might
723 not work for either Alt or ESC. Setting this variable will make
724 it work for ESC."
725 :group 'org-startup
726 :type 'boolean)
728 (if (fboundp 'defvaralias)
729 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
731 (defcustom org-disputed-keys
732 '(([(shift up)] . [(meta p)])
733 ([(shift down)] . [(meta n)])
734 ([(shift left)] . [(meta -)])
735 ([(shift right)] . [(meta +)])
736 ([(control shift right)] . [(meta shift +)])
737 ([(control shift left)] . [(meta shift -)]))
738 "Keys for which Org-mode and other modes compete.
739 This is an alist, cars are the default keys, second element specifies
740 the alternative to use when `org-replace-disputed-keys' is t.
742 Keys can be specified in any syntax supported by `define-key'.
743 The value of this option takes effect only at Org-mode's startup,
744 therefore you'll have to restart Emacs to apply it after changing."
745 :group 'org-startup
746 :type 'alist)
748 (defun org-key (key)
749 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
750 Or return the original if not disputed.
751 Also apply the translations defined in `org-xemacs-key-equivalents'."
752 (when org-replace-disputed-keys
753 (let* ((nkey (key-description key))
754 (x (org-find-if (lambda (x)
755 (equal (key-description (car x)) nkey))
756 org-disputed-keys)))
757 (setq key (if x (cdr x) key))))
758 (when (featurep 'xemacs)
759 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
760 key)
762 (defun org-find-if (predicate seq)
763 (catch 'exit
764 (while seq
765 (if (funcall predicate (car seq))
766 (throw 'exit (car seq))
767 (pop seq)))))
769 (defun org-defkey (keymap key def)
770 "Define a key, possibly translated, as returned by `org-key'."
771 (define-key keymap (org-key key) def))
773 (defcustom org-ellipsis nil
774 "The ellipsis to use in the Org-mode outline.
775 When nil, just use the standard three dots. When a string, use that instead,
776 When a face, use the standard 3 dots, but with the specified face.
777 The change affects only Org-mode (which will then use its own display table).
778 Changing this requires executing `M-x org-mode' in a buffer to become
779 effective."
780 :group 'org-startup
781 :type '(choice (const :tag "Default" nil)
782 (face :tag "Face" :value org-warning)
783 (string :tag "String" :value "...#")))
785 (defvar org-display-table nil
786 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
788 (defgroup org-keywords nil
789 "Keywords in Org-mode."
790 :tag "Org Keywords"
791 :group 'org)
793 (defcustom org-deadline-string "DEADLINE:"
794 "String to mark deadline entries.
795 A deadline is this string, followed by a time stamp. Should be a word,
796 terminated by a colon. You can insert a schedule keyword and
797 a timestamp with \\[org-deadline].
798 Changes become only effective after restarting Emacs."
799 :group 'org-keywords
800 :type 'string)
802 (defcustom org-scheduled-string "SCHEDULED:"
803 "String to mark scheduled TODO entries.
804 A schedule is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-schedule].
807 Changes become only effective after restarting Emacs."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-closed-string "CLOSED:"
812 "String used as the prefix for timestamps logging closing a TODO entry."
813 :group 'org-keywords
814 :type 'string)
816 (defcustom org-clock-string "CLOCK:"
817 "String used as prefix for timestamps clocking work hours on an item."
818 :group 'org-keywords
819 :type 'string)
821 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
822 org-scheduled-string "\\|"
823 org-deadline-string "\\|"
824 org-closed-string "\\|"
825 org-clock-string "\\)")
826 "Matches a line with planning or clock info.")
828 (defcustom org-comment-string "COMMENT"
829 "Entries starting with this keyword will never be exported.
830 An entry can be toggled between COMMENT and normal with
831 \\[org-toggle-comment].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-quote-string "QUOTE"
837 "Entries starting with this keyword will be exported in fixed-width font.
838 Quoting applies only to the text in the entry following the headline, and does
839 not extend beyond the next headline, even if that is lower level.
840 An entry can be toggled between QUOTE and normal with
841 \\[org-toggle-fixed-width-section]."
842 :group 'org-keywords
843 :type 'string)
845 (defconst org-repeat-re
846 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
847 "Regular expression for specifying repeated events.
848 After a match, group 1 contains the repeat expression.")
850 (defgroup org-structure nil
851 "Options concerning the general structure of Org-mode files."
852 :tag "Org Structure"
853 :group 'org)
855 (defgroup org-reveal-location nil
856 "Options about how to make context of a location visible."
857 :tag "Org Reveal Location"
858 :group 'org-structure)
860 (defconst org-context-choice
861 '(choice
862 (const :tag "Always" t)
863 (const :tag "Never" nil)
864 (repeat :greedy t :tag "Individual contexts"
865 (cons
866 (choice :tag "Context"
867 (const agenda)
868 (const org-goto)
869 (const occur-tree)
870 (const tags-tree)
871 (const link-search)
872 (const mark-goto)
873 (const bookmark-jump)
874 (const isearch)
875 (const default))
876 (boolean))))
877 "Contexts for the reveal options.")
879 (defcustom org-show-hierarchy-above '((default . t))
880 "Non-nil means show full hierarchy when revealing a location.
881 Org-mode often shows locations in an org-mode file which might have
882 been invisible before. When this is set, the hierarchy of headings
883 above the exposed location is shown.
884 Turning this off for example for sparse trees makes them very compact.
885 Instead of t, this can also be an alist specifying this option for different
886 contexts. Valid contexts are
887 agenda when exposing an entry from the agenda
888 org-goto when using the command `org-goto' on key C-c C-j
889 occur-tree when using the command `org-occur' on key C-c /
890 tags-tree when constructing a sparse tree based on tags matches
891 link-search when exposing search matches associated with a link
892 mark-goto when exposing the jump goal of a mark
893 bookmark-jump when exposing a bookmark location
894 isearch when exiting from an incremental search
895 default default for all contexts not set explicitly"
896 :group 'org-reveal-location
897 :type org-context-choice)
899 (defcustom org-show-following-heading '((default . nil))
900 "Non-nil means show following heading when revealing a location.
901 Org-mode often shows locations in an org-mode file which might have
902 been invisible before. When this is set, the heading following the
903 match is shown.
904 Turning this off for example for sparse trees makes them very compact,
905 but makes it harder to edit the location of the match. In such a case,
906 use the command \\[org-reveal] to show more context.
907 Instead of t, this can also be an alist specifying this option for different
908 contexts. See `org-show-hierarchy-above' for valid contexts."
909 :group 'org-reveal-location
910 :type org-context-choice)
912 (defcustom org-show-siblings '((default . nil) (isearch t))
913 "Non-nil means show all sibling heading when revealing a location.
914 Org-mode often shows locations in an org-mode file which might have
915 been invisible before. When this is set, the sibling of the current entry
916 heading are all made visible. If `org-show-hierarchy-above' is t,
917 the same happens on each level of the hierarchy above the current entry.
919 By default this is on for the isearch context, off for all other contexts.
920 Turning this off for example for sparse trees makes them very compact,
921 but makes it harder to edit the location of the match. In such a case,
922 use the command \\[org-reveal] to show more context.
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-show-entry-below '((default . nil))
929 "Non-nil means show the entry below a headline when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the text below the headline that is
932 exposed is also shown.
934 By default this is off for all contexts.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. See `org-show-hierarchy-above' for valid contexts."
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-indirect-buffer-display 'other-window
941 "How should indirect tree buffers be displayed?
942 This applies to indirect buffers created with the commands
943 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
944 Valid values are:
945 current-window Display in the current window
946 other-window Just display in another window.
947 dedicated-frame Create one new frame, and re-use it each time.
948 new-frame Make a new frame each time. Note that in this case
949 previously-made indirect buffers are kept, and you need to
950 kill these buffers yourself."
951 :group 'org-structure
952 :group 'org-agenda-windows
953 :type '(choice
954 (const :tag "In current window" current-window)
955 (const :tag "In current frame, other window" other-window)
956 (const :tag "Each time a new frame" new-frame)
957 (const :tag "One dedicated frame" dedicated-frame)))
959 (defcustom org-use-speed-commands nil
960 "Non-nil means activate single letter commands at beginning of a headline.
961 This may also be a function to test for appropriate locations where speed
962 commands should be active."
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Never" nil)
966 (const :tag "At beginning of headline stars" t)
967 (function)))
969 (defcustom org-speed-commands-user nil
970 "Alist of additional speed commands.
971 This list will be checked before `org-speed-commands-default'
972 when the variable `org-use-speed-commands' is non-nil
973 and when the cursor is at the beginning of a headline.
974 The car if each entry is a string with a single letter, which must
975 be assigned to `self-insert-command' in the global map.
976 The cdr is either a command to be called interactively, a function
977 to be called, or a form to be evaluated.
978 An entry that is just a list with a single string will be interpreted
979 as a descriptive headline that will be added when listing the speed
980 commands in the Help buffer using the `?' speed command."
981 :group 'org-structure
982 :type '(repeat :value ("k" . ignore)
983 (choice :value ("k" . ignore)
984 (list :tag "Descriptive Headline" (string :tag "Headline"))
985 (cons :tag "Letter and Command"
986 (string :tag "Command letter")
987 (choice
988 (function)
989 (sexp))))))
991 (defgroup org-cycle nil
992 "Options concerning visibility cycling in Org-mode."
993 :tag "Org Cycle"
994 :group 'org-structure)
996 (defcustom org-cycle-skip-children-state-if-no-children t
997 "Non-nil means skip CHILDREN state in entries that don't have any."
998 :group 'org-cycle
999 :type 'boolean)
1001 (defcustom org-cycle-max-level nil
1002 "Maximum level which should still be subject to visibility cycling.
1003 Levels higher than this will, for cycling, be treated as text, not a headline.
1004 When `org-odd-levels-only' is set, a value of N in this variable actually
1005 means 2N-1 stars as the limiting headline.
1006 When nil, cycle all levels.
1007 Note that the limiting level of cycling is also influenced by
1008 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1009 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1010 than its value."
1011 :group 'org-cycle
1012 :type '(choice
1013 (const :tag "No limit" nil)
1014 (integer :tag "Maximum level")))
1016 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1017 "Names of drawers. Drawers are not opened by cycling on the headline above.
1018 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1019 this:
1020 :DRAWERNAME:
1021 .....
1022 :END:
1023 The drawer \"PROPERTIES\" is special for capturing properties through
1024 the property API.
1026 Drawers can be defined on the per-file basis with a line like:
1028 #+DRAWERS: HIDDEN STATE PROPERTIES"
1029 :group 'org-structure
1030 :group 'org-cycle
1031 :type '(repeat (string :tag "Drawer Name")))
1033 (defcustom org-hide-block-startup nil
1034 "Non-nil means entering Org-mode will fold all blocks.
1035 This can also be set in on a per-file basis with
1037 #+STARTUP: hideblocks
1038 #+STARTUP: showblocks"
1039 :group 'org-startup
1040 :group 'org-cycle
1041 :type 'boolean)
1043 (defcustom org-cycle-global-at-bob nil
1044 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1045 This makes it possible to do global cycling without having to use S-TAB or
1046 \\[universal-argument] TAB. For this special case to work, the first line
1047 of the buffer must not be a headline -- it may be empty or some other text.
1048 When used in this way, `org-cycle-hook' is disabled temporarily to make
1049 sure the cursor stays at the beginning of the buffer. When this option is
1050 nil, don't do anything special at the beginning of the buffer."
1051 :group 'org-cycle
1052 :type 'boolean)
1054 (defcustom org-cycle-level-after-item/entry-creation t
1055 "Non-nil means cycle entry level or item indentation in new empty entries.
1057 When the cursor is at the end of an empty headline, i.e., with only stars
1058 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1059 and then all possible ancestor states, before returning to the original state.
1060 This makes data entry extremely fast: M-RET to create a new headline,
1061 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1063 When the cursor is at the end of an empty plain list item, one TAB will
1064 make it a subitem, two or more tabs will back up to make this an item
1065 higher up in the item hierarchy."
1066 :group 'org-cycle
1067 :type 'boolean)
1069 (defcustom org-cycle-emulate-tab t
1070 "Where should `org-cycle' emulate TAB.
1071 nil Never
1072 white Only in completely white lines
1073 whitestart Only at the beginning of lines, before the first non-white char
1074 t Everywhere except in headlines
1075 exc-hl-bol Everywhere except at the start of a headline
1076 If TAB is used in a place where it does not emulate TAB, the current subtree
1077 visibility is cycled."
1078 :group 'org-cycle
1079 :type '(choice (const :tag "Never" nil)
1080 (const :tag "Only in completely white lines" white)
1081 (const :tag "Before first char in a line" whitestart)
1082 (const :tag "Everywhere except in headlines" t)
1083 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1086 (defcustom org-cycle-separator-lines 2
1087 "Number of empty lines needed to keep an empty line between collapsed trees.
1088 If you leave an empty line between the end of a subtree and the following
1089 headline, this empty line is hidden when the subtree is folded.
1090 Org-mode will leave (exactly) one empty line visible if the number of
1091 empty lines is equal or larger to the number given in this variable.
1092 So the default 2 means at least 2 empty lines after the end of a subtree
1093 are needed to produce free space between a collapsed subtree and the
1094 following headline.
1096 If the number is negative, and the number of empty lines is at least -N,
1097 all empty lines are shown.
1099 Special case: when 0, never leave empty lines in collapsed view."
1100 :group 'org-cycle
1101 :type 'integer)
1102 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1104 (defcustom org-pre-cycle-hook nil
1105 "Hook that is run before visibility cycling is happening.
1106 The function(s) in this hook must accept a single argument which indicates
1107 the new state that will be set right after running this hook. The
1108 argument is a symbol. Before a global state change, it can have the values
1109 `overview', `content', or `all'. Before a local state change, it can have
1110 the values `folded', `children', or `subtree'."
1111 :group 'org-cycle
1112 :type 'hook)
1114 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1115 org-cycle-hide-drawers
1116 org-cycle-hide-inline-tasks
1117 org-cycle-show-empty-lines
1118 org-optimize-window-after-visibility-change)
1119 "Hook that is run after `org-cycle' has changed the buffer visibility.
1120 The function(s) in this hook must accept a single argument which indicates
1121 the new state that was set by the most recent `org-cycle' command. The
1122 argument is a symbol. After a global state change, it can have the values
1123 `overview', `contents', or `all'. After a local state change, it can have
1124 the values `folded', `children', or `subtree'."
1125 :group 'org-cycle
1126 :type 'hook)
1128 (defgroup org-edit-structure nil
1129 "Options concerning structure editing in Org-mode."
1130 :tag "Org Edit Structure"
1131 :group 'org-structure)
1133 (defcustom org-odd-levels-only nil
1134 "Non-nil means skip even levels and only use odd levels for the outline.
1135 This has the effect that two stars are being added/taken away in
1136 promotion/demotion commands. It also influences how levels are
1137 handled by the exporters.
1138 Changing it requires restart of `font-lock-mode' to become effective
1139 for fontification also in regions already fontified.
1140 You may also set this on a per-file basis by adding one of the following
1141 lines to the buffer:
1143 #+STARTUP: odd
1144 #+STARTUP: oddeven"
1145 :group 'org-edit-structure
1146 :group 'org-appearance
1147 :type 'boolean)
1149 (defcustom org-adapt-indentation t
1150 "Non-nil means adapt indentation to outline node level.
1152 When this variable is set, Org assumes that you write outlines by
1153 indenting text in each node to align with the headline (after the stars).
1154 The following issues are influenced by this variable:
1156 - When this is set and the *entire* text in an entry is indented, the
1157 indentation is increased by one space in a demotion command, and
1158 decreased by one in a promotion command. If any line in the entry
1159 body starts with text at column 0, indentation is not changed at all.
1161 - Property drawers and planning information is inserted indented when
1162 this variable s set. When nil, they will not be indented.
1164 - TAB indents a line relative to context. The lines below a headline
1165 will be indented when this variable is set.
1167 Note that this is all about true indentation, by adding and removing
1168 space characters. See also `org-indent.el' which does level-dependent
1169 indentation in a virtual way, i.e. at display time in Emacs."
1170 :group 'org-edit-structure
1171 :type 'boolean)
1173 (defcustom org-special-ctrl-a/e nil
1174 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1176 When t, `C-a' will bring back the cursor to the beginning of the
1177 headline text, i.e. after the stars and after a possible TODO
1178 keyword. In an item, this will be the position after bullet and
1179 check-box, if any. When the cursor is already at that position,
1180 another `C-a' will bring it to the beginning of the line.
1182 `C-e' will jump to the end of the headline, ignoring the presence
1183 of tags in the headline. A second `C-e' will then jump to the
1184 true end of the line, after any tags. This also means that, when
1185 this variable is non-nil, `C-e' also will never jump beyond the
1186 end of the heading of a folded section, i.e. not after the
1187 ellipses.
1189 When set to the symbol `reversed', the first `C-a' or `C-e' works
1190 normally, going to the true line boundary first. Only a directly
1191 following, identical keypress will bring the cursor to the
1192 special positions.
1194 This may also be a cons cell where the behavior for `C-a' and
1195 `C-e' is set separately."
1196 :group 'org-edit-structure
1197 :type '(choice
1198 (const :tag "off" nil)
1199 (const :tag "on: after stars/bullet and before tags first" t)
1200 (const :tag "reversed: true line boundary first" reversed)
1201 (cons :tag "Set C-a and C-e separately"
1202 (choice :tag "Special C-a"
1203 (const :tag "off" nil)
1204 (const :tag "on: after stars/bullet first" t)
1205 (const :tag "reversed: before stars/bullet first" reversed))
1206 (choice :tag "Special C-e"
1207 (const :tag "off" nil)
1208 (const :tag "on: before tags first" t)
1209 (const :tag "reversed: after tags first" reversed)))))
1210 (if (fboundp 'defvaralias)
1211 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1213 (defcustom org-special-ctrl-k nil
1214 "Non-nil means `C-k' will behave specially in headlines.
1215 When nil, `C-k' will call the default `kill-line' command.
1216 When t, the following will happen while the cursor is in the headline:
1218 - When the cursor is at the beginning of a headline, kill the entire
1219 line and possible the folded subtree below the line.
1220 - When in the middle of the headline text, kill the headline up to the tags.
1221 - When after the headline text, kill the tags."
1222 :group 'org-edit-structure
1223 :type 'boolean)
1225 (defcustom org-ctrl-k-protect-subtree nil
1226 "Non-nil means, do not delete a hidden subtree with C-k.
1227 When set to the symbol `error', simply throw an error when C-k is
1228 used to kill (part-of) a headline that has hidden text behind it.
1229 Any other non-nil value will result in a query to the user, if it is
1230 OK to kill that hidden subtree. When nil, kill without remorse."
1231 :group 'org-edit-structure
1232 :version "24.1"
1233 :type '(choice
1234 (const :tag "Do not protect hidden subtrees" nil)
1235 (const :tag "Protect hidden subtrees with a security query" t)
1236 (const :tag "Never kill a hidden subtree with C-k" error)))
1238 (defcustom org-catch-invisible-edits nil
1239 "Check if in invisible region before inserting or deleting a character.
1240 Valid values are:
1242 nil Do not check, so just do invisible edits.
1243 error Throw an error and do nothing.
1244 show Make point visible, and do the requested edit.
1245 show-and-error Make point visible, then throw an error and abort the edit.
1246 smart Make point visible, and do insertion/deletion if it is
1247 adjacent to visible text and the change feels predictable.
1248 Never delete a previously invisible character or add in the
1249 middle or right after an invisible region. Basically, this
1250 allows insertion and backward-delete right before ellipses.
1251 FIXME: maybe in this case we should not even show?"
1252 :group 'org-edit-structure
1253 :version "24.1"
1254 :type '(choice
1255 (const :tag "Do not check" nil)
1256 (const :tag "Throw error when trying to edit" error)
1257 (const :tag "Unhide, but do not do the edit" show-and-error)
1258 (const :tag "Show invisible part and do the edit" show)
1259 (const :tag "Be smart and do the right thing" smart)))
1261 (defcustom org-yank-folded-subtrees t
1262 "Non-nil means when yanking subtrees, fold them.
1263 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1264 it starts with a heading and all other headings in it are either children
1265 or siblings, then fold all the subtrees. However, do this only if no
1266 text after the yank would be swallowed into a folded tree by this action."
1267 :group 'org-edit-structure
1268 :type 'boolean)
1270 (defcustom org-yank-adjusted-subtrees nil
1271 "Non-nil means when yanking subtrees, adjust the level.
1272 With this setting, `org-paste-subtree' is used to insert the subtree, see
1273 this function for details."
1274 :group 'org-edit-structure
1275 :type 'boolean)
1277 (defcustom org-M-RET-may-split-line '((default . t))
1278 "Non-nil means M-RET will split the line at the cursor position.
1279 When nil, it will go to the end of the line before making a
1280 new line.
1281 You may also set this option in a different way for different
1282 contexts. Valid contexts are:
1284 headline when creating a new headline
1285 item when creating a new item
1286 table in a table field
1287 default the value to be used for all contexts not explicitly
1288 customized"
1289 :group 'org-structure
1290 :group 'org-table
1291 :type '(choice
1292 (const :tag "Always" t)
1293 (const :tag "Never" nil)
1294 (repeat :greedy t :tag "Individual contexts"
1295 (cons
1296 (choice :tag "Context"
1297 (const headline)
1298 (const item)
1299 (const table)
1300 (const default))
1301 (boolean)))))
1304 (defcustom org-insert-heading-respect-content nil
1305 "Non-nil means insert new headings after the current subtree.
1306 When nil, the new heading is created directly after the current line.
1307 The commands \\[org-insert-heading-respect-content] and
1308 \\[org-insert-todo-heading-respect-content] turn this variable on
1309 for the duration of the command."
1310 :group 'org-structure
1311 :type 'boolean)
1313 (defcustom org-blank-before-new-entry '((heading . auto)
1314 (plain-list-item . auto))
1315 "Should `org-insert-heading' leave a blank line before new heading/item?
1316 The value is an alist, with `heading' and `plain-list-item' as CAR,
1317 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1318 which case Org will look at the surrounding headings/items and try to
1319 make an intelligent decision whether to insert a blank line or not.
1321 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1322 set, the setting here is ignored and no empty line is inserted, to avoid
1323 breaking the list structure."
1324 :group 'org-edit-structure
1325 :type '(list
1326 (cons (const heading)
1327 (choice (const :tag "Never" nil)
1328 (const :tag "Always" t)
1329 (const :tag "Auto" auto)))
1330 (cons (const plain-list-item)
1331 (choice (const :tag "Never" nil)
1332 (const :tag "Always" t)
1333 (const :tag "Auto" auto)))))
1335 (defcustom org-insert-heading-hook nil
1336 "Hook being run after inserting a new heading."
1337 :group 'org-edit-structure
1338 :type 'hook)
1340 (defcustom org-enable-fixed-width-editor t
1341 "Non-nil means lines starting with \":\" are treated as fixed-width.
1342 This currently only means they are never auto-wrapped.
1343 When nil, such lines will be treated like ordinary lines.
1344 See also the QUOTE keyword."
1345 :group 'org-edit-structure
1346 :type 'boolean)
1348 (defcustom org-goto-auto-isearch t
1349 "Non-nil means typing characters in `org-goto' starts incremental search.
1350 When nil, you can use these keybindings to navigate the buffer:
1352 q Quit the org-goto interface
1353 n Go to the next visible heading
1354 p Go to the previous visible heading
1355 f Go one heading forward on same level
1356 b Go one heading backward on same level
1357 u Go one heading up"
1358 :group 'org-edit-structure
1359 :type 'boolean)
1361 (defgroup org-sparse-trees nil
1362 "Options concerning sparse trees in Org-mode."
1363 :tag "Org Sparse Trees"
1364 :group 'org-structure)
1366 (defcustom org-highlight-sparse-tree-matches t
1367 "Non-nil means highlight all matches that define a sparse tree.
1368 The highlights will automatically disappear the next time the buffer is
1369 changed by an edit command."
1370 :group 'org-sparse-trees
1371 :type 'boolean)
1373 (defcustom org-remove-highlights-with-change t
1374 "Non-nil means any change to the buffer will remove temporary highlights.
1375 Such highlights are created by `org-occur' and `org-clock-display'.
1376 When nil, `C-c C-c needs to be used to get rid of the highlights.
1377 The highlights created by `org-preview-latex-fragment' always need
1378 `C-c C-c' to be removed."
1379 :group 'org-sparse-trees
1380 :group 'org-time
1381 :type 'boolean)
1384 (defcustom org-occur-hook '(org-first-headline-recenter)
1385 "Hook that is run after `org-occur' has constructed a sparse tree.
1386 This can be used to recenter the window to show as much of the structure
1387 as possible."
1388 :group 'org-sparse-trees
1389 :type 'hook)
1391 (defgroup org-imenu-and-speedbar nil
1392 "Options concerning imenu and speedbar in Org-mode."
1393 :tag "Org Imenu and Speedbar"
1394 :group 'org-structure)
1396 (defcustom org-imenu-depth 2
1397 "The maximum level for Imenu access to Org-mode headlines.
1398 This also applied for speedbar access."
1399 :group 'org-imenu-and-speedbar
1400 :type 'integer)
1402 (defgroup org-table nil
1403 "Options concerning tables in Org-mode."
1404 :tag "Org Table"
1405 :group 'org)
1407 (defcustom org-enable-table-editor 'optimized
1408 "Non-nil means lines starting with \"|\" are handled by the table editor.
1409 When nil, such lines will be treated like ordinary lines.
1411 When equal to the symbol `optimized', the table editor will be optimized to
1412 do the following:
1413 - Automatic overwrite mode in front of whitespace in table fields.
1414 This makes the structure of the table stay in tact as long as the edited
1415 field does not exceed the column width.
1416 - Minimize the number of realigns. Normally, the table is aligned each time
1417 TAB or RET are pressed to move to another field. With optimization this
1418 happens only if changes to a field might have changed the column width.
1419 Optimization requires replacing the functions `self-insert-command',
1420 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1421 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1422 very good at guessing when a re-align will be necessary, but you can always
1423 force one with \\[org-ctrl-c-ctrl-c].
1425 If you would like to use the optimized version in Org-mode, but the
1426 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1428 This variable can be used to turn on and off the table editor during a session,
1429 but in order to toggle optimization, a restart is required.
1431 See also the variable `org-table-auto-blank-field'."
1432 :group 'org-table
1433 :type '(choice
1434 (const :tag "off" nil)
1435 (const :tag "on" t)
1436 (const :tag "on, optimized" optimized)))
1438 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1439 (version<= emacs-version "24.1"))
1440 "Non-nil means cluster self-insert commands for undo when possible.
1441 If this is set, then, like in the Emacs command loop, 20 consecutive
1442 characters will be undone together.
1443 This is configurable, because there is some impact on typing performance."
1444 :group 'org-table
1445 :type 'boolean)
1447 (defcustom org-table-tab-recognizes-table.el t
1448 "Non-nil means TAB will automatically notice a table.el table.
1449 When it sees such a table, it moves point into it and - if necessary -
1450 calls `table-recognize-table'."
1451 :group 'org-table-editing
1452 :type 'boolean)
1454 (defgroup org-link nil
1455 "Options concerning links in Org-mode."
1456 :tag "Org Link"
1457 :group 'org)
1459 (defvar org-link-abbrev-alist-local nil
1460 "Buffer-local version of `org-link-abbrev-alist', which see.
1461 The value of this is taken from the #+LINK lines.")
1462 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1464 (defcustom org-link-abbrev-alist nil
1465 "Alist of link abbreviations.
1466 The car of each element is a string, to be replaced at the start of a link.
1467 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1468 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1470 [[linkkey:tag][description]]
1472 The 'linkkey' must be a word word, starting with a letter, followed
1473 by letters, numbers, '-' or '_'.
1475 If REPLACE is a string, the tag will simply be appended to create the link.
1476 If the string contains \"%s\", the tag will be inserted there. If the string
1477 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1478 at that point (see the function `url-hexify-string'). If the string contains
1479 the specifier \"%(my-function)\", then the custom function `my-function' will
1480 be invoked: this function takes the tag as its only argument and must return
1481 a string.
1483 REPLACE may also be a function that will be called with the tag as the
1484 only argument to create the link, which should be returned as a string.
1486 See the manual for examples."
1487 :group 'org-link
1488 :type '(repeat
1489 (cons
1490 (string :tag "Protocol")
1491 (choice
1492 (string :tag "Format")
1493 (function)))))
1495 (defcustom org-descriptive-links t
1496 "Non-nil means Org will display descriptive links.
1497 E.g. [[http://orgmode.org][Org website]] will be displayed as
1498 \"Org Website\", hiding the link itself and just displaying its
1499 description. When set to `nil', Org will display the full links
1500 literally.
1502 You can interactively set the value of this variable by calling
1503 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1504 :group 'org-link
1505 :type 'boolean)
1507 (defcustom org-link-file-path-type 'adaptive
1508 "How the path name in file links should be stored.
1509 Valid values are:
1511 relative Relative to the current directory, i.e. the directory of the file
1512 into which the link is being inserted.
1513 absolute Absolute path, if possible with ~ for home directory.
1514 noabbrev Absolute path, no abbreviation of home directory.
1515 adaptive Use relative path for files in the current directory and sub-
1516 directories of it. For other files, use an absolute path."
1517 :group 'org-link
1518 :type '(choice
1519 (const relative)
1520 (const absolute)
1521 (const noabbrev)
1522 (const adaptive)))
1524 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1525 "Types of links that should be activated in Org-mode files.
1526 This is a list of symbols, each leading to the activation of a certain link
1527 type. In principle, it does not hurt to turn on most link types - there may
1528 be a small gain when turning off unused link types. The types are:
1530 bracket The recommended [[link][description]] or [[link]] links with hiding.
1531 angle Links in angular brackets that may contain whitespace like
1532 <bbdb:Carsten Dominik>.
1533 plain Plain links in normal text, no whitespace, like http://google.com.
1534 radio Text that is matched by a radio target, see manual for details.
1535 tag Tag settings in a headline (link to tag search).
1536 date Time stamps (link to calendar).
1537 footnote Footnote labels.
1539 Changing this variable requires a restart of Emacs to become effective."
1540 :group 'org-link
1541 :type '(set :greedy t
1542 (const :tag "Double bracket links" bracket)
1543 (const :tag "Angular bracket links" angle)
1544 (const :tag "Plain text links" plain)
1545 (const :tag "Radio target matches" radio)
1546 (const :tag "Tags" tag)
1547 (const :tag "Timestamps" date)
1548 (const :tag "Footnotes" footnote)))
1550 (defcustom org-make-link-description-function nil
1551 "Function to use for generating link descriptions from links.
1552 When nil, the link location will be used. This function must take
1553 two parameters: the first one is the link, the second one is the
1554 description generated by `org-insert-link'. The function should
1555 return the description to use."
1556 :group 'org-link
1557 :type 'function)
1559 (defgroup org-link-store nil
1560 "Options concerning storing links in Org-mode."
1561 :tag "Org Store Link"
1562 :group 'org-link)
1564 (defcustom org-url-hexify-p t
1565 "When non-nil, hexify URL when creating a link."
1566 :type 'boolean
1567 :version "24.3"
1568 :group 'org-link-store)
1570 (defcustom org-email-link-description-format "Email %c: %.30s"
1571 "Format of the description part of a link to an email or usenet message.
1572 The following %-escapes will be replaced by corresponding information:
1574 %F full \"From\" field
1575 %f name, taken from \"From\" field, address if no name
1576 %T full \"To\" field
1577 %t first name in \"To\" field, address if no name
1578 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1579 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1580 %s subject
1581 %d date
1582 %m message-id.
1584 You may use normal field width specification between the % and the letter.
1585 This is for example useful to limit the length of the subject.
1587 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1588 :group 'org-link-store
1589 :type 'string)
1591 (defcustom org-from-is-user-regexp
1592 (let (r1 r2)
1593 (when (and user-mail-address (not (string= user-mail-address "")))
1594 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1595 (when (and user-full-name (not (string= user-full-name "")))
1596 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1597 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1598 "Regexp matched against the \"From:\" header of an email or usenet message.
1599 It should match if the message is from the user him/herself."
1600 :group 'org-link-store
1601 :type 'regexp)
1603 (defcustom org-context-in-file-links t
1604 "Non-nil means file links from `org-store-link' contain context.
1605 A search string will be added to the file name with :: as separator and
1606 used to find the context when the link is activated by the command
1607 `org-open-at-point'. When this option is t, the entire active region
1608 will be placed in the search string of the file link. If set to a
1609 positive integer, only the first n lines of context will be stored.
1611 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1612 negates this setting for the duration of the command."
1613 :group 'org-link-store
1614 :type '(choice boolean integer))
1616 (defcustom org-keep-stored-link-after-insertion nil
1617 "Non-nil means keep link in list for entire session.
1619 The command `org-store-link' adds a link pointing to the current
1620 location to an internal list. These links accumulate during a session.
1621 The command `org-insert-link' can be used to insert links into any
1622 Org-mode file (offering completion for all stored links). When this
1623 option is nil, every link which has been inserted once using \\[org-insert-link]
1624 will be removed from the list, to make completing the unused links
1625 more efficient."
1626 :group 'org-link-store
1627 :type 'boolean)
1629 (defgroup org-link-follow nil
1630 "Options concerning following links in Org-mode."
1631 :tag "Org Follow Link"
1632 :group 'org-link)
1634 (defcustom org-link-translation-function nil
1635 "Function to translate links with different syntax to Org syntax.
1636 This can be used to translate links created for example by the Planner
1637 or emacs-wiki packages to Org syntax.
1638 The function must accept two parameters, a TYPE containing the link
1639 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1640 which is everything after the link protocol. It should return a cons
1641 with possibly modified values of type and path.
1642 Org contains a function for this, so if you set this variable to
1643 `org-translate-link-from-planner', you should be able follow many
1644 links created by planner."
1645 :group 'org-link-follow
1646 :type 'function)
1648 (defcustom org-follow-link-hook nil
1649 "Hook that is run after a link has been followed."
1650 :group 'org-link-follow
1651 :type 'hook)
1653 (defcustom org-tab-follows-link nil
1654 "Non-nil means on links TAB will follow the link.
1655 Needs to be set before org.el is loaded.
1656 This really should not be used, it does not make sense, and the
1657 implementation is bad."
1658 :group 'org-link-follow
1659 :type 'boolean)
1661 (defcustom org-return-follows-link nil
1662 "Non-nil means on links RET will follow the link.
1663 In tables, the special behavior of RET has precedence."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-mouse-1-follows-link
1668 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1669 "Non-nil means mouse-1 on a link will follow the link.
1670 A longer mouse click will still set point. Does not work on XEmacs.
1671 Needs to be set before org.el is loaded."
1672 :group 'org-link-follow
1673 :type 'boolean)
1675 (defcustom org-mark-ring-length 4
1676 "Number of different positions to be recorded in the ring.
1677 Changing this requires a restart of Emacs to work correctly."
1678 :group 'org-link-follow
1679 :type 'integer)
1681 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1682 "Non-nil means internal links in Org files must exactly match a headline.
1683 When nil, the link search tries to match a phrase with all words
1684 in the search text."
1685 :group 'org-link-follow
1686 :version "24.1"
1687 :type '(choice
1688 (const :tag "Use fuzzy text search" nil)
1689 (const :tag "Match only exact headline" t)
1690 (const :tag "Match exact headline or query to create it"
1691 query-to-create)))
1693 (defcustom org-link-frame-setup
1694 '((vm . vm-visit-folder-other-frame)
1695 (vm-imap . vm-visit-imap-folder-other-frame)
1696 (gnus . org-gnus-no-new-news)
1697 (file . find-file-other-window)
1698 (wl . wl-other-frame))
1699 "Setup the frame configuration for following links.
1700 When following a link with Emacs, it may often be useful to display
1701 this link in another window or frame. This variable can be used to
1702 set this up for the different types of links.
1703 For VM, use any of
1704 `vm-visit-folder'
1705 `vm-visit-folder-other-window'
1706 `vm-visit-folder-other-frame'
1707 For Gnus, use any of
1708 `gnus'
1709 `gnus-other-frame'
1710 `org-gnus-no-new-news'
1711 For FILE, use any of
1712 `find-file'
1713 `find-file-other-window'
1714 `find-file-other-frame'
1715 For Wanderlust use any of
1716 `wl'
1717 `wl-other-frame'
1718 For the calendar, use the variable `calendar-setup'.
1719 For BBDB, it is currently only possible to display the matches in
1720 another window."
1721 :group 'org-link-follow
1722 :type '(list
1723 (cons (const vm)
1724 (choice
1725 (const vm-visit-folder)
1726 (const vm-visit-folder-other-window)
1727 (const vm-visit-folder-other-frame)))
1728 (cons (const gnus)
1729 (choice
1730 (const gnus)
1731 (const gnus-other-frame)
1732 (const org-gnus-no-new-news)))
1733 (cons (const file)
1734 (choice
1735 (const find-file)
1736 (const find-file-other-window)
1737 (const find-file-other-frame)))
1738 (cons (const wl)
1739 (choice
1740 (const wl)
1741 (const wl-other-frame)))))
1743 (defcustom org-display-internal-link-with-indirect-buffer nil
1744 "Non-nil means use indirect buffer to display infile links.
1745 Activating internal links (from one location in a file to another location
1746 in the same file) normally just jumps to the location. When the link is
1747 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1748 is displayed in
1749 another window. When this option is set, the other window actually displays
1750 an indirect buffer clone of the current buffer, to avoid any visibility
1751 changes to the current buffer."
1752 :group 'org-link-follow
1753 :type 'boolean)
1755 (defcustom org-open-non-existing-files nil
1756 "Non-nil means `org-open-file' will open non-existing files.
1757 When nil, an error will be generated.
1758 This variable applies only to external applications because they
1759 might choke on non-existing files. If the link is to a file that
1760 will be opened in Emacs, the variable is ignored."
1761 :group 'org-link-follow
1762 :type 'boolean)
1764 (defcustom org-open-directory-means-index-dot-org nil
1765 "Non-nil means a link to a directory really means to index.org.
1766 When nil, following a directory link will run dired or open a finder/explorer
1767 window on that directory."
1768 :group 'org-link-follow
1769 :type 'boolean)
1771 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1772 "Function and arguments to call for following mailto links.
1773 This is a list with the first element being a Lisp function, and the
1774 remaining elements being arguments to the function. In string arguments,
1775 %a will be replaced by the address, and %s will be replaced by the subject
1776 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1777 :group 'org-link-follow
1778 :type '(choice
1779 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1780 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1781 (const :tag "message-mail" (message-mail "%a" "%s"))
1782 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1784 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1785 "Non-nil means ask for confirmation before executing shell links.
1786 Shell links can be dangerous: just think about a link
1788 [[shell:rm -rf ~/*][Google Search]]
1790 This link would show up in your Org-mode document as \"Google Search\",
1791 but really it would remove your entire home directory.
1792 Therefore we advise against setting this variable to nil.
1793 Just change it to `y-or-n-p' if you want to confirm with a
1794 single keystroke rather than having to type \"yes\"."
1795 :group 'org-link-follow
1796 :type '(choice
1797 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1798 (const :tag "with y-or-n (faster)" y-or-n-p)
1799 (const :tag "no confirmation (dangerous)" nil)))
1800 (put 'org-confirm-shell-link-function
1801 'safe-local-variable
1802 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1804 (defcustom org-confirm-shell-link-not-regexp ""
1805 "A regexp to skip confirmation for shell links."
1806 :group 'org-link-follow
1807 :version "24.1"
1808 :type 'regexp)
1810 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1811 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1812 Elisp links can be dangerous: just think about a link
1814 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1816 This link would show up in your Org-mode document as \"Google Search\",
1817 but really it would remove your entire home directory.
1818 Therefore we advise against setting this variable to nil.
1819 Just change it to `y-or-n-p' if you want to confirm with a
1820 single keystroke rather than having to type \"yes\"."
1821 :group 'org-link-follow
1822 :type '(choice
1823 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1824 (const :tag "with y-or-n (faster)" y-or-n-p)
1825 (const :tag "no confirmation (dangerous)" nil)))
1826 (put 'org-confirm-shell-link-function
1827 'safe-local-variable
1828 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1830 (defcustom org-confirm-elisp-link-not-regexp ""
1831 "A regexp to skip confirmation for Elisp links."
1832 :group 'org-link-follow
1833 :version "24.1"
1834 :type 'regexp)
1836 (defconst org-file-apps-defaults-gnu
1837 '((remote . emacs)
1838 (system . mailcap)
1839 (t . mailcap))
1840 "Default file applications on a UNIX or GNU/Linux system.
1841 See `org-file-apps'.")
1843 (defconst org-file-apps-defaults-macosx
1844 '((remote . emacs)
1845 (t . "open %s")
1846 (system . "open %s")
1847 ("ps.gz" . "gv %s")
1848 ("eps.gz" . "gv %s")
1849 ("dvi" . "xdvi %s")
1850 ("fig" . "xfig %s"))
1851 "Default file applications on a MacOS X system.
1852 The system \"open\" is known as a default, but we use X11 applications
1853 for some files for which the OS does not have a good default.
1854 See `org-file-apps'.")
1856 (defconst org-file-apps-defaults-windowsnt
1857 (list
1858 '(remote . emacs)
1859 (cons t
1860 (list (if (featurep 'xemacs)
1861 'mswindows-shell-execute
1862 'w32-shell-execute)
1863 "open" 'file))
1864 (cons 'system
1865 (list (if (featurep 'xemacs)
1866 'mswindows-shell-execute
1867 'w32-shell-execute)
1868 "open" 'file)))
1869 "Default file applications on a Windows NT system.
1870 The system \"open\" is used for most files.
1871 See `org-file-apps'.")
1873 (defcustom org-file-apps
1875 (auto-mode . emacs)
1876 ("\\.mm\\'" . default)
1877 ("\\.x?html?\\'" . default)
1878 ("\\.pdf\\'" . default)
1880 "External applications for opening `file:path' items in a document.
1881 Org-mode uses system defaults for different file types, but
1882 you can use this variable to set the application for a given file
1883 extension. The entries in this list are cons cells where the car identifies
1884 files and the cdr the corresponding command. Possible values for the
1885 file identifier are
1886 \"string\" A string as a file identifier can be interpreted in different
1887 ways, depending on its contents:
1889 - Alphanumeric characters only:
1890 Match links with this file extension.
1891 Example: (\"pdf\" . \"evince %s\")
1892 to open PDFs with evince.
1894 - Regular expression: Match links where the
1895 filename matches the regexp. If you want to
1896 use groups here, use shy groups.
1898 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1899 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1900 to open *.html and *.xhtml with firefox.
1902 - Regular expression which contains (non-shy) groups:
1903 Match links where the whole link, including \"::\", and
1904 anything after that, matches the regexp.
1905 In a custom command string, %1, %2, etc. are replaced with
1906 the parts of the link that were matched by the groups.
1907 For backwards compatibility, if a command string is given
1908 that does not use any of the group matches, this case is
1909 handled identically to the second one (i.e. match against
1910 file name only).
1911 In a custom lisp form, you can access the group matches with
1912 (match-string n link).
1914 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1915 to open [[file:document.pdf::5]] with evince at page 5.
1917 `directory' Matches a directory
1918 `remote' Matches a remote file, accessible through tramp or efs.
1919 Remote files most likely should be visited through Emacs
1920 because external applications cannot handle such paths.
1921 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1922 so all files Emacs knows how to handle. Using this with
1923 command `emacs' will open most files in Emacs. Beware that this
1924 will also open html files inside Emacs, unless you add
1925 (\"html\" . default) to the list as well.
1926 t Default for files not matched by any of the other options.
1927 `system' The system command to open files, like `open' on Windows
1928 and Mac OS X, and mailcap under GNU/Linux. This is the command
1929 that will be selected if you call `C-c C-o' with a double
1930 \\[universal-argument] \\[universal-argument] prefix.
1932 Possible values for the command are:
1933 `emacs' The file will be visited by the current Emacs process.
1934 `default' Use the default application for this file type, which is the
1935 association for t in the list, most likely in the system-specific
1936 part.
1937 This can be used to overrule an unwanted setting in the
1938 system-specific variable.
1939 `system' Use the system command for opening files, like \"open\".
1940 This command is specified by the entry whose car is `system'.
1941 Most likely, the system-specific version of this variable
1942 does define this command, but you can overrule/replace it
1943 here.
1944 string A command to be executed by a shell; %s will be replaced
1945 by the path to the file.
1946 sexp A Lisp form which will be evaluated. The file path will
1947 be available in the Lisp variable `file'.
1948 For more examples, see the system specific constants
1949 `org-file-apps-defaults-macosx'
1950 `org-file-apps-defaults-windowsnt'
1951 `org-file-apps-defaults-gnu'."
1952 :group 'org-link-follow
1953 :type '(repeat
1954 (cons (choice :value ""
1955 (string :tag "Extension")
1956 (const :tag "System command to open files" system)
1957 (const :tag "Default for unrecognized files" t)
1958 (const :tag "Remote file" remote)
1959 (const :tag "Links to a directory" directory)
1960 (const :tag "Any files that have Emacs modes"
1961 auto-mode))
1962 (choice :value ""
1963 (const :tag "Visit with Emacs" emacs)
1964 (const :tag "Use default" default)
1965 (const :tag "Use the system command" system)
1966 (string :tag "Command")
1967 (sexp :tag "Lisp form")))))
1969 (defcustom org-doi-server-url "http://dx.doi.org/"
1970 "The URL of the DOI server."
1971 :type 'string
1972 :version "24.3"
1973 :group 'org-link-follow)
1975 (defgroup org-refile nil
1976 "Options concerning refiling entries in Org-mode."
1977 :tag "Org Refile"
1978 :group 'org)
1980 (defcustom org-directory "~/org"
1981 "Directory with org files.
1982 This is just a default location to look for Org files. There is no need
1983 at all to put your files into this directory. It is only used in the
1984 following situations:
1986 1. When a capture template specifies a target file that is not an
1987 absolute path. The path will then be interpreted relative to
1988 `org-directory'
1989 2. When a capture note is filed away in an interactive way (when exiting the
1990 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1991 with `org-directory' as the default path."
1992 :group 'org-refile
1993 :group 'org-remember
1994 :group 'org-capture
1995 :type 'directory)
1997 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1998 "Default target for storing notes.
1999 Used as a fall back file for org-remember.el and org-capture.el, for
2000 templates that do not specify a target file."
2001 :group 'org-refile
2002 :group 'org-remember
2003 :group 'org-capture
2004 :type '(choice
2005 (const :tag "Default from remember-data-file" nil)
2006 file))
2008 (defcustom org-goto-interface 'outline
2009 "The default interface to be used for `org-goto'.
2010 Allowed values are:
2011 outline The interface shows an outline of the relevant file
2012 and the correct heading is found by moving through
2013 the outline or by searching with incremental search.
2014 outline-path-completion Headlines in the current buffer are offered via
2015 completion. This is the interface also used by
2016 the refile command."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Outline" outline)
2020 (const :tag "Outline-path-completion" outline-path-completion)))
2022 (defcustom org-goto-max-level 5
2023 "Maximum target level when running `org-goto' with refile interface."
2024 :group 'org-refile
2025 :type 'integer)
2027 (defcustom org-reverse-note-order nil
2028 "Non-nil means store new notes at the beginning of a file or entry.
2029 When nil, new notes will be filed to the end of a file or entry.
2030 This can also be a list with cons cells of regular expressions that
2031 are matched against file names, and values."
2032 :group 'org-remember
2033 :group 'org-capture
2034 :group 'org-refile
2035 :type '(choice
2036 (const :tag "Reverse always" t)
2037 (const :tag "Reverse never" nil)
2038 (repeat :tag "By file name regexp"
2039 (cons regexp boolean))))
2041 (defcustom org-log-refile nil
2042 "Information to record when a task is refiled.
2044 Possible values are:
2046 nil Don't add anything
2047 time Add a time stamp to the task
2048 note Prompt for a note and add it with template `org-log-note-headings'
2050 This option can also be set with on a per-file-basis with
2052 #+STARTUP: nologrefile
2053 #+STARTUP: logrefile
2054 #+STARTUP: lognoterefile
2056 You can have local logging settings for a subtree by setting the LOGGING
2057 property to one or more of these keywords.
2059 When bulk-refiling from the agenda, the value `note' is forbidden and
2060 will temporarily be changed to `time'."
2061 :group 'org-refile
2062 :group 'org-progress
2063 :version "24.1"
2064 :type '(choice
2065 (const :tag "No logging" nil)
2066 (const :tag "Record timestamp" time)
2067 (const :tag "Record timestamp with note." note)))
2069 (defcustom org-refile-targets nil
2070 "Targets for refiling entries with \\[org-refile].
2071 This is a list of cons cells. Each cell contains:
2072 - a specification of the files to be considered, either a list of files,
2073 or a symbol whose function or variable value will be used to retrieve
2074 a file name or a list of file names. If you use `org-agenda-files' for
2075 that, all agenda files will be scanned for targets. Nil means consider
2076 headings in the current buffer.
2077 - A specification of how to find candidate refile targets. This may be
2078 any of:
2079 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2080 This tag has to be present in all target headlines, inheritance will
2081 not be considered.
2082 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2083 todo keyword.
2084 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2085 headlines that are refiling targets.
2086 - a cons cell (:level . N). Any headline of level N is considered a target.
2087 Note that, when `org-odd-levels-only' is set, level corresponds to
2088 order in hierarchy, not to the number of stars.
2089 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2090 Note that, when `org-odd-levels-only' is set, level corresponds to
2091 order in hierarchy, not to the number of stars.
2093 Each element of this list generates a set of possible targets.
2094 The union of these sets is presented (with completion) to
2095 the user by `org-refile'.
2097 You can set the variable `org-refile-target-verify-function' to a function
2098 to verify each headline found by the simple criteria above.
2100 When this variable is nil, all top-level headlines in the current buffer
2101 are used, equivalent to the value `((nil . (:level . 1))'."
2102 :group 'org-refile
2103 :type '(repeat
2104 (cons
2105 (choice :value org-agenda-files
2106 (const :tag "All agenda files" org-agenda-files)
2107 (const :tag "Current buffer" nil)
2108 (function) (variable) (file))
2109 (choice :tag "Identify target headline by"
2110 (cons :tag "Specific tag" (const :value :tag) (string))
2111 (cons :tag "TODO keyword" (const :value :todo) (string))
2112 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2113 (cons :tag "Level number" (const :value :level) (integer))
2114 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2116 (defcustom org-refile-target-verify-function nil
2117 "Function to verify if the headline at point should be a refile target.
2118 The function will be called without arguments, with point at the
2119 beginning of the headline. It should return t and leave point
2120 where it is if the headline is a valid target for refiling.
2122 If the target should not be selected, the function must return nil.
2123 In addition to this, it may move point to a place from where the search
2124 should be continued. For example, the function may decide that the entire
2125 subtree of the current entry should be excluded and move point to the end
2126 of the subtree."
2127 :group 'org-refile
2128 :type 'function)
2130 (defcustom org-refile-use-cache nil
2131 "Non-nil means cache refile targets to speed up the process.
2132 The cache for a particular file will be updated automatically when
2133 the buffer has been killed, or when any of the marker used for flagging
2134 refile targets no longer points at a live buffer.
2135 If you have added new entries to a buffer that might themselves be targets,
2136 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2137 find that easier, `C-u C-u C-u C-c C-w'."
2138 :group 'org-refile
2139 :version "24.1"
2140 :type 'boolean)
2142 (defcustom org-refile-use-outline-path nil
2143 "Non-nil means provide refile targets as paths.
2144 So a level 3 headline will be available as level1/level2/level3.
2146 When the value is `file', also include the file name (without directory)
2147 into the path. In this case, you can also stop the completion after
2148 the file name, to get entries inserted as top level in the file.
2150 When `full-file-path', include the full file path."
2151 :group 'org-refile
2152 :type '(choice
2153 (const :tag "Not" nil)
2154 (const :tag "Yes" t)
2155 (const :tag "Start with file name" file)
2156 (const :tag "Start with full file path" full-file-path)))
2158 (defcustom org-outline-path-complete-in-steps t
2159 "Non-nil means complete the outline path in hierarchical steps.
2160 When Org-mode uses the refile interface to select an outline path
2161 \(see variable `org-refile-use-outline-path'), the completion of
2162 the path can be done is a single go, or if can be done in steps down
2163 the headline hierarchy. Going in steps is probably the best if you
2164 do not use a special completion package like `ido' or `icicles'.
2165 However, when using these packages, going in one step can be very
2166 fast, while still showing the whole path to the entry."
2167 :group 'org-refile
2168 :type 'boolean)
2170 (defcustom org-refile-allow-creating-parent-nodes nil
2171 "Non-nil means allow to create new nodes as refile targets.
2172 New nodes are then created by adding \"/new node name\" to the completion
2173 of an existing node. When the value of this variable is `confirm',
2174 new node creation must be confirmed by the user (recommended)
2175 When nil, the completion must match an existing entry.
2177 Note that, if the new heading is not seen by the criteria
2178 listed in `org-refile-targets', multiple instances of the same
2179 heading would be created by trying again to file under the new
2180 heading."
2181 :group 'org-refile
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "Always" t)
2185 (const :tag "Prompt for confirmation" confirm)))
2187 (defcustom org-refile-active-region-within-subtree nil
2188 "Non-nil means also refile active region within a subtree.
2190 By default `org-refile' doesn't allow refiling regions if they
2191 don't contain a set of subtrees, but it might be convenient to
2192 do so sometimes: in that case, the first line of the region is
2193 converted to a headline before refiling."
2194 :group 'org-refile
2195 :version "24.1"
2196 :type 'boolean)
2198 (defgroup org-todo nil
2199 "Options concerning TODO items in Org-mode."
2200 :tag "Org TODO"
2201 :group 'org)
2203 (defgroup org-progress nil
2204 "Options concerning Progress logging in Org-mode."
2205 :tag "Org Progress"
2206 :group 'org-time)
2208 (defvar org-todo-interpretation-widgets
2209 '((:tag "Sequence (cycling hits every state)" sequence)
2210 (:tag "Type (cycling directly to DONE)" type))
2211 "The available interpretation symbols for customizing `org-todo-keywords'.
2212 Interested libraries should add to this list.")
2214 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2215 "List of TODO entry keyword sequences and their interpretation.
2216 \\<org-mode-map>This is a list of sequences.
2218 Each sequence starts with a symbol, either `sequence' or `type',
2219 indicating if the keywords should be interpreted as a sequence of
2220 action steps, or as different types of TODO items. The first
2221 keywords are states requiring action - these states will select a headline
2222 for inclusion into the global TODO list Org-mode produces. If one of
2223 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2224 signify that no further action is necessary. If \"|\" is not found,
2225 the last keyword is treated as the only DONE state of the sequence.
2227 The command \\[org-todo] cycles an entry through these states, and one
2228 additional state where no keyword is present. For details about this
2229 cycling, see the manual.
2231 TODO keywords and interpretation can also be set on a per-file basis with
2232 the special #+SEQ_TODO and #+TYP_TODO lines.
2234 Each keyword can optionally specify a character for fast state selection
2235 \(in combination with the variable `org-use-fast-todo-selection')
2236 and specifiers for state change logging, using the same syntax that
2237 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2238 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2239 indicates to record a time stamp each time this state is selected.
2241 Each keyword may also specify if a timestamp or a note should be
2242 recorded when entering or leaving the state, by adding additional
2243 characters in the parenthesis after the keyword. This looks like this:
2244 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2245 record only the time of the state change. With X and Y being either
2246 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2247 Y when leaving the state if and only if the *target* state does not
2248 define X. You may omit any of the fast-selection key or X or /Y,
2249 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2251 For backward compatibility, this variable may also be just a list
2252 of keywords. In this case the interpretation (sequence or type) will be
2253 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2254 :group 'org-todo
2255 :group 'org-keywords
2256 :type '(choice
2257 (repeat :tag "Old syntax, just keywords"
2258 (string :tag "Keyword"))
2259 (repeat :tag "New syntax"
2260 (cons
2261 (choice
2262 :tag "Interpretation"
2263 ;;Quick and dirty way to see
2264 ;;`org-todo-interpretations'. This takes the
2265 ;;place of item arguments
2266 :convert-widget
2267 (lambda (widget)
2268 (widget-put widget
2269 :args (mapcar
2270 #'(lambda (x)
2271 (widget-convert
2272 (cons 'const x)))
2273 org-todo-interpretation-widgets))
2274 widget))
2275 (repeat
2276 (string :tag "Keyword"))))))
2278 (defvar org-todo-keywords-1 nil
2279 "All TODO and DONE keywords active in a buffer.")
2280 (make-variable-buffer-local 'org-todo-keywords-1)
2281 (defvar org-todo-keywords-for-agenda nil)
2282 (defvar org-done-keywords-for-agenda nil)
2283 (defvar org-drawers-for-agenda nil)
2284 (defvar org-todo-keyword-alist-for-agenda nil)
2285 (defvar org-tag-alist-for-agenda nil)
2286 (defvar org-agenda-contributing-files nil)
2287 (defvar org-not-done-keywords nil)
2288 (make-variable-buffer-local 'org-not-done-keywords)
2289 (defvar org-done-keywords nil)
2290 (make-variable-buffer-local 'org-done-keywords)
2291 (defvar org-todo-heads nil)
2292 (make-variable-buffer-local 'org-todo-heads)
2293 (defvar org-todo-sets nil)
2294 (make-variable-buffer-local 'org-todo-sets)
2295 (defvar org-todo-log-states nil)
2296 (make-variable-buffer-local 'org-todo-log-states)
2297 (defvar org-todo-kwd-alist nil)
2298 (make-variable-buffer-local 'org-todo-kwd-alist)
2299 (defvar org-todo-key-alist nil)
2300 (make-variable-buffer-local 'org-todo-key-alist)
2301 (defvar org-todo-key-trigger nil)
2302 (make-variable-buffer-local 'org-todo-key-trigger)
2304 (defcustom org-todo-interpretation 'sequence
2305 "Controls how TODO keywords are interpreted.
2306 This variable is in principle obsolete and is only used for
2307 backward compatibility, if the interpretation of todo keywords is
2308 not given already in `org-todo-keywords'. See that variable for
2309 more information."
2310 :group 'org-todo
2311 :group 'org-keywords
2312 :type '(choice (const sequence)
2313 (const type)))
2315 (defcustom org-use-fast-todo-selection t
2316 "Non-nil means use the fast todo selection scheme with C-c C-t.
2317 This variable describes if and under what circumstances the cycling
2318 mechanism for TODO keywords will be replaced by a single-key, direct
2319 selection scheme.
2321 When nil, fast selection is never used.
2323 When the symbol `prefix', it will be used when `org-todo' is called
2324 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2325 `C-u t' in an agenda buffer.
2327 When t, fast selection is used by default. In this case, the prefix
2328 argument forces cycling instead.
2330 In all cases, the special interface is only used if access keys have
2331 actually been assigned by the user, i.e. if keywords in the configuration
2332 are followed by a letter in parenthesis, like TODO(t)."
2333 :group 'org-todo
2334 :type '(choice
2335 (const :tag "Never" nil)
2336 (const :tag "By default" t)
2337 (const :tag "Only with C-u C-c C-t" prefix)))
2339 (defcustom org-provide-todo-statistics t
2340 "Non-nil means update todo statistics after insert and toggle.
2341 ALL-HEADLINES means update todo statistics by including headlines
2342 with no TODO keyword as well, counting them as not done.
2343 A list of TODO keywords means the same, but skip keywords that are
2344 not in this list.
2346 When this is set, todo statistics is updated in the parent of the
2347 current entry each time a todo state is changed."
2348 :group 'org-todo
2349 :type '(choice
2350 (const :tag "Yes, only for TODO entries" t)
2351 (const :tag "Yes, including all entries" 'all-headlines)
2352 (repeat :tag "Yes, for TODOs in this list"
2353 (string :tag "TODO keyword"))
2354 (other :tag "No TODO statistics" nil)))
2356 (defcustom org-hierarchical-todo-statistics t
2357 "Non-nil means TODO statistics covers just direct children.
2358 When nil, all entries in the subtree are considered.
2359 This has only an effect if `org-provide-todo-statistics' is set.
2360 To set this to nil for only a single subtree, use a COOKIE_DATA
2361 property and include the word \"recursive\" into the value."
2362 :group 'org-todo
2363 :type 'boolean)
2365 (defcustom org-after-todo-state-change-hook nil
2366 "Hook which is run after the state of a TODO item was changed.
2367 The new state (a string with a TODO keyword, or nil) is available in the
2368 Lisp variable `org-state'."
2369 :group 'org-todo
2370 :type 'hook)
2372 (defvar org-blocker-hook nil
2373 "Hook for functions that are allowed to block a state change.
2375 Functions in this hook should not modify the buffer.
2376 Each function gets as its single argument a property list,
2377 see `org-trigger-hook' for more information about this list.
2379 If any of the functions in this hook returns nil, the state change
2380 is blocked.")
2382 (defvar org-trigger-hook nil
2383 "Hook for functions that are triggered by a state change.
2385 Each function gets as its single argument a property list with at
2386 least the following elements:
2388 (:type type-of-change :position pos-at-entry-start
2389 :from old-state :to new-state)
2391 Depending on the type, more properties may be present.
2393 This mechanism is currently implemented for:
2395 TODO state changes
2396 ------------------
2397 :type todo-state-change
2398 :from previous state (keyword as a string), or nil, or a symbol
2399 'todo' or 'done', to indicate the general type of state.
2400 :to new state, like in :from")
2402 (defcustom org-enforce-todo-dependencies nil
2403 "Non-nil means undone TODO entries will block switching the parent to DONE.
2404 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2405 be blocked if any prior sibling is not yet done.
2406 Finally, if the parent is blocked because of ordered siblings of its own,
2407 the child will also be blocked."
2408 :set (lambda (var val)
2409 (set var val)
2410 (if val
2411 (add-hook 'org-blocker-hook
2412 'org-block-todo-from-children-or-siblings-or-parent)
2413 (remove-hook 'org-blocker-hook
2414 'org-block-todo-from-children-or-siblings-or-parent)))
2415 :group 'org-todo
2416 :type 'boolean)
2418 (defcustom org-enforce-todo-checkbox-dependencies nil
2419 "Non-nil means unchecked boxes will block switching the parent to DONE.
2420 When this is nil, checkboxes have no influence on switching TODO states.
2421 When non-nil, you first need to check off all check boxes before the TODO
2422 entry can be switched to DONE.
2423 This variable needs to be set before org.el is loaded, and you need to
2424 restart Emacs after a change to make the change effective. The only way
2425 to change is while Emacs is running is through the customize interface."
2426 :set (lambda (var val)
2427 (set var val)
2428 (if val
2429 (add-hook 'org-blocker-hook
2430 'org-block-todo-from-checkboxes)
2431 (remove-hook 'org-blocker-hook
2432 'org-block-todo-from-checkboxes)))
2433 :group 'org-todo
2434 :type 'boolean)
2436 (defcustom org-treat-insert-todo-heading-as-state-change nil
2437 "Non-nil means inserting a TODO heading is treated as state change.
2438 So when the command \\[org-insert-todo-heading] is used, state change
2439 logging will apply if appropriate. When nil, the new TODO item will
2440 be inserted directly, and no logging will take place."
2441 :group 'org-todo
2442 :type 'boolean)
2444 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2445 "Non-nil means switching TODO states with S-cursor counts as state change.
2446 This is the default behavior. However, setting this to nil allows a
2447 convenient way to select a TODO state and bypass any logging associated
2448 with that."
2449 :group 'org-todo
2450 :type 'boolean)
2452 (defcustom org-todo-state-tags-triggers nil
2453 "Tag changes that should be triggered by TODO state changes.
2454 This is a list. Each entry is
2456 (state-change (tag . flag) .......)
2458 State-change can be a string with a state, and empty string to indicate the
2459 state that has no TODO keyword, or it can be one of the symbols `todo'
2460 or `done', meaning any not-done or done state, respectively."
2461 :group 'org-todo
2462 :group 'org-tags
2463 :type '(repeat
2464 (cons (choice :tag "When changing to"
2465 (const :tag "Not-done state" todo)
2466 (const :tag "Done state" done)
2467 (string :tag "State"))
2468 (repeat
2469 (cons :tag "Tag action"
2470 (string :tag "Tag")
2471 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2473 (defcustom org-log-done nil
2474 "Information to record when a task moves to the DONE state.
2476 Possible values are:
2478 nil Don't add anything, just change the keyword
2479 time Add a time stamp to the task
2480 note Prompt for a note and add it with template `org-log-note-headings'
2482 This option can also be set with on a per-file-basis with
2484 #+STARTUP: nologdone
2485 #+STARTUP: logdone
2486 #+STARTUP: lognotedone
2488 You can have local logging settings for a subtree by setting the LOGGING
2489 property to one or more of these keywords."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "No logging" nil)
2494 (const :tag "Record CLOSED timestamp" time)
2495 (const :tag "Record CLOSED timestamp with note." note)))
2497 ;; Normalize old uses of org-log-done.
2498 (cond
2499 ((eq org-log-done t) (setq org-log-done 'time))
2500 ((and (listp org-log-done) (memq 'done org-log-done))
2501 (setq org-log-done 'note)))
2503 (defcustom org-log-reschedule nil
2504 "Information to record when the scheduling date of a tasks is modified.
2506 Possible values are:
2508 nil Don't add anything, just change the date
2509 time Add a time stamp to the task
2510 note Prompt for a note and add it with template `org-log-note-headings'
2512 This option can also be set with on a per-file-basis with
2514 #+STARTUP: nologreschedule
2515 #+STARTUP: logreschedule
2516 #+STARTUP: lognotereschedule"
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type '(choice
2520 (const :tag "No logging" nil)
2521 (const :tag "Record timestamp" time)
2522 (const :tag "Record timestamp with note." note)))
2524 (defcustom org-log-redeadline nil
2525 "Information to record when the deadline date of a tasks is modified.
2527 Possible values are:
2529 nil Don't add anything, just change the date
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologredeadline
2536 #+STARTUP: logredeadline
2537 #+STARTUP: lognoteredeadline
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record timestamp" time)
2546 (const :tag "Record timestamp with note." note)))
2548 (defcustom org-log-note-clock-out nil
2549 "Non-nil means record a note when clocking out of an item.
2550 This can also be configured on a per-file basis by adding one of
2551 the following lines anywhere in the buffer:
2553 #+STARTUP: lognoteclock-out
2554 #+STARTUP: nolognoteclock-out"
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-done-with-time t
2560 "Non-nil means the CLOSED time stamp will contain date and time.
2561 When nil, only the date will be recorded."
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-note-headings
2566 '((done . "CLOSING NOTE %t")
2567 (state . "State %-12s from %-12S %t")
2568 (note . "Note taken on %t")
2569 (reschedule . "Rescheduled from %S on %t")
2570 (delschedule . "Not scheduled, was %S on %t")
2571 (redeadline . "New deadline from %S on %t")
2572 (deldeadline . "Removed deadline, was %S on %t")
2573 (refile . "Refiled on %t")
2574 (clock-out . ""))
2575 "Headings for notes added to entries.
2576 The value is an alist, with the car being a symbol indicating the note
2577 context, and the cdr is the heading to be used. The heading may also be the
2578 empty string.
2579 %t in the heading will be replaced by a time stamp.
2580 %T will be an active time stamp instead the default inactive one
2581 %d will be replaced by a short-format time stamp.
2582 %D will be replaced by an active short-format time stamp.
2583 %s will be replaced by the new TODO state, in double quotes.
2584 %S will be replaced by the old TODO state, in double quotes.
2585 %u will be replaced by the user name.
2586 %U will be replaced by the full user name.
2588 In fact, it is not a good idea to change the `state' entry, because
2589 agenda log mode depends on the format of these entries."
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(list :greedy t
2593 (cons (const :tag "Heading when closing an item" done) string)
2594 (cons (const :tag
2595 "Heading when changing todo state (todo sequence only)"
2596 state) string)
2597 (cons (const :tag "Heading when just taking a note" note) string)
2598 (cons (const :tag "Heading when clocking out" clock-out) string)
2599 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2600 (cons (const :tag "Heading when rescheduling" reschedule) string)
2601 (cons (const :tag "Heading when changing deadline" redeadline) string)
2602 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2603 (cons (const :tag "Heading when refiling" refile) string)))
2605 (unless (assq 'note org-log-note-headings)
2606 (push '(note . "%t") org-log-note-headings))
2608 (defcustom org-log-into-drawer nil
2609 "Non-nil means insert state change notes and time stamps into a drawer.
2610 When nil, state changes notes will be inserted after the headline and
2611 any scheduling and clock lines, but not inside a drawer.
2613 The value of this variable should be the name of the drawer to use.
2614 LOGBOOK is proposed as the default drawer for this purpose, you can
2615 also set this to a string to define the drawer of your choice.
2617 A value of t is also allowed, representing \"LOGBOOK\".
2619 A value of t or nil can also be set with on a per-file-basis with
2621 #+STARTUP: logdrawer
2622 #+STARTUP: nologdrawer
2624 If this variable is set, `org-log-state-notes-insert-after-drawers'
2625 will be ignored.
2627 You can set the property LOG_INTO_DRAWER to overrule this setting for
2628 a subtree."
2629 :group 'org-todo
2630 :group 'org-progress
2631 :type '(choice
2632 (const :tag "Not into a drawer" nil)
2633 (const :tag "LOGBOOK" t)
2634 (string :tag "Other")))
2636 (if (fboundp 'defvaralias)
2637 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2639 (defun org-log-into-drawer ()
2640 "Return the value of `org-log-into-drawer', but let properties overrule.
2641 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2642 used instead of the default value."
2643 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2644 (cond
2645 ((not p) org-log-into-drawer)
2646 ((equal p "nil") nil)
2647 ((equal p "t") "LOGBOOK")
2648 (t p))))
2650 (defcustom org-log-state-notes-insert-after-drawers nil
2651 "Non-nil means insert state change notes after any drawers in entry.
2652 Only the drawers that *immediately* follow the headline and the
2653 deadline/scheduled line are skipped.
2654 When nil, insert notes right after the heading and perhaps the line
2655 with deadline/scheduling if present.
2657 This variable will have no effect if `org-log-into-drawer' is
2658 set."
2659 :group 'org-todo
2660 :group 'org-progress
2661 :type 'boolean)
2663 (defcustom org-log-states-order-reversed t
2664 "Non-nil means the latest state note will be directly after heading.
2665 When nil, the state change notes will be ordered according to time.
2667 This option can also be set with on a per-file-basis with
2669 #+STARTUP: logstatesreversed
2670 #+STARTUP: nologstatesreversed"
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type 'boolean)
2675 (defcustom org-todo-repeat-to-state nil
2676 "The TODO state to which a repeater should return the repeating task.
2677 By default this is the first task in a TODO sequence, or the previous state
2678 in a TODO_TYP set. But you can specify another task here.
2679 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2680 :group 'org-todo
2681 :version "24.1"
2682 :type '(choice (const :tag "Head of sequence" nil)
2683 (string :tag "Specific state")))
2685 (defcustom org-log-repeat 'time
2686 "Non-nil means record moving through the DONE state when triggering repeat.
2687 An auto-repeating task is immediately switched back to TODO when
2688 marked DONE. If you are not logging state changes (by adding \"@\"
2689 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2690 record a closing note, there will be no record of the task moving
2691 through DONE. This variable forces taking a note anyway.
2693 nil Don't force a record
2694 time Record a time stamp
2695 note Prompt for a note and add it with template `org-log-note-headings'
2697 This option can also be set with on a per-file-basis with
2699 #+STARTUP: nologrepeat
2700 #+STARTUP: logrepeat
2701 #+STARTUP: lognoterepeat
2703 You can have local logging settings for a subtree by setting the LOGGING
2704 property to one or more of these keywords."
2705 :group 'org-todo
2706 :group 'org-progress
2707 :type '(choice
2708 (const :tag "Don't force a record" nil)
2709 (const :tag "Force recording the DONE state" time)
2710 (const :tag "Force recording a note with the DONE state" note)))
2713 (defgroup org-priorities nil
2714 "Priorities in Org-mode."
2715 :tag "Org Priorities"
2716 :group 'org-todo)
2718 (defcustom org-enable-priority-commands t
2719 "Non-nil means priority commands are active.
2720 When nil, these commands will be disabled, so that you never accidentally
2721 set a priority."
2722 :group 'org-priorities
2723 :type 'boolean)
2725 (defcustom org-highest-priority ?A
2726 "The highest priority of TODO items. A character like ?A, ?B etc.
2727 Must have a smaller ASCII number than `org-lowest-priority'."
2728 :group 'org-priorities
2729 :type 'character)
2731 (defcustom org-lowest-priority ?C
2732 "The lowest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a larger ASCII number than `org-highest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-default-priority ?B
2738 "The default priority of TODO items.
2739 This is the priority an item gets if no explicit priority is given.
2740 When starting to cycle on an empty priority the first step in the cycle
2741 depends on `org-priority-start-cycle-with-default'. The resulting first
2742 step priority must not exceed the range from `org-highest-priority' to
2743 `org-lowest-priority' which means that `org-default-priority' has to be
2744 in this range exclusive or inclusive the range boundaries. Else the
2745 first step refuses to set the default and the second will fall back
2746 to (depending on the command used) the highest or lowest priority."
2747 :group 'org-priorities
2748 :type 'character)
2750 (defcustom org-priority-start-cycle-with-default t
2751 "Non-nil means start with default priority when starting to cycle.
2752 When this is nil, the first step in the cycle will be (depending on the
2753 command used) one higher or lower than the default priority.
2754 See also `org-default-priority'."
2755 :group 'org-priorities
2756 :type 'boolean)
2758 (defcustom org-get-priority-function nil
2759 "Function to extract the priority from a string.
2760 The string is normally the headline. If this is nil Org computes the
2761 priority from the priority cookie like [#A] in the headline. It returns
2762 an integer, increasing by 1000 for each priority level.
2763 The user can set a different function here, which should take a string
2764 as an argument and return the numeric priority."
2765 :group 'org-priorities
2766 :version "24.1"
2767 :type 'function)
2769 (defgroup org-time nil
2770 "Options concerning time stamps and deadlines in Org-mode."
2771 :tag "Org Time"
2772 :group 'org)
2774 (defcustom org-insert-labeled-timestamps-at-point nil
2775 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2776 When nil, these labeled time stamps are forces into the second line of an
2777 entry, just after the headline. When scheduling from the global TODO list,
2778 the time stamp will always be forced into the second line."
2779 :group 'org-time
2780 :type 'boolean)
2782 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2783 "Formats for `format-time-string' which are used for time stamps.
2784 It is not recommended to change this constant.")
2786 (defcustom org-time-stamp-rounding-minutes '(0 5)
2787 "Number of minutes to round time stamps to.
2788 These are two values, the first applies when first creating a time stamp.
2789 The second applies when changing it with the commands `S-up' and `S-down'.
2790 When changing the time stamp, this means that it will change in steps
2791 of N minutes, as given by the second value.
2793 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2794 numbers should be factors of 60, so for example 5, 10, 15.
2796 When this is larger than 1, you can still force an exact time stamp by using
2797 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2798 and by using a prefix arg to `S-up/down' to specify the exact number
2799 of minutes to shift."
2800 :group 'org-time
2801 :get #'(lambda (var) ; Make sure both elements are there
2802 (if (integerp (default-value var))
2803 (list (default-value var) 5)
2804 (default-value var)))
2805 :type '(list
2806 (integer :tag "when inserting times")
2807 (integer :tag "when modifying times")))
2809 ;; Normalize old customizations of this variable.
2810 (when (integerp org-time-stamp-rounding-minutes)
2811 (setq org-time-stamp-rounding-minutes
2812 (list org-time-stamp-rounding-minutes
2813 org-time-stamp-rounding-minutes)))
2815 (defcustom org-display-custom-times nil
2816 "Non-nil means overlay custom formats over all time stamps.
2817 The formats are defined through the variable `org-time-stamp-custom-formats'.
2818 To turn this on on a per-file basis, insert anywhere in the file:
2819 #+STARTUP: customtime"
2820 :group 'org-time
2821 :set 'set-default
2822 :type 'sexp)
2823 (make-variable-buffer-local 'org-display-custom-times)
2825 (defcustom org-time-stamp-custom-formats
2826 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2827 "Custom formats for time stamps. See `format-time-string' for the syntax.
2828 These are overlaid over the default ISO format if the variable
2829 `org-display-custom-times' is set. Time like %H:%M should be at the
2830 end of the second format. The custom formats are also honored by export
2831 commands, if custom time display is turned on at the time of export."
2832 :group 'org-time
2833 :type 'sexp)
2835 (defun org-time-stamp-format (&optional long inactive)
2836 "Get the right format for a time string."
2837 (let ((f (if long (cdr org-time-stamp-formats)
2838 (car org-time-stamp-formats))))
2839 (if inactive
2840 (concat "[" (substring f 1 -1) "]")
2841 f)))
2843 (defcustom org-time-clocksum-format
2844 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2845 "The format string used when creating CLOCKSUM lines.
2846 This is also used when Org mode generates a time duration.
2848 The value can be a single format string containing two
2849 %-sequences, which will be filled with the number of hours and
2850 minutes in that order.
2852 Alternatively, the value can be a plist associating any of the
2853 keys :years, :months, :weeks, :days, :hours or :minutes with
2854 format strings. The time duration is formatted using only the
2855 time components that are needed and concatenating the results.
2856 If a time unit in absent, it falls back to the next smallest
2857 unit.
2859 The keys :require-years, :require-months, :require-days,
2860 :require-weeks, :require-hours, :require-minutes are also
2861 meaningful. A non-nil value for these keys indicates that the
2862 corresponding time component should always be included, even if
2863 its value is 0.
2866 For example,
2868 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2869 :require-minutes t)
2871 means durations longer than a day will be expressed in days,
2872 hours and minutes, and durations less than a day will always be
2873 expressed in hours and minutes (even for durations less than an
2874 hour).
2876 The value
2878 \(:days \"%dd\" :minutes \"%dm\")
2880 means durations longer than a day will be expressed in days and
2881 minutes, and durations less than a day will be expressed entirely
2882 in minutes (even for durations longer than an hour)."
2883 :group 'org-time
2884 :group 'org-clock
2885 :version "24.3"
2886 :type '(choice (string :tag "Format string")
2887 (set :tag "Plist"
2888 (group :inline t (const :tag "Years" :years)
2889 (string :tag "Format string"))
2890 (group :inline t
2891 (const :tag "Always show years" :require-years)
2892 (const t))
2893 (group :inline t (const :tag "Months" :months)
2894 (string :tag "Format string"))
2895 (group :inline t
2896 (const :tag "Always show months" :require-months)
2897 (const t))
2898 (group :inline t (const :tag "Weeks" :weeks)
2899 (string :tag "Format string"))
2900 (group :inline t
2901 (const :tag "Always show weeks" :require-weeks)
2902 (const t))
2903 (group :inline t (const :tag "Days" :days)
2904 (string :tag "Format string"))
2905 (group :inline t
2906 (const :tag "Always show days" :require-days)
2907 (const t))
2908 (group :inline t (const :tag "Hours" :hours)
2909 (string :tag "Format string"))
2910 (group :inline t
2911 (const :tag "Always show hours" :require-hours)
2912 (const t))
2913 (group :inline t (const :tag "Minutes" :minutes)
2914 (string :tag "Format string"))
2915 (group :inline t
2916 (const :tag "Always show minutes" :require-minutes)
2917 (const t)))))
2919 (defcustom org-time-clocksum-use-fractional nil
2920 "When non-nil, \\[org-clock-display] uses fractional times.
2921 See `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-use-effort-durations t
2928 "When non-nil, \\[org-clock-display] uses effort durations.
2929 E.g. by default, one day is considered to be a 8 hours effort,
2930 so a task that has been clocked for 16 hours will be displayed
2931 as during 2 days in the clock display or in the clocktable.
2933 See `org-effort-durations' on how to set effort durations
2934 and `org-time-clocksum-format' for more on time clock formats."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.3"
2938 :type 'boolean)
2940 (defcustom org-time-clocksum-fractional-format "%.2f"
2941 "The format string used when creating CLOCKSUM lines,
2942 or when Org mode generates a time duration, if
2943 `org-time-clocksum-use-fractional' is enabled.
2945 The value can be a single format string containing one
2946 %-sequence, which will be filled with the number of hours as
2947 a float.
2949 Alternatively, the value can be a plist associating any of the
2950 keys :years, :months, :weeks, :days, :hours or :minutes with
2951 a format string. The time duration is formatted using the
2952 largest time unit which gives a non-zero integer part. If all
2953 specified formats have zero integer part, the smallest time unit
2954 is used."
2955 :group 'org-time
2956 :type '(choice (string :tag "Format string")
2957 (set (group :inline t (const :tag "Years" :years)
2958 (string :tag "Format string"))
2959 (group :inline t (const :tag "Months" :months)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Weeks" :weeks)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Days" :days)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Hours" :hours)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Minutes" :minutes)
2968 (string :tag "Format string")))))
2970 (defcustom org-deadline-warning-days 14
2971 "Number of days before expiration during which a deadline becomes active.
2972 This variable governs the display in sparse trees and in the agenda.
2973 When 0 or negative, it means use this number (the absolute value of it)
2974 even if a deadline has a different individual lead time specified.
2976 Custom commands can set this variable in the options section."
2977 :group 'org-time
2978 :group 'org-agenda-daily/weekly
2979 :type 'integer)
2981 (defcustom org-scheduled-delay-days 0
2982 "Number of days before a scheduled item becomes active.
2983 This variable governs the display in sparse trees and in the agenda.
2984 The default value (i.e. 0) means: don't delay scheduled item.
2985 When negative, it means use this number (the absolute value of it)
2986 even if a scheduled item has a different individual delay time
2987 specified.
2989 Custom commands can set this variable in the options section."
2990 :group 'org-time
2991 :group 'org-agenda-daily/weekly
2992 :version "24.3"
2993 :type 'integer)
2995 (defcustom org-read-date-prefer-future t
2996 "Non-nil means assume future for incomplete date input from user.
2997 This affects the following situations:
2998 1. The user gives a month but not a year.
2999 For example, if it is April and you enter \"feb 2\", this will be read
3000 as Feb 2, *next* year. \"May 5\", however, will be this year.
3001 2. The user gives a day, but no month.
3002 For example, if today is the 15th, and you enter \"3\", Org-mode will
3003 read this as the third of *next* month. However, if you enter \"17\",
3004 it will be considered as *this* month.
3006 If you set this variable to the symbol `time', then also the following
3007 will work:
3009 3. If the user gives a time.
3010 If the time is before now, it will be interpreted as tomorrow.
3012 Currently none of this works for ISO week specifications.
3014 When this option is nil, the current day, month and year will always be
3015 used as defaults.
3017 See also `org-agenda-jump-prefer-future'."
3018 :group 'org-time
3019 :type '(choice
3020 (const :tag "Never" nil)
3021 (const :tag "Check month and day" t)
3022 (const :tag "Check month, day, and time" time)))
3024 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3025 "Should the agenda jump command prefer the future for incomplete dates?
3026 The default is to do the same as configured in `org-read-date-prefer-future'.
3027 But you can also set a deviating value here.
3028 This may t or nil, or the symbol `org-read-date-prefer-future'."
3029 :group 'org-agenda
3030 :group 'org-time
3031 :version "24.1"
3032 :type '(choice
3033 (const :tag "Use org-read-date-prefer-future"
3034 org-read-date-prefer-future)
3035 (const :tag "Never" nil)
3036 (const :tag "Always" t)))
3038 (defcustom org-read-date-force-compatible-dates t
3039 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3041 Depending on the system Emacs is running on, certain dates cannot
3042 be represented with the type used internally to represent time.
3043 Dates between 1970-1-1 and 2038-1-1 can always be represented
3044 correctly. Some systems allow for earlier dates, some for later,
3045 some for both. One way to find out it to insert any date into an
3046 Org buffer, putting the cursor on the year and hitting S-up and
3047 S-down to test the range.
3049 When this variable is set to t, the date/time prompt will not let
3050 you specify dates outside the 1970-2037 range, so it is certain that
3051 these dates will work in whatever version of Emacs you are
3052 running, and also that you can move a file from one Emacs implementation
3053 to another. WHenever Org is forcing the year for you, it will display
3054 a message and beep.
3056 When this variable is nil, Org will check if the date is
3057 representable in the specific Emacs implementation you are using.
3058 If not, it will force a year, usually the current year, and beep
3059 to remind you. Currently this setting is not recommended because
3060 the likelihood that you will open your Org files in an Emacs that
3061 has limited date range is not negligible.
3063 A workaround for this problem is to use diary sexp dates for time
3064 stamps outside of this range."
3065 :group 'org-time
3066 :version "24.1"
3067 :type 'boolean)
3069 (defcustom org-read-date-display-live t
3070 "Non-nil means display current interpretation of date prompt live.
3071 This display will be in an overlay, in the minibuffer."
3072 :group 'org-time
3073 :type 'boolean)
3075 (defcustom org-read-date-popup-calendar t
3076 "Non-nil means pop up a calendar when prompting for a date.
3077 In the calendar, the date can be selected with mouse-1. However, the
3078 minibuffer will also be active, and you can simply enter the date as well.
3079 When nil, only the minibuffer will be available."
3080 :group 'org-time
3081 :type 'boolean)
3082 (if (fboundp 'defvaralias)
3083 (defvaralias 'org-popup-calendar-for-date-prompt
3084 'org-read-date-popup-calendar))
3086 (make-obsolete-variable
3087 'org-read-date-minibuffer-setup-hook
3088 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3089 (defcustom org-read-date-minibuffer-setup-hook nil
3090 "Hook to be used to set up keys for the date/time interface.
3091 Add key definitions to `minibuffer-local-map', which will be a
3092 temporary copy.
3094 WARNING: This option is obsolete, you should use
3095 `org-read-date-minibuffer-local-map' to set up keys."
3096 :group 'org-time
3097 :type 'hook)
3099 (defcustom org-extend-today-until 0
3100 "The hour when your day really ends. Must be an integer.
3101 This has influence for the following applications:
3102 - When switching the agenda to \"today\". It it is still earlier than
3103 the time given here, the day recognized as TODAY is actually yesterday.
3104 - When a date is read from the user and it is still before the time given
3105 here, the current date and time will be assumed to be yesterday, 23:59.
3106 Also, timestamps inserted in capture templates follow this rule.
3108 IMPORTANT: This is a feature whose implementation is and likely will
3109 remain incomplete. Really, it is only here because past midnight seems to
3110 be the favorite working time of John Wiegley :-)"
3111 :group 'org-time
3112 :type 'integer)
3114 (defcustom org-use-effective-time nil
3115 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3116 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3117 \"effective time\" of any timestamps between midnight and 8am will be
3118 23:59 of the previous day."
3119 :group 'org-time
3120 :version "24.1"
3121 :type 'boolean)
3123 (defcustom org-use-last-clock-out-time-as-effective-time nil
3124 "When non-nil, use the last clock out time for `org-todo'.
3125 Note that this option has precedence over the combined use of
3126 `org-use-effective-time' and `org-extend-today-until'."
3127 :group 'org-time
3128 ;; :version "24.3"
3129 :type 'boolean)
3131 (defcustom org-edit-timestamp-down-means-later nil
3132 "Non-nil means S-down will increase the time in a time stamp.
3133 When nil, S-up will increase."
3134 :group 'org-time
3135 :type 'boolean)
3137 (defcustom org-calendar-follow-timestamp-change t
3138 "Non-nil means make the calendar window follow timestamp changes.
3139 When a timestamp is modified and the calendar window is visible, it will be
3140 moved to the new date."
3141 :group 'org-time
3142 :type 'boolean)
3144 (defgroup org-tags nil
3145 "Options concerning tags in Org-mode."
3146 :tag "Org Tags"
3147 :group 'org)
3149 (defcustom org-tag-alist nil
3150 "List of tags allowed in Org-mode files.
3151 When this list is nil, Org-mode will base TAG input on what is already in the
3152 buffer.
3153 The value of this variable is an alist, the car of each entry must be a
3154 keyword as a string, the cdr may be a character that is used to select
3155 that tag through the fast-tag-selection interface.
3156 See the manual for details."
3157 :group 'org-tags
3158 :type '(repeat
3159 (choice
3160 (cons (string :tag "Tag name")
3161 (character :tag "Access char"))
3162 (list :tag "Start radio group"
3163 (const :startgroup)
3164 (option (string :tag "Group description")))
3165 (list :tag "End radio group"
3166 (const :endgroup)
3167 (option (string :tag "Group description")))
3168 (const :tag "New line" (:newline)))))
3170 (defcustom org-tag-persistent-alist nil
3171 "List of tags that will always appear in all Org-mode files.
3172 This is in addition to any in buffer settings or customizations
3173 of `org-tag-alist'.
3174 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3175 The value of this variable is an alist, the car of each entry must be a
3176 keyword as a string, the cdr may be a character that is used to select
3177 that tag through the fast-tag-selection interface.
3178 See the manual for details.
3179 To disable these tags on a per-file basis, insert anywhere in the file:
3180 #+STARTUP: noptag"
3181 :group 'org-tags
3182 :type '(repeat
3183 (choice
3184 (cons (string :tag "Tag name")
3185 (character :tag "Access char"))
3186 (const :tag "Start radio group" (:startgroup))
3187 (const :tag "End radio group" (:endgroup))
3188 (const :tag "New line" (:newline)))))
3190 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3191 "If non-nil, always offer completion for all tags of all agenda files.
3192 Instead of customizing this variable directly, you might want to
3193 set it locally for capture buffers, because there no list of
3194 tags in that file can be created dynamically (there are none).
3196 (add-hook 'org-capture-mode-hook
3197 (lambda ()
3198 (set (make-local-variable
3199 'org-complete-tags-always-offer-all-agenda-tags)
3200 t)))"
3201 :group 'org-tags
3202 :version "24.1"
3203 :type 'boolean)
3205 (defvar org-file-tags nil
3206 "List of tags that can be inherited by all entries in the file.
3207 The tags will be inherited if the variable `org-use-tag-inheritance'
3208 says they should be.
3209 This variable is populated from #+FILETAGS lines.")
3211 (defcustom org-use-fast-tag-selection 'auto
3212 "Non-nil means use fast tag selection scheme.
3213 This is a special interface to select and deselect tags with single keys.
3214 When nil, fast selection is never used.
3215 When the symbol `auto', fast selection is used if and only if selection
3216 characters for tags have been configured, either through the variable
3217 `org-tag-alist' or through a #+TAGS line in the buffer.
3218 When t, fast selection is always used and selection keys are assigned
3219 automatically if necessary."
3220 :group 'org-tags
3221 :type '(choice
3222 (const :tag "Always" t)
3223 (const :tag "Never" nil)
3224 (const :tag "When selection characters are configured" 'auto)))
3226 (defcustom org-fast-tag-selection-single-key nil
3227 "Non-nil means fast tag selection exits after first change.
3228 When nil, you have to press RET to exit it.
3229 During fast tag selection, you can toggle this flag with `C-c'.
3230 This variable can also have the value `expert'. In this case, the window
3231 displaying the tags menu is not even shown, until you press C-c again."
3232 :group 'org-tags
3233 :type '(choice
3234 (const :tag "No" nil)
3235 (const :tag "Yes" t)
3236 (const :tag "Expert" expert)))
3238 (defvar org-fast-tag-selection-include-todo nil
3239 "Non-nil means fast tags selection interface will also offer TODO states.
3240 This is an undocumented feature, you should not rely on it.")
3242 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3243 "The column to which tags should be indented in a headline.
3244 If this number is positive, it specifies the column. If it is negative,
3245 it means that the tags should be flushright to that column. For example,
3246 -80 works well for a normal 80 character screen.
3247 When 0, place tags directly after headline text, with only one space in
3248 between."
3249 :group 'org-tags
3250 :type 'integer)
3252 (defcustom org-auto-align-tags t
3253 "Non-nil keeps tags aligned when modifying headlines.
3254 Some operations (i.e. demoting) change the length of a headline and
3255 therefore shift the tags around. With this option turned on, after
3256 each such operation the tags are again aligned to `org-tags-column'."
3257 :group 'org-tags
3258 :type 'boolean)
3260 (defcustom org-use-tag-inheritance t
3261 "Non-nil means tags in levels apply also for sublevels.
3262 When nil, only the tags directly given in a specific line apply there.
3263 This may also be a list of tags that should be inherited, or a regexp that
3264 matches tags that should be inherited. Additional control is possible
3265 with the variable `org-tags-exclude-from-inheritance' which gives an
3266 explicit list of tags to be excluded from inheritance, even if the value of
3267 `org-use-tag-inheritance' would select it for inheritance.
3269 If this option is t, a match early-on in a tree can lead to a large
3270 number of matches in the subtree when constructing the agenda or creating
3271 a sparse tree. If you only want to see the first match in a tree during
3272 a search, check out the variable `org-tags-match-list-sublevels'."
3273 :group 'org-tags
3274 :type '(choice
3275 (const :tag "Not" nil)
3276 (const :tag "Always" t)
3277 (repeat :tag "Specific tags" (string :tag "Tag"))
3278 (regexp :tag "Tags matched by regexp")))
3280 (defcustom org-tags-exclude-from-inheritance nil
3281 "List of tags that should never be inherited.
3282 This is a way to exclude a few tags from inheritance. For way to do
3283 the opposite, to actively allow inheritance for selected tags,
3284 see the variable `org-use-tag-inheritance'."
3285 :group 'org-tags
3286 :type '(repeat (string :tag "Tag")))
3288 (defun org-tag-inherit-p (tag)
3289 "Check if TAG is one that should be inherited."
3290 (cond
3291 ((member tag org-tags-exclude-from-inheritance) nil)
3292 ((eq org-use-tag-inheritance t) t)
3293 ((not org-use-tag-inheritance) nil)
3294 ((stringp org-use-tag-inheritance)
3295 (string-match org-use-tag-inheritance tag))
3296 ((listp org-use-tag-inheritance)
3297 (member tag org-use-tag-inheritance))
3298 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3300 (defcustom org-tags-match-list-sublevels t
3301 "Non-nil means list also sublevels of headlines matching a search.
3302 This variable applies to tags/property searches, and also to stuck
3303 projects because this search is based on a tags match as well.
3305 When set to the symbol `indented', sublevels are indented with
3306 leading dots.
3308 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3309 the sublevels of a headline matching a tag search often also match
3310 the same search. Listing all of them can create very long lists.
3311 Setting this variable to nil causes subtrees of a match to be skipped.
3313 This variable is semi-obsolete and probably should always be true. It
3314 is better to limit inheritance to certain tags using the variables
3315 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3316 :group 'org-tags
3317 :type '(choice
3318 (const :tag "No, don't list them" nil)
3319 (const :tag "Yes, do list them" t)
3320 (const :tag "List them, indented with leading dots" indented)))
3322 (defcustom org-tags-sort-function nil
3323 "When set, tags are sorted using this function as a comparator."
3324 :group 'org-tags
3325 :type '(choice
3326 (const :tag "No sorting" nil)
3327 (const :tag "Alphabetical" string<)
3328 (const :tag "Reverse alphabetical" string>)
3329 (function :tag "Custom function" nil)))
3331 (defvar org-tags-history nil
3332 "History of minibuffer reads for tags.")
3333 (defvar org-last-tags-completion-table nil
3334 "The last used completion table for tags.")
3335 (defvar org-after-tags-change-hook nil
3336 "Hook that is run after the tags in a line have changed.")
3338 (defgroup org-properties nil
3339 "Options concerning properties in Org-mode."
3340 :tag "Org Properties"
3341 :group 'org)
3343 (defcustom org-property-format "%-10s %s"
3344 "How property key/value pairs should be formatted by `indent-line'.
3345 When `indent-line' hits a property definition, it will format the line
3346 according to this format, mainly to make sure that the values are
3347 lined-up with respect to each other."
3348 :group 'org-properties
3349 :type 'string)
3351 (defcustom org-properties-postprocess-alist nil
3352 "Alist of properties and functions to adjust inserted values.
3353 Elements of this alist must be of the form
3355 ([string] [function])
3357 where [string] must be a property name and [function] must be a
3358 lambda expression: this lambda expression must take one argument,
3359 the value to adjust, and return the new value as a string.
3361 For example, this element will allow the property \"Remaining\"
3362 to be updated wrt the relation between the \"Effort\" property
3363 and the clock summary:
3365 ((\"Remaining\" (lambda(value)
3366 (let ((clocksum (org-clock-sum-current-item))
3367 (effort (org-duration-string-to-minutes
3368 (org-entry-get (point) \"Effort\"))))
3369 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3370 :group 'org-properties
3371 :version "24.1"
3372 :type '(alist :key-type (string :tag "Property")
3373 :value-type (function :tag "Function")))
3375 (defcustom org-use-property-inheritance nil
3376 "Non-nil means properties apply also for sublevels.
3378 This setting is chiefly used during property searches. Turning it on can
3379 cause significant overhead when doing a search, which is why it is not
3380 on by default.
3382 When nil, only the properties directly given in the current entry count.
3383 When t, every property is inherited. The value may also be a list of
3384 properties that should have inheritance, or a regular expression matching
3385 properties that should be inherited.
3387 However, note that some special properties use inheritance under special
3388 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3389 and the properties ending in \"_ALL\" when they are used as descriptor
3390 for valid values of a property.
3392 Note for programmers:
3393 When querying an entry with `org-entry-get', you can control if inheritance
3394 should be used. By default, `org-entry-get' looks only at the local
3395 properties. You can request inheritance by setting the inherit argument
3396 to t (to force inheritance) or to `selective' (to respect the setting
3397 in this variable)."
3398 :group 'org-properties
3399 :type '(choice
3400 (const :tag "Not" nil)
3401 (const :tag "Always" t)
3402 (repeat :tag "Specific properties" (string :tag "Property"))
3403 (regexp :tag "Properties matched by regexp")))
3405 (defun org-property-inherit-p (property)
3406 "Check if PROPERTY is one that should be inherited."
3407 (cond
3408 ((eq org-use-property-inheritance t) t)
3409 ((not org-use-property-inheritance) nil)
3410 ((stringp org-use-property-inheritance)
3411 (string-match org-use-property-inheritance property))
3412 ((listp org-use-property-inheritance)
3413 (member property org-use-property-inheritance))
3414 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3416 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3417 "The default column format, if no other format has been defined.
3418 This variable can be set on the per-file basis by inserting a line
3420 #+COLUMNS: %25ITEM ....."
3421 :group 'org-properties
3422 :type 'string)
3424 (defcustom org-columns-ellipses ".."
3425 "The ellipses to be used when a field in column view is truncated.
3426 When this is the empty string, as many characters as possible are shown,
3427 but then there will be no visual indication that the field has been truncated.
3428 When this is a string of length N, the last N characters of a truncated
3429 field are replaced by this string. If the column is narrower than the
3430 ellipses string, only part of the ellipses string will be shown."
3431 :group 'org-properties
3432 :type 'string)
3434 (defcustom org-columns-modify-value-for-display-function nil
3435 "Function that modifies values for display in column view.
3436 For example, it can be used to cut out a certain part from a time stamp.
3437 The function must take 2 arguments:
3439 column-title The title of the column (*not* the property name)
3440 value The value that should be modified.
3442 The function should return the value that should be displayed,
3443 or nil if the normal value should be used."
3444 :group 'org-properties
3445 :type 'function)
3447 (defcustom org-effort-property "Effort"
3448 "The property that is being used to keep track of effort estimates.
3449 Effort estimates given in this property need to have the format H:MM."
3450 :group 'org-properties
3451 :group 'org-progress
3452 :type '(string :tag "Property"))
3454 (defconst org-global-properties-fixed
3455 '(("VISIBILITY_ALL" . "folded children content all")
3456 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3457 "List of property/value pairs that can be inherited by any entry.
3459 These are fixed values, for the preset properties. The user variable
3460 that can be used to add to this list is `org-global-properties'.
3462 The entries in this list are cons cells where the car is a property
3463 name and cdr is a string with the value. If the value represents
3464 multiple items like an \"_ALL\" property, separate the items by
3465 spaces.")
3467 (defcustom org-global-properties nil
3468 "List of property/value pairs that can be inherited by any entry.
3470 This list will be combined with the constant `org-global-properties-fixed'.
3472 The entries in this list are cons cells where the car is a property
3473 name and cdr is a string with the value.
3475 You can set buffer-local values for the same purpose in the variable
3476 `org-file-properties' this by adding lines like
3478 #+PROPERTY: NAME VALUE"
3479 :group 'org-properties
3480 :type '(repeat
3481 (cons (string :tag "Property")
3482 (string :tag "Value"))))
3484 (defvar org-file-properties nil
3485 "List of property/value pairs that can be inherited by any entry.
3486 Valid for the current buffer.
3487 This variable is populated from #+PROPERTY lines.")
3488 (make-variable-buffer-local 'org-file-properties)
3490 (defgroup org-agenda nil
3491 "Options concerning agenda views in Org-mode."
3492 :tag "Org Agenda"
3493 :group 'org)
3495 (defvar org-category nil
3496 "Variable used by org files to set a category for agenda display.
3497 Such files should use a file variable to set it, for example
3499 # -*- mode: org; org-category: \"ELisp\"
3501 or contain a special line
3503 #+CATEGORY: ELisp
3505 If the file does not specify a category, then file's base name
3506 is used instead.")
3507 (make-variable-buffer-local 'org-category)
3508 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3510 (defcustom org-agenda-files nil
3511 "The files to be used for agenda display.
3512 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3513 \\[org-remove-file]. You can also use customize to edit the list.
3515 If an entry is a directory, all files in that directory that are matched by
3516 `org-agenda-file-regexp' will be part of the file list.
3518 If the value of the variable is not a list but a single file name, then
3519 the list of agenda files is actually stored and maintained in that file, one
3520 agenda file per line. In this file paths can be given relative to
3521 `org-directory'. Tilde expansion and environment variable substitution
3522 are also made."
3523 :group 'org-agenda
3524 :type '(choice
3525 (repeat :tag "List of files and directories" file)
3526 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3528 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3529 "Regular expression to match files for `org-agenda-files'.
3530 If any element in the list in that variable contains a directory instead
3531 of a normal file, all files in that directory that are matched by this
3532 regular expression will be included."
3533 :group 'org-agenda
3534 :type 'regexp)
3536 (defcustom org-agenda-text-search-extra-files nil
3537 "List of extra files to be searched by text search commands.
3538 These files will be search in addition to the agenda files by the
3539 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3540 Note that these files will only be searched for text search commands,
3541 not for the other agenda views like todo lists, tag searches or the weekly
3542 agenda. This variable is intended to list notes and possibly archive files
3543 that should also be searched by these two commands.
3544 In fact, if the first element in the list is the symbol `agenda-archives',
3545 than all archive files of all agenda files will be added to the search
3546 scope."
3547 :group 'org-agenda
3548 :type '(set :greedy t
3549 (const :tag "Agenda Archives" agenda-archives)
3550 (repeat :inline t (file))))
3552 (if (fboundp 'defvaralias)
3553 (defvaralias 'org-agenda-multi-occur-extra-files
3554 'org-agenda-text-search-extra-files))
3556 (defcustom org-agenda-skip-unavailable-files nil
3557 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3558 A nil value means to remove them, after a query, from the list."
3559 :group 'org-agenda
3560 :type 'boolean)
3562 (defcustom org-calendar-to-agenda-key [?c]
3563 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3564 The command `org-calendar-goto-agenda' will be bound to this key. The
3565 default is the character `c' because then `c' can be used to switch back and
3566 forth between agenda and calendar."
3567 :group 'org-agenda
3568 :type 'sexp)
3570 (defcustom org-calendar-insert-diary-entry-key [?i]
3571 "The key to be installed in `calendar-mode-map' for adding diary entries.
3572 This option is irrelevant until `org-agenda-diary-file' has been configured
3573 to point to an Org-mode file. When that is the case, the command
3574 `org-agenda-diary-entry' will be bound to the key given here, by default
3575 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3576 if you want to continue doing this, you need to change this to a different
3577 key."
3578 :group 'org-agenda
3579 :type 'sexp)
3581 (defcustom org-agenda-diary-file 'diary-file
3582 "File to which to add new entries with the `i' key in agenda and calendar.
3583 When this is the symbol `diary-file', the functionality in the Emacs
3584 calendar will be used to add entries to the `diary-file'. But when this
3585 points to a file, `org-agenda-diary-entry' will be used instead."
3586 :group 'org-agenda
3587 :type '(choice
3588 (const :tag "The standard Emacs diary file" diary-file)
3589 (file :tag "Special Org file diary entries")))
3591 (eval-after-load "calendar"
3592 '(progn
3593 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3594 'org-calendar-goto-agenda)
3595 (add-hook 'calendar-mode-hook
3596 (lambda ()
3597 (unless (eq org-agenda-diary-file 'diary-file)
3598 (define-key calendar-mode-map
3599 org-calendar-insert-diary-entry-key
3600 'org-agenda-diary-entry))))))
3602 (defgroup org-latex nil
3603 "Options for embedding LaTeX code into Org-mode."
3604 :tag "Org LaTeX"
3605 :group 'org)
3607 (defcustom org-format-latex-options
3608 '(:foreground default :background default :scale 1.0
3609 :html-foreground "Black" :html-background "Transparent"
3610 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3611 "Options for creating images from LaTeX fragments.
3612 This is a property list with the following properties:
3613 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3614 `default' means use the foreground of the default face.
3615 `auto' means use the foreground from the text face.
3616 :background the background color, or \"Transparent\".
3617 `default' means use the background of the default face.
3618 `auto' means use the background from the text face.
3619 :scale a scaling factor for the size of the images, to get more pixels
3620 :html-foreground, :html-background, :html-scale
3621 the same numbers for HTML export.
3622 :matchers a list indicating which matchers should be used to
3623 find LaTeX fragments. Valid members of this list are:
3624 \"begin\" find environments
3625 \"$1\" find single characters surrounded by $.$
3626 \"$\" find math expressions surrounded by $...$
3627 \"$$\" find math expressions surrounded by $$....$$
3628 \"\\(\" find math expressions surrounded by \\(...\\)
3629 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3630 :group 'org-latex
3631 :type 'plist)
3633 (defcustom org-format-latex-signal-error t
3634 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3635 When nil, just push out a message."
3636 :group 'org-latex
3637 :version "24.1"
3638 :type 'boolean)
3640 (defcustom org-latex-to-mathml-jar-file nil
3641 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3642 Use this to specify additional executable file say a jar file.
3644 When using MathToWeb as the converter, specify the full-path to
3645 your mathtoweb.jar file."
3646 :group 'org-latex
3647 :version "24.1"
3648 :type '(choice
3649 (const :tag "None" nil)
3650 (file :tag "JAR file" :must-match t)))
3652 (defcustom org-latex-to-mathml-convert-command nil
3653 "Command to convert LaTeX fragments to MathML.
3654 Replace format-specifiers in the command as noted below and use
3655 `shell-command' to convert LaTeX to MathML.
3656 %j: Executable file in fully expanded form as specified by
3657 `org-latex-to-mathml-jar-file'.
3658 %I: Input LaTeX file in fully expanded form
3659 %o: Output MathML file
3660 This command is used by `org-create-math-formula'.
3662 When using MathToWeb as the converter, set this to
3663 \"java -jar %j -unicode -force -df %o %I\"."
3664 :group 'org-latex
3665 :version "24.1"
3666 :type '(choice
3667 (const :tag "None" nil)
3668 (string :tag "\nShell command")))
3670 (defcustom org-latex-create-formula-image-program 'dvipng
3671 "Program to convert LaTeX fragments with.
3673 dvipng Process the LaTeX fragments to dvi file, then convert
3674 dvi files to png files using dvipng.
3675 This will also include processing of non-math environments.
3676 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3677 to convert pdf files to png files"
3678 :group 'org-latex
3679 :version "24.1"
3680 :type '(choice
3681 (const :tag "dvipng" dvipng)
3682 (const :tag "imagemagick" imagemagick)))
3684 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3685 "Path to store latex preview images.
3686 A relative path here creates many directories relative to the
3687 processed org files paths. An absolute path puts all preview
3688 images at the same place."
3689 :group 'org-latex
3690 :version "24.3"
3691 :type 'string)
3693 (defun org-format-latex-mathml-available-p ()
3694 "Return t if `org-latex-to-mathml-convert-command' is usable."
3695 (save-match-data
3696 (when (and (boundp 'org-latex-to-mathml-convert-command)
3697 org-latex-to-mathml-convert-command)
3698 (let ((executable (car (split-string
3699 org-latex-to-mathml-convert-command))))
3700 (when (executable-find executable)
3701 (if (string-match
3702 "%j" org-latex-to-mathml-convert-command)
3703 (file-readable-p org-latex-to-mathml-jar-file)
3704 t))))))
3706 (defcustom org-format-latex-header "\\documentclass{article}
3707 \\usepackage[usenames]{color}
3708 \\usepackage{amsmath}
3709 \\usepackage[mathscr]{eucal}
3710 \\pagestyle{empty} % do not remove
3711 \[PACKAGES]
3712 \[DEFAULT-PACKAGES]
3713 % The settings below are copied from fullpage.sty
3714 \\setlength{\\textwidth}{\\paperwidth}
3715 \\addtolength{\\textwidth}{-3cm}
3716 \\setlength{\\oddsidemargin}{1.5cm}
3717 \\addtolength{\\oddsidemargin}{-2.54cm}
3718 \\setlength{\\evensidemargin}{\\oddsidemargin}
3719 \\setlength{\\textheight}{\\paperheight}
3720 \\addtolength{\\textheight}{-\\headheight}
3721 \\addtolength{\\textheight}{-\\headsep}
3722 \\addtolength{\\textheight}{-\\footskip}
3723 \\addtolength{\\textheight}{-3cm}
3724 \\setlength{\\topmargin}{1.5cm}
3725 \\addtolength{\\topmargin}{-2.54cm}"
3726 "The document header used for processing LaTeX fragments.
3727 It is imperative that this header make sure that no page number
3728 appears on the page. The package defined in the variables
3729 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3730 will either replace the placeholder \"[PACKAGES]\" in this
3731 header, or they will be appended."
3732 :group 'org-latex
3733 :type 'string)
3735 (defun org-set-packages-alist (var val)
3736 "Set the packages alist and make sure it has 3 elements per entry."
3737 (set var (mapcar (lambda (x)
3738 (if (and (consp x) (= (length x) 2))
3739 (list (car x) (nth 1 x) t)
3741 val)))
3743 (defun org-get-packages-alist (var)
3744 "Get the packages alist and make sure it has 3 elements per entry."
3745 (mapcar (lambda (x)
3746 (if (and (consp x) (= (length x) 2))
3747 (list (car x) (nth 1 x) t)
3749 (default-value var)))
3751 (defcustom org-latex-default-packages-alist
3752 '(("AUTO" "inputenc" t)
3753 ("T1" "fontenc" t)
3754 ("" "fixltx2e" nil)
3755 ("" "graphicx" t)
3756 ("" "longtable" nil)
3757 ("" "float" nil)
3758 ("" "wrapfig" nil)
3759 ("" "soul" t)
3760 ("" "textcomp" t)
3761 ("" "marvosym" t)
3762 ("" "wasysym" t)
3763 ("" "latexsym" t)
3764 ("" "amssymb" t)
3765 ("" "hyperref" nil)
3766 "\\tolerance=1000")
3767 "Alist of default packages to be inserted in the header.
3769 Change this only if one of the packages here causes an
3770 incompatibility with another package you are using.
3772 The packages in this list are needed by one part or another of
3773 Org mode to function properly:
3775 - inputenc, fontenc: for basic font and character selection
3776 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3777 symbols used for interpreting the entities in `org-entities'.
3778 You can skip some of these packages if you don't use any of the
3779 symbols in it.
3780 - graphicx: for including images
3781 - float, wrapfig: for figure placement
3782 - longtable: for long tables
3783 - hyperref: for cross references
3785 Therefore you should not modify this variable unless you know
3786 what you are doing. The one reason to change it anyway is that
3787 you might be loading some other package that conflicts with one
3788 of the default packages. Each cell is of the format
3789 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3790 the package also needs to be included when compiling LaTeX
3791 snippets into images for inclusion into non-LaTeX output."
3792 :group 'org-latex
3793 :group 'org-export-latex
3794 :set 'org-set-packages-alist
3795 :get 'org-get-packages-alist
3796 :version "24.1"
3797 :type '(repeat
3798 (choice
3799 (list :tag "options/package pair"
3800 (string :tag "options")
3801 (string :tag "package")
3802 (boolean :tag "Snippet"))
3803 (string :tag "A line of LaTeX"))))
3805 (defcustom org-latex-packages-alist nil
3806 "Alist of packages to be inserted in every LaTeX header.
3808 These will be inserted after `org-latex-default-packages-alist'.
3809 Each cell is of the format:
3811 \(\"options\" \"package\" snippet-flag)
3813 SNIPPET-FLAG, when t, indicates that this package is also needed
3814 when turning LaTeX snippets into images for inclusion into
3815 non-LaTeX output.
3817 Make sure that you only list packages here which:
3819 - you want in every file
3820 - do not conflict with the setup in `org-format-latex-header'.
3821 - do not conflict with the default packages in
3822 `org-latex-default-packages-alist'."
3823 :group 'org-latex
3824 :group 'org-export-latex
3825 :set 'org-set-packages-alist
3826 :get 'org-get-packages-alist
3827 :type '(repeat
3828 (choice
3829 (list :tag "options/package pair"
3830 (string :tag "options")
3831 (string :tag "package")
3832 (boolean :tag "Snippet"))
3833 (string :tag "A line of LaTeX"))))
3835 (defgroup org-appearance nil
3836 "Settings for Org-mode appearance."
3837 :tag "Org Appearance"
3838 :group 'org)
3840 (defcustom org-level-color-stars-only nil
3841 "Non-nil means fontify only the stars in each headline.
3842 When nil, the entire headline is fontified.
3843 Changing it requires restart of `font-lock-mode' to become effective
3844 also in regions already fontified."
3845 :group 'org-appearance
3846 :type 'boolean)
3848 (defcustom org-hide-leading-stars nil
3849 "Non-nil means hide the first N-1 stars in a headline.
3850 This works by using the face `org-hide' for these stars. This
3851 face is white for a light background, and black for a dark
3852 background. You may have to customize the face `org-hide' to
3853 make this work.
3854 Changing it requires restart of `font-lock-mode' to become effective
3855 also in regions already fontified.
3856 You may also set this on a per-file basis by adding one of the following
3857 lines to the buffer:
3859 #+STARTUP: hidestars
3860 #+STARTUP: showstars"
3861 :group 'org-appearance
3862 :type 'boolean)
3864 (defcustom org-hidden-keywords nil
3865 "List of symbols corresponding to keywords to be hidden the org buffer.
3866 For example, a value '(title) for this list will make the document's title
3867 appear in the buffer without the initial #+TITLE: keyword."
3868 :group 'org-appearance
3869 :version "24.1"
3870 :type '(set (const :tag "#+AUTHOR" author)
3871 (const :tag "#+DATE" date)
3872 (const :tag "#+EMAIL" email)
3873 (const :tag "#+TITLE" title)))
3875 (defcustom org-custom-properties nil
3876 "List of properties (as strings) with a special meaning.
3877 The default use of these custom properties is to let the user
3878 hide them with `org-toggle-custom-properties-visibility'."
3879 :group 'org-properties
3880 :group 'org-appearance
3881 :version "24.3"
3882 :type '(repeat (string :tag "Property Name")))
3884 (defcustom org-fontify-done-headline nil
3885 "Non-nil means change the face of a headline if it is marked DONE.
3886 Normally, only the TODO/DONE keyword indicates the state of a headline.
3887 When this is non-nil, the headline after the keyword is set to the
3888 `org-headline-done' as an additional indication."
3889 :group 'org-appearance
3890 :type 'boolean)
3892 (defcustom org-fontify-emphasized-text t
3893 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3894 Changing this variable requires a restart of Emacs to take effect."
3895 :group 'org-appearance
3896 :type 'boolean)
3898 (defcustom org-fontify-whole-heading-line nil
3899 "Non-nil means fontify the whole line for headings.
3900 This is useful when setting a background color for the
3901 org-level-* faces."
3902 :group 'org-appearance
3903 :type 'boolean)
3905 (defcustom org-highlight-latex-and-related nil
3906 "Non-nil means highlight LaTeX related syntax in the buffer.
3907 When non nil, the value should be a list containing any of the
3908 following symbols:
3909 `latex' Highlight LaTeX snippets and environments.
3910 `script' Highlight subscript and superscript.
3911 `entities' Highlight entities."
3912 :group 'org-appearance
3913 :type '(choice
3914 (const :tag "No highlighting" nil)
3915 (set :greedy t :tag "Highlight"
3916 (const :tag "LaTeX snippets and environments" latex)
3917 (const :tag "Subscript and superscript" script)
3918 (const :tag "Entities" entities))))
3920 (defcustom org-hide-emphasis-markers nil
3921 "Non-nil mean font-lock should hide the emphasis marker characters."
3922 :group 'org-appearance
3923 :type 'boolean)
3925 (defcustom org-pretty-entities nil
3926 "Non-nil means show entities as UTF8 characters.
3927 When nil, the \\name form remains in the buffer."
3928 :group 'org-appearance
3929 :version "24.1"
3930 :type 'boolean)
3932 (defcustom org-pretty-entities-include-sub-superscripts t
3933 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3934 :group 'org-appearance
3935 :version "24.1"
3936 :type 'boolean)
3938 (defvar org-emph-re nil
3939 "Regular expression for matching emphasis.
3940 After a match, the match groups contain these elements:
3941 0 The match of the full regular expression, including the characters
3942 before and after the proper match
3943 1 The character before the proper match, or empty at beginning of line
3944 2 The proper match, including the leading and trailing markers
3945 3 The leading marker like * or /, indicating the type of highlighting
3946 4 The text between the emphasis markers, not including the markers
3947 5 The character after the match, empty at the end of a line")
3948 (defvar org-verbatim-re nil
3949 "Regular expression for matching verbatim text.")
3950 (defvar org-emphasis-regexp-components) ; defined just below
3951 (defvar org-emphasis-alist) ; defined just below
3952 (defun org-set-emph-re (var val)
3953 "Set variable and compute the emphasis regular expression."
3954 (set var val)
3955 (when (and (boundp 'org-emphasis-alist)
3956 (boundp 'org-emphasis-regexp-components)
3957 org-emphasis-alist org-emphasis-regexp-components)
3958 (let* ((e org-emphasis-regexp-components)
3959 (pre (car e))
3960 (post (nth 1 e))
3961 (border (nth 2 e))
3962 (body (nth 3 e))
3963 (nl (nth 4 e))
3964 (body1 (concat body "*?"))
3965 (markers (mapconcat 'car org-emphasis-alist ""))
3966 (vmarkers (mapconcat
3967 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3968 org-emphasis-alist "")))
3969 ;; make sure special characters appear at the right position in the class
3970 (if (string-match "\\^" markers)
3971 (setq markers (concat (replace-match "" t t markers) "^")))
3972 (if (string-match "-" markers)
3973 (setq markers (concat (replace-match "" t t markers) "-")))
3974 (if (string-match "\\^" vmarkers)
3975 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3976 (if (string-match "-" vmarkers)
3977 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3978 (if (> nl 0)
3979 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3980 (int-to-string nl) "\\}")))
3981 ;; Make the regexp
3982 (setq org-emph-re
3983 (concat "\\([" pre "]\\|^\\)"
3984 "\\("
3985 "\\([" markers "]\\)"
3986 "\\("
3987 "[^" border "]\\|"
3988 "[^" border "]"
3989 body1
3990 "[^" border "]"
3991 "\\)"
3992 "\\3\\)"
3993 "\\([" post "]\\|$\\)"))
3994 (setq org-verbatim-re
3995 (concat "\\([" pre "]\\|^\\)"
3996 "\\("
3997 "\\([" vmarkers "]\\)"
3998 "\\("
3999 "[^" border "]\\|"
4000 "[^" border "]"
4001 body1
4002 "[^" border "]"
4003 "\\)"
4004 "\\3\\)"
4005 "\\([" post "]\\|$\\)")))))
4007 (defcustom org-emphasis-regexp-components
4008 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4009 "Components used to build the regular expression for emphasis.
4010 This is a list with five entries. Terminology: In an emphasis string
4011 like \" *strong word* \", we call the initial space PREMATCH, the final
4012 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4013 and \"trong wor\" is the body. The different components in this variable
4014 specify what is allowed/forbidden in each part:
4016 pre Chars allowed as prematch. Beginning of line will be allowed too.
4017 post Chars allowed as postmatch. End of line will be allowed too.
4018 border The chars *forbidden* as border characters.
4019 body-regexp A regexp like \".\" to match a body character. Don't use
4020 non-shy groups here, and don't allow newline here.
4021 newline The maximum number of newlines allowed in an emphasis exp.
4023 Use customize to modify this, or restart Emacs after changing it."
4024 :group 'org-appearance
4025 :set 'org-set-emph-re
4026 :type '(list
4027 (sexp :tag "Allowed chars in pre ")
4028 (sexp :tag "Allowed chars in post ")
4029 (sexp :tag "Forbidden chars in border ")
4030 (sexp :tag "Regexp for body ")
4031 (integer :tag "number of newlines allowed")
4032 (option (boolean :tag "Please ignore this button"))))
4034 (defcustom org-emphasis-alist
4035 `(("*" bold "<b>" "</b>")
4036 ("/" italic "<i>" "</i>")
4037 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4038 ("=" org-code "<code>" "</code>" verbatim)
4039 ("~" org-verbatim "<code>" "</code>" verbatim)
4040 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4041 "<del>" "</del>")
4043 "Special syntax for emphasized text.
4044 Text starting and ending with a special character will be emphasized, for
4045 example *bold*, _underlined_ and /italic/. This variable sets the marker
4046 characters, the face to be used by font-lock for highlighting in Org-mode
4047 Emacs buffers, and the HTML tags to be used for this.
4048 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4049 Use customize to modify this, or restart Emacs after changing it."
4050 :group 'org-appearance
4051 :set 'org-set-emph-re
4052 :type '(repeat
4053 (list
4054 (string :tag "Marker character")
4055 (choice
4056 (face :tag "Font-lock-face")
4057 (plist :tag "Face property list"))
4058 (string :tag "HTML start tag")
4059 (string :tag "HTML end tag")
4060 (option (const verbatim)))))
4062 (defvar org-protecting-blocks
4063 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4064 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4065 This is needed for font-lock setup.")
4067 ;;; Miscellaneous options
4069 (defgroup org-completion nil
4070 "Completion in Org-mode."
4071 :tag "Org Completion"
4072 :group 'org)
4074 (defcustom org-completion-use-ido nil
4075 "Non-nil means use ido completion wherever possible.
4076 Note that `ido-mode' must be active for this variable to be relevant.
4077 If you decide to turn this variable on, you might well want to turn off
4078 `org-outline-path-complete-in-steps'.
4079 See also `org-completion-use-iswitchb'."
4080 :group 'org-completion
4081 :type 'boolean)
4083 (defcustom org-completion-use-iswitchb nil
4084 "Non-nil means use iswitchb completion wherever possible.
4085 Note that `iswitchb-mode' must be active for this variable to be relevant.
4086 If you decide to turn this variable on, you might well want to turn off
4087 `org-outline-path-complete-in-steps'.
4088 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4089 :group 'org-completion
4090 :type 'boolean)
4092 (defcustom org-completion-fallback-command 'hippie-expand
4093 "The expansion command called by \\[pcomplete] in normal context.
4094 Normal means, no org-mode-specific context."
4095 :group 'org-completion
4096 :type 'function)
4098 ;;; Functions and variables from their packages
4099 ;; Declared here to avoid compiler warnings
4101 ;; XEmacs only
4102 (defvar outline-mode-menu-heading)
4103 (defvar outline-mode-menu-show)
4104 (defvar outline-mode-menu-hide)
4105 (defvar zmacs-regions) ; XEmacs regions
4107 ;; Emacs only
4108 (defvar mark-active)
4110 ;; Various packages
4111 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4112 (declare-function calendar-forward-day "cal-move" (arg))
4113 (declare-function calendar-goto-date "cal-move" (date))
4114 (declare-function calendar-goto-today "cal-move" ())
4115 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4116 (defvar calc-embedded-close-formula)
4117 (defvar calc-embedded-open-formula)
4118 (declare-function cdlatex-tab "ext:cdlatex" ())
4119 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4120 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4121 (defvar font-lock-unfontify-region-function)
4122 (declare-function iswitchb-read-buffer "iswitchb"
4123 (prompt &optional default require-match start matches-set))
4124 (defvar iswitchb-temp-buflist)
4125 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4126 (defvar org-agenda-tags-todo-honor-ignore-options)
4127 (declare-function org-agenda-skip "org-agenda" ())
4128 (declare-function
4129 org-agenda-format-item "org-agenda"
4130 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4131 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4132 (declare-function org-agenda-change-all-lines "org-agenda"
4133 (newhead hdmarker &optional fixface just-this))
4134 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4135 (declare-function org-agenda-maybe-redo "org-agenda" ())
4136 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4137 (beg end))
4138 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4139 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4140 "org-agenda" (&optional end))
4141 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4142 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4143 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4144 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4145 (declare-function org-indent-mode "org-indent" (&optional arg))
4146 (declare-function parse-time-string "parse-time" (string))
4147 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4148 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4149 (defvar remember-data-file)
4150 (defvar texmathp-why)
4151 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4152 (declare-function table--at-cell-p "table" (position &optional object at-column))
4154 (defvar org-latex-regexps)
4156 ;;; Autoload and prepare some org modules
4158 ;; Some table stuff that needs to be defined here, because it is used
4159 ;; by the functions setting up org-mode or checking for table context.
4161 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4162 "Detect an org-type or table-type table.")
4163 (defconst org-table-line-regexp "^[ \t]*|"
4164 "Detect an org-type table line.")
4165 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4166 "Detect an org-type table line.")
4167 (defconst org-table-hline-regexp "^[ \t]*|-"
4168 "Detect an org-type table hline.")
4169 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4170 "Detect a table-type table hline.")
4171 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4172 "Detect the first line outside a table when searching from within it.
4173 This works for both table types.")
4175 ;; Autoload the functions in org-table.el that are needed by functions here.
4177 (eval-and-compile
4178 (org-autoload "org-table"
4179 '(org-table-begin org-table-blank-field org-table-end)))
4181 ;;;###autoload
4182 (defun turn-on-orgtbl ()
4183 "Unconditionally turn on `orgtbl-mode'."
4184 (require 'org-table)
4185 (orgtbl-mode 1))
4187 (defun org-at-table-p (&optional table-type)
4188 "Return t if the cursor is inside an org-type table.
4189 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4190 (if org-enable-table-editor
4191 (save-excursion
4192 (beginning-of-line 1)
4193 (looking-at (if table-type org-table-any-line-regexp
4194 org-table-line-regexp)))
4195 nil))
4196 (defsubst org-table-p () (org-at-table-p))
4198 (defun org-at-table.el-p ()
4199 "Return t if and only if we are at a table.el table."
4200 (and (org-at-table-p 'any)
4201 (save-excursion
4202 (goto-char (org-table-begin 'any))
4203 (looking-at org-table1-hline-regexp))))
4204 (defun org-table-recognize-table.el ()
4205 "If there is a table.el table nearby, recognize it and move into it."
4206 (if org-table-tab-recognizes-table.el
4207 (if (org-at-table.el-p)
4208 (progn
4209 (beginning-of-line 1)
4210 (if (looking-at org-table-dataline-regexp)
4212 (if (looking-at org-table1-hline-regexp)
4213 (progn
4214 (beginning-of-line 2)
4215 (if (looking-at org-table-any-border-regexp)
4216 (beginning-of-line -1)))))
4217 (if (re-search-forward "|" (org-table-end t) t)
4218 (progn
4219 (require 'table)
4220 (if (table--at-cell-p (point))
4222 (message "recognizing table.el table...")
4223 (table-recognize-table)
4224 (message "recognizing table.el table...done")))
4225 (error "This should not happen"))
4227 nil)
4228 nil))
4230 (defun org-at-table-hline-p ()
4231 "Return t if the cursor is inside a hline in a table."
4232 (if org-enable-table-editor
4233 (save-excursion
4234 (beginning-of-line 1)
4235 (looking-at org-table-hline-regexp))
4236 nil))
4238 (defvar org-table-clean-did-remove-column nil)
4240 (defun org-table-map-tables (function &optional quietly)
4241 "Apply FUNCTION to the start of all tables in the buffer."
4242 (save-excursion
4243 (save-restriction
4244 (widen)
4245 (goto-char (point-min))
4246 (while (re-search-forward org-table-any-line-regexp nil t)
4247 (unless quietly
4248 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4249 (beginning-of-line 1)
4250 (when (and (looking-at org-table-line-regexp)
4251 ;; Exclude tables in src/example/verbatim/clocktable blocks
4252 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4253 (save-excursion (funcall function))
4254 (or (looking-at org-table-line-regexp)
4255 (forward-char 1)))
4256 (re-search-forward org-table-any-border-regexp nil 1))))
4257 (unless quietly (message "Mapping tables: done")))
4259 ;; Declare and autoload functions from ox.el and al.
4261 (declare-function org-export-get-environment "ox"
4262 (&optional backend subtreep ext-plist))
4263 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4265 ;; Declare and autoload functions from org-agenda.el
4267 (eval-and-compile
4268 (org-autoload "org-agenda"
4269 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4271 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4272 (declare-function org-clock-update-mode-line "org-clock" ())
4273 (declare-function org-resolve-clocks "org-clock"
4274 (&optional also-non-dangling-p prompt last-valid))
4275 (defvar org-clock-start-time)
4276 (defvar org-clock-marker (make-marker)
4277 "Marker recording the last clock-in.")
4278 (defvar org-clock-hd-marker (make-marker)
4279 "Marker recording the last clock-in, but the headline position.")
4280 (defvar org-clock-heading ""
4281 "The heading of the current clock entry.")
4282 (defun org-clock-is-active ()
4283 "Return non-nil if clock is currently running.
4284 The return value is actually the clock marker."
4285 (marker-buffer org-clock-marker))
4287 (eval-and-compile
4288 (org-autoload "org-clock" '(org-clock-remove-overlays
4289 org-clock-update-time-maybe
4290 org-clocktable-shift)))
4292 (defun org-check-running-clock ()
4293 "Check if the current buffer contains the running clock.
4294 If yes, offer to stop it and to save the buffer with the changes."
4295 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4296 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4297 (buffer-name))))
4298 (org-clock-out)
4299 (when (y-or-n-p "Save changed buffer?")
4300 (save-buffer))))
4302 (defun org-clocktable-try-shift (dir n)
4303 "Check if this line starts a clock table, if yes, shift the time block."
4304 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4305 (org-clocktable-shift dir n)))
4307 ;;;###autoload
4308 (defun org-clock-persistence-insinuate ()
4309 "Set up hooks for clock persistence."
4310 (require 'org-clock)
4311 (add-hook 'org-mode-hook 'org-clock-load)
4312 (add-hook 'kill-emacs-hook 'org-clock-save))
4314 ;; Define the variable already here, to make sure we have it.
4315 (defvar org-indent-mode nil
4316 "Non-nil if Org-Indent mode is enabled.
4317 Use the command `org-indent-mode' to change this variable.")
4319 ;; Autoload archiving code
4320 ;; The stuff that is needed for cycling and tags has to be defined here.
4322 (defgroup org-archive nil
4323 "Options concerning archiving in Org-mode."
4324 :tag "Org Archive"
4325 :group 'org-structure)
4327 (defcustom org-archive-location "%s_archive::"
4328 "The location where subtrees should be archived.
4330 The value of this variable is a string, consisting of two parts,
4331 separated by a double-colon. The first part is a filename and
4332 the second part is a headline.
4334 When the filename is omitted, archiving happens in the same file.
4335 %s in the filename will be replaced by the current file
4336 name (without the directory part). Archiving to a different file
4337 is useful to keep archived entries from contributing to the
4338 Org-mode Agenda.
4340 The archived entries will be filed as subtrees of the specified
4341 headline. When the headline is omitted, the subtrees are simply
4342 filed away at the end of the file, as top-level entries. Also in
4343 the heading you can use %s to represent the file name, this can be
4344 useful when using the same archive for a number of different files.
4346 Here are a few examples:
4347 \"%s_archive::\"
4348 If the current file is Projects.org, archive in file
4349 Projects.org_archive, as top-level trees. This is the default.
4351 \"::* Archived Tasks\"
4352 Archive in the current file, under the top-level headline
4353 \"* Archived Tasks\".
4355 \"~/org/archive.org::\"
4356 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4358 \"~/org/archive.org::* From %s\"
4359 Archive in file ~/org/archive.org (absolute path), under headlines
4360 \"From FILENAME\" where file name is the current file name.
4362 \"~/org/datetree.org::datetree/* Finished Tasks\"
4363 The \"datetree/\" string is special, signifying to archive
4364 items to the datetree. Items are placed in either the CLOSED
4365 date of the item, or the current date if there is no CLOSED date.
4366 The heading will be a subentry to the current date. There doesn't
4367 need to be a heading, but there always needs to be a slash after
4368 datetree. For example, to store archived items directly in the
4369 datetree, use \"~/org/datetree.org::datetree/\".
4371 \"basement::** Finished Tasks\"
4372 Archive in file ./basement (relative path), as level 3 trees
4373 below the level 2 heading \"** Finished Tasks\".
4375 You may set this option on a per-file basis by adding to the buffer a
4376 line like
4378 #+ARCHIVE: basement::** Finished Tasks
4380 You may also define it locally for a subtree by setting an ARCHIVE property
4381 in the entry. If such a property is found in an entry, or anywhere up
4382 the hierarchy, it will be used."
4383 :group 'org-archive
4384 :type 'string)
4386 (defcustom org-archive-tag "ARCHIVE"
4387 "The tag that marks a subtree as archived.
4388 An archived subtree does not open during visibility cycling, and does
4389 not contribute to the agenda listings.
4390 After changing this, font-lock must be restarted in the relevant buffers to
4391 get the proper fontification."
4392 :group 'org-archive
4393 :group 'org-keywords
4394 :type 'string)
4396 (defcustom org-agenda-skip-archived-trees t
4397 "Non-nil means the agenda will skip any items located in archived trees.
4398 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4399 variable is no longer recommended, you should leave it at the value t.
4400 Instead, use the key `v' to cycle the archives-mode in the agenda."
4401 :group 'org-archive
4402 :group 'org-agenda-skip
4403 :type 'boolean)
4405 (defcustom org-columns-skip-archived-trees t
4406 "Non-nil means ignore archived trees when creating column view."
4407 :group 'org-archive
4408 :group 'org-properties
4409 :type 'boolean)
4411 (defcustom org-cycle-open-archived-trees nil
4412 "Non-nil means `org-cycle' will open archived trees.
4413 An archived tree is a tree marked with the tag ARCHIVE.
4414 When nil, archived trees will stay folded. You can still open them with
4415 normal outline commands like `show-all', but not with the cycling commands."
4416 :group 'org-archive
4417 :group 'org-cycle
4418 :type 'boolean)
4420 (defcustom org-sparse-tree-open-archived-trees nil
4421 "Non-nil means sparse tree construction shows matches in archived trees.
4422 When nil, matches in these trees are highlighted, but the trees are kept in
4423 collapsed state."
4424 :group 'org-archive
4425 :group 'org-sparse-trees
4426 :type 'boolean)
4428 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4429 "The default date type when building a sparse tree.
4430 When this is nil, a date is a scheduled or a deadline timestamp.
4431 Otherwise, these types are allowed:
4433 all: all timestamps
4434 active: only active timestamps (<...>)
4435 inactive: only inactive timestamps (<...)
4436 scheduled: only scheduled timestamps
4437 deadline: only deadline timestamps"
4438 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4439 (const :tag "All timestamps" all)
4440 (const :tag "Only active timestamps" active)
4441 (const :tag "Only inactive timestamps" inactive)
4442 (const :tag "Only scheduled timestamps" scheduled)
4443 (const :tag "Only deadline timestamps" deadline))
4444 :version "24.3"
4445 :group 'org-sparse-trees)
4447 (defun org-cycle-hide-archived-subtrees (state)
4448 "Re-hide all archived subtrees after a visibility state change."
4449 (when (and (not org-cycle-open-archived-trees)
4450 (not (memq state '(overview folded))))
4451 (save-excursion
4452 (let* ((globalp (memq state '(contents all)))
4453 (beg (if globalp (point-min) (point)))
4454 (end (if globalp (point-max) (org-end-of-subtree t))))
4455 (org-hide-archived-subtrees beg end)
4456 (goto-char beg)
4457 (if (looking-at (concat ".*:" org-archive-tag ":"))
4458 (message "%s" (substitute-command-keys
4459 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4461 (defun org-force-cycle-archived ()
4462 "Cycle subtree even if it is archived."
4463 (interactive)
4464 (setq this-command 'org-cycle)
4465 (let ((org-cycle-open-archived-trees t))
4466 (call-interactively 'org-cycle)))
4468 (defun org-hide-archived-subtrees (beg end)
4469 "Re-hide all archived subtrees after a visibility state change."
4470 (save-excursion
4471 (let* ((re (concat ":" org-archive-tag ":")))
4472 (goto-char beg)
4473 (while (re-search-forward re end t)
4474 (when (org-at-heading-p)
4475 (org-flag-subtree t)
4476 (org-end-of-subtree t))))))
4478 (declare-function outline-end-of-heading "outline" ())
4479 (declare-function outline-flag-region "outline" (from to flag))
4480 (defun org-flag-subtree (flag)
4481 (save-excursion
4482 (org-back-to-heading t)
4483 (outline-end-of-heading)
4484 (outline-flag-region (point)
4485 (progn (org-end-of-subtree t) (point))
4486 flag)))
4488 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4490 (eval-and-compile
4491 (org-autoload "org-archive"
4492 '(org-add-archive-files)))
4494 ;; Autoload Column View Code
4496 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4497 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4498 (declare-function org-columns-compute "org-colview" (property))
4500 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4501 '(org-columns-number-to-string
4502 org-columns-get-format-and-top-level
4503 org-columns-compute
4504 org-columns-remove-overlays))
4506 ;; Autoload ID code
4508 (declare-function org-id-store-link "org-id")
4509 (declare-function org-id-locations-load "org-id")
4510 (declare-function org-id-locations-save "org-id")
4511 (defvar org-id-track-globally)
4512 (org-autoload "org-id"
4513 '(org-id-new
4514 org-id-copy
4515 org-id-get-with-outline-path-completion
4516 org-id-get-with-outline-drilling))
4518 ;;; Variables for pre-computed regular expressions, all buffer local
4520 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4521 "Matches first line of a hidden block.")
4522 (make-variable-buffer-local 'org-drawer-regexp)
4523 (defvar org-todo-regexp nil
4524 "Matches any of the TODO state keywords.")
4525 (make-variable-buffer-local 'org-todo-regexp)
4526 (defvar org-not-done-regexp nil
4527 "Matches any of the TODO state keywords except the last one.")
4528 (make-variable-buffer-local 'org-not-done-regexp)
4529 (defvar org-not-done-heading-regexp nil
4530 "Matches a TODO headline that is not done.")
4531 (make-variable-buffer-local 'org-not-done-regexp)
4532 (defvar org-todo-line-regexp nil
4533 "Matches a headline and puts TODO state into group 2 if present.")
4534 (make-variable-buffer-local 'org-todo-line-regexp)
4535 (defvar org-complex-heading-regexp nil
4536 "Matches a headline and puts everything into groups:
4537 group 1: the stars
4538 group 2: The todo keyword, maybe
4539 group 3: Priority cookie
4540 group 4: True headline
4541 group 5: Tags")
4542 (make-variable-buffer-local 'org-complex-heading-regexp)
4543 (defvar org-complex-heading-regexp-format nil
4544 "Printf format to make regexp to match an exact headline.
4545 This regexp will match the headline of any node which has the
4546 exact headline text that is put into the format, but may have any
4547 TODO state, priority and tags.")
4548 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4549 (defvar org-todo-line-tags-regexp nil
4550 "Matches a headline and puts TODO state into group 2 if present.
4551 Also put tags into group 4 if tags are present.")
4552 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4553 (defvar org-ds-keyword-length 12
4554 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4555 (make-variable-buffer-local 'org-ds-keyword-length)
4556 (defvar org-deadline-regexp nil
4557 "Matches the DEADLINE keyword.")
4558 (make-variable-buffer-local 'org-deadline-regexp)
4559 (defvar org-deadline-time-regexp nil
4560 "Matches the DEADLINE keyword together with a time stamp.")
4561 (make-variable-buffer-local 'org-deadline-time-regexp)
4562 (defvar org-deadline-line-regexp nil
4563 "Matches the DEADLINE keyword and the rest of the line.")
4564 (make-variable-buffer-local 'org-deadline-line-regexp)
4565 (defvar org-scheduled-regexp nil
4566 "Matches the SCHEDULED keyword.")
4567 (make-variable-buffer-local 'org-scheduled-regexp)
4568 (defvar org-scheduled-time-regexp nil
4569 "Matches the SCHEDULED keyword together with a time stamp.")
4570 (make-variable-buffer-local 'org-scheduled-time-regexp)
4571 (defvar org-closed-time-regexp nil
4572 "Matches the CLOSED keyword together with a time stamp.")
4573 (make-variable-buffer-local 'org-closed-time-regexp)
4575 (defvar org-keyword-time-regexp nil
4576 "Matches any of the 4 keywords, together with the time stamp.")
4577 (make-variable-buffer-local 'org-keyword-time-regexp)
4578 (defvar org-keyword-time-not-clock-regexp nil
4579 "Matches any of the 3 keywords, together with the time stamp.")
4580 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4581 (defvar org-maybe-keyword-time-regexp nil
4582 "Matches a timestamp, possibly preceded by a keyword.")
4583 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4584 (defvar org-all-time-keywords nil
4585 "List of time keywords.")
4586 (make-variable-buffer-local 'org-all-time-keywords)
4588 (defconst org-plain-time-of-day-regexp
4589 (concat
4590 "\\(\\<[012]?[0-9]"
4591 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4592 "\\(--?"
4593 "\\(\\<[012]?[0-9]"
4594 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4595 "\\)?")
4596 "Regular expression to match a plain time or time range.
4597 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4598 groups carry important information:
4599 0 the full match
4600 1 the first time, range or not
4601 8 the second time, if it is a range.")
4603 (defconst org-plain-time-extension-regexp
4604 (concat
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4608 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4609 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4610 groups carry important information:
4611 0 the full match
4612 7 hours of duration
4613 9 minutes of duration")
4615 (defconst org-stamp-time-of-day-regexp
4616 (concat
4617 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4618 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4619 "\\(--?"
4620 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4621 "Regular expression to match a timestamp time or time range.
4622 After a match, the following groups carry important information:
4623 0 the full match
4624 1 date plus weekday, for back referencing to make sure both times are on the same day
4625 2 the first time, range or not
4626 4 the second time, if it is a range.")
4628 (defconst org-startup-options
4629 '(("fold" org-startup-folded t)
4630 ("overview" org-startup-folded t)
4631 ("nofold" org-startup-folded nil)
4632 ("showall" org-startup-folded nil)
4633 ("showeverything" org-startup-folded showeverything)
4634 ("content" org-startup-folded content)
4635 ("indent" org-startup-indented t)
4636 ("noindent" org-startup-indented nil)
4637 ("hidestars" org-hide-leading-stars t)
4638 ("showstars" org-hide-leading-stars nil)
4639 ("odd" org-odd-levels-only t)
4640 ("oddeven" org-odd-levels-only nil)
4641 ("align" org-startup-align-all-tables t)
4642 ("noalign" org-startup-align-all-tables nil)
4643 ("inlineimages" org-startup-with-inline-images t)
4644 ("noinlineimages" org-startup-with-inline-images nil)
4645 ("latexpreview" org-startup-with-latex-preview t)
4646 ("nolatexpreview" org-startup-with-latex-preview nil)
4647 ("customtime" org-display-custom-times t)
4648 ("logdone" org-log-done time)
4649 ("lognotedone" org-log-done note)
4650 ("nologdone" org-log-done nil)
4651 ("lognoteclock-out" org-log-note-clock-out t)
4652 ("nolognoteclock-out" org-log-note-clock-out nil)
4653 ("logrepeat" org-log-repeat state)
4654 ("lognoterepeat" org-log-repeat note)
4655 ("logdrawer" org-log-into-drawer t)
4656 ("nologdrawer" org-log-into-drawer nil)
4657 ("logstatesreversed" org-log-states-order-reversed t)
4658 ("nologstatesreversed" org-log-states-order-reversed nil)
4659 ("nologrepeat" org-log-repeat nil)
4660 ("logreschedule" org-log-reschedule time)
4661 ("lognotereschedule" org-log-reschedule note)
4662 ("nologreschedule" org-log-reschedule nil)
4663 ("logredeadline" org-log-redeadline time)
4664 ("lognoteredeadline" org-log-redeadline note)
4665 ("nologredeadline" org-log-redeadline nil)
4666 ("logrefile" org-log-refile time)
4667 ("lognoterefile" org-log-refile note)
4668 ("nologrefile" org-log-refile nil)
4669 ("fninline" org-footnote-define-inline t)
4670 ("nofninline" org-footnote-define-inline nil)
4671 ("fnlocal" org-footnote-section nil)
4672 ("fnauto" org-footnote-auto-label t)
4673 ("fnprompt" org-footnote-auto-label nil)
4674 ("fnconfirm" org-footnote-auto-label confirm)
4675 ("fnplain" org-footnote-auto-label plain)
4676 ("fnadjust" org-footnote-auto-adjust t)
4677 ("nofnadjust" org-footnote-auto-adjust nil)
4678 ("constcgs" constants-unit-system cgs)
4679 ("constSI" constants-unit-system SI)
4680 ("noptag" org-tag-persistent-alist nil)
4681 ("hideblocks" org-hide-block-startup t)
4682 ("nohideblocks" org-hide-block-startup nil)
4683 ("beamer" org-startup-with-beamer-mode t)
4684 ("entitiespretty" org-pretty-entities t)
4685 ("entitiesplain" org-pretty-entities nil))
4686 "Variable associated with STARTUP options for org-mode.
4687 Each element is a list of three items: the startup options (as written
4688 in the #+STARTUP line), the corresponding variable, and the value to set
4689 this variable to if the option is found. An optional forth element PUSH
4690 means to push this value onto the list in the variable.")
4692 (defun org-update-property-plist (key val props)
4693 "Update PROPS with KEY and VAL."
4694 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4695 (key (if appending (substring key 0 (- (length key) 1)) key))
4696 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4697 (previous (cdr (assoc key props))))
4698 (if appending
4699 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4700 (cons (cons key val) remainder))))
4702 (defconst org-block-regexp
4703 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4704 "Regular expression for hiding blocks.")
4705 (defconst org-heading-keyword-regexp-format
4706 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4707 "Printf format for a regexp matching an headline with some keyword.
4708 This regexp will match the headline of any node which has the
4709 exact keyword that is put into the format. The keyword isn't in
4710 any group by default, but the stars and the body are.")
4711 (defconst org-heading-keyword-maybe-regexp-format
4712 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4713 "Printf format for a regexp matching an headline, possibly with some keyword.
4714 This regexp can match any headline with the specified keyword, or
4715 without a keyword. The keyword isn't in any group by default,
4716 but the stars and the body are.")
4718 (defun org-set-regexps-and-options ()
4719 "Precompute regular expressions for current buffer."
4720 (when (derived-mode-p 'org-mode)
4721 (org-set-local 'org-todo-kwd-alist nil)
4722 (org-set-local 'org-todo-key-alist nil)
4723 (org-set-local 'org-todo-key-trigger nil)
4724 (org-set-local 'org-todo-keywords-1 nil)
4725 (org-set-local 'org-done-keywords nil)
4726 (org-set-local 'org-todo-heads nil)
4727 (org-set-local 'org-todo-sets nil)
4728 (org-set-local 'org-todo-log-states nil)
4729 (org-set-local 'org-file-properties nil)
4730 (org-set-local 'org-file-tags nil)
4731 (let ((re (org-make-options-regexp
4732 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4733 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4734 "SETUPFILE" "OPTIONS")
4735 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4736 (splitre "[ \t]+")
4737 (scripts org-use-sub-superscripts)
4738 kwds kws0 kwsa key log value cat arch tags const links hw dws
4739 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4740 (start 0))
4741 (save-excursion
4742 (save-restriction
4743 (widen)
4744 (goto-char (point-min))
4745 (while (or (and ext-setup-or-nil
4746 (string-match re ext-setup-or-nil start)
4747 (setq start (match-end 0)))
4748 (and (setq ext-setup-or-nil nil start 0)
4749 (re-search-forward re nil t)))
4750 (setq key (upcase (match-string 1 ext-setup-or-nil))
4751 value (org-match-string-no-properties 2 ext-setup-or-nil))
4752 (if (stringp value) (setq value (org-trim value)))
4753 (cond
4754 ((equal key "CATEGORY")
4755 (setq cat value))
4756 ((member key '("SEQ_TODO" "TODO"))
4757 (push (cons 'sequence (org-split-string value splitre)) kwds))
4758 ((equal key "TYP_TODO")
4759 (push (cons 'type (org-split-string value splitre)) kwds))
4760 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4761 ;; general TODO-like setup
4762 (push (cons (intern (downcase (match-string 1 key)))
4763 (org-split-string value splitre)) kwds))
4764 ((equal key "TAGS")
4765 (setq tags (append tags (if tags '("\\n") nil)
4766 (org-split-string value splitre))))
4767 ((equal key "COLUMNS")
4768 (org-set-local 'org-columns-default-format value))
4769 ((equal key "LINK")
4770 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4771 (push (cons (match-string 1 value)
4772 (org-trim (match-string 2 value)))
4773 links)))
4774 ((equal key "PRIORITIES")
4775 (setq prio (org-split-string value " +")))
4776 ((equal key "PROPERTY")
4777 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4778 (setq props (org-update-property-plist (match-string 1 value)
4779 (match-string 2 value)
4780 props))))
4781 ((equal key "FILETAGS")
4782 (when (string-match "\\S-" value)
4783 (setq ftags
4784 (append
4785 ftags
4786 (apply 'append
4787 (mapcar (lambda (x) (org-split-string x ":"))
4788 (org-split-string value)))))))
4789 ((equal key "DRAWERS")
4790 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4791 ((equal key "CONSTANTS")
4792 (setq const (append const (org-split-string value splitre))))
4793 ((equal key "STARTUP")
4794 (let ((opts (org-split-string value splitre))
4795 l var val)
4796 (while (setq l (pop opts))
4797 (when (setq l (assoc l org-startup-options))
4798 (setq var (nth 1 l) val (nth 2 l))
4799 (if (not (nth 3 l))
4800 (set (make-local-variable var) val)
4801 (if (not (listp (symbol-value var)))
4802 (set (make-local-variable var) nil))
4803 (set (make-local-variable var) (symbol-value var))
4804 (add-to-list var val))))))
4805 ((equal key "ARCHIVE")
4806 (setq arch value)
4807 (remove-text-properties 0 (length arch)
4808 '(face t fontified t) arch))
4809 ((equal key "OPTIONS")
4810 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4811 (setq scripts (read (match-string 2 value)))))
4812 ((equal key "SETUPFILE")
4813 (setq setup-contents (org-file-contents
4814 (expand-file-name
4815 (org-remove-double-quotes value))
4816 'noerror))
4817 (if (not ext-setup-or-nil)
4818 (setq ext-setup-or-nil setup-contents start 0)
4819 (setq ext-setup-or-nil
4820 (concat (substring ext-setup-or-nil 0 start)
4821 "\n" setup-contents "\n"
4822 (substring ext-setup-or-nil start)))))))
4823 ;; search for property blocks
4824 (goto-char (point-min))
4825 (while (re-search-forward org-block-regexp nil t)
4826 (when (equal "PROPERTY" (upcase (match-string 1)))
4827 (setq value (replace-regexp-in-string
4828 "[\n\r]" " " (match-string 4)))
4829 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4830 (setq props (org-update-property-plist (match-string 1 value)
4831 (match-string 2 value)
4832 props)))))))
4833 (org-set-local 'org-use-sub-superscripts scripts)
4834 (when cat
4835 (org-set-local 'org-category (intern cat))
4836 (push (cons "CATEGORY" cat) props))
4837 (when prio
4838 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4839 (setq prio (mapcar 'string-to-char prio))
4840 (org-set-local 'org-highest-priority (nth 0 prio))
4841 (org-set-local 'org-lowest-priority (nth 1 prio))
4842 (org-set-local 'org-default-priority (nth 2 prio)))
4843 (and props (org-set-local 'org-file-properties (nreverse props)))
4844 (and ftags (org-set-local 'org-file-tags
4845 (mapcar 'org-add-prop-inherited ftags)))
4846 (and drawers (org-set-local 'org-drawers drawers))
4847 (and arch (org-set-local 'org-archive-location arch))
4848 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4849 ;; Process the TODO keywords
4850 (unless kwds
4851 ;; Use the global values as if they had been given locally.
4852 (setq kwds (default-value 'org-todo-keywords))
4853 (if (stringp (car kwds))
4854 (setq kwds (list (cons org-todo-interpretation
4855 (default-value 'org-todo-keywords)))))
4856 (setq kwds (reverse kwds)))
4857 (setq kwds (nreverse kwds))
4858 (let (inter kws kw)
4859 (while (setq kws (pop kwds))
4860 (let ((kws (or
4861 (run-hook-with-args-until-success
4862 'org-todo-setup-filter-hook kws)
4863 kws)))
4864 (setq inter (pop kws) sep (member "|" kws)
4865 kws0 (delete "|" (copy-sequence kws))
4866 kwsa nil
4867 kws1 (mapcar
4868 (lambda (x)
4869 ;; 1 2
4870 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4871 (progn
4872 (setq kw (match-string 1 x)
4873 key (and (match-end 2) (match-string 2 x))
4874 log (org-extract-log-state-settings x))
4875 (push (cons kw (and key (string-to-char key))) kwsa)
4876 (and log (push log org-todo-log-states))
4878 (error "Invalid TODO keyword %s" x)))
4879 kws0)
4880 kwsa (if kwsa (append '((:startgroup))
4881 (nreverse kwsa)
4882 '((:endgroup))))
4883 hw (car kws1)
4884 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4885 tail (list inter hw (car dws) (org-last dws))))
4886 (add-to-list 'org-todo-heads hw 'append)
4887 (push kws1 org-todo-sets)
4888 (setq org-done-keywords (append org-done-keywords dws nil))
4889 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4890 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4891 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4892 (setq org-todo-sets (nreverse org-todo-sets)
4893 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4894 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4895 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4896 ;; Process the constants
4897 (when const
4898 (let (e cst)
4899 (while (setq e (pop const))
4900 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4901 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4902 (setq org-table-formula-constants-local cst)))
4904 ;; Process the tags.
4905 (when tags
4906 (let (e tgs)
4907 (while (setq e (pop tags))
4908 (cond
4909 ((equal e "{") (push '(:startgroup) tgs))
4910 ((equal e "}") (push '(:endgroup) tgs))
4911 ((equal e "\\n") (push '(:newline) tgs))
4912 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4913 (push (cons (match-string 1 e)
4914 (string-to-char (match-string 2 e)))
4915 tgs))
4916 (t (push (list e) tgs))))
4917 (org-set-local 'org-tag-alist nil)
4918 (while (setq e (pop tgs))
4919 (or (and (stringp (car e))
4920 (assoc (car e) org-tag-alist))
4921 (push e org-tag-alist)))))
4923 ;; Compute the regular expressions and other local variables.
4924 ;; Using `org-outline-regexp-bol' would complicate them much,
4925 ;; because of the fixed white space at the end of that string.
4926 (if (not org-done-keywords)
4927 (setq org-done-keywords (and org-todo-keywords-1
4928 (list (org-last org-todo-keywords-1)))))
4929 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4930 (length org-scheduled-string)
4931 (length org-clock-string)
4932 (length org-closed-string)))
4933 org-drawer-regexp
4934 (concat "^[ \t]*:\\("
4935 (mapconcat 'regexp-quote org-drawers "\\|")
4936 "\\):[ \t]*$")
4937 org-not-done-keywords
4938 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4939 org-todo-regexp
4940 (concat "\\("
4941 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4942 "\\)")
4943 org-not-done-regexp
4944 (concat "\\("
4945 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4946 "\\)")
4947 org-not-done-heading-regexp
4948 (format org-heading-keyword-regexp-format org-not-done-regexp)
4949 org-todo-line-regexp
4950 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4951 org-complex-heading-regexp
4952 (concat "^\\(\\*+\\)"
4953 "\\(?: +" org-todo-regexp "\\)?"
4954 "\\(?: +\\(\\[#.\\]\\)\\)?"
4955 "\\(?: +\\(.*?\\)\\)??"
4956 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4957 "[ \t]*$")
4958 org-complex-heading-regexp-format
4959 (concat "^\\(\\*+\\)"
4960 "\\(?: +" org-todo-regexp "\\)?"
4961 "\\(?: +\\(\\[#.\\]\\)\\)?"
4962 "\\(?: +"
4963 ;; Stats cookies can be stuck to body.
4964 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4965 "\\(%s\\)"
4966 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4967 "\\)"
4968 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4969 "[ \t]*$")
4970 org-todo-line-tags-regexp
4971 (concat "^\\(\\*+\\)"
4972 "\\(?: +" org-todo-regexp "\\)?"
4973 "\\(?: +\\(.*?\\)\\)??"
4974 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4975 "[ \t]*$")
4976 org-deadline-regexp (concat "\\<" org-deadline-string)
4977 org-deadline-time-regexp
4978 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4979 org-deadline-line-regexp
4980 (concat "\\<\\(" org-deadline-string "\\).*")
4981 org-scheduled-regexp
4982 (concat "\\<" org-scheduled-string)
4983 org-scheduled-time-regexp
4984 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4985 org-closed-time-regexp
4986 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4987 org-keyword-time-regexp
4988 (concat "\\<\\(" org-scheduled-string
4989 "\\|" org-deadline-string
4990 "\\|" org-closed-string
4991 "\\|" org-clock-string "\\)"
4992 " *[[<]\\([^]>]+\\)[]>]")
4993 org-keyword-time-not-clock-regexp
4994 (concat "\\<\\(" org-scheduled-string
4995 "\\|" org-deadline-string
4996 "\\|" org-closed-string
4997 "\\)"
4998 " *[[<]\\([^]>]+\\)[]>]")
4999 org-maybe-keyword-time-regexp
5000 (concat "\\(\\<\\(" org-scheduled-string
5001 "\\|" org-deadline-string
5002 "\\|" org-closed-string
5003 "\\|" org-clock-string "\\)\\)?"
5004 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5005 org-all-time-keywords
5006 (mapcar (lambda (w) (substring w 0 -1))
5007 (list org-scheduled-string org-deadline-string
5008 org-clock-string org-closed-string)))
5009 (org-compute-latex-and-related-regexp)
5010 (org-set-font-lock-defaults))))
5012 (defun org-file-contents (file &optional noerror)
5013 "Return the contents of FILE, as a string."
5014 (if (or (not file)
5015 (not (file-readable-p file)))
5016 (if noerror
5017 (progn
5018 (message "Cannot read file \"%s\"" file)
5019 (ding) (sit-for 2)
5021 (error "Cannot read file \"%s\"" file))
5022 (with-temp-buffer
5023 (insert-file-contents file)
5024 (buffer-string))))
5026 (defun org-extract-log-state-settings (x)
5027 "Extract the log state setting from a TODO keyword string.
5028 This will extract info from a string like \"WAIT(w@/!)\"."
5029 (let (kw key log1 log2)
5030 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5031 (setq kw (match-string 1 x)
5032 key (and (match-end 2) (match-string 2 x))
5033 log1 (and (match-end 3) (match-string 3 x))
5034 log2 (and (match-end 4) (match-string 4 x)))
5035 (and (or log1 log2)
5036 (list kw
5037 (and log1 (if (equal log1 "!") 'time 'note))
5038 (and log2 (if (equal log2 "!") 'time 'note)))))))
5040 (defun org-remove-keyword-keys (list)
5041 "Remove a pair of parenthesis at the end of each string in LIST."
5042 (mapcar (lambda (x)
5043 (if (string-match "(.*)$" x)
5044 (substring x 0 (match-beginning 0))
5046 list))
5048 (defun org-assign-fast-keys (alist)
5049 "Assign fast keys to a keyword-key alist.
5050 Respect keys that are already there."
5051 (let (new e (alt ?0))
5052 (while (setq e (pop alist))
5053 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5054 (cdr e)) ;; Key already assigned.
5055 (push e new)
5056 (let ((clist (string-to-list (downcase (car e))))
5057 (used (append new alist)))
5058 (when (= (car clist) ?@)
5059 (pop clist))
5060 (while (and clist (rassoc (car clist) used))
5061 (pop clist))
5062 (unless clist
5063 (while (rassoc alt used)
5064 (incf alt)))
5065 (push (cons (car e) (or (car clist) alt)) new))))
5066 (nreverse new)))
5068 ;;; Some variables used in various places
5070 (defvar org-window-configuration nil
5071 "Used in various places to store a window configuration.")
5072 (defvar org-selected-window nil
5073 "Used in various places to store a window configuration.")
5074 (defvar org-finish-function nil
5075 "Function to be called when `C-c C-c' is used.
5076 This is for getting out of special buffers like capture.")
5079 ;; FIXME: Occasionally check by commenting these, to make sure
5080 ;; no other functions uses these, forgetting to let-bind them.
5081 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5082 (defvar org-last-state)
5083 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5085 ;; Defined somewhere in this file, but used before definition.
5086 (defvar org-entities) ;; defined in org-entities.el
5087 (defvar org-struct-menu)
5088 (defvar org-org-menu)
5089 (defvar org-tbl-menu)
5091 ;;;; Define the Org-mode
5093 ;; We use a before-change function to check if a table might need
5094 ;; an update.
5095 (defvar org-table-may-need-update t
5096 "Indicates that a table might need an update.
5097 This variable is set by `org-before-change-function'.
5098 `org-table-align' sets it back to nil.")
5099 (defun org-before-change-function (beg end)
5100 "Every change indicates that a table might need an update."
5101 (setq org-table-may-need-update t))
5102 (defvar org-mode-map)
5103 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5104 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5105 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5106 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5107 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5108 (defvar org-table-buffer-is-an nil)
5110 (defvar bidi-paragraph-direction)
5111 (defvar buffer-face-mode-face)
5113 (require 'outline)
5114 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5115 (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"))
5116 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5118 ;; Other stuff we need.
5119 (require 'time-date)
5120 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5121 (require 'easymenu)
5122 (require 'overlay)
5124 ;; (require 'org-macs) moved higher up in the file before it is first used
5125 (require 'org-entities)
5126 ;; (require 'org-compat) moved higher up in the file before it is first used
5127 (require 'org-faces)
5128 (require 'org-list)
5129 (require 'org-pcomplete)
5130 (require 'org-src)
5131 (require 'org-footnote)
5132 (require 'org-macro)
5134 ;; babel
5135 (require 'ob)
5137 ;;;###autoload
5138 (define-derived-mode org-mode outline-mode "Org"
5139 "Outline-based notes management and organizer, alias
5140 \"Carsten's outline-mode for keeping track of everything.\"
5142 Org-mode develops organizational tasks around a NOTES file which
5143 contains information about projects as plain text. Org-mode is
5144 implemented on top of outline-mode, which is ideal to keep the content
5145 of large files well structured. It supports ToDo items, deadlines and
5146 time stamps, which magically appear in the diary listing of the Emacs
5147 calendar. Tables are easily created with a built-in table editor.
5148 Plain text URL-like links connect to websites, emails (VM), Usenet
5149 messages (Gnus), BBDB entries, and any files related to the project.
5150 For printing and sharing of notes, an Org-mode file (or a part of it)
5151 can be exported as a structured ASCII or HTML file.
5153 The following commands are available:
5155 \\{org-mode-map}"
5157 ;; Get rid of Outline menus, they are not needed
5158 ;; Need to do this here because define-derived-mode sets up
5159 ;; the keymap so late. Still, it is a waste to call this each time
5160 ;; we switch another buffer into org-mode.
5161 (if (featurep 'xemacs)
5162 (when (boundp 'outline-mode-menu-heading)
5163 ;; Assume this is Greg's port, it uses easymenu
5164 (easy-menu-remove outline-mode-menu-heading)
5165 (easy-menu-remove outline-mode-menu-show)
5166 (easy-menu-remove outline-mode-menu-hide))
5167 (define-key org-mode-map [menu-bar headings] 'undefined)
5168 (define-key org-mode-map [menu-bar hide] 'undefined)
5169 (define-key org-mode-map [menu-bar show] 'undefined))
5171 (org-load-modules-maybe)
5172 (easy-menu-add org-org-menu)
5173 (easy-menu-add org-tbl-menu)
5174 (org-install-agenda-files-menu)
5175 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5176 (add-to-invisibility-spec '(org-cwidth))
5177 (add-to-invisibility-spec '(org-hide-block . t))
5178 (when (featurep 'xemacs)
5179 (org-set-local 'line-move-ignore-invisible t))
5180 (org-set-local 'outline-regexp org-outline-regexp)
5181 (org-set-local 'outline-level 'org-outline-level)
5182 (setq bidi-paragraph-direction 'left-to-right)
5183 (when (and org-ellipsis
5184 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5185 (fboundp 'make-glyph-code))
5186 (unless org-display-table
5187 (setq org-display-table (make-display-table)))
5188 (set-display-table-slot
5189 org-display-table 4
5190 (vconcat (mapcar
5191 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5192 org-ellipsis)))
5193 (if (stringp org-ellipsis) org-ellipsis "..."))))
5194 (setq buffer-display-table org-display-table))
5195 (org-set-regexps-and-options)
5196 (when (and org-tag-faces (not org-tags-special-faces-re))
5197 ;; tag faces set outside customize.... force initialization.
5198 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5199 ;; Calc embedded
5200 (org-set-local 'calc-embedded-open-mode "# ")
5201 (mapc (lambda(c) (modify-syntax-entry (string-to-char (car c)) "w p"))
5202 org-emphasis-alist)
5203 (modify-syntax-entry ?< "(")
5204 (modify-syntax-entry ?> ")")
5205 (modify-syntax-entry ?{ "(")
5206 (modify-syntax-entry ?} ")")
5207 (modify-syntax-entry ?@ "w")
5208 (modify-syntax-entry ?\" "\"")
5209 (if org-startup-truncated (setq truncate-lines t))
5210 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5211 (org-set-local 'font-lock-unfontify-region-function
5212 'org-unfontify-region)
5213 ;; Activate before-change-function
5214 (org-set-local 'org-table-may-need-update t)
5215 (org-add-hook 'before-change-functions 'org-before-change-function nil
5216 'local)
5217 ;; Check for running clock before killing a buffer
5218 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5219 ;; Initialize macros templates.
5220 (org-macro-initialize-templates)
5221 ;; Initialize radio targets.
5222 (org-update-radio-target-regexp)
5223 ;; Indentation.
5224 (org-set-local 'indent-line-function 'org-indent-line)
5225 (org-set-local 'indent-region-function 'org-indent-region)
5226 ;; Filling and auto-filling.
5227 (org-setup-filling)
5228 ;; Comments.
5229 (org-setup-comments-handling)
5230 ;; Beginning/end of defun
5231 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5232 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5233 ;; Next error for sparse trees
5234 (org-set-local 'next-error-function 'org-occur-next-match)
5235 ;; Make sure dependence stuff works reliably, even for users who set it
5236 ;; too late :-(
5237 (if org-enforce-todo-dependencies
5238 (add-hook 'org-blocker-hook
5239 'org-block-todo-from-children-or-siblings-or-parent)
5240 (remove-hook 'org-blocker-hook
5241 'org-block-todo-from-children-or-siblings-or-parent))
5242 (if org-enforce-todo-checkbox-dependencies
5243 (add-hook 'org-blocker-hook
5244 'org-block-todo-from-checkboxes)
5245 (remove-hook 'org-blocker-hook
5246 'org-block-todo-from-checkboxes))
5248 ;; Align options lines
5249 (org-set-local
5250 'align-mode-rules-list
5251 '((org-in-buffer-settings
5252 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5253 (modes . '(org-mode)))))
5255 ;; Imenu
5256 (org-set-local 'imenu-create-index-function
5257 'org-imenu-get-tree)
5259 ;; Make isearch reveal context
5260 (if (or (featurep 'xemacs)
5261 (not (boundp 'outline-isearch-open-invisible-function)))
5262 ;; Emacs 21 and XEmacs make use of the hook
5263 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5264 ;; Emacs 22 deals with this through a special variable
5265 (org-set-local 'outline-isearch-open-invisible-function
5266 (lambda (&rest ignore) (org-show-context 'isearch))))
5268 ;; Setup the pcomplete hooks
5269 (set (make-local-variable 'pcomplete-command-completion-function)
5270 'org-pcomplete-initial)
5271 (set (make-local-variable 'pcomplete-command-name-function)
5272 'org-command-at-point)
5273 (set (make-local-variable 'pcomplete-default-completion-function)
5274 'ignore)
5275 (set (make-local-variable 'pcomplete-parse-arguments-function)
5276 'org-parse-arguments)
5277 (set (make-local-variable 'pcomplete-termination-string) "")
5278 (when (>= emacs-major-version 23)
5279 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5281 ;; If empty file that did not turn on org-mode automatically, make it to.
5282 (if (and org-insert-mode-line-in-empty-file
5283 (org-called-interactively-p 'any)
5284 (= (point-min) (point-max)))
5285 (insert "# -*- mode: org -*-\n\n"))
5286 (unless org-inhibit-startup
5287 (org-unmodified
5288 (and org-startup-with-beamer-mode (org-beamer-mode))
5289 (when org-startup-align-all-tables
5290 (org-table-map-tables 'org-table-align 'quietly))
5291 (when org-startup-with-inline-images
5292 (org-display-inline-images))
5293 (when org-startup-with-latex-preview
5294 (org-preview-latex-fragment))
5295 (unless org-inhibit-startup-visibility-stuff
5296 (org-set-startup-visibility))))
5297 ;; Try to set org-hide correctly
5298 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5300 (when (fboundp 'abbrev-table-put)
5301 (abbrev-table-put org-mode-abbrev-table
5302 :parents (list text-mode-abbrev-table)))
5304 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5307 (defun org-find-invisible-foreground ()
5308 (let ((candidates (remove
5309 "unspecified-bg"
5310 (nconc
5311 (list (face-background 'default)
5312 (face-background 'org-default))
5313 (mapcar
5314 (lambda (alist)
5315 (when (boundp alist)
5316 (cdr (assoc 'background-color (symbol-value alist)))))
5317 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5318 (list (face-foreground 'org-hide))))))
5319 (car (remove nil candidates))))
5321 (defun org-current-time (&optional rounding-minutes)
5322 "Current time, possibly rounded to ROUNDING-MINUTES.
5323 When ROUNDING-MINUTES is not an integer, fall back on the car of
5324 `org-time-stamp-rounding-minutes'."
5325 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5326 (car org-time-stamp-rounding-minutes)))
5327 (time (decode-time)))
5328 (if (> r 1)
5329 (apply 'encode-time
5330 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5331 (nthcdr 2 time)))
5332 (current-time))))
5334 (defun org-today ()
5335 "Return today date, considering `org-extend-today-until'."
5336 (time-to-days
5337 (time-subtract (current-time)
5338 (list 0 (* 3600 org-extend-today-until) 0))))
5340 ;;;; Font-Lock stuff, including the activators
5342 (defvar org-mouse-map (make-sparse-keymap))
5343 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5344 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5345 (when org-mouse-1-follows-link
5346 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5347 (when org-tab-follows-link
5348 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5349 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5351 (require 'font-lock)
5353 (defconst org-non-link-chars "]\t\n\r<>")
5354 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5355 "shell" "elisp" "doi" "message"))
5356 (defvar org-link-types-re nil
5357 "Matches a link that has a url-like prefix like \"http:\"")
5358 (defvar org-link-re-with-space nil
5359 "Matches a link with spaces, optional angular brackets around it.")
5360 (defvar org-link-re-with-space2 nil
5361 "Matches a link with spaces, optional angular brackets around it.")
5362 (defvar org-link-re-with-space3 nil
5363 "Matches a link with spaces, only for internal part in bracket links.")
5364 (defvar org-angle-link-re nil
5365 "Matches link with angular brackets, spaces are allowed.")
5366 (defvar org-plain-link-re nil
5367 "Matches plain link, without spaces.")
5368 (defvar org-bracket-link-regexp nil
5369 "Matches a link in double brackets.")
5370 (defvar org-bracket-link-analytic-regexp nil
5371 "Regular expression used to analyze links.
5372 Here is what the match groups contain after a match:
5373 1: http:
5374 2: http
5375 3: path
5376 4: [desc]
5377 5: desc")
5378 (defvar org-bracket-link-analytic-regexp++ nil
5379 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5380 (defvar org-any-link-re nil
5381 "Regular expression matching any link.")
5383 (defconst org-match-sexp-depth 3
5384 "Number of stacked braces for sub/superscript matching.")
5386 (defun org-create-multibrace-regexp (left right n)
5387 "Create a regular expression which will match a balanced sexp.
5388 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5389 as single character strings.
5390 The regexp returned will match the entire expression including the
5391 delimiters. It will also define a single group which contains the
5392 match except for the outermost delimiters. The maximum depth of
5393 stacked delimiters is N. Escaping delimiters is not possible."
5394 (let* ((nothing (concat "[^" left right "]*?"))
5395 (or "\\|")
5396 (re nothing)
5397 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5398 (while (> n 1)
5399 (setq n (1- n)
5400 re (concat re or next)
5401 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5402 (concat left "\\(" re "\\)" right)))
5404 (defvar org-match-substring-regexp
5405 (concat
5406 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5407 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5408 "\\|"
5409 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5410 "\\|"
5411 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5412 "The regular expression matching a sub- or superscript.")
5414 (defvar org-match-substring-with-braces-regexp
5415 (concat
5416 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5417 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5418 "\\)")
5419 "The regular expression matching a sub- or superscript, forcing braces.")
5421 (defun org-make-link-regexps ()
5422 "Update the link regular expressions.
5423 This should be called after the variable `org-link-types' has changed."
5424 (setq org-link-types-re
5425 (concat
5426 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5427 org-link-re-with-space
5428 (concat
5429 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5430 "\\([^" org-non-link-chars " ]"
5431 "[^" org-non-link-chars "]*"
5432 "[^" org-non-link-chars " ]\\)>?")
5433 org-link-re-with-space2
5434 (concat
5435 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5436 "\\([^" org-non-link-chars " ]"
5437 "[^\t\n\r]*"
5438 "[^" org-non-link-chars " ]\\)>?")
5439 org-link-re-with-space3
5440 (concat
5441 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5442 "\\([^" org-non-link-chars " ]"
5443 "[^\t\n\r]*\\)")
5444 org-angle-link-re
5445 (concat
5446 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5447 "\\([^" org-non-link-chars " ]"
5448 "[^" org-non-link-chars "]*"
5449 "\\)>")
5450 org-plain-link-re
5451 (concat
5452 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5453 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5454 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5455 org-bracket-link-regexp
5456 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5457 org-bracket-link-analytic-regexp
5458 (concat
5459 "\\[\\["
5460 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5461 "\\([^]]+\\)"
5462 "\\]"
5463 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5464 "\\]")
5465 org-bracket-link-analytic-regexp++
5466 (concat
5467 "\\[\\["
5468 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5469 "\\([^]]+\\)"
5470 "\\]"
5471 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5472 "\\]")
5473 org-any-link-re
5474 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5475 org-angle-link-re "\\)\\|\\("
5476 org-plain-link-re "\\)")))
5478 (org-make-link-regexps)
5480 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5481 "Regular expression for fast time stamp matching.")
5482 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5483 "Regular expression for fast time stamp matching.")
5484 (defconst org-ts-regexp0
5485 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5486 "Regular expression matching time strings for analysis.
5487 This one does not require the space after the date, so it can be used
5488 on a string that terminates immediately after the date.")
5489 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5490 "Regular expression matching time strings for analysis.")
5491 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5492 "Regular expression matching time stamps, with groups.")
5493 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5494 "Regular expression matching time stamps (also [..]), with groups.")
5495 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5496 "Regular expression matching a time stamp range.")
5497 (defconst org-tr-regexp-both
5498 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5499 "Regular expression matching a time stamp range.")
5500 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5501 org-ts-regexp "\\)?")
5502 "Regular expression matching a time stamp or time stamp range.")
5503 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5504 org-ts-regexp-both "\\)?")
5505 "Regular expression matching a time stamp or time stamp range.
5506 The time stamps may be either active or inactive.")
5508 (defvar org-emph-face nil)
5510 (defun org-do-emphasis-faces (limit)
5511 "Run through the buffer and add overlays to emphasized strings."
5512 (let (rtn a)
5513 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5514 (if (not (= (char-after (match-beginning 3))
5515 (char-after (match-beginning 4))))
5516 (progn
5517 (setq rtn t)
5518 (setq a (assoc (match-string 3) org-emphasis-alist))
5519 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5520 'face
5521 (nth 1 a))
5522 (and (nth 4 a)
5523 (org-remove-flyspell-overlays-in
5524 (match-beginning 0) (match-end 0)))
5525 (add-text-properties (match-beginning 2) (match-end 2)
5526 '(font-lock-multiline t org-emphasis t))
5527 (when org-hide-emphasis-markers
5528 (add-text-properties (match-end 4) (match-beginning 5)
5529 '(invisible org-link))
5530 (add-text-properties (match-beginning 3) (match-end 3)
5531 '(invisible org-link)))))
5532 (backward-char 1))
5533 rtn))
5535 (defun org-emphasize (&optional char)
5536 "Insert or change an emphasis, i.e. a font like bold or italic.
5537 If there is an active region, change that region to a new emphasis.
5538 If there is no region, just insert the marker characters and position
5539 the cursor between them.
5540 CHAR should be either the marker character, or the first character of the
5541 HTML tag associated with that emphasis. If CHAR is a space, the means
5542 to remove the emphasis of the selected region.
5543 If char is not given (for example in an interactive call) it
5544 will be prompted for."
5545 (interactive)
5546 (let ((eal org-emphasis-alist) e det
5547 (erc org-emphasis-regexp-components)
5548 (prompt "")
5549 (string "") beg end move tag c s)
5550 (if (org-region-active-p)
5551 (setq beg (region-beginning) end (region-end)
5552 string (buffer-substring beg end))
5553 (setq move t))
5555 (while (setq e (pop eal))
5556 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5557 c (aref tag 0))
5558 (push (cons c (string-to-char (car e))) det)
5559 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5560 (substring tag 1)))))
5561 (setq det (nreverse det))
5562 (unless char
5563 (message "%s" (concat "Emphasis marker or tag:" prompt))
5564 (setq char (read-char-exclusive)))
5565 (setq char (or (cdr (assoc char det)) char))
5566 (if (equal char ?\ )
5567 (setq s "" move nil)
5568 (unless (assoc (char-to-string char) org-emphasis-alist)
5569 (error "No such emphasis marker: \"%c\"" char))
5570 (setq s (char-to-string char)))
5571 (while (and (> (length string) 1)
5572 (equal (substring string 0 1) (substring string -1))
5573 (assoc (substring string 0 1) org-emphasis-alist))
5574 (setq string (substring string 1 -1)))
5575 (setq string (concat s string s))
5576 (if beg (delete-region beg end))
5577 (unless (or (bolp)
5578 (string-match (concat "[" (nth 0 erc) "\n]")
5579 (char-to-string (char-before (point)))))
5580 (insert " "))
5581 (unless (or (eobp)
5582 (string-match (concat "[" (nth 1 erc) "\n]")
5583 (char-to-string (char-after (point)))))
5584 (insert " ") (backward-char 1))
5585 (insert string)
5586 (and move (backward-char 1))))
5588 (defconst org-nonsticky-props
5589 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5591 (defsubst org-rear-nonsticky-at (pos)
5592 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5594 (defun org-activate-plain-links (limit)
5595 "Run through the buffer and add overlays to links."
5596 (catch 'exit
5597 (let (f hl)
5598 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5599 (not (org-in-src-block-p)))
5600 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5601 (setq f (get-text-property (match-beginning 0) 'face))
5602 (setq hl (org-match-string-no-properties 0))
5603 (if (or (eq f 'org-tag)
5604 (and (listp f) (memq 'org-tag f)))
5606 (add-text-properties (match-beginning 0) (match-end 0)
5607 (list 'mouse-face 'highlight
5608 'face 'org-link
5609 'htmlize-link `(:uri ,hl)
5610 'keymap org-mouse-map))
5611 (org-rear-nonsticky-at (match-end 0)))
5612 t))))
5614 (defun org-activate-code (limit)
5615 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5616 (progn
5617 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5618 (remove-text-properties (match-beginning 0) (match-end 0)
5619 '(display t invisible t intangible t))
5620 t)))
5622 (defcustom org-src-fontify-natively nil
5623 "When non-nil, fontify code in code blocks."
5624 :type 'boolean
5625 :version "24.1"
5626 :group 'org-appearance
5627 :group 'org-babel)
5629 (defcustom org-allow-promoting-top-level-subtree nil
5630 "When non-nil, allow promoting a top level subtree.
5631 The leading star of the top level headline will be replaced
5632 by a #."
5633 :type 'boolean
5634 :version "24.1"
5635 :group 'org-appearance)
5637 (defun org-fontify-meta-lines-and-blocks (limit)
5638 (condition-case nil
5639 (org-fontify-meta-lines-and-blocks-1 limit)
5640 (error (message "org-mode fontification error"))))
5642 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5643 "Fontify #+ lines and blocks, in the correct ways."
5644 (let ((case-fold-search t))
5645 (if (re-search-forward
5646 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5647 limit t)
5648 (let ((beg (match-beginning 0))
5649 (block-start (match-end 0))
5650 (block-end nil)
5651 (lang (match-string 7))
5652 (beg1 (line-beginning-position 2))
5653 (dc1 (downcase (match-string 2)))
5654 (dc3 (downcase (match-string 3)))
5655 end end1 quoting block-type ovl)
5656 (cond
5657 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5658 ;; a single line of backend-specific content
5659 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5660 (remove-text-properties (match-beginning 0) (match-end 0)
5661 '(display t invisible t intangible t))
5662 (add-text-properties (match-beginning 1) (match-end 3)
5663 '(font-lock-fontified t face org-meta-line))
5664 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5665 '(font-lock-fontified t face org-block))
5666 ; for backend-specific code
5668 ((and (match-end 4) (equal dc3 "+begin"))
5669 ;; Truly a block
5670 (setq block-type (downcase (match-string 5))
5671 quoting (member block-type org-protecting-blocks))
5672 (when (re-search-forward
5673 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5674 nil t) ;; on purpose, we look further than LIMIT
5675 (setq end (min (point-max) (match-end 0))
5676 end1 (min (point-max) (1- (match-beginning 0))))
5677 (setq block-end (match-beginning 0))
5678 (when quoting
5679 (remove-text-properties beg end
5680 '(display t invisible t intangible t)))
5681 (add-text-properties
5682 beg end
5683 '(font-lock-fontified t font-lock-multiline t))
5684 (add-text-properties beg beg1 '(face org-meta-line))
5685 (add-text-properties end1 (min (point-max) (1+ end))
5686 '(face org-meta-line)) ; for end_src
5687 (cond
5688 ((and lang (not (string= lang "")) org-src-fontify-natively)
5689 (org-src-font-lock-fontify-block lang block-start block-end)
5690 ;; remove old background overlays
5691 (mapc (lambda (ov)
5692 (if (eq (overlay-get ov 'face) 'org-block-background)
5693 (delete-overlay ov)))
5694 (overlays-at (/ (+ beg1 block-end) 2)))
5695 ;; add a background overlay
5696 (setq ovl (make-overlay beg1 block-end))
5697 (overlay-put ovl 'face 'org-block-background)
5698 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5699 (quoting
5700 (add-text-properties beg1 (min (point-max) (1+ end1))
5701 '(face org-block))) ; end of source block
5702 ((not org-fontify-quote-and-verse-blocks))
5703 ((string= block-type "quote")
5704 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5705 ((string= block-type "verse")
5706 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5707 (add-text-properties beg beg1 '(face org-block-begin-line))
5708 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5709 '(face org-block-end-line))
5711 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5712 (add-text-properties
5713 beg (match-end 3)
5714 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5715 '(font-lock-fontified t invisible t)
5716 '(font-lock-fontified t face org-document-info-keyword)))
5717 (add-text-properties
5718 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5719 (if (string-equal dc1 "+title:")
5720 '(font-lock-fontified t face org-document-title)
5721 '(font-lock-fontified t face org-document-info))))
5722 ((or (equal dc1 "+results")
5723 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5724 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5725 "+call:" "+header:" "+headers:" "+name:"))
5726 (and (match-end 4) (equal dc3 "+attr")))
5727 (add-text-properties
5728 beg (match-end 0)
5729 '(font-lock-fontified t face org-meta-line))
5731 ((member dc3 '(" " ""))
5732 (add-text-properties
5733 beg (match-end 0)
5734 '(font-lock-fontified t face font-lock-comment-face)))
5735 ((not (member (char-after beg) '(?\ ?\t)))
5736 ;; just any other in-buffer setting, but not indented
5737 (add-text-properties
5738 beg (match-end 0)
5739 '(font-lock-fontified t face org-meta-line))
5741 (t nil))))))
5743 (defun org-activate-angle-links (limit)
5744 "Run through the buffer and add overlays to links."
5745 (if (and (re-search-forward org-angle-link-re limit t)
5746 (not (org-in-src-block-p)))
5747 (progn
5748 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5749 (add-text-properties (match-beginning 0) (match-end 0)
5750 (list 'mouse-face 'highlight
5751 'keymap org-mouse-map))
5752 (org-rear-nonsticky-at (match-end 0))
5753 t)))
5755 (defun org-activate-footnote-links (limit)
5756 "Run through the buffer and add overlays to footnotes."
5757 (let ((fn (org-footnote-next-reference-or-definition limit)))
5758 (when fn
5759 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5760 (org-remove-flyspell-overlays-in beg end)
5761 (add-text-properties beg end
5762 (list 'mouse-face 'highlight
5763 'keymap org-mouse-map
5764 'help-echo
5765 (if (= (point-at-bol) beg)
5766 "Footnote definition"
5767 "Footnote reference")
5768 'font-lock-fontified t
5769 'font-lock-multiline t
5770 'face 'org-footnote))))))
5772 (defun org-activate-bracket-links (limit)
5773 "Run through the buffer and add overlays to bracketed links."
5774 (if (and (re-search-forward org-bracket-link-regexp limit t)
5775 (not (org-in-src-block-p)))
5776 (let* ((hl (org-match-string-no-properties 1))
5777 (help (concat "LINK: " hl))
5778 ;; FIXME: Above we should remove the escapes. But that
5779 ;; requires another match, protecting match data, a lot
5780 ;; of overhead for font-lock.
5781 (ip (org-maybe-intangible
5782 (list 'invisible 'org-link
5783 'keymap org-mouse-map 'mouse-face 'highlight
5784 'font-lock-multiline t 'help-echo help
5785 'htmlize-link `(:uri ,hl))))
5786 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5787 'font-lock-multiline t 'help-echo help
5788 'htmlize-link `(:uri ,hl))))
5789 ;; We need to remove the invisible property here. Table narrowing
5790 ;; may have made some of this invisible.
5791 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5792 (remove-text-properties (match-beginning 0) (match-end 0)
5793 '(invisible nil))
5794 (if (match-end 3)
5795 (progn
5796 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5797 (org-rear-nonsticky-at (match-beginning 3))
5798 (add-text-properties (match-beginning 3) (match-end 3) vp)
5799 (org-rear-nonsticky-at (match-end 3))
5800 (add-text-properties (match-end 3) (match-end 0) ip)
5801 (org-rear-nonsticky-at (match-end 0)))
5802 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5803 (org-rear-nonsticky-at (match-beginning 1))
5804 (add-text-properties (match-beginning 1) (match-end 1) vp)
5805 (org-rear-nonsticky-at (match-end 1))
5806 (add-text-properties (match-end 1) (match-end 0) ip)
5807 (org-rear-nonsticky-at (match-end 0)))
5808 t)))
5810 (defun org-activate-dates (limit)
5811 "Run through the buffer and add overlays to dates."
5812 (if (re-search-forward org-tsr-regexp-both limit t)
5813 (progn
5814 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5815 (add-text-properties (match-beginning 0) (match-end 0)
5816 (list 'mouse-face 'highlight
5817 'keymap org-mouse-map))
5818 (org-rear-nonsticky-at (match-end 0))
5819 (when org-display-custom-times
5820 (if (match-end 3)
5821 (org-display-custom-time (match-beginning 3) (match-end 3)))
5822 (org-display-custom-time (match-beginning 1) (match-end 1)))
5823 t)))
5825 (defvar org-target-link-regexp nil
5826 "Regular expression matching radio targets in plain text.")
5827 (make-variable-buffer-local 'org-target-link-regexp)
5828 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5829 "Regular expression matching a link target.")
5830 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5831 "Regular expression matching a radio target.")
5832 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5833 "Regular expression matching any target.")
5835 (defun org-activate-target-links (limit)
5836 "Run through the buffer and add overlays to target matches."
5837 (when org-target-link-regexp
5838 (let ((case-fold-search t))
5839 (if (re-search-forward org-target-link-regexp limit t)
5840 (progn
5841 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5842 (add-text-properties (match-beginning 0) (match-end 0)
5843 (list 'mouse-face 'highlight
5844 'keymap org-mouse-map
5845 'help-echo "Radio target link"
5846 'org-linked-text t))
5847 (org-rear-nonsticky-at (match-end 0))
5848 t)))))
5850 (defun org-update-radio-target-regexp ()
5851 "Find all radio targets in this file and update the regular expression."
5852 (interactive)
5853 (when (memq 'radio org-activate-links)
5854 (setq org-target-link-regexp
5855 (org-make-target-link-regexp (org-all-targets 'radio)))
5856 (org-restart-font-lock)))
5858 (defun org-hide-wide-columns (limit)
5859 (let (s e)
5860 (setq s (text-property-any (point) (or limit (point-max))
5861 'org-cwidth t))
5862 (when s
5863 (setq e (next-single-property-change s 'org-cwidth))
5864 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5865 (goto-char e)
5866 t)))
5868 (defvar org-latex-and-related-regexp nil
5869 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5870 (defvar org-match-substring-regexp)
5871 (defvar org-match-substring-with-braces-regexp)
5873 (defun org-compute-latex-and-related-regexp ()
5874 "Compute regular expression for LaTeX, entities and sub/superscript.
5875 Result depends on variable `org-highlight-latex-and-related'."
5876 (org-set-local
5877 'org-latex-and-related-regexp
5878 (let* ((re-sub
5879 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5880 ((eq org-use-sub-superscripts '{})
5881 (list org-match-substring-with-braces-regexp))
5882 (org-use-sub-superscripts (list org-match-substring-regexp))))
5883 (re-latex
5884 (when (memq 'latex org-highlight-latex-and-related)
5885 (let ((matchers (plist-get org-format-latex-options :matchers)))
5886 (delq nil
5887 (mapcar (lambda (x)
5888 (and (member (car x) matchers) (nth 1 x)))
5889 org-latex-regexps)))))
5890 (re-entities
5891 (when (memq 'entities org-highlight-latex-and-related)
5892 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5893 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5895 (defun org-do-latex-and-related (limit)
5896 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5897 LIMIT bounds the search for syntax to highlight. Stop at first
5898 highlighted object, if any. Return t if some highlighting was
5899 done, nil otherwise."
5900 (when org-highlight-latex-and-related
5901 (catch 'found
5902 (while (re-search-forward org-latex-and-related-regexp limit t)
5903 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5904 'face))
5905 '(org-code org-verbatim underline))
5906 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5907 '(?_ ?^))
5909 0)))
5910 (font-lock-prepend-text-property
5911 (+ offset (match-beginning 0)) (match-end 0)
5912 'face 'org-latex-and-related)
5913 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5914 '(font-lock-multiline t)))
5915 (throw 'found t)))
5916 nil)))
5918 (defun org-restart-font-lock ()
5919 "Restart `font-lock-mode', to force refontification."
5920 (when (and (boundp 'font-lock-mode) font-lock-mode)
5921 (font-lock-mode -1)
5922 (font-lock-mode 1)))
5924 (defun org-all-targets (&optional radio)
5925 "Return a list of all targets in this file.
5926 When optional argument RADIO is non-nil, only find radio
5927 targets."
5928 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5929 (save-excursion
5930 (goto-char (point-min))
5931 (while (re-search-forward re nil t)
5932 ;; Make sure point is really within the object.
5933 (backward-char)
5934 (let ((obj (org-element-context)))
5935 (when (memq (org-element-type obj) '(radio-target target))
5936 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5937 rtn)))
5939 (defun org-make-target-link-regexp (targets)
5940 "Make regular expression matching all strings in TARGETS.
5941 The regular expression finds the targets also if there is a line break
5942 between words."
5943 (and targets
5944 (concat
5945 "\\<\\("
5946 (mapconcat
5947 (lambda (x)
5948 (setq x (regexp-quote x))
5949 (while (string-match " +" x)
5950 (setq x (replace-match "\\s-+" t t x)))
5952 targets
5953 "\\|")
5954 "\\)\\>")))
5956 (defun org-activate-tags (limit)
5957 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5958 (progn
5959 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5960 (add-text-properties (match-beginning 1) (match-end 1)
5961 (list 'mouse-face 'highlight
5962 'keymap org-mouse-map))
5963 (org-rear-nonsticky-at (match-end 1))
5964 t)))
5966 (defun org-outline-level ()
5967 "Compute the outline level of the heading at point.
5968 If this is called at a normal headline, the level is the number of stars.
5969 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5970 (save-excursion
5971 (if (not (condition-case nil
5972 (org-back-to-heading t)
5973 (error nil)))
5975 (looking-at org-outline-regexp)
5976 (1- (- (match-end 0) (match-beginning 0))))))
5978 (defvar org-font-lock-keywords nil)
5980 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5981 "Regular expression matching a property line.")
5983 (defvar org-font-lock-hook nil
5984 "Functions to be called for special font lock stuff.")
5986 (defvar org-font-lock-set-keywords-hook nil
5987 "Functions that can manipulate `org-font-lock-extra-keywords'.
5988 This is called after `org-font-lock-extra-keywords' is defined, but before
5989 it is installed to be used by font lock. This can be useful if something
5990 needs to be inserted at a specific position in the font-lock sequence.")
5992 (defun org-font-lock-hook (limit)
5993 "Run `org-font-lock-hook' within LIMIT."
5994 (run-hook-with-args 'org-font-lock-hook limit))
5996 (defun org-set-font-lock-defaults ()
5997 "Set font lock defaults for the current buffer."
5998 (let* ((em org-fontify-emphasized-text)
5999 (lk org-activate-links)
6000 (org-font-lock-extra-keywords
6001 (list
6002 ;; Call the hook
6003 '(org-font-lock-hook)
6004 ;; Headlines
6005 `(,(if org-fontify-whole-heading-line
6006 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6007 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6008 (1 (org-get-level-face 1))
6009 (2 (org-get-level-face 2))
6010 (3 (org-get-level-face 3)))
6011 ;; Table lines
6012 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6013 (1 'org-table t))
6014 ;; Table internals
6015 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6016 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6017 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6018 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6019 ;; Drawers
6020 (list org-drawer-regexp '(0 'org-special-keyword t))
6021 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6022 ;; Properties
6023 (list org-property-re
6024 '(1 'org-special-keyword t)
6025 '(3 'org-property-value t))
6026 ;; Links
6027 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6028 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6029 (if (memq 'plain lk) '(org-activate-plain-links))
6030 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6031 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6032 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6033 (if (memq 'footnote lk) '(org-activate-footnote-links))
6034 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6035 '(org-hide-wide-columns (0 nil append))
6036 ;; TODO keyword
6037 (list (format org-heading-keyword-regexp-format
6038 org-todo-regexp)
6039 '(2 (org-get-todo-face 2) t))
6040 ;; DONE
6041 (if org-fontify-done-headline
6042 (list (format org-heading-keyword-regexp-format
6043 (concat
6044 "\\(?:"
6045 (mapconcat 'regexp-quote org-done-keywords "\\|")
6046 "\\)"))
6047 '(2 'org-headline-done t))
6048 nil)
6049 ;; Priorities
6050 '(org-font-lock-add-priority-faces)
6051 ;; Tags
6052 '(org-font-lock-add-tag-faces)
6053 ;; Special keywords
6054 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6055 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6056 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6057 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6058 ;; Emphasis
6059 (if em
6060 (if (featurep 'xemacs)
6061 '(org-do-emphasis-faces (0 nil append))
6062 '(org-do-emphasis-faces)))
6063 ;; Checkboxes
6064 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6065 1 'org-checkbox prepend)
6066 (if (cdr (assq 'checkbox org-list-automatic-rules))
6067 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6068 (0 (org-get-checkbox-statistics-face) t)))
6069 ;; Description list items
6070 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6071 1 'org-list-dt prepend)
6072 ;; ARCHIVEd headings
6073 (list (concat
6074 org-outline-regexp-bol
6075 "\\(.*:" org-archive-tag ":.*\\)")
6076 '(1 'org-archived prepend))
6077 ;; Specials
6078 '(org-do-latex-and-related)
6079 '(org-fontify-entities)
6080 '(org-raise-scripts)
6081 ;; Code
6082 '(org-activate-code (1 'org-code t))
6083 ;; COMMENT
6084 (list (format org-heading-keyword-regexp-format
6085 (concat "\\("
6086 org-comment-string "\\|" org-quote-string
6087 "\\)"))
6088 '(2 'org-special-keyword t))
6089 ;; Blocks and meta lines
6090 '(org-fontify-meta-lines-and-blocks)
6092 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6093 (run-hooks 'org-font-lock-set-keywords-hook)
6094 ;; Now set the full font-lock-keywords
6095 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6096 (org-set-local 'font-lock-defaults
6097 '(org-font-lock-keywords t nil nil backward-paragraph))
6098 (kill-local-variable 'font-lock-keywords) nil))
6100 (defun org-toggle-pretty-entities ()
6101 "Toggle the composition display of entities as UTF8 characters."
6102 (interactive)
6103 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6104 (org-restart-font-lock)
6105 (if org-pretty-entities
6106 (message "Entities are displayed as UTF8 characters")
6107 (save-restriction
6108 (widen)
6109 (org-decompose-region (point-min) (point-max))
6110 (message "Entities are displayed plain"))))
6112 (defvar org-custom-properties-overlays nil
6113 "List of overlays used for custom properties.")
6114 (make-variable-buffer-local 'org-custom-properties-overlays)
6116 (defun org-toggle-custom-properties-visibility ()
6117 "Display or hide properties in `org-custom-properties'."
6118 (interactive)
6119 (if org-custom-properties-overlays
6120 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6121 (setq org-custom-properties-overlays nil))
6122 (unless (not org-custom-properties)
6123 (save-excursion
6124 (save-restriction
6125 (widen)
6126 (goto-char (point-min))
6127 (while (re-search-forward org-property-re nil t)
6128 (mapc (lambda(p)
6129 (when (equal p (substring (match-string 1) 1 -1))
6130 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6131 (overlay-put o 'invisible t)
6132 (overlay-put o 'org-custom-property t)
6133 (push o org-custom-properties-overlays))))
6134 org-custom-properties)))))))
6136 (defun org-fontify-entities (limit)
6137 "Find an entity to fontify."
6138 (let (ee)
6139 (when org-pretty-entities
6140 (catch 'match
6141 (while (re-search-forward
6142 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6143 limit t)
6144 (if (and (not (org-in-indented-comment-line))
6145 (setq ee (org-entity-get (match-string 1)))
6146 (= (length (nth 6 ee)) 1))
6147 (let*
6148 ((end (if (equal (match-string 2) "{}")
6149 (match-end 2)
6150 (match-end 1))))
6151 (add-text-properties
6152 (match-beginning 0) end
6153 (list 'font-lock-fontified t))
6154 (compose-region (match-beginning 0) end
6155 (nth 6 ee) nil)
6156 (backward-char 1)
6157 (throw 'match t))))
6158 nil))))
6160 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6161 "Fontify string S like in Org-mode."
6162 (with-temp-buffer
6163 (insert s)
6164 (let ((org-odd-levels-only odd-levels))
6165 (org-mode)
6166 (font-lock-fontify-buffer)
6167 (buffer-string))))
6169 (defvar org-m nil)
6170 (defvar org-l nil)
6171 (defvar org-f nil)
6172 (defun org-get-level-face (n)
6173 "Get the right face for match N in font-lock matching of headlines."
6174 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6175 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6176 (if org-cycle-level-faces
6177 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6178 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6179 (cond
6180 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6181 ((eq n 2) org-f)
6182 (t (if org-level-color-stars-only nil org-f))))
6185 (defun org-get-todo-face (kwd)
6186 "Get the right face for a TODO keyword KWD.
6187 If KWD is a number, get the corresponding match group."
6188 (if (numberp kwd) (setq kwd (match-string kwd)))
6189 (or (org-face-from-face-or-color
6190 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6191 (and (member kwd org-done-keywords) 'org-done)
6192 'org-todo))
6194 (defun org-face-from-face-or-color (context inherit face-or-color)
6195 "Create a face list that inherits INHERIT, but sets the foreground color.
6196 When FACE-OR-COLOR is not a string, just return it."
6197 (if (stringp face-or-color)
6198 (list :inherit inherit
6199 (cdr (assoc context org-faces-easy-properties))
6200 face-or-color)
6201 face-or-color))
6203 (defun org-font-lock-add-tag-faces (limit)
6204 "Add the special tag faces."
6205 (when (and org-tag-faces org-tags-special-faces-re)
6206 (while (re-search-forward org-tags-special-faces-re limit t)
6207 (add-text-properties (match-beginning 1) (match-end 1)
6208 (list 'face (org-get-tag-face 1)
6209 'font-lock-fontified t))
6210 (backward-char 1))))
6212 (defun org-font-lock-add-priority-faces (limit)
6213 "Add the special priority faces."
6214 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6215 (when (save-match-data (org-at-heading-p))
6216 (add-text-properties
6217 (match-beginning 0) (match-end 0)
6218 (list 'face (or (org-face-from-face-or-color
6219 'priority 'org-priority
6220 (cdr (assoc (char-after (match-beginning 1))
6221 org-priority-faces)))
6222 'org-priority)
6223 'font-lock-fontified t)))))
6225 (defun org-get-tag-face (kwd)
6226 "Get the right face for a TODO keyword KWD.
6227 If KWD is a number, get the corresponding match group."
6228 (if (numberp kwd) (setq kwd (match-string kwd)))
6229 (or (org-face-from-face-or-color
6230 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6231 'org-tag))
6233 (defun org-unfontify-region (beg end &optional maybe_loudly)
6234 "Remove fontification and activation overlays from links."
6235 (font-lock-default-unfontify-region beg end)
6236 (let* ((buffer-undo-list t)
6237 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6238 (inhibit-modification-hooks t)
6239 deactivate-mark buffer-file-name buffer-file-truename)
6240 (org-decompose-region beg end)
6241 (remove-text-properties beg end
6242 '(mouse-face t keymap t org-linked-text t
6243 invisible t intangible t
6244 org-no-flyspell t org-emphasis t))
6245 (org-remove-font-lock-display-properties beg end)))
6247 (defconst org-script-display '(((raise -0.3) (height 0.7))
6248 ((raise 0.3) (height 0.7))
6249 ((raise -0.5))
6250 ((raise 0.5)))
6251 "Display properties for showing superscripts and subscripts.")
6253 (defun org-remove-font-lock-display-properties (beg end)
6254 "Remove specific display properties that have been added by font lock.
6255 The will remove the raise properties that are used to show superscripts
6256 and subscripts."
6257 (let (next prop)
6258 (while (< beg end)
6259 (setq next (next-single-property-change beg 'display nil end)
6260 prop (get-text-property beg 'display))
6261 (if (member prop org-script-display)
6262 (put-text-property beg next 'display nil))
6263 (setq beg next))))
6265 (defun org-raise-scripts (limit)
6266 "Add raise properties to sub/superscripts."
6267 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6268 (if (re-search-forward
6269 (if (eq org-use-sub-superscripts t)
6270 org-match-substring-regexp
6271 org-match-substring-with-braces-regexp)
6272 limit t)
6273 (let* ((pos (point)) table-p comment-p
6274 (mpos (match-beginning 3))
6275 (emph-p (get-text-property mpos 'org-emphasis))
6276 (link-p (get-text-property mpos 'mouse-face))
6277 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6278 (goto-char (point-at-bol))
6279 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6280 comment-p (org-looking-at-p "[ \t]*#"))
6281 (goto-char pos)
6282 ;; FIXME: Should we go back one character here, for a_b^c
6283 ;; (goto-char (1- pos)) ;????????????????????
6284 (if (or comment-p emph-p link-p keyw-p)
6286 (put-text-property (match-beginning 3) (match-end 0)
6287 'display
6288 (if (equal (char-after (match-beginning 2)) ?^)
6289 (nth (if table-p 3 1) org-script-display)
6290 (nth (if table-p 2 0) org-script-display)))
6291 (add-text-properties (match-beginning 2) (match-end 2)
6292 (list 'invisible t
6293 'org-dwidth t 'org-dwidth-n 1))
6294 (if (and (eq (char-after (match-beginning 3)) ?{)
6295 (eq (char-before (match-end 3)) ?}))
6296 (progn
6297 (add-text-properties
6298 (match-beginning 3) (1+ (match-beginning 3))
6299 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6300 (add-text-properties
6301 (1- (match-end 3)) (match-end 3)
6302 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6303 t)))))
6305 ;;;; Visibility cycling, including org-goto and indirect buffer
6307 ;;; Cycling
6309 (defvar org-cycle-global-status nil)
6310 (make-variable-buffer-local 'org-cycle-global-status)
6311 (put 'org-cycle-global-status 'org-state t)
6312 (defvar org-cycle-subtree-status nil)
6313 (make-variable-buffer-local 'org-cycle-subtree-status)
6314 (put 'org-cycle-subtree-status 'org-state t)
6316 (defvar org-inlinetask-min-level)
6318 ;;;###autoload
6319 (defun org-cycle (&optional arg)
6320 "TAB-action and visibility cycling for Org-mode.
6322 This is the command invoked in Org-mode by the TAB key. Its main purpose
6323 is outline visibility cycling, but it also invokes other actions
6324 in special contexts.
6326 - When this function is called with a prefix argument, rotate the entire
6327 buffer through 3 states (global cycling)
6328 1. OVERVIEW: Show only top-level headlines.
6329 2. CONTENTS: Show all headlines of all levels, but no body text.
6330 3. SHOW ALL: Show everything.
6331 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6332 determined by the variable `org-startup-folded', and by any VISIBILITY
6333 properties in the buffer.
6334 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6335 including any drawers.
6337 - When inside a table, re-align the table and move to the next field.
6339 - When point is at the beginning of a headline, rotate the subtree started
6340 by this line through 3 different states (local cycling)
6341 1. FOLDED: Only the main headline is shown.
6342 2. CHILDREN: The main headline and the direct children are shown.
6343 From this state, you can move to one of the children
6344 and zoom in further.
6345 3. SUBTREE: Show the entire subtree, including body text.
6346 If there is no subtree, switch directly from CHILDREN to FOLDED.
6348 - When point is at the beginning of an empty headline and the variable
6349 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6350 of the headline by demoting and promoting it to likely levels. This
6351 speeds up creation document structure by pressing TAB once or several
6352 times right after creating a new headline.
6354 - When there is a numeric prefix, go up to a heading with level ARG, do
6355 a `show-subtree' and return to the previous cursor position. If ARG
6356 is negative, go up that many levels.
6358 - When point is not at the beginning of a headline, execute the global
6359 binding for TAB, which is re-indenting the line. See the option
6360 `org-cycle-emulate-tab' for details.
6362 - Special case: if point is at the beginning of the buffer and there is
6363 no headline in line 1, this function will act as if called with prefix arg
6364 (C-u TAB, same as S-TAB) also when called without prefix arg.
6365 But only if also the variable `org-cycle-global-at-bob' is t."
6366 (interactive "P")
6367 (org-load-modules-maybe)
6368 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6369 (and org-cycle-level-after-item/entry-creation
6370 (or (org-cycle-level)
6371 (org-cycle-item-indentation))))
6372 (let* (message-log-max ; Don't populate the *Messages* buffer
6373 (limit-level
6374 (or org-cycle-max-level
6375 (and (boundp 'org-inlinetask-min-level)
6376 org-inlinetask-min-level
6377 (1- org-inlinetask-min-level))))
6378 (nstars (and limit-level
6379 (if org-odd-levels-only
6380 (and limit-level (1- (* limit-level 2)))
6381 limit-level)))
6382 (org-outline-regexp
6383 (if (not (derived-mode-p 'org-mode))
6384 outline-regexp
6385 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6386 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6387 (not (looking-at org-outline-regexp))))
6388 (org-cycle-hook
6389 (if bob-special
6390 (delq 'org-optimize-window-after-visibility-change
6391 (copy-sequence org-cycle-hook))
6392 org-cycle-hook))
6393 (pos (point)))
6395 (if (or bob-special (equal arg '(4)))
6396 ;; special case: use global cycling
6397 (setq arg t))
6399 (cond
6401 ((equal arg '(16))
6402 (setq last-command 'dummy)
6403 (org-set-startup-visibility)
6404 (message "Startup visibility, plus VISIBILITY properties"))
6406 ((equal arg '(64))
6407 (show-all)
6408 (message "Entire buffer visible, including drawers"))
6410 ;; Table: enter it or move to the next field.
6411 ((org-at-table-p 'any)
6412 (if (org-at-table.el-p)
6413 (message "Use C-c ' to edit table.el tables")
6414 (if arg (org-table-edit-field t)
6415 (org-table-justify-field-maybe)
6416 (call-interactively 'org-table-next-field))))
6418 ((run-hook-with-args-until-success
6419 'org-tab-after-check-for-table-hook))
6421 ;; Global cycling: delegate to `org-cycle-internal-global'.
6422 ((eq arg t) (org-cycle-internal-global))
6424 ;; Drawers: delegate to `org-flag-drawer'.
6425 ((and org-drawers org-drawer-regexp
6426 (save-excursion
6427 (beginning-of-line 1)
6428 (looking-at org-drawer-regexp)))
6429 (org-flag-drawer ; toggle block visibility
6430 (not (get-char-property (match-end 0) 'invisible))))
6432 ;; Show-subtree, ARG levels up from here.
6433 ((integerp arg)
6434 (save-excursion
6435 (org-back-to-heading)
6436 (outline-up-heading (if (< arg 0) (- arg)
6437 (- (funcall outline-level) arg)))
6438 (org-show-subtree)))
6440 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6441 ((and (featurep 'org-inlinetask)
6442 (org-inlinetask-at-task-p)
6443 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6444 (org-inlinetask-toggle-visibility))
6446 ((org-try-cdlatex-tab))
6448 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6449 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6450 (save-excursion (beginning-of-line 1)
6451 (looking-at org-outline-regexp)))
6452 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6453 (org-cycle-internal-local))
6455 ;; From there: TAB emulation and template completion.
6456 (buffer-read-only (org-back-to-heading))
6458 ((run-hook-with-args-until-success
6459 'org-tab-after-check-for-cycling-hook))
6461 ((org-try-structure-completion))
6463 ((run-hook-with-args-until-success
6464 'org-tab-before-tab-emulation-hook))
6466 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6467 (or (not (bolp))
6468 (not (looking-at org-outline-regexp))))
6469 (call-interactively (global-key-binding "\t")))
6471 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6472 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6473 (or (and (eq org-cycle-emulate-tab 'white)
6474 (= (match-end 0) (point-at-eol)))
6475 (and (eq org-cycle-emulate-tab 'whitestart)
6476 (>= (match-end 0) pos))))
6478 (eq org-cycle-emulate-tab t))
6479 (call-interactively (global-key-binding "\t")))
6481 (t (save-excursion
6482 (org-back-to-heading)
6483 (org-cycle)))))))
6485 (defun org-cycle-internal-global ()
6486 "Do the global cycling action."
6487 ;; Hack to avoid display of messages for .org attachments in Gnus
6488 (let (message-log-max ; Don't populate the *Messages* buffer
6489 (ga (string-match "\\*fontification" (buffer-name))))
6490 (cond
6491 ((and (eq last-command this-command)
6492 (eq org-cycle-global-status 'overview))
6493 ;; We just created the overview - now do table of contents
6494 ;; This can be slow in very large buffers, so indicate action
6495 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6496 (unless ga (message "CONTENTS..."))
6497 (org-content)
6498 (unless ga (message "CONTENTS...done"))
6499 (setq org-cycle-global-status 'contents)
6500 (run-hook-with-args 'org-cycle-hook 'contents))
6502 ((and (eq last-command this-command)
6503 (eq org-cycle-global-status 'contents))
6504 ;; We just showed the table of contents - now show everything
6505 (run-hook-with-args 'org-pre-cycle-hook 'all)
6506 (show-all)
6507 (unless ga (message "SHOW ALL"))
6508 (setq org-cycle-global-status 'all)
6509 (run-hook-with-args 'org-cycle-hook 'all))
6512 ;; Default action: go to overview
6513 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6514 (org-overview)
6515 (unless ga (message "OVERVIEW"))
6516 (setq org-cycle-global-status 'overview)
6517 (run-hook-with-args 'org-cycle-hook 'overview)))))
6519 (defun org-cycle-internal-local ()
6520 "Do the local cycling action."
6521 (let (message-log-max ; Don't populate the *Messages* buffer
6522 (goal-column 0) eoh eol eos has-children children-skipped struct)
6523 ;; First, determine end of headline (EOH), end of subtree or item
6524 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6525 (save-excursion
6526 (if (org-at-item-p)
6527 (progn
6528 (beginning-of-line)
6529 (setq struct (org-list-struct))
6530 (setq eoh (point-at-eol))
6531 (setq eos (org-list-get-item-end-before-blank (point) struct))
6532 (setq has-children (org-list-has-child-p (point) struct)))
6533 (org-back-to-heading)
6534 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6535 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6536 (setq has-children
6537 (or (save-excursion
6538 (let ((level (funcall outline-level)))
6539 (outline-next-heading)
6540 (and (org-at-heading-p t)
6541 (> (funcall outline-level) level))))
6542 (save-excursion
6543 (org-list-search-forward (org-item-beginning-re) eos t)))))
6544 ;; Determine end invisible part of buffer (EOL)
6545 (beginning-of-line 2)
6546 ;; XEmacs doesn't have `next-single-char-property-change'
6547 (if (featurep 'xemacs)
6548 (while (and (not (eobp)) ;; this is like `next-line'
6549 (get-char-property (1- (point)) 'invisible))
6550 (beginning-of-line 2))
6551 (while (and (not (eobp)) ;; this is like `next-line'
6552 (get-char-property (1- (point)) 'invisible))
6553 (goto-char (next-single-char-property-change (point) 'invisible))
6554 (and (eolp) (beginning-of-line 2))))
6555 (setq eol (point)))
6556 ;; Find out what to do next and set `this-command'
6557 (cond
6558 ((= eos eoh)
6559 ;; Nothing is hidden behind this heading
6560 (unless (org-before-first-heading-p)
6561 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6562 (message "EMPTY ENTRY")
6563 (setq org-cycle-subtree-status nil)
6564 (save-excursion
6565 (goto-char eos)
6566 (outline-next-heading)
6567 (if (outline-invisible-p) (org-flag-heading nil))))
6568 ((and (or (>= eol eos)
6569 (not (string-match "\\S-" (buffer-substring eol eos))))
6570 (or has-children
6571 (not (setq children-skipped
6572 org-cycle-skip-children-state-if-no-children))))
6573 ;; Entire subtree is hidden in one line: children view
6574 (unless (org-before-first-heading-p)
6575 (run-hook-with-args 'org-pre-cycle-hook 'children))
6576 (if (org-at-item-p)
6577 (org-list-set-item-visibility (point-at-bol) struct 'children)
6578 (org-show-entry)
6579 (org-with-limited-levels (show-children))
6580 ;; FIXME: This slows down the func way too much.
6581 ;; How keep drawers hidden in subtree anyway?
6582 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6583 ;; (org-cycle-hide-drawers 'subtree))
6585 ;; Fold every list in subtree to top-level items.
6586 (when (eq org-cycle-include-plain-lists 'integrate)
6587 (save-excursion
6588 (org-back-to-heading)
6589 (while (org-list-search-forward (org-item-beginning-re) eos t)
6590 (beginning-of-line 1)
6591 (let* ((struct (org-list-struct))
6592 (prevs (org-list-prevs-alist struct))
6593 (end (org-list-get-bottom-point struct)))
6594 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6595 (org-list-get-all-items (point) struct prevs))
6596 (goto-char end))))))
6597 (message "CHILDREN")
6598 (save-excursion
6599 (goto-char eos)
6600 (outline-next-heading)
6601 (if (outline-invisible-p) (org-flag-heading nil)))
6602 (setq org-cycle-subtree-status 'children)
6603 (unless (org-before-first-heading-p)
6604 (run-hook-with-args 'org-cycle-hook 'children)))
6605 ((or children-skipped
6606 (and (eq last-command this-command)
6607 (eq org-cycle-subtree-status 'children)))
6608 ;; We just showed the children, or no children are there,
6609 ;; now show everything.
6610 (unless (org-before-first-heading-p)
6611 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6612 (outline-flag-region eoh eos nil)
6613 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6614 (setq org-cycle-subtree-status 'subtree)
6615 (unless (org-before-first-heading-p)
6616 (run-hook-with-args 'org-cycle-hook 'subtree)))
6618 ;; Default action: hide the subtree.
6619 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6620 (outline-flag-region eoh eos t)
6621 (message "FOLDED")
6622 (setq org-cycle-subtree-status 'folded)
6623 (unless (org-before-first-heading-p)
6624 (run-hook-with-args 'org-cycle-hook 'folded))))))
6626 ;;;###autoload
6627 (defun org-global-cycle (&optional arg)
6628 "Cycle the global visibility. For details see `org-cycle'.
6629 With \\[universal-argument] prefix arg, switch to startup visibility.
6630 With a numeric prefix, show all headlines up to that level."
6631 (interactive "P")
6632 (let ((org-cycle-include-plain-lists
6633 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6634 (cond
6635 ((integerp arg)
6636 (show-all)
6637 (hide-sublevels arg)
6638 (setq org-cycle-global-status 'contents))
6639 ((equal arg '(4))
6640 (org-set-startup-visibility)
6641 (message "Startup visibility, plus VISIBILITY properties."))
6643 (org-cycle '(4))))))
6645 (defun org-set-startup-visibility ()
6646 "Set the visibility required by startup options and properties."
6647 (cond
6648 ((eq org-startup-folded t)
6649 (org-cycle '(4)))
6650 ((eq org-startup-folded 'content)
6651 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6652 (org-cycle '(4)) (org-cycle '(4)))))
6653 (unless (eq org-startup-folded 'showeverything)
6654 (if org-hide-block-startup (org-hide-block-all))
6655 (org-set-visibility-according-to-property 'no-cleanup)
6656 (org-cycle-hide-archived-subtrees 'all)
6657 (org-cycle-hide-drawers 'all)
6658 (org-cycle-show-empty-lines t)))
6660 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6661 "Switch subtree visibilities according to :VISIBILITY: property."
6662 (interactive)
6663 (let (org-show-entry-below state)
6664 (save-excursion
6665 (goto-char (point-min))
6666 (while (re-search-forward
6667 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6668 nil t)
6669 (setq state (match-string 1))
6670 (save-excursion
6671 (org-back-to-heading t)
6672 (hide-subtree)
6673 (org-reveal)
6674 (cond
6675 ((equal state '("fold" "folded"))
6676 (hide-subtree))
6677 ((equal state "children")
6678 (org-show-hidden-entry)
6679 (show-children))
6680 ((equal state "content")
6681 (save-excursion
6682 (save-restriction
6683 (org-narrow-to-subtree)
6684 (org-content))))
6685 ((member state '("all" "showall"))
6686 (show-subtree)))))
6687 (unless no-cleanup
6688 (org-cycle-hide-archived-subtrees 'all)
6689 (org-cycle-hide-drawers 'all)
6690 (org-cycle-show-empty-lines 'all)))))
6692 ;; This function uses outline-regexp instead of the more fundamental
6693 ;; org-outline-regexp so that org-cycle-global works outside of Org
6694 ;; buffers, where outline-regexp is needed.
6695 (defun org-overview ()
6696 "Switch to overview mode, showing only top-level headlines.
6697 Really, this shows all headlines with level equal or greater than the level
6698 of the first headline in the buffer. This is important, because if the
6699 first headline is not level one, then (hide-sublevels 1) gives confusing
6700 results."
6701 (interactive)
6702 (let ((level (save-excursion
6703 (goto-char (point-min))
6704 (if (re-search-forward (concat "^" outline-regexp) nil t)
6705 (progn
6706 (goto-char (match-beginning 0))
6707 (funcall outline-level))))))
6708 (and level (hide-sublevels level))))
6710 (defun org-content (&optional arg)
6711 "Show all headlines in the buffer, like a table of contents.
6712 With numerical argument N, show content up to level N."
6713 (interactive "P")
6714 (save-excursion
6715 ;; Visit all headings and show their offspring
6716 (and (integerp arg) (org-overview))
6717 (goto-char (point-max))
6718 (catch 'exit
6719 (while (and (progn (condition-case nil
6720 (outline-previous-visible-heading 1)
6721 (error (goto-char (point-min))))
6723 (looking-at org-outline-regexp))
6724 (if (integerp arg)
6725 (show-children (1- arg))
6726 (show-branches))
6727 (if (bobp) (throw 'exit nil))))))
6730 (defun org-optimize-window-after-visibility-change (state)
6731 "Adjust the window after a change in outline visibility.
6732 This function is the default value of the hook `org-cycle-hook'."
6733 (when (get-buffer-window (current-buffer))
6734 (cond
6735 ((eq state 'content) nil)
6736 ((eq state 'all) nil)
6737 ((eq state 'folded) nil)
6738 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6739 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6741 (defun org-remove-empty-overlays-at (pos)
6742 "Remove outline overlays that do not contain non-white stuff."
6743 (mapc
6744 (lambda (o)
6745 (and (eq 'outline (overlay-get o 'invisible))
6746 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6747 (overlay-end o))))
6748 (delete-overlay o)))
6749 (overlays-at pos)))
6751 (defun org-clean-visibility-after-subtree-move ()
6752 "Fix visibility issues after moving a subtree."
6753 ;; First, find a reasonable region to look at:
6754 ;; Start two siblings above, end three below
6755 (let* ((beg (save-excursion
6756 (and (org-get-last-sibling)
6757 (org-get-last-sibling))
6758 (point)))
6759 (end (save-excursion
6760 (and (org-get-next-sibling)
6761 (org-get-next-sibling)
6762 (org-get-next-sibling))
6763 (if (org-at-heading-p)
6764 (point-at-eol)
6765 (point))))
6766 (level (looking-at "\\*+"))
6767 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6768 (save-excursion
6769 (save-restriction
6770 (narrow-to-region beg end)
6771 (when re
6772 ;; Properly fold already folded siblings
6773 (goto-char (point-min))
6774 (while (re-search-forward re nil t)
6775 (if (and (not (outline-invisible-p))
6776 (save-excursion
6777 (goto-char (point-at-eol)) (outline-invisible-p)))
6778 (hide-entry))))
6779 (org-cycle-show-empty-lines 'overview)
6780 (org-cycle-hide-drawers 'overview)))))
6782 (defun org-cycle-show-empty-lines (state)
6783 "Show empty lines above all visible headlines.
6784 The region to be covered depends on STATE when called through
6785 `org-cycle-hook'. Lisp program can use t for STATE to get the
6786 entire buffer covered. Note that an empty line is only shown if there
6787 are at least `org-cycle-separator-lines' empty lines before the headline."
6788 (when (not (= org-cycle-separator-lines 0))
6789 (save-excursion
6790 (let* ((n (abs org-cycle-separator-lines))
6791 (re (cond
6792 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6793 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6794 (t (let ((ns (number-to-string (- n 2))))
6795 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6796 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6797 beg end b e)
6798 (cond
6799 ((memq state '(overview contents t))
6800 (setq beg (point-min) end (point-max)))
6801 ((memq state '(children folded))
6802 (setq beg (point) end (progn (org-end-of-subtree t t)
6803 (beginning-of-line 2)
6804 (point)))))
6805 (when beg
6806 (goto-char beg)
6807 (while (re-search-forward re end t)
6808 (unless (get-char-property (match-end 1) 'invisible)
6809 (setq e (match-end 1))
6810 (if (< org-cycle-separator-lines 0)
6811 (setq b (save-excursion
6812 (goto-char (match-beginning 0))
6813 (org-back-over-empty-lines)
6814 (if (save-excursion
6815 (goto-char (max (point-min) (1- (point))))
6816 (org-at-heading-p))
6817 (1- (point))
6818 (point))))
6819 (setq b (match-beginning 1)))
6820 (outline-flag-region b e nil)))))))
6821 ;; Never hide empty lines at the end of the file.
6822 (save-excursion
6823 (goto-char (point-max))
6824 (outline-previous-heading)
6825 (outline-end-of-heading)
6826 (if (and (looking-at "[ \t\n]+")
6827 (= (match-end 0) (point-max)))
6828 (outline-flag-region (point) (match-end 0) nil))))
6830 (defun org-show-empty-lines-in-parent ()
6831 "Move to the parent and re-show empty lines before visible headlines."
6832 (save-excursion
6833 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6834 (org-cycle-show-empty-lines context))))
6836 (defun org-files-list ()
6837 "Return `org-agenda-files' list, plus all open org-mode files.
6838 This is useful for operations that need to scan all of a user's
6839 open and agenda-wise Org files."
6840 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6841 (dolist (buf (buffer-list))
6842 (with-current-buffer buf
6843 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6844 (let ((file (expand-file-name (buffer-file-name))))
6845 (unless (member file files)
6846 (push file files))))))
6847 files))
6849 (defsubst org-entry-beginning-position ()
6850 "Return the beginning position of the current entry."
6851 (save-excursion (outline-back-to-heading t) (point)))
6853 (defsubst org-entry-end-position ()
6854 "Return the end position of the current entry."
6855 (save-excursion (outline-next-heading) (point)))
6857 (defun org-cycle-hide-drawers (state)
6858 "Re-hide all drawers after a visibility state change."
6859 (when (and (derived-mode-p 'org-mode)
6860 (not (memq state '(overview folded contents))))
6861 (save-excursion
6862 (let* ((globalp (memq state '(contents all)))
6863 (beg (if globalp (point-min) (point)))
6864 (end (if globalp (point-max)
6865 (if (eq state 'children)
6866 (save-excursion (outline-next-heading) (point))
6867 (org-end-of-subtree t)))))
6868 (goto-char beg)
6869 (while (re-search-forward org-drawer-regexp end t)
6870 (org-flag-drawer t))))))
6872 (defun org-cycle-hide-inline-tasks (state)
6873 "Re-hide inline task when switching to 'contents visibility state."
6874 (when (and (eq state 'contents)
6875 (boundp 'org-inlinetask-min-level)
6876 org-inlinetask-min-level)
6877 (hide-sublevels (1- org-inlinetask-min-level))))
6879 (defun org-flag-drawer (flag)
6880 "When FLAG is non-nil, hide the drawer we are within.
6881 Otherwise make it visible."
6882 (save-excursion
6883 (beginning-of-line 1)
6884 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6885 (let ((b (match-end 0)))
6886 (if (re-search-forward
6887 "^[ \t]*:END:"
6888 (save-excursion (outline-next-heading) (point)) t)
6889 (outline-flag-region b (point-at-eol) flag)
6890 (error ":END: line missing at position %s" b))))))
6892 (defun org-subtree-end-visible-p ()
6893 "Is the end of the current subtree visible?"
6894 (pos-visible-in-window-p
6895 (save-excursion (org-end-of-subtree t) (point))))
6897 (defun org-first-headline-recenter (&optional N)
6898 "Move cursor to the first headline and recenter the headline.
6899 Optional argument N means put the headline into the Nth line of the window."
6900 (goto-char (point-min))
6901 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6902 (beginning-of-line)
6903 (recenter (prefix-numeric-value N))))
6905 ;;; Saving and restoring visibility
6907 (defun org-outline-overlay-data (&optional use-markers)
6908 "Return a list of the locations of all outline overlays.
6909 These are overlays with the `invisible' property value `outline'.
6910 The return value is a list of cons cells, with start and stop
6911 positions for each overlay.
6912 If USE-MARKERS is set, return the positions as markers."
6913 (let (beg end)
6914 (save-excursion
6915 (save-restriction
6916 (widen)
6917 (delq nil
6918 (mapcar (lambda (o)
6919 (when (eq (overlay-get o 'invisible) 'outline)
6920 (setq beg (overlay-start o)
6921 end (overlay-end o))
6922 (and beg end (> end beg)
6923 (if use-markers
6924 (cons (move-marker (make-marker) beg)
6925 (move-marker (make-marker) end))
6926 (cons beg end)))))
6927 (overlays-in (point-min) (point-max))))))))
6929 (defun org-set-outline-overlay-data (data)
6930 "Create visibility overlays for all positions in DATA.
6931 DATA should have been made by `org-outline-overlay-data'."
6932 (let (o)
6933 (save-excursion
6934 (save-restriction
6935 (widen)
6936 (show-all)
6937 (mapc (lambda (c)
6938 (outline-flag-region (car c) (cdr c) t))
6939 data)))))
6941 ;;; Folding of blocks
6943 (defvar org-hide-block-overlays nil
6944 "Overlays hiding blocks.")
6945 (make-variable-buffer-local 'org-hide-block-overlays)
6947 (defun org-block-map (function &optional start end)
6948 "Call FUNCTION at the head of all source blocks in the current buffer.
6949 Optional arguments START and END can be used to limit the range."
6950 (let ((start (or start (point-min)))
6951 (end (or end (point-max))))
6952 (save-excursion
6953 (goto-char start)
6954 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6955 (save-excursion
6956 (save-match-data
6957 (goto-char (match-beginning 0))
6958 (funcall function)))))))
6960 (defun org-hide-block-toggle-all ()
6961 "Toggle the visibility of all blocks in the current buffer."
6962 (org-block-map #'org-hide-block-toggle))
6964 (defun org-hide-block-all ()
6965 "Fold all blocks in the current buffer."
6966 (interactive)
6967 (org-show-block-all)
6968 (org-block-map #'org-hide-block-toggle-maybe))
6970 (defun org-show-block-all ()
6971 "Unfold all blocks in the current buffer."
6972 (interactive)
6973 (mapc 'delete-overlay org-hide-block-overlays)
6974 (setq org-hide-block-overlays nil))
6976 (defun org-hide-block-toggle-maybe ()
6977 "Toggle visibility of block at point."
6978 (interactive)
6979 (let ((case-fold-search t))
6980 (if (save-excursion
6981 (beginning-of-line 1)
6982 (looking-at org-block-regexp))
6983 (progn (org-hide-block-toggle)
6984 t) ;; to signal that we took action
6985 nil))) ;; to signal that we did not
6987 (defun org-hide-block-toggle (&optional force)
6988 "Toggle the visibility of the current block."
6989 (interactive)
6990 (save-excursion
6991 (beginning-of-line)
6992 (if (re-search-forward org-block-regexp nil t)
6993 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6994 (end (match-end 0)) ;; end of entire body
6996 (if (memq t (mapcar (lambda (overlay)
6997 (eq (overlay-get overlay 'invisible)
6998 'org-hide-block))
6999 (overlays-at start)))
7000 (if (or (not force) (eq force 'off))
7001 (mapc (lambda (ov)
7002 (when (member ov org-hide-block-overlays)
7003 (setq org-hide-block-overlays
7004 (delq ov org-hide-block-overlays)))
7005 (when (eq (overlay-get ov 'invisible)
7006 'org-hide-block)
7007 (delete-overlay ov)))
7008 (overlays-at start)))
7009 (setq ov (make-overlay start end))
7010 (overlay-put ov 'invisible 'org-hide-block)
7011 ;; make the block accessible to isearch
7012 (overlay-put
7013 ov 'isearch-open-invisible
7014 (lambda (ov)
7015 (when (member ov org-hide-block-overlays)
7016 (setq org-hide-block-overlays
7017 (delq ov org-hide-block-overlays)))
7018 (when (eq (overlay-get ov 'invisible)
7019 'org-hide-block)
7020 (delete-overlay ov))))
7021 (push ov org-hide-block-overlays)))
7022 (error "Not looking at a source block"))))
7024 ;; org-tab-after-check-for-cycling-hook
7025 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7026 ;; Remove overlays when changing major mode
7027 (add-hook 'org-mode-hook
7028 (lambda () (org-add-hook 'change-major-mode-hook
7029 'org-show-block-all 'append 'local)))
7031 ;;; Org-goto
7033 (defvar org-goto-window-configuration nil)
7034 (defvar org-goto-marker nil)
7035 (defvar org-goto-map)
7036 (defun org-goto-map ()
7037 "Set the keymap `org-goto'."
7038 (setq org-goto-map
7039 (let ((map (make-sparse-keymap)))
7040 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7041 mouse-drag-region universal-argument org-occur))
7042 cmd)
7043 (while (setq cmd (pop cmds))
7044 (substitute-key-definition cmd cmd map global-map)))
7045 (suppress-keymap map)
7046 (org-defkey map "\C-m" 'org-goto-ret)
7047 (org-defkey map [(return)] 'org-goto-ret)
7048 (org-defkey map [(left)] 'org-goto-left)
7049 (org-defkey map [(right)] 'org-goto-right)
7050 (org-defkey map [(control ?g)] 'org-goto-quit)
7051 (org-defkey map "\C-i" 'org-cycle)
7052 (org-defkey map [(tab)] 'org-cycle)
7053 (org-defkey map [(down)] 'outline-next-visible-heading)
7054 (org-defkey map [(up)] 'outline-previous-visible-heading)
7055 (if org-goto-auto-isearch
7056 (if (fboundp 'define-key-after)
7057 (define-key-after map [t] 'org-goto-local-auto-isearch)
7058 nil)
7059 (org-defkey map "q" 'org-goto-quit)
7060 (org-defkey map "n" 'outline-next-visible-heading)
7061 (org-defkey map "p" 'outline-previous-visible-heading)
7062 (org-defkey map "f" 'outline-forward-same-level)
7063 (org-defkey map "b" 'outline-backward-same-level)
7064 (org-defkey map "u" 'outline-up-heading))
7065 (org-defkey map "/" 'org-occur)
7066 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7067 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7068 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7069 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7070 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7071 map)))
7073 (defconst org-goto-help
7074 "Browse buffer copy, to find location or copy text.%s
7075 RET=jump to location C-g=quit and return to previous location
7076 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7078 (defvar org-goto-start-pos) ; dynamically scoped parameter
7080 ;; FIXME: Docstring does not mention both interfaces
7081 (defun org-goto (&optional alternative-interface)
7082 "Look up a different location in the current file, keeping current visibility.
7084 When you want look-up or go to a different location in a
7085 document, the fastest way is often to fold the entire buffer and
7086 then dive into the tree. This method has the disadvantage, that
7087 the previous location will be folded, which may not be what you
7088 want.
7090 This command works around this by showing a copy of the current
7091 buffer in an indirect buffer, in overview mode. You can dive
7092 into the tree in that copy, use org-occur and incremental search
7093 to find a location. When pressing RET or `Q', the command
7094 returns to the original buffer in which the visibility is still
7095 unchanged. After RET it will also jump to the location selected
7096 in the indirect buffer and expose the headline hierarchy above.
7098 With a prefix argument, use the alternative interface: e.g. if
7099 `org-goto-interface' is 'outline use 'outline-path-completion."
7100 (interactive "P")
7101 (org-goto-map)
7102 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7103 (org-refile-use-outline-path t)
7104 (org-refile-target-verify-function nil)
7105 (interface
7106 (if (not alternative-interface)
7107 org-goto-interface
7108 (if (eq org-goto-interface 'outline)
7109 'outline-path-completion
7110 'outline)))
7111 (org-goto-start-pos (point))
7112 (selected-point
7113 (if (eq interface 'outline)
7114 (car (org-get-location (current-buffer) org-goto-help))
7115 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7116 (org-refile-check-position pa)
7117 (nth 3 pa)))))
7118 (if selected-point
7119 (progn
7120 (org-mark-ring-push org-goto-start-pos)
7121 (goto-char selected-point)
7122 (if (or (outline-invisible-p) (org-invisible-p2))
7123 (org-show-context 'org-goto)))
7124 (message "Quit"))))
7126 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7127 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7128 (defvar org-goto-local-auto-isearch-map) ; defined below
7130 (defun org-get-location (buf help)
7131 "Let the user select a location in the Org-mode buffer BUF.
7132 This function uses a recursive edit. It returns the selected position
7133 or nil."
7134 (org-no-popups
7135 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7136 (isearch-hide-immediately nil)
7137 (isearch-search-fun-function
7138 (lambda () 'org-goto-local-search-headings))
7139 (org-goto-selected-point org-goto-exit-command))
7140 (save-excursion
7141 (save-window-excursion
7142 (delete-other-windows)
7143 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7144 (org-pop-to-buffer-same-window
7145 (condition-case nil
7146 (make-indirect-buffer (current-buffer) "*org-goto*")
7147 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7148 (with-output-to-temp-buffer "*Org Help*"
7149 (princ (format help (if org-goto-auto-isearch
7150 " Just type for auto-isearch."
7151 " n/p/f/b/u to navigate, q to quit."))))
7152 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7153 (setq buffer-read-only nil)
7154 (let ((org-startup-truncated t)
7155 (org-startup-folded nil)
7156 (org-startup-align-all-tables nil))
7157 (org-mode)
7158 (org-overview))
7159 (setq buffer-read-only t)
7160 (if (and (boundp 'org-goto-start-pos)
7161 (integer-or-marker-p org-goto-start-pos))
7162 (let ((org-show-hierarchy-above t)
7163 (org-show-siblings t)
7164 (org-show-following-heading t))
7165 (goto-char org-goto-start-pos)
7166 (and (outline-invisible-p) (org-show-context)))
7167 (goto-char (point-min)))
7168 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7169 (message "Select location and press RET")
7170 (use-local-map org-goto-map)
7171 (recursive-edit)))
7172 (kill-buffer "*org-goto*")
7173 (cons org-goto-selected-point org-goto-exit-command))))
7175 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7176 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7177 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7178 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7180 (defun org-goto-local-search-headings (string bound noerror)
7181 "Search and make sure that any matches are in headlines."
7182 (catch 'return
7183 (while (if isearch-forward
7184 (search-forward string bound noerror)
7185 (search-backward string bound noerror))
7186 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7187 (and (member :headline context)
7188 (not (member :tags context))))
7189 (throw 'return (point))))))
7191 (defun org-goto-local-auto-isearch ()
7192 "Start isearch."
7193 (interactive)
7194 (goto-char (point-min))
7195 (let ((keys (this-command-keys)))
7196 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7197 (isearch-mode t)
7198 (isearch-process-search-char (string-to-char keys)))))
7200 (defun org-goto-ret (&optional arg)
7201 "Finish `org-goto' by going to the new location."
7202 (interactive "P")
7203 (setq org-goto-selected-point (point)
7204 org-goto-exit-command 'return)
7205 (throw 'exit nil))
7207 (defun org-goto-left ()
7208 "Finish `org-goto' by going to the new location."
7209 (interactive)
7210 (if (org-at-heading-p)
7211 (progn
7212 (beginning-of-line 1)
7213 (setq org-goto-selected-point (point)
7214 org-goto-exit-command 'left)
7215 (throw 'exit nil))
7216 (error "Not on a heading")))
7218 (defun org-goto-right ()
7219 "Finish `org-goto' by going to the new location."
7220 (interactive)
7221 (if (org-at-heading-p)
7222 (progn
7223 (setq org-goto-selected-point (point)
7224 org-goto-exit-command 'right)
7225 (throw 'exit nil))
7226 (error "Not on a heading")))
7228 (defun org-goto-quit ()
7229 "Finish `org-goto' without cursor motion."
7230 (interactive)
7231 (setq org-goto-selected-point nil)
7232 (setq org-goto-exit-command 'quit)
7233 (throw 'exit nil))
7235 ;;; Indirect buffer display of subtrees
7237 (defvar org-indirect-dedicated-frame nil
7238 "This is the frame being used for indirect tree display.")
7239 (defvar org-last-indirect-buffer nil)
7241 (defun org-tree-to-indirect-buffer (&optional arg)
7242 "Create indirect buffer and narrow it to current subtree.
7243 With a numerical prefix ARG, go up to this level and then take that tree.
7244 If ARG is negative, go up that many levels.
7246 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7247 indirect buffer previously made with this command, to avoid proliferation of
7248 indirect buffers. However, when you call the command with a \
7249 \\[universal-argument] prefix, or
7250 when `org-indirect-buffer-display' is `new-frame', the last buffer
7251 is kept so that you can work with several indirect buffers at the same time.
7252 If `org-indirect-buffer-display' is `dedicated-frame', the \
7253 \\[universal-argument] prefix also
7254 requests that a new frame be made for the new buffer, so that the dedicated
7255 frame is not changed."
7256 (interactive "P")
7257 (let ((cbuf (current-buffer))
7258 (cwin (selected-window))
7259 (pos (point))
7260 beg end level heading ibuf)
7261 (save-excursion
7262 (org-back-to-heading t)
7263 (when (numberp arg)
7264 (setq level (org-outline-level))
7265 (if (< arg 0) (setq arg (+ level arg)))
7266 (while (> (setq level (org-outline-level)) arg)
7267 (org-up-heading-safe)))
7268 (setq beg (point)
7269 heading (org-get-heading))
7270 (org-end-of-subtree t t)
7271 (if (org-at-heading-p) (backward-char 1))
7272 (setq end (point)))
7273 (if (and (buffer-live-p org-last-indirect-buffer)
7274 (not (eq org-indirect-buffer-display 'new-frame))
7275 (not arg))
7276 (kill-buffer org-last-indirect-buffer))
7277 (setq ibuf (org-get-indirect-buffer cbuf)
7278 org-last-indirect-buffer ibuf)
7279 (cond
7280 ((or (eq org-indirect-buffer-display 'new-frame)
7281 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7282 (select-frame (make-frame))
7283 (delete-other-windows)
7284 (org-pop-to-buffer-same-window ibuf)
7285 (org-set-frame-title heading))
7286 ((eq org-indirect-buffer-display 'dedicated-frame)
7287 (raise-frame
7288 (select-frame (or (and org-indirect-dedicated-frame
7289 (frame-live-p org-indirect-dedicated-frame)
7290 org-indirect-dedicated-frame)
7291 (setq org-indirect-dedicated-frame (make-frame)))))
7292 (delete-other-windows)
7293 (org-pop-to-buffer-same-window ibuf)
7294 (org-set-frame-title (concat "Indirect: " heading)))
7295 ((eq org-indirect-buffer-display 'current-window)
7296 (org-pop-to-buffer-same-window ibuf))
7297 ((eq org-indirect-buffer-display 'other-window)
7298 (pop-to-buffer ibuf))
7299 (t (error "Invalid value")))
7300 (if (featurep 'xemacs)
7301 (save-excursion (org-mode) (turn-on-font-lock)))
7302 (narrow-to-region beg end)
7303 (show-all)
7304 (goto-char pos)
7305 (run-hook-with-args 'org-cycle-hook 'all)
7306 (and (window-live-p cwin) (select-window cwin))))
7308 (defun org-get-indirect-buffer (&optional buffer)
7309 (setq buffer (or buffer (current-buffer)))
7310 (let ((n 1) (base (buffer-name buffer)) bname)
7311 (while (buffer-live-p
7312 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7313 (setq n (1+ n)))
7314 (condition-case nil
7315 (make-indirect-buffer buffer bname 'clone)
7316 (error (make-indirect-buffer buffer bname)))))
7318 (defun org-set-frame-title (title)
7319 "Set the title of the current frame to the string TITLE."
7320 ;; FIXME: how to name a single frame in XEmacs???
7321 (unless (featurep 'xemacs)
7322 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7324 ;;;; Structure editing
7326 ;;; Inserting headlines
7328 (defun org-previous-line-empty-p ()
7329 (save-excursion
7330 (and (not (bobp))
7331 (or (beginning-of-line 0) t)
7332 (save-match-data
7333 (looking-at "[ \t]*$")))))
7335 (defun org-insert-heading (&optional force-heading invisible-ok)
7336 "Insert a new heading or item with same depth at point.
7337 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7338 If point is at the beginning of a headline, insert a sibling before the
7339 current headline. If point is not at the beginning, split the line,
7340 create the new headline with the text in the current line after point
7341 \(but see also the variable `org-M-RET-may-split-line').
7343 With a double prefix arg, force the heading to be inserted at the
7344 end of the parent subtree.
7346 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7347 This is important for non-interactive uses of the command."
7348 (interactive "P")
7349 (if (or (= (buffer-size) 0)
7350 (and (not (save-excursion
7351 (and (ignore-errors (org-back-to-heading invisible-ok))
7352 (org-at-heading-p))))
7353 (or force-heading (not (org-in-item-p)))))
7354 (progn
7355 (insert "\n* ")
7356 (run-hooks 'org-insert-heading-hook))
7357 (when (or force-heading (not (org-insert-item)))
7358 (let* ((empty-line-p nil)
7359 (level nil)
7360 (on-heading (org-at-heading-p))
7361 (head (save-excursion
7362 (condition-case nil
7363 (progn
7364 (org-back-to-heading invisible-ok)
7365 (when (and (not on-heading)
7366 (featurep 'org-inlinetask)
7367 (integerp org-inlinetask-min-level)
7368 (>= (length (match-string 0))
7369 org-inlinetask-min-level))
7370 ;; Find a heading level before the inline task
7371 (while (and (setq level (org-up-heading-safe))
7372 (>= level org-inlinetask-min-level)))
7373 (if (org-at-heading-p)
7374 (org-back-to-heading invisible-ok)
7375 (error "This should not happen")))
7376 (setq empty-line-p (org-previous-line-empty-p))
7377 (match-string 0))
7378 (error "*"))))
7379 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7380 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7381 pos hide-previous previous-pos)
7382 (cond
7383 ((and (org-at-heading-p) (bolp)
7384 (or (bobp)
7385 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7386 ;; insert before the current line
7387 (open-line (if blank 2 1)))
7388 ((and (bolp)
7389 (not org-insert-heading-respect-content)
7390 (or (bobp)
7391 (save-excursion
7392 (backward-char 1) (not (outline-invisible-p)))))
7393 ;; insert right here
7394 nil)
7396 ;; somewhere in the line
7397 (save-excursion
7398 (setq previous-pos (point-at-bol))
7399 (end-of-line)
7400 (setq hide-previous (outline-invisible-p)))
7401 (and org-insert-heading-respect-content (org-show-subtree))
7402 (let ((split
7403 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7404 (save-excursion
7405 (let ((p (point)))
7406 (goto-char (point-at-bol))
7407 (and (looking-at org-complex-heading-regexp)
7408 (match-beginning 4)
7409 (> p (match-beginning 4)))))))
7410 tags pos)
7411 (cond
7412 (org-insert-heading-respect-content
7413 (if (not (equal force-heading '(16)))
7414 (org-end-of-subtree nil t)
7415 (org-up-heading-safe)
7416 (org-end-of-subtree nil t))
7417 (when (featurep 'org-inlinetask)
7418 (while (and (not (eobp))
7419 (looking-at "\\(\\*+\\)[ \t]+")
7420 (>= (length (match-string 1))
7421 org-inlinetask-min-level))
7422 (org-end-of-subtree nil t)))
7423 (or (bolp) (newline))
7424 (or (org-previous-line-empty-p)
7425 (and blank (newline)))
7426 (open-line 1))
7427 ((org-at-heading-p)
7428 (when hide-previous
7429 (show-children)
7430 (org-show-entry))
7431 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7432 (setq tags (and (match-end 2) (match-string 2)))
7433 (and (match-end 1)
7434 (delete-region (match-beginning 1) (match-end 1)))
7435 (setq pos (point-at-bol))
7436 (or split (end-of-line 1))
7437 (delete-horizontal-space)
7438 (if (string-match "\\`\\*+\\'"
7439 (buffer-substring (point-at-bol) (point)))
7440 (insert " "))
7441 (newline (if blank 2 1))
7442 (when tags
7443 (save-excursion
7444 (goto-char pos)
7445 (end-of-line 1)
7446 (insert " " tags)
7447 (org-set-tags nil 'align))))
7449 (or split (end-of-line 1))
7450 (newline (if blank 2 1)))))))
7451 (insert head) (just-one-space)
7452 (setq pos (point))
7453 (end-of-line 1)
7454 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7455 (when (and org-insert-heading-respect-content hide-previous)
7456 (save-excursion
7457 (goto-char previous-pos)
7458 (hide-subtree)))
7459 (run-hooks 'org-insert-heading-hook)))))
7461 (defun org-get-heading (&optional no-tags no-todo)
7462 "Return the heading of the current entry, without the stars.
7463 When NO-TAGS is non-nil, don't include tags.
7464 When NO-TODO is non-nil, don't include TODO keywords."
7465 (save-excursion
7466 (org-back-to-heading t)
7467 (cond
7468 ((and no-tags no-todo)
7469 (looking-at org-complex-heading-regexp)
7470 (match-string 4))
7471 (no-tags
7472 (looking-at (concat org-outline-regexp
7473 "\\(.*?\\)"
7474 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7475 (match-string 1))
7476 (no-todo
7477 (looking-at org-todo-line-regexp)
7478 (match-string 3))
7479 (t (looking-at org-heading-regexp)
7480 (match-string 2)))))
7482 (defvar orgstruct-mode) ; defined below
7484 (defun org-heading-components ()
7485 "Return the components of the current heading.
7486 This is a list with the following elements:
7487 - the level as an integer
7488 - the reduced level, different if `org-odd-levels-only' is set.
7489 - the TODO keyword, or nil
7490 - the priority character, like ?A, or nil if no priority is given
7491 - the headline text itself, or the tags string if no headline text
7492 - the tags string, or nil."
7493 (save-excursion
7494 (org-back-to-heading t)
7495 (if (let (case-fold-search)
7496 (looking-at
7497 (if orgstruct-mode
7498 org-heading-regexp
7499 org-complex-heading-regexp)))
7500 (if orgstruct-mode
7501 (list (length (match-string 1))
7502 (org-reduced-level (length (match-string 1)))
7505 (match-string 2)
7506 nil)
7507 (list (length (match-string 1))
7508 (org-reduced-level (length (match-string 1)))
7509 (org-match-string-no-properties 2)
7510 (and (match-end 3) (aref (match-string 3) 2))
7511 (org-match-string-no-properties 4)
7512 (org-match-string-no-properties 5))))))
7514 (defun org-get-entry ()
7515 "Get the entry text, after heading, entire subtree."
7516 (save-excursion
7517 (org-back-to-heading t)
7518 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7520 (defun org-insert-heading-after-current ()
7521 "Insert a new heading with same level as current, after current subtree."
7522 (interactive)
7523 (org-back-to-heading)
7524 (org-insert-heading)
7525 (org-move-subtree-down)
7526 (end-of-line 1))
7528 (defun org-insert-heading-respect-content (invisible-ok)
7529 "Insert heading with `org-insert-heading-respect-content' set to t."
7530 (interactive "P")
7531 (let ((org-insert-heading-respect-content t))
7532 (org-insert-heading t invisible-ok)))
7534 (defun org-insert-todo-heading-respect-content (&optional force-state)
7535 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7536 (interactive "P")
7537 (let ((org-insert-heading-respect-content t))
7538 (org-insert-todo-heading force-state t)))
7540 (defun org-insert-todo-heading (arg &optional force-heading)
7541 "Insert a new heading with the same level and TODO state as current heading.
7542 If the heading has no TODO state, or if the state is DONE, use the first
7543 state (TODO by default). Also one prefix arg, force first state. With two
7544 prefix args, force inserting at the end of the parent subtree."
7545 (interactive "P")
7546 (when (or force-heading (not (org-insert-item 'checkbox)))
7547 (org-insert-heading (or (and (equal arg '(16)) '(16))
7548 force-heading))
7549 (save-excursion
7550 (org-back-to-heading)
7551 (outline-previous-heading)
7552 (looking-at org-todo-line-regexp))
7553 (let*
7554 ((new-mark-x
7555 (if (or arg
7556 (not (match-beginning 2))
7557 (member (match-string 2) org-done-keywords))
7558 (car org-todo-keywords-1)
7559 (match-string 2)))
7560 (new-mark
7562 (run-hook-with-args-until-success
7563 'org-todo-get-default-hook new-mark-x nil)
7564 new-mark-x)))
7565 (beginning-of-line 1)
7566 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7567 (if org-treat-insert-todo-heading-as-state-change
7568 (org-todo new-mark)
7569 (insert new-mark " "))))
7570 (when org-provide-todo-statistics
7571 (org-update-parent-todo-statistics))))
7573 (defun org-insert-subheading (arg)
7574 "Insert a new subheading and demote it.
7575 Works for outline headings and for plain lists alike."
7576 (interactive "P")
7577 (org-insert-heading arg)
7578 (cond
7579 ((org-at-heading-p) (org-do-demote))
7580 ((org-at-item-p) (org-indent-item))))
7582 (defun org-insert-todo-subheading (arg)
7583 "Insert a new subheading with TODO keyword or checkbox and demote it.
7584 Works for outline headings and for plain lists alike."
7585 (interactive "P")
7586 (org-insert-todo-heading arg)
7587 (cond
7588 ((org-at-heading-p) (org-do-demote))
7589 ((org-at-item-p) (org-indent-item))))
7591 ;;; Promotion and Demotion
7593 (defvar org-after-demote-entry-hook nil
7594 "Hook run after an entry has been demoted.
7595 The cursor will be at the beginning of the entry.
7596 When a subtree is being demoted, the hook will be called for each node.")
7598 (defvar org-after-promote-entry-hook nil
7599 "Hook run after an entry has been promoted.
7600 The cursor will be at the beginning of the entry.
7601 When a subtree is being promoted, the hook will be called for each node.")
7603 (defun org-promote-subtree ()
7604 "Promote the entire subtree.
7605 See also `org-promote'."
7606 (interactive)
7607 (save-excursion
7608 (org-with-limited-levels (org-map-tree 'org-promote)))
7609 (org-fix-position-after-promote))
7611 (defun org-demote-subtree ()
7612 "Demote the entire subtree. See `org-demote'.
7613 See also `org-promote'."
7614 (interactive)
7615 (save-excursion
7616 (org-with-limited-levels (org-map-tree 'org-demote)))
7617 (org-fix-position-after-promote))
7620 (defun org-do-promote ()
7621 "Promote the current heading higher up the tree.
7622 If the region is active in `transient-mark-mode', promote all headings
7623 in the region."
7624 (interactive)
7625 (save-excursion
7626 (if (org-region-active-p)
7627 (org-map-region 'org-promote (region-beginning) (region-end))
7628 (org-promote)))
7629 (org-fix-position-after-promote))
7631 (defun org-do-demote ()
7632 "Demote the current heading lower down the tree.
7633 If the region is active in `transient-mark-mode', demote all headings
7634 in the region."
7635 (interactive)
7636 (save-excursion
7637 (if (org-region-active-p)
7638 (org-map-region 'org-demote (region-beginning) (region-end))
7639 (org-demote)))
7640 (org-fix-position-after-promote))
7642 (defun org-fix-position-after-promote ()
7643 "Make sure that after pro/demotion cursor position is right."
7644 (let ((pos (point)))
7645 (when (save-excursion
7646 (beginning-of-line 1)
7647 (looking-at org-todo-line-regexp)
7648 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7649 (cond ((eobp) (insert " "))
7650 ((eolp) (insert " "))
7651 ((equal (char-after) ?\ ) (forward-char 1))))))
7653 (defun org-current-level ()
7654 "Return the level of the current entry, or nil if before the first headline.
7655 The level is the number of stars at the beginning of the headline."
7656 (save-excursion
7657 (org-with-limited-levels
7658 (if (ignore-errors (org-back-to-heading t))
7659 (funcall outline-level)))))
7661 (defun org-get-previous-line-level ()
7662 "Return the outline depth of the last headline before the current line.
7663 Returns 0 for the first headline in the buffer, and nil if before the
7664 first headline."
7665 (let ((current-level (org-current-level))
7666 (prev-level (when (> (line-number-at-pos) 1)
7667 (save-excursion
7668 (beginning-of-line 0)
7669 (org-current-level)))))
7670 (cond ((null current-level) nil) ; Before first headline
7671 ((null prev-level) 0) ; At first headline
7672 (prev-level))))
7674 (defun org-reduced-level (l)
7675 "Compute the effective level of a heading.
7676 This takes into account the setting of `org-odd-levels-only'."
7677 (cond
7678 ((zerop l) 0)
7679 (org-odd-levels-only (1+ (floor (/ l 2))))
7680 (t l)))
7682 (defun org-level-increment ()
7683 "Return the number of stars that will be added or removed at a
7684 time to headlines when structure editing, based on the value of
7685 `org-odd-levels-only'."
7686 (if org-odd-levels-only 2 1))
7688 (defun org-get-valid-level (level &optional change)
7689 "Rectify a level change under the influence of `org-odd-levels-only'
7690 LEVEL is a current level, CHANGE is by how much the level should be
7691 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7692 even level numbers will become the next higher odd number."
7693 (if org-odd-levels-only
7694 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7695 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7696 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7697 (max 1 (+ level (or change 0)))))
7699 (if (boundp 'define-obsolete-function-alias)
7700 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7701 (define-obsolete-function-alias 'org-get-legal-level
7702 'org-get-valid-level)
7703 (define-obsolete-function-alias 'org-get-legal-level
7704 'org-get-valid-level "23.1")))
7706 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7707 ;; ̀org-with-limited-levels'
7708 (defun org-promote ()
7709 "Promote the current heading higher up the tree.
7710 If the region is active in `transient-mark-mode', promote all headings
7711 in the region."
7712 (org-back-to-heading t)
7713 (let* ((level (save-match-data (funcall outline-level)))
7714 (after-change-functions (remove 'flyspell-after-change-function
7715 after-change-functions))
7716 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7717 (diff (abs (- level (length up-head) -1))))
7718 (cond ((and (= level 1) org-called-with-limited-levels
7719 org-allow-promoting-top-level-subtree)
7720 (replace-match "# " nil t))
7721 ((= level 1)
7722 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7723 (t (replace-match up-head nil t)))
7724 ;; Fixup tag positioning
7725 (unless (= level 1)
7726 (and org-auto-align-tags (org-set-tags nil t))
7727 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7728 (run-hooks 'org-after-promote-entry-hook)))
7730 (defun org-demote ()
7731 "Demote the current heading lower down the tree.
7732 If the region is active in `transient-mark-mode', demote all headings
7733 in the region."
7734 (org-back-to-heading t)
7735 (let* ((level (save-match-data (funcall outline-level)))
7736 (after-change-functions (remove 'flyspell-after-change-function
7737 after-change-functions))
7738 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7739 (diff (abs (- level (length down-head) -1))))
7740 (replace-match down-head nil t)
7741 ;; Fixup tag positioning
7742 (and org-auto-align-tags (org-set-tags nil t))
7743 (if org-adapt-indentation (org-fixup-indentation diff))
7744 (run-hooks 'org-after-demote-entry-hook)))
7746 (defun org-cycle-level ()
7747 "Cycle the level of an empty headline through possible states.
7748 This goes first to child, then to parent, level, then up the hierarchy.
7749 After top level, it switches back to sibling level."
7750 (interactive)
7751 (let ((org-adapt-indentation nil))
7752 (when (org-point-at-end-of-empty-headline)
7753 (setq this-command 'org-cycle-level) ; Only needed for caching
7754 (let ((cur-level (org-current-level))
7755 (prev-level (org-get-previous-line-level)))
7756 (cond
7757 ;; If first headline in file, promote to top-level.
7758 ((= prev-level 0)
7759 (loop repeat (/ (- cur-level 1) (org-level-increment))
7760 do (org-do-promote)))
7761 ;; If same level as prev, demote one.
7762 ((= prev-level cur-level)
7763 (org-do-demote))
7764 ;; If parent is top-level, promote to top level if not already.
7765 ((= prev-level 1)
7766 (loop repeat (/ (- cur-level 1) (org-level-increment))
7767 do (org-do-promote)))
7768 ;; If top-level, return to prev-level.
7769 ((= cur-level 1)
7770 (loop repeat (/ (- prev-level 1) (org-level-increment))
7771 do (org-do-demote)))
7772 ;; If less than prev-level, promote one.
7773 ((< cur-level prev-level)
7774 (org-do-promote))
7775 ;; If deeper than prev-level, promote until higher than
7776 ;; prev-level.
7777 ((> cur-level prev-level)
7778 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7779 do (org-do-promote))))
7780 t))))
7782 (defun org-map-tree (fun)
7783 "Call FUN for every heading underneath the current one."
7784 (org-back-to-heading)
7785 (let ((level (funcall outline-level)))
7786 (save-excursion
7787 (funcall fun)
7788 (while (and (progn
7789 (outline-next-heading)
7790 (> (funcall outline-level) level))
7791 (not (eobp)))
7792 (funcall fun)))))
7794 (defun org-map-region (fun beg end)
7795 "Call FUN for every heading between BEG and END."
7796 (let ((org-ignore-region t))
7797 (save-excursion
7798 (setq end (copy-marker end))
7799 (goto-char beg)
7800 (if (and (re-search-forward org-outline-regexp-bol nil t)
7801 (< (point) end))
7802 (funcall fun))
7803 (while (and (progn
7804 (outline-next-heading)
7805 (< (point) end))
7806 (not (eobp)))
7807 (funcall fun)))))
7809 (defvar org-property-end-re) ; silence byte-compiler
7810 (defun org-fixup-indentation (diff)
7811 "Change the indentation in the current entry by DIFF.
7812 However, if any line in the current entry has no indentation, or if it
7813 would end up with no indentation after the change, nothing at all is done."
7814 (save-excursion
7815 (let ((end (save-excursion (outline-next-heading)
7816 (point-marker)))
7817 (prohibit (if (> diff 0)
7818 "^\\S-"
7819 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7820 col)
7821 (unless (save-excursion (end-of-line 1)
7822 (re-search-forward prohibit end t))
7823 (while (and (< (point) end)
7824 (re-search-forward "^[ \t]+" end t))
7825 (goto-char (match-end 0))
7826 (setq col (current-column))
7827 (if (< diff 0) (replace-match ""))
7828 (org-indent-to-column (+ diff col))))
7829 (move-marker end nil))))
7831 (defun org-convert-to-odd-levels ()
7832 "Convert an org-mode file with all levels allowed to one with odd levels.
7833 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7834 level 5 etc."
7835 (interactive)
7836 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7837 (let ((outline-level 'org-outline-level)
7838 (org-odd-levels-only nil) n)
7839 (save-excursion
7840 (goto-char (point-min))
7841 (while (re-search-forward "^\\*\\*+ " nil t)
7842 (setq n (- (length (match-string 0)) 2))
7843 (while (>= (setq n (1- n)) 0)
7844 (org-demote))
7845 (end-of-line 1))))))
7847 (defun org-convert-to-oddeven-levels ()
7848 "Convert an org-mode file with only odd levels to one with odd/even levels.
7849 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7850 file contains a section with an even level, conversion would
7851 destroy the structure of the file. An error is signaled in this
7852 case."
7853 (interactive)
7854 (goto-char (point-min))
7855 ;; First check if there are no even levels
7856 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7857 (org-show-context t)
7858 (error "Not all levels are odd in this file. Conversion not possible"))
7859 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7860 (let ((outline-regexp org-outline-regexp)
7861 (outline-level 'org-outline-level)
7862 (org-odd-levels-only nil) n)
7863 (save-excursion
7864 (goto-char (point-min))
7865 (while (re-search-forward "^\\*\\*+ " nil t)
7866 (setq n (/ (1- (length (match-string 0))) 2))
7867 (while (>= (setq n (1- n)) 0)
7868 (org-promote))
7869 (end-of-line 1))))))
7871 (defun org-tr-level (n)
7872 "Make N odd if required."
7873 (if org-odd-levels-only (1+ (/ n 2)) n))
7875 ;;; Vertical tree motion, cutting and pasting of subtrees
7877 (defun org-move-subtree-up (&optional arg)
7878 "Move the current subtree up past ARG headlines of the same level."
7879 (interactive "p")
7880 (org-move-subtree-down (- (prefix-numeric-value arg))))
7882 (defun org-move-subtree-down (&optional arg)
7883 "Move the current subtree down past ARG headlines of the same level."
7884 (interactive "p")
7885 (setq arg (prefix-numeric-value arg))
7886 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7887 'org-get-last-sibling))
7888 (ins-point (make-marker))
7889 (cnt (abs arg))
7890 (col (current-column))
7891 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7892 ;; Select the tree
7893 (org-back-to-heading)
7894 (setq beg0 (point))
7895 (save-excursion
7896 (setq ne-beg (org-back-over-empty-lines))
7897 (setq beg (point)))
7898 (save-match-data
7899 (save-excursion (outline-end-of-heading)
7900 (setq folded (outline-invisible-p)))
7901 (outline-end-of-subtree))
7902 (outline-next-heading)
7903 (setq ne-end (org-back-over-empty-lines))
7904 (setq end (point))
7905 (goto-char beg0)
7906 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7907 ;; include less whitespace
7908 (save-excursion
7909 (goto-char beg)
7910 (forward-line (- ne-beg ne-end))
7911 (setq beg (point))))
7912 ;; Find insertion point, with error handling
7913 (while (> cnt 0)
7914 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7915 (progn (goto-char beg0)
7916 (error "Cannot move past superior level or buffer limit")))
7917 (setq cnt (1- cnt)))
7918 (if (> arg 0)
7919 ;; Moving forward - still need to move over subtree
7920 (progn (org-end-of-subtree t t)
7921 (save-excursion
7922 (org-back-over-empty-lines)
7923 (or (bolp) (newline)))))
7924 (setq ne-ins (org-back-over-empty-lines))
7925 (move-marker ins-point (point))
7926 (setq txt (buffer-substring beg end))
7927 (org-save-markers-in-region beg end)
7928 (delete-region beg end)
7929 (org-remove-empty-overlays-at beg)
7930 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7931 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7932 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7933 (let ((bbb (point)))
7934 (insert-before-markers txt)
7935 (org-reinstall-markers-in-region bbb)
7936 (move-marker ins-point bbb))
7937 (or (bolp) (insert "\n"))
7938 (setq ins-end (point))
7939 (goto-char ins-point)
7940 (org-skip-whitespace)
7941 (when (and (< arg 0)
7942 (org-first-sibling-p)
7943 (> ne-ins ne-beg))
7944 ;; Move whitespace back to beginning
7945 (save-excursion
7946 (goto-char ins-end)
7947 (let ((kill-whole-line t))
7948 (kill-line (- ne-ins ne-beg)) (point)))
7949 (insert (make-string (- ne-ins ne-beg) ?\n)))
7950 (move-marker ins-point nil)
7951 (if folded
7952 (hide-subtree)
7953 (org-show-entry)
7954 (show-children)
7955 (org-cycle-hide-drawers 'children))
7956 (org-clean-visibility-after-subtree-move)
7957 ;; move back to the initial column we were at
7958 (move-to-column col)))
7960 (defvar org-subtree-clip ""
7961 "Clipboard for cut and paste of subtrees.
7962 This is actually only a copy of the kill, because we use the normal kill
7963 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7965 (defvar org-subtree-clip-folded nil
7966 "Was the last copied subtree folded?
7967 This is used to fold the tree back after pasting.")
7969 (defun org-cut-subtree (&optional n)
7970 "Cut the current subtree into the clipboard.
7971 With prefix arg N, cut this many sequential subtrees.
7972 This is a short-hand for marking the subtree and then cutting it."
7973 (interactive "p")
7974 (org-copy-subtree n 'cut))
7976 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7977 "Cut the current subtree into the clipboard.
7978 With prefix arg N, cut this many sequential subtrees.
7979 This is a short-hand for marking the subtree and then copying it.
7980 If CUT is non-nil, actually cut the subtree.
7981 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7982 of some markers in the region, even if CUT is non-nil. This is
7983 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7984 (interactive "p")
7985 (let (beg end folded (beg0 (point)))
7986 (if (org-called-interactively-p 'any)
7987 (org-back-to-heading nil) ; take what looks like a subtree
7988 (org-back-to-heading t)) ; take what is really there
7989 (setq beg (point))
7990 (skip-chars-forward " \t\r\n")
7991 (save-match-data
7992 (if nosubtrees
7993 (outline-next-heading)
7994 (save-excursion (outline-end-of-heading)
7995 (setq folded (outline-invisible-p)))
7996 (condition-case nil
7997 (org-forward-heading-same-level (1- n) t)
7998 (error nil))
7999 (org-end-of-subtree t t)))
8000 (setq end (point))
8001 (goto-char beg0)
8002 (when (> end beg)
8003 (setq org-subtree-clip-folded folded)
8004 (when (or cut force-store-markers)
8005 (org-save-markers-in-region beg end))
8006 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8007 (setq org-subtree-clip (current-kill 0))
8008 (message "%s: Subtree(s) with %d characters"
8009 (if cut "Cut" "Copied")
8010 (length org-subtree-clip)))))
8012 (defun org-paste-subtree (&optional level tree for-yank)
8013 "Paste the clipboard as a subtree, with modification of headline level.
8014 The entire subtree is promoted or demoted in order to match a new headline
8015 level.
8017 If the cursor is at the beginning of a headline, the same level as
8018 that headline is used to paste the tree.
8020 If not, the new level is derived from the *visible* headings
8021 before and after the insertion point, and taken to be the inferior headline
8022 level of the two. So if the previous visible heading is level 3 and the
8023 next is level 4 (or vice versa), level 4 will be used for insertion.
8024 This makes sure that the subtree remains an independent subtree and does
8025 not swallow low level entries.
8027 You can also force a different level, either by using a numeric prefix
8028 argument, or by inserting the heading marker by hand. For example, if the
8029 cursor is after \"*****\", then the tree will be shifted to level 5.
8031 If optional TREE is given, use this text instead of the kill ring.
8033 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8034 move back over whitespace before inserting, and move point to the end of
8035 the inserted text when done."
8036 (interactive "P")
8037 (setq tree (or tree (and kill-ring (current-kill 0))))
8038 (unless (org-kill-is-subtree-p tree)
8039 (error "%s"
8040 (substitute-command-keys
8041 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8042 (org-with-limited-levels
8043 (let* ((visp (not (outline-invisible-p)))
8044 (txt tree)
8045 (^re_ "\\(\\*+\\)[ \t]*")
8046 (old-level (if (string-match org-outline-regexp-bol txt)
8047 (- (match-end 0) (match-beginning 0) 1)
8048 -1))
8049 (force-level (cond (level (prefix-numeric-value level))
8050 ((and (looking-at "[ \t]*$")
8051 (string-match
8052 "^\\*+$" (buffer-substring
8053 (point-at-bol) (point))))
8054 (- (match-end 1) (match-beginning 1)))
8055 ((and (bolp)
8056 (looking-at org-outline-regexp))
8057 (- (match-end 0) (point) 1))))
8058 (previous-level (save-excursion
8059 (condition-case nil
8060 (progn
8061 (outline-previous-visible-heading 1)
8062 (if (looking-at ^re_)
8063 (- (match-end 0) (match-beginning 0) 1)
8065 (error 1))))
8066 (next-level (save-excursion
8067 (condition-case nil
8068 (progn
8069 (or (looking-at org-outline-regexp)
8070 (outline-next-visible-heading 1))
8071 (if (looking-at ^re_)
8072 (- (match-end 0) (match-beginning 0) 1)
8074 (error 1))))
8075 (new-level (or force-level (max previous-level next-level)))
8076 (shift (if (or (= old-level -1)
8077 (= new-level -1)
8078 (= old-level new-level))
8080 (- new-level old-level)))
8081 (delta (if (> shift 0) -1 1))
8082 (func (if (> shift 0) 'org-demote 'org-promote))
8083 (org-odd-levels-only nil)
8084 beg end newend)
8085 ;; Remove the forced level indicator
8086 (if force-level
8087 (delete-region (point-at-bol) (point)))
8088 ;; Paste
8089 (beginning-of-line (if (bolp) 1 2))
8090 (setq beg (point))
8091 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8092 (insert-before-markers txt)
8093 (unless (string-match "\n\\'" txt) (insert "\n"))
8094 (setq newend (point))
8095 (org-reinstall-markers-in-region beg)
8096 (setq end (point))
8097 (goto-char beg)
8098 (skip-chars-forward " \t\n\r")
8099 (setq beg (point))
8100 (if (and (outline-invisible-p) visp)
8101 (save-excursion (outline-show-heading)))
8102 ;; Shift if necessary
8103 (unless (= shift 0)
8104 (save-restriction
8105 (narrow-to-region beg end)
8106 (while (not (= shift 0))
8107 (org-map-region func (point-min) (point-max))
8108 (setq shift (+ delta shift)))
8109 (goto-char (point-min))
8110 (setq newend (point-max))))
8111 (when (or (org-called-interactively-p 'interactive) for-yank)
8112 (message "Clipboard pasted as level %d subtree" new-level))
8113 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8114 kill-ring
8115 (eq org-subtree-clip (current-kill 0))
8116 org-subtree-clip-folded)
8117 ;; The tree was folded before it was killed/copied
8118 (hide-subtree))
8119 (and for-yank (goto-char newend)))))
8121 (defun org-kill-is-subtree-p (&optional txt)
8122 "Check if the current kill is an outline subtree, or a set of trees.
8123 Returns nil if kill does not start with a headline, or if the first
8124 headline level is not the largest headline level in the tree.
8125 So this will actually accept several entries of equal levels as well,
8126 which is OK for `org-paste-subtree'.
8127 If optional TXT is given, check this string instead of the current kill."
8128 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8129 (re (org-get-limited-outline-regexp))
8130 (^re (concat "^" re))
8131 (start-level (and kill
8132 (string-match
8133 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8134 kill)
8135 (- (match-end 2) (match-beginning 2) 1)))
8136 (start (1+ (or (match-beginning 2) -1))))
8137 (if (not start-level)
8138 (progn
8139 nil) ;; does not even start with a heading
8140 (catch 'exit
8141 (while (setq start (string-match ^re kill (1+ start)))
8142 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8143 (throw 'exit nil)))
8144 t))))
8146 (defvar org-markers-to-move nil
8147 "Markers that should be moved with a cut-and-paste operation.
8148 Those markers are stored together with their positions relative to
8149 the start of the region.")
8151 (defun org-save-markers-in-region (beg end)
8152 "Check markers in region.
8153 If these markers are between BEG and END, record their position relative
8154 to BEG, so that after moving the block of text, we can put the markers back
8155 into place.
8156 This function gets called just before an entry or tree gets cut from the
8157 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8158 called immediately, to move the markers with the entries."
8159 (setq org-markers-to-move nil)
8160 (when (featurep 'org-clock)
8161 (org-clock-save-markers-for-cut-and-paste beg end))
8162 (when (featurep 'org-agenda)
8163 (org-agenda-save-markers-for-cut-and-paste beg end)))
8165 (defun org-check-and-save-marker (marker beg end)
8166 "Check if MARKER is between BEG and END.
8167 If yes, remember the marker and the distance to BEG."
8168 (when (and (marker-buffer marker)
8169 (equal (marker-buffer marker) (current-buffer)))
8170 (if (and (>= marker beg) (< marker end))
8171 (push (cons marker (- marker beg)) org-markers-to-move))))
8173 (defun org-reinstall-markers-in-region (beg)
8174 "Move all remembered markers to their position relative to BEG."
8175 (mapc (lambda (x)
8176 (move-marker (car x) (+ beg (cdr x))))
8177 org-markers-to-move)
8178 (setq org-markers-to-move nil))
8180 (defun org-narrow-to-subtree ()
8181 "Narrow buffer to the current subtree."
8182 (interactive)
8183 (save-excursion
8184 (save-match-data
8185 (org-with-limited-levels
8186 (narrow-to-region
8187 (progn (org-back-to-heading t) (point))
8188 (progn (org-end-of-subtree t t)
8189 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8190 (point)))))))
8192 (defun org-narrow-to-block ()
8193 "Narrow buffer to the current block."
8194 (interactive)
8195 (let* ((case-fold-search t)
8196 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8197 "^[ \t]*#\\+end_.*")))
8198 (if blockp
8199 (narrow-to-region (car blockp) (cdr blockp))
8200 (error "Not in a block"))))
8202 (eval-when-compile
8203 (defvar org-property-drawer-re))
8205 (defvar org-property-start-re) ;; defined below
8206 (defun org-clone-subtree-with-time-shift (n &optional shift)
8207 "Clone the task (subtree) at point N times.
8208 The clones will be inserted as siblings.
8210 In interactive use, the user will be prompted for the number of
8211 clones to be produced, and for a time SHIFT, which may be a
8212 repeater as used in time stamps, for example `+3d'.
8214 When a valid repeater is given and the entry contains any time
8215 stamps, the clones will become a sequence in time, with time
8216 stamps in the subtree shifted for each clone produced. If SHIFT
8217 is nil or the empty string, time stamps will be left alone. The
8218 ID property of the original subtree is removed.
8220 If the original subtree did contain time stamps with a repeater,
8221 the following will happen:
8222 - the repeater will be removed in each clone
8223 - an additional clone will be produced, with the current, unshifted
8224 date(s) in the entry.
8225 - the original entry will be placed *after* all the clones, with
8226 repeater intact.
8227 - the start days in the repeater in the original entry will be shifted
8228 to past the last clone.
8229 In this way you can spell out a number of instances of a repeating task,
8230 and still retain the repeater to cover future instances of the task."
8231 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8232 (let (beg end template task idprop
8233 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8234 (drawer-re org-drawer-regexp))
8235 (if (not (and (integerp n) (> n 0)))
8236 (error "Invalid number of replications %s" n))
8237 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8238 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8239 shift)))
8240 (error "Invalid shift specification %s" shift))
8241 (when doshift
8242 (setq shift-n (string-to-number (match-string 1 shift))
8243 shift-what (cdr (assoc (match-string 2 shift)
8244 '(("d" . day) ("w" . week)
8245 ("m" . month) ("y" . year))))))
8246 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8247 (setq nmin 1 nmax n)
8248 (org-back-to-heading t)
8249 (setq beg (point))
8250 (setq idprop (org-entry-get nil "ID"))
8251 (org-end-of-subtree t t)
8252 (or (bolp) (insert "\n"))
8253 (setq end (point))
8254 (setq template (buffer-substring beg end))
8255 (when (and doshift
8256 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8257 (delete-region beg end)
8258 (setq end beg)
8259 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8260 (goto-char end)
8261 (loop for n from nmin to nmax do
8262 ;; prepare clone
8263 (with-temp-buffer
8264 (insert template)
8265 (org-mode)
8266 (goto-char (point-min))
8267 (org-show-subtree)
8268 (and idprop (if org-clone-delete-id
8269 (org-entry-delete nil "ID")
8270 (org-id-get-create t)))
8271 (unless (= n 0)
8272 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8273 (kill-whole-line))
8274 (goto-char (point-min))
8275 (while (re-search-forward drawer-re nil t)
8276 (mapc (lambda (d)
8277 (org-remove-empty-drawer-at d (point))) org-drawers)))
8278 (goto-char (point-min))
8279 (when doshift
8280 (while (re-search-forward org-ts-regexp-both nil t)
8281 (org-timestamp-change (* n shift-n) shift-what))
8282 (unless (= n n-no-remove)
8283 (goto-char (point-min))
8284 (while (re-search-forward org-ts-regexp nil t)
8285 (save-excursion
8286 (goto-char (match-beginning 0))
8287 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8288 (delete-region (match-beginning 1) (match-end 1)))))))
8289 (setq task (buffer-string)))
8290 (insert task))
8291 (goto-char beg)))
8293 ;;; Outline Sorting
8295 (defun org-sort (with-case)
8296 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8297 Optional argument WITH-CASE means sort case-sensitively."
8298 (interactive "P")
8299 (cond
8300 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8301 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8303 (org-call-with-arg 'org-sort-entries with-case))))
8305 (defun org-sort-remove-invisible (s)
8306 (remove-text-properties 0 (length s) org-rm-props s)
8307 (while (string-match org-bracket-link-regexp s)
8308 (setq s (replace-match (if (match-end 2)
8309 (match-string 3 s)
8310 (match-string 1 s)) t t s)))
8313 (defvar org-priority-regexp) ; defined later in the file
8315 (defvar org-after-sorting-entries-or-items-hook nil
8316 "Hook that is run after a bunch of entries or items have been sorted.
8317 When children are sorted, the cursor is in the parent line when this
8318 hook gets called. When a region or a plain list is sorted, the cursor
8319 will be in the first entry of the sorted region/list.")
8321 (defun org-sort-entries
8322 (&optional with-case sorting-type getkey-func compare-func property)
8323 "Sort entries on a certain level of an outline tree.
8324 If there is an active region, the entries in the region are sorted.
8325 Else, if the cursor is before the first entry, sort the top-level items.
8326 Else, the children of the entry at point are sorted.
8328 Sorting can be alphabetically, numerically, by date/time as given by
8329 a time stamp, by a property or by priority.
8331 The command prompts for the sorting type unless it has been given to the
8332 function through the SORTING-TYPE argument, which needs to be a character,
8333 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8334 precise meaning of each character:
8336 n Numerically, by converting the beginning of the entry/item to a number.
8337 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8338 o By order of TODO keywords.
8339 t By date/time, either the first active time stamp in the entry, or, if
8340 none exist, by the first inactive one.
8341 s By the scheduled date/time.
8342 d By deadline date/time.
8343 c By creation time, which is assumed to be the first inactive time stamp
8344 at the beginning of a line.
8345 p By priority according to the cookie.
8346 r By the value of a property.
8348 Capital letters will reverse the sort order.
8350 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8351 called with point at the beginning of the record. It must return either
8352 a string or a number that should serve as the sorting key for that record.
8354 Comparing entries ignores case by default. However, with an optional argument
8355 WITH-CASE, the sorting considers case as well."
8356 (interactive "P")
8357 (let ((case-func (if with-case 'identity 'downcase))
8358 (cmstr
8359 ;; The clock marker is lost when using `sort-subr', let's
8360 ;; store the clocking string.
8361 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8362 (save-excursion
8363 (goto-char org-clock-marker)
8364 (looking-back "^.*") (match-string-no-properties 0))))
8365 start beg end stars re re2
8366 txt what tmp)
8367 ;; Find beginning and end of region to sort
8368 (cond
8369 ((org-region-active-p)
8370 ;; we will sort the region
8371 (setq end (region-end)
8372 what "region")
8373 (goto-char (region-beginning))
8374 (if (not (org-at-heading-p)) (outline-next-heading))
8375 (setq start (point)))
8376 ((or (org-at-heading-p)
8377 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8378 ;; we will sort the children of the current headline
8379 (org-back-to-heading)
8380 (setq start (point)
8381 end (progn (org-end-of-subtree t t)
8382 (or (bolp) (insert "\n"))
8383 (org-back-over-empty-lines)
8384 (point))
8385 what "children")
8386 (goto-char start)
8387 (show-subtree)
8388 (outline-next-heading))
8390 ;; we will sort the top-level entries in this file
8391 (goto-char (point-min))
8392 (or (org-at-heading-p) (outline-next-heading))
8393 (setq start (point))
8394 (goto-char (point-max))
8395 (beginning-of-line 1)
8396 (when (looking-at ".*?\\S-")
8397 ;; File ends in a non-white line
8398 (end-of-line 1)
8399 (insert "\n"))
8400 (setq end (point-max))
8401 (setq what "top-level")
8402 (goto-char start)
8403 (show-all)))
8405 (setq beg (point))
8406 (if (>= beg end) (error "Nothing to sort"))
8408 (looking-at "\\(\\*+\\)")
8409 (setq stars (match-string 1)
8410 re (concat "^" (regexp-quote stars) " +")
8411 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8412 txt (buffer-substring beg end))
8413 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8414 (if (and (not (equal stars "*")) (string-match re2 txt))
8415 (error "Region to sort contains a level above the first entry"))
8417 (unless sorting-type
8418 (message
8419 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8420 [t]ime [s]cheduled [d]eadline [c]reated
8421 A/N/P/R/O/F/T/S/D/C means reversed:"
8422 what)
8423 (setq sorting-type (read-char-exclusive))
8425 (unless getkey-func
8426 (and (= (downcase sorting-type) ?f)
8427 (setq getkey-func
8428 (org-icompleting-read "Sort using function: "
8429 obarray 'fboundp t nil nil))
8430 (setq getkey-func (intern getkey-func))))
8432 (and (= (downcase sorting-type) ?r)
8433 (not property)
8434 (setq property
8435 (org-icompleting-read "Property: "
8436 (mapcar 'list (org-buffer-property-keys t))
8437 nil t))))
8439 (message "Sorting entries...")
8441 (save-restriction
8442 (narrow-to-region start end)
8443 (let ((dcst (downcase sorting-type))
8444 (case-fold-search nil)
8445 (now (current-time)))
8446 (sort-subr
8447 (/= dcst sorting-type)
8448 ;; This function moves to the beginning character of the "record" to
8449 ;; be sorted.
8450 (lambda nil
8451 (if (re-search-forward re nil t)
8452 (goto-char (match-beginning 0))
8453 (goto-char (point-max))))
8454 ;; This function moves to the last character of the "record" being
8455 ;; sorted.
8456 (lambda nil
8457 (save-match-data
8458 (condition-case nil
8459 (outline-forward-same-level 1)
8460 (error
8461 (goto-char (point-max))))))
8462 ;; This function returns the value that gets sorted against.
8463 (lambda nil
8464 (cond
8465 ((= dcst ?n)
8466 (if (looking-at org-complex-heading-regexp)
8467 (string-to-number (match-string 4))
8468 nil))
8469 ((= dcst ?a)
8470 (if (looking-at org-complex-heading-regexp)
8471 (funcall case-func (match-string 4))
8472 nil))
8473 ((= dcst ?t)
8474 (let ((end (save-excursion (outline-next-heading) (point))))
8475 (if (or (re-search-forward org-ts-regexp end t)
8476 (re-search-forward org-ts-regexp-both end t))
8477 (org-time-string-to-seconds (match-string 0))
8478 (org-float-time now))))
8479 ((= dcst ?c)
8480 (let ((end (save-excursion (outline-next-heading) (point))))
8481 (if (re-search-forward
8482 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8483 end t)
8484 (org-time-string-to-seconds (match-string 0))
8485 (org-float-time now))))
8486 ((= dcst ?s)
8487 (let ((end (save-excursion (outline-next-heading) (point))))
8488 (if (re-search-forward org-scheduled-time-regexp end t)
8489 (org-time-string-to-seconds (match-string 1))
8490 (org-float-time now))))
8491 ((= dcst ?d)
8492 (let ((end (save-excursion (outline-next-heading) (point))))
8493 (if (re-search-forward org-deadline-time-regexp end t)
8494 (org-time-string-to-seconds (match-string 1))
8495 (org-float-time now))))
8496 ((= dcst ?p)
8497 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8498 (string-to-char (match-string 2))
8499 org-default-priority))
8500 ((= dcst ?r)
8501 (or (org-entry-get nil property) ""))
8502 ((= dcst ?o)
8503 (if (looking-at org-complex-heading-regexp)
8504 (- 9999 (length (member (match-string 2)
8505 org-todo-keywords-1)))))
8506 ((= dcst ?f)
8507 (if getkey-func
8508 (progn
8509 (setq tmp (funcall getkey-func))
8510 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8511 tmp)
8512 (error "Invalid key function `%s'" getkey-func)))
8513 (t (error "Invalid sorting type `%c'" sorting-type))))
8515 (cond
8516 ((= dcst ?a) 'string<)
8517 ((= dcst ?f) compare-func)
8518 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8519 (run-hooks 'org-after-sorting-entries-or-items-hook)
8520 ;; Reset the clock marker if needed
8521 (when cmstr
8522 (save-excursion
8523 (goto-char start)
8524 (search-forward cmstr nil t)
8525 (move-marker org-clock-marker (point))))
8526 (message "Sorting entries...done")))
8528 (defun org-do-sort (table what &optional with-case sorting-type)
8529 "Sort TABLE of WHAT according to SORTING-TYPE.
8530 The user will be prompted for the SORTING-TYPE if the call to this
8531 function does not specify it. WHAT is only for the prompt, to indicate
8532 what is being sorted. The sorting key will be extracted from
8533 the car of the elements of the table.
8534 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8535 (unless sorting-type
8536 (message
8537 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8538 what)
8539 (setq sorting-type (read-char-exclusive)))
8540 (let ((dcst (downcase sorting-type))
8541 extractfun comparefun)
8542 ;; Define the appropriate functions
8543 (cond
8544 ((= dcst ?n)
8545 (setq extractfun 'string-to-number
8546 comparefun (if (= dcst sorting-type) '< '>)))
8547 ((= dcst ?a)
8548 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8549 (lambda(x) (downcase (org-sort-remove-invisible x))))
8550 comparefun (if (= dcst sorting-type)
8551 'string<
8552 (lambda (a b) (and (not (string< a b))
8553 (not (string= a b)))))))
8554 ((= dcst ?t)
8555 (setq extractfun
8556 (lambda (x)
8557 (if (or (string-match org-ts-regexp x)
8558 (string-match org-ts-regexp-both x))
8559 (org-float-time
8560 (org-time-string-to-time (match-string 0 x)))
8562 comparefun (if (= dcst sorting-type) '< '>)))
8563 (t (error "Invalid sorting type `%c'" sorting-type)))
8565 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8566 table)
8567 (lambda (a b) (funcall comparefun (car a) (car b))))))
8570 ;;; The orgstruct minor mode
8572 ;; Define a minor mode which can be used in other modes in order to
8573 ;; integrate the org-mode structure editing commands.
8575 ;; This is really a hack, because the org-mode structure commands use
8576 ;; keys which normally belong to the major mode. Here is how it
8577 ;; works: The minor mode defines all the keys necessary to operate the
8578 ;; structure commands, but wraps the commands into a function which
8579 ;; tests if the cursor is currently at a headline or a plain list
8580 ;; item. If that is the case, the structure command is used,
8581 ;; temporarily setting many Org-mode variables like regular
8582 ;; expressions for filling etc. However, when any of those keys is
8583 ;; used at a different location, function uses `key-binding' to look
8584 ;; up if the key has an associated command in another currently active
8585 ;; keymap (minor modes, major mode, global), and executes that
8586 ;; command. There might be problems if any of the keys is otherwise
8587 ;; used as a prefix key.
8589 (defcustom orgstruct-heading-prefix-regexp ""
8590 "Regexp that matches the custom prefix of Org headlines in
8591 orgstruct(++)-mode."
8592 :group 'org
8593 :type 'string)
8594 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8596 (defcustom orgstruct-setup-hook nil
8597 "Hook run after orgstruct-mode-map is filled."
8598 :group 'org
8599 :type 'hook)
8601 (defvar orgstruct-initialized nil)
8603 (defvar org-local-vars nil
8604 "List of local variables, for use by `orgstruct-mode'.")
8606 ;;;###autoload
8607 (define-minor-mode orgstruct-mode
8608 "Toggle the minor mode `orgstruct-mode'.
8609 This mode is for using Org-mode structure commands in other
8610 modes. The following keys behave as if Org-mode were active, if
8611 the cursor is on a headline, or on a plain list item (both as
8612 defined by Org-mode)."
8613 nil " OrgStruct" (make-sparse-keymap)
8614 (when orgstruct-mode
8615 (org-load-modules-maybe)
8616 (unless orgstruct-initialized
8617 (orgstruct-setup)
8618 (setq orgstruct-initialized t))))
8620 ;;;###autoload
8621 (defun turn-on-orgstruct ()
8622 "Unconditionally turn on `orgstruct-mode'."
8623 (orgstruct-mode 1))
8625 (defvar org-fb-vars nil)
8626 (make-variable-buffer-local 'org-fb-vars)
8627 (defun orgstruct++-mode (&optional arg)
8628 "Toggle `orgstruct-mode', the enhanced version of it.
8629 In addition to setting orgstruct-mode, this also exports all
8630 indentation and autofilling variables from org-mode into the
8631 buffer. It will also recognize item context in multiline items."
8632 (interactive "P")
8633 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8634 (if (< arg 1)
8635 (progn (orgstruct-mode -1)
8636 (mapc (lambda(v)
8637 (org-set-local (car v)
8638 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8639 org-fb-vars))
8640 (orgstruct-mode 1)
8641 (setq org-fb-vars nil)
8642 (let (var val)
8643 (mapc
8644 (lambda (x)
8645 (when (string-match
8646 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8647 (symbol-name (car x)))
8648 (setq var (car x) val (nth 1 x))
8649 (push (list var `(quote ,(eval var))) org-fb-vars)
8650 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8651 org-local-vars)
8652 (org-set-local 'orgstruct-is-++ t))))
8654 (defvar orgstruct-is-++ nil
8655 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8656 (make-variable-buffer-local 'orgstruct-is-++)
8658 ;;;###autoload
8659 (defun turn-on-orgstruct++ ()
8660 "Unconditionally turn on `orgstruct++-mode'."
8661 (orgstruct++-mode 1))
8663 (defun orgstruct-error ()
8664 "Error when there is no default binding for a structure key."
8665 (interactive)
8666 (error "This key has no function outside structure elements"))
8668 (defun orgstruct-setup ()
8669 "Setup orgstruct keymap."
8670 (dolist (f
8671 '("org-meta"
8672 "org-shiftmeta"
8673 org-shifttab
8674 org-backward-element
8675 org-backward-heading-same-level
8676 org-ctrl-c-ret
8677 org-cycle
8678 org-forward-heading-same-level
8679 org-insert-heading
8680 org-insert-heading-respect-content
8681 org-kill-note-or-show-branches
8682 org-mark-subtree
8683 org-narrow-to-subtree
8684 org-promote-subtree
8685 org-reveal
8686 org-show-subtree
8687 org-sort
8688 org-up-element
8689 outline-demote
8690 outline-next-visible-heading
8691 outline-previous-visible-heading
8692 outline-promote
8693 outline-up-heading
8694 show-children))
8695 (dolist (f (if (stringp f)
8696 (let ((flist))
8697 (dolist (postfix
8698 '("-return" "tab" "left" "right" "up" "down")
8699 flist)
8700 (let ((f (intern (concat f postfix))))
8701 (when (fboundp f)
8702 (push f flist)))))
8703 (list f)))
8704 (dolist (binding (nconc (where-is-internal f org-mode-map)
8705 (where-is-internal f outline-mode-map)))
8706 ;; TODO use local-function-key-map
8707 (dolist (rep '(("<tab>" . "TAB")
8708 ("<ret>" . "RET")
8709 ("<esc>" . "ESC")
8710 ("<del>" . "DEL")))
8711 (setq binding (read-kbd-macro (replace-regexp-in-string
8712 (regexp-quote (car rep))
8713 (cdr rep)
8714 (key-description binding)))))
8715 (let ((key (lookup-key orgstruct-mode-map binding)))
8716 (when (or (not key) (numberp key))
8717 (condition-case nil
8718 (org-defkey orgstruct-mode-map
8719 binding
8720 (orgstruct-make-binding f binding))
8721 (error nil)))))))
8722 (run-hooks 'orgstruct-setup-hook))
8724 (defun orgstruct-make-binding (fun key)
8725 "Create a function for binding in the structure minor mode.
8726 FUN is the command to call inside a table. KEY is the key that
8727 should be checked in for a command to execute outside of tables."
8728 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8729 (let ((nname name)
8730 (i 0))
8731 (while (fboundp (intern nname))
8732 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8733 (setq name (intern nname)))
8734 (eval
8735 `(defun ,name (arg)
8736 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8737 "Outside of structure, run the binding of `"
8738 (key-description key) "'.")
8739 (interactive "p")
8740 (unless
8741 (let* ((org-heading-regexp
8742 (concat "^"
8743 orgstruct-heading-prefix-regexp
8744 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8745 (org-outline-regexp
8746 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8747 (org-outline-regexp-bol
8748 (concat "^" org-outline-regexp))
8749 (outline-regexp org-outline-regexp)
8750 (outline-heading-end-regexp "\n")
8751 (outline-level 'outline-level)
8752 (outline-heading-alist))
8753 (when (org-context-p 'headline 'item
8754 ,(when (memq fun '(org-insert-heading))
8755 '(when orgstruct-is-++
8756 'item-body)))
8757 (org-run-like-in-org-mode ',fun)
8759 (let* ((orgstruct-mode)
8760 (binding (key-binding ,key)))
8761 (if (keymapp binding)
8762 (set-temporary-overlay-map binding)
8763 (call-interactively
8764 (or binding 'orgstruct-error)))))))
8765 name))
8767 (defun org-contextualize-keys (alist contexts)
8768 "Return valid elements in ALIST depending on CONTEXTS.
8770 `org-agenda-custom-commands' or `org-capture-templates' are the
8771 values used for ALIST, and `org-agenda-custom-commands-contexts'
8772 or `org-capture-templates-contexts' are the associated contexts
8773 definitions."
8774 (let ((contexts
8775 ;; normalize contexts
8776 (mapcar
8777 (lambda(c) (cond ((listp (cadr c))
8778 (list (car c) (car c) (cadr c)))
8779 ((string= "" (cadr c))
8780 (list (car c) (car c) (caddr c)))
8781 (t c))) contexts))
8782 (a alist) c r s)
8783 ;; loop over all commands or templates
8784 (while (setq c (pop a))
8785 (let (vrules repl)
8786 (cond
8787 ((not (assoc (car c) contexts))
8788 (push c r))
8789 ((and (assoc (car c) contexts)
8790 (setq vrules (org-contextualize-validate-key
8791 (car c) contexts)))
8792 (mapc (lambda (vr)
8793 (when (not (equal (car vr) (cadr vr)))
8794 (setq repl vr))) vrules)
8795 (if (not repl) (push c r)
8796 (push (cadr repl) s)
8797 (push
8798 (cons (car c)
8799 (cdr (or (assoc (cadr repl) alist)
8800 (error "Undefined key `%s' as contextual replacement for `%s'"
8801 (cadr repl) (car c)))))
8802 r))))))
8803 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8804 (delq
8806 (delete-dups
8807 (mapcar (lambda (x)
8808 (let ((tpl (car x)))
8809 (when (not (delq
8811 (mapcar (lambda(y)
8812 (equal y tpl)) s))) x)))
8813 (reverse r))))))
8815 (defun org-contextualize-validate-key (key contexts)
8816 "Check CONTEXTS for agenda or capture KEY."
8817 (let (r rr res)
8818 (while (setq r (pop contexts))
8819 (mapc
8820 (lambda (rr)
8821 (when
8822 (and (equal key (car r))
8823 (if (functionp rr) (funcall rr)
8824 (or (and (eq (car rr) 'in-file)
8825 (buffer-file-name)
8826 (string-match (cdr rr) (buffer-file-name)))
8827 (and (eq (car rr) 'in-mode)
8828 (string-match (cdr rr) (symbol-name major-mode)))
8829 (and (eq (car rr) 'in-buffer)
8830 (string-match (cdr rr) (buffer-name)))
8831 (when (and (eq (car rr) 'not-in-file)
8832 (buffer-file-name))
8833 (not (string-match (cdr rr) (buffer-file-name))))
8834 (when (eq (car rr) 'not-in-mode)
8835 (not (string-match (cdr rr) (symbol-name major-mode))))
8836 (when (eq (car rr) 'not-in-buffer)
8837 (not (string-match (cdr rr) (buffer-name)))))))
8838 (push r res)))
8839 (car (last r))))
8840 (delete-dups (delq nil res))))
8842 (defun org-context-p (&rest contexts)
8843 "Check if local context is any of CONTEXTS.
8844 Possible values in the list of contexts are `table', `headline', and `item'."
8845 (let ((pos (point)))
8846 (goto-char (point-at-bol))
8847 (prog1 (or (and (memq 'table contexts)
8848 (looking-at "[ \t]*|"))
8849 (and (memq 'headline contexts)
8850 (looking-at org-outline-regexp))
8851 (and (memq 'item contexts)
8852 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8853 (and (memq 'item-body contexts)
8854 (org-in-item-p)))
8855 (goto-char pos))))
8857 (defun org-get-local-variables ()
8858 "Return a list of all local variables in an Org mode buffer."
8859 (let (varlist)
8860 (with-current-buffer (get-buffer-create "*Org tmp*")
8861 (erase-buffer)
8862 (org-mode)
8863 (setq varlist (buffer-local-variables)))
8864 (kill-buffer "*Org tmp*")
8865 (delq nil
8866 (mapcar
8867 (lambda (x)
8868 (setq x
8869 (if (symbolp x)
8870 (list x)
8871 (list (car x) (cdr x))))
8872 (if (and (not (get (car x) 'org-state))
8873 (string-match
8874 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8875 (symbol-name (car x))))
8876 x nil))
8877 varlist))))
8879 (defun org-clone-local-variables (from-buffer &optional regexp)
8880 "Clone local variables from FROM-BUFFER.
8881 Optional argument REGEXP selects variables to clone."
8882 (mapc
8883 (lambda (pair)
8884 (and (symbolp (car pair))
8885 (or (null regexp)
8886 (string-match regexp (symbol-name (car pair))))
8887 (set (make-local-variable (car pair))
8888 (cdr pair))))
8889 (buffer-local-variables from-buffer)))
8891 ;;;###autoload
8892 (defun org-run-like-in-org-mode (cmd)
8893 "Run a command, pretending that the current buffer is in Org-mode.
8894 This will temporarily bind local variables that are typically bound in
8895 Org-mode to the values they have in Org-mode, and then interactively
8896 call CMD."
8897 (org-load-modules-maybe)
8898 (unless org-local-vars
8899 (setq org-local-vars (org-get-local-variables)))
8900 (let (binds)
8901 (dolist (var org-local-vars)
8902 (when (or (not (boundp (car var)))
8903 (eq (symbol-value (car var))
8904 (default-value (car var))))
8905 (push (list (car var) `(quote ,(cadr var))) binds)))
8906 (eval `(let ,binds
8907 (call-interactively (quote ,cmd))))))
8909 ;;;; Archiving
8911 (defun org-get-category (&optional pos force-refresh)
8912 "Get the category applying to position POS."
8913 (save-match-data
8914 (if force-refresh (org-refresh-category-properties))
8915 (let ((pos (or pos (point))))
8916 (or (get-text-property pos 'org-category)
8917 (progn (org-refresh-category-properties)
8918 (get-text-property pos 'org-category))))))
8920 (defun org-refresh-category-properties ()
8921 "Refresh category text properties in the buffer."
8922 (let ((case-fold-search t)
8923 (inhibit-read-only t)
8924 (def-cat (cond
8925 ((null org-category)
8926 (if buffer-file-name
8927 (file-name-sans-extension
8928 (file-name-nondirectory buffer-file-name))
8929 "???"))
8930 ((symbolp org-category) (symbol-name org-category))
8931 (t org-category)))
8932 beg end cat pos optionp)
8933 (org-unmodified
8934 (save-excursion
8935 (save-restriction
8936 (widen)
8937 (goto-char (point-min))
8938 (put-text-property (point) (point-max) 'org-category def-cat)
8939 (while (re-search-forward
8940 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8941 (setq pos (match-end 0)
8942 optionp (equal (char-after (match-beginning 0)) ?#)
8943 cat (org-trim (match-string 2)))
8944 (if optionp
8945 (setq beg (point-at-bol) end (point-max))
8946 (org-back-to-heading t)
8947 (setq beg (point) end (org-end-of-subtree t t)))
8948 (put-text-property beg end 'org-category cat)
8949 (put-text-property beg end 'org-category-position beg)
8950 (goto-char pos)))))))
8952 (defun org-refresh-properties (dprop tprop)
8953 "Refresh buffer text properties.
8954 DPROP is the drawer property and TPROP is the corresponding text
8955 property to set."
8956 (let ((case-fold-search t)
8957 (inhibit-read-only t) p)
8958 (org-unmodified
8959 (save-excursion
8960 (save-restriction
8961 (widen)
8962 (goto-char (point-min))
8963 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8964 (setq p (org-match-string-no-properties 1))
8965 (save-excursion
8966 (org-back-to-heading t)
8967 (put-text-property
8968 (point-at-bol) (point-at-eol) tprop p))))))))
8971 ;;;; Link Stuff
8973 ;;; Link abbreviations
8975 (defun org-link-expand-abbrev (link)
8976 "Apply replacements as defined in `org-link-abbrev-alist'."
8977 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8978 (let* ((key (match-string 1 link))
8979 (as (or (assoc key org-link-abbrev-alist-local)
8980 (assoc key org-link-abbrev-alist)))
8981 (tag (and (match-end 2) (match-string 3 link)))
8982 rpl)
8983 (if (not as)
8984 link
8985 (setq rpl (cdr as))
8986 (cond
8987 ((symbolp rpl) (funcall rpl tag))
8988 ((string-match "%(\\([^)]+\\))" rpl)
8989 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8990 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8991 ((string-match "%h" rpl)
8992 (replace-match (url-hexify-string (or tag "")) t t rpl))
8993 (t (concat rpl tag)))))
8994 link))
8996 ;;; Storing and inserting links
8998 (defvar org-insert-link-history nil
8999 "Minibuffer history for links inserted with `org-insert-link'.")
9001 (defvar org-stored-links nil
9002 "Contains the links stored with `org-store-link'.")
9004 (defvar org-store-link-plist nil
9005 "Plist with info about the most recently link created with `org-store-link'.")
9007 (defvar org-link-protocols nil
9008 "Link protocols added to Org-mode using `org-add-link-type'.")
9010 (defvar org-store-link-functions nil
9011 "List of functions that are called to create and store a link.
9012 Each function will be called in turn until one returns a non-nil
9013 value. Each function should check if it is responsible for creating
9014 this link (for example by looking at the major mode).
9015 If not, it must exit and return nil.
9016 If yes, it should return a non-nil value after a calling
9017 `org-store-link-props' with a list of properties and values.
9018 Special properties are:
9020 :type The link prefix, like \"http\". This must be given.
9021 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9022 This is obligatory as well.
9023 :description Optional default description for the second pair
9024 of brackets in an Org-mode link. The user can still change
9025 this when inserting this link into an Org-mode buffer.
9027 In addition to these, any additional properties can be specified
9028 and then used in capture templates.")
9030 (defun org-add-link-type (type &optional follow export)
9031 "Add TYPE to the list of `org-link-types'.
9032 Re-compute all regular expressions depending on `org-link-types'
9034 FOLLOW and EXPORT are two functions.
9036 FOLLOW should take the link path as the single argument and do whatever
9037 is necessary to follow the link, for example find a file or display
9038 a mail message.
9040 EXPORT should format the link path for export to one of the export formats.
9041 It should be a function accepting three arguments:
9043 path the path of the link, the text after the prefix (like \"http:\")
9044 desc the description of the link, if any, or a description added by
9045 org-export-normalize-links if there is none
9046 format the export format, a symbol like `html' or `latex' or `ascii'..
9048 The function may use the FORMAT information to return different values
9049 depending on the format. The return value will be put literally into
9050 the exported file. If the return value is nil, this means Org should
9051 do what it normally does with links which do not have EXPORT defined.
9053 Org-mode has a built-in default for exporting links. If you are happy with
9054 this default, there is no need to define an export function for the link
9055 type. For a simple example of an export function, see `org-bbdb.el'."
9056 (add-to-list 'org-link-types type t)
9057 (org-make-link-regexps)
9058 (if (assoc type org-link-protocols)
9059 (setcdr (assoc type org-link-protocols) (list follow export))
9060 (push (list type follow export) org-link-protocols)))
9062 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9063 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9065 ;;;###autoload
9066 (defun org-store-link (arg)
9067 "\\<org-mode-map>Store an org-link to the current location.
9068 This link is added to `org-stored-links' and can later be inserted
9069 into an org-buffer with \\[org-insert-link].
9071 For some link types, a prefix arg is interpreted.
9072 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9073 For file links, arg negates `org-context-in-file-links'.
9075 A double prefix arg force skipping storing functions that are not
9076 part of Org's core."
9077 (interactive "P")
9078 (org-load-modules-maybe)
9079 (setq org-store-link-plist nil) ; reset
9080 (org-with-limited-levels
9081 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9082 (cond
9083 ((and (not (equal arg '(16)))
9084 (setq sfuns
9085 (delq
9086 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9087 org-store-link-functions))
9088 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9089 (or (and (cdr sfuns)
9090 (funcall (intern
9091 (completing-read "Which function for creating the link? "
9092 sfunsn t (car sfunsn)))))
9093 (funcall (caar sfuns)))
9094 (setq link (plist-get org-store-link-plist :link)
9095 desc (or (plist-get org-store-link-plist :description) link))))
9096 ((org-src-edit-buffer-p)
9097 (let (label gc)
9098 (while (or (not label)
9099 (save-excursion
9100 (save-restriction
9101 (widen)
9102 (goto-char (point-min))
9103 (re-search-forward
9104 (regexp-quote (format org-coderef-label-format label))
9105 nil t))))
9106 (when label (message "Label exists already") (sit-for 2))
9107 (setq label (read-string "Code line label: " label)))
9108 (end-of-line 1)
9109 (setq link (format org-coderef-label-format label))
9110 (setq gc (- 79 (length link)))
9111 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9112 (insert link)
9113 (setq link (concat "(" label ")") desc nil)))
9115 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9116 ;; We are in the agenda, link to referenced location
9117 (let ((m (or (get-text-property (point) 'org-hd-marker)
9118 (get-text-property (point) 'org-marker))))
9119 (when m
9120 (org-with-point-at m
9121 (setq agenda-link
9122 (if (org-called-interactively-p 'any)
9123 (call-interactively 'org-store-link)
9124 (org-store-link nil)))))))
9126 ((eq major-mode 'calendar-mode)
9127 (let ((cd (calendar-cursor-to-date)))
9128 (setq link
9129 (format-time-string
9130 (car org-time-stamp-formats)
9131 (apply 'encode-time
9132 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9133 nil nil nil))))
9134 (org-store-link-props :type "calendar" :date cd)))
9136 ((eq major-mode 'help-mode)
9137 (setq link (concat "help:" (save-excursion
9138 (goto-char (point-min))
9139 (looking-at "^[^ ]+")
9140 (match-string 0))))
9141 (org-store-link-props :type "help"))
9143 ((eq major-mode 'w3-mode)
9144 (setq cpltxt (if (and (buffer-name)
9145 (not (string-match "Untitled" (buffer-name))))
9146 (buffer-name)
9147 (url-view-url t))
9148 link (url-view-url t))
9149 (org-store-link-props :type "w3" :url (url-view-url t)))
9151 ((setq search (run-hook-with-args-until-success
9152 'org-create-file-search-functions))
9153 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9154 "::" search))
9155 (setq cpltxt (or description link)))
9157 ((eq major-mode 'image-mode)
9158 (setq cpltxt (concat "file:"
9159 (abbreviate-file-name buffer-file-name))
9160 link cpltxt)
9161 (org-store-link-props :type "image" :file buffer-file-name))
9163 ((eq major-mode 'dired-mode)
9164 ;; link to the file in the current line
9165 (let ((file (dired-get-filename nil t)))
9166 (setq file (if file
9167 (abbreviate-file-name
9168 (expand-file-name (dired-get-filename nil t)))
9169 ;; otherwise, no file so use current directory.
9170 default-directory))
9171 (setq cpltxt (concat "file:" file)
9172 link cpltxt)))
9174 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9175 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9176 (cond
9177 ((org-in-regexp "<<\\(.*?\\)>>")
9178 (setq cpltxt
9179 (concat "file:"
9180 (abbreviate-file-name
9181 (buffer-file-name (buffer-base-buffer)))
9182 "::" (match-string 1))
9183 link cpltxt))
9184 ((and (featurep 'org-id)
9185 (or (eq org-id-link-to-org-use-id t)
9186 (and (org-called-interactively-p 'any)
9187 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9188 (and (eq org-id-link-to-org-use-id
9189 'create-if-interactive-and-no-custom-id)
9190 (not custom-id))))
9191 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9192 ;; We can make a link using the ID.
9193 (setq link (condition-case nil
9194 (prog1 (org-id-store-link)
9195 (setq desc (plist-get org-store-link-plist :description)))
9196 (error
9197 ;; probably before first headline, link to file only
9198 (concat "file:"
9199 (abbreviate-file-name
9200 (buffer-file-name (buffer-base-buffer))))))))
9202 ;; Just link to current headline
9203 (setq cpltxt (concat "file:"
9204 (abbreviate-file-name
9205 (buffer-file-name (buffer-base-buffer)))))
9206 ;; Add a context search string
9207 (when (org-xor org-context-in-file-links arg)
9208 (let* ((ee (org-element-at-point))
9209 (et (org-element-type ee))
9210 (ev (plist-get (cadr ee) :value)))
9211 (setq txt (cond
9212 ((org-at-heading-p) nil)
9213 ((eq et 'keyword) ev)
9214 ((org-region-active-p)
9215 (buffer-substring (region-beginning) (region-end)))))
9216 (when (or (null txt) (string-match "\\S-" txt))
9217 (setq cpltxt
9218 (concat cpltxt "::"
9219 (condition-case nil
9220 (org-make-org-heading-search-string txt)
9221 (error "")))
9222 desc (or (and (eq et 'keyword) ev)
9223 (nth 4 (ignore-errors (org-heading-components)))
9224 "NONE")))))
9225 (if (string-match "::\\'" cpltxt)
9226 (setq cpltxt (substring cpltxt 0 -2)))
9227 (setq link cpltxt))))
9229 ((buffer-file-name (buffer-base-buffer))
9230 ;; Just link to this file here.
9231 (setq cpltxt (concat "file:"
9232 (abbreviate-file-name
9233 (buffer-file-name (buffer-base-buffer)))))
9234 ;; Add a context string
9235 (when (org-xor org-context-in-file-links arg)
9236 (setq txt (if (org-region-active-p)
9237 (buffer-substring (region-beginning) (region-end))
9238 (buffer-substring (point-at-bol) (point-at-eol))))
9239 ;; Only use search option if there is some text.
9240 (when (string-match "\\S-" txt)
9241 (setq cpltxt
9242 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9243 desc "NONE")))
9244 (setq link cpltxt))
9246 ((org-called-interactively-p 'interactive)
9247 (user-error "No method for storing a link from this buffer"))
9249 (t (setq link nil)))
9251 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9252 (setq link (or link cpltxt)
9253 desc (or desc cpltxt))
9254 (cond ((equal desc "NONE") (setq desc nil))
9255 ((string-match org-bracket-link-regexp desc)
9256 (setq desc (replace-regexp-in-string
9257 org-bracket-link-regexp
9258 (concat "\\3" (if (equal (length (match-string 0 desc))
9259 (length desc)) "*" "")) desc))))
9261 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9262 (progn
9263 (setq org-stored-links
9264 (cons (list link desc) org-stored-links))
9265 (message "Stored: %s" (or desc link))
9266 (when custom-id
9267 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9268 "::#" custom-id))
9269 (setq org-stored-links
9270 (cons (list link desc) org-stored-links))))
9271 (or agenda-link (and link (org-make-link-string link desc)))))))
9273 (defun org-store-link-props (&rest plist)
9274 "Store link properties, extract names and addresses."
9275 (let (x adr)
9276 (when (setq x (plist-get plist :from))
9277 (setq adr (mail-extract-address-components x))
9278 (setq plist (plist-put plist :fromname (car adr)))
9279 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9280 (when (setq x (plist-get plist :to))
9281 (setq adr (mail-extract-address-components x))
9282 (setq plist (plist-put plist :toname (car adr)))
9283 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9284 (let ((from (plist-get plist :from))
9285 (to (plist-get plist :to)))
9286 (when (and from to org-from-is-user-regexp)
9287 (setq plist
9288 (plist-put plist :fromto
9289 (if (string-match org-from-is-user-regexp from)
9290 (concat "to %t")
9291 (concat "from %f"))))))
9292 (setq org-store-link-plist plist))
9294 (defun org-add-link-props (&rest plist)
9295 "Add these properties to the link property list."
9296 (let (key value)
9297 (while plist
9298 (setq key (pop plist) value (pop plist))
9299 (setq org-store-link-plist
9300 (plist-put org-store-link-plist key value)))))
9302 (defun org-email-link-description (&optional fmt)
9303 "Return the description part of an email link.
9304 This takes information from `org-store-link-plist' and formats it
9305 according to FMT (default from `org-email-link-description-format')."
9306 (setq fmt (or fmt org-email-link-description-format))
9307 (let* ((p org-store-link-plist)
9308 (to (plist-get p :toaddress))
9309 (from (plist-get p :fromaddress))
9310 (table
9311 (list
9312 (cons "%c" (plist-get p :fromto))
9313 (cons "%F" (plist-get p :from))
9314 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9315 (cons "%T" (plist-get p :to))
9316 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9317 (cons "%s" (plist-get p :subject))
9318 (cons "%d" (plist-get p :date))
9319 (cons "%m" (plist-get p :message-id)))))
9320 (when (string-match "%c" fmt)
9321 ;; Check if the user wrote this message
9322 (if (and org-from-is-user-regexp from to
9323 (save-match-data (string-match org-from-is-user-regexp from)))
9324 (setq fmt (replace-match "to %t" t t fmt))
9325 (setq fmt (replace-match "from %f" t t fmt))))
9326 (org-replace-escapes fmt table)))
9328 (defun org-make-org-heading-search-string (&optional string)
9329 "Make search string for the current headline or STRING."
9330 (let ((s (or string
9331 (and (derived-mode-p 'org-mode)
9332 (save-excursion
9333 (org-back-to-heading t)
9334 (org-element-property :raw-value (org-element-at-point))))))
9335 (lines org-context-in-file-links))
9336 (or string (setq s (concat "*" s))) ; Add * for headlines
9337 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9338 (when (and string (integerp lines) (> lines 0))
9339 (let ((slines (org-split-string s "\n")))
9340 (when (< lines (length slines))
9341 (setq s (mapconcat
9342 'identity
9343 (reverse (nthcdr (- (length slines) lines)
9344 (reverse slines))) "\n")))))
9345 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9347 (defun org-make-link-string (link &optional description)
9348 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9349 (unless (string-match "\\S-" link)
9350 (error "Empty link"))
9351 (when (and description
9352 (stringp description)
9353 (not (string-match "\\S-" description)))
9354 (setq description nil))
9355 (when (stringp description)
9356 ;; Remove brackets from the description, they are fatal.
9357 (while (string-match "\\[" description)
9358 (setq description (replace-match "{" t t description)))
9359 (while (string-match "\\]" description)
9360 (setq description (replace-match "}" t t description))))
9361 (when (equal link description)
9362 ;; No description needed, it is identical
9363 (setq description nil))
9364 (when (and (not description)
9365 (not (string-match (org-image-file-name-regexp) link))
9366 (not (equal link (org-link-escape link))))
9367 (setq description (org-extract-attributes link)))
9368 (setq link
9369 (cond ((string-match (org-image-file-name-regexp) link) link)
9370 ((string-match org-link-types-re link)
9371 (concat (match-string 1 link)
9372 (org-link-escape (substring link (match-end 1)))))
9373 (t (org-link-escape link))))
9374 (concat "[[" link "]"
9375 (if description (concat "[" description "]") "")
9376 "]"))
9378 (defconst org-link-escape-chars
9379 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9380 "List of characters that should be escaped in link.
9381 This is the list that is used for internal purposes.")
9383 (defconst org-link-escape-chars-browser
9384 '(?\ )
9385 "List of escapes for characters that are problematic in links.
9386 This is the list that is used before handing over to the browser.")
9388 (defun org-link-escape (text &optional table merge)
9389 "Return percent escaped representation of TEXT.
9390 TEXT is a string with the text to escape.
9391 Optional argument TABLE is a list with characters that should be
9392 escaped. When nil, `org-link-escape-chars' is used.
9393 If optional argument MERGE is set, merge TABLE into
9394 `org-link-escape-chars'."
9395 (cond
9396 ((and table merge)
9397 (mapc (lambda (defchr)
9398 (unless (member defchr table)
9399 (setq table (cons defchr table)))) org-link-escape-chars))
9400 ((null table)
9401 (setq table org-link-escape-chars)))
9402 (mapconcat
9403 (lambda (char)
9404 (if (or (member char table)
9405 (and (or (< char 32) (= char 37) (> char 126))
9406 org-url-hexify-p))
9407 (mapconcat (lambda (sequence-element)
9408 (format "%%%.2X" sequence-element))
9409 (or (encode-coding-char char 'utf-8)
9410 (error "Unable to percent escape character: %s"
9411 (char-to-string char))) "")
9412 (char-to-string char))) text ""))
9414 (defun org-link-unescape (str)
9415 "Unhex hexified Unicode strings as returned from the JavaScript function
9416 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9417 (unless (and (null str) (string= "" str))
9418 (let ((pos 0) (case-fold-search t) unhexed)
9419 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9420 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9421 (setq str (replace-match unhexed t t str))
9422 (setq pos (+ pos (length unhexed))))))
9423 str)
9425 (defun org-link-unescape-compound (hex)
9426 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9427 Note: this function also decodes single byte encodings like
9428 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9429 (save-match-data
9430 (let* ((bytes (cdr (split-string hex "%")))
9431 (ret "")
9432 (eat 0)
9433 (sum 0))
9434 (while bytes
9435 (let* ((val (string-to-number (pop bytes) 16))
9436 (shift-xor
9437 (if (= 0 eat)
9438 (cond
9439 ((>= val 252) (cons 6 252))
9440 ((>= val 248) (cons 5 248))
9441 ((>= val 240) (cons 4 240))
9442 ((>= val 224) (cons 3 224))
9443 ((>= val 192) (cons 2 192))
9444 (t (cons 0 0)))
9445 (cons 6 128))))
9446 (if (>= val 192) (setq eat (car shift-xor)))
9447 (setq val (logxor val (cdr shift-xor)))
9448 (setq sum (+ (lsh sum (car shift-xor)) val))
9449 (if (> eat 0) (setq eat (- eat 1)))
9450 (cond
9451 ((= 0 eat) ;multi byte
9452 (setq ret (concat ret (org-char-to-string sum)))
9453 (setq sum 0))
9454 ((not bytes) ; single byte(s)
9455 (setq ret (org-link-unescape-single-byte-sequence hex))))
9456 )) ;; end (while bytes
9457 ret )))
9459 (defun org-link-unescape-single-byte-sequence (hex)
9460 "Unhexify hex-encoded single byte character sequences."
9461 (mapconcat (lambda (byte)
9462 (char-to-string (string-to-number byte 16)))
9463 (cdr (split-string hex "%")) ""))
9465 (defun org-xor (a b)
9466 "Exclusive or."
9467 (if a (not b) b))
9469 (defun org-fixup-message-id-for-http (s)
9470 "Replace special characters in a message id, so it can be used in an http query."
9471 (when (string-match "%" s)
9472 (setq s (mapconcat (lambda (c)
9473 (if (eq c ?%)
9474 "%25"
9475 (char-to-string c)))
9476 s "")))
9477 (while (string-match "<" s)
9478 (setq s (replace-match "%3C" t t s)))
9479 (while (string-match ">" s)
9480 (setq s (replace-match "%3E" t t s)))
9481 (while (string-match "@" s)
9482 (setq s (replace-match "%40" t t s)))
9485 (defun org-link-prettify (link)
9486 "Return a human-readable representation of LINK.
9487 The car of LINK must be a raw link the cdr of LINK must be either
9488 a link description or nil."
9489 (let ((desc (or (cadr link) "<no description>")))
9490 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9491 "<" (car link) ">")))
9493 ;;;###autoload
9494 (defun org-insert-link-global ()
9495 "Insert a link like Org-mode does.
9496 This command can be called in any mode to insert a link in Org-mode syntax."
9497 (interactive)
9498 (org-load-modules-maybe)
9499 (org-run-like-in-org-mode 'org-insert-link))
9501 (defun org-insert-all-links (&optional keep)
9502 "Insert all links in `org-stored-links'."
9503 (interactive "P")
9504 (let ((links (copy-sequence org-stored-links)) l)
9505 (while (setq l (if keep (pop links) (pop org-stored-links)))
9506 (insert "- ")
9507 (org-insert-link nil (car l) (cadr l))
9508 (insert "\n"))))
9510 (defun org-link-fontify-links-to-this-file ()
9511 "Fontify links to the current file in `org-stored-links'."
9512 (let ((f (buffer-file-name)) a b)
9513 (setq a (mapcar (lambda(l)
9514 (let ((ll (car l)))
9515 (when (and (string-match "^file:\\(.+\\)::" ll)
9516 (equal f (expand-file-name (match-string 1 ll))))
9517 ll)))
9518 org-stored-links))
9519 (when (featurep 'org-id)
9520 (setq b (mapcar (lambda(l)
9521 (let ((ll (car l)))
9522 (when (and (string-match "^id:\\(.+\\)$" ll)
9523 (equal f (expand-file-name
9524 (or (org-id-find-id-file
9525 (match-string 1 ll)) ""))))
9526 ll)))
9527 org-stored-links)))
9528 (mapcar (lambda(l)
9529 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9530 (delq nil (append a b)))))
9532 (defvar org-link-links-in-this-file nil)
9533 (defun org-insert-link (&optional complete-file link-location default-description)
9534 "Insert a link. At the prompt, enter the link.
9536 Completion can be used to insert any of the link protocol prefixes like
9537 http or ftp in use.
9539 The history can be used to select a link previously stored with
9540 `org-store-link'. When the empty string is entered (i.e. if you just
9541 press RET at the prompt), the link defaults to the most recently
9542 stored link. As SPC triggers completion in the minibuffer, you need to
9543 use M-SPC or C-q SPC to force the insertion of a space character.
9545 You will also be prompted for a description, and if one is given, it will
9546 be displayed in the buffer instead of the link.
9548 If there is already a link at point, this command will allow you to edit link
9549 and description parts.
9551 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9552 be selected using completion. The path to the file will be relative to the
9553 current directory if the file is in the current directory or a subdirectory.
9554 Otherwise, the link will be the absolute path as completed in the minibuffer
9555 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9556 option `org-link-file-path-type'.
9558 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9559 the current directory or below.
9561 With three \\[universal-argument] prefixes, negate the meaning of
9562 `org-keep-stored-link-after-insertion'.
9564 If `org-make-link-description-function' is non-nil, this function will be
9565 called with the link target, and the result will be the default
9566 link description.
9568 If the LINK-LOCATION parameter is non-nil, this value will be
9569 used as the link location instead of reading one interactively.
9571 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9572 be used as the default description."
9573 (interactive "P")
9574 (let* ((wcf (current-window-configuration))
9575 (origbuf (current-buffer))
9576 (region (if (org-region-active-p)
9577 (buffer-substring (region-beginning) (region-end))))
9578 (remove (and region (list (region-beginning) (region-end))))
9579 (desc region)
9580 tmphist ; byte-compile incorrectly complains about this
9581 (link link-location)
9582 (abbrevs org-link-abbrev-alist-local)
9583 entry file all-prefixes auto-desc)
9584 (cond
9585 (link-location) ; specified by arg, just use it.
9586 ((org-in-regexp org-bracket-link-regexp 1)
9587 ;; We do have a link at point, and we are going to edit it.
9588 (setq remove (list (match-beginning 0) (match-end 0)))
9589 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9590 (setq link (read-string "Link: "
9591 (org-link-unescape
9592 (org-match-string-no-properties 1)))))
9593 ((or (org-in-regexp org-angle-link-re)
9594 (org-in-regexp org-plain-link-re))
9595 ;; Convert to bracket link
9596 (setq remove (list (match-beginning 0) (match-end 0))
9597 link (read-string "Link: "
9598 (org-remove-angle-brackets (match-string 0)))))
9599 ((member complete-file '((4) (16)))
9600 ;; Completing read for file names.
9601 (setq link (org-file-complete-link complete-file)))
9603 ;; Read link, with completion for stored links.
9604 (org-link-fontify-links-to-this-file)
9605 (org-switch-to-buffer-other-window "*Org Links*")
9606 (with-current-buffer "*Org Links*"
9607 (erase-buffer)
9608 (insert "Insert a link.
9609 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9610 (when org-stored-links
9611 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9612 (insert (mapconcat 'org-link-prettify
9613 (reverse org-stored-links) "\n")))
9614 (goto-char (point-min)))
9615 (let ((cw (selected-window)))
9616 (select-window (get-buffer-window "*Org Links*" 'visible))
9617 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9618 (unless (pos-visible-in-window-p (point-max))
9619 (org-fit-window-to-buffer))
9620 (and (window-live-p cw) (select-window cw)))
9621 ;; Fake a link history, containing the stored links.
9622 (setq tmphist (append (mapcar 'car org-stored-links)
9623 org-insert-link-history))
9624 (setq all-prefixes (append (mapcar 'car abbrevs)
9625 (mapcar 'car org-link-abbrev-alist)
9626 org-link-types))
9627 (unwind-protect
9628 (progn
9629 (setq link
9630 (org-completing-read
9631 "Link: "
9632 (append
9633 (mapcar (lambda (x) (concat x ":"))
9634 all-prefixes)
9635 (mapcar 'car org-stored-links))
9636 nil nil nil
9637 'tmphist
9638 (caar org-stored-links)))
9639 (if (not (string-match "\\S-" link))
9640 (error "No link selected"))
9641 (mapc (lambda(l)
9642 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9643 org-stored-links)
9644 (if (or (member link all-prefixes)
9645 (and (equal ":" (substring link -1))
9646 (member (substring link 0 -1) all-prefixes)
9647 (setq link (substring link 0 -1))))
9648 (setq link (with-current-buffer origbuf
9649 (org-link-try-special-completion link)))))
9650 (set-window-configuration wcf)
9651 (kill-buffer "*Org Links*"))
9652 (setq entry (assoc link org-stored-links))
9653 (or entry (push link org-insert-link-history))
9654 (setq desc (or desc (nth 1 entry)))))
9656 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9657 (not org-keep-stored-link-after-insertion))
9658 (setq org-stored-links (delq (assoc link org-stored-links)
9659 org-stored-links)))
9661 (if (string-match org-plain-link-re link)
9662 ;; URL-like link, normalize the use of angular brackets.
9663 (setq link (org-remove-angle-brackets link)))
9665 ;; Check if we are linking to the current file with a search
9666 ;; option If yes, simplify the link by using only the search
9667 ;; option.
9668 (when (and buffer-file-name
9669 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9670 (let* ((path (match-string 1 link))
9671 (case-fold-search nil)
9672 (search (match-string 2 link)))
9673 (save-match-data
9674 (if (equal (file-truename buffer-file-name) (file-truename path))
9675 ;; We are linking to this same file, with a search option
9676 (setq link search)))))
9678 ;; Check if we can/should use a relative path. If yes, simplify the link
9679 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9680 (let* ((type (match-string 1 link))
9681 (path (match-string 2 link))
9682 (origpath path)
9683 (case-fold-search nil))
9684 (cond
9685 ((or (eq org-link-file-path-type 'absolute)
9686 (equal complete-file '(16)))
9687 (setq path (abbreviate-file-name (expand-file-name path))))
9688 ((eq org-link-file-path-type 'noabbrev)
9689 (setq path (expand-file-name path)))
9690 ((eq org-link-file-path-type 'relative)
9691 (setq path (file-relative-name path)))
9693 (save-match-data
9694 (if (string-match (concat "^" (regexp-quote
9695 (expand-file-name
9696 (file-name-as-directory
9697 default-directory))))
9698 (expand-file-name path))
9699 ;; We are linking a file with relative path name.
9700 (setq path (substring (expand-file-name path)
9701 (match-end 0)))
9702 (setq path (abbreviate-file-name (expand-file-name path)))))))
9703 (setq link (concat type path))
9704 (if (equal desc origpath)
9705 (setq desc path))))
9707 (if org-make-link-description-function
9708 (setq desc
9709 (or (condition-case nil
9710 (funcall org-make-link-description-function link desc)
9711 (error (progn (message "Can't get link description from `%s'"
9712 (symbol-name org-make-link-description-function))
9713 (sit-for 2) nil)))
9714 (read-string "Description: " default-description)))
9715 (if default-description (setq desc default-description)
9716 (setq desc (or (and auto-desc desc)
9717 (read-string "Description: " desc)))))
9719 (unless (string-match "\\S-" desc) (setq desc nil))
9720 (if remove (apply 'delete-region remove))
9721 (insert (org-make-link-string link desc))))
9723 (defun org-link-try-special-completion (type)
9724 "If there is completion support for link type TYPE, offer it."
9725 (let ((fun (intern (concat "org-" type "-complete-link"))))
9726 (if (functionp fun)
9727 (funcall fun)
9728 (read-string "Link (no completion support): " (concat type ":")))))
9730 (defun org-file-complete-link (&optional arg)
9731 "Create a file link using completion."
9732 (let (file link)
9733 (setq file (org-iread-file-name "File: "))
9734 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9735 (pwd1 (file-name-as-directory (abbreviate-file-name
9736 (expand-file-name ".")))))
9737 (cond
9738 ((equal arg '(16))
9739 (setq link (concat
9740 "file:"
9741 (abbreviate-file-name (expand-file-name file)))))
9742 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9743 (setq link (concat "file:" (match-string 1 file))))
9744 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9745 (expand-file-name file))
9746 (setq link (concat
9747 "file:" (match-string 1 (expand-file-name file)))))
9748 (t (setq link (concat "file:" file)))))
9749 link))
9751 (defun org-iread-file-name (&rest args)
9752 "Read-file-name using `ido-mode' speedup if available.
9753 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9754 See `read-file-name' for a description of parameters."
9755 (org-without-partial-completion
9756 (if (and org-completion-use-ido
9757 (fboundp 'ido-read-file-name)
9758 (boundp 'ido-mode) ido-mode
9759 (listp (second args)))
9760 (let ((ido-enter-matching-directory nil))
9761 (apply 'ido-read-file-name args))
9762 (apply 'read-file-name args))))
9764 (defun org-completing-read (&rest args)
9765 "Completing-read with SPACE being a normal character."
9766 (let ((enable-recursive-minibuffers t)
9767 (minibuffer-local-completion-map
9768 (copy-keymap minibuffer-local-completion-map)))
9769 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9770 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9771 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9772 (apply 'org-icompleting-read args)))
9774 (defun org-completing-read-no-i (&rest args)
9775 (let (org-completion-use-ido org-completion-use-iswitchb)
9776 (apply 'org-completing-read args)))
9778 (defun org-iswitchb-completing-read (prompt choices &rest args)
9779 "Use iswitch as a completing-read replacement to choose from choices.
9780 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9781 from."
9782 (let* ((iswitchb-use-virtual-buffers nil)
9783 (iswitchb-make-buflist-hook
9784 (lambda ()
9785 (setq iswitchb-temp-buflist choices))))
9786 (iswitchb-read-buffer prompt)))
9788 (defun org-icompleting-read (&rest args)
9789 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9790 (org-without-partial-completion
9791 (if (and org-completion-use-ido
9792 (fboundp 'ido-completing-read)
9793 (boundp 'ido-mode) ido-mode
9794 (listp (second args)))
9795 (let ((ido-enter-matching-directory nil))
9796 (apply 'ido-completing-read (concat (car args))
9797 (if (consp (car (nth 1 args)))
9798 (mapcar 'car (nth 1 args))
9799 (nth 1 args))
9800 (cddr args)))
9801 (if (and org-completion-use-iswitchb
9802 (boundp 'iswitchb-mode) iswitchb-mode
9803 (listp (second args)))
9804 (apply 'org-iswitchb-completing-read (concat (car args))
9805 (if (consp (car (nth 1 args)))
9806 (mapcar 'car (nth 1 args))
9807 (nth 1 args))
9808 (cddr args))
9809 (apply 'completing-read args)))))
9811 (defun org-extract-attributes (s)
9812 "Extract the attributes cookie from a string and set as text property."
9813 (let (a attr (start 0) key value)
9814 (save-match-data
9815 (when (string-match "{{\\([^}]+\\)}}$" s)
9816 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9817 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9818 (setq key (match-string 1 a) value (match-string 2 a)
9819 start (match-end 0)
9820 attr (plist-put attr (intern key) value))))
9821 (org-add-props s nil 'org-attr attr))
9824 (defun org-extract-attributes-from-string (tag)
9825 (let (key value attr)
9826 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9827 (setq key (match-string 1 tag) value (match-string 2 tag)
9828 tag (replace-match "" t t tag)
9829 attr (plist-put attr (intern key) value)))
9830 (cons tag attr)))
9832 (defun org-attributes-to-string (plist)
9833 "Format a property list into an HTML attribute list."
9834 (let ((s "") key value)
9835 (while plist
9836 (setq key (pop plist) value (pop plist))
9837 (and value
9838 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9841 ;;; Opening/following a link
9843 (defvar org-link-search-failed nil)
9845 (defvar org-open-link-functions nil
9846 "Hook for functions finding a plain text link.
9847 These functions must take a single argument, the link content.
9848 They will be called for links that look like [[link text][description]]
9849 when LINK TEXT does not have a protocol like \"http:\" and does not look
9850 like a filename (e.g. \"./blue.png\").
9852 These functions will be called *before* Org attempts to resolve the
9853 link by doing text searches in the current buffer - so if you want a
9854 link \"[[target]]\" to still find \"<<target>>\", your function should
9855 handle this as a special case.
9857 When the function does handle the link, it must return a non-nil value.
9858 If it decides that it is not responsible for this link, it must return
9859 nil to indicate that that Org-mode can continue with other options
9860 like exact and fuzzy text search.")
9862 (defun org-next-link ()
9863 "Move forward to the next link.
9864 If the link is in hidden text, expose it."
9865 (interactive)
9866 (when (and org-link-search-failed (eq this-command last-command))
9867 (goto-char (point-min))
9868 (message "Link search wrapped back to beginning of buffer"))
9869 (setq org-link-search-failed nil)
9870 (let* ((pos (point))
9871 (ct (org-context))
9872 (a (assoc :link ct)))
9873 (if a (goto-char (nth 2 a)))
9874 (if (re-search-forward org-any-link-re nil t)
9875 (progn
9876 (goto-char (match-beginning 0))
9877 (if (outline-invisible-p) (org-show-context)))
9878 (goto-char pos)
9879 (setq org-link-search-failed t)
9880 (error "No further link found"))))
9882 (defun org-previous-link ()
9883 "Move backward to the previous link.
9884 If the link is in hidden text, expose it."
9885 (interactive)
9886 (when (and org-link-search-failed (eq this-command last-command))
9887 (goto-char (point-max))
9888 (message "Link search wrapped back to end of buffer"))
9889 (setq org-link-search-failed nil)
9890 (let* ((pos (point))
9891 (ct (org-context))
9892 (a (assoc :link ct)))
9893 (if a (goto-char (nth 1 a)))
9894 (if (re-search-backward org-any-link-re nil t)
9895 (progn
9896 (goto-char (match-beginning 0))
9897 (if (outline-invisible-p) (org-show-context)))
9898 (goto-char pos)
9899 (setq org-link-search-failed t)
9900 (error "No further link found"))))
9902 (defun org-translate-link (s)
9903 "Translate a link string if a translation function has been defined."
9904 (if (and org-link-translation-function
9905 (fboundp org-link-translation-function)
9906 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9907 (progn
9908 (setq s (funcall org-link-translation-function
9909 (match-string 1 s) (match-string 2 s)))
9910 (concat (car s) ":" (cdr s)))
9913 (defun org-translate-link-from-planner (type path)
9914 "Translate a link from Emacs Planner syntax so that Org can follow it.
9915 This is still an experimental function, your mileage may vary."
9916 (cond
9917 ((member type '("http" "https" "news" "ftp"))
9918 ;; standard Internet links are the same.
9919 nil)
9920 ((and (equal type "irc") (string-match "^//" path))
9921 ;; Planner has two / at the beginning of an irc link, we have 1.
9922 ;; We should have zero, actually....
9923 (setq path (substring path 1)))
9924 ((and (equal type "lisp") (string-match "^/" path))
9925 ;; Planner has a slash, we do not.
9926 (setq type "elisp" path (substring path 1)))
9927 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9928 ;; A typical message link. Planner has the id after the final slash,
9929 ;; we separate it with a hash mark
9930 (setq path (concat (match-string 1 path) "#"
9931 (org-remove-angle-brackets (match-string 2 path)))))
9933 (cons type path))
9935 (defun org-find-file-at-mouse (ev)
9936 "Open file link or URL at mouse."
9937 (interactive "e")
9938 (mouse-set-point ev)
9939 (org-open-at-point 'in-emacs))
9941 (defun org-open-at-mouse (ev)
9942 "Open file link or URL at mouse.
9943 See the docstring of `org-open-file' for details."
9944 (interactive "e")
9945 (mouse-set-point ev)
9946 (if (eq major-mode 'org-agenda-mode)
9947 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9948 (org-open-at-point))
9950 (defvar org-window-config-before-follow-link nil
9951 "The window configuration before following a link.
9952 This is saved in case the need arises to restore it.")
9954 (defvar org-open-link-marker (make-marker)
9955 "Marker pointing to the location where `org-open-at-point; was called.")
9957 ;;;###autoload
9958 (defun org-open-at-point-global ()
9959 "Follow a link like Org-mode does.
9960 This command can be called in any mode to follow a link that has
9961 Org-mode syntax."
9962 (interactive)
9963 (org-run-like-in-org-mode 'org-open-at-point))
9965 ;;;###autoload
9966 (defun org-open-link-from-string (s &optional arg reference-buffer)
9967 "Open a link in the string S, as if it was in Org-mode."
9968 (interactive "sLink: \nP")
9969 (let ((reference-buffer (or reference-buffer (current-buffer))))
9970 (with-temp-buffer
9971 (let ((org-inhibit-startup (not reference-buffer)))
9972 (org-mode)
9973 (insert s)
9974 (goto-char (point-min))
9975 (when reference-buffer
9976 (setq org-link-abbrev-alist-local
9977 (with-current-buffer reference-buffer
9978 org-link-abbrev-alist-local)))
9979 (org-open-at-point arg reference-buffer)))))
9981 (defvar org-open-at-point-functions nil
9982 "Hook that is run when following a link at point.
9984 Functions in this hook must return t if they identify and follow
9985 a link at point. If they don't find anything interesting at point,
9986 they must return nil.")
9988 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9989 (defun org-open-at-point (&optional arg reference-buffer)
9990 "Open link at or after point.
9991 If there is no link at point, this function will search forward up to
9992 the end of the current line.
9993 Normally, files will be opened by an appropriate application. If the
9994 optional prefix argument ARG is non-nil, Emacs will visit the file.
9995 With a double prefix argument, try to open outside of Emacs, in the
9996 application the system uses for this file type."
9997 (interactive "P")
9998 ;; if in a code block, then open the block's results
9999 (unless (call-interactively #'org-babel-open-src-block-result)
10000 (org-load-modules-maybe)
10001 (move-marker org-open-link-marker (point))
10002 (setq org-window-config-before-follow-link (current-window-configuration))
10003 (org-remove-occur-highlights nil nil t)
10004 (cond
10005 ((and (org-at-heading-p)
10006 (not (org-at-timestamp-p t))
10007 (not (org-in-regexp
10008 (concat org-plain-link-re "\\|"
10009 org-bracket-link-regexp "\\|"
10010 org-angle-link-re "\\|"
10011 "[ \t]:[^ \t\n]+:[ \t]*$")))
10012 (not (get-text-property (point) 'org-linked-text)))
10013 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10014 (lk0 (car lkall))
10015 (lk (if (stringp lk0) (list lk0) lk0))
10016 (lkend (cdr lkall)))
10017 (mapcar (lambda(l)
10018 (search-forward l nil lkend)
10019 (goto-char (match-beginning 0))
10020 (org-open-at-point))
10021 lk))
10022 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10023 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10024 ((and (org-at-timestamp-p t)
10025 (not (org-in-regexp org-bracket-link-regexp)))
10026 (org-follow-timestamp-link))
10027 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10028 (not (org-in-regexp org-any-link-re)))
10029 (org-footnote-action))
10031 (let (type path link line search (pos (point)))
10032 (catch 'match
10033 (save-excursion
10034 (skip-chars-forward "^]\n\r")
10035 (when (org-in-regexp org-bracket-link-regexp 1)
10036 (setq link (org-extract-attributes
10037 (org-link-unescape (org-match-string-no-properties 1))))
10038 (while (string-match " *\n *" link)
10039 (setq link (replace-match " " t t link)))
10040 (setq link (org-link-expand-abbrev link))
10041 (cond
10042 ((or (file-name-absolute-p link)
10043 (string-match "^\\.\\.?/" link))
10044 (setq type "file" path link))
10045 ((string-match org-link-re-with-space3 link)
10046 (setq type (match-string 1 link) path (match-string 2 link)))
10047 ((string-match "^help:+\\(.+\\)" link)
10048 (setq type "help" path (match-string 1 link)))
10049 (t (setq type "thisfile" path link)))
10050 (throw 'match t)))
10052 (when (get-text-property (point) 'org-linked-text)
10053 (setq type "thisfile"
10054 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10055 (1+ (point)) (point))
10056 path (buffer-substring
10057 (or (previous-single-property-change pos 'org-linked-text)
10058 (point-min))
10059 (or (next-single-property-change pos 'org-linked-text)
10060 (point-max))))
10061 (throw 'match t))
10063 (save-excursion
10064 (when (or (org-in-regexp org-angle-link-re)
10065 (let ((match (org-in-regexp org-plain-link-re)))
10066 ;; Check a plain link is not within a bracket link
10067 (and match
10068 (save-excursion
10069 (progn
10070 (goto-char (car match))
10071 (not (org-in-regexp org-bracket-link-regexp))))))
10072 (let ((line_ending (save-excursion (end-of-line) (point))))
10073 ;; We are in a line before a plain or bracket link
10074 (or (re-search-forward org-plain-link-re line_ending t)
10075 (re-search-forward org-bracket-link-regexp line_ending t))))
10076 (setq type (match-string 1)
10077 path (org-link-unescape (match-string 2)))
10078 (throw 'match t)))
10079 (save-excursion
10080 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10081 (setq type "tags"
10082 path (match-string 1))
10083 (while (string-match ":" path)
10084 (setq path (replace-match "+" t t path)))
10085 (throw 'match t)))
10086 (when (org-in-regexp "<\\([^><\n]+\\)>")
10087 (setq type "tree-match"
10088 path (match-string 1))
10089 (throw 'match t)))
10090 (unless path
10091 (user-error "No link found"))
10093 ;; switch back to reference buffer
10094 ;; needed when if called in a temporary buffer through
10095 ;; org-open-link-from-string
10096 (with-current-buffer (or reference-buffer (current-buffer))
10098 ;; Remove any trailing spaces in path
10099 (if (string-match " +\\'" path)
10100 (setq path (replace-match "" t t path)))
10101 (if (and org-link-translation-function
10102 (fboundp org-link-translation-function))
10103 ;; Check if we need to translate the link
10104 (let ((tmp (funcall org-link-translation-function type path)))
10105 (setq type (car tmp) path (cdr tmp))))
10107 (cond
10109 ((assoc type org-link-protocols)
10110 (funcall (nth 1 (assoc type org-link-protocols)) path))
10112 ((equal type "help")
10113 (let ((f-or-v (intern path)))
10114 (cond ((fboundp f-or-v)
10115 (describe-function f-or-v))
10116 ((boundp f-or-v)
10117 (describe-variable f-or-v))
10118 (t (error "Not a known function or variable")))))
10120 ((equal type "mailto")
10121 (let ((cmd (car org-link-mailto-program))
10122 (args (cdr org-link-mailto-program)) args1
10123 (address path) (subject "") a)
10124 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10125 (setq address (match-string 1 path)
10126 subject (org-link-escape (match-string 2 path))))
10127 (while args
10128 (cond
10129 ((not (stringp (car args))) (push (pop args) args1))
10130 (t (setq a (pop args))
10131 (if (string-match "%a" a)
10132 (setq a (replace-match address t t a)))
10133 (if (string-match "%s" a)
10134 (setq a (replace-match subject t t a)))
10135 (push a args1))))
10136 (apply cmd (nreverse args1))))
10138 ((member type '("http" "https" "ftp" "news"))
10139 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10140 (org-link-escape
10141 path org-link-escape-chars-browser)
10142 path))))
10144 ((string= type "doi")
10145 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10146 (org-link-escape
10147 path org-link-escape-chars-browser)
10148 path))))
10150 ((member type '("message"))
10151 (browse-url (concat type ":" path)))
10153 ((string= type "tags")
10154 (org-tags-view arg path))
10156 ((string= type "tree-match")
10157 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10159 ((string= type "file")
10160 (if (string-match "::\\([0-9]+\\)\\'" path)
10161 (setq line (string-to-number (match-string 1 path))
10162 path (substring path 0 (match-beginning 0)))
10163 (if (string-match "::\\(.+\\)\\'" path)
10164 (setq search (match-string 1 path)
10165 path (substring path 0 (match-beginning 0)))))
10166 (if (string-match "[*?{]" (file-name-nondirectory path))
10167 (dired path)
10168 (org-open-file path arg line search)))
10170 ((string= type "shell")
10171 (let ((buf (generate-new-buffer "*Org Shell Output"))
10172 (cmd path))
10173 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10174 (string-match org-confirm-shell-link-not-regexp cmd))
10175 (not org-confirm-shell-link-function)
10176 (funcall org-confirm-shell-link-function
10177 (format "Execute \"%s\" in shell? "
10178 (org-add-props cmd nil
10179 'face 'org-warning))))
10180 (progn
10181 (message "Executing %s" cmd)
10182 (shell-command cmd buf)
10183 (if (featurep 'midnight)
10184 (setq clean-buffer-list-kill-buffer-names
10185 (cons buf clean-buffer-list-kill-buffer-names))))
10186 (error "Abort"))))
10188 ((string= type "elisp")
10189 (let ((cmd path))
10190 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10191 (string-match org-confirm-elisp-link-not-regexp cmd))
10192 (not org-confirm-elisp-link-function)
10193 (funcall org-confirm-elisp-link-function
10194 (format "Execute \"%s\" as elisp? "
10195 (org-add-props cmd nil
10196 'face 'org-warning))))
10197 (message "%s => %s" cmd
10198 (if (equal (string-to-char cmd) ?\()
10199 (eval (read cmd))
10200 (call-interactively (read cmd))))
10201 (error "Abort"))))
10203 ((and (string= type "thisfile")
10204 (run-hook-with-args-until-success
10205 'org-open-link-functions path)))
10207 ((string= type "thisfile")
10208 (if arg
10209 (switch-to-buffer-other-window
10210 (org-get-buffer-for-internal-link (current-buffer)))
10211 (org-mark-ring-push))
10212 (let ((cmd `(org-link-search
10213 ,path
10214 ,(cond ((equal arg '(4)) ''occur)
10215 ((equal arg '(16)) ''org-occur))
10216 ,pos)))
10217 (condition-case nil (let ((org-link-search-inhibit-query t))
10218 (eval cmd))
10219 (error (progn (widen) (eval cmd))))))
10221 (t (browse-url-at-point)))))))
10222 (move-marker org-open-link-marker nil)
10223 (run-hook-with-args 'org-follow-link-hook)))
10225 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10226 "Offer links in the current entry and return the selected link.
10227 If there is only one link, return it.
10228 If NTH is an integer, return the NTH link found.
10229 If ZERO is a string, check also this string for a link, and if
10230 there is one, return it."
10231 (with-current-buffer buffer
10232 (save-excursion
10233 (save-restriction
10234 (widen)
10235 (goto-char marker)
10236 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10237 "\\(" org-angle-link-re "\\)\\|"
10238 "\\(" org-plain-link-re "\\)"))
10239 (cnt ?0)
10240 (in-emacs (if (integerp nth) nil nth))
10241 have-zero end links link c)
10242 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10243 (push (match-string 0 zero) links)
10244 (setq cnt (1- cnt) have-zero t))
10245 (save-excursion
10246 (org-back-to-heading t)
10247 (setq end (save-excursion (outline-next-heading) (point)))
10248 (while (re-search-forward re end t)
10249 (push (match-string 0) links))
10250 (setq links (org-uniquify (reverse links))))
10251 (cond
10252 ((null links)
10253 (message "No links"))
10254 ((equal (length links) 1)
10255 (setq link (car links)))
10256 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10257 (setq link (nth (if have-zero nth (1- nth)) links)))
10258 (t ; we have to select a link
10259 (save-excursion
10260 (save-window-excursion
10261 (delete-other-windows)
10262 (with-output-to-temp-buffer "*Select Link*"
10263 (mapc (lambda (l)
10264 (if (not (string-match org-bracket-link-regexp l))
10265 (princ (format "[%c] %s\n" (incf cnt)
10266 (org-remove-angle-brackets l)))
10267 (if (match-end 3)
10268 (princ (format "[%c] %s (%s)\n" (incf cnt)
10269 (match-string 3 l) (match-string 1 l)))
10270 (princ (format "[%c] %s\n" (incf cnt)
10271 (match-string 1 l))))))
10272 links))
10273 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10274 (message "Select link to open, RET to open all:")
10275 (setq c (read-char-exclusive))
10276 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10277 (when (equal c ?q) (error "Abort"))
10278 (if (equal c ?\C-m)
10279 (setq link links)
10280 (setq nth (- c ?0))
10281 (if have-zero (setq nth (1+ nth)))
10282 (unless (and (integerp nth) (>= (length links) nth))
10283 (error "Invalid link selection"))
10284 (setq link (nth (1- nth) links)))))
10285 (cons link end))))))
10287 ;; Add special file links that specify the way of opening
10289 (org-add-link-type "file+sys" 'org-open-file-with-system)
10290 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10291 (defun org-open-file-with-system (path)
10292 "Open file at PATH using the system way of opening it."
10293 (org-open-file path 'system))
10294 (defun org-open-file-with-emacs (path)
10295 "Open file at PATH in Emacs."
10296 (org-open-file path 'emacs))
10299 ;;; File search
10301 (defvar org-create-file-search-functions nil
10302 "List of functions to construct the right search string for a file link.
10303 These functions are called in turn with point at the location to
10304 which the link should point.
10306 A function in the hook should first test if it would like to
10307 handle this file type, for example by checking the `major-mode'
10308 or the file extension. If it decides not to handle this file, it
10309 should just return nil to give other functions a chance. If it
10310 does handle the file, it must return the search string to be used
10311 when following the link. The search string will be part of the
10312 file link, given after a double colon, and `org-open-at-point'
10313 will automatically search for it. If special measures must be
10314 taken to make the search successful, another function should be
10315 added to the companion hook `org-execute-file-search-functions',
10316 which see.
10318 A function in this hook may also use `setq' to set the variable
10319 `description' to provide a suggestion for the descriptive text to
10320 be used for this link when it gets inserted into an Org-mode
10321 buffer with \\[org-insert-link].")
10323 (defvar org-execute-file-search-functions nil
10324 "List of functions to execute a file search triggered by a link.
10326 Functions added to this hook must accept a single argument, the
10327 search string that was part of the file link, the part after the
10328 double colon. The function must first check if it would like to
10329 handle this search, for example by checking the `major-mode' or
10330 the file extension. If it decides not to handle this search, it
10331 should just return nil to give other functions a chance. If it
10332 does handle the search, it must return a non-nil value to keep
10333 other functions from trying.
10335 Each function can access the current prefix argument through the
10336 variable `current-prefix-argument'. Note that a single prefix is
10337 used to force opening a link in Emacs, so it may be good to only
10338 use a numeric or double prefix to guide the search function.
10340 In case this is needed, a function in this hook can also restore
10341 the window configuration before `org-open-at-point' was called using:
10343 (set-window-configuration org-window-config-before-follow-link)")
10345 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10346 (defun org-link-search (s &optional type avoid-pos stealth)
10347 "Search for a link search option.
10348 If S is surrounded by forward slashes, it is interpreted as a
10349 regular expression. In org-mode files, this will create an `org-occur'
10350 sparse tree. In ordinary files, `occur' will be used to list matches.
10351 If the current buffer is in `dired-mode', grep will be used to search
10352 in all files. If AVOID-POS is given, ignore matches near that position.
10354 When optional argument STEALTH is non-nil, do not modify
10355 visibility around point, thus ignoring
10356 `org-show-hierarchy-above', `org-show-following-heading' and
10357 `org-show-siblings' variables."
10358 (let ((case-fold-search t)
10359 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10360 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10361 (append '(("") (" ") ("\t") ("\n"))
10362 org-emphasis-alist)
10363 "\\|") "\\)"))
10364 (pos (point))
10365 (pre nil) (post nil)
10366 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10367 (cond
10368 ;; First check if there are any special search functions
10369 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10370 ;; Now try the builtin stuff
10371 ((and (equal (string-to-char s0) ?#)
10372 (> (length s0) 1)
10373 (save-excursion
10374 (goto-char (point-min))
10375 (and
10376 (re-search-forward
10377 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10378 (setq type 'dedicated
10379 pos (match-beginning 0))))
10380 ;; There is an exact target for this
10381 (goto-char pos)
10382 (org-back-to-heading t)))
10383 ((save-excursion
10384 (goto-char (point-min))
10385 (and
10386 (re-search-forward
10387 (concat "<<" (regexp-quote s0) ">>") nil t)
10388 (setq type 'dedicated
10389 pos (match-beginning 0))))
10390 ;; There is an exact target for this
10391 (goto-char pos))
10392 ((save-excursion
10393 (goto-char (point-min))
10394 (and
10395 (re-search-forward
10396 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10397 (setq type 'dedicated pos (match-beginning 0))))
10398 ;; Found an invisible target.
10399 (goto-char pos))
10400 ((save-excursion
10401 (goto-char (point-min))
10402 (and
10403 (re-search-forward
10404 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10405 (setq type 'dedicated pos (match-beginning 0))))
10406 ;; Found an element with a matching #+name affiliated keyword.
10407 (goto-char pos))
10408 ((and (string-match "^(\\(.*\\))$" s0)
10409 (save-excursion
10410 (goto-char (point-min))
10411 (and
10412 (re-search-forward
10413 (concat "[^[]" (regexp-quote
10414 (format org-coderef-label-format
10415 (match-string 1 s0))))
10416 nil t)
10417 (setq type 'dedicated
10418 pos (1+ (match-beginning 0))))))
10419 ;; There is a coderef target for this
10420 (goto-char pos))
10421 ((string-match "^/\\(.*\\)/$" s)
10422 ;; A regular expression
10423 (cond
10424 ((derived-mode-p 'org-mode)
10425 (org-occur (match-string 1 s)))
10426 (t (org-do-occur (match-string 1 s)))))
10427 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10428 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10429 (goto-char (point-min))
10430 (cond
10431 ((let (case-fold-search)
10432 (re-search-forward (format org-complex-heading-regexp-format
10433 (regexp-quote s))
10434 nil t))
10435 ;; OK, found a match
10436 (setq type 'dedicated)
10437 (goto-char (match-beginning 0)))
10438 ((and (not org-link-search-inhibit-query)
10439 (eq org-link-search-must-match-exact-headline 'query-to-create)
10440 (y-or-n-p "No match - create this as a new heading? "))
10441 (goto-char (point-max))
10442 (or (bolp) (newline))
10443 (insert "* " s "\n")
10444 (beginning-of-line 0))
10446 (goto-char pos)
10447 (error "No match"))))
10449 ;; A normal search string
10450 (when (equal (string-to-char s) ?*)
10451 ;; Anchor on headlines, post may include tags.
10452 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10453 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10454 s (substring s 1)))
10455 (remove-text-properties
10456 0 (length s)
10457 '(face nil mouse-face nil keymap nil fontified nil) s)
10458 ;; Make a series of regular expressions to find a match
10459 (setq words (org-split-string s "[ \n\r\t]+")
10461 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10462 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10463 "\\)" markers)
10464 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10465 re2a (concat "[ \t\r\n]" re2a_)
10466 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10467 re4 (concat "[^a-zA-Z_]" re4_)
10469 re1 (concat pre re2 post)
10470 re3 (concat pre (if pre re4_ re4) post)
10471 re5 (concat pre ".*" re4)
10472 re2 (concat pre re2)
10473 re2a (concat pre (if pre re2a_ re2a))
10474 re4 (concat pre (if pre re4_ re4))
10475 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10476 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10477 re5 "\\)"
10479 (cond
10480 ((eq type 'org-occur) (org-occur reall))
10481 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10482 (t (goto-char (point-min))
10483 (setq type 'fuzzy)
10484 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10485 (org-search-not-self 1 re1 nil t)
10486 (org-search-not-self 1 re2 nil t)
10487 (org-search-not-self 1 re2a nil t)
10488 (org-search-not-self 1 re3 nil t)
10489 (org-search-not-self 1 re4 nil t)
10490 (org-search-not-self 1 re5 nil t)
10492 (goto-char (match-beginning 1))
10493 (goto-char pos)
10494 (error "No match"))))))
10495 (and (derived-mode-p 'org-mode)
10496 (not stealth)
10497 (org-show-context 'link-search))
10498 type))
10500 (defun org-search-not-self (group &rest args)
10501 "Execute `re-search-forward', but only accept matches that do not
10502 enclose the position of `org-open-link-marker'."
10503 (let ((m org-open-link-marker))
10504 (catch 'exit
10505 (while (apply 're-search-forward args)
10506 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10507 (goto-char (match-end group))
10508 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10509 (> (match-beginning 0) (marker-position m))
10510 (< (match-end 0) (marker-position m)))
10511 (save-match-data
10512 (or (not (org-in-regexp
10513 org-bracket-link-analytic-regexp 1))
10514 (not (match-end 4)) ; no description
10515 (and (<= (match-beginning 4) (point))
10516 (>= (match-end 4) (point))))))
10517 (throw 'exit (point))))))))
10519 (defun org-get-buffer-for-internal-link (buffer)
10520 "Return a buffer to be used for displaying the link target of internal links."
10521 (cond
10522 ((not org-display-internal-link-with-indirect-buffer)
10523 buffer)
10524 ((string-match "(Clone)$" (buffer-name buffer))
10525 (message "Buffer is already a clone, not making another one")
10526 ;; we also do not modify visibility in this case
10527 buffer)
10528 (t ; make a new indirect buffer for displaying the link
10529 (let* ((bn (buffer-name buffer))
10530 (ibn (concat bn "(Clone)"))
10531 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10532 (with-current-buffer ib (org-overview))
10533 ib))))
10535 (defun org-do-occur (regexp &optional cleanup)
10536 "Call the Emacs command `occur'.
10537 If CLEANUP is non-nil, remove the printout of the regular expression
10538 in the *Occur* buffer. This is useful if the regex is long and not useful
10539 to read."
10540 (occur regexp)
10541 (when cleanup
10542 (let ((cwin (selected-window)) win beg end)
10543 (when (setq win (get-buffer-window "*Occur*"))
10544 (select-window win))
10545 (goto-char (point-min))
10546 (when (re-search-forward "match[a-z]+" nil t)
10547 (setq beg (match-end 0))
10548 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10549 (setq end (1- (match-beginning 0)))))
10550 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10551 (goto-char (point-min))
10552 (select-window cwin))))
10554 ;;; The mark ring for links jumps
10556 (defvar org-mark-ring nil
10557 "Mark ring for positions before jumps in Org-mode.")
10558 (defvar org-mark-ring-last-goto nil
10559 "Last position in the mark ring used to go back.")
10560 ;; Fill and close the ring
10561 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10562 (loop for i from 1 to org-mark-ring-length do
10563 (push (make-marker) org-mark-ring))
10564 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10565 org-mark-ring)
10567 (defun org-mark-ring-push (&optional pos buffer)
10568 "Put the current position or POS into the mark ring and rotate it."
10569 (interactive)
10570 (setq pos (or pos (point)))
10571 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10572 (move-marker (car org-mark-ring)
10573 (or pos (point))
10574 (or buffer (current-buffer)))
10575 (message "%s"
10576 (substitute-command-keys
10577 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10579 (defun org-mark-ring-goto (&optional n)
10580 "Jump to the previous position in the mark ring.
10581 With prefix arg N, jump back that many stored positions. When
10582 called several times in succession, walk through the entire ring.
10583 Org-mode commands jumping to a different position in the current file,
10584 or to another Org-mode file, automatically push the old position
10585 onto the ring."
10586 (interactive "p")
10587 (let (p m)
10588 (if (eq last-command this-command)
10589 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10590 (setq p org-mark-ring))
10591 (setq org-mark-ring-last-goto p)
10592 (setq m (car p))
10593 (org-pop-to-buffer-same-window (marker-buffer m))
10594 (goto-char m)
10595 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10597 (defun org-remove-angle-brackets (s)
10598 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10599 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10601 (defun org-add-angle-brackets (s)
10602 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10603 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10605 (defun org-remove-double-quotes (s)
10606 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10607 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10610 ;;; Following specific links
10612 (defun org-follow-timestamp-link ()
10613 "Open an agenda view for the time-stamp date/range at point."
10614 (cond
10615 ((org-at-date-range-p t)
10616 (let ((org-agenda-start-on-weekday)
10617 (t1 (match-string 1))
10618 (t2 (match-string 2)) tt1 tt2)
10619 (setq tt1 (time-to-days (org-time-string-to-time t1))
10620 tt2 (time-to-days (org-time-string-to-time t2)))
10621 (let ((org-agenda-buffer-tmp-name
10622 (format "*Org Agenda(a:%s)"
10623 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10624 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10625 ((org-at-timestamp-p t)
10626 (let ((org-agenda-buffer-tmp-name
10627 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10628 (org-agenda-list nil (time-to-days (org-time-string-to-time
10629 (substring (match-string 1) 0 10)))
10630 1)))
10631 (t (error "This should not happen"))))
10634 ;;; Following file links
10635 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10636 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10637 (declare-function mailcap-mime-info
10638 "mailcap" (string &optional request no-decode))
10639 (defvar org-wait nil)
10640 (defun org-open-file (path &optional in-emacs line search)
10641 "Open the file at PATH.
10642 First, this expands any special file name abbreviations. Then the
10643 configuration variable `org-file-apps' is checked if it contains an
10644 entry for this file type, and if yes, the corresponding command is launched.
10646 If no application is found, Emacs simply visits the file.
10648 With optional prefix argument IN-EMACS, Emacs will visit the file.
10649 With a double \\[universal-argument] \\[universal-argument] \
10650 prefix arg, Org tries to avoid opening in Emacs
10651 and to use an external application to visit the file.
10653 Optional LINE specifies a line to go to, optional SEARCH a string
10654 to search for. If LINE or SEARCH is given, the file will be
10655 opened in Emacs, unless an entry from org-file-apps that makes
10656 use of groups in a regexp matches.
10658 If you want to change the way frames are used when following a
10659 link, please customize `org-link-frame-setup'.
10661 If the file does not exist, an error is thrown."
10662 (let* ((file (if (equal path "")
10663 buffer-file-name
10664 (substitute-in-file-name (expand-file-name path))))
10665 (file-apps (append org-file-apps (org-default-apps)))
10666 (apps (org-remove-if
10667 'org-file-apps-entry-match-against-dlink-p file-apps))
10668 (apps-dlink (org-remove-if-not
10669 'org-file-apps-entry-match-against-dlink-p file-apps))
10670 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10671 (dirp (if remp nil (file-directory-p file)))
10672 (file (if (and dirp org-open-directory-means-index-dot-org)
10673 (concat (file-name-as-directory file) "index.org")
10674 file))
10675 (a-m-a-p (assq 'auto-mode apps))
10676 (dfile (downcase file))
10677 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10678 (link (cond ((and (eq line nil)
10679 (eq search nil))
10680 file)
10681 (line
10682 (concat file "::" (number-to-string line)))
10683 (search
10684 (concat file "::" search))))
10685 (dlink (downcase link))
10686 (old-buffer (current-buffer))
10687 (old-pos (point))
10688 (old-mode major-mode)
10689 ext cmd link-match-data)
10690 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10691 (setq ext (match-string 1 dfile))
10692 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10693 (setq ext (match-string 1 dfile))))
10694 (cond
10695 ((member in-emacs '((16) system))
10696 (setq cmd (cdr (assoc 'system apps))))
10697 (in-emacs (setq cmd 'emacs))
10699 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10700 (and dirp (cdr (assoc 'directory apps)))
10701 ; first, try matching against apps-dlink
10702 ; if we get a match here, store the match data for later
10703 (let ((match (assoc-default dlink apps-dlink
10704 'string-match)))
10705 (if match
10706 (progn (setq link-match-data (match-data))
10707 match)
10708 (progn (setq in-emacs (or in-emacs line search))
10709 nil))) ; if we have no match in apps-dlink,
10710 ; always open the file in emacs if line or search
10711 ; is given (for backwards compatibility)
10712 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10713 'string-match)
10714 (cdr (assoc ext apps))
10715 (cdr (assoc t apps))))))
10716 (when (eq cmd 'system)
10717 (setq cmd (cdr (assoc 'system apps))))
10718 (when (eq cmd 'default)
10719 (setq cmd (cdr (assoc t apps))))
10720 (when (eq cmd 'mailcap)
10721 (require 'mailcap)
10722 (mailcap-parse-mailcaps)
10723 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10724 (command (mailcap-mime-info mime-type)))
10725 (if (stringp command)
10726 (setq cmd command)
10727 (setq cmd 'emacs))))
10728 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10729 (not (file-exists-p file))
10730 (not org-open-non-existing-files))
10731 (error "No such file: %s" file))
10732 (cond
10733 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10734 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10735 (while (string-match "['\"]%s['\"]" cmd)
10736 (setq cmd (replace-match "%s" t t cmd)))
10737 (while (string-match "%s" cmd)
10738 (setq cmd (replace-match
10739 (save-match-data
10740 (shell-quote-argument
10741 (convert-standard-filename file)))
10742 t t cmd)))
10744 ;; Replace "%1", "%2" etc. in command with group matches from regex
10745 (save-match-data
10746 (let ((match-index 1)
10747 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10748 (set-match-data link-match-data)
10749 (while (<= match-index number-of-groups)
10750 (let ((regex (concat "%" (number-to-string match-index)))
10751 (replace-with (match-string match-index dlink)))
10752 (while (string-match regex cmd)
10753 (setq cmd (replace-match replace-with t t cmd))))
10754 (setq match-index (+ match-index 1)))))
10756 (save-window-excursion
10757 (message "Running %s...done" cmd)
10758 (start-process-shell-command cmd nil cmd)
10759 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10760 ((or (stringp cmd)
10761 (eq cmd 'emacs))
10762 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10763 (widen)
10764 (if line (org-goto-line line)
10765 (if search (org-link-search search))))
10766 ((consp cmd)
10767 (let ((file (convert-standard-filename file)))
10768 (save-match-data
10769 (set-match-data link-match-data)
10770 (eval cmd))))
10771 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10772 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10773 (or (not (equal old-buffer (current-buffer)))
10774 (not (equal old-pos (point))))
10775 (org-mark-ring-push old-pos old-buffer))))
10777 (defun org-file-apps-entry-match-against-dlink-p (entry)
10778 "This function returns non-nil if `entry' uses a regular
10779 expression which should be matched against the whole link by
10780 org-open-file.
10782 It assumes that is the case when the entry uses a regular
10783 expression which has at least one grouping construct and the
10784 action is either a lisp form or a command string containing
10785 '%1', i.e. using at least one subexpression match as a
10786 parameter."
10787 (let ((selector (car entry))
10788 (action (cdr entry)))
10789 (if (stringp selector)
10790 (and (> (regexp-opt-depth selector) 0)
10791 (or (and (stringp action)
10792 (string-match "%[0-9]" action))
10793 (consp action)))
10794 nil)))
10796 (defun org-default-apps ()
10797 "Return the default applications for this operating system."
10798 (cond
10799 ((eq system-type 'darwin)
10800 org-file-apps-defaults-macosx)
10801 ((eq system-type 'windows-nt)
10802 org-file-apps-defaults-windowsnt)
10803 (t org-file-apps-defaults-gnu)))
10805 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10806 "Convert extensions to regular expressions in the cars of LIST.
10807 Also, weed out any non-string entries, because the return value is used
10808 only for regexp matching.
10809 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10810 point to the symbol `emacs', indicating that the file should
10811 be opened in Emacs."
10812 (append
10813 (delq nil
10814 (mapcar (lambda (x)
10815 (if (not (stringp (car x)))
10817 (if (string-match "\\W" (car x))
10819 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10820 list))
10821 (if add-auto-mode
10822 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10824 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10825 (defun org-file-remote-p (file)
10826 "Test whether FILE specifies a location on a remote system.
10827 Return non-nil if the location is indeed remote.
10829 For example, the filename \"/user@host:/foo\" specifies a location
10830 on the system \"/user@host:\"."
10831 (cond ((fboundp 'file-remote-p)
10832 (file-remote-p file))
10833 ((fboundp 'tramp-handle-file-remote-p)
10834 (tramp-handle-file-remote-p file))
10835 ((and (boundp 'ange-ftp-name-format)
10836 (string-match (car ange-ftp-name-format) file))
10837 t)))
10840 ;;;; Refiling
10842 (defun org-get-org-file ()
10843 "Read a filename, with default directory `org-directory'."
10844 (let ((default (or org-default-notes-file remember-data-file)))
10845 (read-file-name (format "File name [%s]: " default)
10846 (file-name-as-directory org-directory)
10847 default)))
10849 (defun org-notes-order-reversed-p ()
10850 "Check if the current file should receive notes in reversed order."
10851 (cond
10852 ((not org-reverse-note-order) nil)
10853 ((eq t org-reverse-note-order) t)
10854 ((not (listp org-reverse-note-order)) nil)
10855 (t (catch 'exit
10856 (let ((all org-reverse-note-order)
10857 entry)
10858 (while (setq entry (pop all))
10859 (if (string-match (car entry) buffer-file-name)
10860 (throw 'exit (cdr entry))))
10861 nil)))))
10863 (defvar org-refile-target-table nil
10864 "The list of refile targets, created by `org-refile'.")
10866 (defvar org-agenda-new-buffers nil
10867 "Buffers created to visit agenda files.")
10869 (defvar org-refile-cache nil
10870 "Cache for refile targets.")
10872 (defvar org-refile-markers nil
10873 "All the markers used for caching refile locations.")
10875 (defun org-refile-marker (pos)
10876 "Get a new refile marker, but only if caching is in use."
10877 (if (not org-refile-use-cache)
10879 (let ((m (make-marker)))
10880 (move-marker m pos)
10881 (push m org-refile-markers)
10882 m)))
10884 (defun org-refile-cache-clear ()
10885 "Clear the refile cache and disable all the markers."
10886 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10887 (setq org-refile-markers nil)
10888 (setq org-refile-cache nil)
10889 (message "Refile cache has been cleared"))
10891 (defun org-refile-cache-check-set (set)
10892 "Check if all the markers in the cache still have live buffers."
10893 (let (marker)
10894 (catch 'exit
10895 (while (and set (setq marker (nth 3 (pop set))))
10896 ;; if org-refile-use-outline-path is 'file, marker may be nil
10897 (when (and marker (null (marker-buffer marker)))
10898 (message "not found") (sit-for 3)
10899 (throw 'exit nil)))
10900 t)))
10902 (defun org-refile-cache-put (set &rest identifiers)
10903 "Push the refile targets SET into the cache, under IDENTIFIERS."
10904 (let* ((key (sha1 (prin1-to-string identifiers)))
10905 (entry (assoc key org-refile-cache)))
10906 (if entry
10907 (setcdr entry set)
10908 (push (cons key set) org-refile-cache))))
10910 (defun org-refile-cache-get (&rest identifiers)
10911 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10912 (cond
10913 ((not org-refile-cache) nil)
10914 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10916 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10917 org-refile-cache))))
10918 (and set (org-refile-cache-check-set set) set)))))
10920 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10921 "Produce a table with refile targets."
10922 (let ((case-fold-search nil)
10923 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10924 (entries (or org-refile-targets '((nil . (:level . 1)))))
10925 targets tgs txt re files f desc descre fast-path-p level pos0)
10926 (message "Getting targets...")
10927 (with-current-buffer (or default-buffer (current-buffer))
10928 (while (setq entry (pop entries))
10929 (setq files (car entry) desc (cdr entry))
10930 (setq fast-path-p nil)
10931 (cond
10932 ((null files) (setq files (list (current-buffer))))
10933 ((eq files 'org-agenda-files)
10934 (setq files (org-agenda-files 'unrestricted)))
10935 ((and (symbolp files) (fboundp files))
10936 (setq files (funcall files)))
10937 ((and (symbolp files) (boundp files))
10938 (setq files (symbol-value files))))
10939 (if (stringp files) (setq files (list files)))
10940 (cond
10941 ((eq (car desc) :tag)
10942 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10943 ((eq (car desc) :todo)
10944 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10945 ((eq (car desc) :regexp)
10946 (setq descre (cdr desc)))
10947 ((eq (car desc) :level)
10948 (setq descre (concat "^\\*\\{" (number-to-string
10949 (if org-odd-levels-only
10950 (1- (* 2 (cdr desc)))
10951 (cdr desc)))
10952 "\\}[ \t]")))
10953 ((eq (car desc) :maxlevel)
10954 (setq fast-path-p t)
10955 (setq descre (concat "^\\*\\{1," (number-to-string
10956 (if org-odd-levels-only
10957 (1- (* 2 (cdr desc)))
10958 (cdr desc)))
10959 "\\}[ \t]")))
10960 (t (error "Bad refiling target description %s" desc)))
10961 (while (setq f (pop files))
10962 (with-current-buffer
10963 (if (bufferp f) f (org-get-agenda-file-buffer f))
10965 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10966 (progn
10967 (if (bufferp f) (setq f (buffer-file-name
10968 (buffer-base-buffer f))))
10969 (setq f (and f (expand-file-name f)))
10970 (if (eq org-refile-use-outline-path 'file)
10971 (push (list (file-name-nondirectory f) f nil nil) tgs))
10972 (save-excursion
10973 (save-restriction
10974 (widen)
10975 (goto-char (point-min))
10976 (while (re-search-forward descre nil t)
10977 (goto-char (setq pos0 (point-at-bol)))
10978 (catch 'next
10979 (when org-refile-target-verify-function
10980 (save-match-data
10981 (or (funcall org-refile-target-verify-function)
10982 (throw 'next t))))
10983 (when (and (looking-at org-complex-heading-regexp)
10984 (not (member (match-string 4) excluded-entries))
10985 (match-string 4))
10986 (setq level (org-reduced-level
10987 (- (match-end 1) (match-beginning 1)))
10988 txt (org-link-display-format (match-string 4))
10989 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10990 re (format org-complex-heading-regexp-format
10991 (regexp-quote (match-string 4))))
10992 (when org-refile-use-outline-path
10993 (setq txt (mapconcat
10994 'org-protect-slash
10995 (append
10996 (if (eq org-refile-use-outline-path
10997 'file)
10998 (list (file-name-nondirectory
10999 (buffer-file-name
11000 (buffer-base-buffer))))
11001 (if (eq org-refile-use-outline-path
11002 'full-file-path)
11003 (list (buffer-file-name
11004 (buffer-base-buffer)))))
11005 (org-get-outline-path fast-path-p
11006 level txt)
11007 (list txt))
11008 "/")))
11009 (push (list txt f re (org-refile-marker (point)))
11010 tgs)))
11011 (when (= (point) pos0)
11012 ;; verification function has not moved point
11013 (goto-char (point-at-eol))))))))
11014 (when org-refile-use-cache
11015 (org-refile-cache-put tgs (buffer-file-name) descre))
11016 (setq targets (append tgs targets))
11017 ))))
11018 (message "Getting targets...done")
11019 (nreverse targets)))
11021 (defun org-protect-slash (s)
11022 (while (string-match "/" s)
11023 (setq s (replace-match "\\" t t s)))
11026 (defvar org-olpa (make-vector 20 nil))
11028 (defun org-get-outline-path (&optional fastp level heading)
11029 "Return the outline path to the current entry, as a list.
11031 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11032 routine which makes outline path derivations for an entire file,
11033 avoiding backtracing. Refile target collection makes use of that."
11034 (if fastp
11035 (progn
11036 (if (> level 19)
11037 (error "Outline path failure, more than 19 levels"))
11038 (loop for i from level upto 19 do
11039 (aset org-olpa i nil))
11040 (prog1
11041 (delq nil (append org-olpa nil))
11042 (aset org-olpa level heading)))
11043 (let (rtn case-fold-search)
11044 (save-excursion
11045 (save-restriction
11046 (widen)
11047 (while (org-up-heading-safe)
11048 (when (looking-at org-complex-heading-regexp)
11049 (push (org-match-string-no-properties 4) rtn)))
11050 rtn)))))
11052 (defun org-format-outline-path (path &optional width prefix separator)
11053 "Format the outline path PATH for display.
11054 WIDTH is the maximum number of characters that is available.
11055 PREFIX is a prefix to be included in the returned string,
11056 such as the file name.
11057 SEPARATOR is inserted between the different parts of the path,
11058 the default is \"/\"."
11059 (setq width (or width 79))
11060 (if prefix (setq width (- width (length prefix))))
11061 (if (not path)
11062 (or prefix "")
11063 (let* ((nsteps (length path))
11064 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11065 (maxwidth (if (<= total-width width)
11066 10000 ;; everything fits
11067 ;; we need to shorten the level headings
11068 (/ (- width nsteps) nsteps)))
11069 (org-odd-levels-only nil)
11070 (n 0)
11071 (total (1+ (length prefix))))
11072 (setq maxwidth (max maxwidth 10))
11073 (concat prefix
11074 (if prefix (or separator "/"))
11075 (mapconcat
11076 (lambda (h)
11077 (setq n (1+ n))
11078 (if (and (= n nsteps) (< maxwidth 10000))
11079 (setq maxwidth (- total-width total)))
11080 (if (< (length h) maxwidth)
11081 (progn (setq total (+ total (length h) 1)) h)
11082 (setq h (substring h 0 (- maxwidth 2))
11083 total (+ total maxwidth 1))
11084 (if (string-match "[ \t]+\\'" h)
11085 (setq h (substring h 0 (match-beginning 0))))
11086 (setq h (concat h "..")))
11087 (org-add-props h nil 'face
11088 (nth (% (1- n) org-n-level-faces)
11089 org-level-faces))
11091 path (or separator "/"))))))
11093 (defun org-display-outline-path (&optional file current separator just-return-string)
11094 "Display the current outline path in the echo area.
11096 If FILE is non-nil, prepend the output with the file name.
11097 If CURRENT is non-nil, append the current heading to the output.
11098 SEPARATOR is passed through to `org-format-outline-path'. It separates
11099 the different parts of the path and defaults to \"/\".
11100 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11101 (interactive "P")
11102 (let* (case-fold-search
11103 message-log-max ; Don't populate the *Messages* buffer
11104 (bfn (buffer-file-name (buffer-base-buffer)))
11105 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11106 res)
11107 (if current (setq path (append path
11108 (save-excursion
11109 (org-back-to-heading t)
11110 (if (looking-at org-complex-heading-regexp)
11111 (list (match-string 4)))))))
11112 (setq res
11113 (org-format-outline-path
11114 path
11115 (1- (frame-width))
11116 (and file bfn (concat (file-name-nondirectory bfn) separator))
11117 separator))
11118 (if just-return-string
11119 (org-no-properties res)
11120 (message "%s" res))))
11122 (defvar org-refile-history nil
11123 "History for refiling operations.")
11125 (defvar org-after-refile-insert-hook nil
11126 "Hook run after `org-refile' has inserted its stuff at the new location.
11127 Note that this is still *before* the stuff will be removed from
11128 the *old* location.")
11130 (defvar org-capture-last-stored-marker)
11131 (defvar org-refile-keep nil
11132 "Non-nil means `org-refile' will copy instead of refile.")
11134 (defun org-copy ()
11135 "Like `org-refile', but copy."
11136 (interactive)
11137 (let ((org-refile-keep t))
11138 (funcall 'org-refile nil nil nil "Copy")))
11140 (defun org-refile (&optional goto default-buffer rfloc msg)
11141 "Move the entry or entries at point to another heading.
11142 The list of target headings is compiled using the information in
11143 `org-refile-targets', which see.
11145 At the target location, the entry is filed as a subitem of the target
11146 heading. Depending on `org-reverse-note-order', the new subitem will
11147 either be the first or the last subitem.
11149 If there is an active region, all entries in that region will be moved.
11150 However, the region must fulfill the requirement that the first heading
11151 is the first one sets the top-level of the moved text - at most siblings
11152 below it are allowed.
11154 With prefix arg GOTO, the command will only visit the target location
11155 and not actually move anything.
11157 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11158 go to the location where the last refiling operation has put the subtree.
11159 With a prefix argument of `2', refile to the running clock.
11161 RFLOC can be a refile location obtained in a different way.
11163 MSG is a string to replace \"Refile\" in the default prompt with
11164 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11166 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11168 If you are using target caching (see `org-refile-use-cache'),
11169 you have to clear the target cache in order to find new targets.
11170 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11171 prefix argument (`C-u C-u C-u C-c C-w')."
11173 (interactive "P")
11174 (if (member goto '(0 (64)))
11175 (org-refile-cache-clear)
11176 (let* ((actionmsg (or msg "Refile"))
11177 (cbuf (current-buffer))
11178 (regionp (org-region-active-p))
11179 (region-start (and regionp (region-beginning)))
11180 (region-end (and regionp (region-end)))
11181 (region-length (and regionp (- region-end region-start)))
11182 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11183 pos it nbuf file re level reversed)
11184 (setq last-command nil)
11185 (when regionp
11186 (goto-char region-start)
11187 (or (bolp) (goto-char (point-at-bol)))
11188 (setq region-start (point))
11189 (unless (or (org-kill-is-subtree-p
11190 (buffer-substring region-start region-end))
11191 (prog1 org-refile-active-region-within-subtree
11192 (org-toggle-heading)))
11193 (error "The region is not a (sequence of) subtree(s)")))
11194 (if (equal goto '(16))
11195 (org-refile-goto-last-stored)
11196 (when (or
11197 (and (equal goto 2)
11198 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11199 (prog1
11200 (setq it (list (or org-clock-heading "running clock")
11201 (buffer-file-name
11202 (marker-buffer org-clock-hd-marker))
11204 (marker-position org-clock-hd-marker)))
11205 (setq goto nil)))
11206 (setq it (or rfloc
11207 (let (heading-text)
11208 (save-excursion
11209 (unless goto
11210 (org-back-to-heading t)
11211 (setq heading-text
11212 (nth 4 (org-heading-components))))
11214 (org-refile-get-location
11215 (cond (goto "Goto")
11216 (regionp (concat actionmsg " region to"))
11217 (t (concat actionmsg " subtree \""
11218 heading-text "\" to")))
11219 default-buffer
11220 (and (not (equal '(4) goto))
11221 org-refile-allow-creating-parent-nodes)
11222 goto))))))
11223 (setq file (nth 1 it)
11224 re (nth 2 it)
11225 pos (nth 3 it))
11226 (if (and (not goto)
11228 (equal (buffer-file-name) file)
11229 (if regionp
11230 (and (>= pos region-start)
11231 (<= pos region-end))
11232 (and (>= pos (point))
11233 (< pos (save-excursion
11234 (org-end-of-subtree t t))))))
11235 (error "Cannot refile to position inside the tree or region"))
11237 (setq nbuf (or (find-buffer-visiting file)
11238 (find-file-noselect file)))
11239 (if goto
11240 (progn
11241 (org-pop-to-buffer-same-window nbuf)
11242 (goto-char pos)
11243 (org-show-context 'org-goto))
11244 (if regionp
11245 (progn
11246 (org-kill-new (buffer-substring region-start region-end))
11247 (org-save-markers-in-region region-start region-end))
11248 (org-copy-subtree 1 nil t))
11249 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11250 (find-file-noselect file)))
11251 (setq reversed (org-notes-order-reversed-p))
11252 (save-excursion
11253 (save-restriction
11254 (widen)
11255 (if pos
11256 (progn
11257 (goto-char pos)
11258 (looking-at org-outline-regexp)
11259 (setq level (org-get-valid-level (funcall outline-level) 1))
11260 (goto-char
11261 (if reversed
11262 (or (outline-next-heading) (point-max))
11263 (or (save-excursion (org-get-next-sibling))
11264 (org-end-of-subtree t t)
11265 (point-max)))))
11266 (setq level 1)
11267 (if (not reversed)
11268 (goto-char (point-max))
11269 (goto-char (point-min))
11270 (or (outline-next-heading) (goto-char (point-max)))))
11271 (if (not (bolp)) (newline))
11272 (org-paste-subtree level)
11273 (when org-log-refile
11274 (org-add-log-setup 'refile nil nil 'findpos
11275 org-log-refile)
11276 (unless (eq org-log-refile 'note)
11277 (save-excursion (org-add-log-note))))
11278 (and org-auto-align-tags
11279 (let ((org-loop-over-headlines-in-active-region nil))
11280 (org-set-tags nil t)))
11281 (with-demoted-errors
11282 (bookmark-set "org-refile-last-stored"))
11283 ;; If we are refiling for capture, make sure that the
11284 ;; last-capture pointers point here
11285 (when (org-bound-and-true-p org-refile-for-capture)
11286 (with-demoted-errors
11287 (bookmark-set "org-capture-last-stored-marker"))
11288 (move-marker org-capture-last-stored-marker (point)))
11289 (if (fboundp 'deactivate-mark) (deactivate-mark))
11290 (run-hooks 'org-after-refile-insert-hook))))
11291 (unless org-refile-keep
11292 (if regionp
11293 (delete-region (point) (+ (point) region-length))
11294 (org-cut-subtree)))
11295 (when (featurep 'org-inlinetask)
11296 (org-inlinetask-remove-END-maybe))
11297 (setq org-markers-to-move nil)
11298 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11300 (defun org-refile-goto-last-stored ()
11301 "Go to the location where the last refile was stored."
11302 (interactive)
11303 (bookmark-jump "org-refile-last-stored")
11304 (message "This is the location of the last refile"))
11306 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11307 no-exclude)
11308 "Prompt the user for a refile location, using PROMPT.
11309 PROMPT should not be suffixed with a colon and a space, because
11310 this function appends the default value from
11311 `org-refile-history' automatically, if that is not empty.
11312 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11313 this is used for the GOTO interface."
11314 (let ((org-refile-targets org-refile-targets)
11315 (org-refile-use-outline-path org-refile-use-outline-path)
11316 excluded-entries)
11317 (when (and (derived-mode-p 'org-mode)
11318 (not org-refile-use-cache)
11319 (not no-exclude))
11320 (org-map-tree
11321 (lambda()
11322 (setq excluded-entries
11323 (append excluded-entries (list (org-get-heading t t)))))))
11324 (setq org-refile-target-table
11325 (org-refile-get-targets default-buffer excluded-entries)))
11326 (unless org-refile-target-table
11327 (error "No refile targets"))
11328 (let* ((cbuf (current-buffer))
11329 (partial-completion-mode nil)
11330 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11331 (cfunc (if (and org-refile-use-outline-path
11332 org-outline-path-complete-in-steps)
11333 'org-olpath-completing-read
11334 'org-icompleting-read))
11335 (extra (if org-refile-use-outline-path "/" ""))
11336 (cbnex (concat (buffer-name) extra))
11337 (filename (and cfn (expand-file-name cfn)))
11338 (tbl (mapcar
11339 (lambda (x)
11340 (if (and (not (member org-refile-use-outline-path
11341 '(file full-file-path)))
11342 (not (equal filename (nth 1 x))))
11343 (cons (concat (car x) extra " ("
11344 (file-name-nondirectory (nth 1 x)) ")")
11345 (cdr x))
11346 (cons (concat (car x) extra) (cdr x))))
11347 org-refile-target-table))
11348 (completion-ignore-case t)
11349 cdef
11350 (prompt (concat prompt
11351 (or (and (car org-refile-history)
11352 (concat " (default " (car org-refile-history) ")"))
11353 (and (assoc cbnex tbl) (setq cdef cbnex)
11354 (concat " (default " cbnex ")"))) ": "))
11355 pa answ parent-target child parent old-hist)
11356 (setq old-hist org-refile-history)
11357 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11358 nil 'org-refile-history (or cdef (car org-refile-history))))
11359 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11360 (org-refile-check-position pa)
11361 (if pa
11362 (progn
11363 (when (or (not org-refile-history)
11364 (not (eq old-hist org-refile-history))
11365 (not (equal (car pa) (car org-refile-history))))
11366 (setq org-refile-history
11367 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11368 org-refile-history
11369 (cdr org-refile-history))))
11370 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11371 (pop org-refile-history)))
11373 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11374 (progn
11375 (setq parent (match-string 1 answ)
11376 child (match-string 2 answ))
11377 (setq parent-target (or (assoc parent tbl)
11378 (assoc (concat parent "/") tbl)))
11379 (when (and parent-target
11380 (or (eq new-nodes t)
11381 (and (eq new-nodes 'confirm)
11382 (y-or-n-p (format "Create new node \"%s\"? "
11383 child)))))
11384 (org-refile-new-child parent-target child)))
11385 (error "Invalid target location")))))
11387 (declare-function org-string-nw-p "org-macs" (s))
11388 (defun org-refile-check-position (refile-pointer)
11389 "Check if the refile pointer matches the headline to which it points."
11390 (let* ((file (nth 1 refile-pointer))
11391 (re (nth 2 refile-pointer))
11392 (pos (nth 3 refile-pointer))
11393 buffer)
11394 (if (and (not (markerp pos)) (not file))
11395 (error "Please save the buffer to a file before refiling")
11396 (when (org-string-nw-p re)
11397 (setq buffer (if (markerp pos)
11398 (marker-buffer pos)
11399 (or (find-buffer-visiting file)
11400 (find-file-noselect file))))
11401 (with-current-buffer buffer
11402 (save-excursion
11403 (save-restriction
11404 (widen)
11405 (goto-char pos)
11406 (beginning-of-line 1)
11407 (unless (org-looking-at-p re)
11408 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11410 (defun org-refile-new-child (parent-target child)
11411 "Use refile target PARENT-TARGET to add new CHILD below it."
11412 (unless parent-target
11413 (error "Cannot find parent for new node"))
11414 (let ((file (nth 1 parent-target))
11415 (pos (nth 3 parent-target))
11416 level)
11417 (with-current-buffer (or (find-buffer-visiting file)
11418 (find-file-noselect file))
11419 (save-excursion
11420 (save-restriction
11421 (widen)
11422 (if pos
11423 (goto-char pos)
11424 (goto-char (point-max))
11425 (if (not (bolp)) (newline)))
11426 (when (looking-at org-outline-regexp)
11427 (setq level (funcall outline-level))
11428 (org-end-of-subtree t t))
11429 (org-back-over-empty-lines)
11430 (insert "\n" (make-string
11431 (if pos (org-get-valid-level level 1) 1) ?*)
11432 " " child "\n")
11433 (beginning-of-line 0)
11434 (list (concat (car parent-target) "/" child) file "" (point)))))))
11436 (defun org-olpath-completing-read (prompt collection &rest args)
11437 "Read an outline path like a file name."
11438 (let ((thetable collection)
11439 (org-completion-use-ido nil) ; does not work with ido.
11440 (org-completion-use-iswitchb nil)) ; or iswitchb
11441 (apply
11442 'org-icompleting-read prompt
11443 (lambda (string predicate &optional flag)
11444 (let (rtn r f (l (length string)))
11445 (cond
11446 ((eq flag nil)
11447 ;; try completion
11448 (try-completion string thetable))
11449 ((eq flag t)
11450 ;; all-completions
11451 (setq rtn (all-completions string thetable predicate))
11452 (mapcar
11453 (lambda (x)
11454 (setq r (substring x l))
11455 (if (string-match " ([^)]*)$" x)
11456 (setq f (match-string 0 x))
11457 (setq f ""))
11458 (if (string-match "/" r)
11459 (concat string (substring r 0 (match-end 0)) f)
11461 rtn))
11462 ((eq flag 'lambda)
11463 ;; exact match?
11464 (assoc string thetable)))))
11465 args)))
11467 ;;;; Dynamic blocks
11469 (defun org-find-dblock (name)
11470 "Find the first dynamic block with name NAME in the buffer.
11471 If not found, stay at current position and return nil."
11472 (let ((case-fold-search t) pos)
11473 (save-excursion
11474 (goto-char (point-min))
11475 (setq pos (and (re-search-forward
11476 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11477 (match-beginning 0))))
11478 (if pos (goto-char pos))
11479 pos))
11481 (defconst org-dblock-start-re
11482 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11483 "Matches the start line of a dynamic block, with parameters.")
11485 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11486 "Matches the end of a dynamic block.")
11488 (defun org-create-dblock (plist)
11489 "Create a dynamic block section, with parameters taken from PLIST.
11490 PLIST must contain a :name entry which is used as name of the block."
11491 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11492 (end-of-line 1)
11493 (newline))
11494 (let ((col (current-column))
11495 (name (plist-get plist :name)))
11496 (insert "#+BEGIN: " name)
11497 (while plist
11498 (if (eq (car plist) :name)
11499 (setq plist (cddr plist))
11500 (insert " " (prin1-to-string (pop plist)))))
11501 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11502 (beginning-of-line -2)))
11504 (defun org-prepare-dblock ()
11505 "Prepare dynamic block for refresh.
11506 This empties the block, puts the cursor at the insert position and returns
11507 the property list including an extra property :name with the block name."
11508 (unless (looking-at org-dblock-start-re)
11509 (error "Not at a dynamic block"))
11510 (let* ((begdel (1+ (match-end 0)))
11511 (name (org-no-properties (match-string 1)))
11512 (params (append (list :name name)
11513 (read (concat "(" (match-string 3) ")")))))
11514 (save-excursion
11515 (beginning-of-line 1)
11516 (skip-chars-forward " \t")
11517 (setq params (plist-put params :indentation-column (current-column))))
11518 (unless (re-search-forward org-dblock-end-re nil t)
11519 (error "Dynamic block not terminated"))
11520 (setq params
11521 (append params
11522 (list :content (buffer-substring
11523 begdel (match-beginning 0)))))
11524 (delete-region begdel (match-beginning 0))
11525 (goto-char begdel)
11526 (open-line 1)
11527 params))
11529 (defun org-map-dblocks (&optional command)
11530 "Apply COMMAND to all dynamic blocks in the current buffer.
11531 If COMMAND is not given, use `org-update-dblock'."
11532 (let ((cmd (or command 'org-update-dblock)))
11533 (save-excursion
11534 (goto-char (point-min))
11535 (while (re-search-forward org-dblock-start-re nil t)
11536 (goto-char (match-beginning 0))
11537 (save-excursion
11538 (condition-case nil
11539 (funcall cmd)
11540 (error (message "Error during update of dynamic block"))))
11541 (unless (re-search-forward org-dblock-end-re nil t)
11542 (error "Dynamic block not terminated"))))))
11544 (defun org-dblock-update (&optional arg)
11545 "User command for updating dynamic blocks.
11546 Update the dynamic block at point. With prefix ARG, update all dynamic
11547 blocks in the buffer."
11548 (interactive "P")
11549 (if arg
11550 (org-update-all-dblocks)
11551 (or (looking-at org-dblock-start-re)
11552 (org-beginning-of-dblock))
11553 (org-update-dblock)))
11555 (defun org-update-dblock ()
11556 "Update the dynamic block at point.
11557 This means to empty the block, parse for parameters and then call
11558 the correct writing function."
11559 (interactive)
11560 (save-window-excursion
11561 (let* ((pos (point))
11562 (line (org-current-line))
11563 (params (org-prepare-dblock))
11564 (name (plist-get params :name))
11565 (indent (plist-get params :indentation-column))
11566 (cmd (intern (concat "org-dblock-write:" name))))
11567 (message "Updating dynamic block `%s' at line %d..." name line)
11568 (funcall cmd params)
11569 (message "Updating dynamic block `%s' at line %d...done" name line)
11570 (goto-char pos)
11571 (when (and indent (> indent 0))
11572 (setq indent (make-string indent ?\ ))
11573 (save-excursion
11574 (org-beginning-of-dblock)
11575 (forward-line 1)
11576 (while (not (looking-at org-dblock-end-re))
11577 (insert indent)
11578 (beginning-of-line 2))
11579 (when (looking-at org-dblock-end-re)
11580 (and (looking-at "[ \t]+")
11581 (replace-match ""))
11582 (insert indent)))))))
11584 (defun org-beginning-of-dblock ()
11585 "Find the beginning of the dynamic block at point.
11586 Error if there is no such block at point."
11587 (let ((pos (point))
11588 beg)
11589 (end-of-line 1)
11590 (if (and (re-search-backward org-dblock-start-re nil t)
11591 (setq beg (match-beginning 0))
11592 (re-search-forward org-dblock-end-re nil t)
11593 (> (match-end 0) pos))
11594 (goto-char beg)
11595 (goto-char pos)
11596 (error "Not in a dynamic block"))))
11598 (defun org-update-all-dblocks ()
11599 "Update all dynamic blocks in the buffer.
11600 This function can be used in a hook."
11601 (interactive)
11602 (when (derived-mode-p 'org-mode)
11603 (org-map-dblocks 'org-update-dblock)))
11606 ;;;; Completion
11608 (defun org-get-export-keywords ()
11609 "Return a list of all currently understood export keywords.
11610 Export keywords include options, block names, attributes and
11611 keywords relative to each registered export back-end."
11612 (delq nil
11613 (let (keywords)
11614 (mapc
11615 (lambda (back-end)
11616 (let ((props (cdr back-end)))
11617 ;; Back-end name (for keywords, like #+LATEX:)
11618 (push (upcase (symbol-name (car back-end))) keywords)
11619 ;; Back-end options.
11620 (mapc (lambda (option) (push (cadr option) keywords))
11621 (plist-get (cdr back-end) :options-alist))))
11622 (org-bound-and-true-p org-export-registered-backends))
11623 keywords)))
11625 (defconst org-options-keywords
11626 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11627 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11628 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11629 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11630 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11632 (defcustom org-structure-template-alist
11633 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11634 "<src lang=\"?\">\n\n</src>")
11635 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11636 "<example>\n?\n</example>")
11637 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11638 "<quote>\n?\n</quote>")
11639 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11640 "<verse>\n?\n</verse>")
11641 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11642 "<verbatim>\n?\n</verbatim>")
11643 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11644 "<center>\n?\n</center>")
11645 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11646 "<literal style=\"latex\">\n?\n</literal>")
11647 ("L" "#+LaTeX: "
11648 "<literal style=\"latex\">?</literal>")
11649 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11650 "<literal style=\"html\">\n?\n</literal>")
11651 ("H" "#+HTML: "
11652 "<literal style=\"html\">?</literal>")
11653 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11654 ("A" "#+ASCII: ")
11655 ("i" "#+INDEX: ?"
11656 "#+INDEX: ?")
11657 ("I" "#+INCLUDE: %file ?"
11658 "<include file=%file markup=\"?\">"))
11659 "Structure completion elements.
11660 This is a list of abbreviation keys and values. The value gets inserted
11661 if you type `<' followed by the key and then press the completion key,
11662 usually `M-TAB'. %file will be replaced by a file name after prompting
11663 for the file using completion. The cursor will be placed at the position
11664 of the `?` in the template.
11665 There are two templates for each key, the first uses the original Org syntax,
11666 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11667 the default when the /org-mtags.el/ module has been loaded. See also the
11668 variable `org-mtags-prefer-muse-templates'."
11669 :group 'org-completion
11670 :type '(repeat
11671 (string :tag "Key")
11672 (string :tag "Template")
11673 (string :tag "Muse Template")))
11675 (defun org-try-structure-completion ()
11676 "Try to complete a structure template before point.
11677 This looks for strings like \"<e\" on an otherwise empty line and
11678 expands them."
11679 (let ((l (buffer-substring (point-at-bol) (point)))
11681 (when (and (looking-at "[ \t]*$")
11682 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11683 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11684 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11685 (match-beginning 1)) a)
11686 t)))
11688 (defun org-complete-expand-structure-template (start cell)
11689 "Expand a structure template."
11690 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11691 (rpl (nth (if musep 2 1) cell))
11692 (ind ""))
11693 (delete-region start (point))
11694 (when (string-match "\\`#\\+" rpl)
11695 (cond
11696 ((bolp))
11697 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11698 (setq ind (buffer-substring (point-at-bol) (point))))
11699 (t (newline))))
11700 (setq start (point))
11701 (if (string-match "%file" rpl)
11702 (setq rpl (replace-match
11703 (concat
11704 "\""
11705 (save-match-data
11706 (abbreviate-file-name (read-file-name "Include file: ")))
11707 "\"")
11708 t t rpl)))
11709 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11710 (concat "\n" ind)))
11711 (insert rpl)
11712 (if (re-search-backward "\\?" start t) (delete-char 1))))
11714 ;;;; TODO, DEADLINE, Comments
11716 (defun org-toggle-comment ()
11717 "Change the COMMENT state of an entry."
11718 (interactive)
11719 (save-excursion
11720 (org-back-to-heading)
11721 (let (case-fold-search)
11722 (cond
11723 ((looking-at (format org-heading-keyword-regexp-format
11724 org-comment-string))
11725 (goto-char (match-end 1))
11726 (looking-at (concat " +" org-comment-string))
11727 (replace-match "" t t)
11728 (when (eolp) (insert " ")))
11729 ((looking-at org-outline-regexp)
11730 (goto-char (match-end 0))
11731 (insert org-comment-string " "))))))
11733 (defvar org-last-todo-state-is-todo nil
11734 "This is non-nil when the last TODO state change led to a TODO state.
11735 If the last change removed the TODO tag or switched to DONE, then
11736 this is nil.")
11738 (defvar org-setting-tags nil) ; dynamically skipped
11740 (defvar org-todo-setup-filter-hook nil
11741 "Hook for functions that pre-filter todo specs.
11742 Each function takes a todo spec and returns either nil or the spec
11743 transformed into canonical form." )
11745 (defvar org-todo-get-default-hook nil
11746 "Hook for functions that get a default item for todo.
11747 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11748 nil or a string to be used for the todo mark." )
11750 (defvar org-agenda-headline-snapshot-before-repeat)
11752 (defun org-current-effective-time ()
11753 "Return current time adjusted for `org-extend-today-until' variable."
11754 (let* ((ct (org-current-time))
11755 (dct (decode-time ct))
11756 (ct1
11757 (cond
11758 (org-use-last-clock-out-time-as-effective-time
11759 (or (org-clock-get-last-clock-out-time) ct))
11760 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11761 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11762 (t ct))))
11763 ct1))
11765 (defun org-todo-yesterday (&optional arg)
11766 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11767 (interactive "P")
11768 (if (eq major-mode 'org-agenda-mode)
11769 (apply 'org-agenda-todo-yesterday arg)
11770 (let* ((hour (third (decode-time
11771 (org-current-time))))
11772 (org-extend-today-until (1+ hour)))
11773 (org-todo arg))))
11775 (defvar org-block-entry-blocking ""
11776 "First entry preventing the TODO state change.")
11778 (defun org-todo (&optional arg)
11779 "Change the TODO state of an item.
11780 The state of an item is given by a keyword at the start of the heading,
11781 like
11782 *** TODO Write paper
11783 *** DONE Call mom
11785 The different keywords are specified in the variable `org-todo-keywords'.
11786 By default the available states are \"TODO\" and \"DONE\".
11787 So for this example: when the item starts with TODO, it is changed to DONE.
11788 When it starts with DONE, the DONE is removed. And when neither TODO nor
11789 DONE are present, add TODO at the beginning of the heading.
11791 With \\[universal-argument] prefix arg, use completion to determine the new \
11792 state.
11793 With numeric prefix arg, switch to that state.
11794 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11795 keywords (nextset).
11796 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11797 With a numeric prefix arg of 0, inhibit note taking for the change.
11799 For calling through lisp, arg is also interpreted in the following way:
11800 'none -> empty state
11801 \"\"(empty string) -> switch to empty state
11802 'done -> switch to DONE
11803 'nextset -> switch to the next set of keywords
11804 'previousset -> switch to the previous set of keywords
11805 \"WAITING\" -> switch to the specified keyword, but only if it
11806 really is a member of `org-todo-keywords'."
11807 (interactive "P")
11808 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11809 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11810 'region-start-level 'region))
11811 org-loop-over-headlines-in-active-region)
11812 (org-map-entries
11813 `(org-todo ,arg)
11814 org-loop-over-headlines-in-active-region
11815 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11816 (if (equal arg '(16)) (setq arg 'nextset))
11817 (let ((org-blocker-hook org-blocker-hook)
11818 commentp
11819 case-fold-search)
11820 (when (equal arg '(64))
11821 (setq arg nil org-blocker-hook nil))
11822 (when (and org-blocker-hook
11823 (or org-inhibit-blocking
11824 (org-entry-get nil "NOBLOCKING")))
11825 (setq org-blocker-hook nil))
11826 (save-excursion
11827 (catch 'exit
11828 (org-back-to-heading t)
11829 (when (looking-at (concat "^\\*+ " org-comment-string))
11830 (org-toggle-comment)
11831 (setq commentp t))
11832 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11833 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11834 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11835 (let* ((match-data (match-data))
11836 (startpos (point-at-bol))
11837 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11838 (org-log-done org-log-done)
11839 (org-log-repeat org-log-repeat)
11840 (org-todo-log-states org-todo-log-states)
11841 (org-inhibit-logging
11842 (if (equal arg 0)
11843 (progn (setq arg nil) 'note) org-inhibit-logging))
11844 (this (match-string 1))
11845 (hl-pos (match-beginning 0))
11846 (head (org-get-todo-sequence-head this))
11847 (ass (assoc head org-todo-kwd-alist))
11848 (interpret (nth 1 ass))
11849 (done-word (nth 3 ass))
11850 (final-done-word (nth 4 ass))
11851 (org-last-state (or this ""))
11852 (completion-ignore-case t)
11853 (member (member this org-todo-keywords-1))
11854 (tail (cdr member))
11855 (org-state (cond
11856 ((and org-todo-key-trigger
11857 (or (and (equal arg '(4))
11858 (eq org-use-fast-todo-selection 'prefix))
11859 (and (not arg) org-use-fast-todo-selection
11860 (not (eq org-use-fast-todo-selection
11861 'prefix)))))
11862 ;; Use fast selection
11863 (org-fast-todo-selection))
11864 ((and (equal arg '(4))
11865 (or (not org-use-fast-todo-selection)
11866 (not org-todo-key-trigger)))
11867 ;; Read a state with completion
11868 (org-icompleting-read
11869 "State: " (mapcar (lambda(x) (list x))
11870 org-todo-keywords-1)
11871 nil t))
11872 ((eq arg 'right)
11873 (if this
11874 (if tail (car tail) nil)
11875 (car org-todo-keywords-1)))
11876 ((eq arg 'left)
11877 (if (equal member org-todo-keywords-1)
11879 (if this
11880 (nth (- (length org-todo-keywords-1)
11881 (length tail) 2)
11882 org-todo-keywords-1)
11883 (org-last org-todo-keywords-1))))
11884 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11885 (setq arg nil))) ; hack to fall back to cycling
11886 (arg
11887 ;; user or caller requests a specific state
11888 (cond
11889 ((equal arg "") nil)
11890 ((eq arg 'none) nil)
11891 ((eq arg 'done) (or done-word (car org-done-keywords)))
11892 ((eq arg 'nextset)
11893 (or (car (cdr (member head org-todo-heads)))
11894 (car org-todo-heads)))
11895 ((eq arg 'previousset)
11896 (let ((org-todo-heads (reverse org-todo-heads)))
11897 (or (car (cdr (member head org-todo-heads)))
11898 (car org-todo-heads))))
11899 ((car (member arg org-todo-keywords-1)))
11900 ((stringp arg)
11901 (error "State `%s' not valid in this file" arg))
11902 ((nth (1- (prefix-numeric-value arg))
11903 org-todo-keywords-1))))
11904 ((null member) (or head (car org-todo-keywords-1)))
11905 ((equal this final-done-word) nil) ;; -> make empty
11906 ((null tail) nil) ;; -> first entry
11907 ((memq interpret '(type priority))
11908 (if (eq this-command last-command)
11909 (car tail)
11910 (if (> (length tail) 0)
11911 (or done-word (car org-done-keywords))
11912 nil)))
11914 (car tail))))
11915 (org-state (or
11916 (run-hook-with-args-until-success
11917 'org-todo-get-default-hook org-state org-last-state)
11918 org-state))
11919 (next (if org-state (concat " " org-state " ") " "))
11920 (change-plist (list :type 'todo-state-change :from this :to org-state
11921 :position startpos))
11922 dolog now-done-p)
11923 (when org-blocker-hook
11924 (setq org-last-todo-state-is-todo
11925 (not (member this org-done-keywords)))
11926 (unless (save-excursion
11927 (save-match-data
11928 (org-with-wide-buffer
11929 (run-hook-with-args-until-failure
11930 'org-blocker-hook change-plist))))
11931 (if (org-called-interactively-p 'interactive)
11932 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11933 this org-state org-block-entry-blocking)
11934 ;; fail silently
11935 (message "TODO state change from %s to %s blocked (by \"%s\")"
11936 this org-state org-block-entry-blocking)
11937 (throw 'exit nil))))
11938 (store-match-data match-data)
11939 (replace-match next t t)
11940 (unless (pos-visible-in-window-p hl-pos)
11941 (message "TODO state changed to %s" (org-trim next)))
11942 (unless head
11943 (setq head (org-get-todo-sequence-head org-state)
11944 ass (assoc head org-todo-kwd-alist)
11945 interpret (nth 1 ass)
11946 done-word (nth 3 ass)
11947 final-done-word (nth 4 ass)))
11948 (when (memq arg '(nextset previousset))
11949 (message "Keyword-Set %d/%d: %s"
11950 (- (length org-todo-sets) -1
11951 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11952 (length org-todo-sets)
11953 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11954 (setq org-last-todo-state-is-todo
11955 (not (member org-state org-done-keywords)))
11956 (setq now-done-p (and (member org-state org-done-keywords)
11957 (not (member this org-done-keywords))))
11958 (and logging (org-local-logging logging))
11959 (when (and (or org-todo-log-states org-log-done)
11960 (not (eq org-inhibit-logging t))
11961 (not (memq arg '(nextset previousset))))
11962 ;; we need to look at recording a time and note
11963 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11964 (nth 2 (assoc this org-todo-log-states))))
11965 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11966 (setq dolog 'time))
11967 (when (and org-state
11968 (member org-state org-not-done-keywords)
11969 (not (member this org-not-done-keywords)))
11970 ;; This is now a todo state and was not one before
11971 ;; If there was a CLOSED time stamp, get rid of it.
11972 (org-add-planning-info nil nil 'closed))
11973 (when (and now-done-p org-log-done)
11974 ;; It is now done, and it was not done before
11975 (org-add-planning-info 'closed (org-current-effective-time))
11976 (if (and (not dolog) (eq 'note org-log-done))
11977 (org-add-log-setup 'done org-state this 'findpos 'note)))
11978 (when (and org-state dolog)
11979 ;; This is a non-nil state, and we need to log it
11980 (org-add-log-setup 'state org-state this 'findpos dolog)))
11981 ;; Fixup tag positioning
11982 (org-todo-trigger-tag-changes org-state)
11983 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11984 (when org-provide-todo-statistics
11985 (org-update-parent-todo-statistics))
11986 (run-hooks 'org-after-todo-state-change-hook)
11987 (if (and arg (not (member org-state org-done-keywords)))
11988 (setq head (org-get-todo-sequence-head org-state)))
11989 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11990 ;; Do we need to trigger a repeat?
11991 (when now-done-p
11992 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11993 ;; This is for the agenda, take a snapshot of the headline.
11994 (save-match-data
11995 (setq org-agenda-headline-snapshot-before-repeat
11996 (org-get-heading))))
11997 (org-auto-repeat-maybe org-state))
11998 ;; Fixup cursor location if close to the keyword
11999 (if (and (outline-on-heading-p)
12000 (not (bolp))
12001 (save-excursion (beginning-of-line 1)
12002 (looking-at org-todo-line-regexp))
12003 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12004 (progn
12005 (goto-char (or (match-end 2) (match-end 1)))
12006 (and (looking-at " ") (just-one-space))))
12007 (when org-trigger-hook
12008 (save-excursion
12009 (run-hook-with-args 'org-trigger-hook change-plist)))
12010 (when commentp (org-toggle-comment))))))))
12012 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12013 "Block turning an entry into a TODO, using the hierarchy.
12014 This checks whether the current task should be blocked from state
12015 changes. Such blocking occurs when:
12017 1. The task has children which are not all in a completed state.
12019 2. A task has a parent with the property :ORDERED:, and there
12020 are siblings prior to the current task with incomplete
12021 status.
12023 3. The parent of the task is blocked because it has siblings that should
12024 be done first, or is child of a block grandparent TODO entry."
12026 (if (not org-enforce-todo-dependencies)
12027 t ; if locally turned off don't block
12028 (catch 'dont-block
12029 ;; If this is not a todo state change, or if this entry is already DONE,
12030 ;; do not block
12031 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12032 (member (plist-get change-plist :from)
12033 (cons 'done org-done-keywords))
12034 (member (plist-get change-plist :to)
12035 (cons 'todo org-not-done-keywords))
12036 (not (plist-get change-plist :to)))
12037 (throw 'dont-block t))
12038 ;; If this task has children, and any are undone, it's blocked
12039 (save-excursion
12040 (org-back-to-heading t)
12041 (let ((this-level (funcall outline-level)))
12042 (outline-next-heading)
12043 (let ((child-level (funcall outline-level)))
12044 (while (and (not (eobp))
12045 (> child-level this-level))
12046 ;; this todo has children, check whether they are all
12047 ;; completed
12048 (if (and (not (org-entry-is-done-p))
12049 (org-entry-is-todo-p))
12050 (progn (setq org-block-entry-blocking (org-get-heading))
12051 (throw 'dont-block nil)))
12052 (outline-next-heading)
12053 (setq child-level (funcall outline-level))))))
12054 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12055 ;; any previous siblings are undone, it's blocked
12056 (save-excursion
12057 (org-back-to-heading t)
12058 (let* ((pos (point))
12059 (parent-pos (and (org-up-heading-safe) (point))))
12060 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12061 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12062 (forward-line 1)
12063 (re-search-forward org-not-done-heading-regexp pos t))
12064 (setq org-block-entry-blocking (match-string 0))
12065 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12066 ;; Search further up the hierarchy, to see if an ancestor is blocked
12067 (while t
12068 (goto-char parent-pos)
12069 (if (not (looking-at org-not-done-heading-regexp))
12070 (throw 'dont-block t)) ; do not block, parent is not a TODO
12071 (setq pos (point))
12072 (setq parent-pos (and (org-up-heading-safe) (point)))
12073 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12074 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12075 (forward-line 1)
12076 (re-search-forward org-not-done-heading-regexp pos t)
12077 (setq org-block-entry-blocking (org-get-heading)))
12078 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12080 (defcustom org-track-ordered-property-with-tag nil
12081 "Should the ORDERED property also be shown as a tag?
12082 The ORDERED property decides if an entry should require subtasks to be
12083 completed in sequence. Since a property is not very visible, setting
12084 this option means that toggling the ORDERED property with the command
12085 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12086 not relevant for the behavior, but it makes things more visible.
12088 Note that toggling the tag with tags commands will not change the property
12089 and therefore not influence behavior!
12091 This can be t, meaning the tag ORDERED should be used, It can also be a
12092 string to select a different tag for this task."
12093 :group 'org-todo
12094 :type '(choice
12095 (const :tag "No tracking" nil)
12096 (const :tag "Track with ORDERED tag" t)
12097 (string :tag "Use other tag")))
12099 (defun org-toggle-ordered-property ()
12100 "Toggle the ORDERED property of the current entry.
12101 For better visibility, you can track the value of this property with a tag.
12102 See variable `org-track-ordered-property-with-tag'."
12103 (interactive)
12104 (let* ((t1 org-track-ordered-property-with-tag)
12105 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12106 (save-excursion
12107 (org-back-to-heading)
12108 (if (org-entry-get nil "ORDERED")
12109 (progn
12110 (org-delete-property "ORDERED" "PROPERTIES")
12111 (and tag (org-toggle-tag tag 'off))
12112 (message "Subtasks can be completed in arbitrary order"))
12113 (org-entry-put nil "ORDERED" "t")
12114 (and tag (org-toggle-tag tag 'on))
12115 (message "Subtasks must be completed in sequence")))))
12117 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12118 (defun org-block-todo-from-checkboxes (change-plist)
12119 "Block turning an entry into a TODO, using checkboxes.
12120 This checks whether the current task should be blocked from state
12121 changes because there are unchecked boxes in this entry."
12122 (if (not org-enforce-todo-checkbox-dependencies)
12123 t ; if locally turned off don't block
12124 (catch 'dont-block
12125 ;; If this is not a todo state change, or if this entry is already DONE,
12126 ;; do not block
12127 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12128 (member (plist-get change-plist :from)
12129 (cons 'done org-done-keywords))
12130 (member (plist-get change-plist :to)
12131 (cons 'todo org-not-done-keywords))
12132 (not (plist-get change-plist :to)))
12133 (throw 'dont-block t))
12134 ;; If this task has checkboxes that are not checked, it's blocked
12135 (save-excursion
12136 (org-back-to-heading t)
12137 (let ((beg (point)) end)
12138 (outline-next-heading)
12139 (setq end (point))
12140 (goto-char beg)
12141 (if (org-list-search-forward
12142 (concat (org-item-beginning-re)
12143 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12144 "\\[[- ]\\]")
12145 end t)
12146 (progn
12147 (if (boundp 'org-blocked-by-checkboxes)
12148 (setq org-blocked-by-checkboxes t))
12149 (throw 'dont-block nil)))))
12150 t))) ; do not block
12152 (defun org-entry-blocked-p ()
12153 "Is the current entry blocked?"
12154 (org-with-buffer-modified-unmodified
12155 (if (org-entry-get nil "NOBLOCKING")
12156 nil ;; Never block this entry
12157 (not
12158 (run-hook-with-args-until-failure
12159 'org-blocker-hook
12160 (list :type 'todo-state-change
12161 :position (point)
12162 :from 'todo
12163 :to 'done))))))
12165 (defun org-update-statistics-cookies (all)
12166 "Update the statistics cookie, either from TODO or from checkboxes.
12167 This should be called with the cursor in a line with a statistics cookie."
12168 (interactive "P")
12169 (if all
12170 (progn
12171 (org-update-checkbox-count 'all)
12172 (org-map-entries 'org-update-parent-todo-statistics))
12173 (if (not (org-at-heading-p))
12174 (org-update-checkbox-count)
12175 (let ((pos (point-marker))
12176 end l1 l2)
12177 (ignore-errors (org-back-to-heading t))
12178 (if (not (org-at-heading-p))
12179 (org-update-checkbox-count)
12180 (setq l1 (org-outline-level))
12181 (setq end (save-excursion
12182 (outline-next-heading)
12183 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12184 (point)))
12185 (if (and (save-excursion
12186 (re-search-forward
12187 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12188 (not (save-excursion (re-search-forward
12189 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12190 (org-update-checkbox-count)
12191 (if (and l2 (> l2 l1))
12192 (progn
12193 (goto-char end)
12194 (org-update-parent-todo-statistics))
12195 (goto-char pos)
12196 (beginning-of-line 1)
12197 (while (re-search-forward
12198 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12199 (point-at-eol) t)
12200 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12201 (goto-char pos)
12202 (move-marker pos nil)))))
12204 (defvar org-entry-property-inherited-from) ;; defined below
12205 (defun org-update-parent-todo-statistics ()
12206 "Update any statistics cookie in the parent of the current headline.
12207 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12208 the entire subtree and this will travel up the hierarchy and update
12209 statistics everywhere."
12210 (let* ((prop (save-excursion (org-up-heading-safe)
12211 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12212 (recursive (or (not org-hierarchical-todo-statistics)
12213 (and prop (string-match "\\<recursive\\>" prop))))
12214 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12216 (first t)
12217 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12218 level ltoggle l1 new ndel
12219 (cnt-all 0) (cnt-done 0) is-percent kwd
12220 checkbox-beg ov ovs ove cookie-present)
12221 (catch 'exit
12222 (save-excursion
12223 (beginning-of-line 1)
12224 (setq ltoggle (funcall outline-level))
12225 ;; Three situations are to consider:
12227 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12228 ;; to the top-level ancestor on the headline;
12230 ;; 2. If parent has "recursive" property, repeat up to the
12231 ;; headline setting that property, taking inheritance into
12232 ;; account;
12234 ;; 3. Else, move up to direct parent and proceed only once.
12235 (while (and (setq level (org-up-heading-safe))
12236 (or recursive first)
12237 (>= (point) lim))
12238 (setq first nil cookie-present nil)
12239 (unless (and level
12240 (not (string-match
12241 "\\<checkbox\\>"
12242 (downcase (or (org-entry-get nil "COOKIE_DATA")
12243 "")))))
12244 (throw 'exit nil))
12245 (while (re-search-forward box-re (point-at-eol) t)
12246 (setq cnt-all 0 cnt-done 0 cookie-present t)
12247 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12248 (save-match-data
12249 (unless (outline-next-heading) (throw 'exit nil))
12250 (while (and (looking-at org-complex-heading-regexp)
12251 (> (setq l1 (length (match-string 1))) level))
12252 (setq kwd (and (or recursive (= l1 ltoggle))
12253 (match-string 2)))
12254 (if (or (eq org-provide-todo-statistics 'all-headlines)
12255 (and (listp org-provide-todo-statistics)
12256 (or (member kwd org-provide-todo-statistics)
12257 (member kwd org-done-keywords))))
12258 (setq cnt-all (1+ cnt-all))
12259 (if (eq org-provide-todo-statistics t)
12260 (and kwd (setq cnt-all (1+ cnt-all)))))
12261 (and (member kwd org-done-keywords)
12262 (setq cnt-done (1+ cnt-done)))
12263 (outline-next-heading)))
12264 (setq new
12265 (if is-percent
12266 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12267 (format "[%d/%d]" cnt-done cnt-all))
12268 ndel (- (match-end 0) checkbox-beg))
12269 ;; handle overlays when updating cookie from column view
12270 (when (setq ov (car (overlays-at checkbox-beg)))
12271 (setq ovs (overlay-start ov) ove (overlay-end ov))
12272 (delete-overlay ov))
12273 (goto-char checkbox-beg)
12274 (insert new)
12275 (delete-region (point) (+ (point) ndel))
12276 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12277 (when ov (move-overlay ov ovs ove)))
12278 (when cookie-present
12279 (run-hook-with-args 'org-after-todo-statistics-hook
12280 cnt-done (- cnt-all cnt-done))))))
12281 (run-hooks 'org-todo-statistics-hook)))
12283 (defvar org-after-todo-statistics-hook nil
12284 "Hook that is called after a TODO statistics cookie has been updated.
12285 Each function is called with two arguments: the number of not-done entries
12286 and the number of done entries.
12288 For example, the following function, when added to this hook, will switch
12289 an entry to DONE when all children are done, and back to TODO when new
12290 entries are set to a TODO status. Note that this hook is only called
12291 when there is a statistics cookie in the headline!
12293 (defun org-summary-todo (n-done n-not-done)
12294 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12295 (let (org-log-done org-log-states) ; turn off logging
12296 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12299 (defvar org-todo-statistics-hook nil
12300 "Hook that is run whenever Org thinks TODO statistics should be updated.
12301 This hook runs even if there is no statistics cookie present, in which case
12302 `org-after-todo-statistics-hook' would not run.")
12304 (defun org-todo-trigger-tag-changes (state)
12305 "Apply the changes defined in `org-todo-state-tags-triggers'."
12306 (let ((l org-todo-state-tags-triggers)
12307 changes)
12308 (when (or (not state) (equal state ""))
12309 (setq changes (append changes (cdr (assoc "" l)))))
12310 (when (and (stringp state) (> (length state) 0))
12311 (setq changes (append changes (cdr (assoc state l)))))
12312 (when (member state org-not-done-keywords)
12313 (setq changes (append changes (cdr (assoc 'todo l)))))
12314 (when (member state org-done-keywords)
12315 (setq changes (append changes (cdr (assoc 'done l)))))
12316 (dolist (c changes)
12317 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12319 (defun org-local-logging (value)
12320 "Get logging settings from a property VALUE."
12321 (let* (words w a)
12322 ;; directly set the variables, they are already local.
12323 (setq org-log-done nil
12324 org-log-repeat nil
12325 org-todo-log-states nil)
12326 (setq words (org-split-string value))
12327 (while (setq w (pop words))
12328 (cond
12329 ((setq a (assoc w org-startup-options))
12330 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12331 (set (nth 1 a) (nth 2 a))))
12332 ((setq a (org-extract-log-state-settings w))
12333 (and (member (car a) org-todo-keywords-1)
12334 (push a org-todo-log-states)))))))
12336 (defun org-get-todo-sequence-head (kwd)
12337 "Return the head of the TODO sequence to which KWD belongs.
12338 If KWD is not set, check if there is a text property remembering the
12339 right sequence."
12340 (let (p)
12341 (cond
12342 ((not kwd)
12343 (or (get-text-property (point-at-bol) 'org-todo-head)
12344 (progn
12345 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12346 nil (point-at-eol)))
12347 (get-text-property p 'org-todo-head))))
12348 ((not (member kwd org-todo-keywords-1))
12349 (car org-todo-keywords-1))
12350 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12352 (defun org-fast-todo-selection ()
12353 "Fast TODO keyword selection with single keys.
12354 Returns the new TODO keyword, or nil if no state change should occur."
12355 (let* ((fulltable org-todo-key-alist)
12356 (done-keywords org-done-keywords) ;; needed for the faces.
12357 (maxlen (apply 'max (mapcar
12358 (lambda (x)
12359 (if (stringp (car x)) (string-width (car x)) 0))
12360 fulltable)))
12361 (expert nil)
12362 (fwidth (+ maxlen 3 1 3))
12363 (ncol (/ (- (window-width) 4) fwidth))
12364 tg cnt e c tbl
12365 groups ingroup)
12366 (save-excursion
12367 (save-window-excursion
12368 (if expert
12369 (set-buffer (get-buffer-create " *Org todo*"))
12370 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12371 (erase-buffer)
12372 (org-set-local 'org-done-keywords done-keywords)
12373 (setq tbl fulltable cnt 0)
12374 (while (setq e (pop tbl))
12375 (cond
12376 ((equal e '(:startgroup))
12377 (push '() groups) (setq ingroup t)
12378 (when (not (= cnt 0))
12379 (setq cnt 0)
12380 (insert "\n"))
12381 (insert "{ "))
12382 ((equal e '(:endgroup))
12383 (setq ingroup nil cnt 0)
12384 (insert "}\n"))
12385 ((equal e '(:newline))
12386 (when (not (= cnt 0))
12387 (setq cnt 0)
12388 (insert "\n")
12389 (setq e (car tbl))
12390 (while (equal (car tbl) '(:newline))
12391 (insert "\n")
12392 (setq tbl (cdr tbl)))))
12394 (setq tg (car e) c (cdr e))
12395 (if ingroup (push tg (car groups)))
12396 (setq tg (org-add-props tg nil 'face
12397 (org-get-todo-face tg)))
12398 (if (and (= cnt 0) (not ingroup)) (insert " "))
12399 (insert "[" c "] " tg (make-string
12400 (- fwidth 4 (length tg)) ?\ ))
12401 (when (= (setq cnt (1+ cnt)) ncol)
12402 (insert "\n")
12403 (if ingroup (insert " "))
12404 (setq cnt 0)))))
12405 (insert "\n")
12406 (goto-char (point-min))
12407 (if (not expert) (org-fit-window-to-buffer))
12408 (message "[a-z..]:Set [SPC]:clear")
12409 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12410 (cond
12411 ((or (= c ?\C-g)
12412 (and (= c ?q) (not (rassoc c fulltable))))
12413 (setq quit-flag t))
12414 ((= c ?\ ) nil)
12415 ((setq e (rassoc c fulltable) tg (car e))
12417 (t (setq quit-flag t)))))))
12419 (defun org-entry-is-todo-p ()
12420 (member (org-get-todo-state) org-not-done-keywords))
12422 (defun org-entry-is-done-p ()
12423 (member (org-get-todo-state) org-done-keywords))
12425 (defun org-get-todo-state ()
12426 (save-excursion
12427 (org-back-to-heading t)
12428 (and (looking-at org-todo-line-regexp)
12429 (match-end 2)
12430 (match-string 2))))
12432 (defun org-at-date-range-p (&optional inactive-ok)
12433 "Is the cursor inside a date range?"
12434 (interactive)
12435 (save-excursion
12436 (catch 'exit
12437 (let ((pos (point)))
12438 (skip-chars-backward "^[<\r\n")
12439 (skip-chars-backward "<[")
12440 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12441 (>= (match-end 0) pos)
12442 (throw 'exit t))
12443 (skip-chars-backward "^<[\r\n")
12444 (skip-chars-backward "<[")
12445 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12446 (>= (match-end 0) pos)
12447 (throw 'exit t)))
12448 nil)))
12450 (defun org-get-repeat (&optional tagline)
12451 "Check if there is a deadline/schedule with repeater in this entry."
12452 (save-match-data
12453 (save-excursion
12454 (org-back-to-heading t)
12455 (and (re-search-forward (if tagline
12456 (concat tagline "\\s-*" org-repeat-re)
12457 org-repeat-re)
12458 (org-entry-end-position) t)
12459 (match-string-no-properties 1)))))
12461 (defvar org-last-changed-timestamp)
12462 (defvar org-last-inserted-timestamp)
12463 (defvar org-log-post-message)
12464 (defvar org-log-note-purpose)
12465 (defvar org-log-note-how)
12466 (defvar org-log-note-extra)
12467 (defun org-auto-repeat-maybe (done-word)
12468 "Check if the current headline contains a repeated deadline/schedule.
12469 If yes, set TODO state back to what it was and change the base date
12470 of repeating deadline/scheduled time stamps to new date.
12471 This function is run automatically after each state change to a DONE state."
12472 ;; last-state is dynamically scoped into this function
12473 (let* ((repeat (org-get-repeat))
12474 (aa (assoc org-last-state org-todo-kwd-alist))
12475 (interpret (nth 1 aa))
12476 (head (nth 2 aa))
12477 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12478 (msg "Entry repeats: ")
12479 (org-log-done nil)
12480 (org-todo-log-states nil)
12481 re type n what ts time to-state)
12482 (when repeat
12483 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12484 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12485 org-todo-repeat-to-state))
12486 (unless (and to-state (member to-state org-todo-keywords-1))
12487 (setq to-state (if (eq interpret 'type) org-last-state head)))
12488 (org-todo to-state)
12489 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12490 (org-entry-put nil "LAST_REPEAT" (format-time-string
12491 (org-time-stamp-format t t))))
12492 (when org-log-repeat
12493 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12494 (memq 'org-add-log-note post-command-hook))
12495 ;; OK, we are already setup for some record
12496 (if (eq org-log-repeat 'note)
12497 ;; make sure we take a note, not only a time stamp
12498 (setq org-log-note-how 'note))
12499 ;; Set up for taking a record
12500 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12501 org-last-state
12502 'findpos org-log-repeat)))
12503 (org-back-to-heading t)
12504 (org-add-planning-info nil nil 'closed)
12505 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12506 org-deadline-time-regexp "\\)\\|\\("
12507 org-ts-regexp "\\)"))
12508 (while (re-search-forward
12509 re (save-excursion (outline-next-heading) (point)) t)
12510 (setq type (if (match-end 1) org-scheduled-string
12511 (if (match-end 3) org-deadline-string "Plain:"))
12512 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12513 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12514 (setq n (string-to-number (match-string 2 ts))
12515 what (match-string 3 ts))
12516 (if (equal what "w") (setq n (* n 7) what "d"))
12517 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12518 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12519 ;; Preparation, see if we need to modify the start date for the change
12520 (when (match-end 1)
12521 (setq time (save-match-data (org-time-string-to-time ts)))
12522 (cond
12523 ((equal (match-string 1 ts) ".")
12524 ;; Shift starting date to today
12525 (org-timestamp-change
12526 (- (org-today) (time-to-days time))
12527 'day))
12528 ((equal (match-string 1 ts) "+")
12529 (let ((nshiftmax 10) (nshift 0))
12530 (while (or (= nshift 0)
12531 (<= (time-to-days time)
12532 (time-to-days (current-time))))
12533 (when (= (incf nshift) nshiftmax)
12534 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12535 (error "Abort")))
12536 (org-timestamp-change n (cdr (assoc what whata)))
12537 (org-at-timestamp-p t)
12538 (setq ts (match-string 1))
12539 (setq time (save-match-data (org-time-string-to-time ts)))))
12540 (org-timestamp-change (- n) (cdr (assoc what whata)))
12541 ;; rematch, so that we have everything in place for the real shift
12542 (org-at-timestamp-p t)
12543 (setq ts (match-string 1))
12544 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12545 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12546 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12547 (setq org-log-post-message msg)
12548 (message "%s" msg))))
12550 (defun org-show-todo-tree (arg)
12551 "Make a compact tree which shows all headlines marked with TODO.
12552 The tree will show the lines where the regexp matches, and all higher
12553 headlines above the match.
12554 With a \\[universal-argument] prefix, prompt for a regexp to match.
12555 With a numeric prefix N, construct a sparse tree for the Nth element
12556 of `org-todo-keywords-1'."
12557 (interactive "P")
12558 (let ((case-fold-search nil)
12559 (kwd-re
12560 (cond ((null arg) org-not-done-regexp)
12561 ((equal arg '(4))
12562 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12563 (mapcar 'list org-todo-keywords-1))))
12564 (concat "\\("
12565 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12566 "\\)\\>")))
12567 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12568 (regexp-quote (nth (1- (prefix-numeric-value arg))
12569 org-todo-keywords-1)))
12570 (t (error "Invalid prefix argument: %s" arg)))))
12571 (message "%d TODO entries found"
12572 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12574 (defun org-deadline (&optional arg time)
12575 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12576 With one universal prefix argument, remove any deadline from the item.
12577 With two universal prefix arguments, prompt for a warning delay.
12578 With argument TIME, set the deadline at the corresponding date. TIME
12579 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12580 (interactive "P")
12581 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12582 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12583 'region-start-level 'region))
12584 org-loop-over-headlines-in-active-region)
12585 (org-map-entries
12586 `(org-deadline ',arg ,time)
12587 org-loop-over-headlines-in-active-region
12588 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12589 (let* ((old-date (org-entry-get nil "DEADLINE"))
12590 (repeater (and old-date
12591 (string-match
12592 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12593 old-date)
12594 (match-string 1 old-date))))
12595 (cond
12596 ((equal arg '(4))
12597 (when (and old-date org-log-redeadline)
12598 (org-add-log-setup 'deldeadline nil old-date 'findpos
12599 org-log-redeadline))
12600 (org-remove-timestamp-with-keyword org-deadline-string)
12601 (message "Item no longer has a deadline."))
12602 ((equal arg '(16))
12603 (save-excursion
12604 (if (re-search-forward
12605 org-deadline-time-regexp
12606 (save-excursion (outline-next-heading) (point)) t)
12607 (let* ((rpl0 (match-string 1))
12608 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12609 (replace-match
12610 (concat org-deadline-string
12611 " <" rpl
12612 (format " -%dd" (abs
12613 (- (time-to-days
12614 (save-match-data
12615 (org-read-date nil t nil "Warn starting from")))
12616 (time-to-days nil))))
12617 ">") t t))
12618 (user-error "No deadline information to update"))))
12620 (org-add-planning-info 'deadline time 'closed)
12621 (when (and old-date org-log-redeadline
12622 (not (equal old-date
12623 (substring org-last-inserted-timestamp 1 -1))))
12624 (org-add-log-setup 'redeadline nil old-date 'findpos
12625 org-log-redeadline))
12626 (when repeater
12627 (save-excursion
12628 (org-back-to-heading t)
12629 (when (re-search-forward (concat org-deadline-string " "
12630 org-last-inserted-timestamp)
12631 (save-excursion
12632 (outline-next-heading) (point)) t)
12633 (goto-char (1- (match-end 0)))
12634 (insert " " repeater)
12635 (setq org-last-inserted-timestamp
12636 (concat (substring org-last-inserted-timestamp 0 -1)
12637 " " repeater
12638 (substring org-last-inserted-timestamp -1))))))
12639 (message "Deadline on %s" org-last-inserted-timestamp))))))
12641 (defun org-schedule (&optional arg time)
12642 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12643 With one universal prefix argument, remove any scheduling date from the item.
12644 With two universal prefix arguments, prompt for a delay cookie.
12645 With argument TIME, scheduled at the corresponding date. TIME can
12646 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12647 (interactive "P")
12648 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12649 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12650 'region-start-level 'region))
12651 org-loop-over-headlines-in-active-region)
12652 (org-map-entries
12653 `(org-schedule ',arg ,time)
12654 org-loop-over-headlines-in-active-region
12655 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12656 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12657 (repeater (and old-date
12658 (string-match
12659 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12660 old-date)
12661 (match-string 1 old-date))))
12662 (cond
12663 ((equal arg '(4))
12664 (progn
12665 (when (and old-date org-log-reschedule)
12666 (org-add-log-setup 'delschedule nil old-date 'findpos
12667 org-log-reschedule))
12668 (org-remove-timestamp-with-keyword org-scheduled-string)
12669 (message "Item is no longer scheduled.")))
12670 ((equal arg '(16))
12671 (save-excursion
12672 (if (re-search-forward
12673 org-scheduled-time-regexp
12674 (save-excursion (outline-next-heading) (point)) t)
12675 (let* ((rpl0 (match-string 1))
12676 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12677 (replace-match
12678 (concat org-scheduled-string
12679 " <" rpl
12680 (format " -%dd" (abs
12681 (- (time-to-days
12682 (save-match-data
12683 (org-read-date nil t nil "Delay until")))
12684 (time-to-days nil))))
12685 ">") t t))
12686 (user-error "No scheduled information to update"))))
12688 (org-add-planning-info 'scheduled time 'closed)
12689 (when (and old-date org-log-reschedule
12690 (not (equal old-date
12691 (substring org-last-inserted-timestamp 1 -1))))
12692 (org-add-log-setup 'reschedule nil old-date 'findpos
12693 org-log-reschedule))
12694 (when repeater
12695 (save-excursion
12696 (org-back-to-heading t)
12697 (when (re-search-forward (concat org-scheduled-string " "
12698 org-last-inserted-timestamp)
12699 (save-excursion
12700 (outline-next-heading) (point)) t)
12701 (goto-char (1- (match-end 0)))
12702 (insert " " repeater)
12703 (setq org-last-inserted-timestamp
12704 (concat (substring org-last-inserted-timestamp 0 -1)
12705 " " repeater
12706 (substring org-last-inserted-timestamp -1))))))
12707 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12709 (defun org-get-scheduled-time (pom &optional inherit)
12710 "Get the scheduled time as a time tuple, of a format suitable
12711 for calling org-schedule with, or if there is no scheduling,
12712 returns nil."
12713 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12714 (when time
12715 (apply 'encode-time (org-parse-time-string time)))))
12717 (defun org-get-deadline-time (pom &optional inherit)
12718 "Get the deadline as a time tuple, of a format suitable for
12719 calling org-deadline with, or if there is no scheduling, returns
12720 nil."
12721 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12722 (when time
12723 (apply 'encode-time (org-parse-time-string time)))))
12725 (defun org-remove-timestamp-with-keyword (keyword)
12726 "Remove all time stamps with KEYWORD in the current entry."
12727 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12728 beg)
12729 (save-excursion
12730 (org-back-to-heading t)
12731 (setq beg (point))
12732 (outline-next-heading)
12733 (while (re-search-backward re beg t)
12734 (replace-match "")
12735 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12736 (equal (char-before) ?\ ))
12737 (backward-delete-char 1)
12738 (if (string-match "^[ \t]*$" (buffer-substring
12739 (point-at-bol) (point-at-eol)))
12740 (delete-region (point-at-bol)
12741 (min (point-max) (1+ (point-at-eol))))))))))
12743 (defun org-add-planning-info (what &optional time &rest remove)
12744 "Insert new timestamp with keyword in the line directly after the headline.
12745 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12746 If non is given, the user is prompted for a date.
12747 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12748 be removed."
12749 (interactive)
12750 (let (org-time-was-given org-end-time-was-given ts
12751 end default-time default-input)
12753 (catch 'exit
12754 (when (and (memq what '(scheduled deadline))
12755 (or (not time)
12756 (and (stringp time)
12757 (string-match "^[-+]+[0-9]" time))))
12758 ;; Try to get a default date/time from existing timestamp
12759 (save-excursion
12760 (org-back-to-heading t)
12761 (setq end (save-excursion (outline-next-heading) (point)))
12762 (when (re-search-forward (if (eq what 'scheduled)
12763 org-scheduled-time-regexp
12764 org-deadline-time-regexp)
12765 end t)
12766 (setq ts (match-string 1)
12767 default-time
12768 (apply 'encode-time (org-parse-time-string ts))
12769 default-input (and ts (org-get-compact-tod ts))))))
12770 (when what
12771 (setq time
12772 (if (stringp time)
12773 ;; This is a string (relative or absolute), set proper date
12774 (apply 'encode-time
12775 (org-read-date-analyze
12776 time default-time (decode-time default-time)))
12777 ;; If necessary, get the time from the user
12778 (or time (org-read-date nil 'to-time nil nil
12779 default-time default-input)))))
12781 (when (and org-insert-labeled-timestamps-at-point
12782 (member what '(scheduled deadline)))
12783 (insert
12784 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12785 (org-insert-time-stamp time org-time-was-given
12786 nil nil nil (list org-end-time-was-given))
12787 (setq what nil))
12788 (save-excursion
12789 (save-restriction
12790 (let (col list elt ts buffer-invisibility-spec)
12791 (org-back-to-heading t)
12792 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12793 (goto-char (match-end 1))
12794 (setq col (current-column))
12795 (goto-char (match-end 0))
12796 (if (eobp) (insert "\n") (forward-char 1))
12797 (when (and (not what)
12798 (not (looking-at
12799 (concat "[ \t]*"
12800 org-keyword-time-not-clock-regexp))))
12801 ;; Nothing to add, nothing to remove...... :-)
12802 (throw 'exit nil))
12803 (if (and (not (looking-at org-outline-regexp))
12804 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12805 "[^\r\n]*"))
12806 (not (equal (match-string 1) org-clock-string)))
12807 (narrow-to-region (match-beginning 0) (match-end 0))
12808 (insert-before-markers "\n")
12809 (backward-char 1)
12810 (narrow-to-region (point) (point))
12811 (and org-adapt-indentation (org-indent-to-column col)))
12812 ;; Check if we have to remove something.
12813 (setq list (cons what remove))
12814 (while list
12815 (setq elt (pop list))
12816 (when (or (and (eq elt 'scheduled)
12817 (re-search-forward org-scheduled-time-regexp nil t))
12818 (and (eq elt 'deadline)
12819 (re-search-forward org-deadline-time-regexp nil t))
12820 (and (eq elt 'closed)
12821 (re-search-forward org-closed-time-regexp nil t)))
12822 (replace-match "")
12823 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12824 (and (looking-at "[ \t]+") (replace-match ""))
12825 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12826 (when what
12827 (insert
12828 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12829 (cond ((eq what 'scheduled) org-scheduled-string)
12830 ((eq what 'deadline) org-deadline-string)
12831 ((eq what 'closed) org-closed-string))
12832 " ")
12833 (setq ts (org-insert-time-stamp
12834 time
12835 (or org-time-was-given
12836 (and (eq what 'closed) org-log-done-with-time))
12837 (eq what 'closed)
12838 nil nil (list org-end-time-was-given)))
12839 (insert
12840 (if (not (or (bolp) (eq (char-before) ?\ )
12841 (memq (char-after) '(32 10))
12842 (eobp))) " " ""))
12843 (end-of-line 1))
12844 (goto-char (point-min))
12845 (widen)
12846 (if (and (looking-at "[ \t]*\n")
12847 (equal (char-before) ?\n))
12848 (delete-region (1- (point)) (point-at-eol)))
12849 ts))))))
12851 (defvar org-log-note-marker (make-marker))
12852 (defvar org-log-note-purpose nil)
12853 (defvar org-log-note-state nil)
12854 (defvar org-log-note-previous-state nil)
12855 (defvar org-log-note-how nil)
12856 (defvar org-log-note-extra nil)
12857 (defvar org-log-note-window-configuration nil)
12858 (defvar org-log-note-return-to (make-marker))
12859 (defvar org-log-note-effective-time nil
12860 "Remembered current time so that dynamically scoped
12861 `org-extend-today-until' affects tha timestamps in state change
12862 log")
12864 (defvar org-log-post-message nil
12865 "Message to be displayed after a log note has been stored.
12866 The auto-repeater uses this.")
12868 (defun org-add-note ()
12869 "Add a note to the current entry.
12870 This is done in the same way as adding a state change note."
12871 (interactive)
12872 (org-add-log-setup 'note nil nil 'findpos nil))
12874 (defvar org-property-end-re)
12875 (defun org-add-log-setup (&optional purpose state prev-state
12876 findpos how extra)
12877 "Set up the post command hook to take a note.
12878 If this is about to TODO state change, the new state is expected in STATE.
12879 When FINDPOS is non-nil, find the correct position for the note in
12880 the current entry. If not, assume that it can be inserted at point.
12881 HOW is an indicator what kind of note should be created.
12882 EXTRA is additional text that will be inserted into the notes buffer."
12883 (let* ((org-log-into-drawer (org-log-into-drawer))
12884 (drawer (cond ((stringp org-log-into-drawer)
12885 org-log-into-drawer)
12886 (org-log-into-drawer "LOGBOOK"))))
12887 (save-restriction
12888 (save-excursion
12889 (when findpos
12890 (org-back-to-heading t)
12891 (narrow-to-region (point) (save-excursion
12892 (outline-next-heading) (point)))
12893 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12894 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12895 "[^\r\n]*\\)?"))
12896 (goto-char (match-end 0))
12897 (cond
12898 (drawer
12899 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12900 nil t)
12901 (progn
12902 (goto-char (match-end 0))
12903 (or org-log-states-order-reversed
12904 (and (re-search-forward org-property-end-re nil t)
12905 (goto-char (1- (match-beginning 0))))))
12906 (insert "\n:" drawer ":\n:END:")
12907 (beginning-of-line 0)
12908 (org-indent-line)
12909 (beginning-of-line 2)
12910 (org-indent-line)
12911 (end-of-line 0)))
12912 ((and org-log-state-notes-insert-after-drawers
12913 (save-excursion
12914 (forward-line) (looking-at org-drawer-regexp)))
12915 (forward-line)
12916 (while (looking-at org-drawer-regexp)
12917 (goto-char (match-end 0))
12918 (re-search-forward org-property-end-re (point-max) t)
12919 (forward-line))
12920 (forward-line -1)))
12921 (unless org-log-states-order-reversed
12922 (and (= (char-after) ?\n) (forward-char 1))
12923 (org-skip-over-state-notes)
12924 (skip-chars-backward " \t\n\r")))
12925 (move-marker org-log-note-marker (point))
12926 (setq org-log-note-purpose purpose
12927 org-log-note-state state
12928 org-log-note-previous-state prev-state
12929 org-log-note-how how
12930 org-log-note-extra extra
12931 org-log-note-effective-time (org-current-effective-time))
12932 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12934 (defun org-skip-over-state-notes ()
12935 "Skip past the list of State notes in an entry."
12936 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12937 (when (ignore-errors (goto-char (org-in-item-p)))
12938 (let* ((struct (org-list-struct))
12939 (prevs (org-list-prevs-alist struct)))
12940 (while (looking-at "[ \t]*- State")
12941 (goto-char (or (org-list-get-next-item (point) struct prevs)
12942 (org-list-get-item-end (point) struct)))))))
12944 (defun org-add-log-note (&optional purpose)
12945 "Pop up a window for taking a note, and add this note later at point."
12946 (remove-hook 'post-command-hook 'org-add-log-note)
12947 (setq org-log-note-window-configuration (current-window-configuration))
12948 (delete-other-windows)
12949 (move-marker org-log-note-return-to (point))
12950 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12951 (goto-char org-log-note-marker)
12952 (org-switch-to-buffer-other-window "*Org Note*")
12953 (erase-buffer)
12954 (if (memq org-log-note-how '(time state))
12955 (let (current-prefix-arg) (org-store-log-note))
12956 (let ((org-inhibit-startup t)) (org-mode))
12957 (insert (format "# Insert note for %s.
12958 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12959 (cond
12960 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12961 ((eq org-log-note-purpose 'done) "closed todo item")
12962 ((eq org-log-note-purpose 'state)
12963 (format "state change from \"%s\" to \"%s\""
12964 (or org-log-note-previous-state "")
12965 (or org-log-note-state "")))
12966 ((eq org-log-note-purpose 'reschedule)
12967 "rescheduling")
12968 ((eq org-log-note-purpose 'delschedule)
12969 "no longer scheduled")
12970 ((eq org-log-note-purpose 'redeadline)
12971 "changing deadline")
12972 ((eq org-log-note-purpose 'deldeadline)
12973 "removing deadline")
12974 ((eq org-log-note-purpose 'refile)
12975 "refiling")
12976 ((eq org-log-note-purpose 'note)
12977 "this entry")
12978 (t (error "This should not happen")))))
12979 (if org-log-note-extra (insert org-log-note-extra))
12980 (org-set-local 'org-finish-function 'org-store-log-note)
12981 (run-hooks 'org-log-buffer-setup-hook)))
12983 (defvar org-note-abort nil) ; dynamically scoped
12984 (defun org-store-log-note ()
12985 "Finish taking a log note, and insert it to where it belongs."
12986 (let ((txt (buffer-string)))
12987 (kill-buffer (current-buffer))
12988 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12989 lines ind bul)
12990 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12991 (setq txt (replace-match "" t t txt)))
12992 (if (string-match "\\s-+\\'" txt)
12993 (setq txt (replace-match "" t t txt)))
12994 (setq lines (org-split-string txt "\n"))
12995 (when (and note (string-match "\\S-" note))
12996 (setq note
12997 (org-replace-escapes
12998 note
12999 (list (cons "%u" (user-login-name))
13000 (cons "%U" user-full-name)
13001 (cons "%t" (format-time-string
13002 (org-time-stamp-format 'long 'inactive)
13003 org-log-note-effective-time))
13004 (cons "%T" (format-time-string
13005 (org-time-stamp-format 'long nil)
13006 org-log-note-effective-time))
13007 (cons "%d" (format-time-string
13008 (org-time-stamp-format nil 'inactive)
13009 org-log-note-effective-time))
13010 (cons "%D" (format-time-string
13011 (org-time-stamp-format nil nil)
13012 org-log-note-effective-time))
13013 (cons "%s" (if org-log-note-state
13014 (concat "\"" org-log-note-state "\"")
13015 ""))
13016 (cons "%S" (if org-log-note-previous-state
13017 (concat "\"" org-log-note-previous-state "\"")
13018 "\"\"")))))
13019 (if lines (setq note (concat note " \\\\")))
13020 (push note lines))
13021 (when (or current-prefix-arg org-note-abort)
13022 (when org-log-into-drawer
13023 (org-remove-empty-drawer-at
13024 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13025 org-log-note-marker))
13026 (setq lines nil))
13027 (when lines
13028 (with-current-buffer (marker-buffer org-log-note-marker)
13029 (save-excursion
13030 (goto-char org-log-note-marker)
13031 (move-marker org-log-note-marker nil)
13032 (end-of-line 1)
13033 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13034 (setq ind (save-excursion
13035 (if (ignore-errors (goto-char (org-in-item-p)))
13036 (let ((struct (org-list-struct)))
13037 (org-list-get-ind
13038 (org-list-get-top-point struct) struct))
13039 (skip-chars-backward " \r\t\n")
13040 (cond
13041 ((and (org-at-heading-p)
13042 org-adapt-indentation)
13043 (1+ (org-current-level)))
13044 ((org-at-heading-p) 0)
13045 (t (org-get-indentation))))))
13046 (setq bul (org-list-bullet-string "-"))
13047 (org-indent-line-to ind)
13048 (insert bul (pop lines))
13049 (let ((ind-body (+ (length bul) ind)))
13050 (while lines
13051 (insert "\n")
13052 (org-indent-line-to ind-body)
13053 (insert (pop lines))))
13054 (message "Note stored")
13055 (org-back-to-heading t)
13056 (org-cycle-hide-drawers 'children))))))
13057 (set-window-configuration org-log-note-window-configuration)
13058 (with-current-buffer (marker-buffer org-log-note-return-to)
13059 (goto-char org-log-note-return-to))
13060 (move-marker org-log-note-return-to nil)
13061 (and org-log-post-message (message "%s" org-log-post-message)))
13063 (defun org-remove-empty-drawer-at (drawer pos)
13064 "Remove an empty drawer DRAWER at position POS.
13065 POS may also be a marker."
13066 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13067 (save-excursion
13068 (save-restriction
13069 (widen)
13070 (goto-char pos)
13071 (if (org-in-regexp
13072 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13073 (replace-match ""))))))
13075 (defvar org-ts-type nil)
13076 (defun org-sparse-tree (&optional arg type)
13077 "Create a sparse tree, prompt for the details.
13078 This command can create sparse trees. You first need to select the type
13079 of match used to create the tree:
13081 t Show all TODO entries.
13082 T Show entries with a specific TODO keyword.
13083 m Show entries selected by a tags/property match.
13084 p Enter a property name and its value (both with completion on existing
13085 names/values) and show entries with that property.
13086 r Show entries matching a regular expression (`/' can be used as well).
13087 b Show deadlines and scheduled items before a date.
13088 a Show deadlines and scheduled items after a date.
13089 d Show deadlines due within `org-deadline-warning-days'.
13090 D Show deadlines and scheduled items between a date range."
13091 (interactive "P")
13092 (let (ans kwd value ts-type)
13093 (setq type (or type org-sparse-tree-default-date-type))
13094 (setq org-ts-type type)
13095 (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"
13096 (cond ((eq type 'all) "all timestamps")
13097 ((eq type 'scheduled) "only scheduled")
13098 ((eq type 'deadline) "only deadline")
13099 ((eq type 'active) "only active timestamps")
13100 ((eq type 'inactive) "only inactive timestamps")
13101 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13102 (t "scheduled/deadline")))
13103 (setq ans (read-char-exclusive))
13104 (cond
13105 ((equal ans ?c)
13106 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13107 ((equal ans ?d)
13108 (call-interactively 'org-check-deadlines))
13109 ((equal ans ?b)
13110 (call-interactively 'org-check-before-date))
13111 ((equal ans ?a)
13112 (call-interactively 'org-check-after-date))
13113 ((equal ans ?D)
13114 (call-interactively 'org-check-dates-range))
13115 ((equal ans ?t)
13116 (call-interactively 'org-show-todo-tree))
13117 ((equal ans ?T)
13118 (org-show-todo-tree '(4)))
13119 ((member ans '(?T ?m))
13120 (call-interactively 'org-match-sparse-tree))
13121 ((member ans '(?p ?P))
13122 (setq kwd (org-icompleting-read "Property: "
13123 (mapcar 'list (org-buffer-property-keys))))
13124 (setq value (org-icompleting-read "Value: "
13125 (mapcar 'list (org-property-values kwd))))
13126 (unless (string-match "\\`{.*}\\'" value)
13127 (setq value (concat "\"" value "\"")))
13128 (org-match-sparse-tree arg (concat kwd "=" value)))
13129 ((member ans '(?r ?R ?/))
13130 (call-interactively 'org-occur))
13131 (t (error "No such sparse tree command \"%c\"" ans)))))
13133 (defvar org-occur-highlights nil
13134 "List of overlays used for occur matches.")
13135 (make-variable-buffer-local 'org-occur-highlights)
13136 (defvar org-occur-parameters nil
13137 "Parameters of the active org-occur calls.
13138 This is a list, each call to org-occur pushes as cons cell,
13139 containing the regular expression and the callback, onto the list.
13140 The list can contain several entries if `org-occur' has been called
13141 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13142 will only contain one set of parameters. When the highlights are
13143 removed (for example with `C-c C-c', or with the next edit (depending
13144 on `org-remove-highlights-with-change'), this variable is emptied
13145 as well.")
13146 (make-variable-buffer-local 'org-occur-parameters)
13148 (defun org-occur (regexp &optional keep-previous callback)
13149 "Make a compact tree which shows all matches of REGEXP.
13150 The tree will show the lines where the regexp matches, and all higher
13151 headlines above the match. It will also show the heading after the match,
13152 to make sure editing the matching entry is easy.
13153 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13154 call to `org-occur' will be kept, to allow stacking of calls to this
13155 command.
13156 If CALLBACK is non-nil, it is a function which is called to confirm
13157 that the match should indeed be shown."
13158 (interactive "sRegexp: \nP")
13159 (when (equal regexp "")
13160 (error "Regexp cannot be empty"))
13161 (unless keep-previous
13162 (org-remove-occur-highlights nil nil t))
13163 (push (cons regexp callback) org-occur-parameters)
13164 (let ((cnt 0))
13165 (save-excursion
13166 (goto-char (point-min))
13167 (if (or (not keep-previous) ; do not want to keep
13168 (not org-occur-highlights)) ; no previous matches
13169 ;; hide everything
13170 (org-overview))
13171 (while (re-search-forward regexp nil t)
13172 (when (or (not callback)
13173 (save-match-data (funcall callback)))
13174 (setq cnt (1+ cnt))
13175 (when org-highlight-sparse-tree-matches
13176 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13177 (org-show-context 'occur-tree))))
13178 (when org-remove-highlights-with-change
13179 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13180 nil 'local))
13181 (unless org-sparse-tree-open-archived-trees
13182 (org-hide-archived-subtrees (point-min) (point-max)))
13183 (run-hooks 'org-occur-hook)
13184 (if (org-called-interactively-p 'interactive)
13185 (message "%d match(es) for regexp %s" cnt regexp))
13186 cnt))
13188 (defun org-occur-next-match (&optional n reset)
13189 "Function for `next-error-function' to find sparse tree matches.
13190 N is the number of matches to move, when negative move backwards.
13191 RESET is entirely ignored - this function always goes back to the
13192 starting point when no match is found."
13193 (let* ((limit (if (< n 0) (point-min) (point-max)))
13194 (search-func (if (< n 0)
13195 'previous-single-char-property-change
13196 'next-single-char-property-change))
13197 (n (abs n))
13198 (pos (point))
13200 (catch 'exit
13201 (while (setq p1 (funcall search-func (point) 'org-type))
13202 (when (equal p1 limit)
13203 (goto-char pos)
13204 (error "No more matches"))
13205 (when (equal (get-char-property p1 'org-type) 'org-occur)
13206 (setq n (1- n))
13207 (when (= n 0)
13208 (goto-char p1)
13209 (throw 'exit (point))))
13210 (goto-char p1))
13211 (goto-char p1)
13212 (error "No more matches"))))
13214 (defun org-show-context (&optional key)
13215 "Make sure point and context are visible.
13216 How much context is shown depends upon the variables
13217 `org-show-hierarchy-above', `org-show-following-heading',
13218 `org-show-entry-below' and `org-show-siblings'."
13219 (let ((heading-p (org-at-heading-p t))
13220 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13221 (following-p (org-get-alist-option org-show-following-heading key))
13222 (entry-p (org-get-alist-option org-show-entry-below key))
13223 (siblings-p (org-get-alist-option org-show-siblings key)))
13224 (catch 'exit
13225 ;; Show heading or entry text
13226 (if (and heading-p (not entry-p))
13227 (org-flag-heading nil) ; only show the heading
13228 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13229 (org-show-hidden-entry))) ; show entire entry
13230 (when following-p
13231 ;; Show next sibling, or heading below text
13232 (save-excursion
13233 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13234 (org-flag-heading nil))))
13235 (when siblings-p (org-show-siblings))
13236 (when hierarchy-p
13237 ;; show all higher headings, possibly with siblings
13238 (save-excursion
13239 (while (and (condition-case nil
13240 (progn (org-up-heading-all 1) t)
13241 (error nil))
13242 (not (bobp)))
13243 (org-flag-heading nil)
13244 (when siblings-p (org-show-siblings))))))))
13246 (defvar org-reveal-start-hook nil
13247 "Hook run before revealing a location.")
13249 (defun org-reveal (&optional siblings)
13250 "Show current entry, hierarchy above it, and the following headline.
13251 This can be used to show a consistent set of context around locations
13252 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13253 not t for the search context.
13255 With optional argument SIBLINGS, on each level of the hierarchy all
13256 siblings are shown. This repairs the tree structure to what it would
13257 look like when opened with hierarchical calls to `org-cycle'.
13258 With double optional argument \\[universal-argument] \\[universal-argument], \
13259 go to the parent and show the
13260 entire tree."
13261 (interactive "P")
13262 (run-hooks 'org-reveal-start-hook)
13263 (let ((org-show-hierarchy-above t)
13264 (org-show-following-heading t)
13265 (org-show-siblings (if siblings t org-show-siblings)))
13266 (org-show-context nil))
13267 (when (equal siblings '(16))
13268 (save-excursion
13269 (when (org-up-heading-safe)
13270 (org-show-subtree)
13271 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13273 (defun org-highlight-new-match (beg end)
13274 "Highlight from BEG to END and mark the highlight is an occur headline."
13275 (let ((ov (make-overlay beg end)))
13276 (overlay-put ov 'face 'secondary-selection)
13277 (overlay-put ov 'org-type 'org-occur)
13278 (push ov org-occur-highlights)))
13280 (defun org-remove-occur-highlights (&optional beg end noremove)
13281 "Remove the occur highlights from the buffer.
13282 BEG and END are ignored. If NOREMOVE is nil, remove this function
13283 from the `before-change-functions' in the current buffer."
13284 (interactive)
13285 (unless org-inhibit-highlight-removal
13286 (mapc 'delete-overlay org-occur-highlights)
13287 (setq org-occur-highlights nil)
13288 (setq org-occur-parameters nil)
13289 (unless noremove
13290 (remove-hook 'before-change-functions
13291 'org-remove-occur-highlights 'local))))
13293 ;;;; Priorities
13295 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13296 "Regular expression matching the priority indicator.")
13298 (defvar org-remove-priority-next-time nil)
13300 (defun org-priority-up ()
13301 "Increase the priority of the current item."
13302 (interactive)
13303 (org-priority 'up))
13305 (defun org-priority-down ()
13306 "Decrease the priority of the current item."
13307 (interactive)
13308 (org-priority 'down))
13310 (defun org-priority (&optional action show)
13311 "Change the priority of an item.
13312 ACTION can be `set', `up', `down', or a character."
13313 (interactive "P")
13314 (if (equal action '(4))
13315 (org-show-priority)
13316 (unless org-enable-priority-commands
13317 (error "Priority commands are disabled"))
13318 (setq action (or action 'set))
13319 (let (current new news have remove)
13320 (save-excursion
13321 (org-back-to-heading t)
13322 (if (looking-at org-priority-regexp)
13323 (setq current (string-to-char (match-string 2))
13324 have t))
13325 (cond
13326 ((eq action 'remove)
13327 (setq remove t new ?\ ))
13328 ((or (eq action 'set)
13329 (if (featurep 'xemacs) (characterp action) (integerp action)))
13330 (if (not (eq action 'set))
13331 (setq new action)
13332 (message "Priority %c-%c, SPC to remove: "
13333 org-highest-priority org-lowest-priority)
13334 (save-match-data
13335 (setq new (read-char-exclusive))))
13336 (if (and (= (upcase org-highest-priority) org-highest-priority)
13337 (= (upcase org-lowest-priority) org-lowest-priority))
13338 (setq new (upcase new)))
13339 (cond ((equal new ?\ ) (setq remove t))
13340 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13341 (error "Priority must be between `%c' and `%c'"
13342 org-highest-priority org-lowest-priority))))
13343 ((eq action 'up)
13344 (setq new (if have
13345 (1- current) ; normal cycling
13346 ;; last priority was empty
13347 (if (eq last-command this-command)
13348 org-lowest-priority ; wrap around empty to lowest
13349 ;; default
13350 (if org-priority-start-cycle-with-default
13351 org-default-priority
13352 (1- org-default-priority))))))
13353 ((eq action 'down)
13354 (setq new (if have
13355 (1+ current) ; normal cycling
13356 ;; last priority was empty
13357 (if (eq last-command this-command)
13358 org-highest-priority ; wrap around empty to highest
13359 ;; default
13360 (if org-priority-start-cycle-with-default
13361 org-default-priority
13362 (1+ org-default-priority))))))
13363 (t (error "Invalid action")))
13364 (if (or (< (upcase new) org-highest-priority)
13365 (> (upcase new) org-lowest-priority))
13366 (if (and (memq action '(up down))
13367 (not have) (not (eq last-command this-command)))
13368 ;; `new' is from default priority
13369 (error
13370 "The default can not be set, see `org-default-priority' why")
13371 ;; normal cycling: `new' is beyond highest/lowest priority
13372 ;; and is wrapped around to the empty priority
13373 (setq remove t)))
13374 (setq news (format "%c" new))
13375 (if have
13376 (if remove
13377 (replace-match "" t t nil 1)
13378 (replace-match news t t nil 2))
13379 (if remove
13380 (error "No priority cookie found in line")
13381 (let ((case-fold-search nil))
13382 (looking-at org-todo-line-regexp))
13383 (if (match-end 2)
13384 (progn
13385 (goto-char (match-end 2))
13386 (insert " [#" news "]"))
13387 (goto-char (match-beginning 3))
13388 (insert "[#" news "] "))))
13389 (org-preserve-lc (org-set-tags nil 'align)))
13390 (if remove
13391 (message "Priority removed")
13392 (message "Priority of current item set to %s" news)))))
13394 (defun org-show-priority ()
13395 "Show the priority of the current item.
13396 This priority is composed of the main priority given with the [#A] cookies,
13397 and by additional input from the age of a schedules or deadline entry."
13398 (interactive)
13399 (let ((pri (if (eq major-mode 'org-agenda-mode)
13400 (org-get-at-bol 'priority)
13401 (save-excursion
13402 (save-match-data
13403 (beginning-of-line)
13404 (and (looking-at org-heading-regexp)
13405 (org-get-priority (match-string 0))))))))
13406 (message "Priority is %d" (if pri pri -1000))))
13408 (defun org-get-priority (s)
13409 "Find priority cookie and return priority."
13410 (save-match-data
13411 (if (functionp org-get-priority-function)
13412 (funcall org-get-priority-function)
13413 (if (not (string-match org-priority-regexp s))
13414 (* 1000 (- org-lowest-priority org-default-priority))
13415 (* 1000 (- org-lowest-priority
13416 (string-to-char (match-string 2 s))))))))
13418 ;;;; Tags
13420 (defvar org-agenda-archives-mode)
13421 (defvar org-map-continue-from nil
13422 "Position from where mapping should continue.
13423 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13425 (defvar org-scanner-tags nil
13426 "The current tag list while the tags scanner is running.")
13427 (defvar org-trust-scanner-tags nil
13428 "Should `org-get-tags-at' use the tags for the scanner.
13429 This is for internal dynamical scoping only.
13430 When this is non-nil, the function `org-get-tags-at' will return the value
13431 of `org-scanner-tags' instead of building the list by itself. This
13432 can lead to large speed-ups when the tags scanner is used in a file with
13433 many entries, and when the list of tags is retrieved, for example to
13434 obtain a list of properties. Building the tags list for each entry in such
13435 a file becomes an N^2 operation - but with this variable set, it scales
13436 as N.")
13438 (defun org-scan-tags (action matcher todo-only &optional start-level)
13439 "Scan headline tags with inheritance and produce output ACTION.
13441 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13442 or `agenda' to produce an entry list for an agenda view. It can also be
13443 a Lisp form or a function that should be called at each matched headline, in
13444 this case the return value is a list of all return values from these calls.
13446 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13447 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13448 only lines with a not-done TODO keyword are included in the output.
13449 This should be the same variable that was scoped into
13450 and set by `org-make-tags-matcher' when it constructed MATCHER.
13452 START-LEVEL can be a string with asterisks, reducing the scope to
13453 headlines matching this string."
13454 (require 'org-agenda)
13455 (let* ((re (concat "^"
13456 (if start-level
13457 ;; Get the correct level to match
13458 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13459 org-outline-regexp)
13460 " *\\(\\<\\("
13461 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13462 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13463 (props (list 'face 'default
13464 'done-face 'org-agenda-done
13465 'undone-face 'default
13466 'mouse-face 'highlight
13467 'org-not-done-regexp org-not-done-regexp
13468 'org-todo-regexp org-todo-regexp
13469 'org-complex-heading-regexp org-complex-heading-regexp
13470 'help-echo
13471 (format "mouse-2 or RET jump to org file %s"
13472 (abbreviate-file-name
13473 (or (buffer-file-name (buffer-base-buffer))
13474 (buffer-name (buffer-base-buffer)))))))
13475 (case-fold-search nil)
13476 (org-map-continue-from nil)
13477 lspos tags tags-list
13478 (tags-alist (list (cons 0 org-file-tags)))
13479 (llast 0) rtn rtn1 level category i txt
13480 todo marker entry priority)
13481 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13482 (setq action (list 'lambda nil action)))
13483 (save-excursion
13484 (goto-char (point-min))
13485 (when (eq action 'sparse-tree)
13486 (org-overview)
13487 (org-remove-occur-highlights))
13488 (while (re-search-forward re nil t)
13489 (setq org-map-continue-from nil)
13490 (catch :skip
13491 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13492 tags (if (match-end 4) (org-match-string-no-properties 4)))
13493 (goto-char (setq lspos (match-beginning 0)))
13494 (setq level (org-reduced-level (org-outline-level))
13495 category (org-get-category))
13496 (setq i llast llast level)
13497 ;; remove tag lists from same and sublevels
13498 (while (>= i level)
13499 (when (setq entry (assoc i tags-alist))
13500 (setq tags-alist (delete entry tags-alist)))
13501 (setq i (1- i)))
13502 ;; add the next tags
13503 (when tags
13504 (setq tags (org-split-string tags ":")
13505 tags-alist
13506 (cons (cons level tags) tags-alist)))
13507 ;; compile tags for current headline
13508 (setq tags-list
13509 (if org-use-tag-inheritance
13510 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13511 tags)
13512 org-scanner-tags tags-list)
13513 (when org-use-tag-inheritance
13514 (setcdr (car tags-alist)
13515 (mapcar (lambda (x)
13516 (setq x (copy-sequence x))
13517 (org-add-prop-inherited x))
13518 (cdar tags-alist))))
13519 (when (and tags org-use-tag-inheritance
13520 (or (not (eq t org-use-tag-inheritance))
13521 org-tags-exclude-from-inheritance))
13522 ;; selective inheritance, remove uninherited ones
13523 (setcdr (car tags-alist)
13524 (org-remove-uninherited-tags (cdar tags-alist))))
13525 (when (and
13527 ;; eval matcher only when the todo condition is OK
13528 (and (or (not todo-only) (member todo org-not-done-keywords))
13529 (let ((case-fold-search t) (org-trust-scanner-tags t))
13530 (eval matcher)))
13532 ;; Call the skipper, but return t if it does not skip,
13533 ;; so that the `and' form continues evaluating
13534 (progn
13535 (unless (eq action 'sparse-tree) (org-agenda-skip))
13538 ;; Check if timestamps are deselecting this entry
13539 (or (not todo-only)
13540 (and (member todo org-not-done-keywords)
13541 (or (not org-agenda-tags-todo-honor-ignore-options)
13542 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13544 ;; select this headline
13545 (cond
13546 ((eq action 'sparse-tree)
13547 (and org-highlight-sparse-tree-matches
13548 (org-get-heading) (match-end 0)
13549 (org-highlight-new-match
13550 (match-beginning 1) (match-end 1)))
13551 (org-show-context 'tags-tree))
13552 ((eq action 'agenda)
13553 (setq txt (org-agenda-format-item
13555 (concat
13556 (if (eq org-tags-match-list-sublevels 'indented)
13557 (make-string (1- level) ?.) "")
13558 (org-get-heading))
13559 level category
13560 tags-list)
13561 priority (org-get-priority txt))
13562 (goto-char lspos)
13563 (setq marker (org-agenda-new-marker))
13564 (org-add-props txt props
13565 'org-marker marker 'org-hd-marker marker 'org-category category
13566 'todo-state todo
13567 'priority priority 'type "tagsmatch")
13568 (push txt rtn))
13569 ((functionp action)
13570 (setq org-map-continue-from nil)
13571 (save-excursion
13572 (setq rtn1 (funcall action))
13573 (push rtn1 rtn)))
13574 (t (error "Invalid action")))
13576 ;; if we are to skip sublevels, jump to end of subtree
13577 (unless org-tags-match-list-sublevels
13578 (org-end-of-subtree t)
13579 (backward-char 1))))
13580 ;; Get the correct position from where to continue
13581 (if org-map-continue-from
13582 (goto-char org-map-continue-from)
13583 (and (= (point) lspos) (end-of-line 1)))))
13584 (when (and (eq action 'sparse-tree)
13585 (not org-sparse-tree-open-archived-trees))
13586 (org-hide-archived-subtrees (point-min) (point-max)))
13587 (nreverse rtn)))
13589 (defun org-remove-uninherited-tags (tags)
13590 "Remove all tags that are not inherited from the list TAGS."
13591 (cond
13592 ((eq org-use-tag-inheritance t)
13593 (if org-tags-exclude-from-inheritance
13594 (org-delete-all org-tags-exclude-from-inheritance tags)
13595 tags))
13596 ((not org-use-tag-inheritance) nil)
13597 ((stringp org-use-tag-inheritance)
13598 (delq nil (mapcar
13599 (lambda (x)
13600 (if (and (string-match org-use-tag-inheritance x)
13601 (not (member x org-tags-exclude-from-inheritance)))
13602 x nil))
13603 tags)))
13604 ((listp org-use-tag-inheritance)
13605 (delq nil (mapcar
13606 (lambda (x)
13607 (if (member x org-use-tag-inheritance) x nil))
13608 tags)))))
13610 (defun org-match-sparse-tree (&optional todo-only match)
13611 "Create a sparse tree according to tags string MATCH.
13612 MATCH can contain positive and negative selection of tags, like
13613 \"+WORK+URGENT-WITHBOSS\".
13614 If optional argument TODO-ONLY is non-nil, only select lines that are
13615 also TODO lines."
13616 (interactive "P")
13617 (org-agenda-prepare-buffers (list (current-buffer)))
13618 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13620 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13622 (defvar org-cached-props nil)
13623 (defun org-cached-entry-get (pom property)
13624 (if (or (eq t org-use-property-inheritance)
13625 (and (stringp org-use-property-inheritance)
13626 (string-match org-use-property-inheritance property))
13627 (and (listp org-use-property-inheritance)
13628 (member property org-use-property-inheritance)))
13629 ;; Caching is not possible, check it directly
13630 (org-entry-get pom property 'inherit)
13631 ;; Get all properties, so that we can do complicated checks easily
13632 (cdr (assoc property (or org-cached-props
13633 (setq org-cached-props
13634 (org-entry-properties pom)))))))
13636 (defun org-global-tags-completion-table (&optional files)
13637 "Return the list of all tags in all agenda buffer/files.
13638 Optional FILES argument is a list of files which can be used
13639 instead of the agenda files."
13640 (save-excursion
13641 (org-uniquify
13642 (delq nil
13643 (apply 'append
13644 (mapcar
13645 (lambda (file)
13646 (set-buffer (find-file-noselect file))
13647 (append (org-get-buffer-tags)
13648 (mapcar (lambda (x) (if (stringp (car-safe x))
13649 (list (car-safe x)) nil))
13650 org-tag-alist)))
13651 (if (and files (car files))
13652 files
13653 (org-agenda-files))))))))
13655 (defun org-make-tags-matcher (match)
13656 "Create the TAGS/TODO matcher form for the selection string MATCH.
13658 The variable `todo-only' is scoped dynamically into this function.
13659 It will be set to t if the matcher restricts matching to TODO entries,
13660 otherwise will not be touched.
13662 Returns a cons of the selection string MATCH and the constructed
13663 lisp form implementing the matcher. The matcher is to be evaluated
13664 at an Org entry, with point on the headline, and returns t if the
13665 entry matches the selection string MATCH. The returned lisp form
13666 references two variables with information about the entry, which
13667 must be bound around the form's evaluation: todo, the TODO keyword
13668 at the entry (or nil of none); and tags-list, the list of all tags
13669 at the entry including inherited ones. Additionally, the category
13670 of the entry (if any) must be specified as the text property
13671 'org-category on the headline.
13673 See also `org-scan-tags'.
13675 (declare (special todo-only))
13676 (unless (boundp 'todo-only)
13677 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13678 (unless match
13679 ;; Get a new match request, with completion
13680 (let ((org-last-tags-completion-table
13681 (org-global-tags-completion-table)))
13682 (setq match (org-completing-read-no-i
13683 "Match: " 'org-tags-completion-function nil nil nil
13684 'org-tags-history))))
13686 ;; Parse the string and create a lisp form
13687 (let ((match0 match)
13688 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13689 minus tag mm
13690 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13691 orterms term orlist re-p str-p level-p level-op time-p
13692 prop-p pn pv po gv rest)
13693 (if (string-match "/+" match)
13694 ;; match contains also a todo-matching request
13695 (progn
13696 (setq tagsmatch (substring match 0 (match-beginning 0))
13697 todomatch (substring match (match-end 0)))
13698 (if (string-match "^!" todomatch)
13699 (setq todo-only t todomatch (substring todomatch 1)))
13700 (if (string-match "^\\s-*$" todomatch)
13701 (setq todomatch nil)))
13702 ;; only matching tags
13703 (setq tagsmatch match todomatch nil))
13705 ;; Make the tags matcher
13706 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13707 (setq tagsmatcher t)
13708 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13709 (while (setq term (pop orterms))
13710 (while (and (equal (substring term -1) "\\") orterms)
13711 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13712 (while (string-match re term)
13713 (setq rest (substring term (match-end 0))
13714 minus (and (match-end 1)
13715 (equal (match-string 1 term) "-"))
13716 tag (save-match-data (replace-regexp-in-string
13717 "\\\\-" "-"
13718 (match-string 2 term)))
13719 re-p (equal (string-to-char tag) ?{)
13720 level-p (match-end 4)
13721 prop-p (match-end 5)
13722 mm (cond
13723 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13724 (level-p
13725 (setq level-op (org-op-to-function (match-string 3 term)))
13726 `(,level-op level ,(string-to-number
13727 (match-string 4 term))))
13728 (prop-p
13729 (setq pn (match-string 5 term)
13730 po (match-string 6 term)
13731 pv (match-string 7 term)
13732 re-p (equal (string-to-char pv) ?{)
13733 str-p (equal (string-to-char pv) ?\")
13734 time-p (save-match-data
13735 (string-match "^\"[[<].*[]>]\"$" pv))
13736 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13737 (if time-p (setq pv (org-matcher-time pv)))
13738 (setq po (org-op-to-function po (if time-p 'time str-p)))
13739 (cond
13740 ((equal pn "CATEGORY")
13741 (setq gv '(get-text-property (point) 'org-category)))
13742 ((equal pn "TODO")
13743 (setq gv 'todo))
13745 (setq gv `(org-cached-entry-get nil ,pn))))
13746 (if re-p
13747 (if (eq po 'org<>)
13748 `(not (string-match ,pv (or ,gv "")))
13749 `(string-match ,pv (or ,gv "")))
13750 (if str-p
13751 `(,po (or ,gv "") ,pv)
13752 `(,po (string-to-number (or ,gv ""))
13753 ,(string-to-number pv) ))))
13754 (t `(member ,tag tags-list)))
13755 mm (if minus (list 'not mm) mm)
13756 term rest)
13757 (push mm tagsmatcher))
13758 (push (if (> (length tagsmatcher) 1)
13759 (cons 'and tagsmatcher)
13760 (car tagsmatcher))
13761 orlist)
13762 (setq tagsmatcher nil))
13763 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13764 (setq tagsmatcher
13765 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13766 ;; Make the todo matcher
13767 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13768 (setq todomatcher t)
13769 (setq orterms (org-split-string todomatch "|") orlist nil)
13770 (while (setq term (pop orterms))
13771 (while (string-match re term)
13772 (setq minus (and (match-end 1)
13773 (equal (match-string 1 term) "-"))
13774 kwd (match-string 2 term)
13775 re-p (equal (string-to-char kwd) ?{)
13776 term (substring term (match-end 0))
13777 mm (if re-p
13778 `(string-match ,(substring kwd 1 -1) todo)
13779 (list 'equal 'todo kwd))
13780 mm (if minus (list 'not mm) mm))
13781 (push mm todomatcher))
13782 (push (if (> (length todomatcher) 1)
13783 (cons 'and todomatcher)
13784 (car todomatcher))
13785 orlist)
13786 (setq todomatcher nil))
13787 (setq todomatcher (if (> (length orlist) 1)
13788 (cons 'or orlist) (car orlist))))
13790 ;; Return the string and lisp forms of the matcher
13791 (setq matcher (if todomatcher
13792 (list 'and tagsmatcher todomatcher)
13793 tagsmatcher))
13794 (when todo-only
13795 (setq matcher (list 'and '(member todo org-not-done-keywords)
13796 matcher)))
13797 (cons match0 matcher)))
13799 (defun org-op-to-function (op &optional stringp)
13800 "Turn an operator into the appropriate function."
13801 (setq op
13802 (cond
13803 ((equal op "<" ) '(< string< org-time<))
13804 ((equal op ">" ) '(> org-string> org-time>))
13805 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13806 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13807 ((member op '("=" "==")) '(= string= org-time=))
13808 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13809 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13811 (defun org<> (a b) (not (= a b)))
13812 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13813 (defun org-string>= (a b) (not (string< a b)))
13814 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13815 (defun org-string<> (a b) (not (string= a b)))
13816 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13817 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13818 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13819 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13820 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13821 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13822 (defun org-2ft (s)
13823 "Convert S to a floating point time.
13824 If S is already a number, just return it. If it is a string, parse
13825 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13826 (cond
13827 ((numberp s) s)
13828 ((stringp s)
13829 (condition-case nil
13830 (float-time (apply 'encode-time (org-parse-time-string s)))
13831 (error 0.)))
13832 (t 0.)))
13834 (defun org-time-today ()
13835 "Time in seconds today at 0:00.
13836 Returns the float number of seconds since the beginning of the
13837 epoch to the beginning of today (00:00)."
13838 (float-time (apply 'encode-time
13839 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13841 (defun org-matcher-time (s)
13842 "Interpret a time comparison value."
13843 (save-match-data
13844 (cond
13845 ((string= s "<now>") (float-time))
13846 ((string= s "<today>") (org-time-today))
13847 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13848 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13849 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13850 (+ (org-time-today)
13851 (* (string-to-number (match-string 1 s))
13852 (cdr (assoc (match-string 2 s)
13853 '(("d" . 86400.0) ("w" . 604800.0)
13854 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13855 (t (org-2ft s)))))
13857 (defun org-match-any-p (re list)
13858 "Does re match any element of list?"
13859 (setq list (mapcar (lambda (x) (string-match re x)) list))
13860 (delq nil list))
13862 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13863 (defvar org-tags-overlay (make-overlay 1 1))
13864 (org-detach-overlay org-tags-overlay)
13866 (defun org-get-local-tags-at (&optional pos)
13867 "Get a list of tags defined in the current headline."
13868 (org-get-tags-at pos 'local))
13870 (defun org-get-local-tags ()
13871 "Get a list of tags defined in the current headline."
13872 (org-get-tags-at nil 'local))
13874 (defun org-get-tags-at (&optional pos local)
13875 "Get a list of all headline tags applicable at POS.
13876 POS defaults to point. If tags are inherited, the list contains
13877 the targets in the same sequence as the headlines appear, i.e.
13878 the tags of the current headline come last.
13879 When LOCAL is non-nil, only return tags from the current headline,
13880 ignore inherited ones."
13881 (interactive)
13882 (if (and org-trust-scanner-tags
13883 (or (not pos) (equal pos (point)))
13884 (not local))
13885 org-scanner-tags
13886 (let (tags ltags lastpos parent)
13887 (save-excursion
13888 (save-restriction
13889 (widen)
13890 (goto-char (or pos (point)))
13891 (save-match-data
13892 (catch 'done
13893 (condition-case nil
13894 (progn
13895 (org-back-to-heading t)
13896 (while (not (equal lastpos (point)))
13897 (setq lastpos (point))
13898 (when (looking-at
13899 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13900 (setq ltags (org-split-string
13901 (org-match-string-no-properties 1) ":"))
13902 (when parent
13903 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13904 (setq tags (append
13905 (if parent
13906 (org-remove-uninherited-tags ltags)
13907 ltags)
13908 tags)))
13909 (or org-use-tag-inheritance (throw 'done t))
13910 (if local (throw 'done t))
13911 (or (org-up-heading-safe) (error nil))
13912 (setq parent t)))
13913 (error nil)))))
13914 (if local
13915 tags
13916 (reverse (delete-dups
13917 (reverse (append
13918 (org-remove-uninherited-tags
13919 org-file-tags) tags)))))))))
13921 (defun org-add-prop-inherited (s)
13922 (add-text-properties 0 (length s) '(inherited t) s)
13925 (defun org-toggle-tag (tag &optional onoff)
13926 "Toggle the tag TAG for the current line.
13927 If ONOFF is `on' or `off', don't toggle but set to this state."
13928 (let (res current)
13929 (save-excursion
13930 (org-back-to-heading t)
13931 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13932 (point-at-eol) t)
13933 (progn
13934 (setq current (match-string 1))
13935 (replace-match ""))
13936 (setq current ""))
13937 (setq current (nreverse (org-split-string current ":")))
13938 (cond
13939 ((eq onoff 'on)
13940 (setq res t)
13941 (or (member tag current) (push tag current)))
13942 ((eq onoff 'off)
13943 (or (not (member tag current)) (setq current (delete tag current))))
13944 (t (if (member tag current)
13945 (setq current (delete tag current))
13946 (setq res t)
13947 (push tag current))))
13948 (end-of-line 1)
13949 (if current
13950 (progn
13951 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13952 (org-set-tags nil t))
13953 (delete-horizontal-space))
13954 (run-hooks 'org-after-tags-change-hook))
13955 res))
13957 (defun org-align-tags-here (to-col)
13958 ;; Assumes that this is a headline
13959 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13960 (beginning-of-line 1)
13961 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13962 (< pos (match-beginning 2)))
13963 (progn
13964 (setq tags-l (- (match-end 2) (match-beginning 2)))
13965 (goto-char (match-beginning 1))
13966 (insert " ")
13967 (delete-region (point) (1+ (match-beginning 2)))
13968 (setq ncol (max (current-column)
13969 (1+ col)
13970 (if (> to-col 0)
13971 to-col
13972 (- (abs to-col) tags-l))))
13973 (setq p (point))
13974 (insert (make-string (- ncol (current-column)) ?\ ))
13975 (setq ncol (current-column))
13976 (when indent-tabs-mode (tabify p (point-at-eol)))
13977 (org-move-to-column (min ncol col) t))
13978 (goto-char pos))))
13980 (defun org-set-tags-command (&optional arg just-align)
13981 "Call the set-tags command for the current entry."
13982 (interactive "P")
13983 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13984 (org-set-tags arg just-align)
13985 (save-excursion
13986 (unless (and (org-region-active-p)
13987 org-loop-over-headlines-in-active-region)
13988 (org-back-to-heading t))
13989 (org-set-tags arg just-align))))
13991 (defun org-set-tags-to (data)
13992 "Set the tags of the current entry to DATA, replacing the current tags.
13993 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13994 If DATA is nil or the empty string, any tags will be removed."
13995 (interactive "sTags: ")
13996 (setq data
13997 (cond
13998 ((eq data nil) "")
13999 ((equal data "") "")
14000 ((stringp data)
14001 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14002 ":"))
14003 ((listp data)
14004 (concat ":" (mapconcat 'identity data ":") ":"))))
14005 (when data
14006 (save-excursion
14007 (org-back-to-heading t)
14008 (when (looking-at org-complex-heading-regexp)
14009 (if (match-end 5)
14010 (progn
14011 (goto-char (match-beginning 5))
14012 (insert data)
14013 (delete-region (point) (point-at-eol))
14014 (org-set-tags nil 'align))
14015 (goto-char (point-at-eol))
14016 (insert " " data)
14017 (org-set-tags nil 'align)))
14018 (beginning-of-line 1)
14019 (if (looking-at ".*?\\([ \t]+\\)$")
14020 (delete-region (match-beginning 1) (match-end 1))))))
14022 (defun org-align-all-tags ()
14023 "Align the tags i all headings."
14024 (interactive)
14025 (save-excursion
14026 (or (ignore-errors (org-back-to-heading t))
14027 (outline-next-heading))
14028 (if (org-at-heading-p)
14029 (org-set-tags t)
14030 (message "No headings"))))
14032 (defvar org-indent-indentation-per-level)
14033 (defun org-set-tags (&optional arg just-align)
14034 "Set the tags for the current headline.
14035 With prefix ARG, realign all tags in headings in the current buffer."
14036 (interactive "P")
14037 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14038 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14039 'region-start-level 'region))
14040 org-loop-over-headlines-in-active-region)
14041 (org-map-entries
14042 ;; We don't use ARG and JUST-ALIGN here these args are not
14043 ;; useful when looping over headlines
14044 `(org-set-tags)
14045 org-loop-over-headlines-in-active-region
14046 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14047 (let* ((re org-outline-regexp-bol)
14048 (current (unless arg (org-get-tags-string)))
14049 (col (current-column))
14050 (org-setting-tags t)
14051 table current-tags inherited-tags ; computed below when needed
14052 tags p0 c0 c1 rpl di tc level)
14053 (if arg
14054 (save-excursion
14055 (goto-char (point-min))
14056 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14057 (while (re-search-forward re nil t)
14058 (org-set-tags nil t)
14059 (end-of-line 1)))
14060 (message "All tags realigned to column %d" org-tags-column))
14061 (if just-align
14062 (setq tags current)
14063 ;; Get a new set of tags from the user
14064 (save-excursion
14065 (setq table (append org-tag-persistent-alist
14066 (or org-tag-alist (org-get-buffer-tags))
14067 (and
14068 org-complete-tags-always-offer-all-agenda-tags
14069 (org-global-tags-completion-table
14070 (org-agenda-files))))
14071 org-last-tags-completion-table table
14072 current-tags (org-split-string current ":")
14073 inherited-tags (nreverse
14074 (nthcdr (length current-tags)
14075 (nreverse (org-get-tags-at))))
14076 tags
14077 (if (or (eq t org-use-fast-tag-selection)
14078 (and org-use-fast-tag-selection
14079 (delq nil (mapcar 'cdr table))))
14080 (org-fast-tag-selection
14081 current-tags inherited-tags table
14082 (if org-fast-tag-selection-include-todo
14083 org-todo-key-alist))
14084 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14085 (org-trim
14086 (org-icompleting-read "Tags: "
14087 'org-tags-completion-function
14088 nil nil current 'org-tags-history))))))
14089 (while (string-match "[-+&]+" tags)
14090 ;; No boolean logic, just a list
14091 (setq tags (replace-match ":" t t tags))))
14093 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14095 (if org-tags-sort-function
14096 (setq tags (mapconcat 'identity
14097 (sort (org-split-string
14098 tags (org-re "[^[:alnum:]_@#%]+"))
14099 org-tags-sort-function) ":")))
14101 (if (string-match "\\`[\t ]*\\'" tags)
14102 (setq tags "")
14103 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14104 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14106 ;; Insert new tags at the correct column
14107 (beginning-of-line 1)
14108 (setq level (or (and (looking-at org-outline-regexp)
14109 (- (match-end 0) (point) 1))
14111 (cond
14112 ((and (equal current "") (equal tags "")))
14113 ((re-search-forward
14114 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14115 (point-at-eol) t)
14116 (if (equal tags "")
14117 (setq rpl "")
14118 (goto-char (match-beginning 0))
14119 (setq c0 (current-column)
14120 ;; compute offset for the case of org-indent-mode active
14121 di (if org-indent-mode
14122 (* (1- org-indent-indentation-per-level) (1- level))
14124 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14125 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14126 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14127 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14128 (replace-match rpl t t)
14129 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14130 tags)
14131 (t (error "Tags alignment failed")))
14132 (org-move-to-column col)
14133 (unless just-align
14134 (run-hooks 'org-after-tags-change-hook))))))
14136 (defun org-change-tag-in-region (beg end tag off)
14137 "Add or remove TAG for each entry in the region.
14138 This works in the agenda, and also in an org-mode buffer."
14139 (interactive
14140 (list (region-beginning) (region-end)
14141 (let ((org-last-tags-completion-table
14142 (if (derived-mode-p 'org-mode)
14143 (org-get-buffer-tags)
14144 (org-global-tags-completion-table))))
14145 (org-icompleting-read
14146 "Tag: " 'org-tags-completion-function nil nil nil
14147 'org-tags-history))
14148 (progn
14149 (message "[s]et or [r]emove? ")
14150 (equal (read-char-exclusive) ?r))))
14151 (if (fboundp 'deactivate-mark) (deactivate-mark))
14152 (let ((agendap (equal major-mode 'org-agenda-mode))
14153 l1 l2 m buf pos newhead (cnt 0))
14154 (goto-char end)
14155 (setq l2 (1- (org-current-line)))
14156 (goto-char beg)
14157 (setq l1 (org-current-line))
14158 (loop for l from l1 to l2 do
14159 (org-goto-line l)
14160 (setq m (get-text-property (point) 'org-hd-marker))
14161 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14162 (and agendap m))
14163 (setq buf (if agendap (marker-buffer m) (current-buffer))
14164 pos (if agendap m (point)))
14165 (with-current-buffer buf
14166 (save-excursion
14167 (save-restriction
14168 (goto-char pos)
14169 (setq cnt (1+ cnt))
14170 (org-toggle-tag tag (if off 'off 'on))
14171 (setq newhead (org-get-heading)))))
14172 (and agendap (org-agenda-change-all-lines newhead m))))
14173 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14175 (defun org-tags-completion-function (string predicate &optional flag)
14176 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14177 (confirm (lambda (x) (stringp (car x)))))
14178 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14179 (setq s1 (match-string 1 string)
14180 s2 (match-string 2 string))
14181 (setq s1 "" s2 string))
14182 (cond
14183 ((eq flag nil)
14184 ;; try completion
14185 (setq rtn (try-completion s2 ctable confirm))
14186 (if (stringp rtn)
14187 (setq rtn
14188 (concat s1 s2 (substring rtn (length s2))
14189 (if (and org-add-colon-after-tag-completion
14190 (assoc rtn ctable))
14191 ":" ""))))
14192 rtn)
14193 ((eq flag t)
14194 ;; all-completions
14195 (all-completions s2 ctable confirm)
14197 ((eq flag 'lambda)
14198 ;; exact match?
14199 (assoc s2 ctable)))
14202 (defun org-fast-tag-insert (kwd tags face &optional end)
14203 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14204 (insert (format "%-12s" (concat kwd ":"))
14205 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14206 (or end "")))
14208 (defun org-fast-tag-show-exit (flag)
14209 (save-excursion
14210 (org-goto-line 3)
14211 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14212 (replace-match ""))
14213 (when flag
14214 (end-of-line 1)
14215 (org-move-to-column (- (window-width) 19) t)
14216 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14218 (defun org-set-current-tags-overlay (current prefix)
14219 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14220 (if (featurep 'xemacs)
14221 (org-overlay-display org-tags-overlay (concat prefix s)
14222 'secondary-selection)
14223 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14224 (org-overlay-display org-tags-overlay (concat prefix s)))))
14226 (defvar org-last-tag-selection-key nil)
14227 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14228 "Fast tag selection with single keys.
14229 CURRENT is the current list of tags in the headline, INHERITED is the
14230 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14231 possibly with grouping information. TODO-TABLE is a similar table with
14232 TODO keywords, should these have keys assigned to them.
14233 If the keys are nil, a-z are automatically assigned.
14234 Returns the new tags string, or nil to not change the current settings."
14235 (let* ((fulltable (append table todo-table))
14236 (maxlen (apply 'max (mapcar
14237 (lambda (x)
14238 (if (stringp (car x)) (string-width (car x)) 0))
14239 fulltable)))
14240 (buf (current-buffer))
14241 (expert (eq org-fast-tag-selection-single-key 'expert))
14242 (buffer-tags nil)
14243 (fwidth (+ maxlen 3 1 3))
14244 (ncol (/ (- (window-width) 4) fwidth))
14245 (i-face 'org-done)
14246 (c-face 'org-todo)
14247 tg cnt e c char c1 c2 ntable tbl rtn
14248 ov-start ov-end ov-prefix
14249 (exit-after-next org-fast-tag-selection-single-key)
14250 (done-keywords org-done-keywords)
14251 groups ingroup)
14252 (save-excursion
14253 (beginning-of-line 1)
14254 (if (looking-at
14255 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14256 (setq ov-start (match-beginning 1)
14257 ov-end (match-end 1)
14258 ov-prefix "")
14259 (setq ov-start (1- (point-at-eol))
14260 ov-end (1+ ov-start))
14261 (skip-chars-forward "^\n\r")
14262 (setq ov-prefix
14263 (concat
14264 (buffer-substring (1- (point)) (point))
14265 (if (> (current-column) org-tags-column)
14267 (make-string (- org-tags-column (current-column)) ?\ ))))))
14268 (move-overlay org-tags-overlay ov-start ov-end)
14269 (save-window-excursion
14270 (if expert
14271 (set-buffer (get-buffer-create " *Org tags*"))
14272 (delete-other-windows)
14273 (split-window-vertically)
14274 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14275 (erase-buffer)
14276 (org-set-local 'org-done-keywords done-keywords)
14277 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14278 (org-fast-tag-insert "Current" current c-face "\n\n")
14279 (org-fast-tag-show-exit exit-after-next)
14280 (org-set-current-tags-overlay current ov-prefix)
14281 (setq tbl fulltable char ?a cnt 0)
14282 (while (setq e (pop tbl))
14283 (cond
14284 ((equal (car e) :startgroup)
14285 (push '() groups) (setq ingroup t)
14286 (when (not (= cnt 0))
14287 (setq cnt 0)
14288 (insert "\n"))
14289 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14290 ((equal (car e) :endgroup)
14291 (setq ingroup nil cnt 0)
14292 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14293 ((equal e '(:newline))
14294 (when (not (= cnt 0))
14295 (setq cnt 0)
14296 (insert "\n")
14297 (setq e (car tbl))
14298 (while (equal (car tbl) '(:newline))
14299 (insert "\n")
14300 (setq tbl (cdr tbl)))))
14302 (setq tg (copy-sequence (car e)) c2 nil)
14303 (if (cdr e)
14304 (setq c (cdr e))
14305 ;; automatically assign a character.
14306 (setq c1 (string-to-char
14307 (downcase (substring
14308 tg (if (= (string-to-char tg) ?@) 1 0)))))
14309 (if (or (rassoc c1 ntable) (rassoc c1 table))
14310 (while (or (rassoc char ntable) (rassoc char table))
14311 (setq char (1+ char)))
14312 (setq c2 c1))
14313 (setq c (or c2 char)))
14314 (if ingroup (push tg (car groups)))
14315 (setq tg (org-add-props tg nil 'face
14316 (cond
14317 ((not (assoc tg table))
14318 (org-get-todo-face tg))
14319 ((member tg current) c-face)
14320 ((member tg inherited) i-face))))
14321 (if (and (= cnt 0) (not ingroup)) (insert " "))
14322 (insert "[" c "] " tg (make-string
14323 (- fwidth 4 (length tg)) ?\ ))
14324 (push (cons tg c) ntable)
14325 (when (= (setq cnt (1+ cnt)) ncol)
14326 (insert "\n")
14327 (if ingroup (insert " "))
14328 (setq cnt 0)))))
14329 (setq ntable (nreverse ntable))
14330 (insert "\n")
14331 (goto-char (point-min))
14332 (if (not expert) (org-fit-window-to-buffer))
14333 (setq rtn
14334 (catch 'exit
14335 (while t
14336 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14337 (if (not groups) "no " "")
14338 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14339 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14340 (setq org-last-tag-selection-key c)
14341 (cond
14342 ((= c ?\r) (throw 'exit t))
14343 ((= c ?!)
14344 (setq groups (not groups))
14345 (goto-char (point-min))
14346 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14347 ((= c ?\C-c)
14348 (if (not expert)
14349 (org-fast-tag-show-exit
14350 (setq exit-after-next (not exit-after-next)))
14351 (setq expert nil)
14352 (delete-other-windows)
14353 (set-window-buffer (split-window-vertically) " *Org tags*")
14354 (org-switch-to-buffer-other-window " *Org tags*")
14355 (org-fit-window-to-buffer)))
14356 ((or (= c ?\C-g)
14357 (and (= c ?q) (not (rassoc c ntable))))
14358 (org-detach-overlay org-tags-overlay)
14359 (setq quit-flag t))
14360 ((= c ?\ )
14361 (setq current nil)
14362 (if exit-after-next (setq exit-after-next 'now)))
14363 ((= c ?\t)
14364 (condition-case nil
14365 (setq tg (org-icompleting-read
14366 "Tag: "
14367 (or buffer-tags
14368 (with-current-buffer buf
14369 (org-get-buffer-tags)))))
14370 (quit (setq tg "")))
14371 (when (string-match "\\S-" tg)
14372 (add-to-list 'buffer-tags (list tg))
14373 (if (member tg current)
14374 (setq current (delete tg current))
14375 (push tg current)))
14376 (if exit-after-next (setq exit-after-next 'now)))
14377 ((setq e (rassoc c todo-table) tg (car e))
14378 (with-current-buffer buf
14379 (save-excursion (org-todo tg)))
14380 (if exit-after-next (setq exit-after-next 'now)))
14381 ((setq e (rassoc c ntable) tg (car e))
14382 (if (member tg current)
14383 (setq current (delete tg current))
14384 (loop for g in groups do
14385 (if (member tg g)
14386 (mapc (lambda (x)
14387 (setq current (delete x current)))
14388 g)))
14389 (push tg current))
14390 (if exit-after-next (setq exit-after-next 'now))))
14392 ;; Create a sorted list
14393 (setq current
14394 (sort current
14395 (lambda (a b)
14396 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14397 (if (eq exit-after-next 'now) (throw 'exit t))
14398 (goto-char (point-min))
14399 (beginning-of-line 2)
14400 (delete-region (point) (point-at-eol))
14401 (org-fast-tag-insert "Current" current c-face)
14402 (org-set-current-tags-overlay current ov-prefix)
14403 (while (re-search-forward
14404 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14405 (setq tg (match-string 1))
14406 (add-text-properties
14407 (match-beginning 1) (match-end 1)
14408 (list 'face
14409 (cond
14410 ((member tg current) c-face)
14411 ((member tg inherited) i-face)
14412 (t (get-text-property (match-beginning 1) 'face))))))
14413 (goto-char (point-min)))))
14414 (org-detach-overlay org-tags-overlay)
14415 (if rtn
14416 (mapconcat 'identity current ":")
14417 nil))))
14419 (defun org-get-tags-string ()
14420 "Get the TAGS string in the current headline."
14421 (unless (org-at-heading-p t)
14422 (error "Not on a heading"))
14423 (save-excursion
14424 (beginning-of-line 1)
14425 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14426 (org-match-string-no-properties 1)
14427 "")))
14429 (defun org-get-tags ()
14430 "Get the list of tags specified in the current headline."
14431 (org-split-string (org-get-tags-string) ":"))
14433 (defun org-get-buffer-tags ()
14434 "Get a table of all tags used in the buffer, for completion."
14435 (let (tags)
14436 (save-excursion
14437 (goto-char (point-min))
14438 (while (re-search-forward
14439 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14440 (when (equal (char-after (point-at-bol 0)) ?*)
14441 (mapc (lambda (x) (add-to-list 'tags x))
14442 (org-split-string (org-match-string-no-properties 1) ":")))))
14443 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14444 (mapcar 'list tags)))
14446 ;;;; The mapping API
14448 (defun org-map-entries (func &optional match scope &rest skip)
14449 "Call FUNC at each headline selected by MATCH in SCOPE.
14451 FUNC is a function or a lisp form. The function will be called without
14452 arguments, with the cursor positioned at the beginning of the headline.
14453 The return values of all calls to the function will be collected and
14454 returned as a list.
14456 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14457 does not need to preserve point. After evaluation, the cursor will be
14458 moved to the end of the line (presumably of the headline of the
14459 processed entry) and search continues from there. Under some
14460 circumstances, this may not produce the wanted results. For example,
14461 if you have removed (e.g. archived) the current (sub)tree it could
14462 mean that the next entry will be skipped entirely. In such cases, you
14463 can specify the position from where search should continue by making
14464 FUNC set the variable `org-map-continue-from' to the desired buffer
14465 position.
14467 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14468 Only headlines that are matched by this query will be considered during
14469 the iteration. When MATCH is nil or t, all headlines will be
14470 visited by the iteration.
14472 SCOPE determines the scope of this command. It can be any of:
14474 nil The current buffer, respecting the restriction if any
14475 tree The subtree started with the entry at point
14476 region The entries within the active region, if any
14477 region-start-level
14478 The entries within the active region, but only those at
14479 the same level than the first one.
14480 file The current buffer, without restriction
14481 file-with-archives
14482 The current buffer, and any archives associated with it
14483 agenda All agenda files
14484 agenda-with-archives
14485 All agenda files with any archive files associated with them
14486 \(file1 file2 ...)
14487 If this is a list, all files in the list will be scanned
14489 The remaining args are treated as settings for the skipping facilities of
14490 the scanner. The following items can be given here:
14492 archive skip trees with the archive tag.
14493 comment skip trees with the COMMENT keyword
14494 function or Emacs Lisp form:
14495 will be used as value for `org-agenda-skip-function', so whenever
14496 the function returns t, FUNC will not be called for that
14497 entry and search will continue from the point where the
14498 function leaves it.
14500 If your function needs to retrieve the tags including inherited tags
14501 at the *current* entry, you can use the value of the variable
14502 `org-scanner-tags' which will be much faster than getting the value
14503 with `org-get-tags-at'. If your function gets properties with
14504 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14505 to t around the call to `org-entry-properties' to get the same speedup.
14506 Note that if your function moves around to retrieve tags and properties at
14507 a *different* entry, you cannot use these techniques."
14508 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14509 (not (org-region-active-p)))
14510 (let* ((org-agenda-archives-mode nil) ; just to make sure
14511 (org-agenda-skip-archived-trees (memq 'archive skip))
14512 (org-agenda-skip-comment-trees (memq 'comment skip))
14513 (org-agenda-skip-function
14514 (car (org-delete-all '(comment archive) skip)))
14515 (org-tags-match-list-sublevels t)
14516 (start-level (eq scope 'region-start-level))
14517 matcher file res
14518 org-todo-keywords-for-agenda
14519 org-done-keywords-for-agenda
14520 org-todo-keyword-alist-for-agenda
14521 org-drawers-for-agenda
14522 org-tag-alist-for-agenda
14523 todo-only)
14525 (cond
14526 ((eq match t) (setq matcher t))
14527 ((eq match nil) (setq matcher t))
14528 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14530 (save-excursion
14531 (save-restriction
14532 (cond ((eq scope 'tree)
14533 (org-back-to-heading t)
14534 (org-narrow-to-subtree)
14535 (setq scope nil))
14536 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14537 (org-region-active-p))
14538 ;; If needed, set start-level to a string like "2"
14539 (when start-level
14540 (save-excursion
14541 (goto-char (region-beginning))
14542 (unless (org-at-heading-p) (outline-next-heading))
14543 (setq start-level (org-current-level))))
14544 (narrow-to-region (region-beginning)
14545 (save-excursion
14546 (goto-char (region-end))
14547 (unless (and (bolp) (org-at-heading-p))
14548 (outline-next-heading))
14549 (point)))
14550 (setq scope nil)))
14552 (if (not scope)
14553 (progn
14554 (org-agenda-prepare-buffers
14555 (list (buffer-file-name (current-buffer))))
14556 (setq res (org-scan-tags func matcher todo-only start-level)))
14557 ;; Get the right scope
14558 (cond
14559 ((and scope (listp scope) (symbolp (car scope)))
14560 (setq scope (eval scope)))
14561 ((eq scope 'agenda)
14562 (setq scope (org-agenda-files t)))
14563 ((eq scope 'agenda-with-archives)
14564 (setq scope (org-agenda-files t))
14565 (setq scope (org-add-archive-files scope)))
14566 ((eq scope 'file)
14567 (setq scope (list (buffer-file-name))))
14568 ((eq scope 'file-with-archives)
14569 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14570 (org-agenda-prepare-buffers scope)
14571 (while (setq file (pop scope))
14572 (with-current-buffer (org-find-base-buffer-visiting file)
14573 (save-excursion
14574 (save-restriction
14575 (widen)
14576 (goto-char (point-min))
14577 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14578 res)))
14580 ;;;; Properties
14582 ;;; Setting and retrieving properties
14584 (defconst org-special-properties
14585 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14586 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14587 "The special properties valid in Org-mode.
14589 These are properties that are not defined in the property drawer,
14590 but in some other way.")
14592 (defconst org-default-properties
14593 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14594 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14595 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14596 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14597 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14598 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14599 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14600 "Some properties that are used by Org-mode for various purposes.
14601 Being in this list makes sure that they are offered for completion.")
14603 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14604 "Regular expression matching the first line of a property drawer.")
14606 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14607 "Regular expression matching the last line of a property drawer.")
14609 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14610 "Regular expression matching the first line of a property drawer.")
14612 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14613 "Regular expression matching the first line of a property drawer.")
14615 (defconst org-property-drawer-re
14616 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14617 org-property-end-re "\\)\n?")
14618 "Matches an entire property drawer.")
14620 (defconst org-clock-drawer-re
14621 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14622 org-property-end-re "\\)\n?")
14623 "Matches an entire clock drawer.")
14625 (defsubst org-re-property (property)
14626 "Return a regexp matching a PROPERTY line.
14627 Match group 1 will be set to the value."
14628 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14630 (defsubst org-re-property-keyword (property)
14631 "Return a regexp matching a PROPERTY line, possibly with no
14632 value for the property."
14633 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14635 (defun org-property-action ()
14636 "Do an action on properties."
14637 (interactive)
14638 (let (c)
14639 (org-at-property-p)
14640 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14641 (setq c (read-char-exclusive))
14642 (cond
14643 ((equal c ?s)
14644 (call-interactively 'org-set-property))
14645 ((equal c ?d)
14646 (call-interactively 'org-delete-property))
14647 ((equal c ?D)
14648 (call-interactively 'org-delete-property-globally))
14649 ((equal c ?c)
14650 (call-interactively 'org-compute-property-at-point))
14651 (t (error "No such property action %c" c)))))
14653 (defun org-inc-effort ()
14654 "Increment the value of the effort property in the current entry."
14655 (interactive)
14656 (org-set-effort nil t))
14658 (defun org-set-effort (&optional value increment)
14659 "Set the effort property of the current entry.
14660 With numerical prefix arg, use the nth allowed value, 0 stands for the
14661 10th allowed value.
14663 When INCREMENT is non-nil, set the property to the next allowed value."
14664 (interactive "P")
14665 (if (equal value 0) (setq value 10))
14666 (let* ((completion-ignore-case t)
14667 (prop org-effort-property)
14668 (cur (org-entry-get nil prop))
14669 (allowed (org-property-get-allowed-values nil prop 'table))
14670 (existing (mapcar 'list (org-property-values prop)))
14672 (val (cond
14673 ((stringp value) value)
14674 ((and allowed (integerp value))
14675 (or (car (nth (1- value) allowed))
14676 (car (org-last allowed))))
14677 ((and allowed increment)
14678 (or (caadr (member (list cur) allowed))
14679 (error "Allowed effort values are not set")))
14680 (allowed
14681 (message "Select 1-9,0, [RET%s]: %s"
14682 (if cur (concat "=" cur) "")
14683 (mapconcat 'car allowed " "))
14684 (setq rpl (read-char-exclusive))
14685 (if (equal rpl ?\r)
14687 (setq rpl (- rpl ?0))
14688 (if (equal rpl 0) (setq rpl 10))
14689 (if (and (> rpl 0) (<= rpl (length allowed)))
14690 (car (nth (1- rpl) allowed))
14691 (org-completing-read "Effort: " allowed nil))))
14693 (let (org-completion-use-ido org-completion-use-iswitchb)
14694 (org-completing-read
14695 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14696 (concat "[" cur "]") "")
14697 ": ")
14698 existing nil nil "" nil cur))))))
14699 (unless (equal (org-entry-get nil prop) val)
14700 (org-entry-put nil prop val))
14701 (save-excursion
14702 (org-back-to-heading t)
14703 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14704 (message "%s is now %s" prop val)))
14706 (defun org-at-property-p ()
14707 "Is cursor inside a property drawer?"
14708 (save-excursion
14709 (beginning-of-line 1)
14710 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14711 (save-match-data ;; Used by calling procedures
14712 (let ((p (point))
14713 (range (unless (org-before-first-heading-p)
14714 (org-get-property-block))))
14715 (and range (<= (car range) p) (< p (cdr range))))))))
14717 (defun org-get-property-block (&optional beg end force)
14718 "Return the (beg . end) range of the body of the property drawer.
14719 BEG and END are the beginning and end of the current subtree, or of
14720 the part before the first headline. If they are not given, they will
14721 be found. If the drawer does not exist and FORCE is non-nil, create
14722 the drawer."
14723 (catch 'exit
14724 (save-excursion
14725 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14726 (progn (org-back-to-heading t) (point))))
14727 (end (or end (and (not (outline-next-heading)) (point-max))
14728 (point))))
14729 (goto-char beg)
14730 (if (re-search-forward org-property-start-re end t)
14731 (setq beg (1+ (match-end 0)))
14732 (if force
14733 (save-excursion
14734 (org-insert-property-drawer)
14735 (setq end (progn (outline-next-heading) (point))))
14736 (throw 'exit nil))
14737 (goto-char beg)
14738 (if (re-search-forward org-property-start-re end t)
14739 (setq beg (1+ (match-end 0)))))
14740 (if (re-search-forward org-property-end-re end t)
14741 (setq end (match-beginning 0))
14742 (or force (throw 'exit nil))
14743 (goto-char beg)
14744 (setq end beg)
14745 (org-indent-line)
14746 (insert ":END:\n"))
14747 (cons beg end)))))
14749 (defun org-entry-properties (&optional pom which specific)
14750 "Get all properties of the entry at point-or-marker POM.
14751 This includes the TODO keyword, the tags, time strings for deadline,
14752 scheduled, and clocking, and any additional properties defined in the
14753 entry. The return value is an alist, keys may occur multiple times
14754 if the property key was used several times.
14755 POM may also be nil, in which case the current entry is used.
14756 If WHICH is nil or `all', get all properties. If WHICH is
14757 `special' or `standard', only get that subclass. If WHICH
14758 is a string only get exactly this property. SPECIFIC can be a string, the
14759 specific property we are interested in. Specifying it can speed
14760 things up because then unnecessary parsing is avoided."
14761 (setq which (or which 'all))
14762 (org-with-point-at pom
14763 (let ((clockstr (substring org-clock-string 0 -1))
14764 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14765 (case-fold-search nil)
14766 beg end range props sum-props key key1 value string clocksum clocksumt)
14767 (save-excursion
14768 (when (condition-case nil
14769 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14770 (error nil))
14771 (setq beg (point))
14772 (setq sum-props (get-text-property (point) 'org-summaries))
14773 (setq clocksum (get-text-property (point) :org-clock-minutes)
14774 clocksumt (get-text-property (point) :org-clock-minutes-today))
14775 (outline-next-heading)
14776 (setq end (point))
14777 (when (memq which '(all special))
14778 ;; Get the special properties, like TODO and tags
14779 (goto-char beg)
14780 (when (and (or (not specific) (string= specific "TODO"))
14781 (looking-at org-todo-line-regexp) (match-end 2))
14782 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14783 (when (and (or (not specific) (string= specific "PRIORITY"))
14784 (looking-at org-priority-regexp))
14785 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14786 (when (or (not specific) (string= specific "FILE"))
14787 (push (cons "FILE" buffer-file-name) props))
14788 (when (and (or (not specific) (string= specific "TAGS"))
14789 (setq value (org-get-tags-string))
14790 (string-match "\\S-" value))
14791 (push (cons "TAGS" value) props))
14792 (when (and (or (not specific) (string= specific "ALLTAGS"))
14793 (setq value (org-get-tags-at)))
14794 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14795 ":"))
14796 props))
14797 (when (or (not specific) (string= specific "BLOCKED"))
14798 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14799 (when (or (not specific)
14800 (member specific
14801 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14802 "TIMESTAMP" "TIMESTAMP_IA")))
14803 (catch 'match
14804 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14805 (setq key (if (match-end 1)
14806 (substring (org-match-string-no-properties 1)
14807 0 -1))
14808 string (if (equal key clockstr)
14809 (org-trim
14810 (buffer-substring-no-properties
14811 (match-beginning 3) (goto-char
14812 (point-at-eol))))
14813 (substring (org-match-string-no-properties 3)
14814 1 -1)))
14815 ;; Get the correct property name from the key. This is
14816 ;; necessary if the user has configured time keywords.
14817 (setq key1 (concat key ":"))
14818 (cond
14819 ((not key)
14820 (setq key
14821 (if (= (char-after (match-beginning 3)) ?\[)
14822 "TIMESTAMP_IA" "TIMESTAMP")))
14823 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14824 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14825 ((equal key1 org-closed-string) (setq key "CLOSED"))
14826 ((equal key1 org-clock-string) (setq key "CLOCK")))
14827 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14828 (progn
14829 (push (cons key string) props)
14830 ;; no need to search further if match is found
14831 (throw 'match t))
14832 (when (or (equal key "CLOCK") (not (assoc key props)))
14833 (push (cons key string) props)))))))
14835 (when (memq which '(all standard))
14836 ;; Get the standard properties, like :PROP: ...
14837 (setq range (org-get-property-block beg end))
14838 (when range
14839 (goto-char (car range))
14840 (while (re-search-forward
14841 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14842 (cdr range) t)
14843 (setq key (org-match-string-no-properties 1)
14844 value (org-trim (or (org-match-string-no-properties 2) "")))
14845 (unless (member key excluded)
14846 (push (cons key (or value "")) props)))))
14847 (if clocksum
14848 (push (cons "CLOCKSUM"
14849 (org-columns-number-to-string (/ (float clocksum) 60.)
14850 'add_times))
14851 props))
14852 (if clocksumt
14853 (push (cons "CLOCKSUM_T"
14854 (org-columns-number-to-string (/ (float clocksumt) 60.)
14855 'add_times))
14856 props))
14857 (unless (assoc "CATEGORY" props)
14858 (push (cons "CATEGORY" (org-get-category)) props))
14859 (append sum-props (nreverse props)))))))
14861 (defun org-entry-get (pom property &optional inherit literal-nil)
14862 "Get value of PROPERTY for entry or content at point-or-marker POM.
14863 If INHERIT is non-nil and the entry does not have the property,
14864 then also check higher levels of the hierarchy.
14865 If INHERIT is the symbol `selective', use inheritance only if the setting
14866 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14867 If the property is present but empty, the return value is the empty string.
14868 If the property is not present at all, nil is returned.
14870 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14871 do not interpret it as the list atom nil. This is used for inheritance
14872 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14873 (org-with-point-at pom
14874 (if (and inherit (if (eq inherit 'selective)
14875 (org-property-inherit-p property)
14877 (org-entry-get-with-inheritance property literal-nil)
14878 (if (member property org-special-properties)
14879 ;; We need a special property. Use `org-entry-properties' to
14880 ;; retrieve it, but specify the wanted property
14881 (cdr (assoc property (org-entry-properties nil 'special property)))
14882 (let ((range (org-get-property-block)))
14883 (when (and range (not (eq (car range) (cdr range))))
14884 (let* ((props (list (or (assoc property org-file-properties)
14885 (assoc property org-global-properties)
14886 (assoc property org-global-properties-fixed))))
14887 (ap (lambda (key)
14888 (when (re-search-forward
14889 (org-re-property key) (cdr range) t)
14890 (setq props
14891 (org-update-property-plist
14893 (if (match-end 1)
14894 (org-match-string-no-properties 1) "")
14895 props)))))
14896 val)
14897 (goto-char (car range))
14898 (funcall ap property)
14899 (goto-char (car range))
14900 (while (funcall ap (concat property "+")))
14901 (setq val (cdr (assoc property props)))
14902 (when val (if literal-nil val (org-not-nil val))))))))))
14904 (defun org-property-or-variable-value (var &optional inherit)
14905 "Check if there is a property fixing the value of VAR.
14906 If yes, return this value. If not, return the current value of the variable."
14907 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14908 (if (and prop (stringp prop) (string-match "\\S-" prop))
14909 (read prop)
14910 (symbol-value var))))
14912 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14913 "Delete the property PROPERTY from entry at point-or-marker POM.
14914 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14915 an empty drawer to delete."
14916 (org-with-point-at pom
14917 (if (member property org-special-properties)
14918 nil ; cannot delete these properties.
14919 (let ((range (org-get-property-block)))
14920 (if (and range
14921 (goto-char (car range))
14922 (re-search-forward
14923 (org-re-property property)
14924 (cdr range) t))
14925 (progn
14926 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14927 (and delete-empty-drawer
14928 (org-remove-empty-drawer-at
14929 delete-empty-drawer (car range)))
14931 nil)))))
14933 ;; Multi-values properties are properties that contain multiple values
14934 ;; These values are assumed to be single words, separated by whitespace.
14935 (defun org-entry-add-to-multivalued-property (pom property value)
14936 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14937 (let* ((old (org-entry-get pom property))
14938 (values (and old (org-split-string old "[ \t]"))))
14939 (setq value (org-entry-protect-space value))
14940 (unless (member value values)
14941 (setq values (cons value values))
14942 (org-entry-put pom property
14943 (mapconcat 'identity values " ")))))
14945 (defun org-entry-remove-from-multivalued-property (pom property value)
14946 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14947 (let* ((old (org-entry-get pom property))
14948 (values (and old (org-split-string old "[ \t]"))))
14949 (setq value (org-entry-protect-space value))
14950 (when (member value values)
14951 (setq values (delete value values))
14952 (org-entry-put pom property
14953 (mapconcat 'identity values " ")))))
14955 (defun org-entry-member-in-multivalued-property (pom property value)
14956 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14957 (let* ((old (org-entry-get pom property))
14958 (values (and old (org-split-string old "[ \t]"))))
14959 (setq value (org-entry-protect-space value))
14960 (member value values)))
14962 (defun org-entry-get-multivalued-property (pom property)
14963 "Return a list of values in a multivalued property."
14964 (let* ((value (org-entry-get pom property))
14965 (values (and value (org-split-string value "[ \t]"))))
14966 (mapcar 'org-entry-restore-space values)))
14968 (defun org-entry-put-multivalued-property (pom property &rest values)
14969 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14970 VALUES should be a list of strings. Spaces will be protected."
14971 (org-entry-put pom property
14972 (mapconcat 'org-entry-protect-space values " "))
14973 (let* ((value (org-entry-get pom property))
14974 (values (and value (org-split-string value "[ \t]"))))
14975 (mapcar 'org-entry-restore-space values)))
14977 (defun org-entry-protect-space (s)
14978 "Protect spaces and newline in string S."
14979 (while (string-match " " s)
14980 (setq s (replace-match "%20" t t s)))
14981 (while (string-match "\n" s)
14982 (setq s (replace-match "%0A" t t s)))
14985 (defun org-entry-restore-space (s)
14986 "Restore spaces and newline in string S."
14987 (while (string-match "%20" s)
14988 (setq s (replace-match " " t t s)))
14989 (while (string-match "%0A" s)
14990 (setq s (replace-match "\n" t t s)))
14993 (defvar org-entry-property-inherited-from (make-marker)
14994 "Marker pointing to the entry from where a property was inherited.
14995 Each call to `org-entry-get-with-inheritance' will set this marker to the
14996 location of the entry where the inheritance search matched. If there was
14997 no match, the marker will point nowhere.
14998 Note that also `org-entry-get' calls this function, if the INHERIT flag
14999 is set.")
15001 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15002 "Get PROPERTY of entry or content at point, search higher levels if needed.
15003 The search will stop at the first ancestor which has the property defined.
15004 If the value found is \"nil\", return nil to show that the property
15005 should be considered as undefined (this is the meaning of nil here).
15006 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15007 (move-marker org-entry-property-inherited-from nil)
15008 (let (tmp)
15009 (save-excursion
15010 (save-restriction
15011 (widen)
15012 (catch 'ex
15013 (while t
15014 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15015 (or (ignore-errors (org-back-to-heading t))
15016 (goto-char (point-min)))
15017 (move-marker org-entry-property-inherited-from (point))
15018 (throw 'ex tmp))
15019 (or (ignore-errors (org-up-heading-safe))
15020 (throw 'ex nil))))))
15021 (setq tmp (or tmp
15022 (cdr (assoc property org-file-properties))
15023 (cdr (assoc property org-global-properties))
15024 (cdr (assoc property org-global-properties-fixed))))
15025 (if literal-nil tmp (org-not-nil tmp))))
15027 (defvar org-property-changed-functions nil
15028 "Hook called when the value of a property has changed.
15029 Each hook function should accept two arguments, the name of the property
15030 and the new value.")
15032 (defun org-entry-put (pom property value)
15033 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15034 (org-with-point-at pom
15035 (org-back-to-heading t)
15036 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15037 range)
15038 (cond
15039 ((equal property "TODO")
15040 (when (and (stringp value) (string-match "\\S-" value)
15041 (not (member value org-todo-keywords-1)))
15042 (error "\"%s\" is not a valid TODO state" value))
15043 (if (or (not value)
15044 (not (string-match "\\S-" value)))
15045 (setq value 'none))
15046 (org-todo value)
15047 (org-set-tags nil 'align))
15048 ((equal property "PRIORITY")
15049 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15050 (string-to-char value) ?\ ))
15051 (org-set-tags nil 'align))
15052 ((equal property "CLOCKSUM")
15053 (if (not (re-search-forward
15054 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15055 (error "Cannot find a clock log")
15056 (goto-char (- (match-end 1) 2))
15057 (cond
15058 ((eq value 'earlier) (org-timestamp-down))
15059 ((eq value 'later) (org-timestamp-up)))
15060 (org-clock-sum-current-item)))
15061 ((equal property "SCHEDULED")
15062 (if (re-search-forward org-scheduled-time-regexp end t)
15063 (cond
15064 ((eq value 'earlier) (org-timestamp-change -1 'day))
15065 ((eq value 'later) (org-timestamp-change 1 'day))
15066 (t (call-interactively 'org-schedule)))
15067 (call-interactively 'org-schedule)))
15068 ((equal property "DEADLINE")
15069 (if (re-search-forward org-deadline-time-regexp end t)
15070 (cond
15071 ((eq value 'earlier) (org-timestamp-change -1 'day))
15072 ((eq value 'later) (org-timestamp-change 1 'day))
15073 (t (call-interactively 'org-deadline)))
15074 (call-interactively 'org-deadline)))
15075 ((member property org-special-properties)
15076 (error "The %s property can not yet be set with `org-entry-put'"
15077 property))
15078 (t ; a non-special property
15079 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15080 (setq range (org-get-property-block beg end 'force))
15081 (goto-char (car range))
15082 (if (re-search-forward
15083 (org-re-property-keyword property) (cdr range) t)
15084 (progn
15085 (delete-region (match-beginning 0) (match-end 0))
15086 (goto-char (match-beginning 0)))
15087 (goto-char (cdr range))
15088 (insert "\n")
15089 (backward-char 1)
15090 (org-indent-line))
15091 (insert ":" property ":")
15092 (and value (insert " " value))
15093 (org-indent-line)))))
15094 (run-hook-with-args 'org-property-changed-functions property value)))
15096 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15097 "Get all property keys in the current buffer.
15098 With INCLUDE-SPECIALS, also list the special properties that reflect things
15099 like tags and TODO state.
15100 With INCLUDE-DEFAULTS, also include properties that has special meaning
15101 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15102 and others.
15103 With INCLUDE-COLUMNS, also include property names given in COLUMN
15104 formats in the current buffer."
15105 (let (rtn range cfmt s p)
15106 (save-excursion
15107 (save-restriction
15108 (widen)
15109 (goto-char (point-min))
15110 (while (re-search-forward org-property-start-re nil t)
15111 (setq range (org-get-property-block))
15112 (goto-char (car range))
15113 (while (re-search-forward
15114 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15115 (cdr range) t)
15116 (add-to-list 'rtn (org-match-string-no-properties 1)))
15117 (outline-next-heading))))
15119 (when include-specials
15120 (setq rtn (append org-special-properties rtn)))
15122 (when include-defaults
15123 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15124 (add-to-list 'rtn org-effort-property))
15126 (when include-columns
15127 (save-excursion
15128 (save-restriction
15129 (widen)
15130 (goto-char (point-min))
15131 (while (re-search-forward
15132 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15133 nil t)
15134 (setq cfmt (match-string 2) s 0)
15135 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15136 cfmt s)
15137 (setq s (match-end 0)
15138 p (match-string 1 cfmt))
15139 (unless (or (equal p "ITEM")
15140 (member p org-special-properties))
15141 (add-to-list 'rtn (match-string 1 cfmt))))))))
15143 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15145 (defun org-property-values (key)
15146 "Return a list of all values of property KEY in the current buffer."
15147 (save-excursion
15148 (save-restriction
15149 (widen)
15150 (goto-char (point-min))
15151 (let ((re (org-re-property key))
15152 values)
15153 (while (re-search-forward re nil t)
15154 (add-to-list 'values (org-trim (match-string 1))))
15155 (delete "" values)))))
15157 (defun org-insert-property-drawer ()
15158 "Insert a property drawer into the current entry."
15159 (org-back-to-heading t)
15160 (looking-at org-outline-regexp)
15161 (let ((indent (if org-adapt-indentation
15162 (- (match-end 0) (match-beginning 0))
15164 (beg (point))
15165 (re (concat "^[ \t]*" org-keyword-time-regexp))
15166 end hiddenp)
15167 (outline-next-heading)
15168 (setq end (point))
15169 (goto-char beg)
15170 (while (re-search-forward re end t))
15171 (setq hiddenp (outline-invisible-p))
15172 (end-of-line 1)
15173 (and (equal (char-after) ?\n) (forward-char 1))
15174 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15175 (if (member (match-string 1) '("CLOCK:" ":END:"))
15176 ;; just skip this line
15177 (beginning-of-line 2)
15178 ;; Drawer start, find the end
15179 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15180 (beginning-of-line 1)))
15181 (org-skip-over-state-notes)
15182 (skip-chars-backward " \t\n\r")
15183 (if (eq (char-before) ?*) (forward-char 1))
15184 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15185 (beginning-of-line 0)
15186 (org-indent-to-column indent)
15187 (beginning-of-line 2)
15188 (org-indent-to-column indent)
15189 (beginning-of-line 0)
15190 (if hiddenp
15191 (save-excursion
15192 (org-back-to-heading t)
15193 (hide-entry))
15194 (org-flag-drawer t))))
15196 (defun org-insert-drawer (&optional arg drawer)
15197 "Insert a drawer at point.
15199 Optional argument DRAWER, when non-nil, is a string representing
15200 drawer's name. Otherwise, the user is prompted for a name.
15202 If a region is active, insert the drawer around that region
15203 instead.
15205 Point is left between drawer's boundaries."
15206 (interactive "P")
15207 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15208 "LOGBOOK"))
15209 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15210 ;; internally by Org. They are meant to be inserted
15211 ;; automatically.
15212 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15213 ;; Remove system drawers from list. Note: For some reason,
15214 ;; `org-completing-read' ignores the predicate while
15215 ;; `completing-read' handles it fine.
15216 (drawer (if arg "PROPERTIES"
15217 (or drawer
15218 (completing-read
15219 "Drawer: " org-drawers
15220 (lambda (d) (not (member d system-drawers))))))))
15221 (cond
15222 ;; With C-u, fall back on `org-insert-property-drawer'
15223 (arg (org-insert-property-drawer))
15224 ;; With an active region, insert a drawer at point.
15225 ((not (org-region-active-p))
15226 (progn
15227 (unless (bolp) (insert "\n"))
15228 (insert (format ":%s:\n\n:END:\n" drawer))
15229 (forward-line -2)))
15230 ;; Otherwise, insert the drawer at point
15232 (let ((rbeg (region-beginning))
15233 (rend (copy-marker (region-end))))
15234 (unwind-protect
15235 (progn
15236 (goto-char rbeg)
15237 (beginning-of-line)
15238 (when (save-excursion
15239 (re-search-forward org-outline-regexp-bol rend t))
15240 (error "Drawers cannot contain headlines"))
15241 ;; Position point at the beginning of the first
15242 ;; non-blank line in region. Insert drawer's opening
15243 ;; there, then indent it.
15244 (org-skip-whitespace)
15245 (beginning-of-line)
15246 (insert ":" drawer ":\n")
15247 (forward-line -1)
15248 (indent-for-tab-command)
15249 ;; Move point to the beginning of the first blank line
15250 ;; after the last non-blank line in region. Insert
15251 ;; drawer's closing, then indent it.
15252 (goto-char rend)
15253 (skip-chars-backward " \r\t\n")
15254 (insert "\n:END:")
15255 (deactivate-mark t)
15256 (indent-for-tab-command)
15257 (unless (eolp) (insert "\n")))
15258 ;; Clear marker, whatever the outcome of insertion is.
15259 (set-marker rend nil)))))))
15261 (defvar org-property-set-functions-alist nil
15262 "Property set function alist.
15263 Each entry should have the following format:
15265 (PROPERTY . READ-FUNCTION)
15267 The read function will be called with the same argument as
15268 `org-completing-read'.")
15270 (defun org-set-property-function (property)
15271 "Get the function that should be used to set PROPERTY.
15272 This is computed according to `org-property-set-functions-alist'."
15273 (or (cdr (assoc property org-property-set-functions-alist))
15274 'org-completing-read))
15276 (defun org-read-property-value (property)
15277 "Read PROPERTY value from user."
15278 (let* ((completion-ignore-case t)
15279 (allowed (org-property-get-allowed-values nil property 'table))
15280 (cur (org-entry-get nil property))
15281 (prompt (concat property " value"
15282 (if (and cur (string-match "\\S-" cur))
15283 (concat " [" cur "]") "") ": "))
15284 (set-function (org-set-property-function property))
15285 (val (if allowed
15286 (funcall set-function prompt allowed nil
15287 (not (get-text-property 0 'org-unrestricted
15288 (caar allowed))))
15289 (let (org-completion-use-ido org-completion-use-iswitchb)
15290 (funcall set-function prompt
15291 (mapcar 'list (org-property-values property))
15292 nil nil "" nil cur)))))
15293 (if (equal val "")
15295 val)))
15297 (defvar org-last-set-property nil)
15298 (defvar org-last-set-property-value nil)
15299 (defun org-read-property-name ()
15300 "Read a property name."
15301 (let* ((completion-ignore-case t)
15302 (keys (org-buffer-property-keys nil t t))
15303 (default-prop (or (save-excursion
15304 (save-match-data
15305 (beginning-of-line)
15306 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15307 (null (string= (match-string 1) "END"))
15308 (match-string 1))))
15309 org-last-set-property))
15310 (property (org-icompleting-read
15311 (concat "Property"
15312 (if default-prop (concat " [" default-prop "]") "")
15313 ": ")
15314 (mapcar 'list keys)
15315 nil nil nil nil
15316 default-prop)))
15317 (if (member property keys)
15318 property
15319 (or (cdr (assoc (downcase property)
15320 (mapcar (lambda (x) (cons (downcase x) x))
15321 keys)))
15322 property))))
15324 (defun org-set-property-and-value (use-last)
15325 "Allow to set [PROPERTY]: [value] direction from prompt.
15326 When use-default, don't even ask, just use the last
15327 \"[PROPERTY]: [value]\" string from the history."
15328 (interactive "P")
15329 (let* ((completion-ignore-case t)
15330 (pv (or (and use-last org-last-set-property-value)
15331 (org-completing-read
15332 "Enter a \"[Property]: [value]\" pair: "
15333 nil nil nil nil nil
15334 org-last-set-property-value)))
15335 prop val)
15336 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15337 (setq prop (match-string 1 pv)
15338 val (match-string 2 pv))
15339 (org-set-property prop val))))
15341 (defun org-set-property (property value)
15342 "In the current entry, set PROPERTY to VALUE.
15343 When called interactively, this will prompt for a property name, offering
15344 completion on existing and default properties. And then it will prompt
15345 for a value, offering completion either on allowed values (via an inherited
15346 xxx_ALL property) or on existing values in other instances of this property
15347 in the current file."
15348 (interactive (list nil nil))
15349 (let* ((property (or property (org-read-property-name)))
15350 (value (or value (org-read-property-value property)))
15351 (fn (cdr (assoc property org-properties-postprocess-alist))))
15352 (setq org-last-set-property property)
15353 (setq org-last-set-property-value (concat property ": " value))
15354 ;; Possibly postprocess the inserted value:
15355 (when fn (setq value (funcall fn value)))
15356 (unless (equal (org-entry-get nil property) value)
15357 (org-entry-put nil property value))))
15359 (defun org-delete-property (property &optional delete-empty-drawer)
15360 "In the current entry, delete PROPERTY.
15361 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15362 an empty drawer to delete."
15363 (interactive
15364 (let* ((completion-ignore-case t)
15365 (prop (org-icompleting-read "Property: "
15366 (org-entry-properties nil 'standard))))
15367 (list prop)))
15368 (message "Property %s %s" property
15369 (if (org-entry-delete nil property delete-empty-drawer)
15370 "deleted"
15371 "was not present in the entry")))
15373 (defun org-delete-property-globally (property)
15374 "Remove PROPERTY globally, from all entries."
15375 (interactive
15376 (let* ((completion-ignore-case t)
15377 (prop (org-icompleting-read
15378 "Globally remove property: "
15379 (mapcar 'list (org-buffer-property-keys)))))
15380 (list prop)))
15381 (save-excursion
15382 (save-restriction
15383 (widen)
15384 (goto-char (point-min))
15385 (let ((cnt 0))
15386 (while (re-search-forward
15387 (org-re-property property)
15388 nil t)
15389 (setq cnt (1+ cnt))
15390 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15391 (message "Property \"%s\" removed from %d entries" property cnt)))))
15393 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15395 (defun org-compute-property-at-point ()
15396 "Compute the property at point.
15397 This looks for an enclosing column format, extracts the operator and
15398 then applies it to the property in the column format's scope."
15399 (interactive)
15400 (unless (org-at-property-p)
15401 (error "Not at a property"))
15402 (let ((prop (org-match-string-no-properties 2)))
15403 (org-columns-get-format-and-top-level)
15404 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15405 (error "No operator defined for property %s" prop))
15406 (org-columns-compute prop)))
15408 (defvar org-property-allowed-value-functions nil
15409 "Hook for functions supplying allowed values for a specific property.
15410 The functions must take a single argument, the name of the property, and
15411 return a flat list of allowed values. If \":ETC\" is one of
15412 the values, this means that these values are intended as defaults for
15413 completion, but that other values should be allowed too.
15414 The functions must return nil if they are not responsible for this
15415 property.")
15417 (defun org-property-get-allowed-values (pom property &optional table)
15418 "Get allowed values for the property PROPERTY.
15419 When TABLE is non-nil, return an alist that can directly be used for
15420 completion."
15421 (let (vals)
15422 (cond
15423 ((equal property "TODO")
15424 (setq vals (org-with-point-at pom
15425 (append org-todo-keywords-1 '("")))))
15426 ((equal property "PRIORITY")
15427 (let ((n org-lowest-priority))
15428 (while (>= n org-highest-priority)
15429 (push (char-to-string n) vals)
15430 (setq n (1- n)))))
15431 ((member property org-special-properties))
15432 ((setq vals (run-hook-with-args-until-success
15433 'org-property-allowed-value-functions property)))
15435 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15436 (when (and vals (string-match "\\S-" vals))
15437 (setq vals (car (read-from-string (concat "(" vals ")"))))
15438 (setq vals (mapcar (lambda (x)
15439 (cond ((stringp x) x)
15440 ((numberp x) (number-to-string x))
15441 ((symbolp x) (symbol-name x))
15442 (t "???")))
15443 vals)))))
15444 (when (member ":ETC" vals)
15445 (setq vals (remove ":ETC" vals))
15446 (org-add-props (car vals) '(org-unrestricted t)))
15447 (if table (mapcar 'list vals) vals)))
15449 (defun org-property-previous-allowed-value (&optional previous)
15450 "Switch to the next allowed value for this property."
15451 (interactive)
15452 (org-property-next-allowed-value t))
15454 (defun org-property-next-allowed-value (&optional previous)
15455 "Switch to the next allowed value for this property."
15456 (interactive)
15457 (unless (org-at-property-p)
15458 (error "Not at a property"))
15459 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15460 (key (match-string 2))
15461 (value (match-string 3))
15462 (allowed (or (org-property-get-allowed-values (point) key)
15463 (and (member value '("[ ]" "[-]" "[X]"))
15464 '("[ ]" "[X]"))))
15465 nval)
15466 (unless allowed
15467 (error "Allowed values for this property have not been defined"))
15468 (if previous (setq allowed (reverse allowed)))
15469 (if (member value allowed)
15470 (setq nval (car (cdr (member value allowed)))))
15471 (setq nval (or nval (car allowed)))
15472 (if (equal nval value)
15473 (error "Only one allowed value for this property"))
15474 (org-at-property-p)
15475 (replace-match (concat " :" key ": " nval) t t)
15476 (org-indent-line)
15477 (beginning-of-line 1)
15478 (skip-chars-forward " \t")
15479 (when (equal prop org-effort-property)
15480 (save-excursion
15481 (org-back-to-heading t)
15482 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15483 (run-hook-with-args 'org-property-changed-functions key nval)))
15485 (defun org-find-olp (path &optional this-buffer)
15486 "Return a marker pointing to the entry at outline path OLP.
15487 If anything goes wrong, throw an error.
15488 You can wrap this call to catch the error like this:
15490 (condition-case msg
15491 (org-mobile-locate-entry (match-string 4))
15492 (error (nth 1 msg)))
15494 The return value will then be either a string with the error message,
15495 or a marker if everything is OK.
15497 If THIS-BUFFER is set, the outline path does not contain a file,
15498 only headings."
15499 (let* ((file (if this-buffer buffer-file-name (pop path)))
15500 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15501 (level 1)
15502 (lmin 1)
15503 (lmax 1)
15504 limit re end found pos heading cnt flevel)
15505 (unless buffer (error "File not found :%s" file))
15506 (with-current-buffer buffer
15507 (save-excursion
15508 (save-restriction
15509 (widen)
15510 (setq limit (point-max))
15511 (goto-char (point-min))
15512 (while (setq heading (pop path))
15513 (setq re (format org-complex-heading-regexp-format
15514 (regexp-quote heading)))
15515 (setq cnt 0 pos (point))
15516 (while (re-search-forward re end t)
15517 (setq level (- (match-end 1) (match-beginning 1)))
15518 (if (and (>= level lmin) (<= level lmax))
15519 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15520 (when (= cnt 0) (error "Heading not found on level %d: %s"
15521 lmax heading))
15522 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15523 lmax heading))
15524 (goto-char found)
15525 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15526 (setq end (save-excursion (org-end-of-subtree t t))))
15527 (when (org-at-heading-p)
15528 (point-marker)))))))
15530 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15531 "Find node HEADING in BUFFER.
15532 Return a marker to the heading if it was found, or nil if not.
15533 If POS-ONLY is set, return just the position instead of a marker.
15535 The heading text must match exact, but it may have a TODO keyword,
15536 a priority cookie and tags in the standard locations."
15537 (with-current-buffer (or buffer (current-buffer))
15538 (save-excursion
15539 (save-restriction
15540 (widen)
15541 (goto-char (point-min))
15542 (let (case-fold-search)
15543 (if (re-search-forward
15544 (format org-complex-heading-regexp-format
15545 (regexp-quote heading)) nil t)
15546 (if pos-only
15547 (match-beginning 0)
15548 (move-marker (make-marker) (match-beginning 0)))))))))
15550 (defun org-find-exact-heading-in-directory (heading &optional dir)
15551 "Find Org node headline HEADING in all .org files in directory DIR.
15552 When the target headline is found, return a marker to this location."
15553 (let ((files (directory-files (or dir default-directory)
15554 nil "\\`[^.#].*\\.org\\'"))
15555 file visiting m buffer)
15556 (catch 'found
15557 (while (setq file (pop files))
15558 (message "trying %s" file)
15559 (setq visiting (org-find-base-buffer-visiting file))
15560 (setq buffer (or visiting (find-file-noselect file)))
15561 (setq m (org-find-exact-headline-in-buffer
15562 heading buffer))
15563 (when (and (not m) (not visiting)) (kill-buffer buffer))
15564 (and m (throw 'found m))))))
15566 (defun org-find-entry-with-id (ident)
15567 "Locate the entry that contains the ID property with exact value IDENT.
15568 IDENT can be a string, a symbol or a number, this function will search for
15569 the string representation of it.
15570 Return the position where this entry starts, or nil if there is no such entry."
15571 (interactive "sID: ")
15572 (let ((id (cond
15573 ((stringp ident) ident)
15574 ((symbol-name ident) (symbol-name ident))
15575 ((numberp ident) (number-to-string ident))
15576 (t (error "IDENT %s must be a string, symbol or number" ident))))
15577 (case-fold-search nil))
15578 (save-excursion
15579 (save-restriction
15580 (widen)
15581 (goto-char (point-min))
15582 (when (re-search-forward
15583 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15584 nil t)
15585 (org-back-to-heading t)
15586 (point))))))
15588 ;;;; Timestamps
15590 (defvar org-last-changed-timestamp nil)
15591 (defvar org-last-inserted-timestamp nil
15592 "The last time stamp inserted with `org-insert-time-stamp'.")
15593 (defvar org-time-was-given) ; dynamically scoped parameter
15594 (defvar org-end-time-was-given) ; dynamically scoped parameter
15595 (defvar org-ts-what) ; dynamically scoped parameter
15597 (defun org-time-stamp (arg &optional inactive)
15598 "Prompt for a date/time and insert a time stamp.
15599 If the user specifies a time like HH:MM or if this command is
15600 called with at least one prefix argument, the time stamp contains
15601 the date and the time. Otherwise, only the date is be included.
15603 All parts of a date not specified by the user is filled in from
15604 the current date/time. So if you just press return without
15605 typing anything, the time stamp will represent the current
15606 date/time.
15608 If there is already a timestamp at the cursor, it will be
15609 modified.
15611 With two universal prefix arguments, insert an active timestamp
15612 with the current time without prompting the user."
15613 (interactive "P")
15614 (let* ((ts nil)
15615 (default-time
15616 ;; Default time is either today, or, when entering a range,
15617 ;; the range start.
15618 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15619 (save-excursion
15620 (re-search-backward
15621 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15622 (- (point) 20) t)))
15623 (apply 'encode-time (org-parse-time-string (match-string 1)))
15624 (current-time)))
15625 (default-input (and ts (org-get-compact-tod ts)))
15626 (repeater (save-excursion
15627 (save-match-data
15628 (beginning-of-line)
15629 (when (re-search-forward
15630 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15631 (save-excursion (progn (end-of-line) (point))) t)
15632 (match-string 0)))))
15633 org-time-was-given org-end-time-was-given time)
15634 (cond
15635 ((and (org-at-timestamp-p t)
15636 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15637 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15638 (insert "--")
15639 (setq time (let ((this-command this-command))
15640 (org-read-date arg 'totime nil nil
15641 default-time default-input inactive)))
15642 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15643 ((org-at-timestamp-p t)
15644 (setq time (let ((this-command this-command))
15645 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15646 (when (org-at-timestamp-p t) ; just to get the match data
15647 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15648 (replace-match "")
15649 (setq org-last-changed-timestamp
15650 (org-insert-time-stamp
15651 time (or org-time-was-given arg)
15652 inactive nil nil (list org-end-time-was-given)))
15653 (when repeater (goto-char (1- (point))) (insert " " repeater)
15654 (setq org-last-changed-timestamp
15655 (concat (substring org-last-inserted-timestamp 0 -1)
15656 " " repeater ">"))))
15657 (message "Timestamp updated"))
15658 ((equal arg '(16))
15659 (org-insert-time-stamp (current-time) t))
15661 (setq time (let ((this-command this-command))
15662 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15663 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15664 nil nil (list org-end-time-was-given))))))
15666 ;; FIXME: can we use this for something else, like computing time differences?
15667 (defun org-get-compact-tod (s)
15668 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15669 (let* ((t1 (match-string 1 s))
15670 (h1 (string-to-number (match-string 2 s)))
15671 (m1 (string-to-number (match-string 3 s)))
15672 (t2 (and (match-end 4) (match-string 5 s)))
15673 (h2 (and t2 (string-to-number (match-string 6 s))))
15674 (m2 (and t2 (string-to-number (match-string 7 s))))
15675 dh dm)
15676 (if (not t2)
15678 (setq dh (- h2 h1) dm (- m2 m1))
15679 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15680 (concat t1 "+" (number-to-string dh)
15681 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15683 (defun org-time-stamp-inactive (&optional arg)
15684 "Insert an inactive time stamp.
15685 An inactive time stamp is enclosed in square brackets instead of angle
15686 brackets. It is inactive in the sense that it does not trigger agenda entries,
15687 does not link to the calendar and cannot be changed with the S-cursor keys.
15688 So these are more for recording a certain time/date."
15689 (interactive "P")
15690 (org-time-stamp arg 'inactive))
15692 (defvar org-date-ovl (make-overlay 1 1))
15693 (overlay-put org-date-ovl 'face 'org-date-selected)
15694 (org-detach-overlay org-date-ovl)
15696 (defvar org-ans1) ; dynamically scoped parameter
15697 (defvar org-ans2) ; dynamically scoped parameter
15699 (defvar org-plain-time-of-day-regexp) ; defined below
15701 (defvar org-overriding-default-time nil) ; dynamically scoped
15702 (defvar org-read-date-overlay nil)
15703 (defvar org-dcst nil) ; dynamically scoped
15704 (defvar org-read-date-history nil)
15705 (defvar org-read-date-final-answer nil)
15706 (defvar org-read-date-analyze-futurep nil)
15707 (defvar org-read-date-analyze-forced-year nil)
15708 (defvar org-read-date-inactive)
15710 (defvar org-read-date-minibuffer-local-map
15711 (let ((map (make-sparse-keymap)))
15712 (set-keymap-parent map minibuffer-local-map)
15713 (org-defkey map (kbd ".")
15714 (lambda () (interactive)
15715 (org-eval-in-calendar '(calendar-goto-today))))
15716 (org-defkey map [(meta shift left)]
15717 (lambda () (interactive)
15718 (org-eval-in-calendar '(calendar-backward-month 1))))
15719 (org-defkey map [(meta shift right)]
15720 (lambda () (interactive)
15721 (org-eval-in-calendar '(calendar-forward-month 1))))
15722 (org-defkey map [(meta shift up)]
15723 (lambda () (interactive)
15724 (org-eval-in-calendar '(calendar-backward-year 1))))
15725 (org-defkey map [(meta shift down)]
15726 (lambda () (interactive)
15727 (org-eval-in-calendar '(calendar-forward-year 1))))
15728 (org-defkey map [?\e (shift left)]
15729 (lambda () (interactive)
15730 (org-eval-in-calendar '(calendar-backward-month 1))))
15731 (org-defkey map [?\e (shift right)]
15732 (lambda () (interactive)
15733 (org-eval-in-calendar '(calendar-forward-month 1))))
15734 (org-defkey map [?\e (shift up)]
15735 (lambda () (interactive)
15736 (org-eval-in-calendar '(calendar-backward-year 1))))
15737 (org-defkey map [?\e (shift down)]
15738 (lambda () (interactive)
15739 (org-eval-in-calendar '(calendar-forward-year 1))))
15740 (org-defkey map [(shift up)]
15741 (lambda () (interactive)
15742 (org-eval-in-calendar '(calendar-backward-week 1))))
15743 (org-defkey map [(shift down)]
15744 (lambda () (interactive)
15745 (org-eval-in-calendar '(calendar-forward-week 1))))
15746 (org-defkey map [(shift left)]
15747 (lambda () (interactive)
15748 (org-eval-in-calendar '(calendar-backward-day 1))))
15749 (org-defkey map [(shift right)]
15750 (lambda () (interactive)
15751 (org-eval-in-calendar '(calendar-forward-day 1))))
15752 (org-defkey map "!"
15753 (lambda () (interactive)
15754 (org-eval-in-calendar '(diary-view-entries))
15755 (message "")))
15756 (org-defkey map ">"
15757 (lambda () (interactive)
15758 (org-eval-in-calendar '(scroll-calendar-left 1))))
15759 (org-defkey map "<"
15760 (lambda () (interactive)
15761 (org-eval-in-calendar '(scroll-calendar-right 1))))
15762 (org-defkey map "\C-v"
15763 (lambda () (interactive)
15764 (org-eval-in-calendar
15765 '(calendar-scroll-left-three-months 1))))
15766 (org-defkey map "\M-v"
15767 (lambda () (interactive)
15768 (org-eval-in-calendar
15769 '(calendar-scroll-right-three-months 1))))
15770 map)
15771 "Keymap for minibuffer commands when using `org-read-date'.")
15773 (defun org-read-date (&optional org-with-time to-time from-string prompt
15774 default-time default-input inactive)
15775 "Read a date, possibly a time, and make things smooth for the user.
15776 The prompt will suggest to enter an ISO date, but you can also enter anything
15777 which will at least partially be understood by `parse-time-string'.
15778 Unrecognized parts of the date will default to the current day, month, year,
15779 hour and minute. If this command is called to replace a timestamp at point,
15780 or to enter the second timestamp of a range, the default time is taken
15781 from the existing stamp. Furthermore, the command prefers the future,
15782 so if you are giving a date where the year is not given, and the day-month
15783 combination is already past in the current year, it will assume you
15784 mean next year. For details, see the manual. A few examples:
15786 3-2-5 --> 2003-02-05
15787 feb 15 --> currentyear-02-15
15788 2/15 --> currentyear-02-15
15789 sep 12 9 --> 2009-09-12
15790 12:45 --> today 12:45
15791 22 sept 0:34 --> currentyear-09-22 0:34
15792 12 --> currentyear-currentmonth-12
15793 Fri --> nearest Friday (today or later)
15794 etc.
15796 Furthermore you can specify a relative date by giving, as the *first* thing
15797 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15798 change in days weeks, months, years.
15799 With a single plus or minus, the date is relative to today. With a double
15800 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15801 +4d --> four days from today
15802 +4 --> same as above
15803 +2w --> two weeks from today
15804 ++5 --> five days from default date
15806 The function understands only English month and weekday abbreviations.
15808 While prompting, a calendar is popped up - you can also select the
15809 date with the mouse (button 1). The calendar shows a period of three
15810 months. To scroll it to other months, use the keys `>' and `<'.
15811 If you don't like the calendar, turn it off with
15812 \(setq org-read-date-popup-calendar nil)
15814 With optional argument TO-TIME, the date will immediately be converted
15815 to an internal time.
15816 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15817 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15818 still enter a time, and this function will inform the calling routine
15819 about this change. The calling routine may then choose to change the
15820 format used to insert the time stamp into the buffer to include the time.
15821 With optional argument FROM-STRING, read from this string instead from
15822 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15823 the time/date that is used for everything that is not specified by the
15824 user."
15825 (require 'parse-time)
15826 (let* ((org-time-stamp-rounding-minutes
15827 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15828 (org-dcst org-display-custom-times)
15829 (ct (org-current-time))
15830 (org-def (or org-overriding-default-time default-time ct))
15831 (org-defdecode (decode-time org-def))
15832 (dummy (progn
15833 (when (< (nth 2 org-defdecode) org-extend-today-until)
15834 (setcar (nthcdr 2 org-defdecode) -1)
15835 (setcar (nthcdr 1 org-defdecode) 59)
15836 (setq org-def (apply 'encode-time org-defdecode)
15837 org-defdecode (decode-time org-def)))))
15838 (mouse-autoselect-window nil) ; Don't let the mouse jump
15839 (calendar-frame-setup nil)
15840 (calendar-setup nil)
15841 (calendar-move-hook nil)
15842 (calendar-view-diary-initially-flag nil)
15843 (calendar-view-holidays-initially-flag nil)
15844 (timestr (format-time-string
15845 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15846 (prompt (concat (if prompt (concat prompt " ") "")
15847 (format "Date+time [%s]: " timestr)))
15848 ans (org-ans0 "") org-ans1 org-ans2 final)
15850 (cond
15851 (from-string (setq ans from-string))
15852 (org-read-date-popup-calendar
15853 (save-excursion
15854 (save-window-excursion
15855 (calendar)
15856 (org-eval-in-calendar '(setq cursor-type nil) t)
15857 (unwind-protect
15858 (progn
15859 (calendar-forward-day (- (time-to-days org-def)
15860 (calendar-absolute-from-gregorian
15861 (calendar-current-date))))
15862 (org-eval-in-calendar nil t)
15863 (let* ((old-map (current-local-map))
15864 (map (copy-keymap calendar-mode-map))
15865 (minibuffer-local-map
15866 (copy-keymap org-read-date-minibuffer-local-map)))
15867 (org-defkey map (kbd "RET") 'org-calendar-select)
15868 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15869 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15870 (unwind-protect
15871 (progn
15872 (use-local-map map)
15873 (setq org-read-date-inactive inactive)
15874 (add-hook 'post-command-hook 'org-read-date-display)
15875 (setq org-ans0 (read-string prompt default-input
15876 'org-read-date-history nil))
15877 ;; org-ans0: from prompt
15878 ;; org-ans1: from mouse click
15879 ;; org-ans2: from calendar motion
15880 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15881 (remove-hook 'post-command-hook 'org-read-date-display)
15882 (use-local-map old-map)
15883 (when org-read-date-overlay
15884 (delete-overlay org-read-date-overlay)
15885 (setq org-read-date-overlay nil)))))
15886 (bury-buffer "*Calendar*")))))
15888 (t ; Naked prompt only
15889 (unwind-protect
15890 (setq ans (read-string prompt default-input
15891 'org-read-date-history timestr))
15892 (when org-read-date-overlay
15893 (delete-overlay org-read-date-overlay)
15894 (setq org-read-date-overlay nil)))))
15896 (setq final (org-read-date-analyze ans org-def org-defdecode))
15898 (when org-read-date-analyze-forced-year
15899 (message "Year was forced into %s"
15900 (if org-read-date-force-compatible-dates
15901 "compatible range (1970-2037)"
15902 "range representable on this machine"))
15903 (ding))
15905 ;; One round trip to get rid of 34th of August and stuff like that....
15906 (setq final (decode-time (apply 'encode-time final)))
15908 (setq org-read-date-final-answer ans)
15910 (if to-time
15911 (apply 'encode-time final)
15912 (if (and (boundp 'org-time-was-given) org-time-was-given)
15913 (format "%04d-%02d-%02d %02d:%02d"
15914 (nth 5 final) (nth 4 final) (nth 3 final)
15915 (nth 2 final) (nth 1 final))
15916 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15918 (defvar org-def)
15919 (defvar org-defdecode)
15920 (defvar org-with-time)
15921 (defun org-read-date-display ()
15922 "Display the current date prompt interpretation in the minibuffer."
15923 (when org-read-date-display-live
15924 (when org-read-date-overlay
15925 (delete-overlay org-read-date-overlay))
15926 (when (minibufferp (current-buffer))
15927 (save-excursion
15928 (end-of-line 1)
15929 (while (not (equal (buffer-substring
15930 (max (point-min) (- (point) 4)) (point))
15931 " "))
15932 (insert " ")))
15933 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15934 " " (or org-ans1 org-ans2)))
15935 (org-end-time-was-given nil)
15936 (f (org-read-date-analyze ans org-def org-defdecode))
15937 (fmts (if org-dcst
15938 org-time-stamp-custom-formats
15939 org-time-stamp-formats))
15940 (fmt (if (or org-with-time
15941 (and (boundp 'org-time-was-given) org-time-was-given))
15942 (cdr fmts)
15943 (car fmts)))
15944 (txt (format-time-string fmt (apply 'encode-time f)))
15945 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15946 (txt (concat "=> " txt)))
15947 (when (and org-end-time-was-given
15948 (string-match org-plain-time-of-day-regexp txt))
15949 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15950 org-end-time-was-given
15951 (substring txt (match-end 0)))))
15952 (when org-read-date-analyze-futurep
15953 (setq txt (concat txt " (=>F)")))
15954 (setq org-read-date-overlay
15955 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15956 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15958 (defun org-read-date-analyze (ans org-def org-defdecode)
15959 "Analyze the combined answer of the date prompt."
15960 ;; FIXME: cleanup and comment
15961 (let ((nowdecode (decode-time (current-time)))
15962 delta deltan deltaw deltadef year month day
15963 hour minute second wday pm h2 m2 tl wday1
15964 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15965 (setq org-read-date-analyze-futurep nil
15966 org-read-date-analyze-forced-year nil)
15967 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15968 (setq ans "+0"))
15970 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15971 (setq ans (replace-match "" t t ans)
15972 deltan (car delta)
15973 deltaw (nth 1 delta)
15974 deltadef (nth 2 delta)))
15976 ;; Check if there is an iso week date in there. If yes, store the
15977 ;; info and postpone interpreting it until the rest of the parsing
15978 ;; is done.
15979 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15980 (setq iso-year (if (match-end 1)
15981 (org-small-year-to-year
15982 (string-to-number (match-string 1 ans))))
15983 iso-weekday (if (match-end 3)
15984 (string-to-number (match-string 3 ans)))
15985 iso-week (string-to-number (match-string 2 ans)))
15986 (setq ans (replace-match "" t t ans)))
15988 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15989 (when (string-match
15990 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15991 (setq year (if (match-end 2)
15992 (string-to-number (match-string 2 ans))
15993 (progn (setq kill-year t)
15994 (string-to-number (format-time-string "%Y"))))
15995 month (string-to-number (match-string 3 ans))
15996 day (string-to-number (match-string 4 ans)))
15997 (if (< year 100) (setq year (+ 2000 year)))
15998 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15999 t nil ans)))
16001 ;; Help matching dotted european dates
16002 (when (string-match
16003 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16004 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16005 (setq kill-year t)
16006 (string-to-number (format-time-string "%Y")))
16007 day (string-to-number (match-string 1 ans))
16008 month (string-to-number (match-string 2 ans))
16009 ans (replace-match (format "%04d-%02d-%02d" year month day)
16010 t nil ans)))
16012 ;; Help matching american dates, like 5/30 or 5/30/7
16013 (when (string-match
16014 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16015 (setq year (if (match-end 4)
16016 (string-to-number (match-string 4 ans))
16017 (progn (setq kill-year t)
16018 (string-to-number (format-time-string "%Y"))))
16019 month (string-to-number (match-string 1 ans))
16020 day (string-to-number (match-string 2 ans)))
16021 (if (< year 100) (setq year (+ 2000 year)))
16022 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16023 t nil ans)))
16024 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16025 ;; If there is a time with am/pm, and *no* time without it, we convert
16026 ;; so that matching will be successful.
16027 (loop for i from 1 to 2 do ; twice, for end time as well
16028 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16029 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16030 (setq hour (string-to-number (match-string 1 ans))
16031 minute (if (match-end 3)
16032 (string-to-number (match-string 3 ans))
16034 pm (equal ?p
16035 (string-to-char (downcase (match-string 4 ans)))))
16036 (if (and (= hour 12) (not pm))
16037 (setq hour 0)
16038 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16039 (setq ans (replace-match (format "%02d:%02d" hour minute)
16040 t t ans))))
16042 ;; Check if a time range is given as a duration
16043 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16044 (setq hour (string-to-number (match-string 1 ans))
16045 h2 (+ hour (string-to-number (match-string 3 ans)))
16046 minute (string-to-number (match-string 2 ans))
16047 m2 (+ minute (if (match-end 5) (string-to-number
16048 (match-string 5 ans))0)))
16049 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16050 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16051 t t ans)))
16053 ;; Check if there is a time range
16054 (when (boundp 'org-end-time-was-given)
16055 (setq org-time-was-given nil)
16056 (when (and (string-match org-plain-time-of-day-regexp ans)
16057 (match-end 8))
16058 (setq org-end-time-was-given (match-string 8 ans))
16059 (setq ans (concat (substring ans 0 (match-beginning 7))
16060 (substring ans (match-end 7))))))
16062 (setq tl (parse-time-string ans)
16063 day (or (nth 3 tl) (nth 3 org-defdecode))
16064 month (or (nth 4 tl)
16065 (if (and org-read-date-prefer-future
16066 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16067 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16068 (nth 4 org-defdecode)))
16069 year (or (and (not kill-year) (nth 5 tl))
16070 (if (and org-read-date-prefer-future
16071 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16072 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16073 (nth 5 org-defdecode)))
16074 hour (or (nth 2 tl) (nth 2 org-defdecode))
16075 minute (or (nth 1 tl) (nth 1 org-defdecode))
16076 second (or (nth 0 tl) 0)
16077 wday (nth 6 tl))
16079 (when (and (eq org-read-date-prefer-future 'time)
16080 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16081 (equal day (nth 3 nowdecode))
16082 (equal month (nth 4 nowdecode))
16083 (equal year (nth 5 nowdecode))
16084 (nth 2 tl)
16085 (or (< (nth 2 tl) (nth 2 nowdecode))
16086 (and (= (nth 2 tl) (nth 2 nowdecode))
16087 (nth 1 tl)
16088 (< (nth 1 tl) (nth 1 nowdecode)))))
16089 (setq day (1+ day)
16090 futurep t))
16092 ;; Special date definitions below
16093 (cond
16094 (iso-week
16095 ;; There was an iso week
16096 (require 'cal-iso)
16097 (setq futurep nil)
16098 (setq year (or iso-year year)
16099 day (or iso-weekday wday 1)
16100 wday nil ; to make sure that the trigger below does not match
16101 iso-date (calendar-gregorian-from-absolute
16102 (calendar-absolute-from-iso
16103 (list iso-week day year))))
16104 ; FIXME: Should we also push ISO weeks into the future?
16105 ; (when (and org-read-date-prefer-future
16106 ; (not iso-year)
16107 ; (< (calendar-absolute-from-gregorian iso-date)
16108 ; (time-to-days (current-time))))
16109 ; (setq year (1+ year)
16110 ; iso-date (calendar-gregorian-from-absolute
16111 ; (calendar-absolute-from-iso
16112 ; (list iso-week day year)))))
16113 (setq month (car iso-date)
16114 year (nth 2 iso-date)
16115 day (nth 1 iso-date)))
16116 (deltan
16117 (setq futurep nil)
16118 (unless deltadef
16119 (let ((now (decode-time (current-time))))
16120 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16121 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16122 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16123 ((equal deltaw "m") (setq month (+ month deltan)))
16124 ((equal deltaw "y") (setq year (+ year deltan)))))
16125 ((and wday (not (nth 3 tl)))
16126 ;; Weekday was given, but no day, so pick that day in the week
16127 ;; on or after the derived date.
16128 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16129 (unless (equal wday wday1)
16130 (setq day (+ day (% (- wday wday1 -7) 7))))))
16131 (if (and (boundp 'org-time-was-given)
16132 (nth 2 tl))
16133 (setq org-time-was-given t))
16134 (if (< year 100) (setq year (+ 2000 year)))
16135 ;; Check of the date is representable
16136 (if org-read-date-force-compatible-dates
16137 (progn
16138 (if (< year 1970)
16139 (setq year 1970 org-read-date-analyze-forced-year t))
16140 (if (> year 2037)
16141 (setq year 2037 org-read-date-analyze-forced-year t)))
16142 (condition-case nil
16143 (ignore (encode-time second minute hour day month year))
16144 (error
16145 (setq year (nth 5 org-defdecode))
16146 (setq org-read-date-analyze-forced-year t))))
16147 (setq org-read-date-analyze-futurep futurep)
16148 (list second minute hour day month year)))
16150 (defvar parse-time-weekdays)
16151 (defun org-read-date-get-relative (s today default)
16152 "Check string S for special relative date string.
16153 TODAY and DEFAULT are internal times, for today and for a default.
16154 Return shift list (N what def-flag)
16155 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16156 N is the number of WHATs to shift.
16157 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16158 the DEFAULT date rather than TODAY."
16159 (require 'parse-time)
16160 (when (and
16161 (string-match
16162 (concat
16163 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16164 "\\([0-9]+\\)?"
16165 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16166 "\\([ \t]\\|$\\)") s)
16167 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16168 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16169 (string-to-char (substring (match-string 1 s) -1))
16170 ?+))
16171 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16172 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16173 (what (if (match-end 3) (match-string 3 s) "d"))
16174 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16175 (date (if rel default today))
16176 (wday (nth 6 (decode-time date)))
16177 delta)
16178 (if wday1
16179 (progn
16180 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16181 (if (= dir ?-) (setq delta (- delta 7)))
16182 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16183 (list delta "d" rel))
16184 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16186 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16187 "Turn a user-specified date into the internal representation.
16188 The internal representation needed by the calendar is (month day year).
16189 This is a wrapper to handle the brain-dead convention in calendar that
16190 user function argument order change dependent on argument order."
16191 (if (boundp 'calendar-date-style)
16192 (cond
16193 ((eq calendar-date-style 'american)
16194 (list arg1 arg2 arg3))
16195 ((eq calendar-date-style 'european)
16196 (list arg2 arg1 arg3))
16197 ((eq calendar-date-style 'iso)
16198 (list arg2 arg3 arg1)))
16199 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16200 (if (org-bound-and-true-p european-calendar-style)
16201 (list arg2 arg1 arg3)
16202 (list arg1 arg2 arg3)))))
16204 (defun org-eval-in-calendar (form &optional keepdate)
16205 "Eval FORM in the calendar window and return to current window.
16206 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16207 otherwise stick to the current value of `org-ans2'."
16208 (let ((sf (selected-frame))
16209 (sw (selected-window)))
16210 (select-window (get-buffer-window "*Calendar*" t))
16211 (eval form)
16212 (when (and (not keepdate) (calendar-cursor-to-date))
16213 (let* ((date (calendar-cursor-to-date))
16214 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16215 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16216 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16217 (select-window sw)
16218 (org-select-frame-set-input-focus sf)))
16220 (defun org-calendar-select ()
16221 "Return to `org-read-date' with the date currently selected.
16222 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16223 (interactive)
16224 (when (calendar-cursor-to-date)
16225 (let* ((date (calendar-cursor-to-date))
16226 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16227 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16228 (if (active-minibuffer-window) (exit-minibuffer))))
16230 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16231 "Insert a date stamp for the date given by the internal TIME.
16232 WITH-HM means use the stamp format that includes the time of the day.
16233 INACTIVE means use square brackets instead of angular ones, so that the
16234 stamp will not contribute to the agenda.
16235 PRE and POST are optional strings to be inserted before and after the
16236 stamp.
16237 The command returns the inserted time stamp."
16238 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16239 stamp)
16240 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16241 (insert-before-markers (or pre ""))
16242 (when (listp extra)
16243 (setq extra (car extra))
16244 (if (and (stringp extra)
16245 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16246 (setq extra (format "-%02d:%02d"
16247 (string-to-number (match-string 1 extra))
16248 (string-to-number (match-string 2 extra))))
16249 (setq extra nil)))
16250 (when extra
16251 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16252 (insert-before-markers (setq stamp (format-time-string fmt time)))
16253 (insert-before-markers (or post ""))
16254 (setq org-last-inserted-timestamp stamp)))
16256 (defun org-toggle-time-stamp-overlays ()
16257 "Toggle the use of custom time stamp formats."
16258 (interactive)
16259 (setq org-display-custom-times (not org-display-custom-times))
16260 (unless org-display-custom-times
16261 (let ((p (point-min)) (bmp (buffer-modified-p)))
16262 (while (setq p (next-single-property-change p 'display))
16263 (if (and (get-text-property p 'display)
16264 (eq (get-text-property p 'face) 'org-date))
16265 (remove-text-properties
16266 p (setq p (next-single-property-change p 'display))
16267 '(display t))))
16268 (set-buffer-modified-p bmp)))
16269 (if (featurep 'xemacs)
16270 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16271 (org-restart-font-lock)
16272 (setq org-table-may-need-update t)
16273 (if org-display-custom-times
16274 (message "Time stamps are overlaid with custom format")
16275 (message "Time stamp overlays removed")))
16277 (defun org-display-custom-time (beg end)
16278 "Overlay modified time stamp format over timestamp between BEG and END."
16279 (let* ((ts (buffer-substring beg end))
16280 t1 w1 with-hm tf time str w2 (off 0))
16281 (save-match-data
16282 (setq t1 (org-parse-time-string ts t))
16283 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16284 (setq off (- (match-end 0) (match-beginning 0)))))
16285 (setq end (- end off))
16286 (setq w1 (- end beg)
16287 with-hm (and (nth 1 t1) (nth 2 t1))
16288 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16289 time (org-fix-decoded-time t1)
16290 str (org-add-props
16291 (format-time-string
16292 (substring tf 1 -1) (apply 'encode-time time))
16293 nil 'mouse-face 'highlight)
16294 w2 (length str))
16295 (if (not (= w2 w1))
16296 (add-text-properties (1+ beg) (+ 2 beg)
16297 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16298 (if (featurep 'xemacs)
16299 (progn
16300 (put-text-property beg end 'invisible t)
16301 (put-text-property beg end 'end-glyph (make-glyph str)))
16302 (put-text-property beg end 'display str))))
16304 (defun org-translate-time (string)
16305 "Translate all timestamps in STRING to custom format.
16306 But do this only if the variable `org-display-custom-times' is set."
16307 (when org-display-custom-times
16308 (save-match-data
16309 (let* ((start 0)
16310 (re org-ts-regexp-both)
16311 t1 with-hm inactive tf time str beg end)
16312 (while (setq start (string-match re string start))
16313 (setq beg (match-beginning 0)
16314 end (match-end 0)
16315 t1 (save-match-data
16316 (org-parse-time-string (substring string beg end) t))
16317 with-hm (and (nth 1 t1) (nth 2 t1))
16318 inactive (equal (substring string beg (1+ beg)) "[")
16319 tf (funcall (if with-hm 'cdr 'car)
16320 org-time-stamp-custom-formats)
16321 time (org-fix-decoded-time t1)
16322 str (format-time-string
16323 (concat
16324 (if inactive "[" "<") (substring tf 1 -1)
16325 (if inactive "]" ">"))
16326 (apply 'encode-time time))
16327 string (replace-match str t t string)
16328 start (+ start (length str)))))))
16329 string)
16331 (defun org-fix-decoded-time (time)
16332 "Set 0 instead of nil for the first 6 elements of time.
16333 Don't touch the rest."
16334 (let ((n 0))
16335 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16337 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16339 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16340 "Difference between TIMESTAMP-STRING and now in days.
16341 If SECONDS is non-nil, return the difference in seconds."
16342 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16343 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16344 (funcall fdiff (current-time)))))
16346 (defun org-deadline-close (timestamp-string &optional ndays)
16347 "Is the time in TIMESTAMP-STRING close to the current date?"
16348 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16349 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16350 (not (org-entry-is-done-p))))
16352 (defun org-get-wdays (ts &optional delay zero-delay)
16353 "Get the deadline lead time appropriate for timestring TS.
16354 When DELAY is non-nil, get the delay time for scheduled items
16355 instead of the deadline lead time. When ZERO-DELAY is non-nil
16356 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16357 don't try to find the delay cookie in the scheduled timestamp."
16358 (let ((tv (if delay org-scheduled-delay-days
16359 org-deadline-warning-days)))
16360 (cond
16361 ((or (and delay (< tv 0))
16362 (and delay zero-delay (<= tv 0))
16363 (and (not delay) (<= tv 0)))
16364 ;; Enforce this value no matter what
16365 (- tv))
16366 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16367 ;; lead time is specified.
16368 (floor (* (string-to-number (match-string 1 ts))
16369 (cdr (assoc (match-string 2 ts)
16370 '(("d" . 1) ("w" . 7)
16371 ("m" . 30.4) ("y" . 365.25)
16372 ("h" . 0.041667)))))))
16373 ;; go for the default.
16374 (t tv))))
16376 (defun org-calendar-select-mouse (ev)
16377 "Return to `org-read-date' with the date currently selected.
16378 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16379 (interactive "e")
16380 (mouse-set-point ev)
16381 (when (calendar-cursor-to-date)
16382 (let* ((date (calendar-cursor-to-date))
16383 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16384 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16385 (if (active-minibuffer-window) (exit-minibuffer))))
16387 (defun org-check-deadlines (ndays)
16388 "Check if there are any deadlines due or past due.
16389 A deadline is considered due if it happens within `org-deadline-warning-days'
16390 days from today's date. If the deadline appears in an entry marked DONE,
16391 it is not shown. The prefix arg NDAYS can be used to test that many
16392 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16393 (interactive "P")
16394 (let* ((org-warn-days
16395 (cond
16396 ((equal ndays '(4)) 100000)
16397 (ndays (prefix-numeric-value ndays))
16398 (t (abs org-deadline-warning-days))))
16399 (case-fold-search nil)
16400 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16401 (callback
16402 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16404 (message "%d deadlines past-due or due within %d days"
16405 (org-occur regexp nil callback)
16406 org-warn-days)))
16408 (defsubst org-re-timestamp (type)
16409 "Return a regexp for timestamp TYPE.
16410 Allowed values for TYPE are:
16412 all: all timestamps
16413 active: only active timestamps (<...>)
16414 inactive: only inactive timestamps ([...])
16415 scheduled: only scheduled timestamps
16416 deadline: only deadline timestamps
16418 When TYPE is nil, fall back on returning a regexp that matches
16419 both scheduled and deadline timestamps."
16420 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16421 ((eq type 'active) org-ts-regexp)
16422 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16423 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16424 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16425 ((eq type 'scheduled-or-deadline)
16426 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16428 (defun org-check-before-date (date)
16429 "Check if there are deadlines or scheduled entries before DATE."
16430 (interactive (list (org-read-date)))
16431 (let ((case-fold-search nil)
16432 (regexp (org-re-timestamp org-ts-type))
16433 (callback
16434 (lambda () (time-less-p
16435 (org-time-string-to-time (match-string 1))
16436 (org-time-string-to-time date)))))
16437 (message "%d entries before %s"
16438 (org-occur regexp nil callback) date)))
16440 (defun org-check-after-date (date)
16441 "Check if there are deadlines or scheduled entries after DATE."
16442 (interactive (list (org-read-date)))
16443 (let ((case-fold-search nil)
16444 (regexp (org-re-timestamp org-ts-type))
16445 (callback
16446 (lambda () (not
16447 (time-less-p
16448 (org-time-string-to-time (match-string 1))
16449 (org-time-string-to-time date))))))
16450 (message "%d entries after %s"
16451 (org-occur regexp nil callback) date)))
16453 (defun org-check-dates-range (start-date end-date)
16454 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16455 (interactive (list (org-read-date nil nil nil "Range starts")
16456 (org-read-date nil nil nil "Range end")))
16457 (let ((case-fold-search nil)
16458 (regexp (org-re-timestamp org-ts-type))
16459 (callback
16460 (lambda ()
16461 (let ((match (match-string 1)))
16462 (and
16463 (not (time-less-p
16464 (org-time-string-to-time match)
16465 (org-time-string-to-time start-date)))
16466 (time-less-p
16467 (org-time-string-to-time match)
16468 (org-time-string-to-time end-date)))))))
16469 (message "%d entries between %s and %s"
16470 (org-occur regexp nil callback) start-date end-date)))
16472 (defun org-evaluate-time-range (&optional to-buffer)
16473 "Evaluate a time range by computing the difference between start and end.
16474 Normally the result is just printed in the echo area, but with prefix arg
16475 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16476 If the time range is actually in a table, the result is inserted into the
16477 next column.
16478 For time difference computation, a year is assumed to be exactly 365
16479 days in order to avoid rounding problems."
16480 (interactive "P")
16482 (org-clock-update-time-maybe)
16483 (save-excursion
16484 (unless (org-at-date-range-p t)
16485 (goto-char (point-at-bol))
16486 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16487 (if (not (org-at-date-range-p t))
16488 (error "Not at a time-stamp range, and none found in current line")))
16489 (let* ((ts1 (match-string 1))
16490 (ts2 (match-string 2))
16491 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16492 (match-end (match-end 0))
16493 (time1 (org-time-string-to-time ts1))
16494 (time2 (org-time-string-to-time ts2))
16495 (t1 (org-float-time time1))
16496 (t2 (org-float-time time2))
16497 (diff (abs (- t2 t1)))
16498 (negative (< (- t2 t1) 0))
16499 ;; (ys (floor (* 365 24 60 60)))
16500 (ds (* 24 60 60))
16501 (hs (* 60 60))
16502 (fy "%dy %dd %02d:%02d")
16503 (fy1 "%dy %dd")
16504 (fd "%dd %02d:%02d")
16505 (fd1 "%dd")
16506 (fh "%02d:%02d")
16507 y d h m align)
16508 (if havetime
16509 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16511 d (floor (/ diff ds)) diff (mod diff ds)
16512 h (floor (/ diff hs)) diff (mod diff hs)
16513 m (floor (/ diff 60)))
16514 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16516 d (floor (+ (/ diff ds) 0.5))
16517 h 0 m 0))
16518 (if (not to-buffer)
16519 (message "%s" (org-make-tdiff-string y d h m))
16520 (if (org-at-table-p)
16521 (progn
16522 (goto-char match-end)
16523 (setq align t)
16524 (and (looking-at " *|") (goto-char (match-end 0))))
16525 (goto-char match-end))
16526 (if (looking-at
16527 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16528 (replace-match ""))
16529 (if negative (insert " -"))
16530 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16531 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16532 (insert " " (format fh h m))))
16533 (if align (org-table-align))
16534 (message "Time difference inserted")))))
16536 (defun org-make-tdiff-string (y d h m)
16537 (let ((fmt "")
16538 (l nil))
16539 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16540 l (push y l)))
16541 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16542 l (push d l)))
16543 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16544 l (push h l)))
16545 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16546 l (push m l)))
16547 (apply 'format fmt (nreverse l))))
16549 (defun org-time-string-to-time (s &optional buffer pos)
16550 "Convert a timestamp string into internal time."
16551 (condition-case errdata
16552 (apply 'encode-time (org-parse-time-string s))
16553 (error (error "Bad timestamp `%s'%s\nError was: %s"
16554 s (if (not (and buffer pos))
16556 (format " at %d in buffer `%s'" pos buffer))
16557 (cdr errdata)))))
16559 (defun org-time-string-to-seconds (s)
16560 "Convert a timestamp string to a number of seconds."
16561 (org-float-time (org-time-string-to-time s)))
16563 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16564 "Convert a time stamp to an absolute day number.
16565 If there is a specifier for a cyclic time stamp, get the closest
16566 date to DAYNR.
16567 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16568 The variable date is bound by the calendar when this is called."
16569 (cond
16570 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16571 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16572 daynr
16573 (+ daynr 1000)))
16574 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16575 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16576 (time-to-days (current-time))) (match-string 0 s)
16577 prefer show-all))
16578 (t (time-to-days
16579 (condition-case errdata
16580 (apply 'encode-time (org-parse-time-string s))
16581 (error (error "Bad timestamp `%s'%s\nError was: %s"
16582 s (if (not (and buffer pos))
16584 (format " at %d in buffer `%s'" pos buffer))
16585 (cdr errdata))))))))
16587 (defun org-days-to-iso-week (days)
16588 "Return the iso week number."
16589 (require 'cal-iso)
16590 (car (calendar-iso-from-absolute days)))
16592 (defun org-small-year-to-year (year)
16593 "Convert 2-digit years into 4-digit years.
16594 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16595 The year 2000 cannot be abbreviated. Any year larger than 99
16596 is returned unchanged."
16597 (if (< year 38)
16598 (setq year (+ 2000 year))
16599 (if (< year 100)
16600 (setq year (+ 1900 year))))
16601 year)
16603 (defun org-time-from-absolute (d)
16604 "Return the time corresponding to date D.
16605 D may be an absolute day number, or a calendar-type list (month day year)."
16606 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16607 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16609 (defun org-calendar-holiday ()
16610 "List of holidays, for Diary display in Org-mode."
16611 (require 'holidays)
16612 (let ((hl (funcall
16613 (if (fboundp 'calendar-check-holidays)
16614 'calendar-check-holidays 'check-calendar-holidays) date)))
16615 (if hl (mapconcat 'identity hl "; "))))
16617 (defun org-diary-sexp-entry (sexp entry date)
16618 "Process a SEXP diary ENTRY for DATE."
16619 (require 'diary-lib)
16620 (let ((result (if calendar-debug-sexp
16621 (let ((stack-trace-on-error t))
16622 (eval (car (read-from-string sexp))))
16623 (condition-case nil
16624 (eval (car (read-from-string sexp)))
16625 (error
16626 (beep)
16627 (message "Bad sexp at line %d in %s: %s"
16628 (org-current-line)
16629 (buffer-file-name) sexp)
16630 (sleep-for 2))))))
16631 (cond ((stringp result) (split-string result "; "))
16632 ((and (consp result)
16633 (not (consp (cdr result)))
16634 (stringp (cdr result))) (cdr result))
16635 ((and (consp result)
16636 (stringp (car result))) result)
16637 (result entry))))
16639 (defun org-diary-to-ical-string (frombuf)
16640 "Get iCalendar entries from diary entries in buffer FROMBUF.
16641 This uses the icalendar.el library."
16642 (let* ((tmpdir (if (featurep 'xemacs)
16643 (temp-directory)
16644 temporary-file-directory))
16645 (tmpfile (make-temp-name
16646 (expand-file-name "orgics" tmpdir)))
16647 buf rtn b e)
16648 (with-current-buffer frombuf
16649 (icalendar-export-region (point-min) (point-max) tmpfile)
16650 (setq buf (find-buffer-visiting tmpfile))
16651 (set-buffer buf)
16652 (goto-char (point-min))
16653 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16654 (setq b (match-beginning 0)))
16655 (goto-char (point-max))
16656 (if (re-search-backward "^END:VEVENT" nil t)
16657 (setq e (match-end 0)))
16658 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16659 (kill-buffer buf)
16660 (delete-file tmpfile)
16661 rtn))
16663 (defun org-closest-date (start current change prefer show-all)
16664 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16665 When PREFER is `past', return a date that is either CURRENT or past.
16666 When PREFER is `future', return a date that is either CURRENT or future.
16667 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16668 ;; Make the proper lists from the dates
16669 (catch 'exit
16670 (let ((a1 '(("h" . hour)
16671 ("d" . day)
16672 ("w" . week)
16673 ("m" . month)
16674 ("y" . year)))
16675 (shour (nth 2 (org-parse-time-string start)))
16676 dn dw sday cday n1 n2 n0
16677 d m y y1 y2 date1 date2 nmonths nm ny m2)
16679 (setq start (org-date-to-gregorian start)
16680 current (org-date-to-gregorian
16681 (if show-all
16682 current
16683 (time-to-days (current-time))))
16684 sday (calendar-absolute-from-gregorian start)
16685 cday (calendar-absolute-from-gregorian current))
16687 (if (<= cday sday) (throw 'exit sday))
16689 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16690 (setq dn (string-to-number (match-string 1 change))
16691 dw (cdr (assoc (match-string 2 change) a1)))
16692 (error "Invalid change specifier: %s" change))
16693 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16694 (cond
16695 ((eq dw 'hour)
16696 (let ((missing-hours
16697 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16698 dn)))
16699 (setq n1 (if (zerop missing-hours) cday
16700 (- cday (1+ (floor (/ missing-hours 24)))))
16701 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16702 ((eq dw 'day)
16703 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16704 n2 (+ n1 dn)))
16705 ((eq dw 'year)
16706 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16707 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16708 (setq date1 (list m d y1)
16709 n1 (calendar-absolute-from-gregorian date1)
16710 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16711 n2 (calendar-absolute-from-gregorian date2)))
16712 ((eq dw 'month)
16713 ;; approx number of month between the two dates
16714 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16715 ;; How often does dn fit in there?
16716 (setq d (nth 1 start) m (car start) y (nth 2 start)
16717 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16718 m (+ m nm)
16719 ny (floor (/ m 12))
16720 y (+ y ny)
16721 m (- m (* ny 12)))
16722 (while (> m 12) (setq m (- m 12) y (1+ y)))
16723 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16724 (setq m2 (+ m dn) y2 y)
16725 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16726 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16727 (while (<= n2 cday)
16728 (setq n1 n2 m m2 y y2)
16729 (setq m2 (+ m dn) y2 y)
16730 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16731 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16732 ;; Make sure n1 is the earlier date
16733 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16734 (if show-all
16735 (cond
16736 ((eq prefer 'past) (if (= cday n2) n2 n1))
16737 ((eq prefer 'future) (if (= cday n1) n1 n2))
16738 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16739 (cond
16740 ((eq prefer 'past) (if (= cday n2) n2 n1))
16741 ((eq prefer 'future) (if (= cday n1) n1 n2))
16742 (t (if (= cday n1) n1 n2)))))))
16744 (defun org-date-to-gregorian (date)
16745 "Turn any specification of DATE into a Gregorian date for the calendar."
16746 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16747 ((and (listp date) (= (length date) 3)) date)
16748 ((stringp date)
16749 (setq date (org-parse-time-string date))
16750 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16751 ((listp date)
16752 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16754 (defun org-parse-time-string (s &optional nodefault)
16755 "Parse the standard Org-mode time string.
16756 This should be a lot faster than the normal `parse-time-string'.
16757 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16758 hour and minute fields will be nil if not given."
16759 (cond ((string-match org-ts-regexp0 s)
16760 (list 0
16761 (if (or (match-beginning 8) (not nodefault))
16762 (string-to-number (or (match-string 8 s) "0")))
16763 (if (or (match-beginning 7) (not nodefault))
16764 (string-to-number (or (match-string 7 s) "0")))
16765 (string-to-number (match-string 4 s))
16766 (string-to-number (match-string 3 s))
16767 (string-to-number (match-string 2 s))
16768 nil nil nil))
16769 ((string-match "^<[^>]+>$" s)
16770 (decode-time (seconds-to-time (org-matcher-time s))))
16771 (t (error "Not a standard Org-mode time string: %s" s))))
16773 (defun org-timestamp-up (&optional arg)
16774 "Increase the date item at the cursor by one.
16775 If the cursor is on the year, change the year. If it is on the month,
16776 the day or the time, change that.
16777 With prefix ARG, change by that many units."
16778 (interactive "p")
16779 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16781 (defun org-timestamp-down (&optional arg)
16782 "Decrease the date item at the cursor by one.
16783 If the cursor is on the year, change the year. If it is on the month,
16784 the day or the time, change that.
16785 With prefix ARG, change by that many units."
16786 (interactive "p")
16787 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16789 (defun org-timestamp-up-day (&optional arg)
16790 "Increase the date in the time stamp by one day.
16791 With prefix ARG, change that many days."
16792 (interactive "p")
16793 (if (and (not (org-at-timestamp-p t))
16794 (org-at-heading-p))
16795 (org-todo 'up)
16796 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16798 (defun org-timestamp-down-day (&optional arg)
16799 "Decrease the date in the time stamp by one day.
16800 With prefix ARG, change that many days."
16801 (interactive "p")
16802 (if (and (not (org-at-timestamp-p t))
16803 (org-at-heading-p))
16804 (org-todo 'down)
16805 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16807 (defun org-at-timestamp-p (&optional inactive-ok)
16808 "Determine if the cursor is in or at a timestamp."
16809 (interactive)
16810 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16811 (pos (point))
16812 (ans (or (looking-at tsr)
16813 (save-excursion
16814 (skip-chars-backward "^[<\n\r\t")
16815 (if (> (point) (point-min)) (backward-char 1))
16816 (and (looking-at tsr)
16817 (> (- (match-end 0) pos) -1))))))
16818 (and ans
16819 (boundp 'org-ts-what)
16820 (setq org-ts-what
16821 (cond
16822 ((= pos (match-beginning 0)) 'bracket)
16823 ;; Point is considered to be "on the bracket" whether
16824 ;; it's really on it or right after it.
16825 ((= pos (1- (match-end 0))) 'bracket)
16826 ((= pos (match-end 0)) 'after)
16827 ((org-pos-in-match-range pos 2) 'year)
16828 ((org-pos-in-match-range pos 3) 'month)
16829 ((org-pos-in-match-range pos 7) 'hour)
16830 ((org-pos-in-match-range pos 8) 'minute)
16831 ((or (org-pos-in-match-range pos 4)
16832 (org-pos-in-match-range pos 5)) 'day)
16833 ((and (> pos (or (match-end 8) (match-end 5)))
16834 (< pos (match-end 0)))
16835 (- pos (or (match-end 8) (match-end 5))))
16836 (t 'day))))
16837 ans))
16839 (defun org-toggle-timestamp-type ()
16840 "Toggle the type (<active> or [inactive]) of a time stamp."
16841 (interactive)
16842 (when (org-at-timestamp-p t)
16843 (let ((beg (match-beginning 0)) (end (match-end 0))
16844 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16845 (save-excursion
16846 (goto-char beg)
16847 (while (re-search-forward "[][<>]" end t)
16848 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16849 t t)))
16850 (message "Timestamp is now %sactive"
16851 (if (equal (char-after beg) ?<) "" "in")))))
16853 (defvar org-clock-history) ; defined in org-clock.el
16854 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16855 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16856 "Change the date in the time stamp at point.
16857 The date will be changed by N times WHAT. WHAT can be `day', `month',
16858 `year', `minute', `second'. If WHAT is not given, the cursor position
16859 in the timestamp determines what will be changed.
16860 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16861 (let ((origin (point)) origin-cat
16862 with-hm inactive
16863 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16864 org-ts-what
16865 extra rem
16866 ts time time0 fixnext clrgx)
16867 (if (not (org-at-timestamp-p t))
16868 (error "Not at a timestamp"))
16869 (if (and (not what) (eq org-ts-what 'bracket))
16870 (org-toggle-timestamp-type)
16871 ;; Point isn't on brackets. Remember the part of the time-stamp
16872 ;; the point was in. Indeed, size of time-stamps may change,
16873 ;; but point must be kept in the same category nonetheless.
16874 (setq origin-cat org-ts-what)
16875 (if (and (not what) (not (eq org-ts-what 'day))
16876 org-display-custom-times
16877 (get-text-property (point) 'display)
16878 (not (get-text-property (1- (point)) 'display)))
16879 (setq org-ts-what 'day))
16880 (setq org-ts-what (or what org-ts-what)
16881 inactive (= (char-after (match-beginning 0)) ?\[)
16882 ts (match-string 0))
16883 (replace-match "")
16884 (when (string-match
16885 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16887 (setq extra (match-string 1 ts))
16888 (if suppress-tmp-delay
16889 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16890 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16891 (setq with-hm t))
16892 (setq time0 (org-parse-time-string ts))
16893 (when (and updown
16894 (eq org-ts-what 'minute)
16895 (not current-prefix-arg))
16896 ;; This looks like s-up and s-down. Change by one rounding step.
16897 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16898 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16899 (setcar (cdr time0) (+ (nth 1 time0)
16900 (if (> n 0) (- rem) (- dm rem))))))
16901 (setq time
16902 (encode-time (or (car time0) 0)
16903 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16904 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16905 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16906 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16907 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16908 (nthcdr 6 time0)))
16909 (when (and (member org-ts-what '(hour minute))
16910 extra
16911 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16912 (setq extra (org-modify-ts-extra
16913 extra
16914 (if (eq org-ts-what 'hour) 2 5)
16915 n dm)))
16916 (when (integerp org-ts-what)
16917 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16918 (if (eq what 'calendar)
16919 (let ((cal-date (org-get-date-from-calendar)))
16920 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16921 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16922 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16923 (setcar time0 (or (car time0) 0))
16924 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16925 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16926 (setq time (apply 'encode-time time0))))
16927 ;; Insert the new time-stamp, and ensure point stays in the same
16928 ;; category as before (i.e. not after the last position in that
16929 ;; category).
16930 (let ((pos (point)))
16931 ;; Stay before inserted string. `save-excursion' is of no use.
16932 (setq org-last-changed-timestamp
16933 (org-insert-time-stamp time with-hm inactive nil nil extra))
16934 (goto-char pos))
16935 (save-match-data
16936 (looking-at org-ts-regexp3)
16937 (goto-char (cond
16938 ;; `day' category ends before `hour' if any, or at
16939 ;; the end of the day name.
16940 ((eq origin-cat 'day)
16941 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16942 ((eq origin-cat 'hour) (min (match-end 7) origin))
16943 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16944 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16945 ;; `year' and `month' have both fixed size: point
16946 ;; couldn't have moved into another part.
16947 (t origin))))
16948 ;; Update clock if on a CLOCK line.
16949 (org-clock-update-time-maybe)
16950 ;; Maybe adjust the closest clock in `org-clock-history'
16951 (when org-clock-adjust-closest
16952 (if (not (and (org-at-clock-log-p)
16953 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16954 org-clock-history))))))
16955 (message "No clock to adjust")
16956 (cond ((save-excursion ; fix previous clock?
16957 (re-search-backward org-ts-regexp0 nil t)
16958 (org-looking-back (concat org-clock-string " \\[")))
16959 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16960 ((save-excursion ; fix next clock?
16961 (re-search-backward org-ts-regexp0 nil t)
16962 (looking-at (concat org-ts-regexp0 "\\] =>")))
16963 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16964 (save-window-excursion
16965 ;; Find closest clock to point, adjust the previous/next one in history
16966 (let* ((p (save-excursion (org-back-to-heading t)))
16967 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16968 (clfixnth
16969 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16970 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16971 (if (not clfixpos)
16972 (message "No clock to adjust")
16973 (save-excursion
16974 (org-goto-marker-or-bmk clfixpos)
16975 (org-show-subtree)
16976 (when (re-search-forward clrgx nil t)
16977 (goto-char (match-beginning 1))
16978 (let (org-clock-adjust-closest)
16979 (org-timestamp-change n org-ts-what updown))
16980 (message "Clock adjusted in %s for heading: %s"
16981 (file-name-nondirectory (buffer-file-name))
16982 (org-get-heading t t)))))))))
16983 ;; Try to recenter the calendar window, if any.
16984 (if (and org-calendar-follow-timestamp-change
16985 (get-buffer-window "*Calendar*" t)
16986 (memq org-ts-what '(day month year)))
16987 (org-recenter-calendar (time-to-days time))))))
16989 (defun org-modify-ts-extra (s pos n dm)
16990 "Change the different parts of the lead-time and repeat fields in timestamp."
16991 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16992 ng h m new rem)
16993 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16994 (cond
16995 ((or (org-pos-in-match-range pos 2)
16996 (org-pos-in-match-range pos 3))
16997 (setq m (string-to-number (match-string 3 s))
16998 h (string-to-number (match-string 2 s)))
16999 (if (org-pos-in-match-range pos 2)
17000 (setq h (+ h n))
17001 (setq n (* dm (org-no-warnings (signum n))))
17002 (when (not (= 0 (setq rem (% m dm))))
17003 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17004 (setq m (+ m n)))
17005 (if (< m 0) (setq m (+ m 60) h (1- h)))
17006 (if (> m 59) (setq m (- m 60) h (1+ h)))
17007 (setq h (min 24 (max 0 h)))
17008 (setq ng 1 new (format "-%02d:%02d" h m)))
17009 ((org-pos-in-match-range pos 6)
17010 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17011 ((org-pos-in-match-range pos 5)
17012 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17014 ((org-pos-in-match-range pos 9)
17015 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17016 ((org-pos-in-match-range pos 8)
17017 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17019 (when ng
17020 (setq s (concat
17021 (substring s 0 (match-beginning ng))
17023 (substring s (match-end ng))))))
17026 (defun org-recenter-calendar (date)
17027 "If the calendar is visible, recenter it to DATE."
17028 (let ((cwin (get-buffer-window "*Calendar*" t)))
17029 (when cwin
17030 (let ((calendar-move-hook nil))
17031 (with-selected-window cwin
17032 (calendar-goto-date (if (listp date) date
17033 (calendar-gregorian-from-absolute date))))))))
17035 (defun org-goto-calendar (&optional arg)
17036 "Go to the Emacs calendar at the current date.
17037 If there is a time stamp in the current line, go to that date.
17038 A prefix ARG can be used to force the current date."
17039 (interactive "P")
17040 (let ((tsr org-ts-regexp) diff
17041 (calendar-move-hook nil)
17042 (calendar-view-holidays-initially-flag nil)
17043 (calendar-view-diary-initially-flag nil))
17044 (if (or (org-at-timestamp-p)
17045 (save-excursion
17046 (beginning-of-line 1)
17047 (looking-at (concat ".*" tsr))))
17048 (let ((d1 (time-to-days (current-time)))
17049 (d2 (time-to-days
17050 (org-time-string-to-time (match-string 1)))))
17051 (setq diff (- d2 d1))))
17052 (calendar)
17053 (calendar-goto-today)
17054 (if (and diff (not arg)) (calendar-forward-day diff))))
17056 (defun org-get-date-from-calendar ()
17057 "Return a list (month day year) of date at point in calendar."
17058 (with-current-buffer "*Calendar*"
17059 (save-match-data
17060 (calendar-cursor-to-date))))
17062 (defun org-date-from-calendar ()
17063 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17064 If there is already a time stamp at the cursor position, update it."
17065 (interactive)
17066 (if (org-at-timestamp-p t)
17067 (org-timestamp-change 0 'calendar)
17068 (let ((cal-date (org-get-date-from-calendar)))
17069 (org-insert-time-stamp
17070 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17072 (defcustom org-effort-durations
17073 `(("h" . 60)
17074 ("d" . ,(* 60 8))
17075 ("w" . ,(* 60 8 5))
17076 ("m" . ,(* 60 8 5 4))
17077 ("y" . ,(* 60 8 5 40)))
17078 "Conversion factor to minutes for an effort modifier.
17080 Each entry has the form (MODIFIER . MINUTES).
17082 In an effort string, a number followed by MODIFIER is multiplied
17083 by the specified number of MINUTES to obtain an effort in
17084 minutes.
17086 For example, if the value of this variable is ((\"hours\" . 60)), then an
17087 effort string \"2hours\" is equivalent to 120 minutes."
17088 :group 'org-agenda
17089 :version "24.1"
17090 :type '(alist :key-type (string :tag "Modifier")
17091 :value-type (number :tag "Minutes")))
17093 (defun org-minutes-to-clocksum-string (m)
17094 "Format number of minutes as a clocksum string.
17095 The format is determined by `org-time-clocksum-format',
17096 `org-time-clocksum-use-fractional' and
17097 `org-time-clocksum-fractional-format' and
17098 `org-time-clocksum-use-effort-durations'."
17099 (let ((clocksum "") h d w mo y fmt n)
17100 (setq h (if org-time-clocksum-use-effort-durations
17101 (cdr (assoc "h" org-effort-durations)) 60)
17102 d (if org-time-clocksum-use-effort-durations
17103 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17104 w (if org-time-clocksum-use-effort-durations
17105 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17106 mo (if org-time-clocksum-use-effort-durations
17107 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17108 y (if org-time-clocksum-use-effort-durations
17109 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17110 ;; fractional format
17111 (if org-time-clocksum-use-fractional
17112 (cond
17113 ;; single format string
17114 ((stringp org-time-clocksum-fractional-format)
17115 (format org-time-clocksum-fractional-format (/ m (float h))))
17116 ;; choice of fractional formats for different time units
17117 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17118 (> (/ (truncate m) (* y d h)) 0))
17119 (format fmt (/ m (* y d (float h)))))
17120 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17121 (> (/ (truncate m) (* mo d h)) 0))
17122 (format fmt (/ m (* mo d (float h)))))
17123 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17124 (> (/ (truncate m) (* w d h)) 0))
17125 (format fmt (/ m (* w d (float h)))))
17126 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17127 (> (/ (truncate m) (* d h)) 0))
17128 (format fmt (/ m (* d (float h)))))
17129 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17130 (> (/ (truncate m) h) 0))
17131 (format fmt (/ m (float h))))
17132 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17133 (format fmt m))
17134 ;; fall back to smallest time unit with a format
17135 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17136 (format fmt (/ m (float h))))
17137 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17138 (format fmt (/ m (* d (float h)))))
17139 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17140 (format fmt (/ m (* w d (float h)))))
17141 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17142 (format fmt (/ m (* mo d (float h)))))
17143 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17144 (format fmt (/ m (* y d (float h))))))
17145 ;; standard (non-fractional) format, with single format string
17146 (if (stringp org-time-clocksum-format)
17147 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17148 ;; separate formats components
17149 (and (setq fmt (plist-get org-time-clocksum-format :years))
17150 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17151 (plist-get org-time-clocksum-format :require-years))
17152 (setq clocksum (concat clocksum (format fmt n))
17153 m (- m (* n y d h))))
17154 (and (setq fmt (plist-get org-time-clocksum-format :months))
17155 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17156 (plist-get org-time-clocksum-format :require-months))
17157 (setq clocksum (concat clocksum (format fmt n))
17158 m (- m (* n mo d h))))
17159 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17160 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17161 (plist-get org-time-clocksum-format :require-weeks))
17162 (setq clocksum (concat clocksum (format fmt n))
17163 m (- m (* n w d h))))
17164 (and (setq fmt (plist-get org-time-clocksum-format :days))
17165 (or (> (setq n (/ (truncate m) (* d h))) 0)
17166 (plist-get org-time-clocksum-format :require-days))
17167 (setq clocksum (concat clocksum (format fmt n))
17168 m (- m (* n d h))))
17169 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17170 (or (> (setq n (/ (truncate m) h)) 0)
17171 (plist-get org-time-clocksum-format :require-hours))
17172 (setq clocksum (concat clocksum (format fmt n))
17173 m (- m (* n h))))
17174 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17175 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17176 (setq clocksum (concat clocksum (format fmt m))))
17177 ;; return formatted time duration
17178 clocksum))))
17180 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17181 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17182 "Org mode version 8.0")
17184 (defun org-hours-to-clocksum-string (n)
17185 (org-minutes-to-clocksum-string (* n 60)))
17187 (defun org-hh:mm-string-to-minutes (s)
17188 "Convert a string H:MM to a number of minutes.
17189 If the string is just a number, interpret it as minutes.
17190 In fact, the first hh:mm or number in the string will be taken,
17191 there can be extra stuff in the string.
17192 If no number is found, the return value is 0."
17193 (cond
17194 ((integerp s) s)
17195 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17196 (+ (* (string-to-number (match-string 1 s)) 60)
17197 (string-to-number (match-string 2 s))))
17198 ((string-match "\\([0-9]+\\)" s)
17199 (string-to-number (match-string 1 s)))
17200 (t 0)))
17202 (defcustom org-image-actual-width t
17203 "Should we use the actual width of images when inlining them?
17205 When set to `t', always use the image width.
17207 When set to a number, use imagemagick (when available) to set
17208 the image's width to this value.
17210 When set to a number in a list, try to get the width from the
17211 #+ATTR.* keyword if it matches a width specification like
17212 width=\"[0-9]+\", and fall back on that number if none is found.
17214 When set to nil, try to get the width from an #+ATTR.* keyword
17215 and fall back on the original width if none is found.
17217 This requires Emacs >= 24.1, build with imagemagick support."
17218 :group 'org-appearance
17219 :version "24.3"
17220 :type '(choice
17221 (const :tag "Use the image width" t)
17222 (integer :tag "Use a number of pixels")
17223 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17224 (const :tag "Use #+ATTR* or don't resize" nil)))
17226 (defcustom org-agenda-inhibit-startup t
17227 "Inhibit startup when preparing agenda buffers.
17228 When this variable is `t' (the default), the initialization of
17229 the Org agenda buffers is inhibited: e.g. the visibility state
17230 is not set, the tables are not re-aligned, etc."
17231 :type 'boolean
17232 :version "24.3"
17233 :group 'org-agenda)
17235 (defun org-duration-string-to-minutes (s &optional output-to-string)
17236 "Convert a duration string S to minutes.
17238 A bare number is interpreted as minutes, modifiers can be set by
17239 customizing `org-effort-durations' (which see).
17241 Entries containing a colon are interpreted as H:MM by
17242 `org-hh:mm-string-to-minutes'."
17243 (let ((result 0)
17244 (re (concat "\\([0-9.]+\\) *\\("
17245 (regexp-opt (mapcar 'car org-effort-durations))
17246 "\\)")))
17247 (while (string-match re s)
17248 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17249 (string-to-number (match-string 1 s))))
17250 (setq s (replace-match "" nil t s)))
17251 (setq result (floor result))
17252 (incf result (org-hh:mm-string-to-minutes s))
17253 (if output-to-string (number-to-string result) result)))
17255 ;;;; Files
17257 (defun org-save-all-org-buffers ()
17258 "Save all Org-mode buffers without user confirmation."
17259 (interactive)
17260 (message "Saving all Org-mode buffers...")
17261 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17262 (when (featurep 'org-id) (org-id-locations-save))
17263 (message "Saving all Org-mode buffers... done"))
17265 (defun org-revert-all-org-buffers ()
17266 "Revert all Org-mode buffers.
17267 Prompt for confirmation when there are unsaved changes.
17268 Be sure you know what you are doing before letting this function
17269 overwrite your changes.
17271 This function is useful in a setup where one tracks org files
17272 with a version control system, to revert on one machine after pulling
17273 changes from another. I believe the procedure must be like this:
17275 1. M-x org-save-all-org-buffers
17276 2. Pull changes from the other machine, resolve conflicts
17277 3. M-x org-revert-all-org-buffers"
17278 (interactive)
17279 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17280 (error "Abort"))
17281 (save-excursion
17282 (save-window-excursion
17283 (mapc
17284 (lambda (b)
17285 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17286 (with-current-buffer b buffer-file-name))
17287 (org-pop-to-buffer-same-window b)
17288 (revert-buffer t 'no-confirm)))
17289 (buffer-list))
17290 (when (and (featurep 'org-id) org-id-track-globally)
17291 (org-id-locations-load)))))
17293 ;;;; Agenda files
17295 ;;;###autoload
17296 (defun org-switchb (&optional arg)
17297 "Switch between Org buffers.
17298 With one prefix argument, restrict available buffers to files.
17299 With two prefix arguments, restrict available buffers to agenda files.
17301 Defaults to `iswitchb' for buffer name completion.
17302 Set `org-completion-use-ido' to make it use ido instead."
17303 (interactive "P")
17304 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17305 ((equal arg '(16)) (org-buffer-list 'agenda))
17306 (t (org-buffer-list))))
17307 (org-completion-use-iswitchb org-completion-use-iswitchb)
17308 (org-completion-use-ido org-completion-use-ido))
17309 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17310 (setq org-completion-use-iswitchb t))
17311 (org-pop-to-buffer-same-window
17312 (org-icompleting-read "Org buffer: "
17313 (mapcar 'list (mapcar 'buffer-name blist))
17314 nil t))))
17316 ;;; Define some older names previously used for this functionality
17317 ;;;###autoload
17318 (defalias 'org-ido-switchb 'org-switchb)
17319 ;;;###autoload
17320 (defalias 'org-iswitchb 'org-switchb)
17322 (defun org-buffer-list (&optional predicate exclude-tmp)
17323 "Return a list of Org buffers.
17324 PREDICATE can be `export', `files' or `agenda'.
17326 export restrict the list to Export buffers.
17327 files restrict the list to buffers visiting Org files.
17328 agenda restrict the list to buffers visiting agenda files.
17330 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17331 (let* ((bfn nil)
17332 (agenda-files (and (eq predicate 'agenda)
17333 (mapcar 'file-truename (org-agenda-files t))))
17334 (filter
17335 (cond
17336 ((eq predicate 'files)
17337 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17338 ((eq predicate 'export)
17339 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17340 ((eq predicate 'agenda)
17341 (lambda (b)
17342 (with-current-buffer b
17343 (and (derived-mode-p 'org-mode)
17344 (setq bfn (buffer-file-name b))
17345 (member (file-truename bfn) agenda-files)))))
17346 (t (lambda (b) (with-current-buffer b
17347 (or (derived-mode-p 'org-mode)
17348 (string-match "\*Org .*Export"
17349 (buffer-name b)))))))))
17350 (delq nil
17351 (mapcar
17352 (lambda(b)
17353 (if (and (funcall filter b)
17354 (or (not exclude-tmp)
17355 (not (string-match "tmp" (buffer-name b)))))
17357 nil))
17358 (buffer-list)))))
17360 (defun org-agenda-files (&optional unrestricted archives)
17361 "Get the list of agenda files.
17362 Optional UNRESTRICTED means return the full list even if a restriction
17363 is currently in place.
17364 When ARCHIVES is t, include all archive files that are really being
17365 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17366 `org-agenda-archives-mode' is t."
17367 (let ((files
17368 (cond
17369 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17370 ((stringp org-agenda-files) (org-read-agenda-file-list))
17371 ((listp org-agenda-files) org-agenda-files)
17372 (t (error "Invalid value of `org-agenda-files'")))))
17373 (setq files (apply 'append
17374 (mapcar (lambda (f)
17375 (if (file-directory-p f)
17376 (directory-files
17377 f t org-agenda-file-regexp)
17378 (list f)))
17379 files)))
17380 (when org-agenda-skip-unavailable-files
17381 (setq files (delq nil
17382 (mapcar (function
17383 (lambda (file)
17384 (and (file-readable-p file) file)))
17385 files))))
17386 (when (or (eq archives t)
17387 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17388 (setq files (org-add-archive-files files)))
17389 files))
17391 (defun org-agenda-file-p (&optional file)
17392 "Return non-nil, if FILE is an agenda file.
17393 If FILE is omitted, use the file associated with the current
17394 buffer."
17395 (member (or file (buffer-file-name))
17396 (org-agenda-files t)))
17398 (defun org-edit-agenda-file-list ()
17399 "Edit the list of agenda files.
17400 Depending on setup, this either uses customize to edit the variable
17401 `org-agenda-files', or it visits the file that is holding the list. In the
17402 latter case, the buffer is set up in a way that saving it automatically kills
17403 the buffer and restores the previous window configuration."
17404 (interactive)
17405 (if (stringp org-agenda-files)
17406 (let ((cw (current-window-configuration)))
17407 (find-file org-agenda-files)
17408 (org-set-local 'org-window-configuration cw)
17409 (org-add-hook 'after-save-hook
17410 (lambda ()
17411 (set-window-configuration
17412 (prog1 org-window-configuration
17413 (kill-buffer (current-buffer))))
17414 (org-install-agenda-files-menu)
17415 (message "New agenda file list installed"))
17416 nil 'local)
17417 (message "%s" (substitute-command-keys
17418 "Edit list and finish with \\[save-buffer]")))
17419 (customize-variable 'org-agenda-files)))
17421 (defun org-store-new-agenda-file-list (list)
17422 "Set new value for the agenda file list and save it correctly."
17423 (if (stringp org-agenda-files)
17424 (let ((fe (org-read-agenda-file-list t)) b u)
17425 (while (setq b (find-buffer-visiting org-agenda-files))
17426 (kill-buffer b))
17427 (with-temp-file org-agenda-files
17428 (insert
17429 (mapconcat
17430 (lambda (f) ;; Keep un-expanded entries.
17431 (if (setq u (assoc f fe))
17432 (cdr u)
17434 list "\n")
17435 "\n")))
17436 (let ((org-mode-hook nil) (org-inhibit-startup t)
17437 (org-insert-mode-line-in-empty-file nil))
17438 (setq org-agenda-files list)
17439 (customize-save-variable 'org-agenda-files org-agenda-files))))
17441 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17442 "Read the list of agenda files from a file.
17443 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17444 filenames, used by `org-store-new-agenda-file-list' to write back
17445 un-expanded file names."
17446 (when (file-directory-p org-agenda-files)
17447 (error "`org-agenda-files' cannot be a single directory"))
17448 (when (stringp org-agenda-files)
17449 (with-temp-buffer
17450 (insert-file-contents org-agenda-files)
17451 (mapcar
17452 (lambda (f)
17453 (let ((e (expand-file-name (substitute-in-file-name f)
17454 org-directory)))
17455 (if pair-with-expansion
17456 (cons e f)
17457 e)))
17458 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17460 ;;;###autoload
17461 (defun org-cycle-agenda-files ()
17462 "Cycle through the files in `org-agenda-files'.
17463 If the current buffer visits an agenda file, find the next one in the list.
17464 If the current buffer does not, find the first agenda file."
17465 (interactive)
17466 (let* ((fs (org-agenda-files t))
17467 (files (append fs (list (car fs))))
17468 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17469 file)
17470 (unless files (error "No agenda files"))
17471 (catch 'exit
17472 (while (setq file (pop files))
17473 (if (equal (file-truename file) tcf)
17474 (when (car files)
17475 (find-file (car files))
17476 (throw 'exit t))))
17477 (find-file (car fs)))
17478 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17480 (defun org-agenda-file-to-front (&optional to-end)
17481 "Move/add the current file to the top of the agenda file list.
17482 If the file is not present in the list, it is added to the front. If it is
17483 present, it is moved there. With optional argument TO-END, add/move to the
17484 end of the list."
17485 (interactive "P")
17486 (let ((org-agenda-skip-unavailable-files nil)
17487 (file-alist (mapcar (lambda (x)
17488 (cons (file-truename x) x))
17489 (org-agenda-files t)))
17490 (ctf (file-truename
17491 (or buffer-file-name
17492 (error "Please save the current buffer to a file"))))
17493 x had)
17494 (setq x (assoc ctf file-alist) had x)
17496 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17497 (if to-end
17498 (setq file-alist (append (delq x file-alist) (list x)))
17499 (setq file-alist (cons x (delq x file-alist))))
17500 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17501 (org-install-agenda-files-menu)
17502 (message "File %s to %s of agenda file list"
17503 (if had "moved" "added") (if to-end "end" "front"))))
17505 (defun org-remove-file (&optional file)
17506 "Remove current file from the list of files in variable `org-agenda-files'.
17507 These are the files which are being checked for agenda entries.
17508 Optional argument FILE means use this file instead of the current."
17509 (interactive)
17510 (let* ((org-agenda-skip-unavailable-files nil)
17511 (file (or file buffer-file-name
17512 (error "Current buffer does not visit a file")))
17513 (true-file (file-truename file))
17514 (afile (abbreviate-file-name file))
17515 (files (delq nil (mapcar
17516 (lambda (x)
17517 (if (equal true-file
17518 (file-truename x))
17519 nil x))
17520 (org-agenda-files t)))))
17521 (if (not (= (length files) (length (org-agenda-files t))))
17522 (progn
17523 (org-store-new-agenda-file-list files)
17524 (org-install-agenda-files-menu)
17525 (message "Removed file: %s" afile))
17526 (message "File was not in list: %s (not removed)" afile))))
17528 (defun org-file-menu-entry (file)
17529 (vector file (list 'find-file file) t))
17531 (defun org-check-agenda-file (file)
17532 "Make sure FILE exists. If not, ask user what to do."
17533 (when (not (file-exists-p file))
17534 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17535 (abbreviate-file-name file))
17536 (let ((r (downcase (read-char-exclusive))))
17537 (cond
17538 ((equal r ?r)
17539 (org-remove-file file)
17540 (throw 'nextfile t))
17541 (t (error "Abort"))))))
17543 (defun org-get-agenda-file-buffer (file)
17544 "Get a buffer visiting FILE. If the buffer needs to be created, add
17545 it to the list of buffers which might be released later."
17546 (let ((buf (org-find-base-buffer-visiting file)))
17547 (if buf
17548 buf ; just return it
17549 ;; Make a new buffer and remember it
17550 (setq buf (find-file-noselect file))
17551 (if buf (push buf org-agenda-new-buffers))
17552 buf)))
17554 (defun org-release-buffers (blist)
17555 "Release all buffers in list, asking the user for confirmation when needed.
17556 When a buffer is unmodified, it is just killed. When modified, it is saved
17557 \(if the user agrees) and then killed."
17558 (let (buf file)
17559 (while (setq buf (pop blist))
17560 (setq file (buffer-file-name buf))
17561 (when (and (buffer-modified-p buf)
17562 file
17563 (y-or-n-p (format "Save file %s? " file)))
17564 (with-current-buffer buf (save-buffer)))
17565 (kill-buffer buf))))
17567 (defun org-agenda-prepare-buffers (files)
17568 "Create buffers for all agenda files, protect archived trees and comments."
17569 (interactive)
17570 (let ((pa '(:org-archived t))
17571 (pc '(:org-comment t))
17572 (pall '(:org-archived t :org-comment t))
17573 (inhibit-read-only t)
17574 (org-inhibit-startup org-agenda-inhibit-startup)
17575 (rea (concat ":" org-archive-tag ":"))
17576 file re)
17577 (save-excursion
17578 (save-restriction
17579 (while (setq file (pop files))
17580 (catch 'nextfile
17581 (if (bufferp file)
17582 (set-buffer file)
17583 (org-check-agenda-file file)
17584 (set-buffer (org-get-agenda-file-buffer file)))
17585 (widen)
17586 (org-unmodified
17587 (org-refresh-category-properties)
17588 (org-refresh-properties org-effort-property 'org-effort)
17589 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17590 (setq org-todo-keywords-for-agenda
17591 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17592 (setq org-done-keywords-for-agenda
17593 (append org-done-keywords-for-agenda org-done-keywords))
17594 (setq org-todo-keyword-alist-for-agenda
17595 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17596 (setq org-drawers-for-agenda
17597 (append org-drawers-for-agenda org-drawers))
17598 (setq org-tag-alist-for-agenda
17599 (append org-tag-alist-for-agenda org-tag-alist))
17601 (save-excursion
17602 (remove-text-properties (point-min) (point-max) pall)
17603 (when org-agenda-skip-archived-trees
17604 (goto-char (point-min))
17605 (while (re-search-forward rea nil t)
17606 (if (org-at-heading-p t)
17607 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17608 (goto-char (point-min))
17609 (setq re (format org-heading-keyword-regexp-format
17610 org-comment-string))
17611 (while (re-search-forward re nil t)
17612 (add-text-properties
17613 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17614 (setq org-todo-keywords-for-agenda
17615 (org-uniquify org-todo-keywords-for-agenda))
17616 (setq org-todo-keyword-alist-for-agenda
17617 (org-uniquify org-todo-keyword-alist-for-agenda)
17618 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17622 ;;;; CDLaTeX minor mode
17624 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17625 "Keymap for the minor `org-cdlatex-mode'.")
17627 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17628 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17629 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17630 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17631 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17633 (defvar org-cdlatex-texmathp-advice-is-done nil
17634 "Flag remembering if we have applied the advice to texmathp already.")
17636 (define-minor-mode org-cdlatex-mode
17637 "Toggle the minor `org-cdlatex-mode'.
17638 This mode supports entering LaTeX environment and math in LaTeX fragments
17639 in Org-mode.
17640 \\{org-cdlatex-mode-map}"
17641 nil " OCDL" nil
17642 (when org-cdlatex-mode
17643 (require 'cdlatex)
17644 (run-hooks 'cdlatex-mode-hook)
17645 (cdlatex-compute-tables))
17646 (unless org-cdlatex-texmathp-advice-is-done
17647 (setq org-cdlatex-texmathp-advice-is-done t)
17648 (defadvice texmathp (around org-math-always-on activate)
17649 "Always return t in org-mode buffers.
17650 This is because we want to insert math symbols without dollars even outside
17651 the LaTeX math segments. If Orgmode thinks that point is actually inside
17652 an embedded LaTeX fragment, let texmathp do its job.
17653 \\[org-cdlatex-mode-map]"
17654 (interactive)
17655 (let (p)
17656 (cond
17657 ((not (derived-mode-p 'org-mode)) ad-do-it)
17658 ((eq this-command 'cdlatex-math-symbol)
17659 (setq ad-return-value t
17660 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17662 (let ((p (org-inside-LaTeX-fragment-p)))
17663 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17664 (setq ad-return-value t
17665 texmathp-why '("Org-mode embedded math" . 0))
17666 (if p ad-do-it)))))))))
17668 (defun turn-on-org-cdlatex ()
17669 "Unconditionally turn on `org-cdlatex-mode'."
17670 (org-cdlatex-mode 1))
17672 (defun org-try-cdlatex-tab ()
17673 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17674 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17675 - inside a LaTeX fragment, or
17676 - after the first word in a line, where an abbreviation expansion could
17677 insert a LaTeX environment."
17678 (when org-cdlatex-mode
17679 (cond
17680 ;; Before any word on the line: No expansion possible.
17681 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17682 ;; Just after first word on the line: Expand it. Make sure it
17683 ;; cannot happen on headlines, though.
17684 ((save-excursion
17685 (skip-chars-backward "a-zA-Z0-9*")
17686 (skip-chars-backward " \t")
17687 (and (bolp) (not (org-at-heading-p))))
17688 (cdlatex-tab) t)
17689 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17691 (defun org-cdlatex-underscore-caret (&optional arg)
17692 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17693 Revert to the normal definition outside of these fragments."
17694 (interactive "P")
17695 (if (org-inside-LaTeX-fragment-p)
17696 (call-interactively 'cdlatex-sub-superscript)
17697 (let (org-cdlatex-mode)
17698 (call-interactively (key-binding (vector last-input-event))))))
17700 (defun org-cdlatex-math-modify (&optional arg)
17701 "Execute `cdlatex-math-modify' in LaTeX fragments.
17702 Revert to the normal definition outside of these fragments."
17703 (interactive "P")
17704 (if (org-inside-LaTeX-fragment-p)
17705 (call-interactively 'cdlatex-math-modify)
17706 (let (org-cdlatex-mode)
17707 (call-interactively (key-binding (vector last-input-event))))))
17711 ;;;; LaTeX fragments
17713 (defvar org-latex-regexps
17714 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17715 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17716 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17717 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17718 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17719 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17720 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17721 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17722 "Regular expressions for matching embedded LaTeX.")
17724 (defun org-inside-LaTeX-fragment-p ()
17725 "Test if point is inside a LaTeX fragment.
17726 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17727 sequence appearing also before point.
17728 Even though the matchers for math are configurable, this function assumes
17729 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17730 delimiters are skipped when they have been removed by customization.
17731 The return value is nil, or a cons cell with the delimiter and the
17732 position of this delimiter.
17734 This function does a reasonably good job, but can locally be fooled by
17735 for example currency specifications. For example it will assume being in
17736 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17737 fragments that are properly closed, but during editing, we have to live
17738 with the uncertainty caused by missing closing delimiters. This function
17739 looks only before point, not after."
17740 (catch 'exit
17741 (let ((pos (point))
17742 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17743 (lim (progn
17744 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17745 (point)))
17746 dd-on str (start 0) m re)
17747 (goto-char pos)
17748 (when dodollar
17749 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17750 re (nth 1 (assoc "$" org-latex-regexps)))
17751 (while (string-match re str start)
17752 (cond
17753 ((= (match-end 0) (length str))
17754 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17755 ((= (match-end 0) (- (length str) 5))
17756 (throw 'exit nil))
17757 (t (setq start (match-end 0))))))
17758 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17759 (goto-char pos)
17760 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17761 (and (match-beginning 2) (throw 'exit nil))
17762 ;; count $$
17763 (while (re-search-backward "\\$\\$" lim t)
17764 (setq dd-on (not dd-on)))
17765 (goto-char pos)
17766 (if dd-on (cons "$$" m))))))
17768 (defun org-inside-latex-macro-p ()
17769 "Is point inside a LaTeX macro or its arguments?"
17770 (save-match-data
17771 (org-in-regexp
17772 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17774 (defvar org-latex-fragment-image-overlays nil
17775 "List of overlays carrying the images of latex fragments.")
17776 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17778 (defun org-remove-latex-fragment-image-overlays ()
17779 "Remove all overlays with LaTeX fragment images in current buffer."
17780 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17781 (setq org-latex-fragment-image-overlays nil))
17783 (defun org-preview-latex-fragment (&optional subtree)
17784 "Preview the LaTeX fragment at point, or all locally or globally.
17785 If the cursor is in a LaTeX fragment, create the image and overlay
17786 it over the source code. If there is no fragment at point, display
17787 all fragments in the current text, from one headline to the next. With
17788 prefix SUBTREE, display all fragments in the current subtree. With a
17789 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17790 the cursor is before the first headline,
17791 display all fragments in the buffer.
17792 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17793 (interactive "P")
17794 (unless buffer-file-name
17795 (error "Can't preview LaTeX fragment in a non-file buffer"))
17796 (org-remove-latex-fragment-image-overlays)
17797 (save-excursion
17798 (save-restriction
17799 (let (beg end at msg)
17800 (cond
17801 ((or (equal subtree '(16))
17802 (not (save-excursion
17803 (re-search-backward org-outline-regexp-bol nil t))))
17804 (setq beg (point-min) end (point-max)
17805 msg "Creating images for buffer...%s"))
17806 ((equal subtree '(4))
17807 (org-back-to-heading)
17808 (setq beg (point) end (org-end-of-subtree t)
17809 msg "Creating images for subtree...%s"))
17811 (if (setq at (org-inside-LaTeX-fragment-p))
17812 (goto-char (max (point-min) (- (cdr at) 2)))
17813 (org-back-to-heading))
17814 (setq beg (point) end (progn (outline-next-heading) (point))
17815 msg (if at "Creating image...%s"
17816 "Creating images for entry...%s"))))
17817 (message msg "")
17818 (narrow-to-region beg end)
17819 (goto-char beg)
17820 (org-format-latex
17821 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17822 (file-name-nondirectory
17823 buffer-file-name)))
17824 default-directory 'overlays msg at 'forbuffer
17825 org-latex-create-formula-image-program)
17826 (message msg "done. Use `C-c C-c' to remove images.")))))
17828 (defun org-format-latex (prefix &optional dir overlays msg at
17829 forbuffer processing-type)
17830 "Replace LaTeX fragments with links to an image, and produce images.
17831 Some of the options can be changed using the variable
17832 `org-format-latex-options'."
17833 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17834 (let* ((prefixnodir (file-name-nondirectory prefix))
17835 (absprefix (expand-file-name prefix dir))
17836 (todir (file-name-directory absprefix))
17837 (opt org-format-latex-options)
17838 (optnew org-format-latex-options)
17839 (matchers (plist-get opt :matchers))
17840 (re-list org-latex-regexps)
17841 (cnt 0) txt hash link beg end re e checkdir
17842 string
17843 m n block-type block linkfile movefile ov)
17844 ;; Check the different regular expressions
17845 (while (setq e (pop re-list))
17846 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17847 block (if block-type "\n\n" ""))
17848 (when (member m matchers)
17849 (goto-char (point-min))
17850 (while (re-search-forward re nil t)
17851 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17852 (or (not overlays)
17853 (not (eq (get-char-property (match-beginning n)
17854 'org-overlay-type)
17855 'org-latex-overlay))))
17856 (cond
17857 ((eq processing-type 'verbatim))
17858 ((eq processing-type 'mathjax)
17859 ;; Prepare for MathJax processing.
17860 (setq string (match-string n))
17861 (when (member m '("$" "$1"))
17862 (save-excursion
17863 (delete-region (match-beginning n) (match-end n))
17864 (goto-char (match-beginning n))
17865 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17866 ((or (eq processing-type 'dvipng)
17867 (eq processing-type 'imagemagick))
17868 ;; Process to an image.
17869 (setq txt (match-string n)
17870 beg (match-beginning n) end (match-end n)
17871 cnt (1+ cnt))
17872 (let ((face (face-at-point))
17873 (fg (plist-get opt :foreground))
17874 (bg (plist-get opt :background))
17875 ;; Ensure full list is printed.
17876 print-length print-level)
17877 (when forbuffer
17878 ;; Get the colors from the face at point.
17879 (goto-char beg)
17880 (when (eq fg 'auto)
17881 (setq fg (face-attribute face :foreground nil 'default)))
17882 (when (eq bg 'auto)
17883 (setq bg (face-attribute face :background nil 'default)))
17884 (setq optnew (copy-sequence opt))
17885 (plist-put optnew :foreground fg)
17886 (plist-put optnew :background bg))
17887 (setq hash (sha1 (prin1-to-string
17888 (list org-format-latex-header
17889 org-latex-default-packages-alist
17890 org-latex-packages-alist
17891 org-format-latex-options
17892 forbuffer txt fg bg)))
17893 linkfile (format "%s_%s.png" prefix hash)
17894 movefile (format "%s_%s.png" absprefix hash)))
17895 (setq link (concat block "[[file:" linkfile "]]" block))
17896 (if msg (message msg cnt))
17897 (goto-char beg)
17898 (unless checkdir ; Ensure the directory exists.
17899 (setq checkdir t)
17900 (or (file-directory-p todir) (make-directory todir t)))
17901 (unless (file-exists-p movefile)
17902 (org-create-formula-image
17903 txt movefile optnew forbuffer processing-type))
17904 (if overlays
17905 (progn
17906 (mapc (lambda (o)
17907 (if (eq (overlay-get o 'org-overlay-type)
17908 'org-latex-overlay)
17909 (delete-overlay o)))
17910 (overlays-in beg end))
17911 (setq ov (make-overlay beg end))
17912 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17913 (if (featurep 'xemacs)
17914 (progn
17915 (overlay-put ov 'invisible t)
17916 (overlay-put
17917 ov 'end-glyph
17918 (make-glyph (vector 'png :file movefile))))
17919 (overlay-put
17920 ov 'display
17921 (list 'image :type 'png :file movefile :ascent 'center)))
17922 (push ov org-latex-fragment-image-overlays)
17923 (goto-char end))
17924 (delete-region beg end)
17925 (insert (org-add-props link
17926 (list 'org-latex-src
17927 (replace-regexp-in-string
17928 "\"" "" txt)
17929 'org-latex-src-embed-type
17930 (if block-type 'paragraph 'character))))))
17931 ((eq processing-type 'mathml)
17932 ;; Process to MathML
17933 (unless (save-match-data (org-format-latex-mathml-available-p))
17934 (error "LaTeX to MathML converter not configured"))
17935 (setq txt (match-string n)
17936 beg (match-beginning n) end (match-end n)
17937 cnt (1+ cnt))
17938 (if msg (message msg cnt))
17939 (goto-char beg)
17940 (delete-region beg end)
17941 (insert (org-format-latex-as-mathml
17942 txt block-type prefix dir)))
17944 (error "Unknown conversion type %s for latex fragments"
17945 processing-type)))))))))
17947 (defun org-create-math-formula (latex-frag &optional mathml-file)
17948 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17949 Use `org-latex-to-mathml-convert-command'. If the conversion is
17950 sucessful, return the portion between \"<math...> </math>\"
17951 elements otherwise return nil. When MATHML-FILE is specified,
17952 write the results in to that file. When invoked as an
17953 interactive command, prompt for LATEX-FRAG, with initial value
17954 set to the current active region and echo the results for user
17955 inspection."
17956 (interactive (list (let ((frag (when (org-region-active-p)
17957 (buffer-substring-no-properties
17958 (region-beginning) (region-end)))))
17959 (read-string "LaTeX Fragment: " frag nil frag))))
17960 (unless latex-frag (error "Invalid latex-frag"))
17961 (let* ((tmp-in-file (file-relative-name
17962 (make-temp-name (expand-file-name "ltxmathml-in"))))
17963 (ignore (write-region latex-frag nil tmp-in-file))
17964 (tmp-out-file (file-relative-name
17965 (make-temp-name (expand-file-name "ltxmathml-out"))))
17966 (cmd (format-spec
17967 org-latex-to-mathml-convert-command
17968 `((?j . ,(shell-quote-argument
17969 (expand-file-name org-latex-to-mathml-jar-file)))
17970 (?I . ,(shell-quote-argument tmp-in-file))
17971 (?o . ,(shell-quote-argument tmp-out-file)))))
17972 mathml shell-command-output)
17973 (when (org-called-interactively-p 'any)
17974 (unless (org-format-latex-mathml-available-p)
17975 (error "LaTeX to MathML converter not configured")))
17976 (message "Running %s" cmd)
17977 (setq shell-command-output (shell-command-to-string cmd))
17978 (setq mathml
17979 (when (file-readable-p tmp-out-file)
17980 (with-current-buffer (find-file-noselect tmp-out-file t)
17981 (goto-char (point-min))
17982 (when (re-search-forward
17983 (concat
17984 (regexp-quote
17985 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17986 "\\(.\\|\n\\)*"
17987 (regexp-quote "</math>")) nil t)
17988 (prog1 (match-string 0) (kill-buffer))))))
17989 (cond
17990 (mathml
17991 (setq mathml
17992 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17993 (when mathml-file
17994 (write-region mathml nil mathml-file))
17995 (when (org-called-interactively-p 'any)
17996 (message mathml)))
17997 ((message "LaTeX to MathML conversion failed")
17998 (message shell-command-output)))
17999 (delete-file tmp-in-file)
18000 (when (file-exists-p tmp-out-file)
18001 (delete-file tmp-out-file))
18002 mathml))
18004 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18005 prefix &optional dir)
18006 "Use `org-create-math-formula' but check local cache first."
18007 (let* ((absprefix (expand-file-name prefix dir))
18008 (print-length nil) (print-level nil)
18009 (formula-id (concat
18010 "formula-"
18011 (sha1
18012 (prin1-to-string
18013 (list latex-frag
18014 org-latex-to-mathml-convert-command)))))
18015 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18016 (formula-cache-dir (file-name-directory formula-cache)))
18018 (unless (file-directory-p formula-cache-dir)
18019 (make-directory formula-cache-dir t))
18021 (unless (file-exists-p formula-cache)
18022 (org-create-math-formula latex-frag formula-cache))
18024 (if (file-exists-p formula-cache)
18025 ;; Successful conversion. Return the link to MathML file.
18026 (org-add-props
18027 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18028 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18029 'org-latex-src-embed-type (if latex-frag-type
18030 'paragraph 'character)))
18031 ;; Failed conversion. Return the LaTeX fragment verbatim
18032 latex-frag)))
18034 (defun org-create-formula-image (string tofile options buffer &optional type)
18035 "Create an image from LaTeX source using dvipng or convert.
18036 This function calls either `org-create-formula-image-with-dvipng'
18037 or `org-create-formula-image-with-imagemagick' depending on the
18038 value of `org-latex-create-formula-image-program' or on the value
18039 of the optional TYPE variable.
18041 Note: ultimately these two function should be combined as they
18042 share a good deal of logic."
18043 (org-check-external-command
18044 "latex" "needed to convert LaTeX fragments to images")
18045 (funcall
18046 (case (or type org-latex-create-formula-image-program)
18047 ('dvipng
18048 (org-check-external-command
18049 "dvipng" "needed to convert LaTeX fragments to images")
18050 #'org-create-formula-image-with-dvipng)
18051 ('imagemagick
18052 (org-check-external-command
18053 "convert" "you need to install imagemagick")
18054 #'org-create-formula-image-with-imagemagick)
18055 (t (error
18056 "invalid value of `org-latex-create-formula-image-program'")))
18057 string tofile options buffer))
18059 ;; This function borrows from Ganesh Swami's latex2png.el
18060 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18061 "This calls dvipng."
18062 (let* ((tmpdir (if (featurep 'xemacs)
18063 (temp-directory)
18064 temporary-file-directory))
18065 (texfilebase (make-temp-name
18066 (expand-file-name "orgtex" tmpdir)))
18067 (texfile (concat texfilebase ".tex"))
18068 (dvifile (concat texfilebase ".dvi"))
18069 (pngfile (concat texfilebase ".png"))
18070 (fnh (if (featurep 'xemacs)
18071 (font-height (face-font 'default))
18072 (face-attribute 'default :height nil)))
18073 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18074 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18075 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18076 "Black"))
18077 (bg (or (plist-get options (if buffer :background :html-background))
18078 "Transparent")))
18079 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18080 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18081 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18082 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18083 (with-temp-file texfile
18084 (require 'ox-latex)
18085 (insert (org-latex-guess-inputenc
18086 (org-splice-latex-header
18087 org-format-latex-header
18088 org-latex-default-packages-alist
18089 org-latex-packages-alist t)))
18090 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18091 (let ((dir default-directory))
18092 (condition-case nil
18093 (progn
18094 (cd tmpdir)
18095 (call-process "latex" nil nil nil texfile))
18096 (error nil))
18097 (cd dir))
18098 (if (not (file-exists-p dvifile))
18099 (progn (message "Failed to create dvi file from %s" texfile) nil)
18100 (condition-case nil
18101 (if (featurep 'xemacs)
18102 (call-process "dvipng" nil nil nil
18103 "-fg" fg "-bg" bg
18104 "-T" "tight"
18105 "-o" pngfile
18106 dvifile)
18107 (call-process "dvipng" nil nil nil
18108 "-fg" fg "-bg" bg
18109 "-D" dpi
18110 ;;"-x" scale "-y" scale
18111 "-T" "tight"
18112 "-o" pngfile
18113 dvifile))
18114 (error nil))
18115 (if (not (file-exists-p pngfile))
18116 (if org-format-latex-signal-error
18117 (error "Failed to create png file from %s" texfile)
18118 (message "Failed to create png file from %s" texfile)
18119 nil)
18120 ;; Use the requested file name and clean up
18121 (copy-file pngfile tofile 'replace)
18122 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18123 (if (file-exists-p (concat texfilebase e))
18124 (delete-file (concat texfilebase e))))
18125 pngfile))))
18127 (defvar org-latex-pdf-process) ; From ox-latex.el
18128 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18129 "This calls convert, which is included into imagemagick."
18130 (let* ((tmpdir (if (featurep 'xemacs)
18131 (temp-directory)
18132 temporary-file-directory))
18133 (texfilebase (make-temp-name
18134 (expand-file-name "orgtex" tmpdir)))
18135 (texfile (concat texfilebase ".tex"))
18136 (pdffile (concat texfilebase ".pdf"))
18137 (pngfile (concat texfilebase ".png"))
18138 (fnh (if (featurep 'xemacs)
18139 (font-height (face-font 'default))
18140 (face-attribute 'default :height nil)))
18141 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18142 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18143 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18144 "black"))
18145 (bg (or (plist-get options (if buffer :background :html-background))
18146 "white")))
18147 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18148 (setq fg (org-latex-color-format fg)))
18149 (if (eq bg 'default) (setq bg (org-latex-color :background))
18150 (setq bg (org-latex-color-format
18151 (if (string= bg "Transparent") "white" bg))))
18152 (with-temp-file texfile
18153 (require 'ox-latex)
18154 (insert (org-latex-guess-inputenc
18155 (org-splice-latex-header
18156 org-format-latex-header
18157 org-latex-default-packages-alist
18158 org-latex-packages-alist t)))
18159 (insert "\n\\begin{document}\n"
18160 "\\definecolor{fg}{rgb}{" fg "}\n"
18161 "\\definecolor{bg}{rgb}{" bg "}\n"
18162 "\n\\pagecolor{bg}\n"
18163 "\n{\\color{fg}\n"
18164 string
18165 "\n}\n"
18166 "\n\\end{document}\n"))
18167 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18168 (condition-case nil
18169 (progn
18170 (cd tmpdir)
18171 (setq cmds org-latex-pdf-process)
18172 (while cmds
18173 (setq latex-frags-cmds (pop cmds))
18174 (if (listp latex-frags-cmds)
18175 (setq cmds nil)
18176 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18177 (while latex-frags-cmds
18178 (setq cmd (pop latex-frags-cmds))
18179 (while (string-match "%b" cmd)
18180 (setq cmd (replace-match
18181 (save-match-data
18182 (shell-quote-argument texfile))
18183 t t cmd)))
18184 (while (string-match "%f" cmd)
18185 (setq cmd (replace-match
18186 (save-match-data
18187 (shell-quote-argument
18188 (file-name-nondirectory texfile)))
18189 t t cmd)))
18190 (while (string-match "%o" cmd)
18191 (setq cmd (replace-match
18192 (save-match-data
18193 (shell-quote-argument
18194 (file-name-directory texfile)))
18195 t t cmd)))
18196 (setq cmd (split-string cmd))
18197 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18198 (error nil))
18199 (cd dir))
18200 (if (not (file-exists-p pdffile))
18201 (progn (message "Failed to create pdf file from %s" texfile) nil)
18202 (condition-case nil
18203 (if (featurep 'xemacs)
18204 (call-process "convert" nil nil nil
18205 "-density" "96"
18206 "-trim"
18207 "-antialias"
18208 pdffile
18209 "-quality" "100"
18210 ;; "-sharpen" "0x1.0"
18211 pngfile)
18212 (call-process "convert" nil nil nil
18213 "-density" dpi
18214 "-trim"
18215 "-antialias"
18216 pdffile
18217 "-quality" "100"
18218 ;; "-sharpen" "0x1.0"
18219 pngfile))
18220 (error nil))
18221 (if (not (file-exists-p pngfile))
18222 (if org-format-latex-signal-error
18223 (error "Failed to create png file from %s" texfile)
18224 (message "Failed to create png file from %s" texfile)
18225 nil)
18226 ;; Use the requested file name and clean up
18227 (copy-file pngfile tofile 'replace)
18228 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18229 (if (file-exists-p (concat texfilebase e))
18230 (delete-file (concat texfilebase e))))
18231 pngfile))))
18233 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18234 "Fill a LaTeX header template TPL.
18235 In the template, the following place holders will be recognized:
18237 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18238 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18239 [PACKAGES] \\usepackage statements for PKG
18240 [NO-PACKAGES] do not include PKG
18241 [EXTRA] the string EXTRA
18242 [NO-EXTRA] do not include EXTRA
18244 For backward compatibility, if both the positive and the negative place
18245 holder is missing, the positive one (without the \"NO-\") will be
18246 assumed to be present at the end of the template.
18247 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18248 EXTRA is a string.
18249 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18250 (let (rpl (end ""))
18251 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18252 (setq rpl (if (or (match-end 1) (not def-pkg))
18253 "" (org-latex-packages-to-string def-pkg snippets-p t))
18254 tpl (replace-match rpl t t tpl))
18255 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18257 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18258 (setq rpl (if (or (match-end 1) (not pkg))
18259 "" (org-latex-packages-to-string pkg snippets-p t))
18260 tpl (replace-match rpl t t tpl))
18261 (if pkg (setq end
18262 (concat end "\n"
18263 (org-latex-packages-to-string pkg snippets-p)))))
18265 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18266 (setq rpl (if (or (match-end 1) (not extra))
18267 "" (concat extra "\n"))
18268 tpl (replace-match rpl t t tpl))
18269 (if (and extra (string-match "\\S-" extra))
18270 (setq end (concat end "\n" extra))))
18272 (if (string-match "\\S-" end)
18273 (concat tpl "\n" end)
18274 tpl)))
18276 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18277 "Turn an alist of packages into a string with the \\usepackage macros."
18278 (setq pkg (mapconcat (lambda(p)
18279 (cond
18280 ((stringp p) p)
18281 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18282 (format "%% Package %s omitted" (cadr p)))
18283 ((equal "" (car p))
18284 (format "\\usepackage{%s}" (cadr p)))
18286 (format "\\usepackage[%s]{%s}"
18287 (car p) (cadr p)))))
18289 "\n"))
18290 (if newline (concat pkg "\n") pkg))
18292 (defun org-dvipng-color (attr)
18293 "Return a RGB color specification for dvipng."
18294 (apply 'format "rgb %s %s %s"
18295 (mapcar 'org-normalize-color
18296 (if (featurep 'xemacs)
18297 (color-rgb-components
18298 (face-property 'default
18299 (cond ((eq attr :foreground) 'foreground)
18300 ((eq attr :background) 'background))))
18301 (color-values (face-attribute 'default attr nil))))))
18303 (defun org-dvipng-color-format (color-name)
18304 "Convert COLOR-NAME to a RGB color value for dvipng."
18305 (apply 'format "rgb %s %s %s"
18306 (mapcar 'org-normalize-color
18307 (color-values color-name))))
18309 (defun org-latex-color (attr)
18310 "Return a RGB color for the LaTeX color package."
18311 (apply 'format "%s,%s,%s"
18312 (mapcar 'org-normalize-color
18313 (if (featurep 'xemacs)
18314 (color-rgb-components
18315 (face-property 'default
18316 (cond ((eq attr :foreground) 'foreground)
18317 ((eq attr :background) 'background))))
18318 (color-values (face-attribute 'default attr nil))))))
18320 (defun org-latex-color-format (color-name)
18321 "Convert COLOR-NAME to a RGB color value."
18322 (apply 'format "%s,%s,%s"
18323 (mapcar 'org-normalize-color
18324 (color-values color-name))))
18326 (defun org-normalize-color (value)
18327 "Return string to be used as color value for an RGB component."
18328 (format "%g" (/ value 65535.0)))
18332 ;; Image display
18334 (defvar org-inline-image-overlays nil)
18335 (make-variable-buffer-local 'org-inline-image-overlays)
18337 (defun org-toggle-inline-images (&optional include-linked)
18338 "Toggle the display of inline images.
18339 INCLUDE-LINKED is passed to `org-display-inline-images'."
18340 (interactive "P")
18341 (if org-inline-image-overlays
18342 (progn
18343 (org-remove-inline-images)
18344 (message "Inline image display turned off"))
18345 (org-display-inline-images include-linked)
18346 (if (and (org-called-interactively-p)
18347 org-inline-image-overlays)
18348 (message "%d images displayed inline"
18349 (length org-inline-image-overlays))
18350 (message "No images to display inline"))))
18352 (defun org-redisplay-inline-images ()
18353 "Refresh the display of inline images."
18354 (interactive)
18355 (if (not org-inline-image-overlays)
18356 (org-toggle-inline-images)
18357 (org-toggle-inline-images)
18358 (org-toggle-inline-images)))
18360 (defun org-display-inline-images (&optional include-linked refresh beg end)
18361 "Display inline images.
18362 Normally only links without a description part are inlined, because this
18363 is how it will work for export. When INCLUDE-LINKED is set, also links
18364 with a description part will be inlined. This can be nice for a quick
18365 look at those images, but it does not reflect what exported files will look
18366 like.
18367 When REFRESH is set, refresh existing images between BEG and END.
18368 This will create new image displays only if necessary.
18369 BEG and END default to the buffer boundaries."
18370 (interactive "P")
18371 (unless refresh
18372 (org-remove-inline-images)
18373 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18374 (save-excursion
18375 (save-restriction
18376 (widen)
18377 (setq beg (or beg (point-min)) end (or end (point-max)))
18378 (goto-char beg)
18379 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18380 (substring (org-image-file-name-regexp) 0 -2)
18381 "\\)\\]" (if include-linked "" "\\]")))
18382 old file ov img type attrwidth width)
18383 (while (re-search-forward re end t)
18384 (setq old (get-char-property-and-overlay (match-beginning 1)
18385 'org-image-overlay)
18386 file (expand-file-name
18387 (concat (or (match-string 3) "") (match-string 4))))
18388 (when (image-type-available-p 'imagemagick)
18389 (setq attrwidth (if (or (listp org-image-actual-width)
18390 (null org-image-actual-width))
18391 (save-excursion
18392 (save-match-data
18393 (when (re-search-backward
18394 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18395 (save-excursion
18396 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18397 (string-to-number (match-string 1))))))
18398 width (cond ((eq org-image-actual-width t) nil)
18399 ((null org-image-actual-width) attrwidth)
18400 ((numberp org-image-actual-width)
18401 org-image-actual-width)
18402 ((listp org-image-actual-width)
18403 (or attrwidth (car org-image-actual-width))))
18404 type (if width 'imagemagick)))
18405 (when (file-exists-p file)
18406 (if (and (car-safe old) refresh)
18407 (image-refresh (overlay-get (cdr old) 'display))
18408 (setq img (save-match-data (create-image file type nil :width width)))
18409 (when img
18410 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18411 (overlay-put ov 'display img)
18412 (overlay-put ov 'face 'default)
18413 (overlay-put ov 'org-image-overlay t)
18414 (overlay-put ov 'modification-hooks
18415 (list 'org-display-inline-remove-overlay))
18416 (push ov org-inline-image-overlays)))))))))
18418 (define-obsolete-function-alias
18419 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18421 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18422 "Remove inline-display overlay if a corresponding region is modified."
18423 (let ((inhibit-modification-hooks t))
18424 (when (and ov after)
18425 (delete ov org-inline-image-overlays)
18426 (delete-overlay ov))))
18428 (defun org-remove-inline-images ()
18429 "Remove inline display of images."
18430 (interactive)
18431 (mapc 'delete-overlay org-inline-image-overlays)
18432 (setq org-inline-image-overlays nil))
18434 ;;;; Key bindings
18436 ;; Outline functions from `outline-mode-prefix-map'
18437 ;; that can be remapped in Org:
18438 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18439 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18440 (define-key org-mode-map [remap outline-forward-same-level]
18441 'org-forward-heading-same-level)
18442 (define-key org-mode-map [remap outline-backward-same-level]
18443 'org-backward-heading-same-level)
18444 (define-key org-mode-map [remap show-branches]
18445 'org-kill-note-or-show-branches)
18446 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18447 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18448 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18450 ;; Outline functions from `outline-mode-prefix-map' that can not
18451 ;; be remapped in Org:
18453 ;; - the column "key binding" shows whether the Outline function is still
18454 ;; available in Org mode on the same key that it has been bound to in
18455 ;; Outline mode:
18456 ;; - "overridden": key used for a different functionality in Org mode
18457 ;; - else: key still bound to the same Outline function in Org mode
18459 ;; | Outline function | key binding | Org replacement |
18460 ;; |------------------------------------+-------------+-----------------------|
18461 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18462 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18463 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18464 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18465 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18466 ;; | `show-entry' | overridden | no replacement |
18467 ;; | `show-children' | `C-c C-i' | visibility cycling |
18468 ;; | `show-branches' | `C-c C-k' | still same function |
18469 ;; | `show-subtree' | overridden | visibility cycling |
18470 ;; | `show-all' | overridden | no replacement |
18471 ;; | `hide-subtree' | overridden | visibility cycling |
18472 ;; | `hide-body' | overridden | no replacement |
18473 ;; | `hide-entry' | overridden | visibility cycling |
18474 ;; | `hide-leaves' | overridden | no replacement |
18475 ;; | `hide-sublevels' | overridden | no replacement |
18476 ;; | `hide-other' | overridden | no replacement |
18478 ;; Make `C-c C-x' a prefix key
18479 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18481 ;; TAB key with modifiers
18482 (org-defkey org-mode-map "\C-i" 'org-cycle)
18483 (org-defkey org-mode-map [(tab)] 'org-cycle)
18484 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18485 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18486 ;; The following line is necessary under Suse GNU/Linux
18487 (unless (featurep 'xemacs)
18488 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18489 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18490 (define-key org-mode-map [backtab] 'org-shifttab)
18492 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18493 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18494 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18496 ;; Cursor keys with modifiers
18497 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18498 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18499 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18500 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18502 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18503 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18504 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18505 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18507 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18508 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18509 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18510 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18512 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18513 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18514 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18515 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18517 ;; Babel keys
18518 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18519 (mapc (lambda (pair)
18520 (define-key org-babel-map (car pair) (cdr pair)))
18521 org-babel-key-bindings)
18523 ;;; Extra keys for tty access.
18524 ;; We only set them when really needed because otherwise the
18525 ;; menus don't show the simple keys
18527 (when (or org-use-extra-keys
18528 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18529 (not window-system))
18530 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18531 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18532 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18533 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18534 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18535 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18536 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18537 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18538 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18539 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18540 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18541 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18542 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18543 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18544 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18545 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18546 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18547 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18548 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18549 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18550 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18551 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18552 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18553 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18554 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18555 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18556 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18557 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18559 ;; All the other keys
18561 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18562 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18563 (if (boundp 'narrow-map)
18564 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18565 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18566 (if (boundp 'narrow-map)
18567 (org-defkey narrow-map "b" 'org-narrow-to-block)
18568 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18569 (if (boundp 'narrow-map)
18570 (org-defkey narrow-map "e" 'org-narrow-to-element)
18571 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18572 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18573 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18574 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18575 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18576 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18577 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18578 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18579 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18580 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18581 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18582 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18583 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18584 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18585 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18586 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18587 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18588 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18589 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18590 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18591 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18592 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18593 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18594 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18595 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18596 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18597 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18598 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18599 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18600 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18601 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18602 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18603 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18604 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18605 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18606 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18607 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18608 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18609 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18610 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18611 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18612 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18613 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18614 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18615 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18616 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18617 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18618 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18619 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18620 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18621 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18622 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18623 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18624 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18625 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18626 (org-defkey org-mode-map "\C-c^" 'org-sort)
18627 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18628 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18629 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18630 (org-defkey org-mode-map "\C-m" 'org-return)
18631 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18632 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18633 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18634 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18635 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18636 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18637 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18638 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18639 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18640 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18641 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18642 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18643 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18644 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18645 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18646 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18647 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18648 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18649 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18650 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18651 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18652 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18653 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18655 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18656 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18657 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18659 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18660 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18661 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18662 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18663 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18664 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18665 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18666 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18667 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18668 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18669 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18670 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18671 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18672 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18673 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18674 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18675 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18676 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18677 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18678 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18679 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18680 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18681 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18683 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18684 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18685 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18686 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18687 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18689 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18691 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18693 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18694 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18696 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18699 (when (featurep 'xemacs)
18700 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18703 (defconst org-speed-commands-default
18705 ("Outline Navigation")
18706 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18707 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18708 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18709 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18710 ("F" . org-next-block)
18711 ("B" . org-previous-block)
18712 ("u" . (org-speed-move-safe 'outline-up-heading))
18713 ("j" . org-goto)
18714 ("g" . (org-refile t))
18715 ("Outline Visibility")
18716 ("c" . org-cycle)
18717 ("C" . org-shifttab)
18718 (" " . org-display-outline-path)
18719 ("=" . org-columns)
18720 ("Outline Structure Editing")
18721 ("U" . org-shiftmetaup)
18722 ("D" . org-shiftmetadown)
18723 ("r" . org-metaright)
18724 ("l" . org-metaleft)
18725 ("R" . org-shiftmetaright)
18726 ("L" . org-shiftmetaleft)
18727 ("i" . (progn (forward-char 1) (call-interactively
18728 'org-insert-heading-respect-content)))
18729 ("^" . org-sort)
18730 ("w" . org-refile)
18731 ("a" . org-archive-subtree-default-with-confirmation)
18732 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18733 ("#" . org-toggle-comment)
18734 ("Clock Commands")
18735 ("I" . org-clock-in)
18736 ("O" . org-clock-out)
18737 ("Meta Data Editing")
18738 ("t" . org-todo)
18739 ("," . (org-priority))
18740 ("0" . (org-priority ?\ ))
18741 ("1" . (org-priority ?A))
18742 ("2" . (org-priority ?B))
18743 ("3" . (org-priority ?C))
18744 (":" . org-set-tags-command)
18745 ("e" . org-set-effort)
18746 ("E" . org-inc-effort)
18747 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18748 (org-entry-put (point) "APPT_WARNTIME" m)))
18749 ("Agenda Views etc")
18750 ("v" . org-agenda)
18751 ("/" . org-sparse-tree)
18752 ("Misc")
18753 ("o" . org-open-at-point)
18754 ("?" . org-speed-command-help)
18755 ("<" . (org-agenda-set-restriction-lock 'subtree))
18756 (">" . (org-agenda-remove-restriction-lock))
18758 "The default speed commands.")
18760 (defun org-print-speed-command (e)
18761 (if (> (length (car e)) 1)
18762 (progn
18763 (princ "\n")
18764 (princ (car e))
18765 (princ "\n")
18766 (princ (make-string (length (car e)) ?-))
18767 (princ "\n"))
18768 (princ (car e))
18769 (princ " ")
18770 (if (symbolp (cdr e))
18771 (princ (symbol-name (cdr e)))
18772 (prin1 (cdr e)))
18773 (princ "\n")))
18775 (defun org-speed-command-help ()
18776 "Show the available speed commands."
18777 (interactive)
18778 (if (not org-use-speed-commands)
18779 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18780 (with-output-to-temp-buffer "*Help*"
18781 (princ "User-defined Speed commands\n===========================\n")
18782 (mapc 'org-print-speed-command org-speed-commands-user)
18783 (princ "\n")
18784 (princ "Built-in Speed commands\n=======================\n")
18785 (mapc 'org-print-speed-command org-speed-commands-default))
18786 (with-current-buffer "*Help*"
18787 (setq truncate-lines t))))
18789 (defun org-speed-move-safe (cmd)
18790 "Execute CMD, but make sure that the cursor always ends up in a headline.
18791 If not, return to the original position and throw an error."
18792 (interactive)
18793 (let ((pos (point)))
18794 (call-interactively cmd)
18795 (unless (and (bolp) (org-at-heading-p))
18796 (goto-char pos)
18797 (error "Boundary reached while executing %s" cmd))))
18799 (defvar org-self-insert-command-undo-counter 0)
18801 (defvar org-table-auto-blank-field) ; defined in org-table.el
18802 (defvar org-speed-command nil)
18804 (define-obsolete-function-alias
18805 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18807 (defun org-speed-command-activate (keys)
18808 "Hook for activating single-letter speed commands.
18809 `org-speed-commands-default' specifies a minimal command set.
18810 Use `org-speed-commands-user' for further customization."
18811 (when (or (and (bolp) (looking-at org-outline-regexp))
18812 (and (functionp org-use-speed-commands)
18813 (funcall org-use-speed-commands)))
18814 (cdr (assoc keys (append org-speed-commands-user
18815 org-speed-commands-default)))))
18817 (define-obsolete-function-alias
18818 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18820 (defun org-babel-speed-command-activate (keys)
18821 "Hook for activating single-letter code block commands."
18822 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18823 (cdr (assoc keys org-babel-key-bindings))))
18825 (defcustom org-speed-command-hook
18826 '(org-speed-command-default-hook org-babel-speed-command-hook)
18827 "Hook for activating speed commands at strategic locations.
18828 Hook functions are called in sequence until a valid handler is
18829 found.
18831 Each hook takes a single argument, a user-pressed command key
18832 which is also a `self-insert-command' from the global map.
18834 Within the hook, examine the cursor position and the command key
18835 and return nil or a valid handler as appropriate. Handler could
18836 be one of an interactive command, a function, or a form.
18838 Set `org-use-speed-commands' to non-nil value to enable this
18839 hook. The default setting is `org-speed-command-activate'."
18840 :group 'org-structure
18841 :version "24.1"
18842 :type 'hook)
18844 (defun org-self-insert-command (N)
18845 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18846 If the cursor is in a table looking at whitespace, the whitespace is
18847 overwritten, and the table is not marked as requiring realignment."
18848 (interactive "p")
18849 (org-check-before-invisible-edit 'insert)
18850 (cond
18851 ((and org-use-speed-commands
18852 (setq org-speed-command
18853 (run-hook-with-args-until-success
18854 'org-speed-command-hook (this-command-keys))))
18855 (cond
18856 ((commandp org-speed-command)
18857 (setq this-command org-speed-command)
18858 (call-interactively org-speed-command))
18859 ((functionp org-speed-command)
18860 (funcall org-speed-command))
18861 ((and org-speed-command (listp org-speed-command))
18862 (eval org-speed-command))
18863 (t (let (org-use-speed-commands)
18864 (call-interactively 'org-self-insert-command)))))
18865 ((and
18866 (org-table-p)
18867 (progn
18868 ;; check if we blank the field, and if that triggers align
18869 (and (featurep 'org-table) org-table-auto-blank-field
18870 (member last-command
18871 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18872 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18873 ;; got extra space, this field does not determine column width
18874 (let (org-table-may-need-update) (org-table-blank-field))
18875 ;; no extra space, this field may determine column width
18876 (org-table-blank-field)))
18878 (eq N 1)
18879 (looking-at "[^|\n]* |"))
18880 (let (org-table-may-need-update)
18881 (goto-char (1- (match-end 0)))
18882 (backward-delete-char 1)
18883 (goto-char (match-beginning 0))
18884 (self-insert-command N)))
18886 (setq org-table-may-need-update t)
18887 (self-insert-command N)
18888 (org-fix-tags-on-the-fly)
18889 (if org-self-insert-cluster-for-undo
18890 (if (not (eq last-command 'org-self-insert-command))
18891 (setq org-self-insert-command-undo-counter 1)
18892 (if (>= org-self-insert-command-undo-counter 20)
18893 (setq org-self-insert-command-undo-counter 1)
18894 (and (> org-self-insert-command-undo-counter 0)
18895 buffer-undo-list (listp buffer-undo-list)
18896 (not (cadr buffer-undo-list)) ; remove nil entry
18897 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18898 (setq org-self-insert-command-undo-counter
18899 (1+ org-self-insert-command-undo-counter))))))))
18901 (defun org-check-before-invisible-edit (kind)
18902 "Check is editing if kind KIND would be dangerous with invisible text around.
18903 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18904 ;; First, try to get out of here as quickly as possible, to reduce overhead
18905 (if (and org-catch-invisible-edits
18906 (or (not (boundp 'visible-mode)) (not visible-mode))
18907 (or (get-char-property (point) 'invisible)
18908 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18909 ;; OK, we need to take a closer look
18910 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18911 (invisible-before-point (if (bobp) nil (get-char-property
18912 (1- (point)) 'invisible)))
18913 (border-and-ok-direction
18915 ;; Check if we are acting predictably before invisible text
18916 (and invisible-at-point (not invisible-before-point)
18917 (memq kind '(insert delete-backward)))
18918 ;; Check if we are acting predictably after invisible text
18919 ;; This works not well, and I have turned it off. It seems
18920 ;; better to always show and stop after invisible text.
18921 ;; (and (not invisible-at-point) invisible-before-point
18922 ;; (memq kind '(insert delete)))
18924 (when (or (memq invisible-at-point '(outline org-hide-block t))
18925 (memq invisible-before-point '(outline org-hide-block t)))
18926 (if (eq org-catch-invisible-edits 'error)
18927 (error "Editing in invisible areas is prohibited - make visible first"))
18928 (if (and org-custom-properties-overlays
18929 (y-or-n-p "Display invisible properties in this buffer? "))
18930 (org-toggle-custom-properties-visibility)
18931 ;; Make the area visible
18932 (save-excursion
18933 (if invisible-before-point
18934 (goto-char (previous-single-char-property-change
18935 (point) 'invisible)))
18936 (org-cycle))
18937 (cond
18938 ((eq org-catch-invisible-edits 'show)
18939 ;; That's it, we do the edit after showing
18940 (message
18941 "Unfolding invisible region around point before editing")
18942 (sit-for 1))
18943 ((and (eq org-catch-invisible-edits 'smart)
18944 border-and-ok-direction)
18945 (message "Unfolding invisible region around point before editing"))
18947 ;; Don't do the edit, make the user repeat it in full visibility
18948 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18950 (defun org-fix-tags-on-the-fly ()
18951 (when (and (equal (char-after (point-at-bol)) ?*)
18952 (org-at-heading-p))
18953 (org-align-tags-here org-tags-column)))
18955 (defun org-delete-backward-char (N)
18956 "Like `delete-backward-char', insert whitespace at field end in tables.
18957 When deleting backwards, in tables this function will insert whitespace in
18958 front of the next \"|\" separator, to keep the table aligned. The table will
18959 still be marked for re-alignment if the field did fill the entire column,
18960 because, in this case the deletion might narrow the column."
18961 (interactive "p")
18962 (save-match-data
18963 (org-check-before-invisible-edit 'delete-backward)
18964 (if (and (org-table-p)
18965 (eq N 1)
18966 (string-match "|" (buffer-substring (point-at-bol) (point)))
18967 (looking-at ".*?|"))
18968 (let ((pos (point))
18969 (noalign (looking-at "[^|\n\r]* |"))
18970 (c org-table-may-need-update))
18971 (backward-delete-char N)
18972 (if (not overwrite-mode)
18973 (progn
18974 (skip-chars-forward "^|")
18975 (insert " ")
18976 (goto-char (1- pos))))
18977 ;; noalign: if there were two spaces at the end, this field
18978 ;; does not determine the width of the column.
18979 (if noalign (setq org-table-may-need-update c)))
18980 (backward-delete-char N)
18981 (org-fix-tags-on-the-fly))))
18983 (defun org-delete-char (N)
18984 "Like `delete-char', but insert whitespace at field end in tables.
18985 When deleting characters, in tables this function will insert whitespace in
18986 front of the next \"|\" separator, to keep the table aligned. The table will
18987 still be marked for re-alignment if the field did fill the entire column,
18988 because, in this case the deletion might narrow the column."
18989 (interactive "p")
18990 (save-match-data
18991 (org-check-before-invisible-edit 'delete)
18992 (if (and (org-table-p)
18993 (not (bolp))
18994 (not (= (char-after) ?|))
18995 (eq N 1))
18996 (if (looking-at ".*?|")
18997 (let ((pos (point))
18998 (noalign (looking-at "[^|\n\r]* |"))
18999 (c org-table-may-need-update))
19000 (replace-match (concat
19001 (substring (match-string 0) 1 -1)
19002 " |"))
19003 (goto-char pos)
19004 ;; noalign: if there were two spaces at the end, this field
19005 ;; does not determine the width of the column.
19006 (if noalign (setq org-table-may-need-update c)))
19007 (delete-char N))
19008 (delete-char N)
19009 (org-fix-tags-on-the-fly))))
19011 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19012 (put 'org-self-insert-command 'delete-selection t)
19013 (put 'orgtbl-self-insert-command 'delete-selection t)
19014 (put 'org-delete-char 'delete-selection 'supersede)
19015 (put 'org-delete-backward-char 'delete-selection 'supersede)
19016 (put 'org-yank 'delete-selection 'yank)
19018 ;; Make `flyspell-mode' delay after some commands
19019 (put 'org-self-insert-command 'flyspell-delayed t)
19020 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19021 (put 'org-delete-char 'flyspell-delayed t)
19022 (put 'org-delete-backward-char 'flyspell-delayed t)
19024 ;; Make pabbrev-mode expand after org-mode commands
19025 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19026 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19028 ;; How to do this: Measure non-white length of current string
19029 ;; If equal to column width, we should realign.
19031 (defun org-remap (map &rest commands)
19032 "In MAP, remap the functions given in COMMANDS.
19033 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19034 (let (new old)
19035 (while commands
19036 (setq old (pop commands) new (pop commands))
19037 (if (fboundp 'command-remapping)
19038 (org-defkey map (vector 'remap old) new)
19039 (substitute-key-definition old new map global-map)))))
19041 (when (eq org-enable-table-editor 'optimized)
19042 ;; If the user wants maximum table support, we need to hijack
19043 ;; some standard editing functions
19044 (org-remap org-mode-map
19045 'self-insert-command 'org-self-insert-command
19046 'delete-char 'org-delete-char
19047 'delete-backward-char 'org-delete-backward-char)
19048 (org-defkey org-mode-map "|" 'org-force-self-insert))
19050 (defvar org-ctrl-c-ctrl-c-hook nil
19051 "Hook for functions attaching themselves to `C-c C-c'.
19053 This can be used to add additional functionality to the C-c C-c
19054 key which executes context-dependent commands. This hook is run
19055 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19056 run after the last test.
19058 Each function will be called with no arguments. The function
19059 must check if the context is appropriate for it to act. If yes,
19060 it should do its thing and then return a non-nil value. If the
19061 context is wrong, just do nothing and return nil.")
19063 (defvar org-ctrl-c-ctrl-c-final-hook nil
19064 "Hook for functions attaching themselves to `C-c C-c'.
19066 This can be used to add additional functionality to the C-c C-c
19067 key which executes context-dependent commands. This hook is run
19068 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19069 before the first test.
19071 Each function will be called with no arguments. The function
19072 must check if the context is appropriate for it to act. If yes,
19073 it should do its thing and then return a non-nil value. If the
19074 context is wrong, just do nothing and return nil.")
19076 (defvar org-tab-first-hook nil
19077 "Hook for functions to attach themselves to TAB.
19078 See `org-ctrl-c-ctrl-c-hook' for more information.
19079 This hook runs as the first action when TAB is pressed, even before
19080 `org-cycle' messes around with the `outline-regexp' to cater for
19081 inline tasks and plain list item folding.
19082 If any function in this hook returns t, any other actions that
19083 would have been caused by TAB (such as table field motion or visibility
19084 cycling) will not occur.")
19086 (defvar org-tab-after-check-for-table-hook nil
19087 "Hook for functions to attach themselves to TAB.
19088 See `org-ctrl-c-ctrl-c-hook' for more information.
19089 This hook runs after it has been established that the cursor is not in a
19090 table, but before checking if the cursor is in a headline or if global cycling
19091 should be done.
19092 If any function in this hook returns t, not other actions like visibility
19093 cycling will be done.")
19095 (defvar org-tab-after-check-for-cycling-hook nil
19096 "Hook for functions to attach themselves to TAB.
19097 See `org-ctrl-c-ctrl-c-hook' for more information.
19098 This hook runs after it has been established that not table field motion and
19099 not visibility should be done because of current context. This is probably
19100 the place where a package like yasnippets can hook in.")
19102 (defvar org-tab-before-tab-emulation-hook nil
19103 "Hook for functions to attach themselves to TAB.
19104 See `org-ctrl-c-ctrl-c-hook' for more information.
19105 This hook runs after every other options for TAB have been exhausted, but
19106 before indentation and \t insertion takes place.")
19108 (defvar org-metaleft-hook nil
19109 "Hook for functions attaching themselves to `M-left'.
19110 See `org-ctrl-c-ctrl-c-hook' for more information.")
19111 (defvar org-metaright-hook nil
19112 "Hook for functions attaching themselves to `M-right'.
19113 See `org-ctrl-c-ctrl-c-hook' for more information.")
19114 (defvar org-metaup-hook nil
19115 "Hook for functions attaching themselves to `M-up'.
19116 See `org-ctrl-c-ctrl-c-hook' for more information.")
19117 (defvar org-metadown-hook nil
19118 "Hook for functions attaching themselves to `M-down'.
19119 See `org-ctrl-c-ctrl-c-hook' for more information.")
19120 (defvar org-shiftmetaleft-hook nil
19121 "Hook for functions attaching themselves to `M-S-left'.
19122 See `org-ctrl-c-ctrl-c-hook' for more information.")
19123 (defvar org-shiftmetaright-hook nil
19124 "Hook for functions attaching themselves to `M-S-right'.
19125 See `org-ctrl-c-ctrl-c-hook' for more information.")
19126 (defvar org-shiftmetaup-hook nil
19127 "Hook for functions attaching themselves to `M-S-up'.
19128 See `org-ctrl-c-ctrl-c-hook' for more information.")
19129 (defvar org-shiftmetadown-hook nil
19130 "Hook for functions attaching themselves to `M-S-down'.
19131 See `org-ctrl-c-ctrl-c-hook' for more information.")
19132 (defvar org-metareturn-hook nil
19133 "Hook for functions attaching themselves to `M-RET'.
19134 See `org-ctrl-c-ctrl-c-hook' for more information.")
19135 (defvar org-shiftup-hook nil
19136 "Hook for functions attaching themselves to `S-up'.
19137 See `org-ctrl-c-ctrl-c-hook' for more information.")
19138 (defvar org-shiftup-final-hook nil
19139 "Hook for functions attaching themselves to `S-up'.
19140 This one runs after all other options except shift-select have been excluded.
19141 See `org-ctrl-c-ctrl-c-hook' for more information.")
19142 (defvar org-shiftdown-hook nil
19143 "Hook for functions attaching themselves to `S-down'.
19144 See `org-ctrl-c-ctrl-c-hook' for more information.")
19145 (defvar org-shiftdown-final-hook nil
19146 "Hook for functions attaching themselves to `S-down'.
19147 This one runs after all other options except shift-select have been excluded.
19148 See `org-ctrl-c-ctrl-c-hook' for more information.")
19149 (defvar org-shiftleft-hook nil
19150 "Hook for functions attaching themselves to `S-left'.
19151 See `org-ctrl-c-ctrl-c-hook' for more information.")
19152 (defvar org-shiftleft-final-hook nil
19153 "Hook for functions attaching themselves to `S-left'.
19154 This one runs after all other options except shift-select have been excluded.
19155 See `org-ctrl-c-ctrl-c-hook' for more information.")
19156 (defvar org-shiftright-hook nil
19157 "Hook for functions attaching themselves to `S-right'.
19158 See `org-ctrl-c-ctrl-c-hook' for more information.")
19159 (defvar org-shiftright-final-hook nil
19160 "Hook for functions attaching themselves to `S-right'.
19161 This one runs after all other options except shift-select have been excluded.
19162 See `org-ctrl-c-ctrl-c-hook' for more information.")
19164 (defun org-modifier-cursor-error ()
19165 "Throw an error, a modified cursor command was applied in wrong context."
19166 (error "This command is active in special context like tables, headlines or items"))
19168 (defun org-shiftselect-error ()
19169 "Throw an error because Shift-Cursor command was applied in wrong context."
19170 (if (and (boundp 'shift-select-mode) shift-select-mode)
19171 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19172 (error "This command works only in special context like headlines or timestamps")))
19174 (defun org-call-for-shift-select (cmd)
19175 (let ((this-command-keys-shift-translated t))
19176 (call-interactively cmd)))
19178 (defun org-shifttab (&optional arg)
19179 "Global visibility cycling or move to previous table field.
19180 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19181 on context.
19182 See the individual commands for more information."
19183 (interactive "P")
19184 (cond
19185 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19186 ((integerp arg)
19187 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19188 (message "Content view to level: %d" arg)
19189 (org-content (prefix-numeric-value arg2))
19190 (setq org-cycle-global-status 'overview)))
19191 (t (call-interactively 'org-global-cycle))))
19193 (defun org-shiftmetaleft ()
19194 "Promote subtree or delete table column.
19195 Calls `org-promote-subtree', `org-outdent-item-tree', or
19196 `org-table-delete-column', depending on context. See the
19197 individual commands for more information."
19198 (interactive)
19199 (cond
19200 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19201 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19202 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19203 ((if (not (org-region-active-p)) (org-at-item-p)
19204 (save-excursion (goto-char (region-beginning))
19205 (org-at-item-p)))
19206 (call-interactively 'org-outdent-item-tree))
19207 (t (org-modifier-cursor-error))))
19209 (defun org-shiftmetaright ()
19210 "Demote subtree or insert table column.
19211 Calls `org-demote-subtree', `org-indent-item-tree', or
19212 `org-table-insert-column', depending on context. See the
19213 individual commands for more information."
19214 (interactive)
19215 (cond
19216 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19217 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19218 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19219 ((if (not (org-region-active-p)) (org-at-item-p)
19220 (save-excursion (goto-char (region-beginning))
19221 (org-at-item-p)))
19222 (call-interactively 'org-indent-item-tree))
19223 (t (org-modifier-cursor-error))))
19225 (defun org-shiftmetaup (&optional arg)
19226 "Move subtree up or kill table row.
19227 Calls `org-move-subtree-up' or `org-table-kill-row' or
19228 `org-move-item-up' or `org-timestamp-up', depending on context.
19229 See the individual commands for more information."
19230 (interactive "P")
19231 (cond
19232 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19233 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19234 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19235 ((org-at-item-p) (call-interactively 'org-move-item-up))
19236 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19237 (call-interactively 'org-timestamp-up)))
19238 (t (call-interactively 'org-drag-line-backward))))
19240 (defun org-shiftmetadown (&optional arg)
19241 "Move subtree down or insert table row.
19242 Calls `org-move-subtree-down' or `org-table-insert-row' or
19243 `org-move-item-down' or `org-timestamp-up', depending on context.
19244 See the individual commands for more information."
19245 (interactive "P")
19246 (cond
19247 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19248 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19249 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19250 ((org-at-item-p) (call-interactively 'org-move-item-down))
19251 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19252 (call-interactively 'org-timestamp-down)))
19253 (t (call-interactively 'org-drag-line-forward))))
19255 (defsubst org-hidden-tree-error ()
19256 (error
19257 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19259 (defun org-metaleft (&optional arg)
19260 "Promote heading or move table column to left.
19261 Calls `org-do-promote' or `org-table-move-column', depending on context.
19262 With no specific context, calls the Emacs default `backward-word'.
19263 See the individual commands for more information."
19264 (interactive "P")
19265 (cond
19266 ((run-hook-with-args-until-success 'org-metaleft-hook))
19267 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19268 ((org-with-limited-levels
19269 (or (org-at-heading-p)
19270 (and (org-region-active-p)
19271 (save-excursion
19272 (goto-char (region-beginning))
19273 (org-at-heading-p)))))
19274 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19275 (call-interactively 'org-do-promote))
19276 ;; At an inline task.
19277 ((org-at-heading-p)
19278 (call-interactively 'org-inlinetask-promote))
19279 ((or (org-at-item-p)
19280 (and (org-region-active-p)
19281 (save-excursion
19282 (goto-char (region-beginning))
19283 (org-at-item-p))))
19284 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19285 (call-interactively 'org-outdent-item))
19286 (t (call-interactively 'backward-word))))
19288 (defun org-metaright (&optional arg)
19289 "Demote a subtree, a list item or move table column to right.
19290 In front of a drawer or a block keyword, indent it correctly.
19291 With no specific context, calls the Emacs default `forward-word'.
19292 See the individual commands for more information."
19293 (interactive "P")
19294 (cond
19295 ((run-hook-with-args-until-success 'org-metaright-hook))
19296 ((org-at-table-p) (call-interactively 'org-table-move-column))
19297 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19298 ((org-at-block-p) (call-interactively 'org-indent-block))
19299 ((org-with-limited-levels
19300 (or (org-at-heading-p)
19301 (and (org-region-active-p)
19302 (save-excursion
19303 (goto-char (region-beginning))
19304 (org-at-heading-p)))))
19305 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19306 (call-interactively 'org-do-demote))
19307 ;; At an inline task.
19308 ((org-at-heading-p)
19309 (call-interactively 'org-inlinetask-demote))
19310 ((or (org-at-item-p)
19311 (and (org-region-active-p)
19312 (save-excursion
19313 (goto-char (region-beginning))
19314 (org-at-item-p))))
19315 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19316 (call-interactively 'org-indent-item))
19317 (t (call-interactively 'forward-word))))
19319 (defun org-check-for-hidden (what)
19320 "Check if there are hidden headlines/items in the current visual line.
19321 WHAT can be either `headlines' or `items'. If the current line is
19322 an outline or item heading and it has a folded subtree below it,
19323 this function returns t, nil otherwise."
19324 (let ((re (cond
19325 ((eq what 'headlines) org-outline-regexp-bol)
19326 ((eq what 'items) (org-item-beginning-re))
19327 (t (error "This should not happen"))))
19328 beg end)
19329 (save-excursion
19330 (catch 'exit
19331 (unless (org-region-active-p)
19332 (setq beg (point-at-bol))
19333 (beginning-of-line 2)
19334 (while (and (not (eobp)) ;; this is like `next-line'
19335 (get-char-property (1- (point)) 'invisible))
19336 (beginning-of-line 2))
19337 (setq end (point))
19338 (goto-char beg)
19339 (goto-char (point-at-eol))
19340 (setq end (max end (point)))
19341 (while (re-search-forward re end t)
19342 (if (get-char-property (match-beginning 0) 'invisible)
19343 (throw 'exit t))))
19344 nil))))
19346 (defun org-metaup (&optional arg)
19347 "Move subtree up or move table row up.
19348 Calls `org-move-subtree-up' or `org-table-move-row' or
19349 `org-move-item-up', depending on context. See the individual commands
19350 for more information."
19351 (interactive "P")
19352 (cond
19353 ((run-hook-with-args-until-success 'org-metaup-hook))
19354 ((org-region-active-p)
19355 (let* ((a (min (region-beginning) (region-end)))
19356 (b (1- (max (region-beginning) (region-end))))
19357 (c (save-excursion (goto-char a)
19358 (move-beginning-of-line 0)))
19359 (d (save-excursion (goto-char a)
19360 (move-end-of-line 0) (point))))
19361 (transpose-regions a b c d)
19362 (goto-char c)))
19363 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19364 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19365 ((org-at-item-p) (call-interactively 'org-move-item-up))
19366 (t (org-drag-element-backward))))
19368 (defun org-metadown (&optional arg)
19369 "Move subtree down or move table row down.
19370 Calls `org-move-subtree-down' or `org-table-move-row' or
19371 `org-move-item-down', depending on context. See the individual
19372 commands for more information."
19373 (interactive "P")
19374 (cond
19375 ((run-hook-with-args-until-success 'org-metadown-hook))
19376 ((org-region-active-p)
19377 (let* ((a (min (region-beginning) (region-end)))
19378 (b (max (region-beginning) (region-end)))
19379 (c (save-excursion (goto-char b)
19380 (move-beginning-of-line 1)))
19381 (d (save-excursion (goto-char b)
19382 (move-end-of-line 1) (1+ (point)))))
19383 (transpose-regions a b c d)
19384 (goto-char d)))
19385 ((org-at-table-p) (call-interactively 'org-table-move-row))
19386 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19387 ((org-at-item-p) (call-interactively 'org-move-item-down))
19388 (t (org-drag-element-forward))))
19390 (defun org-shiftup (&optional arg)
19391 "Increase item in timestamp or increase priority of current headline.
19392 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19393 depending on context. See the individual commands for more information."
19394 (interactive "P")
19395 (cond
19396 ((run-hook-with-args-until-success 'org-shiftup-hook))
19397 ((and org-support-shift-select (org-region-active-p))
19398 (org-call-for-shift-select 'previous-line))
19399 ((org-at-timestamp-p t)
19400 (call-interactively (if org-edit-timestamp-down-means-later
19401 'org-timestamp-down 'org-timestamp-up)))
19402 ((and (not (eq org-support-shift-select 'always))
19403 org-enable-priority-commands
19404 (org-at-heading-p))
19405 (call-interactively 'org-priority-up))
19406 ((and (not org-support-shift-select) (org-at-item-p))
19407 (call-interactively 'org-previous-item))
19408 ((org-clocktable-try-shift 'up arg))
19409 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19410 (org-support-shift-select
19411 (org-call-for-shift-select 'previous-line))
19412 (t (org-shiftselect-error))))
19414 (defun org-shiftdown (&optional arg)
19415 "Decrease item in timestamp or decrease priority of current headline.
19416 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19417 depending on context. See the individual commands for more information."
19418 (interactive "P")
19419 (cond
19420 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19421 ((and org-support-shift-select (org-region-active-p))
19422 (org-call-for-shift-select 'next-line))
19423 ((org-at-timestamp-p t)
19424 (call-interactively (if org-edit-timestamp-down-means-later
19425 'org-timestamp-up 'org-timestamp-down)))
19426 ((and (not (eq org-support-shift-select 'always))
19427 org-enable-priority-commands
19428 (org-at-heading-p))
19429 (call-interactively 'org-priority-down))
19430 ((and (not org-support-shift-select) (org-at-item-p))
19431 (call-interactively 'org-next-item))
19432 ((org-clocktable-try-shift 'down arg))
19433 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19434 (org-support-shift-select
19435 (org-call-for-shift-select 'next-line))
19436 (t (org-shiftselect-error))))
19438 (defun org-shiftright (&optional arg)
19439 "Cycle the thing at point or in the current line, depending on context.
19440 Depending on context, this does one of the following:
19442 - switch a timestamp at point one day into the future
19443 - on a headline, switch to the next TODO keyword.
19444 - on an item, switch entire list to the next bullet type
19445 - on a property line, switch to the next allowed value
19446 - on a clocktable definition line, move time block into the future"
19447 (interactive "P")
19448 (cond
19449 ((run-hook-with-args-until-success 'org-shiftright-hook))
19450 ((and org-support-shift-select (org-region-active-p))
19451 (org-call-for-shift-select 'forward-char))
19452 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19453 ((and (not (eq org-support-shift-select 'always))
19454 (org-at-heading-p))
19455 (let ((org-inhibit-logging
19456 (not org-treat-S-cursor-todo-selection-as-state-change))
19457 (org-inhibit-blocking
19458 (not org-treat-S-cursor-todo-selection-as-state-change)))
19459 (org-call-with-arg 'org-todo 'right)))
19460 ((or (and org-support-shift-select
19461 (not (eq org-support-shift-select 'always))
19462 (org-at-item-bullet-p))
19463 (and (not org-support-shift-select) (org-at-item-p)))
19464 (org-call-with-arg 'org-cycle-list-bullet nil))
19465 ((and (not (eq org-support-shift-select 'always))
19466 (org-at-property-p))
19467 (call-interactively 'org-property-next-allowed-value))
19468 ((org-clocktable-try-shift 'right arg))
19469 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19470 (org-support-shift-select
19471 (org-call-for-shift-select 'forward-char))
19472 (t (org-shiftselect-error))))
19474 (defun org-shiftleft (&optional arg)
19475 "Cycle the thing at point or in the current line, depending on context.
19476 Depending on context, this does one of the following:
19478 - switch a timestamp at point one day into the past
19479 - on a headline, switch to the previous TODO keyword.
19480 - on an item, switch entire list to the previous bullet type
19481 - on a property line, switch to the previous allowed value
19482 - on a clocktable definition line, move time block into the past"
19483 (interactive "P")
19484 (cond
19485 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19486 ((and org-support-shift-select (org-region-active-p))
19487 (org-call-for-shift-select 'backward-char))
19488 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19489 ((and (not (eq org-support-shift-select 'always))
19490 (org-at-heading-p))
19491 (let ((org-inhibit-logging
19492 (not org-treat-S-cursor-todo-selection-as-state-change))
19493 (org-inhibit-blocking
19494 (not org-treat-S-cursor-todo-selection-as-state-change)))
19495 (org-call-with-arg 'org-todo 'left)))
19496 ((or (and org-support-shift-select
19497 (not (eq org-support-shift-select 'always))
19498 (org-at-item-bullet-p))
19499 (and (not org-support-shift-select) (org-at-item-p)))
19500 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19501 ((and (not (eq org-support-shift-select 'always))
19502 (org-at-property-p))
19503 (call-interactively 'org-property-previous-allowed-value))
19504 ((org-clocktable-try-shift 'left arg))
19505 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19506 (org-support-shift-select
19507 (org-call-for-shift-select 'backward-char))
19508 (t (org-shiftselect-error))))
19510 (defun org-shiftcontrolright ()
19511 "Switch to next TODO set."
19512 (interactive)
19513 (cond
19514 ((and org-support-shift-select (org-region-active-p))
19515 (org-call-for-shift-select 'forward-word))
19516 ((and (not (eq org-support-shift-select 'always))
19517 (org-at-heading-p))
19518 (org-call-with-arg 'org-todo 'nextset))
19519 (org-support-shift-select
19520 (org-call-for-shift-select 'forward-word))
19521 (t (org-shiftselect-error))))
19523 (defun org-shiftcontrolleft ()
19524 "Switch to previous TODO set."
19525 (interactive)
19526 (cond
19527 ((and org-support-shift-select (org-region-active-p))
19528 (org-call-for-shift-select 'backward-word))
19529 ((and (not (eq org-support-shift-select 'always))
19530 (org-at-heading-p))
19531 (org-call-with-arg 'org-todo 'previousset))
19532 (org-support-shift-select
19533 (org-call-for-shift-select 'backward-word))
19534 (t (org-shiftselect-error))))
19536 (defun org-shiftcontrolup (&optional n)
19537 "Change timestamps synchronously up in CLOCK log lines.
19538 Optional argument N tells to change by that many units."
19539 (interactive "P")
19540 (cond ((and (not org-support-shift-select)
19541 (org-at-clock-log-p)
19542 (org-at-timestamp-p t))
19543 (org-clock-timestamps-up n))
19544 (t (org-shiftselect-error))))
19546 (defun org-shiftcontroldown (&optional n)
19547 "Change timestamps synchronously down in CLOCK log lines.
19548 Optional argument N tells to change by that many units."
19549 (interactive "P")
19550 (cond ((and (not org-support-shift-select)
19551 (org-at-clock-log-p)
19552 (org-at-timestamp-p t))
19553 (org-clock-timestamps-down n))
19554 (t (org-shiftselect-error))))
19556 (defun org-ctrl-c-ret ()
19557 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19558 (interactive)
19559 (cond
19560 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19561 (t (call-interactively 'org-insert-heading))))
19563 (defun org-find-visible ()
19564 (let ((s (point)))
19565 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19566 (get-char-property s 'invisible)))
19568 (defun org-find-invisible ()
19569 (let ((s (point)))
19570 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19571 (not (get-char-property s 'invisible))))
19574 (defun org-copy-visible (beg end)
19575 "Copy the visible parts of the region."
19576 (interactive "r")
19577 (let (snippets s)
19578 (save-excursion
19579 (save-restriction
19580 (narrow-to-region beg end)
19581 (setq s (goto-char (point-min)))
19582 (while (not (= (point) (point-max)))
19583 (goto-char (org-find-invisible))
19584 (push (buffer-substring s (point)) snippets)
19585 (setq s (goto-char (org-find-visible))))))
19586 (kill-new (apply 'concat (nreverse snippets)))))
19588 (defun org-copy-special ()
19589 "Copy region in table or copy current subtree.
19590 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19591 See the individual commands for more information."
19592 (interactive)
19593 (call-interactively
19594 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19596 (defun org-cut-special ()
19597 "Cut region in table or cut current subtree.
19598 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19599 See the individual commands for more information."
19600 (interactive)
19601 (call-interactively
19602 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19604 (defun org-paste-special (arg)
19605 "Paste rectangular region into table, or past subtree relative to level.
19606 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19607 See the individual commands for more information."
19608 (interactive "P")
19609 (if (org-at-table-p)
19610 (org-table-paste-rectangle)
19611 (org-paste-subtree arg)))
19613 (defsubst org-in-fixed-width-region-p ()
19614 "Is point in a fixed-width region?"
19615 (save-match-data
19616 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19618 (defun org-edit-special (&optional arg)
19619 "Call a special editor for the element at point.
19620 When at a table, call the formula editor with `org-table-edit-formulas'.
19621 When in a source code block, call `org-edit-src-code'.
19622 When in a fixed-width region, call `org-edit-fixed-width-region'.
19623 When at an #+INCLUDE keyword, visit the included file.
19624 On a link, call `ffap' to visit the link at point.
19625 Otherwise, return a user error."
19626 (interactive)
19627 (let ((element (org-element-at-point)))
19628 (assert (not buffer-read-only) nil
19629 "Buffer is read-only: %s" (buffer-name))
19630 (case (org-element-type element)
19631 (src-block
19632 (if (not arg) (org-edit-src-code)
19633 (let* ((info (org-babel-get-src-block-info))
19634 (lang (nth 0 info))
19635 (params (nth 2 info))
19636 (session (cdr (assq :session params))))
19637 (if (not session) (org-edit-src-code)
19638 ;; At a src-block with a session and function called with
19639 ;; an ARG: switch to the buffer related to the inferior
19640 ;; process.
19641 (funcall (intern (concat "org-babel-prep-session:" lang))
19642 session params)))))
19643 (keyword
19644 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19645 (find-file
19646 (org-remove-double-quotes
19647 (car (org-split-string (org-element-property :value element)))))
19648 (user-error "No special environment to edit here")))
19649 (table
19650 (if (eq (org-element-property :type element) 'table.el)
19651 (org-edit-src-code)
19652 (call-interactively 'org-table-edit-formulas)))
19653 ;; Only Org tables contain `table-row' type elements.
19654 (table-row (call-interactively 'org-table-edit-formulas))
19655 ((example-block export-block) (org-edit-src-code))
19656 (fixed-width (org-edit-fixed-width-region))
19657 (otherwise
19658 ;; No notable element at point. Though, we may be at a link,
19659 ;; which is an object. Thus, scan deeper.
19660 (if (eq (org-element-type (org-element-context element)) 'link)
19661 (call-interactively 'ffap)
19662 (user-error "No special environment to edit here"))))))
19664 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19665 (defun org-ctrl-c-ctrl-c (&optional arg)
19666 "Set tags in headline, or update according to changed information at point.
19668 This command does many different things, depending on context:
19670 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19671 this is what we do.
19673 - If the cursor is on a statistics cookie, update it.
19675 - If the cursor is in a headline, prompt for tags and insert them
19676 into the current line, aligned to `org-tags-column'. When called
19677 with prefix arg, realign all tags in the current buffer.
19679 - If the cursor is in one of the special #+KEYWORD lines, this
19680 triggers scanning the buffer for these lines and updating the
19681 information.
19683 - If the cursor is inside a table, realign the table. This command
19684 works even if the automatic table editor has been turned off.
19686 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19687 the entire table.
19689 - If the cursor is at a footnote reference or definition, jump to
19690 the corresponding definition or references, respectively.
19692 - If the cursor is a the beginning of a dynamic block, update it.
19694 - If the current buffer is a capture buffer, close note and file it.
19696 - If the cursor is on a <<<target>>>, update radio targets and
19697 corresponding links in this buffer.
19699 - If the cursor is on a numbered item in a plain list, renumber the
19700 ordered list.
19702 - If the cursor is on a checkbox, toggle it.
19704 - If the cursor is on a code block, evaluate it. The variable
19705 `org-confirm-babel-evaluate' can be used to control prompting
19706 before code block evaluation, by default every code block
19707 evaluation requires confirmation. Code block evaluation can be
19708 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19709 (interactive "P")
19710 (cond
19711 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19712 org-occur-highlights
19713 org-latex-fragment-image-overlays)
19714 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19715 (org-remove-occur-highlights)
19716 (org-remove-latex-fragment-image-overlays)
19717 (message "Temporary highlights/overlays removed from current buffer"))
19718 ((and (local-variable-p 'org-finish-function (current-buffer))
19719 (fboundp org-finish-function))
19720 (funcall org-finish-function))
19721 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19723 (let* ((context (org-element-context)) (type (org-element-type context)))
19724 ;; Test if point is within a blank line.
19725 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19726 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19727 (user-error "C-c C-c can do nothing useful at this location"))
19728 ;; For convenience: at the first line of a paragraph on the
19729 ;; same line as an item, apply function on that item instead.
19730 (when (eq type 'paragraph)
19731 (let ((parent (org-element-property :parent context)))
19732 (when (and (eq (org-element-type parent) 'item)
19733 (= (point-at-bol) (org-element-property :begin parent)))
19734 (setq context parent type 'item))))
19735 ;; Act according to type of element or object at point.
19736 (case type
19737 (clock (org-clock-update-time-maybe))
19738 (dynamic-block
19739 (save-excursion
19740 (goto-char (org-element-property :post-affiliated context))
19741 (org-update-dblock)))
19742 (footnote-definition
19743 (goto-char (org-element-property :post-affiliated context))
19744 (call-interactively 'org-footnote-action))
19745 (footnote-reference (call-interactively 'org-footnote-action))
19746 ((headline inlinetask)
19747 (save-excursion (goto-char (org-element-property :begin context))
19748 (call-interactively 'org-set-tags)))
19749 (item
19750 ;; At an item: a double C-u set checkbox to "[-]"
19751 ;; unconditionally, whereas a single one will toggle its
19752 ;; presence. Without an universal argument, if the item
19753 ;; has a checkbox, toggle it. Otherwise repair the list.
19754 (let* ((box (org-element-property :checkbox context))
19755 (struct (org-element-property :structure context))
19756 (old-struct (copy-tree struct))
19757 (parents (org-list-parents-alist struct))
19758 (prevs (org-list-prevs-alist struct))
19759 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19760 (org-list-set-checkbox
19761 (org-element-property :begin context) struct
19762 (cond ((equal arg '(16)) "[-]")
19763 ((and (not box) (equal arg '(4))) "[ ]")
19764 ((or (not box) (equal arg '(4))) nil)
19765 ((eq box 'on) "[ ]")
19766 (t "[X]")))
19767 ;; Mimic `org-list-write-struct' but with grabbing
19768 ;; a return value from `org-list-struct-fix-box'.
19769 (org-list-struct-fix-ind struct parents 2)
19770 (org-list-struct-fix-item-end struct)
19771 (org-list-struct-fix-bul struct prevs)
19772 (org-list-struct-fix-ind struct parents)
19773 (let ((block-item
19774 (org-list-struct-fix-box struct parents prevs orderedp)))
19775 (if (and box (equal struct old-struct))
19776 (if (equal arg '(16))
19777 (message "Checkboxes already reset")
19778 (user-error "Cannot toggle this checkbox: %s"
19779 (if (eq box 'on)
19780 "all subitems checked"
19781 "unchecked subitems")))
19782 (org-list-struct-apply-struct struct old-struct)
19783 (org-update-checkbox-count-maybe))
19784 (when block-item
19785 (message "Checkboxes were removed due to empty box at line %d"
19786 (org-current-line block-item))))))
19787 (keyword
19788 (let ((org-inhibit-startup-visibility-stuff t)
19789 (org-startup-align-all-tables nil))
19790 (when (boundp 'org-table-coordinate-overlays)
19791 (mapc 'delete-overlay org-table-coordinate-overlays)
19792 (setq org-table-coordinate-overlays nil))
19793 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19794 (message "Local setup has been refreshed"))
19795 (plain-list
19796 ;; At a plain list, with a double C-u argument, set
19797 ;; checkboxes of each item to "[-]", whereas a single one
19798 ;; will toggle their presence according to the state of the
19799 ;; first item in the list. Without an argument, repair the
19800 ;; list.
19801 (let* ((begin (org-element-property :contents-begin context))
19802 (struct (org-element-property :structure context))
19803 (old-struct (copy-tree struct))
19804 (first-box (save-excursion
19805 (goto-char begin)
19806 (looking-at org-list-full-item-re)
19807 (match-string-no-properties 3)))
19808 (new-box (cond ((equal arg '(16)) "[-]")
19809 ((equal arg '(4)) (unless first-box "[ ]"))
19810 ((equal first-box "[X]") "[ ]")
19811 (t "[X]"))))
19812 (cond
19813 (arg
19814 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19815 (org-list-get-all-items
19816 begin struct (org-list-prevs-alist struct))))
19817 ((and first-box (eq (point) begin))
19818 ;; For convenience, when point is at bol on the first
19819 ;; item of the list and no argument is provided, simply
19820 ;; toggle checkbox of that item, if any.
19821 (org-list-set-checkbox begin struct new-box)))
19822 (org-list-write-struct
19823 struct (org-list-parents-alist struct) old-struct)
19824 (org-update-checkbox-count-maybe)
19825 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19826 ((property-drawer node-property)
19827 (call-interactively 'org-property-action))
19828 ((radio-target target)
19829 (call-interactively 'org-update-radio-target-regexp))
19830 (statistics-cookie
19831 (call-interactively 'org-update-statistics-cookies))
19832 ((table table-cell table-row)
19833 ;; At a table, recalculate every field and align it. Also
19834 ;; send the table if necessary. If the table has
19835 ;; a `table.el' type, just give up. At a table row or
19836 ;; cell, maybe recalculate line but always align table.
19837 (if (eq (org-element-property :type context) 'table.el)
19838 (message "Use C-c ' to edit table.el tables")
19839 (let ((org-enable-table-editor t))
19840 (if (or (eq type 'table)
19841 ;; Check if point is at a TBLFM line.
19842 (and (eq type 'table-row)
19843 (= (point) (org-element-property :end context))))
19844 (save-excursion
19845 (goto-char (org-element-property :contents-begin context))
19846 (org-call-with-arg 'org-table-recalculate (or arg t))
19847 (orgtbl-send-table 'maybe))
19848 (org-table-maybe-eval-formula)
19849 (cond (arg (call-interactively 'org-table-recalculate))
19850 ((org-table-maybe-recalculate-line))
19851 (t (org-table-align)))))))
19852 (timestamp (org-timestamp-change 0 'day))
19853 (otherwise
19854 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19855 (user-error
19856 "C-c C-c can do nothing useful at this location")))))))))
19858 (defun org-mode-restart ()
19859 "Restart Org-mode, to scan again for special lines.
19860 Also updates the keyword regular expressions."
19861 (interactive)
19862 (org-mode)
19863 (message "Org-mode restarted"))
19865 (defun org-kill-note-or-show-branches ()
19866 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19867 (interactive)
19868 (if (not org-finish-function)
19869 (progn
19870 (hide-subtree)
19871 (call-interactively 'show-branches))
19872 (let ((org-note-abort t))
19873 (funcall org-finish-function))))
19875 (defun org-return (&optional indent)
19876 "Goto next table row or insert a newline.
19877 Calls `org-table-next-row' or `newline', depending on context.
19878 See the individual commands for more information."
19879 (interactive)
19880 (let (org-ts-what)
19881 (cond
19882 ((or (bobp) (org-in-src-block-p))
19883 (if indent (newline-and-indent) (newline)))
19884 ((org-at-table-p)
19885 (org-table-justify-field-maybe)
19886 (call-interactively 'org-table-next-row))
19887 ;; when `newline-and-indent' is called within a list, make sure
19888 ;; text moved stays inside the item.
19889 ((and (org-in-item-p) indent)
19890 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19891 (progn
19892 (save-match-data (newline))
19893 (org-indent-line-to (length (match-string 0))))
19894 (let ((ind (org-get-indentation)))
19895 (newline)
19896 (if (org-looking-back org-list-end-re)
19897 (org-indent-line)
19898 (org-indent-line-to ind)))))
19899 ((and org-return-follows-link
19900 (org-at-timestamp-p t)
19901 (not (eq org-ts-what 'after)))
19902 (org-follow-timestamp-link))
19903 ((and org-return-follows-link
19904 (let ((tprop (get-text-property (point) 'face)))
19905 (or (eq tprop 'org-link)
19906 (and (listp tprop) (memq 'org-link tprop)))))
19907 (call-interactively 'org-open-at-point))
19908 ((and (org-at-heading-p)
19909 (looking-at
19910 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19911 (org-show-entry)
19912 (end-of-line 1)
19913 (newline))
19914 (t (if indent (newline-and-indent) (newline))))))
19916 (defun org-return-indent ()
19917 "Goto next table row or insert a newline and indent.
19918 Calls `org-table-next-row' or `newline-and-indent', depending on
19919 context. See the individual commands for more information."
19920 (interactive)
19921 (org-return t))
19923 (defun org-ctrl-c-star ()
19924 "Compute table, or change heading status of lines.
19925 Calls `org-table-recalculate' or `org-toggle-heading',
19926 depending on context."
19927 (interactive)
19928 (cond
19929 ((org-at-table-p)
19930 (call-interactively 'org-table-recalculate))
19932 ;; Convert all lines in region to list items
19933 (call-interactively 'org-toggle-heading))))
19935 (defun org-ctrl-c-minus ()
19936 "Insert separator line in table or modify bullet status of line.
19937 Also turns a plain line or a region of lines into list items.
19938 Calls `org-table-insert-hline', `org-toggle-item', or
19939 `org-cycle-list-bullet', depending on context."
19940 (interactive)
19941 (cond
19942 ((org-at-table-p)
19943 (call-interactively 'org-table-insert-hline))
19944 ((org-region-active-p)
19945 (call-interactively 'org-toggle-item))
19946 ((org-in-item-p)
19947 (call-interactively 'org-cycle-list-bullet))
19949 (call-interactively 'org-toggle-item))))
19951 (defun org-toggle-item (arg)
19952 "Convert headings or normal lines to items, items to normal lines.
19953 If there is no active region, only the current line is considered.
19955 If the first non blank line in the region is an headline, convert
19956 all headlines to items, shifting text accordingly.
19958 If it is an item, convert all items to normal lines.
19960 If it is normal text, change region into an item. With a prefix
19961 argument ARG, change each line in region into an item."
19962 (interactive "P")
19963 (let ((shift-text
19964 (function
19965 ;; Shift text in current section to IND, from point to END.
19966 ;; The function leaves point to END line.
19967 (lambda (ind end)
19968 (let ((min-i 1000) (end (copy-marker end)))
19969 ;; First determine the minimum indentation (MIN-I) of
19970 ;; the text.
19971 (save-excursion
19972 (catch 'exit
19973 (while (< (point) end)
19974 (let ((i (org-get-indentation)))
19975 (cond
19976 ;; Skip blank lines and inline tasks.
19977 ((looking-at "^[ \t]*$"))
19978 ((looking-at org-outline-regexp-bol))
19979 ;; We can't find less than 0 indentation.
19980 ((zerop i) (throw 'exit (setq min-i 0)))
19981 ((< i min-i) (setq min-i i))))
19982 (forward-line))))
19983 ;; Then indent each line so that a line indented to
19984 ;; MIN-I becomes indented to IND. Ignore blank lines
19985 ;; and inline tasks in the process.
19986 (let ((delta (- ind min-i)))
19987 (while (< (point) end)
19988 (unless (or (looking-at "^[ \t]*$")
19989 (looking-at org-outline-regexp-bol))
19990 (org-indent-line-to (+ (org-get-indentation) delta)))
19991 (forward-line)))))))
19992 (skip-blanks
19993 (function
19994 ;; Return beginning of first non-blank line, starting from
19995 ;; line at POS.
19996 (lambda (pos)
19997 (save-excursion
19998 (goto-char pos)
19999 (skip-chars-forward " \r\t\n")
20000 (point-at-bol)))))
20001 beg end)
20002 ;; Determine boundaries of changes.
20003 (if (org-region-active-p)
20004 (setq beg (funcall skip-blanks (region-beginning))
20005 end (copy-marker (region-end)))
20006 (setq beg (funcall skip-blanks (point-at-bol))
20007 end (copy-marker (point-at-eol))))
20008 ;; Depending on the starting line, choose an action on the text
20009 ;; between BEG and END.
20010 (org-with-limited-levels
20011 (save-excursion
20012 (goto-char beg)
20013 (cond
20014 ;; Case 1. Start at an item: de-itemize. Note that it only
20015 ;; happens when a region is active: `org-ctrl-c-minus'
20016 ;; would call `org-cycle-list-bullet' otherwise.
20017 ((org-at-item-p)
20018 (while (< (point) end)
20019 (when (org-at-item-p)
20020 (skip-chars-forward " \t")
20021 (delete-region (point) (match-end 0)))
20022 (forward-line)))
20023 ;; Case 2. Start at an heading: convert to items.
20024 ((org-at-heading-p)
20025 (let* ((bul (org-list-bullet-string "-"))
20026 (bul-len (length bul))
20027 ;; Indentation of the first heading. It should be
20028 ;; relative to the indentation of its parent, if any.
20029 (start-ind (save-excursion
20030 (cond
20031 ((not org-adapt-indentation) 0)
20032 ((not (outline-previous-heading)) 0)
20033 (t (length (match-string 0))))))
20034 ;; Level of first heading. Further headings will be
20035 ;; compared to it to determine hierarchy in the list.
20036 (ref-level (org-reduced-level (org-outline-level))))
20037 (while (< (point) end)
20038 (let* ((level (org-reduced-level (org-outline-level)))
20039 (delta (max 0 (- level ref-level))))
20040 ;; If current headline is less indented than the first
20041 ;; one, set it as reference, in order to preserve
20042 ;; subtrees.
20043 (when (< level ref-level) (setq ref-level level))
20044 (replace-match bul t t)
20045 (org-indent-line-to (+ start-ind (* delta bul-len)))
20046 ;; Ensure all text down to END (or SECTION-END) belongs
20047 ;; to the newly created item.
20048 (let ((section-end (save-excursion
20049 (or (outline-next-heading) (point)))))
20050 (forward-line)
20051 (funcall shift-text
20052 (+ start-ind (* (1+ delta) bul-len))
20053 (min end section-end)))))))
20054 ;; Case 3. Normal line with ARG: turn each non-item line into
20055 ;; an item.
20056 (arg
20057 (while (< (point) end)
20058 (unless (or (org-at-heading-p) (org-at-item-p))
20059 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20060 (replace-match
20061 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20062 (forward-line)))
20063 ;; Case 4. Normal line without ARG: make the first line of
20064 ;; region an item, and shift indentation of others
20065 ;; lines to set them as item's body.
20066 (t (let* ((bul (org-list-bullet-string "-"))
20067 (bul-len (length bul))
20068 (ref-ind (org-get-indentation)))
20069 (skip-chars-forward " \t")
20070 (insert bul)
20071 (forward-line)
20072 (while (< (point) end)
20073 ;; Ensure that lines less indented than first one
20074 ;; still get included in item body.
20075 (funcall shift-text
20076 (+ ref-ind bul-len)
20077 (min end (save-excursion (or (outline-next-heading)
20078 (point)))))
20079 (forward-line)))))))))
20081 (defun org-toggle-heading (&optional nstars)
20082 "Convert headings to normal text, or items or text to headings.
20083 If there is no active region, only the current line is considered.
20085 With a \\[universal-argument] prefix, convert the whole list at
20086 point into heading.
20088 In a region:
20090 - If the first non blank line is an headline, remove the stars
20091 from all headlines in the region.
20093 - If it is a normal line turn each and every normal line (i.e. not an
20094 heading or an item) in the region into a heading.
20096 - If it is a plain list item, turn all plain list items into headings.
20098 When converting a line into a heading, the number of stars is chosen
20099 such that the lines become children of the current entry. However,
20100 when a prefix argument is given, its value determines the number of
20101 stars to add."
20102 (interactive "P")
20103 (let ((skip-blanks
20104 (function
20105 ;; Return beginning of first non-blank line, starting from
20106 ;; line at POS.
20107 (lambda (pos)
20108 (save-excursion
20109 (goto-char pos)
20110 (while (org-at-comment-p) (forward-line))
20111 (skip-chars-forward " \r\t\n")
20112 (point-at-bol)))))
20113 beg end toggled)
20114 ;; Determine boundaries of changes. If a universal prefix has
20115 ;; been given, put the list in a region. If region ends at a bol,
20116 ;; do not consider the last line to be in the region.
20118 (when (and current-prefix-arg (org-at-item-p))
20119 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20120 (org-mark-element))
20122 (if (org-region-active-p)
20123 (setq beg (funcall skip-blanks (region-beginning))
20124 end (copy-marker (save-excursion
20125 (goto-char (region-end))
20126 (if (bolp) (point) (point-at-eol)))))
20127 (setq beg (funcall skip-blanks (point-at-bol))
20128 end (copy-marker (point-at-eol))))
20129 ;; Ensure inline tasks don't count as headings.
20130 (org-with-limited-levels
20131 (save-excursion
20132 (goto-char beg)
20133 (cond
20134 ;; Case 1. Started at an heading: de-star headings.
20135 ((org-at-heading-p)
20136 (while (< (point) end)
20137 (when (org-at-heading-p t)
20138 (looking-at org-outline-regexp) (replace-match "")
20139 (setq toggled t))
20140 (forward-line)))
20141 ;; Case 2. Started at an item: change items into headlines.
20142 ;; One star will be added by `org-list-to-subtree'.
20143 ((org-at-item-p)
20144 (let* ((stars (make-string
20145 (if nstars
20146 ;; subtract the star that will be added again by
20147 ;; `org-list-to-subtree'
20148 (1- (prefix-numeric-value current-prefix-arg))
20149 (or (org-current-level) 0))
20150 ?*))
20151 (add-stars
20152 (cond (nstars "") ; stars from prefix only
20153 ((equal stars "") "") ; before first heading
20154 (org-odd-levels-only "*") ; inside heading, odd
20155 (t "")))) ; inside heading, oddeven
20156 (while (< (point) end)
20157 (when (org-at-item-p)
20158 ;; Pay attention to cases when region ends before list.
20159 (let* ((struct (org-list-struct))
20160 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20161 (save-restriction
20162 (narrow-to-region (point) list-end)
20163 (insert
20164 (org-list-to-subtree
20165 (org-list-parse-list t)
20166 '(:istart (concat stars add-stars (funcall get-stars depth))
20167 :icount (concat stars add-stars (funcall get-stars depth)))))))
20168 (setq toggled t))
20169 (forward-line))))
20170 ;; Case 3. Started at normal text: make every line an heading,
20171 ;; skipping headlines and items.
20172 (t (let* ((stars (make-string
20173 (if nstars
20174 (prefix-numeric-value current-prefix-arg)
20175 (or (org-current-level) 0))
20176 ?*))
20177 (add-stars
20178 (cond (nstars "") ; stars from prefix only
20179 ((equal stars "") "*") ; before first heading
20180 (org-odd-levels-only "**") ; inside heading, odd
20181 (t "*"))) ; inside heading, oddeven
20182 (rpl (concat stars add-stars " ")))
20183 (while (< (point) end)
20184 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20185 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20186 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20187 (forward-line)))))))
20188 (unless toggled (message "Cannot toggle heading from here"))))
20190 (defun org-meta-return (&optional arg)
20191 "Insert a new heading or wrap a region in a table.
20192 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20193 See the individual commands for more information."
20194 (interactive "P")
20195 (cond
20196 ((run-hook-with-args-until-success 'org-metareturn-hook))
20197 ((or (org-at-drawer-p) (org-at-property-p))
20198 (newline-and-indent))
20199 ((org-at-table-p)
20200 (call-interactively 'org-table-wrap-region))
20201 (t (call-interactively 'org-insert-heading))))
20203 ;;; Menu entries
20205 (defsubst org-in-subtree-not-table-p ()
20206 "Are we in a subtree and not in a table?"
20207 (and (not (org-before-first-heading-p))
20208 (not (org-at-table-p))))
20210 ;; Define the Org-mode menus
20211 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20212 '("Tbl"
20213 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20214 ["Next Field" org-cycle (org-at-table-p)]
20215 ["Previous Field" org-shifttab (org-at-table-p)]
20216 ["Next Row" org-return (org-at-table-p)]
20217 "--"
20218 ["Blank Field" org-table-blank-field (org-at-table-p)]
20219 ["Edit Field" org-table-edit-field (org-at-table-p)]
20220 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20221 "--"
20222 ("Column"
20223 ["Move Column Left" org-metaleft (org-at-table-p)]
20224 ["Move Column Right" org-metaright (org-at-table-p)]
20225 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20226 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20227 ("Row"
20228 ["Move Row Up" org-metaup (org-at-table-p)]
20229 ["Move Row Down" org-metadown (org-at-table-p)]
20230 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20231 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20232 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20233 "--"
20234 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20235 ("Rectangle"
20236 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20237 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20238 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20239 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20240 "--"
20241 ("Calculate"
20242 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20243 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20244 ["Edit Formulas" org-edit-special (org-at-table-p)]
20245 "--"
20246 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20247 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20248 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20249 "--"
20250 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20251 "--"
20252 ["Sum Column/Rectangle" org-table-sum
20253 (or (org-at-table-p) (org-region-active-p))]
20254 ["Which Column?" org-table-current-column (org-at-table-p)])
20255 ["Debug Formulas"
20256 org-table-toggle-formula-debugger
20257 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20258 ["Show Col/Row Numbers"
20259 org-table-toggle-coordinate-overlays
20260 :style toggle
20261 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20262 "--"
20263 ["Create" org-table-create (and (not (org-at-table-p))
20264 org-enable-table-editor)]
20265 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20266 ["Import from File" org-table-import (not (org-at-table-p))]
20267 ["Export to File" org-table-export (org-at-table-p)]
20268 "--"
20269 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20271 (easy-menu-define org-org-menu org-mode-map "Org menu"
20272 '("Org"
20273 ("Show/Hide"
20274 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20275 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20276 ["Sparse Tree..." org-sparse-tree t]
20277 ["Reveal Context" org-reveal t]
20278 ["Show All" show-all t]
20279 "--"
20280 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20281 "--"
20282 ["New Heading" org-insert-heading t]
20283 ("Navigate Headings"
20284 ["Up" outline-up-heading t]
20285 ["Next" outline-next-visible-heading t]
20286 ["Previous" outline-previous-visible-heading t]
20287 ["Next Same Level" outline-forward-same-level t]
20288 ["Previous Same Level" outline-backward-same-level t]
20289 "--"
20290 ["Jump" org-goto t])
20291 ("Edit Structure"
20292 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20293 "--"
20294 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20295 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20296 "--"
20297 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20298 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20299 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20300 "--"
20301 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20302 "--"
20303 ["Copy visible text" org-copy-visible t]
20304 "--"
20305 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20306 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20307 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20308 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20309 "--"
20310 ["Sort Region/Children" org-sort t]
20311 "--"
20312 ["Convert to odd levels" org-convert-to-odd-levels t]
20313 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20314 ("Editing"
20315 ["Emphasis..." org-emphasize t]
20316 ["Edit Source Example" org-edit-special t]
20317 "--"
20318 ["Footnote new/jump" org-footnote-action t]
20319 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20320 ("Archive"
20321 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20322 "--"
20323 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20324 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20325 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20327 "--"
20328 ("Hyperlinks"
20329 ["Store Link (Global)" org-store-link t]
20330 ["Find existing link to here" org-occur-link-in-agenda-files t]
20331 ["Insert Link" org-insert-link t]
20332 ["Follow Link" org-open-at-point t]
20333 "--"
20334 ["Next link" org-next-link t]
20335 ["Previous link" org-previous-link t]
20336 "--"
20337 ["Descriptive Links"
20338 org-toggle-link-display
20339 :style radio
20340 :selected org-descriptive-links
20342 ["Literal Links"
20343 org-toggle-link-display
20344 :style radio
20345 :selected (not org-descriptive-links)])
20346 "--"
20347 ("TODO Lists"
20348 ["TODO/DONE/-" org-todo t]
20349 ("Select keyword"
20350 ["Next keyword" org-shiftright (org-at-heading-p)]
20351 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20352 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20353 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20354 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20355 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20356 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20357 "--"
20358 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20359 :selected org-enforce-todo-dependencies :style toggle :active t]
20360 "Settings for tree at point"
20361 ["Do Children sequentially" org-toggle-ordered-property :style radio
20362 :selected (org-entry-get nil "ORDERED")
20363 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20364 ["Do Children parallel" org-toggle-ordered-property :style radio
20365 :selected (not (org-entry-get nil "ORDERED"))
20366 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20367 "--"
20368 ["Set Priority" org-priority t]
20369 ["Priority Up" org-shiftup t]
20370 ["Priority Down" org-shiftdown t]
20371 "--"
20372 ["Get news from all feeds" org-feed-update-all t]
20373 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20374 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20375 ("TAGS and Properties"
20376 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20377 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20378 "--"
20379 ["Set property" org-set-property (not (org-before-first-heading-p))]
20380 ["Column view of properties" org-columns t]
20381 ["Insert Column View DBlock" org-insert-columns-dblock t])
20382 ("Dates and Scheduling"
20383 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20384 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20385 ("Change Date"
20386 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20387 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20388 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20389 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20390 ["Compute Time Range" org-evaluate-time-range t]
20391 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20392 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20393 "--"
20394 ["Custom time format" org-toggle-time-stamp-overlays
20395 :style radio :selected org-display-custom-times]
20396 "--"
20397 ["Goto Calendar" org-goto-calendar t]
20398 ["Date from Calendar" org-date-from-calendar t]
20399 "--"
20400 ["Start/Restart Timer" org-timer-start t]
20401 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20402 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20403 ["Insert Timer String" org-timer t]
20404 ["Insert Timer Item" org-timer-item t])
20405 ("Logging work"
20406 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20407 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20408 ["Clock out" org-clock-out t]
20409 ["Clock cancel" org-clock-cancel t]
20410 "--"
20411 ["Mark as default task" org-clock-mark-default-task t]
20412 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20413 ["Goto running clock" org-clock-goto t]
20414 "--"
20415 ["Display times" org-clock-display t]
20416 ["Create clock table" org-clock-report t]
20417 "--"
20418 ["Record DONE time"
20419 (progn (setq org-log-done (not org-log-done))
20420 (message "Switching to %s will %s record a timestamp"
20421 (car org-done-keywords)
20422 (if org-log-done "automatically" "not")))
20423 :style toggle :selected org-log-done])
20424 "--"
20425 ["Agenda Command..." org-agenda t]
20426 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20427 ("File List for Agenda")
20428 ("Special views current file"
20429 ["TODO Tree" org-show-todo-tree t]
20430 ["Check Deadlines" org-check-deadlines t]
20431 ["Timeline" org-timeline t]
20432 ["Tags/Property tree" org-match-sparse-tree t])
20433 "--"
20434 ["Export/Publish..." org-export-dispatch t]
20435 ("LaTeX"
20436 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20437 :selected org-cdlatex-mode]
20438 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20439 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20440 ["Modify math symbol" org-cdlatex-math-modify
20441 (org-inside-LaTeX-fragment-p)]
20442 ["Insert citation" org-reftex-citation t]
20443 "--"
20444 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20445 "--"
20446 ("MobileOrg"
20447 ["Push Files and Views" org-mobile-push t]
20448 ["Get Captured and Flagged" org-mobile-pull t]
20449 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20450 "--"
20451 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20452 "--"
20453 ("Documentation"
20454 ["Show Version" org-version t]
20455 ["Info Documentation" org-info t])
20456 ("Customize"
20457 ["Browse Org Group" org-customize t]
20458 "--"
20459 ["Expand This Menu" org-create-customize-menu
20460 (fboundp 'customize-menu-create)])
20461 ["Send bug report" org-submit-bug-report t]
20462 "--"
20463 ("Refresh/Reload"
20464 ["Refresh setup current buffer" org-mode-restart t]
20465 ["Reload Org (after update)" org-reload t]
20466 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20469 (defun org-info (&optional node)
20470 "Read documentation for Org-mode in the info system.
20471 With optional NODE, go directly to that node."
20472 (interactive)
20473 (info (format "(org)%s" (or node ""))))
20475 ;;;###autoload
20476 (defun org-submit-bug-report ()
20477 "Submit a bug report on Org-mode via mail.
20479 Don't hesitate to report any problems or inaccurate documentation.
20481 If you don't have setup sending mail from (X)Emacs, please copy the
20482 output buffer into your mail program, as it gives us important
20483 information about your Org-mode version and configuration."
20484 (interactive)
20485 (require 'reporter)
20486 (org-load-modules-maybe)
20487 (org-require-autoloaded-modules)
20488 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20489 (reporter-submit-bug-report
20490 "emacs-orgmode@gnu.org"
20491 (org-version nil 'full)
20492 (let (list)
20493 (save-window-excursion
20494 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20495 (delete-other-windows)
20496 (erase-buffer)
20497 (insert "You are about to submit a bug report to the Org-mode mailing list.
20499 We would like to add your full Org-mode and Outline configuration to the
20500 bug report. This greatly simplifies the work of the maintainer and
20501 other experts on the mailing list.
20503 HOWEVER, some variables you have customized may contain private
20504 information. The names of customers, colleagues, or friends, might
20505 appear in the form of file names, tags, todo states, or search strings.
20506 If you answer yes to the prompt, you might want to check and remove
20507 such private information before sending the email.")
20508 (add-text-properties (point-min) (point-max) '(face org-warning))
20509 (when (yes-or-no-p "Include your Org-mode configuration ")
20510 (mapatoms
20511 (lambda (v)
20512 (and (boundp v)
20513 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20514 (or (and (symbol-value v)
20515 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20516 (and
20517 (get v 'custom-type) (get v 'standard-value)
20518 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20519 (push v list)))))
20520 (kill-buffer (get-buffer "*Warn about privacy*"))
20521 list))
20522 nil nil
20523 "Remember to cover the basics, that is, what you expected to happen and
20524 what in fact did happen. You don't know how to make a good report? See
20526 http://orgmode.org/manual/Feedback.html#Feedback
20528 Your bug report will be posted to the Org-mode mailing list.
20529 ------------------------------------------------------------------------")
20530 (save-excursion
20531 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20532 (replace-match "\\1Bug: \\3 [\\2]")))))
20535 (defun org-install-agenda-files-menu ()
20536 (let ((bl (buffer-list)))
20537 (save-excursion
20538 (while bl
20539 (set-buffer (pop bl))
20540 (if (derived-mode-p 'org-mode) (setq bl nil)))
20541 (when (derived-mode-p 'org-mode)
20542 (easy-menu-change
20543 '("Org") "File List for Agenda"
20544 (append
20545 (list
20546 ["Edit File List" (org-edit-agenda-file-list) t]
20547 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20548 ["Remove Current File from List" org-remove-file t]
20549 ["Cycle through agenda files" org-cycle-agenda-files t]
20550 ["Occur in all agenda files" org-occur-in-agenda-files t]
20551 "--")
20552 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20554 ;;;; Documentation
20556 (defun org-require-autoloaded-modules ()
20557 (interactive)
20558 (mapc 'require
20559 '(org-agenda org-archive org-attach org-clock org-colview org-id
20560 org-remember org-table org-timer)))
20562 ;;;###autoload
20563 (defun org-reload (&optional uncompiled)
20564 "Reload all org lisp files.
20565 With prefix arg UNCOMPILED, load the uncompiled versions."
20566 (interactive "P")
20567 (require 'loadhist)
20568 (let* ((org-dir (org-find-library-dir "org"))
20569 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20570 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20571 (remove-re (mapconcat 'identity
20572 (mapcar (lambda (f) (concat "^" f "$"))
20573 (list (if (featurep 'xemacs)
20574 "org-colview"
20575 "org-colview-xemacs")
20576 "org" "org-loaddefs" "org-version"))
20577 "\\|"))
20578 (feats (delete-dups
20579 (mapcar 'file-name-sans-extension
20580 (mapcar 'file-name-nondirectory
20581 (delq nil
20582 (mapcar 'feature-file
20583 features))))))
20584 (lfeat (append
20585 (sort
20586 (setq feats
20587 (delq nil (mapcar
20588 (lambda (f)
20589 (if (and (string-match feature-re f)
20590 (not (string-match remove-re f)))
20591 f nil))
20592 feats)))
20593 'string-lessp)
20594 (list "org-version" "org")))
20595 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20596 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20597 load-uncore load-misses)
20598 (setq load-misses
20599 (delq 't
20600 (mapcar (lambda (f)
20601 (or (org-load-noerror-mustsuffix (concat org-dir f))
20602 (and (string= org-dir contrib-dir)
20603 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20604 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20605 (add-to-list 'load-uncore f 'append)
20608 lfeat)))
20609 (if load-uncore
20610 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20611 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20612 (if load-misses
20613 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20614 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20615 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20617 ;;;###autoload
20618 (defun org-customize ()
20619 "Call the customize function with org as argument."
20620 (interactive)
20621 (org-load-modules-maybe)
20622 (org-require-autoloaded-modules)
20623 (customize-browse 'org))
20625 (defun org-create-customize-menu ()
20626 "Create a full customization menu for Org-mode, insert it into the menu."
20627 (interactive)
20628 (org-load-modules-maybe)
20629 (org-require-autoloaded-modules)
20630 (if (fboundp 'customize-menu-create)
20631 (progn
20632 (easy-menu-change
20633 '("Org") "Customize"
20634 `(["Browse Org group" org-customize t]
20635 "--"
20636 ,(customize-menu-create 'org)
20637 ["Set" Custom-set t]
20638 ["Save" Custom-save t]
20639 ["Reset to Current" Custom-reset-current t]
20640 ["Reset to Saved" Custom-reset-saved t]
20641 ["Reset to Standard Settings" Custom-reset-standard t]))
20642 (message "\"Org\"-menu now contains full customization menu"))
20643 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20645 ;;;; Miscellaneous stuff
20647 ;;; Generally useful functions
20649 (defun org-get-at-bol (property)
20650 "Get text property PROPERTY at beginning of line."
20651 (get-text-property (point-at-bol) property))
20653 (defun org-find-text-property-in-string (prop s)
20654 "Return the first non-nil value of property PROP in string S."
20655 (or (get-text-property 0 prop s)
20656 (get-text-property (or (next-single-property-change 0 prop s) 0)
20657 prop s)))
20659 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20660 "Display the given MESSAGE as a warning."
20661 (if (fboundp 'display-warning)
20662 (display-warning 'org message
20663 (if (featurep 'xemacs) 'warning :warning))
20664 (let ((buf (get-buffer-create "*Org warnings*")))
20665 (with-current-buffer buf
20666 (goto-char (point-max))
20667 (insert "Warning (Org): " message)
20668 (unless (bolp)
20669 (newline)))
20670 (display-buffer buf)
20671 (sit-for 0))))
20673 (defun org-eval (form)
20674 "Eval FORM and return result."
20675 (condition-case error
20676 (eval form)
20677 (error (format "%%![Error: %s]" error))))
20679 (defun org-in-clocktable-p ()
20680 "Check if the cursor is in a clocktable."
20681 (let ((pos (point)) start)
20682 (save-excursion
20683 (end-of-line 1)
20684 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20685 (setq start (match-beginning 0))
20686 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20687 (>= (match-end 0) pos)
20688 start))))
20690 (defun org-in-commented-line ()
20691 "Is point in a line starting with `#'?"
20692 (equal (char-after (point-at-bol)) ?#))
20694 (defun org-in-indented-comment-line ()
20695 "Is point in a line starting with `#' after some white space?"
20696 (save-excursion
20697 (save-match-data
20698 (goto-char (point-at-bol))
20699 (looking-at "[ \t]*#"))))
20701 (defun org-in-verbatim-emphasis ()
20702 (save-match-data
20703 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20705 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20706 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20707 (if (and marker (marker-buffer marker)
20708 (buffer-live-p (marker-buffer marker)))
20709 (progn
20710 (org-pop-to-buffer-same-window (marker-buffer marker))
20711 (if (or (> marker (point-max)) (< marker (point-min)))
20712 (widen))
20713 (goto-char marker)
20714 (org-show-context 'org-goto))
20715 (if bookmark
20716 (bookmark-jump bookmark)
20717 (error "Cannot find location"))))
20719 (defun org-quote-csv-field (s)
20720 "Quote field for inclusion in CSV material."
20721 (if (string-match "[\",]" s)
20722 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20725 (defun org-force-self-insert (N)
20726 "Needed to enforce self-insert under remapping."
20727 (interactive "p")
20728 (self-insert-command N))
20730 (defun org-string-width (s)
20731 "Compute width of string, ignoring invisible characters.
20732 This ignores character with invisibility property `org-link', and also
20733 characters with property `org-cwidth', because these will become invisible
20734 upon the next fontification round."
20735 (let (b l)
20736 (when (or (eq t buffer-invisibility-spec)
20737 (assq 'org-link buffer-invisibility-spec))
20738 (while (setq b (text-property-any 0 (length s)
20739 'invisible 'org-link s))
20740 (setq s (concat (substring s 0 b)
20741 (substring s (or (next-single-property-change
20742 b 'invisible s) (length s)))))))
20743 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20744 (setq s (concat (substring s 0 b)
20745 (substring s (or (next-single-property-change
20746 b 'org-cwidth s) (length s))))))
20747 (setq l (string-width s) b -1)
20748 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20749 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20752 (defun org-shorten-string (s maxlength)
20753 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20754 If the string is shorter or has length MAXLENGTH, just return the
20755 original string. If it is longer, the functions finds a space in the
20756 string, breaks this string off at that locations and adds three dots
20757 as ellipsis. Including the ellipsis, the string will not be longer
20758 than MAXLENGTH. If finding a good breaking point in the string does
20759 not work, the string is just chopped off in the middle of a word
20760 if necessary."
20761 (if (<= (length s) maxlength)
20763 (let* ((n (max (- maxlength 4) 1))
20764 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20765 (if (string-match re s)
20766 (concat (match-string 1 s) "...")
20767 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20769 (defun org-get-indentation (&optional line)
20770 "Get the indentation of the current line, interpreting tabs.
20771 When LINE is given, assume it represents a line and compute its indentation."
20772 (if line
20773 (if (string-match "^ *" (org-remove-tabs line))
20774 (match-end 0))
20775 (save-excursion
20776 (beginning-of-line 1)
20777 (skip-chars-forward " \t")
20778 (current-column))))
20780 (defun org-get-string-indentation (s)
20781 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20782 (let ((n -1) (i 0) (w tab-width) c)
20783 (catch 'exit
20784 (while (< (setq n (1+ n)) (length s))
20785 (setq c (aref s n))
20786 (cond ((= c ?\ ) (setq i (1+ i)))
20787 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20788 (t (throw 'exit t)))))
20791 (defun org-remove-tabs (s &optional width)
20792 "Replace tabulators in S with spaces.
20793 Assumes that s is a single line, starting in column 0."
20794 (setq width (or width tab-width))
20795 (while (string-match "\t" s)
20796 (setq s (replace-match
20797 (make-string
20798 (- (* width (/ (+ (match-beginning 0) width) width))
20799 (match-beginning 0)) ?\ )
20800 t t s)))
20803 (defun org-fix-indentation (line ind)
20804 "Fix indentation in LINE.
20805 IND is a cons cell with target and minimum indentation.
20806 If the current indentation in LINE is smaller than the minimum,
20807 leave it alone. If it is larger than ind, set it to the target."
20808 (let* ((l (org-remove-tabs line))
20809 (i (org-get-indentation l))
20810 (i1 (car ind)) (i2 (cdr ind)))
20811 (if (>= i i2) (setq l (substring line i2)))
20812 (if (> i1 0)
20813 (concat (make-string i1 ?\ ) l)
20814 l)))
20816 (defun org-remove-indentation (code &optional n)
20817 "Remove the maximum common indentation from the lines in CODE.
20818 N may optionally be the number of spaces to remove."
20819 (with-temp-buffer
20820 (insert code)
20821 (org-do-remove-indentation n)
20822 (buffer-string)))
20824 (defun org-do-remove-indentation (&optional n)
20825 "Remove the maximum common indentation from the buffer."
20826 (untabify (point-min) (point-max))
20827 (let ((min 10000) re)
20828 (if n
20829 (setq min n)
20830 (goto-char (point-min))
20831 (while (re-search-forward "^ *[^ \n]" nil t)
20832 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20833 (unless (or (= min 0) (= min 10000))
20834 (setq re (format "^ \\{%d\\}" min))
20835 (goto-char (point-min))
20836 (while (re-search-forward re nil t)
20837 (replace-match "")
20838 (end-of-line 1))
20839 min)))
20841 (defun org-fill-template (template alist)
20842 "Find each %key of ALIST in TEMPLATE and replace it."
20843 (let ((case-fold-search nil)
20844 entry key value)
20845 (setq alist (sort (copy-sequence alist)
20846 (lambda (a b) (< (length (car a)) (length (car b))))))
20847 (while (setq entry (pop alist))
20848 (setq template
20849 (replace-regexp-in-string
20850 (concat "%" (regexp-quote (car entry)))
20851 (or (cdr entry) "") template t t)))
20852 template))
20854 (defun org-base-buffer (buffer)
20855 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20856 (if (not buffer)
20857 buffer
20858 (or (buffer-base-buffer buffer)
20859 buffer)))
20861 (defun org-trim (s)
20862 "Remove whitespace at beginning and end of string."
20863 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20864 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20867 (defun org-wrap (string &optional width lines)
20868 "Wrap string to either a number of lines, or a width in characters.
20869 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20870 that costs. If there is a word longer than WIDTH, the text is actually
20871 wrapped to the length of that word.
20872 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20873 many lines, whatever width that takes.
20874 The return value is a list of lines, without newlines at the end."
20875 (let* ((words (org-split-string string "[ \t\n]+"))
20876 (maxword (apply 'max (mapcar 'org-string-width words)))
20877 w ll)
20878 (cond (width
20879 (org-do-wrap words (max maxword width)))
20880 (lines
20881 (setq w maxword)
20882 (setq ll (org-do-wrap words maxword))
20883 (if (<= (length ll) lines)
20885 (setq ll words)
20886 (while (> (length ll) lines)
20887 (setq w (1+ w))
20888 (setq ll (org-do-wrap words w)))
20889 ll))
20890 (t (error "Cannot wrap this")))))
20892 (defun org-do-wrap (words width)
20893 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20894 (let (lines line)
20895 (while words
20896 (setq line (pop words))
20897 (while (and words (< (+ (length line) (length (car words))) width))
20898 (setq line (concat line " " (pop words))))
20899 (setq lines (push line lines)))
20900 (nreverse lines)))
20902 (defun org-split-string (string &optional separators)
20903 "Splits STRING into substrings at SEPARATORS.
20904 No empty strings are returned if there are matches at the beginning
20905 and end of string."
20906 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20907 (start 0)
20908 notfirst
20909 (list nil))
20910 (while (and (string-match rexp string
20911 (if (and notfirst
20912 (= start (match-beginning 0))
20913 (< start (length string)))
20914 (1+ start) start))
20915 (< (match-beginning 0) (length string)))
20916 (setq notfirst t)
20917 (or (eq (match-beginning 0) 0)
20918 (and (eq (match-beginning 0) (match-end 0))
20919 (eq (match-beginning 0) start))
20920 (setq list
20921 (cons (substring string start (match-beginning 0))
20922 list)))
20923 (setq start (match-end 0)))
20924 (or (eq start (length string))
20925 (setq list
20926 (cons (substring string start)
20927 list)))
20928 (nreverse list)))
20930 (defun org-quote-vert (s)
20931 "Replace \"|\" with \"\\vert\"."
20932 (while (string-match "|" s)
20933 (setq s (replace-match "\\vert" t t s)))
20936 (defun org-uuidgen-p (s)
20937 "Is S an ID created by UUIDGEN?"
20938 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20940 (defun org-in-src-block-p (&optional inside)
20941 "Whether point is in a code source block.
20942 When INSIDE is non-nil, don't consider we are within a src block
20943 when point is at #+BEGIN_SRC or #+END_SRC."
20944 (let ((case-fold-search t) ov)
20945 (or (and (setq ov (overlays-at (point)))
20946 (memq 'org-block-background
20947 (overlay-properties (car ov))))
20948 (and (not inside)
20949 (save-match-data
20950 (save-excursion
20951 (beginning-of-line)
20952 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20954 (defun org-context ()
20955 "Return a list of contexts of the current cursor position.
20956 If several contexts apply, all are returned.
20957 Each context entry is a list with a symbol naming the context, and
20958 two positions indicating start and end of the context. Possible
20959 contexts are:
20961 :headline anywhere in a headline
20962 :headline-stars on the leading stars in a headline
20963 :todo-keyword on a TODO keyword (including DONE) in a headline
20964 :tags on the TAGS in a headline
20965 :priority on the priority cookie in a headline
20966 :item on the first line of a plain list item
20967 :item-bullet on the bullet/number of a plain list item
20968 :checkbox on the checkbox in a plain list item
20969 :table in an org-mode table
20970 :table-special on a special filed in a table
20971 :table-table in a table.el table
20972 :clocktable in a clocktable
20973 :src-block in a source block
20974 :link on a hyperlink
20975 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20976 :target on a <<target>>
20977 :radio-target on a <<<radio-target>>>
20978 :latex-fragment on a LaTeX fragment
20979 :latex-preview on a LaTeX fragment with overlaid preview image
20981 This function expects the position to be visible because it uses font-lock
20982 faces as a help to recognize the following contexts: :table-special, :link,
20983 and :keyword."
20984 (let* ((f (get-text-property (point) 'face))
20985 (faces (if (listp f) f (list f)))
20986 (case-fold-search t)
20987 (p (point)) clist o)
20988 ;; First the large context
20989 (cond
20990 ((org-at-heading-p t)
20991 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20992 (when (progn
20993 (beginning-of-line 1)
20994 (looking-at org-todo-line-tags-regexp))
20995 (push (org-point-in-group p 1 :headline-stars) clist)
20996 (push (org-point-in-group p 2 :todo-keyword) clist)
20997 (push (org-point-in-group p 4 :tags) clist))
20998 (goto-char p)
20999 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21000 (if (looking-at "\\[#[A-Z0-9]\\]")
21001 (push (org-point-in-group p 0 :priority) clist)))
21003 ((org-at-item-p)
21004 (push (org-point-in-group p 2 :item-bullet) clist)
21005 (push (list :item (point-at-bol)
21006 (save-excursion (org-end-of-item) (point)))
21007 clist)
21008 (and (org-at-item-checkbox-p)
21009 (push (org-point-in-group p 0 :checkbox) clist)))
21011 ((org-at-table-p)
21012 (push (list :table (org-table-begin) (org-table-end)) clist)
21013 (if (memq 'org-formula faces)
21014 (push (list :table-special
21015 (previous-single-property-change p 'face)
21016 (next-single-property-change p 'face)) clist)))
21017 ((org-at-table-p 'any)
21018 (push (list :table-table) clist)))
21019 (goto-char p)
21021 (let ((case-fold-search t))
21022 ;; New the "medium" contexts: clocktables, source blocks
21023 (cond ((org-in-clocktable-p)
21024 (push (list :clocktable
21025 (and (or (looking-at "#\\+BEGIN: clocktable")
21026 (search-backward "#+BEGIN: clocktable" nil t))
21027 (match-beginning 0))
21028 (and (re-search-forward "#\\+END:?" nil t)
21029 (match-end 0))) clist))
21030 ((org-in-src-block-p)
21031 (push (list :src-block
21032 (and (or (looking-at "#\\+BEGIN_SRC")
21033 (search-backward "#+BEGIN_SRC" nil t))
21034 (match-beginning 0))
21035 (and (search-forward "#+END_SRC" nil t)
21036 (match-beginning 0))) clist))))
21037 (goto-char p)
21039 ;; Now the small context
21040 (cond
21041 ((org-at-timestamp-p)
21042 (push (org-point-in-group p 0 :timestamp) clist))
21043 ((memq 'org-link faces)
21044 (push (list :link
21045 (previous-single-property-change p 'face)
21046 (next-single-property-change p 'face)) clist))
21047 ((memq 'org-special-keyword faces)
21048 (push (list :keyword
21049 (previous-single-property-change p 'face)
21050 (next-single-property-change p 'face)) clist))
21051 ((org-at-target-p)
21052 (push (org-point-in-group p 0 :target) clist)
21053 (goto-char (1- (match-beginning 0)))
21054 (if (looking-at org-radio-target-regexp)
21055 (push (org-point-in-group p 0 :radio-target) clist))
21056 (goto-char p))
21057 ((setq o (car (delq nil
21058 (mapcar
21059 (lambda (x)
21060 (if (memq x org-latex-fragment-image-overlays) x))
21061 (overlays-at (point))))))
21062 (push (list :latex-fragment
21063 (overlay-start o) (overlay-end o)) clist)
21064 (push (list :latex-preview
21065 (overlay-start o) (overlay-end o)) clist))
21066 ((org-inside-LaTeX-fragment-p)
21067 ;; FIXME: positions wrong.
21068 (push (list :latex-fragment (point) (point)) clist)))
21070 (setq clist (nreverse (delq nil clist)))
21071 clist))
21073 ;; FIXME: Compare with at-regexp-p Do we need both?
21074 (defun org-in-regexp (re &optional nlines visually)
21075 "Check if point is inside a match of regexp.
21076 Normally only the current line is checked, but you can include NLINES extra
21077 lines both before and after point into the search.
21078 If VISUALLY is set, require that the cursor is not after the match but
21079 really on, so that the block visually is on the match."
21080 (catch 'exit
21081 (let ((pos (point))
21082 (eol (point-at-eol (+ 1 (or nlines 0))))
21083 (inc (if visually 1 0)))
21084 (save-excursion
21085 (beginning-of-line (- 1 (or nlines 0)))
21086 (while (re-search-forward re eol t)
21087 (if (and (<= (match-beginning 0) pos)
21088 (>= (+ inc (match-end 0)) pos))
21089 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21091 (defun org-at-regexp-p (regexp)
21092 "Is point inside a match of REGEXP in the current line?"
21093 (catch 'exit
21094 (save-excursion
21095 (let ((pos (point)) (end (point-at-eol)))
21096 (beginning-of-line 1)
21097 (while (re-search-forward regexp end t)
21098 (if (and (<= (match-beginning 0) pos)
21099 (>= (match-end 0) pos))
21100 (throw 'exit t)))
21101 nil))))
21103 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21104 "Non-nil when point is between matches of START-RE and END-RE.
21106 Also return a non-nil value when point is on one of the matches.
21108 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21109 buffer positions. Default values are the positions of headlines
21110 surrounding the point.
21112 The functions returns a cons cell whose car (resp. cdr) is the
21113 position before START-RE (resp. after END-RE)."
21114 (save-match-data
21115 (let ((pos (point))
21116 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21117 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21118 beg end)
21119 (save-excursion
21120 ;; Point is on a block when on START-RE or if START-RE can be
21121 ;; found before it...
21122 (and (or (org-at-regexp-p start-re)
21123 (re-search-backward start-re limit-up t))
21124 (setq beg (match-beginning 0))
21125 ;; ... and END-RE after it...
21126 (goto-char (match-end 0))
21127 (re-search-forward end-re limit-down t)
21128 (> (setq end (match-end 0)) pos)
21129 ;; ... without another START-RE in-between.
21130 (goto-char (match-beginning 0))
21131 (not (re-search-backward start-re (1+ beg) t))
21132 ;; Return value.
21133 (cons beg end))))))
21135 (defun org-in-block-p (names)
21136 "Non-nil when point belongs to a block whose name belongs to NAMES.
21138 NAMES is a list of strings containing names of blocks.
21140 Return first block name matched, or nil. Beware that in case of
21141 nested blocks, the returned name may not belong to the closest
21142 block from point."
21143 (save-match-data
21144 (catch 'exit
21145 (let ((case-fold-search t)
21146 (lim-up (save-excursion (outline-previous-heading)))
21147 (lim-down (save-excursion (outline-next-heading))))
21148 (mapc (lambda (name)
21149 (let ((n (regexp-quote name)))
21150 (when (org-between-regexps-p
21151 (concat "^[ \t]*#\\+begin_" n)
21152 (concat "^[ \t]*#\\+end_" n)
21153 lim-up lim-down)
21154 (throw 'exit n))))
21155 names))
21156 nil)))
21158 (defun org-occur-in-agenda-files (regexp &optional nlines)
21159 "Call `multi-occur' with buffers for all agenda files."
21160 (interactive "sOrg-files matching: \np")
21161 (let* ((files (org-agenda-files))
21162 (tnames (mapcar 'file-truename files))
21163 (extra org-agenda-text-search-extra-files)
21165 (when (eq (car extra) 'agenda-archives)
21166 (setq extra (cdr extra))
21167 (setq files (org-add-archive-files files)))
21168 (while (setq f (pop extra))
21169 (unless (member (file-truename f) tnames)
21170 (add-to-list 'files f 'append)
21171 (add-to-list 'tnames (file-truename f) 'append)))
21172 (multi-occur
21173 (mapcar (lambda (x)
21174 (with-current-buffer
21175 (or (get-file-buffer x) (find-file-noselect x))
21176 (widen)
21177 (current-buffer)))
21178 files)
21179 regexp)))
21181 (if (boundp 'occur-mode-find-occurrence-hook)
21182 ;; Emacs 23
21183 (add-hook 'occur-mode-find-occurrence-hook
21184 (lambda ()
21185 (when (derived-mode-p 'org-mode)
21186 (org-reveal))))
21187 ;; Emacs 22
21188 (defadvice occur-mode-goto-occurrence
21189 (after org-occur-reveal activate)
21190 (and (derived-mode-p 'org-mode) (org-reveal)))
21191 (defadvice occur-mode-goto-occurrence-other-window
21192 (after org-occur-reveal activate)
21193 (and (derived-mode-p 'org-mode) (org-reveal)))
21194 (defadvice occur-mode-display-occurrence
21195 (after org-occur-reveal activate)
21196 (when (derived-mode-p 'org-mode)
21197 (let ((pos (occur-mode-find-occurrence)))
21198 (with-current-buffer (marker-buffer pos)
21199 (save-excursion
21200 (goto-char pos)
21201 (org-reveal)))))))
21203 (defun org-occur-link-in-agenda-files ()
21204 "Create a link and search for it in the agendas.
21205 The link is not stored in `org-stored-links', it is just created
21206 for the search purpose."
21207 (interactive)
21208 (let ((link (condition-case nil
21209 (org-store-link nil)
21210 (error "Unable to create a link to here"))))
21211 (org-occur-in-agenda-files (regexp-quote link))))
21213 (defun org-reverse-string (string)
21214 "Return the reverse of STRING."
21215 (apply 'string (reverse (string-to-list string))))
21217 (defun org-uniquify (list)
21218 "Remove duplicate elements from LIST."
21219 (let (res)
21220 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21221 res))
21223 (defun org-delete-all (elts list)
21224 "Remove all elements in ELTS from LIST."
21225 (while elts
21226 (setq list (delete (pop elts) list)))
21227 list)
21229 (defun org-count (cl-item cl-seq)
21230 "Count the number of occurrences of ITEM in SEQ.
21231 Taken from `count' in cl-seq.el with all keyword arguments removed."
21232 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21233 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21234 (while (< cl-start cl-end)
21235 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21236 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21237 (setq cl-start (1+ cl-start)))
21238 cl-count))
21240 (defun org-remove-if (predicate seq)
21241 "Remove everything from SEQ that fulfills PREDICATE."
21242 (let (res e)
21243 (while seq
21244 (setq e (pop seq))
21245 (if (not (funcall predicate e)) (push e res)))
21246 (nreverse res)))
21248 (defun org-remove-if-not (predicate seq)
21249 "Remove everything from SEQ that does not fulfill PREDICATE."
21250 (let (res e)
21251 (while seq
21252 (setq e (pop seq))
21253 (if (funcall predicate e) (push e res)))
21254 (nreverse res)))
21256 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21257 "Reduce two-argument FUNCTION across SEQ.
21258 Taken from `reduce' in cl-seq.el with all keyword arguments but
21259 \":initial-value\" removed."
21260 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21261 (cadr (memq :initial-value cl-keys)))
21262 (cl-seq (pop cl-seq))
21263 (t (funcall cl-func)))))
21264 (while cl-seq
21265 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21266 cl-accum))
21268 (defun org-back-over-empty-lines ()
21269 "Move backwards over whitespace, to the beginning of the first empty line.
21270 Returns the number of empty lines passed."
21271 (let ((pos (point)))
21272 (if (cdr (assoc 'heading org-blank-before-new-entry))
21273 (skip-chars-backward " \t\n\r")
21274 (unless (eobp)
21275 (forward-line -1)))
21276 (beginning-of-line 2)
21277 (goto-char (min (point) pos))
21278 (count-lines (point) pos)))
21280 (defun org-skip-whitespace ()
21281 (skip-chars-forward " \t\n\r"))
21283 (defun org-point-in-group (point group &optional context)
21284 "Check if POINT is in match-group GROUP.
21285 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21286 match. If the match group does not exist or point is not inside it,
21287 return nil."
21288 (and (match-beginning group)
21289 (>= point (match-beginning group))
21290 (<= point (match-end group))
21291 (if context
21292 (list context (match-beginning group) (match-end group))
21293 t)))
21295 (defun org-switch-to-buffer-other-window (&rest args)
21296 "Switch to buffer in a second window on the current frame.
21297 In particular, do not allow pop-up frames.
21298 Returns the newly created buffer."
21299 (org-no-popups
21300 (apply 'switch-to-buffer-other-window args)))
21302 (defun org-combine-plists (&rest plists)
21303 "Create a single property list from all plists in PLISTS.
21304 The process starts by copying the first list, and then setting properties
21305 from the other lists. Settings in the last list are the most significant
21306 ones and overrule settings in the other lists."
21307 (let ((rtn (copy-sequence (pop plists)))
21308 p v ls)
21309 (while plists
21310 (setq ls (pop plists))
21311 (while ls
21312 (setq p (pop ls) v (pop ls))
21313 (setq rtn (plist-put rtn p v))))
21314 rtn))
21316 (defun org-replace-escapes (string table)
21317 "Replace %-escapes in STRING with values in TABLE.
21318 TABLE is an association list with keys like \"%a\" and string values.
21319 The sequences in STRING may contain normal field width and padding information,
21320 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21321 so values can contain further %-escapes if they are define later in TABLE."
21322 (let ((tbl (copy-alist table))
21323 (case-fold-search nil)
21324 (pchg 0)
21325 e re rpl)
21326 (while (setq e (pop tbl))
21327 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21328 (when (and (cdr e) (string-match re (cdr e)))
21329 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21330 (safe "SREF"))
21331 (add-text-properties 0 3 (list 'sref sref) safe)
21332 (setcdr e (replace-match safe t t (cdr e)))))
21333 (while (string-match re string)
21334 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21335 (cdr e)))
21336 (setq string (replace-match rpl t t string))))
21337 (while (setq pchg (next-property-change pchg string))
21338 (let ((sref (get-text-property pchg 'sref string)))
21339 (when (and sref (string-match "SREF" string pchg))
21340 (setq string (replace-match sref t t string)))))
21341 string))
21343 (defun org-sublist (list start end)
21344 "Return a section of LIST, from START to END.
21345 Counting starts at 1."
21346 (let (rtn (c start))
21347 (setq list (nthcdr (1- start) list))
21348 (while (and list (<= c end))
21349 (push (pop list) rtn)
21350 (setq c (1+ c)))
21351 (nreverse rtn)))
21353 (defun org-find-base-buffer-visiting (file)
21354 "Like `find-buffer-visiting' but always return the base buffer and
21355 not an indirect buffer."
21356 (let ((buf (or (get-file-buffer file)
21357 (find-buffer-visiting file))))
21358 (if buf
21359 (or (buffer-base-buffer buf) buf)
21360 nil)))
21362 (defun org-image-file-name-regexp (&optional extensions)
21363 "Return regexp matching the file names of images.
21364 If EXTENSIONS is given, only match these."
21365 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21366 (image-file-name-regexp)
21367 (let ((image-file-name-extensions
21368 (or extensions
21369 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21370 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21371 (concat "\\."
21372 (regexp-opt (nconc (mapcar 'upcase
21373 image-file-name-extensions)
21374 image-file-name-extensions)
21376 "\\'"))))
21378 (defun org-file-image-p (file &optional extensions)
21379 "Return non-nil if FILE is an image."
21380 (save-match-data
21381 (string-match (org-image-file-name-regexp extensions) file)))
21383 (defun org-get-cursor-date (&optional with-time)
21384 "Return the date at cursor in as a time.
21385 This works in the calendar and in the agenda, anywhere else it just
21386 returns the current time.
21387 If WITH-TIME is non-nil, returns the time of the event at point (in
21388 the agenda) or the current time of the day."
21389 (let (date day defd tp tm hod mod)
21390 (when with-time
21391 (setq tp (get-text-property (point) 'time))
21392 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21393 (setq hod (string-to-number (match-string 1 tp))
21394 mod (string-to-number (match-string 2 tp))))
21395 (or tp (setq hod (nth 2 (decode-time (current-time)))
21396 mod (nth 1 (decode-time (current-time))))))
21397 (cond
21398 ((eq major-mode 'calendar-mode)
21399 (setq date (calendar-cursor-to-date)
21400 defd (encode-time 0 (or mod 0) (or hod 0)
21401 (nth 1 date) (nth 0 date) (nth 2 date))))
21402 ((eq major-mode 'org-agenda-mode)
21403 (setq day (get-text-property (point) 'day))
21404 (if day
21405 (setq date (calendar-gregorian-from-absolute day)
21406 defd (encode-time 0 (or mod 0) (or hod 0)
21407 (nth 1 date) (nth 0 date) (nth 2 date))))))
21408 (or defd (current-time))))
21410 (defun org-mark-subtree (&optional up)
21411 "Mark the current subtree.
21412 This puts point at the start of the current subtree, and mark at
21413 the end. If a numeric prefix UP is given, move up into the
21414 hierarchy of headlines by UP levels before marking the subtree."
21415 (interactive "P")
21416 (org-with-limited-levels
21417 (cond ((org-at-heading-p) (beginning-of-line))
21418 ((org-before-first-heading-p) (error "Not in a subtree"))
21419 (t (outline-previous-visible-heading 1))))
21420 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21421 (if (org-called-interactively-p 'any)
21422 (call-interactively 'org-mark-element)
21423 (org-mark-element)))
21426 ;;; Indentation
21428 (defun org-indent-line ()
21429 "Indent line depending on context."
21430 (interactive)
21431 (let* ((pos (point))
21432 (itemp (org-at-item-p))
21433 (case-fold-search t)
21434 (org-drawer-regexp (or org-drawer-regexp "\000"))
21435 (inline-task-p (and (featurep 'org-inlinetask)
21436 (org-inlinetask-in-task-p)))
21437 (inline-re (and inline-task-p
21438 (org-inlinetask-outline-regexp)))
21439 column)
21440 (if (and orgstruct-is-++ (eq pos (point)))
21441 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21442 (indent-according-to-mode))
21443 (beginning-of-line 1)
21444 (cond
21445 ;; Headings
21446 ((looking-at org-outline-regexp) (setq column 0))
21447 ;; Footnote definition
21448 ((looking-at org-footnote-definition-re) (setq column 0))
21449 ;; Literal examples
21450 ((looking-at "[ \t]*:\\( \\|$\\)")
21451 (setq column (org-get-indentation))) ; do nothing
21452 ;; Lists
21453 ((ignore-errors (goto-char (org-in-item-p)))
21454 (setq column (if itemp
21455 (org-get-indentation)
21456 (org-list-item-body-column (point))))
21457 (goto-char pos))
21458 ;; Drawers
21459 ((and (looking-at "[ \t]*:END:")
21460 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21461 (save-excursion
21462 (goto-char (1- (match-beginning 1)))
21463 (setq column (current-column))))
21464 ;; Special blocks
21465 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21466 (save-excursion
21467 (re-search-backward
21468 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21469 (setq column (org-get-indentation (match-string 0))))
21470 ((and (not (looking-at "[ \t]*#\\+begin_"))
21471 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21472 (save-excursion
21473 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21474 (setq column
21475 (cond ((equal (downcase (match-string 1)) "src")
21476 ;; src blocks: let `org-edit-src-exit' handle them
21477 (org-get-indentation))
21478 ((equal (downcase (match-string 1)) "example")
21479 (max (org-get-indentation)
21480 (org-get-indentation (match-string 0))))
21482 (org-get-indentation (match-string 0))))))
21483 ;; This line has nothing special, look at the previous relevant
21484 ;; line to compute indentation
21486 (beginning-of-line 0)
21487 (while (and (not (bobp))
21488 (not (looking-at org-table-line-regexp))
21489 (not (looking-at org-drawer-regexp))
21490 ;; When point started in an inline task, do not move
21491 ;; above task starting line.
21492 (not (and inline-task-p (looking-at inline-re)))
21493 ;; Skip drawers, blocks, empty lines, verbatim,
21494 ;; comments, tables, footnotes definitions, lists,
21495 ;; inline tasks.
21496 (or (and (looking-at "[ \t]*:END:")
21497 (re-search-backward org-drawer-regexp nil t))
21498 (and (looking-at "[ \t]*#\\+end_")
21499 (re-search-backward "[ \t]*#\\+begin_"nil t))
21500 (looking-at "[ \t]*[\n:#|]")
21501 (looking-at org-footnote-definition-re)
21502 (and (ignore-errors (goto-char (org-in-item-p)))
21503 (goto-char
21504 (org-list-get-top-point (org-list-struct))))
21505 (and (not inline-task-p)
21506 (featurep 'org-inlinetask)
21507 (org-inlinetask-in-task-p)
21508 (or (org-inlinetask-goto-beginning) t))))
21509 (beginning-of-line 0))
21510 (cond
21511 ;; There was an heading above.
21512 ((looking-at "\\*+[ \t]+")
21513 (if (not org-adapt-indentation)
21514 (setq column 0)
21515 (goto-char (match-end 0))
21516 (setq column (current-column))))
21517 ;; A drawer had started and is unfinished
21518 ((looking-at org-drawer-regexp)
21519 (goto-char (1- (match-beginning 1)))
21520 (setq column (current-column)))
21521 ;; Else, nothing noticeable found: get indentation and go on.
21522 (t (setq column (org-get-indentation))))))
21523 ;; Now apply indentation and move cursor accordingly
21524 (goto-char pos)
21525 (if (<= (current-column) (current-indentation))
21526 (org-indent-line-to column)
21527 (save-excursion (org-indent-line-to column)))
21528 ;; Special polishing for properties, see `org-property-format'
21529 (setq column (current-column))
21530 (beginning-of-line 1)
21531 (if (looking-at
21532 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21533 (replace-match (concat (match-string 1)
21534 (format org-property-format
21535 (match-string 2) (match-string 3)))
21536 t t))
21537 (org-move-to-column column))))
21539 (defun org-indent-drawer ()
21540 "Indent the drawer at point."
21541 (interactive)
21542 (let ((p (point))
21543 (e (and (save-excursion (re-search-forward ":END:" nil t))
21544 (match-end 0)))
21545 (folded
21546 (save-excursion
21547 (end-of-line)
21548 (when (overlays-at (point))
21549 (member 'invisible (overlay-properties
21550 (car (overlays-at (point)))))))))
21551 (when folded (org-cycle))
21552 (indent-for-tab-command)
21553 (while (and (move-beginning-of-line 2) (< (point) e))
21554 (indent-for-tab-command))
21555 (goto-char p)
21556 (when folded (org-cycle)))
21557 (message "Drawer at point indented"))
21559 (defun org-indent-block ()
21560 "Indent the block at point."
21561 (interactive)
21562 (let ((p (point))
21563 (case-fold-search t)
21564 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21565 (match-end 0)))
21566 (folded
21567 (save-excursion
21568 (end-of-line)
21569 (when (overlays-at (point))
21570 (member 'invisible (overlay-properties
21571 (car (overlays-at (point)))))))))
21572 (when folded (org-cycle))
21573 (indent-for-tab-command)
21574 (while (and (move-beginning-of-line 2) (< (point) e))
21575 (indent-for-tab-command))
21576 (goto-char p)
21577 (when folded (org-cycle)))
21578 (message "Block at point indented"))
21580 (defun org-indent-region (start end)
21581 "Indent region."
21582 (interactive "r")
21583 (save-excursion
21584 (let ((line-end (org-current-line end)))
21585 (goto-char start)
21586 (while (< (org-current-line) line-end)
21587 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21588 (t (call-interactively 'org-indent-line)))
21589 (move-beginning-of-line 2)))))
21592 ;;; Filling
21594 ;; We use our own fill-paragraph and auto-fill functions.
21596 ;; `org-fill-paragraph' relies on adaptive filling and context
21597 ;; checking. Appropriate `fill-prefix' is computed with
21598 ;; `org-adaptive-fill-function'.
21600 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21601 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21602 ;; `org-adaptive-fill-function' value. Internally,
21603 ;; `org-comment-line-break-function' breaks the line.
21605 ;; `org-setup-filling' installs filling and auto-filling related
21606 ;; variables during `org-mode' initialization.
21608 (defun org-setup-filling ()
21609 (interactive)
21610 ;; Prevent auto-fill from inserting unwanted new items.
21611 (when (boundp 'fill-nobreak-predicate)
21612 (org-set-local
21613 'fill-nobreak-predicate
21614 (org-uniquify
21615 (append fill-nobreak-predicate
21616 '(org-fill-paragraph-separate-nobreak-p
21617 org-fill-line-break-nobreak-p
21618 org-fill-paragraph-with-timestamp-nobreak-p)))))
21619 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21620 (org-set-local 'auto-fill-inhibit-regexp nil)
21621 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21622 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21623 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21625 (defvar org-element-paragraph-separate) ; org-element.el
21626 (defun org-fill-paragraph-separate-nobreak-p ()
21627 "Non-nil when a line break at point would insert a new item."
21628 (looking-at (substring org-element-paragraph-separate 1)))
21630 (defun org-fill-line-break-nobreak-p ()
21631 "Non-nil when a line break at point would create an Org line break."
21632 (save-excursion
21633 (skip-chars-backward "[ \t]")
21634 (skip-chars-backward "\\\\")
21635 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21637 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21638 "Non-nil when a line break at point would insert a new item."
21639 (and (org-at-timestamp-p t)
21640 (not (looking-at org-ts-regexp-both))))
21642 (declare-function message-in-body-p "message" ())
21643 (defvar orgtbl-line-start-regexp) ; From org-table.el
21644 (defun org-adaptive-fill-function ()
21645 "Compute a fill prefix for the current line.
21646 Return fill prefix, as a string, or nil if current line isn't
21647 meant to be filled."
21648 (let (prefix)
21649 (catch 'exit
21650 (when (derived-mode-p 'message-mode)
21651 (save-excursion
21652 (beginning-of-line)
21653 (cond ((or (not (message-in-body-p))
21654 (looking-at orgtbl-line-start-regexp))
21655 (throw 'exit nil))
21656 ((looking-at message-cite-prefix-regexp)
21657 (throw 'exit (match-string-no-properties 0)))
21658 ((looking-at org-outline-regexp)
21659 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21660 (org-with-wide-buffer
21661 (let* ((p (line-beginning-position))
21662 (element (save-excursion (beginning-of-line)
21663 (org-element-at-point)))
21664 (type (org-element-type element))
21665 (post-affiliated (org-element-property :post-affiliated element)))
21666 (unless (and post-affiliated (< p post-affiliated))
21667 (case type
21668 (comment (looking-at "[ \t]*# ?") (match-string 0))
21669 (footnote-definition "")
21670 ((item plain-list)
21671 (make-string (org-list-item-body-column
21672 (or post-affiliated
21673 (org-element-property :begin element)))
21674 ? ))
21675 (paragraph
21676 ;; Fill prefix is usually the same as the current line,
21677 ;; except if the paragraph is at the beginning of an item.
21678 (let ((parent (org-element-property :parent element)))
21679 (cond ((eq (org-element-type parent) 'item)
21680 (make-string (org-list-item-body-column
21681 (org-element-property :begin parent))
21682 ? ))
21683 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21684 (match-string 0))
21685 (t ""))))
21686 (comment-block
21687 ;; Only fill contents if P is within block boundaries.
21688 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21689 (forward-line)
21690 (point)))
21691 (cend (save-excursion
21692 (goto-char (org-element-property :end element))
21693 (skip-chars-backward " \r\t\n")
21694 (line-beginning-position))))
21695 (when (and (>= p cbeg) (< p cend))
21696 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21697 (match-string 0)
21698 "")))))))))))
21700 (declare-function message-goto-body "message" ())
21701 (defvar message-cite-prefix-regexp) ; From message.el
21702 (defvar org-element-all-objects) ; From org-element.el
21703 (defun org-fill-paragraph (&optional justify)
21704 "Fill element at point, when applicable.
21706 This function only applies to comment blocks, comments, example
21707 blocks and paragraphs. Also, as a special case, re-align table
21708 when point is at one.
21710 If JUSTIFY is non-nil (interactively, with prefix argument),
21711 justify as well. If `sentence-end-double-space' is non-nil, then
21712 period followed by one space does not end a sentence, so don't
21713 break a line there. The variable `fill-column' controls the
21714 width for filling.
21716 For convenience, when point is at a plain list, an item or
21717 a footnote definition, try to fill the first paragraph within."
21718 (interactive)
21719 (if (and (derived-mode-p 'message-mode)
21720 (or (not (message-in-body-p))
21721 (save-excursion (move-beginning-of-line 1)
21722 (looking-at message-cite-prefix-regexp))))
21723 ;; First ensure filling is correct in message-mode.
21724 (let ((fill-paragraph-function
21725 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21726 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21727 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21728 (paragraph-separate
21729 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21730 (fill-paragraph nil))
21731 (save-excursion
21732 ;; Move to end of line in order to get the first paragraph
21733 ;; within a plain list or a footnote definition.
21734 (end-of-line)
21735 (let ((element (org-element-at-point)))
21736 ;; First check if point is in a blank line at the beginning of
21737 ;; the buffer. In that case, ignore filling.
21738 (if (< (point) (org-element-property :begin element)) t
21739 (case (org-element-type element)
21740 ;; Use major mode filling function is src blocks.
21741 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21742 ;; Align Org tables, leave table.el tables as-is.
21743 (table-row (org-table-align) t)
21744 (table
21745 (when (eq (org-element-property :type element) 'org)
21746 (org-table-align))
21748 (paragraph
21749 ;; Paragraphs may contain `line-break' type objects.
21750 (let ((beg (max (point-min)
21751 (org-element-property :contents-begin element)))
21752 (end (min (point-max)
21753 (org-element-property :contents-end element))))
21754 ;; Do nothing if point is at an affiliated keyword.
21755 (if (< (point) beg) t
21756 (when (derived-mode-p 'message-mode)
21757 ;; In `message-mode', do not fill following
21758 ;; citation in current paragraph nor text before
21759 ;; message body.
21760 (let ((body-start (save-excursion (message-goto-body))))
21761 (when body-start (setq beg (max body-start beg))))
21762 (when (save-excursion
21763 (re-search-forward
21764 (concat "^" message-cite-prefix-regexp) end t))
21765 (setq end (match-beginning 0))))
21766 ;; Fill paragraph, taking line breaks into
21767 ;; consideration. For that, slice the paragraph
21768 ;; using line breaks as separators, and fill the
21769 ;; parts in reverse order to avoid messing with
21770 ;; markers.
21771 (save-excursion
21772 (goto-char end)
21773 (mapc
21774 (lambda (pos)
21775 (fill-region-as-paragraph pos (point) justify)
21776 (goto-char pos))
21777 ;; Find the list of ending positions for line
21778 ;; breaks in the current paragraph. Add paragraph
21779 ;; beginning to include first slice.
21780 (nreverse
21781 (cons
21783 (org-element-map
21784 (org-element--parse-objects
21785 beg end nil org-element-all-objects)
21786 'line-break
21787 (lambda (lb) (org-element-property :end lb)))))))
21788 t)))
21789 ;; Contents of `comment-block' type elements should be
21790 ;; filled as plain text, but only if point is within block
21791 ;; markers.
21792 (comment-block
21793 (let* ((case-fold-search t)
21794 (beg (save-excursion
21795 (goto-char (org-element-property :begin element))
21796 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21797 (forward-line)
21798 (point)))
21799 (end (save-excursion
21800 (goto-char (org-element-property :end element))
21801 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21802 (line-beginning-position))))
21803 (when (and (>= (point) beg) (< (point) end))
21804 (fill-region-as-paragraph
21805 (save-excursion
21806 (end-of-line)
21807 (re-search-backward "^[ \t]*$" beg 'move)
21808 (line-beginning-position))
21809 (save-excursion
21810 (beginning-of-line)
21811 (re-search-forward "^[ \t]*$" end 'move)
21812 (line-beginning-position))
21813 justify)))
21815 ;; Fill comments.
21816 (comment (fill-comment-paragraph justify))
21817 ;; Ignore every other element.
21818 (otherwise t)))))))
21820 (defun org-auto-fill-function ()
21821 "Auto-fill function."
21822 ;; Check if auto-filling is meaningful.
21823 (let ((fc (current-fill-column)))
21824 (when (and fc (> (current-column) fc))
21825 (let* ((fill-prefix (org-adaptive-fill-function))
21826 ;; Enforce empty fill prefix, if required. Otherwise, it
21827 ;; will be computed again.
21828 (adaptive-fill-mode (not (equal fill-prefix ""))))
21829 (when fill-prefix (do-auto-fill))))))
21831 (defun org-comment-line-break-function (&optional soft)
21832 "Break line at point and indent, continuing comment if within one.
21833 The inserted newline is marked hard if variable
21834 `use-hard-newlines' is true, unless optional argument SOFT is
21835 non-nil."
21836 (if soft (insert-and-inherit ?\n) (newline 1))
21837 (save-excursion (forward-char -1) (delete-horizontal-space))
21838 (delete-horizontal-space)
21839 (indent-to-left-margin)
21840 (insert-before-markers-and-inherit fill-prefix))
21843 ;;; Comments
21845 ;; Org comments syntax is quite complex. It requires the entire line
21846 ;; to be just a comment. Also, even with the right syntax at the
21847 ;; beginning of line, some some elements (i.e. verse-block or
21848 ;; example-block) don't accept comments. Usual Emacs comment commands
21849 ;; cannot cope with those requirements. Therefore, Org replaces them.
21851 ;; Org still relies on `comment-dwim', but cannot trust
21852 ;; `comment-only-p'. So, `comment-region-function' and
21853 ;; `uncomment-region-function' both point
21854 ;; to`org-comment-or-uncomment-region'. Eventually,
21855 ;; `org-insert-comment' takes care of insertion of comments at the
21856 ;; beginning of line.
21858 ;; `org-setup-comments-handling' install comments related variables
21859 ;; during `org-mode' initialization.
21861 (defun org-setup-comments-handling ()
21862 (interactive)
21863 (org-set-local 'comment-use-syntax nil)
21864 (org-set-local 'comment-start "# ")
21865 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21866 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21867 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21868 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21870 (defun org-insert-comment ()
21871 "Insert an empty comment above current line.
21872 If the line is empty, insert comment at its beginning."
21873 (beginning-of-line)
21874 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21875 (org-indent-line)
21876 (insert "# "))
21878 (defvar comment-empty-lines) ; From newcomment.el.
21879 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21880 "Comment or uncomment each non-blank line in the region.
21881 Uncomment each non-blank line between BEG and END if it only
21882 contains commented lines. Otherwise, comment them."
21883 (save-restriction
21884 ;; Restrict region
21885 (narrow-to-region (save-excursion (goto-char beg)
21886 (skip-chars-forward " \r\t\n" end)
21887 (line-beginning-position))
21888 (save-excursion (goto-char end)
21889 (skip-chars-backward " \r\t\n" beg)
21890 (line-end-position)))
21891 (let ((uncommentp
21892 ;; UNCOMMENTP is non-nil when every non blank line between
21893 ;; BEG and END is a comment.
21894 (save-excursion
21895 (goto-char (point-min))
21896 (while (and (not (eobp))
21897 (let ((element (org-element-at-point)))
21898 (and (eq (org-element-type element) 'comment)
21899 (goto-char (min (point-max)
21900 (org-element-property
21901 :end element)))))))
21902 (eobp))))
21903 (if uncommentp
21904 ;; Only blank lines and comments in region: uncomment it.
21905 (save-excursion
21906 (goto-char (point-min))
21907 (while (not (eobp))
21908 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21909 (replace-match "" nil nil nil 1))
21910 (forward-line)))
21911 ;; Comment each line in region.
21912 (let ((min-indent (point-max)))
21913 ;; First find the minimum indentation across all lines.
21914 (save-excursion
21915 (goto-char (point-min))
21916 (while (and (not (eobp)) (not (zerop min-indent)))
21917 (unless (looking-at "[ \t]*$")
21918 (setq min-indent (min min-indent (current-indentation))))
21919 (forward-line)))
21920 ;; Then loop over all lines.
21921 (save-excursion
21922 (goto-char (point-min))
21923 (while (not (eobp))
21924 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21925 (org-move-to-column min-indent t)
21926 (insert comment-start))
21927 (forward-line))))))))
21930 ;;; Planning
21932 ;; This section contains tools to operate on timestamp objects, as
21933 ;; returned by, e.g. `org-element-context'.
21935 (defun org-timestamp-has-time-p (timestamp)
21936 "Non-nil when TIMESTAMP has a time specified."
21937 (org-element-property :hour-start timestamp))
21939 (defun org-timestamp-format (timestamp format &optional end utc)
21940 "Format a TIMESTAMP element into a string.
21942 FORMAT is a format specifier to be passed to
21943 `format-time-string'.
21945 When optional argument END is non-nil, use end of date-range or
21946 time-range, if possible.
21948 When optional argument UTC is non-nil, time will be expressed as
21949 Universal Time."
21950 (format-time-string
21951 format
21952 (apply 'encode-time
21953 (cons 0
21954 (mapcar
21955 (lambda (prop) (or (org-element-property prop timestamp) 0))
21956 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21957 '(:minute-start :hour-start :day-start :month-start
21958 :year-start)))))
21959 utc))
21961 (defun org-timestamp-split-range (timestamp &optional end)
21962 "Extract a timestamp object from a date or time range.
21964 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21965 the end of the range. Otherwise, extract its start.
21967 Return a new timestamp object sharing the same parent as
21968 TIMESTAMP."
21969 (let ((type (org-element-property :type timestamp)))
21970 (if (memq type '(active inactive diary)) timestamp
21971 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21972 ;; Set new type.
21973 (org-element-put-property
21974 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21975 ;; Copy start properties over end properties if END is
21976 ;; non-nil. Otherwise, copy end properties over `start' ones.
21977 (let ((p-alist '((:minute-start . :minute-end)
21978 (:hour-start . :hour-end)
21979 (:day-start . :day-end)
21980 (:month-start . :month-end)
21981 (:year-start . :year-end))))
21982 (dolist (p-cell p-alist)
21983 (org-element-put-property
21984 split-ts
21985 (funcall (if end 'car 'cdr) p-cell)
21986 (org-element-property
21987 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21988 ;; Eventually refresh `:raw-value'.
21989 (org-element-put-property split-ts :raw-value nil)
21990 (org-element-put-property
21991 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21993 (defun org-timestamp-translate (timestamp &optional boundary)
21994 "Apply `org-translate-time' on a TIMESTAMP object.
21995 When optional argument BOUNDARY is non-nil, it is either the
21996 symbol `start' or `end'. In this case, only translate the
21997 starting or ending part of TIMESTAMP if it is a date or time
21998 range. Otherwise, translate both parts."
21999 (if (and (not boundary)
22000 (memq (org-element-property :type timestamp)
22001 '(active-range inactive-range)))
22002 (concat
22003 (org-translate-time
22004 (org-element-property :raw-value
22005 (org-timestamp-split-range timestamp)))
22006 "--"
22007 (org-translate-time
22008 (org-element-property :raw-value
22009 (org-timestamp-split-range timestamp t))))
22010 (org-translate-time
22011 (org-element-property
22012 :raw-value
22013 (if (not boundary) timestamp
22014 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22018 ;;; Other stuff.
22020 (defun org-toggle-fixed-width-section (arg)
22021 "Toggle the fixed-width export.
22022 If there is no active region, the QUOTE keyword at the current headline is
22023 inserted or removed. When present, it causes the text between this headline
22024 and the next to be exported as fixed-width text, and unmodified.
22025 If there is an active region, this command adds or removes a colon as the
22026 first character of this line. If the first character of a line is a colon,
22027 this line is also exported in fixed-width font."
22028 (interactive "P")
22029 (let* ((cc 0)
22030 (regionp (org-region-active-p))
22031 (beg (if regionp (region-beginning) (point)))
22032 (end (if regionp (region-end)))
22033 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22034 (case-fold-search nil)
22035 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22036 off)
22037 (if regionp
22038 (save-excursion
22039 (goto-char beg)
22040 (setq cc (current-column))
22041 (beginning-of-line 1)
22042 (setq off (looking-at re))
22043 (while (> nlines 0)
22044 (setq nlines (1- nlines))
22045 (beginning-of-line 1)
22046 (cond
22047 (arg
22048 (org-move-to-column cc t)
22049 (insert ": \n")
22050 (forward-line -1))
22051 ((and off (looking-at re))
22052 (replace-match "" t t nil 1))
22053 ((not off) (org-move-to-column cc t) (insert ": ")))
22054 (forward-line 1)))
22055 (save-excursion
22056 (org-back-to-heading)
22057 (cond
22058 ((looking-at (format org-heading-keyword-regexp-format
22059 org-quote-string))
22060 (goto-char (match-end 1))
22061 (looking-at (concat " +" org-quote-string))
22062 (replace-match "" t t)
22063 (when (eolp) (insert " ")))
22064 ((looking-at org-outline-regexp)
22065 (goto-char (match-end 0))
22066 (insert org-quote-string " ")))))))
22068 (defun org-reftex-citation ()
22069 "Use reftex-citation to insert a citation into the buffer.
22070 This looks for a line like
22072 #+BIBLIOGRAPHY: foo plain option:-d
22074 and derives from it that foo.bib is the bibliography file relevant
22075 for this document. It then installs the necessary environment for RefTeX
22076 to work in this buffer and calls `reftex-citation' to insert a citation
22077 into the buffer.
22079 Export of such citations to both LaTeX and HTML is handled by the contributed
22080 package org-exp-bibtex by Taru Karttunen."
22081 (interactive)
22082 (let ((reftex-docstruct-symbol 'rds)
22083 (reftex-cite-format "\\cite{%l}")
22084 rds bib)
22085 (save-excursion
22086 (save-restriction
22087 (widen)
22088 (let ((case-fold-search t)
22089 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22090 (if (not (save-excursion
22091 (or (re-search-forward re nil t)
22092 (re-search-backward re nil t))))
22093 (error "No bibliography defined in file")
22094 (setq bib (concat (match-string 1) ".bib")
22095 rds (list (list 'bib bib)))))))
22096 (call-interactively 'reftex-citation)))
22098 ;;;; Functions extending outline functionality
22100 (defun org-beginning-of-line (&optional arg)
22101 "Go to the beginning of the current line. If that is invisible, continue
22102 to a visible line beginning. This makes the function of C-a more intuitive.
22103 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22104 first attempt, and only move to after the tags when the cursor is already
22105 beyond the end of the headline."
22106 (interactive "P")
22107 (let ((pos (point))
22108 (special (if (consp org-special-ctrl-a/e)
22109 (car org-special-ctrl-a/e)
22110 org-special-ctrl-a/e))
22111 refpos)
22112 (if (org-bound-and-true-p visual-line-mode)
22113 (beginning-of-visual-line 1)
22114 (beginning-of-line 1))
22115 (if (and arg (fboundp 'move-beginning-of-line))
22116 (call-interactively 'move-beginning-of-line)
22117 (if (bobp)
22119 (backward-char 1)
22120 (if (org-truely-invisible-p)
22121 (while (and (not (bobp)) (org-truely-invisible-p))
22122 (backward-char 1)
22123 (beginning-of-line 1))
22124 (forward-char 1))))
22125 (when special
22126 (cond
22127 ((and (looking-at org-complex-heading-regexp)
22128 (= (char-after (match-end 1)) ?\ ))
22129 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22130 (point-at-eol)))
22131 (goto-char
22132 (if (eq special t)
22133 (cond ((> pos refpos) refpos)
22134 ((= pos (point)) refpos)
22135 (t (point)))
22136 (cond ((> pos (point)) (point))
22137 ((not (eq last-command this-command)) (point))
22138 (t refpos)))))
22139 ((org-at-item-p)
22140 ;; Being at an item and not looking at an the item means point
22141 ;; was previously moved to beginning of a visual line, which
22142 ;; doesn't contain the item. Therefore, do nothing special,
22143 ;; just stay here.
22144 (when (looking-at org-list-full-item-re)
22145 ;; Set special position at first white space character after
22146 ;; bullet, and check-box, if any.
22147 (let ((after-bullet
22148 (let ((box (match-end 3)))
22149 (if (not box) (match-end 1)
22150 (let ((after (char-after box)))
22151 (if (and after (= after ? )) (1+ box) box))))))
22152 ;; Special case: Move point to special position when
22153 ;; currently after it or at beginning of line.
22154 (if (eq special t)
22155 (when (or (> pos after-bullet) (= (point) pos))
22156 (goto-char after-bullet))
22157 ;; Reversed case: Move point to special position when
22158 ;; point was already at beginning of line and command is
22159 ;; repeated.
22160 (when (and (= (point) pos) (eq last-command this-command))
22161 (goto-char after-bullet))))))))
22162 (org-no-warnings
22163 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22165 (defun org-end-of-line (&optional arg)
22166 "Go to the end of the line.
22167 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22168 tags on the first attempt, and only move to after the tags when
22169 the cursor is already beyond the end of the headline."
22170 (interactive "P")
22171 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22172 org-special-ctrl-a/e))
22173 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22174 'end-of-visual-line)
22175 ((fboundp 'move-end-of-line) 'move-end-of-line)
22176 (t 'end-of-line))))
22177 (if (or (not special) arg) (call-interactively move-fun)
22178 (let* ((element (save-excursion (beginning-of-line)
22179 (org-element-at-point)))
22180 (type (org-element-type element)))
22181 (cond
22182 ((memq type '(headline inlinetask))
22183 (let ((pos (point)))
22184 (beginning-of-line 1)
22185 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22186 (if (eq special t)
22187 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22188 (goto-char (match-beginning 1))
22189 (goto-char (match-end 0)))
22190 (if (or (< pos (match-end 0))
22191 (not (eq this-command last-command)))
22192 (goto-char (match-end 0))
22193 (goto-char (match-beginning 1))))
22194 (call-interactively move-fun))))
22195 ((org-element-property :hiddenp element)
22196 ;; If element is hidden, `move-end-of-line' would put point
22197 ;; after it. Use `end-of-line' to stay on current line.
22198 (call-interactively 'end-of-line))
22199 (t (call-interactively move-fun)))))
22200 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22202 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22203 (define-key org-mode-map "\C-e" 'org-end-of-line)
22205 (defun org-backward-sentence (&optional arg)
22206 "Go to beginning of sentence, or beginning of table field.
22207 This will call `backward-sentence' or `org-table-beginning-of-field',
22208 depending on context."
22209 (interactive "P")
22210 (cond
22211 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22212 (t (call-interactively 'backward-sentence))))
22214 (defun org-forward-sentence (&optional arg)
22215 "Go to end of sentence, or end of table field.
22216 This will call `forward-sentence' or `org-table-end-of-field',
22217 depending on context."
22218 (interactive "P")
22219 (cond
22220 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22221 (t (call-interactively 'forward-sentence))))
22223 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22224 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22226 (defun org-kill-line (&optional arg)
22227 "Kill line, to tags or end of line."
22228 (interactive "P")
22229 (cond
22230 ((or (not org-special-ctrl-k)
22231 (bolp)
22232 (not (org-at-heading-p)))
22233 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22234 org-ctrl-k-protect-subtree)
22235 (if (or (eq org-ctrl-k-protect-subtree 'error)
22236 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22237 (error "C-k aborted - would kill hidden subtree")))
22238 (call-interactively
22239 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22240 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22241 (kill-region (point) (match-beginning 1))
22242 (org-set-tags nil t))
22243 (t (kill-region (point) (point-at-eol)))))
22245 (define-key org-mode-map "\C-k" 'org-kill-line)
22247 (defun org-yank (&optional arg)
22248 "Yank. If the kill is a subtree, treat it specially.
22249 This command will look at the current kill and check if is a single
22250 subtree, or a series of subtrees[1]. If it passes the test, and if the
22251 cursor is at the beginning of a line or after the stars of a currently
22252 empty headline, then the yank is handled specially. How exactly depends
22253 on the value of the following variables, both set by default.
22255 org-yank-folded-subtrees
22256 When set, the subtree(s) will be folded after insertion, but only
22257 if doing so would now swallow text after the yanked text.
22259 org-yank-adjusted-subtrees
22260 When set, the subtree will be promoted or demoted in order to
22261 fit into the local outline tree structure, which means that the level
22262 will be adjusted so that it becomes the smaller one of the two
22263 *visible* surrounding headings.
22265 Any prefix to this command will cause `yank' to be called directly with
22266 no special treatment. In particular, a simple \\[universal-argument] prefix \
22267 will just
22268 plainly yank the text as it is.
22270 \[1] The test checks if the first non-white line is a heading
22271 and if there are no other headings with fewer stars."
22272 (interactive "P")
22273 (org-yank-generic 'yank arg))
22275 (defun org-yank-generic (command arg)
22276 "Perform some yank-like command.
22278 This function implements the behavior described in the `org-yank'
22279 documentation. However, it has been generalized to work for any
22280 interactive command with similar behavior."
22282 ;; pretend to be command COMMAND
22283 (setq this-command command)
22285 (if arg
22286 (call-interactively command)
22288 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22289 (and (org-kill-is-subtree-p)
22290 (or (bolp)
22291 (and (looking-at "[ \t]*$")
22292 (string-match
22293 "\\`\\*+\\'"
22294 (buffer-substring (point-at-bol) (point)))))))
22295 swallowp)
22296 (cond
22297 ((and subtreep org-yank-folded-subtrees)
22298 (let ((beg (point))
22299 end)
22300 (if (and subtreep org-yank-adjusted-subtrees)
22301 (org-paste-subtree nil nil 'for-yank)
22302 (call-interactively command))
22304 (setq end (point))
22305 (goto-char beg)
22306 (when (and (bolp) subtreep
22307 (not (setq swallowp
22308 (org-yank-folding-would-swallow-text beg end))))
22309 (org-with-limited-levels
22310 (or (looking-at org-outline-regexp)
22311 (re-search-forward org-outline-regexp-bol end t))
22312 (while (and (< (point) end) (looking-at org-outline-regexp))
22313 (hide-subtree)
22314 (org-cycle-show-empty-lines 'folded)
22315 (condition-case nil
22316 (outline-forward-same-level 1)
22317 (error (goto-char end))))))
22318 (when swallowp
22319 (message
22320 "Inserted text not folded because that would swallow text"))
22322 (goto-char end)
22323 (skip-chars-forward " \t\n\r")
22324 (beginning-of-line 1)
22325 (push-mark beg 'nomsg)))
22326 ((and subtreep org-yank-adjusted-subtrees)
22327 (let ((beg (point-at-bol)))
22328 (org-paste-subtree nil nil 'for-yank)
22329 (push-mark beg 'nomsg)))
22331 (call-interactively command))))))
22333 (defun org-yank-folding-would-swallow-text (beg end)
22334 "Would hide-subtree at BEG swallow any text after END?"
22335 (let (level)
22336 (org-with-limited-levels
22337 (save-excursion
22338 (goto-char beg)
22339 (when (or (looking-at org-outline-regexp)
22340 (re-search-forward org-outline-regexp-bol end t))
22341 (setq level (org-outline-level)))
22342 (goto-char end)
22343 (skip-chars-forward " \t\r\n\v\f")
22344 (if (or (eobp)
22345 (and (bolp) (looking-at org-outline-regexp)
22346 (<= (org-outline-level) level)))
22347 nil ; Nothing would be swallowed
22348 t))))) ; something would swallow
22350 (define-key org-mode-map "\C-y" 'org-yank)
22352 (defun org-truely-invisible-p ()
22353 "Check if point is at a character currently not visible.
22354 This version does not only check the character property, but also
22355 `visible-mode'."
22356 ;; Early versions of noutline don't have `outline-invisible-p'.
22357 (if (org-bound-and-true-p visible-mode)
22359 (outline-invisible-p)))
22361 (defun org-invisible-p2 ()
22362 "Check if point is at a character currently not visible."
22363 (save-excursion
22364 (if (and (eolp) (not (bobp))) (backward-char 1))
22365 ;; Early versions of noutline don't have `outline-invisible-p'.
22366 (outline-invisible-p)))
22368 (defun org-back-to-heading (&optional invisible-ok)
22369 "Call `outline-back-to-heading', but provide a better error message."
22370 (condition-case nil
22371 (outline-back-to-heading invisible-ok)
22372 (error (error "Before first headline at position %d in buffer %s"
22373 (point) (current-buffer)))))
22375 (defun org-before-first-heading-p ()
22376 "Before first heading?"
22377 (save-excursion
22378 (end-of-line)
22379 (null (re-search-backward org-outline-regexp-bol nil t))))
22381 (defun org-at-heading-p (&optional ignored)
22382 (outline-on-heading-p t))
22383 ;; Compatibility alias with Org versions < 7.8.03
22384 (defalias 'org-on-heading-p 'org-at-heading-p)
22386 (defun org-at-comment-p nil
22387 "Is cursor in a line starting with a # character?"
22388 (save-excursion
22389 (beginning-of-line)
22390 (looking-at "^#")))
22392 (defun org-at-drawer-p nil
22393 "Is cursor at a drawer keyword?"
22394 (save-excursion
22395 (move-beginning-of-line 1)
22396 (looking-at org-drawer-regexp)))
22398 (defun org-at-block-p nil
22399 "Is cursor at a block keyword?"
22400 (save-excursion
22401 (move-beginning-of-line 1)
22402 (looking-at org-block-regexp)))
22404 (defun org-point-at-end-of-empty-headline ()
22405 "If point is at the end of an empty headline, return t, else nil.
22406 If the heading only contains a TODO keyword, it is still still considered
22407 empty."
22408 (and (looking-at "[ \t]*$")
22409 (when org-todo-line-regexp
22410 (save-excursion
22411 (beginning-of-line 1)
22412 (let ((case-fold-search nil))
22413 (looking-at org-todo-line-regexp)
22414 (string= (match-string 3) ""))))))
22416 (defun org-at-heading-or-item-p ()
22417 (or (org-at-heading-p) (org-at-item-p)))
22419 (defun org-at-target-p ()
22420 (or (org-in-regexp org-radio-target-regexp)
22421 (org-in-regexp org-target-regexp)))
22422 ;; Compatibility alias with Org versions < 7.8.03
22423 (defalias 'org-on-target-p 'org-at-target-p)
22425 (defun org-up-heading-all (arg)
22426 "Move to the heading line of which the present line is a subheading.
22427 This function considers both visible and invisible heading lines.
22428 With argument, move up ARG levels."
22429 (if (fboundp 'outline-up-heading-all)
22430 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22431 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22433 (defun org-up-heading-safe ()
22434 "Move to the heading line of which the present line is a subheading.
22435 This version will not throw an error. It will return the level of the
22436 headline found, or nil if no higher level is found.
22438 Also, this function will be a lot faster than `outline-up-heading',
22439 because it relies on stars being the outline starters. This can really
22440 make a significant difference in outlines with very many siblings."
22441 (let (start-level re)
22442 (org-back-to-heading t)
22443 (setq start-level (funcall outline-level))
22444 (if (equal start-level 1)
22446 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22447 (if (re-search-backward re nil t)
22448 (funcall outline-level)))))
22450 (defun org-first-sibling-p ()
22451 "Is this heading the first child of its parents?"
22452 (interactive)
22453 (let ((re org-outline-regexp-bol)
22454 level l)
22455 (unless (org-at-heading-p t)
22456 (error "Not at a heading"))
22457 (setq level (funcall outline-level))
22458 (save-excursion
22459 (if (not (re-search-backward re nil t))
22461 (setq l (funcall outline-level))
22462 (< l level)))))
22464 (defun org-goto-sibling (&optional previous)
22465 "Goto the next sibling, even if it is invisible.
22466 When PREVIOUS is set, go to the previous sibling instead. Returns t
22467 when a sibling was found. When none is found, return nil and don't
22468 move point."
22469 (let ((fun (if previous 're-search-backward 're-search-forward))
22470 (pos (point))
22471 (re org-outline-regexp-bol)
22472 level l)
22473 (when (condition-case nil (org-back-to-heading t) (error nil))
22474 (setq level (funcall outline-level))
22475 (catch 'exit
22476 (or previous (forward-char 1))
22477 (while (funcall fun re nil t)
22478 (setq l (funcall outline-level))
22479 (when (< l level) (goto-char pos) (throw 'exit nil))
22480 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22481 (goto-char pos)
22482 nil))))
22484 (defun org-show-siblings ()
22485 "Show all siblings of the current headline."
22486 (save-excursion
22487 (while (org-goto-sibling) (org-flag-heading nil)))
22488 (save-excursion
22489 (while (org-goto-sibling 'previous)
22490 (org-flag-heading nil))))
22492 (defun org-goto-first-child ()
22493 "Goto the first child, even if it is invisible.
22494 Return t when a child was found. Otherwise don't move point and
22495 return nil."
22496 (let (level (pos (point)) (re org-outline-regexp-bol))
22497 (when (condition-case nil (org-back-to-heading t) (error nil))
22498 (setq level (outline-level))
22499 (forward-char 1)
22500 (if (and (re-search-forward re nil t) (> (outline-level) level))
22501 (progn (goto-char (match-beginning 0)) t)
22502 (goto-char pos) nil))))
22504 (defun org-show-hidden-entry ()
22505 "Show an entry where even the heading is hidden."
22506 (save-excursion
22507 (org-show-entry)))
22509 (defun org-flag-heading (flag &optional entry)
22510 "Flag the current heading. FLAG non-nil means make invisible.
22511 When ENTRY is non-nil, show the entire entry."
22512 (save-excursion
22513 (org-back-to-heading t)
22514 ;; Check if we should show the entire entry
22515 (if entry
22516 (progn
22517 (org-show-entry)
22518 (save-excursion
22519 (and (outline-next-heading)
22520 (org-flag-heading nil))))
22521 (outline-flag-region (max (point-min) (1- (point)))
22522 (save-excursion (outline-end-of-heading) (point))
22523 flag))))
22525 (defun org-get-next-sibling ()
22526 "Move to next heading of the same level, and return point.
22527 If there is no such heading, return nil.
22528 This is like outline-next-sibling, but invisible headings are ok."
22529 (let ((level (funcall outline-level)))
22530 (outline-next-heading)
22531 (while (and (not (eobp)) (> (funcall outline-level) level))
22532 (outline-next-heading))
22533 (if (or (eobp) (< (funcall outline-level) level))
22535 (point))))
22537 (defun org-get-last-sibling ()
22538 "Move to previous heading of the same level, and return point.
22539 If there is no such heading, return nil."
22540 (let ((opoint (point))
22541 (level (funcall outline-level)))
22542 (outline-previous-heading)
22543 (when (and (/= (point) opoint) (outline-on-heading-p t))
22544 (while (and (> (funcall outline-level) level)
22545 (not (bobp)))
22546 (outline-previous-heading))
22547 (if (< (funcall outline-level) level)
22549 (point)))))
22551 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22552 "Goto to the end of a subtree."
22553 ;; This contains an exact copy of the original function, but it uses
22554 ;; `org-back-to-heading', to make it work also in invisible
22555 ;; trees. And is uses an invisible-ok argument.
22556 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22557 ;; Furthermore, when used inside Org, finding the end of a large subtree
22558 ;; with many children and grandchildren etc, this can be much faster
22559 ;; than the outline version.
22560 (org-back-to-heading invisible-ok)
22561 (let ((first t)
22562 (level (funcall outline-level)))
22563 (if (and (derived-mode-p 'org-mode) (< level 1000))
22564 ;; A true heading (not a plain list item), in Org-mode
22565 ;; This means we can easily find the end by looking
22566 ;; only for the right number of stars. Using a regexp to do
22567 ;; this is so much faster than using a Lisp loop.
22568 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22569 (forward-char 1)
22570 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22571 ;; something else, do it the slow way
22572 (while (and (not (eobp))
22573 (or first (> (funcall outline-level) level)))
22574 (setq first nil)
22575 (outline-next-heading)))
22576 (unless to-heading
22577 (if (memq (preceding-char) '(?\n ?\^M))
22578 (progn
22579 ;; Go to end of line before heading
22580 (forward-char -1)
22581 (if (memq (preceding-char) '(?\n ?\^M))
22582 ;; leave blank line before heading
22583 (forward-char -1))))))
22584 (point))
22586 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22587 "Use Org version in org-mode, for dramatic speed-up."
22588 (if (derived-mode-p 'org-mode)
22589 (progn
22590 (org-end-of-subtree nil t)
22591 (unless (eobp) (backward-char 1)))
22592 ad-do-it))
22594 (defun org-end-of-meta-data-and-drawers ()
22595 "Jump to the first text after meta data and drawers in the current entry.
22596 This will move over empty lines, lines with planning time stamps,
22597 clocking lines, and drawers."
22598 (org-back-to-heading t)
22599 (let ((end (save-excursion (outline-next-heading) (point)))
22600 (re (concat "\\(" org-drawer-regexp "\\)"
22601 "\\|" "[ \t]*" org-keyword-time-regexp)))
22602 (forward-line 1)
22603 (while (re-search-forward re end t)
22604 (if (not (match-end 1))
22605 ;; empty or planning line
22606 (forward-line 1)
22607 ;; a drawer, find the end
22608 (re-search-forward "^[ \t]*:END:" end 'move)
22609 (forward-line 1)))
22610 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22611 (point)))
22613 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22614 "Move forward to the ARG'th subheading at same level as this one.
22615 Stop at the first and last subheadings of a superior heading.
22616 Normally this only looks at visible headings, but when INVISIBLE-OK is
22617 non-nil it will also look at invisible ones."
22618 (interactive "p")
22619 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22620 (if (and arg (< arg 0))
22621 (goto-char (point-min))
22622 (outline-next-heading))
22623 (org-at-heading-p)
22624 (let ((level (- (match-end 0) (match-beginning 0) 1))
22625 (f (if (and arg (< arg 0))
22626 're-search-backward
22627 're-search-forward))
22628 (count (if arg (abs arg) 1))
22629 (result (point)))
22630 (forward-char (if (and arg (< arg 0)) -1 1))
22631 (while (and (> count 0)
22632 (funcall f org-outline-regexp-bol nil 'move))
22633 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22634 (cond ((< l level) (setq count 0))
22635 ((and (= l level)
22636 (or invisible-ok
22637 (progn
22638 (goto-char (line-beginning-position))
22639 (not (outline-invisible-p)))))
22640 (setq count (1- count))
22641 (when (eq l level)
22642 (setq result (point)))))))
22643 (goto-char result))
22644 (beginning-of-line 1)))
22646 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22647 "Move backward to the ARG'th subheading at same level as this one.
22648 Stop at the first and last subheadings of a superior heading."
22649 (interactive "p")
22650 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22652 (defun org-next-block (arg &optional backward block-regexp)
22653 "Jump to the next block.
22654 With a prefix argument ARG, jump forward ARG many source blocks.
22655 When BACKWARD is non-nil, jump to the previous block.
22656 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22657 (interactive "p")
22658 (let ((re (or block-regexp org-block-regexp))
22659 (re-search-fn (or (and backward 're-search-backward)
22660 're-search-forward)))
22661 (if (looking-at re) (forward-char 1))
22662 (condition-case nil
22663 (funcall re-search-fn re nil nil arg)
22664 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22665 (goto-char (match-beginning 0)) (org-show-context)))
22667 (defun org-previous-block (arg &optional block-regexp)
22668 "Jump to the previous block.
22669 With a prefix argument ARG, jump backward ARG many source blocks.
22670 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22671 (interactive "p")
22672 (org-next-block arg t block-regexp))
22674 (defun org-forward-element ()
22675 "Move forward by one element.
22676 Move to the next element at the same level, when possible."
22677 (interactive)
22678 (cond ((eobp) (error "Cannot move further down"))
22679 ((org-with-limited-levels (org-at-heading-p))
22680 (let ((origin (point)))
22681 (goto-char (org-end-of-subtree nil t))
22682 (unless (org-with-limited-levels (org-at-heading-p))
22683 (goto-char origin)
22684 (error "Cannot move further down"))))
22686 (let* ((elem (org-element-at-point))
22687 (end (org-element-property :end elem))
22688 (parent (org-element-property :parent elem)))
22689 (if (and parent (= (org-element-property :contents-end parent) end))
22690 (goto-char (org-element-property :end parent))
22691 (goto-char end))))))
22693 (defun org-backward-element ()
22694 "Move backward by one element.
22695 Move to the previous element at the same level, when possible."
22696 (interactive)
22697 (cond ((bobp) (error "Cannot move further up"))
22698 ((org-with-limited-levels (org-at-heading-p))
22699 ;; At an headline, move to the previous one, if any, or stay
22700 ;; here.
22701 (let ((origin (point)))
22702 (org-with-limited-levels (org-backward-heading-same-level 1))
22703 ;; When current headline has no sibling above, move to its
22704 ;; parent.
22705 (when (= (point) origin)
22706 (or (org-with-limited-levels (org-up-heading-safe))
22707 (progn (goto-char origin)
22708 (error "Cannot move further up"))))))
22710 (let* ((trail (org-element-at-point 'keep-trail))
22711 (elem (car trail))
22712 (prev-elem (nth 1 trail))
22713 (beg (org-element-property :begin elem)))
22714 (cond
22715 ;; Move to beginning of current element if point isn't
22716 ;; there already.
22717 ((/= (point) beg) (goto-char beg))
22718 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22719 ((org-before-first-heading-p) (goto-char (point-min)))
22720 (t (org-back-to-heading)))))))
22722 (defun org-up-element ()
22723 "Move to upper element."
22724 (interactive)
22725 (if (org-with-limited-levels (org-at-heading-p))
22726 (unless (org-up-heading-safe) (error "No surrounding element"))
22727 (let* ((elem (org-element-at-point))
22728 (parent (org-element-property :parent elem)))
22729 (if parent (goto-char (org-element-property :begin parent))
22730 (if (org-with-limited-levels (org-before-first-heading-p))
22731 (error "No surrounding element")
22732 (org-with-limited-levels (org-back-to-heading)))))))
22734 (defvar org-element-greater-elements)
22735 (defun org-down-element ()
22736 "Move to inner element."
22737 (interactive)
22738 (let ((element (org-element-at-point)))
22739 (cond
22740 ((memq (org-element-type element) '(plain-list table))
22741 (goto-char (org-element-property :contents-begin element))
22742 (forward-char))
22743 ((memq (org-element-type element) org-element-greater-elements)
22744 ;; If contents are hidden, first disclose them.
22745 (when (org-element-property :hiddenp element) (org-cycle))
22746 (goto-char (or (org-element-property :contents-begin element)
22747 (error "No content for this element"))))
22748 (t (error "No inner element")))))
22750 (defun org-drag-element-backward ()
22751 "Move backward element at point."
22752 (interactive)
22753 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22754 (let* ((trail (org-element-at-point 'keep-trail))
22755 (elem (car trail))
22756 (prev-elem (nth 1 trail)))
22757 ;; Error out if no previous element or previous element is
22758 ;; a parent of the current one.
22759 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22760 (error "Cannot drag element backward")
22761 (let ((pos (point)))
22762 (org-element-swap-A-B prev-elem elem)
22763 (goto-char (+ (org-element-property :begin prev-elem)
22764 (- pos (org-element-property :begin elem)))))))))
22766 (defun org-drag-element-forward ()
22767 "Move forward element at point."
22768 (interactive)
22769 (let* ((pos (point))
22770 (elem (org-element-at-point)))
22771 (when (= (point-max) (org-element-property :end elem))
22772 (error "Cannot drag element forward"))
22773 (goto-char (org-element-property :end elem))
22774 (let ((next-elem (org-element-at-point)))
22775 (when (or (org-element-nested-p elem next-elem)
22776 (and (eq (org-element-type next-elem) 'headline)
22777 (not (eq (org-element-type elem) 'headline))))
22778 (goto-char pos)
22779 (error "Cannot drag element forward"))
22780 ;; Compute new position of point: it's shifted by NEXT-ELEM
22781 ;; body's length (without final blanks) and by the length of
22782 ;; blanks between ELEM and NEXT-ELEM.
22783 (let ((size-next (- (save-excursion
22784 (goto-char (org-element-property :end next-elem))
22785 (skip-chars-backward " \r\t\n")
22786 (forward-line)
22787 ;; Small correction if buffer doesn't end
22788 ;; with a newline character.
22789 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22790 (org-element-property :begin next-elem)))
22791 (size-blank (- (org-element-property :end elem)
22792 (save-excursion
22793 (goto-char (org-element-property :end elem))
22794 (skip-chars-backward " \r\t\n")
22795 (forward-line)
22796 (point)))))
22797 (org-element-swap-A-B elem next-elem)
22798 (goto-char (+ pos size-next size-blank))))))
22800 (defun org-drag-line-forward (arg)
22801 "Drag the line at point ARG lines forward."
22802 (interactive "p")
22803 (dotimes (n (abs arg))
22804 (let ((c (current-column)))
22805 (if (< 0 arg)
22806 (progn
22807 (beginning-of-line 2)
22808 (transpose-lines 1)
22809 (beginning-of-line 0))
22810 (transpose-lines 1)
22811 (beginning-of-line -1))
22812 (org-move-to-column c))))
22814 (defun org-drag-line-backward (arg)
22815 "Drag the line at point ARG lines backward."
22816 (interactive "p")
22817 (org-drag-line-forward (- arg)))
22819 (defun org-mark-element ()
22820 "Put point at beginning of this element, mark at end.
22822 Interactively, if this command is repeated or (in Transient Mark
22823 mode) if the mark is active, it marks the next element after the
22824 ones already marked."
22825 (interactive)
22826 (let (deactivate-mark)
22827 (if (and (org-called-interactively-p 'any)
22828 (or (and (eq last-command this-command) (mark t))
22829 (and transient-mark-mode mark-active)))
22830 (set-mark
22831 (save-excursion
22832 (goto-char (mark))
22833 (goto-char (org-element-property :end (org-element-at-point)))))
22834 (let ((element (org-element-at-point)))
22835 (end-of-line)
22836 (push-mark (org-element-property :end element) t t)
22837 (goto-char (org-element-property :begin element))))))
22839 (defun org-narrow-to-element ()
22840 "Narrow buffer to current element."
22841 (interactive)
22842 (let ((elem (org-element-at-point)))
22843 (cond
22844 ((eq (car elem) 'headline)
22845 (narrow-to-region
22846 (org-element-property :begin elem)
22847 (org-element-property :end elem)))
22848 ((memq (car elem) org-element-greater-elements)
22849 (narrow-to-region
22850 (org-element-property :contents-begin elem)
22851 (org-element-property :contents-end elem)))
22853 (narrow-to-region
22854 (org-element-property :begin elem)
22855 (org-element-property :end elem))))))
22857 (defun org-transpose-element ()
22858 "Transpose current and previous elements, keeping blank lines between.
22859 Point is moved after both elements."
22860 (interactive)
22861 (org-skip-whitespace)
22862 (let ((end (org-element-property :end (org-element-at-point))))
22863 (org-drag-element-backward)
22864 (goto-char end)))
22866 (defun org-unindent-buffer ()
22867 "Un-indent the visible part of the buffer.
22868 Relative indentation (between items, inside blocks, etc.) isn't
22869 modified."
22870 (interactive)
22871 (unless (eq major-mode 'org-mode)
22872 (error "Cannot un-indent a buffer not in Org mode"))
22873 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22874 unindent-tree ; For byte-compiler.
22875 (unindent-tree
22876 (function
22877 (lambda (contents)
22878 (mapc
22879 (lambda (element)
22880 (if (memq (org-element-type element) '(headline section))
22881 (funcall unindent-tree (org-element-contents element))
22882 (save-excursion
22883 (save-restriction
22884 (narrow-to-region
22885 (org-element-property :begin element)
22886 (org-element-property :end element))
22887 (org-do-remove-indentation)))))
22888 (reverse contents))))))
22889 (funcall unindent-tree (org-element-contents parse-tree))))
22891 (defun org-show-subtree ()
22892 "Show everything after this heading at deeper levels."
22893 (interactive)
22894 (outline-flag-region
22895 (point)
22896 (save-excursion
22897 (org-end-of-subtree t t))
22898 nil))
22900 (defun org-show-entry ()
22901 "Show the body directly following this heading.
22902 Show the heading too, if it is currently invisible."
22903 (interactive)
22904 (save-excursion
22905 (condition-case nil
22906 (progn
22907 (org-back-to-heading t)
22908 (outline-flag-region
22909 (max (point-min) (1- (point)))
22910 (save-excursion
22911 (if (re-search-forward
22912 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22913 (match-beginning 1)
22914 (point-max)))
22915 nil)
22916 (org-cycle-hide-drawers 'children))
22917 (error nil))))
22919 (defun org-make-options-regexp (kwds &optional extra)
22920 "Make a regular expression for keyword lines."
22921 (concat
22922 "^#\\+\\("
22923 (mapconcat 'regexp-quote kwds "\\|")
22924 (if extra (concat "\\|" extra))
22925 "\\):[ \t]*\\(.*\\)"))
22927 ;; Make isearch reveal the necessary context
22928 (defun org-isearch-end ()
22929 "Reveal context after isearch exits."
22930 (when isearch-success ; only if search was successful
22931 (if (featurep 'xemacs)
22932 ;; Under XEmacs, the hook is run in the correct place,
22933 ;; we directly show the context.
22934 (org-show-context 'isearch)
22935 ;; In Emacs the hook runs *before* restoring the overlays.
22936 ;; So we have to use a one-time post-command-hook to do this.
22937 ;; (Emacs 22 has a special variable, see function `org-mode')
22938 (unless (and (boundp 'isearch-mode-end-hook-quit)
22939 isearch-mode-end-hook-quit)
22940 ;; Only when the isearch was not quitted.
22941 (org-add-hook 'post-command-hook 'org-isearch-post-command
22942 'append 'local)))))
22944 (defun org-isearch-post-command ()
22945 "Remove self from hook, and show context."
22946 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22947 (org-show-context 'isearch))
22950 ;;;; Integration with and fixes for other packages
22952 ;;; Imenu support
22954 (defvar org-imenu-markers nil
22955 "All markers currently used by Imenu.")
22956 (make-variable-buffer-local 'org-imenu-markers)
22958 (defun org-imenu-new-marker (&optional pos)
22959 "Return a new marker for use by Imenu, and remember the marker."
22960 (let ((m (make-marker)))
22961 (move-marker m (or pos (point)))
22962 (push m org-imenu-markers)
22965 (defun org-imenu-get-tree ()
22966 "Produce the index for Imenu."
22967 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22968 (setq org-imenu-markers nil)
22969 (let* ((n org-imenu-depth)
22970 (re (concat "^" (org-get-limited-outline-regexp)))
22971 (subs (make-vector (1+ n) nil))
22972 (last-level 0)
22973 m level head)
22974 (save-excursion
22975 (save-restriction
22976 (widen)
22977 (goto-char (point-max))
22978 (while (re-search-backward re nil t)
22979 (setq level (org-reduced-level (funcall outline-level)))
22980 (when (and (<= level n)
22981 (looking-at org-complex-heading-regexp))
22982 (setq head (org-link-display-format
22983 (org-match-string-no-properties 4))
22984 m (org-imenu-new-marker))
22985 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22986 (if (>= level last-level)
22987 (push (cons head m) (aref subs level))
22988 (push (cons head (aref subs (1+ level))) (aref subs level))
22989 (loop for i from (1+ level) to n do (aset subs i nil)))
22990 (setq last-level level)))))
22991 (aref subs 1)))
22993 (eval-after-load "imenu"
22994 '(progn
22995 (add-hook 'imenu-after-jump-hook
22996 (lambda ()
22997 (if (derived-mode-p 'org-mode)
22998 (org-show-context 'org-goto))))))
23000 (defun org-link-display-format (link)
23001 "Replace a link with either the description, or the link target
23002 if no description is present"
23003 (save-match-data
23004 (if (string-match org-bracket-link-analytic-regexp link)
23005 (replace-match (if (match-end 5)
23006 (match-string 5 link)
23007 (concat (match-string 1 link)
23008 (match-string 3 link)))
23009 nil t link)
23010 link)))
23012 (defun org-toggle-link-display ()
23013 "Toggle the literal or descriptive display of links."
23014 (interactive)
23015 (if org-descriptive-links
23016 (progn (org-remove-from-invisibility-spec '(org-link))
23017 (org-restart-font-lock)
23018 (setq org-descriptive-links nil))
23019 (progn (add-to-invisibility-spec '(org-link))
23020 (org-restart-font-lock)
23021 (setq org-descriptive-links t))))
23023 ;; Speedbar support
23025 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23026 "Overlay marking the agenda restriction line in speedbar.")
23027 (overlay-put org-speedbar-restriction-lock-overlay
23028 'face 'org-agenda-restriction-lock)
23029 (overlay-put org-speedbar-restriction-lock-overlay
23030 'help-echo "Agendas are currently limited to this item.")
23031 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23033 (defun org-speedbar-set-agenda-restriction ()
23034 "Restrict future agenda commands to the location at point in speedbar.
23035 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23036 (interactive)
23037 (require 'org-agenda)
23038 (let (p m tp np dir txt)
23039 (cond
23040 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23041 'org-imenu t))
23042 (setq m (get-text-property p 'org-imenu-marker))
23043 (with-current-buffer (marker-buffer m)
23044 (goto-char m)
23045 (org-agenda-set-restriction-lock 'subtree)))
23046 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23047 'speedbar-function 'speedbar-find-file))
23048 (setq tp (previous-single-property-change
23049 (1+ p) 'speedbar-function)
23050 np (next-single-property-change
23051 tp 'speedbar-function)
23052 dir (speedbar-line-directory)
23053 txt (buffer-substring-no-properties (or tp (point-min))
23054 (or np (point-max))))
23055 (with-current-buffer (find-file-noselect
23056 (let ((default-directory dir))
23057 (expand-file-name txt)))
23058 (unless (derived-mode-p 'org-mode)
23059 (error "Cannot restrict to non-Org-mode file"))
23060 (org-agenda-set-restriction-lock 'file)))
23061 (t (error "Don't know how to restrict Org-mode's agenda")))
23062 (move-overlay org-speedbar-restriction-lock-overlay
23063 (point-at-bol) (point-at-eol))
23064 (setq current-prefix-arg nil)
23065 (org-agenda-maybe-redo)))
23067 (eval-after-load "speedbar"
23068 '(progn
23069 (speedbar-add-supported-extension ".org")
23070 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23071 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23072 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23073 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23074 (add-hook 'speedbar-visiting-tag-hook
23075 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23077 ;;; Fixes and Hacks for problems with other packages
23079 ;; Make flyspell not check words in links, to not mess up our keymap
23080 (defvar org-element-affiliated-keywords) ; From org-element.el
23081 (defvar org-element-block-name-alist) ; From org-element.el
23082 (defun org-mode-flyspell-verify ()
23083 "Don't let flyspell put overlays at active buttons, or on
23084 {todo,all-time,additional-option-like}-keywords."
23085 (let ((pos (max (1- (point)) (point-min)))
23086 (word (thing-at-point 'word)))
23087 (and (not (get-text-property pos 'keymap))
23088 (not (get-text-property pos 'org-no-flyspell))
23089 (not (member word org-todo-keywords-1))
23090 (not (member word org-all-time-keywords))
23091 (not (member word org-options-keywords))
23092 (not (member word (mapcar 'car org-startup-options)))
23093 (not (member-ignore-case word org-element-affiliated-keywords))
23094 (not (member-ignore-case word (org-get-export-keywords)))
23095 (not (member-ignore-case
23096 word (mapcar 'car org-element-block-name-alist)))
23097 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23099 (defun org-remove-flyspell-overlays-in (beg end)
23100 "Remove flyspell overlays in region."
23101 (and (org-bound-and-true-p flyspell-mode)
23102 (fboundp 'flyspell-delete-region-overlays)
23103 (flyspell-delete-region-overlays beg end))
23104 (add-text-properties beg end '(org-no-flyspell t)))
23106 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23107 (eval-after-load "bookmark"
23108 '(if (boundp 'bookmark-after-jump-hook)
23109 ;; We can use the hook
23110 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23111 ;; Hook not available, use advice
23112 (defadvice bookmark-jump (after org-make-visible activate)
23113 "Make the position visible."
23114 (org-bookmark-jump-unhide))))
23116 ;; Make sure saveplace shows the location if it was hidden
23117 (eval-after-load "saveplace"
23118 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23119 "Make the position visible."
23120 (org-bookmark-jump-unhide)))
23122 ;; Make sure ecb shows the location if it was hidden
23123 (eval-after-load "ecb"
23124 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23125 "Make hierarchy visible when jumping into location from ECB tree buffer."
23126 (if (derived-mode-p 'org-mode)
23127 (org-show-context))))
23129 (defun org-bookmark-jump-unhide ()
23130 "Unhide the current position, to show the bookmark location."
23131 (and (derived-mode-p 'org-mode)
23132 (or (outline-invisible-p)
23133 (save-excursion (goto-char (max (point-min) (1- (point))))
23134 (outline-invisible-p)))
23135 (org-show-context 'bookmark-jump)))
23137 ;; Make session.el ignore our circular variable
23138 (eval-after-load "session"
23139 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23141 ;;;; Experimental code
23143 (defun org-closed-in-range ()
23144 "Sparse tree of items closed in a certain time range.
23145 Still experimental, may disappear in the future."
23146 (interactive)
23147 ;; Get the time interval from the user.
23148 (let* ((time1 (org-float-time
23149 (org-read-date nil 'to-time nil "Starting date: ")))
23150 (time2 (org-float-time
23151 (org-read-date nil 'to-time nil "End date:")))
23152 ;; callback function
23153 (callback (lambda ()
23154 (let ((time
23155 (org-float-time
23156 (apply 'encode-time
23157 (org-parse-time-string
23158 (match-string 1))))))
23159 ;; check if time in interval
23160 (and (>= time time1) (<= time time2))))))
23161 ;; make tree, check each match with the callback
23162 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23164 ;;;; Finish up
23166 (provide 'org)
23168 (run-hooks 'org-load-hook)
23170 ;;; org.el ends here