c53ce2bed4f5864f549c0a10f3f256738f788a61
[org-mode.git] / lisp / org.el
blobc53ce2bed4f5864f549c0a10f3f256738f788a61
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything"
590 :group 'org-startup
591 :type '(choice
592 (const :tag "nofold: show all" nil)
593 (const :tag "fold: overview" t)
594 (const :tag "content: all headlines" content)
595 (const :tag "show everything, even drawers" showeverything)))
597 (defcustom org-startup-truncated t
598 "Non-nil means entering Org-mode will set `truncate-lines'.
599 This is useful since some lines containing links can be very long and
600 uninteresting. Also tables look terrible when wrapped."
601 :group 'org-startup
602 :type 'boolean)
604 (defcustom org-startup-indented nil
605 "Non-nil means turn on `org-indent-mode' on startup.
606 This can also be configured on a per-file basis by adding one of
607 the following lines anywhere in the buffer:
609 #+STARTUP: indent
610 #+STARTUP: noindent"
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Not" nil)
614 (const :tag "Globally (slow on startup in large files)" t)))
616 (defcustom org-use-sub-superscripts t
617 "Non-nil means interpret \"_\" and \"^\" for display.
618 When this option is turned on, you can use TeX-like syntax for sub- and
619 superscripts. Several characters after \"_\" or \"^\" will be
620 considered as a single item - so grouping with {} is normally not
621 needed. For example, the following things will be parsed as single
622 sub- or superscripts.
624 10^24 or 10^tau several digits will be considered 1 item.
625 10^-12 or 10^-tau a leading sign with digits or a word
626 x^2-y^3 will be read as x^2 - y^3, because items are
627 terminated by almost any nonword/nondigit char.
628 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
630 Still, ambiguity is possible - so when in doubt use {} to enclose
631 the sub/superscript. If you set this variable to the symbol
632 `{}', the braces are *required* in order to trigger
633 interpretations as sub/superscript. This can be helpful in
634 documents that need \"_\" frequently in plain text."
635 :group 'org-startup
636 :version "24.1"
637 :type '(choice
638 (const :tag "Always interpret" t)
639 (const :tag "Only with braces" {})
640 (const :tag "Never interpret" nil)))
642 (defcustom org-startup-with-beamer-mode nil
643 "Non-nil means turn on `org-beamer-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: beamer"
648 :group 'org-startup
649 :version "24.1"
650 :type 'boolean)
652 (defcustom org-startup-align-all-tables nil
653 "Non-nil means align all tables when visiting a file.
654 This is useful when the column width in tables is forced with <N> cookies
655 in table fields. Such tables will look correct only after the first re-align.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
658 #+STARTUP: align
659 #+STARTUP: noalign"
660 :group 'org-startup
661 :type 'boolean)
663 (defcustom org-startup-with-inline-images nil
664 "Non-nil means show inline images when loading a new Org file.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: inlineimages
668 #+STARTUP: noinlineimages"
669 :group 'org-startup
670 :version "24.1"
671 :type 'boolean)
673 (defcustom org-insert-mode-line-in-empty-file nil
674 "Non-nil means insert the first line setting Org-mode in empty files.
675 When the function `org-mode' is called interactively in an empty file, this
676 normally means that the file name does not automatically trigger Org-mode.
677 To ensure that the file will always be in Org-mode in the future, a
678 line enforcing Org-mode will be inserted into the buffer, if this option
679 has been set."
680 :group 'org-startup
681 :type 'boolean)
683 (defcustom org-replace-disputed-keys nil
684 "Non-nil means use alternative key bindings for some keys.
685 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
686 These keys are also used by other packages like shift-selection-mode'
687 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
688 If you want to use Org-mode together with one of these other modes,
689 or more generally if you would like to move some Org-mode commands to
690 other keys, set this variable and configure the keys with the variable
691 `org-disputed-keys'.
693 This option is only relevant at load-time of Org-mode, and must be set
694 *before* org.el is loaded. Changing it requires a restart of Emacs to
695 become effective."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-use-extra-keys nil
700 "Non-nil means use extra key sequence definitions for certain commands.
701 This happens automatically if you run XEmacs or if `window-system'
702 is nil. This variable lets you do the same manually. You must
703 set it before loading org.
705 Example: on Carbon Emacs 22 running graphically, with an external
706 keyboard on a Powerbook, the default way of setting M-left might
707 not work for either Alt or ESC. Setting this variable will make
708 it work for ESC."
709 :group 'org-startup
710 :type 'boolean)
712 (if (fboundp 'defvaralias)
713 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
715 (defcustom org-disputed-keys
716 '(([(shift up)] . [(meta p)])
717 ([(shift down)] . [(meta n)])
718 ([(shift left)] . [(meta -)])
719 ([(shift right)] . [(meta +)])
720 ([(control shift right)] . [(meta shift +)])
721 ([(control shift left)] . [(meta shift -)]))
722 "Keys for which Org-mode and other modes compete.
723 This is an alist, cars are the default keys, second element specifies
724 the alternative to use when `org-replace-disputed-keys' is t.
726 Keys can be specified in any syntax supported by `define-key'.
727 The value of this option takes effect only at Org-mode's startup,
728 therefore you'll have to restart Emacs to apply it after changing."
729 :group 'org-startup
730 :type 'alist)
732 (defun org-key (key)
733 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
734 Or return the original if not disputed.
735 Also apply the translations defined in `org-xemacs-key-equivalents'."
736 (when org-replace-disputed-keys
737 (let* ((nkey (key-description key))
738 (x (org-find-if (lambda (x)
739 (equal (key-description (car x)) nkey))
740 org-disputed-keys)))
741 (setq key (if x (cdr x) key))))
742 (when (featurep 'xemacs)
743 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
744 key)
746 (defun org-find-if (predicate seq)
747 (catch 'exit
748 (while seq
749 (if (funcall predicate (car seq))
750 (throw 'exit (car seq))
751 (pop seq)))))
753 (defun org-defkey (keymap key def)
754 "Define a key, possibly translated, as returned by `org-key'."
755 (define-key keymap (org-key key) def))
757 (defcustom org-ellipsis nil
758 "The ellipsis to use in the Org-mode outline.
759 When nil, just use the standard three dots. When a string, use that instead,
760 When a face, use the standard 3 dots, but with the specified face.
761 The change affects only Org-mode (which will then use its own display table).
762 Changing this requires executing `M-x org-mode' in a buffer to become
763 effective."
764 :group 'org-startup
765 :type '(choice (const :tag "Default" nil)
766 (face :tag "Face" :value org-warning)
767 (string :tag "String" :value "...#")))
769 (defvar org-display-table nil
770 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
772 (defgroup org-keywords nil
773 "Keywords in Org-mode."
774 :tag "Org Keywords"
775 :group 'org)
777 (defcustom org-deadline-string "DEADLINE:"
778 "String to mark deadline entries.
779 A deadline is this string, followed by a time stamp. Should be a word,
780 terminated by a colon. You can insert a schedule keyword and
781 a timestamp with \\[org-deadline].
782 Changes become only effective after restarting Emacs."
783 :group 'org-keywords
784 :type 'string)
786 (defcustom org-scheduled-string "SCHEDULED:"
787 "String to mark scheduled TODO entries.
788 A schedule is this string, followed by a time stamp. Should be a word,
789 terminated by a colon. You can insert a schedule keyword and
790 a timestamp with \\[org-schedule].
791 Changes become only effective after restarting Emacs."
792 :group 'org-keywords
793 :type 'string)
795 (defcustom org-closed-string "CLOSED:"
796 "String used as the prefix for timestamps logging closing a TODO entry."
797 :group 'org-keywords
798 :type 'string)
800 (defcustom org-clock-string "CLOCK:"
801 "String used as prefix for timestamps clocking work hours on an item."
802 :group 'org-keywords
803 :type 'string)
805 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
806 org-scheduled-string "\\|"
807 org-deadline-string "\\|"
808 org-closed-string "\\|"
809 org-clock-string "\\)")
810 "Matches a line with planning or clock info.")
812 (defcustom org-comment-string "COMMENT"
813 "Entries starting with this keyword will never be exported.
814 An entry can be toggled between COMMENT and normal with
815 \\[org-toggle-comment].
816 Changes become only effective after restarting Emacs."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-quote-string "QUOTE"
821 "Entries starting with this keyword will be exported in fixed-width font.
822 Quoting applies only to the text in the entry following the headline, and does
823 not extend beyond the next headline, even if that is lower level.
824 An entry can be toggled between QUOTE and normal with
825 \\[org-toggle-fixed-width-section]."
826 :group 'org-keywords
827 :type 'string)
829 (defconst org-repeat-re
830 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
831 "Regular expression for specifying repeated events.
832 After a match, group 1 contains the repeat expression.")
834 (defgroup org-structure nil
835 "Options concerning the general structure of Org-mode files."
836 :tag "Org Structure"
837 :group 'org)
839 (defgroup org-reveal-location nil
840 "Options about how to make context of a location visible."
841 :tag "Org Reveal Location"
842 :group 'org-structure)
844 (defconst org-context-choice
845 '(choice
846 (const :tag "Always" t)
847 (const :tag "Never" nil)
848 (repeat :greedy t :tag "Individual contexts"
849 (cons
850 (choice :tag "Context"
851 (const agenda)
852 (const org-goto)
853 (const occur-tree)
854 (const tags-tree)
855 (const link-search)
856 (const mark-goto)
857 (const bookmark-jump)
858 (const isearch)
859 (const default))
860 (boolean))))
861 "Contexts for the reveal options.")
863 (defcustom org-show-hierarchy-above '((default . t))
864 "Non-nil means show full hierarchy when revealing a location.
865 Org-mode often shows locations in an org-mode file which might have
866 been invisible before. When this is set, the hierarchy of headings
867 above the exposed location is shown.
868 Turning this off for example for sparse trees makes them very compact.
869 Instead of t, this can also be an alist specifying this option for different
870 contexts. Valid contexts are
871 agenda when exposing an entry from the agenda
872 org-goto when using the command `org-goto' on key C-c C-j
873 occur-tree when using the command `org-occur' on key C-c /
874 tags-tree when constructing a sparse tree based on tags matches
875 link-search when exposing search matches associated with a link
876 mark-goto when exposing the jump goal of a mark
877 bookmark-jump when exposing a bookmark location
878 isearch when exiting from an incremental search
879 default default for all contexts not set explicitly"
880 :group 'org-reveal-location
881 :type org-context-choice)
883 (defcustom org-show-following-heading '((default . nil))
884 "Non-nil means show following heading when revealing a location.
885 Org-mode often shows locations in an org-mode file which might have
886 been invisible before. When this is set, the heading following the
887 match is shown.
888 Turning this off for example for sparse trees makes them very compact,
889 but makes it harder to edit the location of the match. In such a case,
890 use the command \\[org-reveal] to show more context.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. See `org-show-hierarchy-above' for valid contexts."
893 :group 'org-reveal-location
894 :type org-context-choice)
896 (defcustom org-show-siblings '((default . nil) (isearch t))
897 "Non-nil means show all sibling heading when revealing a location.
898 Org-mode often shows locations in an org-mode file which might have
899 been invisible before. When this is set, the sibling of the current entry
900 heading are all made visible. If `org-show-hierarchy-above' is t,
901 the same happens on each level of the hierarchy above the current entry.
903 By default this is on for the isearch context, off for all other contexts.
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-entry-below '((default . nil))
913 "Non-nil means show the entry below a headline 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 text below the headline that is
916 exposed is also shown.
918 By default this is off for all contexts.
919 Instead of t, this can also be an alist specifying this option for different
920 contexts. See `org-show-hierarchy-above' for valid contexts."
921 :group 'org-reveal-location
922 :type org-context-choice)
924 (defcustom org-indirect-buffer-display 'other-window
925 "How should indirect tree buffers be displayed?
926 This applies to indirect buffers created with the commands
927 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
928 Valid values are:
929 current-window Display in the current window
930 other-window Just display in another window.
931 dedicated-frame Create one new frame, and re-use it each time.
932 new-frame Make a new frame each time. Note that in this case
933 previously-made indirect buffers are kept, and you need to
934 kill these buffers yourself."
935 :group 'org-structure
936 :group 'org-agenda-windows
937 :type '(choice
938 (const :tag "In current window" current-window)
939 (const :tag "In current frame, other window" other-window)
940 (const :tag "Each time a new frame" new-frame)
941 (const :tag "One dedicated frame" dedicated-frame)))
943 (defcustom org-use-speed-commands nil
944 "Non-nil means activate single letter commands at beginning of a headline.
945 This may also be a function to test for appropriate locations where speed
946 commands should be active."
947 :group 'org-structure
948 :type '(choice
949 (const :tag "Never" nil)
950 (const :tag "At beginning of headline stars" t)
951 (function)))
953 (defcustom org-speed-commands-user nil
954 "Alist of additional speed commands.
955 This list will be checked before `org-speed-commands-default'
956 when the variable `org-use-speed-commands' is non-nil
957 and when the cursor is at the beginning of a headline.
958 The car if each entry is a string with a single letter, which must
959 be assigned to `self-insert-command' in the global map.
960 The cdr is either a command to be called interactively, a function
961 to be called, or a form to be evaluated.
962 An entry that is just a list with a single string will be interpreted
963 as a descriptive headline that will be added when listing the speed
964 commands in the Help buffer using the `?' speed command."
965 :group 'org-structure
966 :type '(repeat :value ("k" . ignore)
967 (choice :value ("k" . ignore)
968 (list :tag "Descriptive Headline" (string :tag "Headline"))
969 (cons :tag "Letter and Command"
970 (string :tag "Command letter")
971 (choice
972 (function)
973 (sexp))))))
975 (defgroup org-cycle nil
976 "Options concerning visibility cycling in Org-mode."
977 :tag "Org Cycle"
978 :group 'org-structure)
980 (defcustom org-cycle-skip-children-state-if-no-children t
981 "Non-nil means skip CHILDREN state in entries that don't have any."
982 :group 'org-cycle
983 :type 'boolean)
985 (defcustom org-cycle-max-level nil
986 "Maximum level which should still be subject to visibility cycling.
987 Levels higher than this will, for cycling, be treated as text, not a headline.
988 When `org-odd-levels-only' is set, a value of N in this variable actually
989 means 2N-1 stars as the limiting headline.
990 When nil, cycle all levels.
991 Note that the limiting level of cycling is also influenced by
992 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
993 `org-inlinetask-min-level' is, cycling will be limited to levels one less
994 than its value."
995 :group 'org-cycle
996 :type '(choice
997 (const :tag "No limit" nil)
998 (integer :tag "Maximum level")))
1000 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1001 "Names of drawers. Drawers are not opened by cycling on the headline above.
1002 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1003 this:
1004 :DRAWERNAME:
1005 .....
1006 :END:
1007 The drawer \"PROPERTIES\" is special for capturing properties through
1008 the property API.
1010 Drawers can be defined on the per-file basis with a line like:
1012 #+DRAWERS: HIDDEN STATE PROPERTIES"
1013 :group 'org-structure
1014 :group 'org-cycle
1015 :type '(repeat (string :tag "Drawer Name")))
1017 (defcustom org-hide-block-startup nil
1018 "Non-nil means entering Org-mode will fold all blocks.
1019 This can also be set in on a per-file basis with
1021 #+STARTUP: hideblocks
1022 #+STARTUP: showblocks"
1023 :group 'org-startup
1024 :group 'org-cycle
1025 :type 'boolean)
1027 (defcustom org-cycle-global-at-bob nil
1028 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1029 This makes it possible to do global cycling without having to use S-TAB or
1030 \\[universal-argument] TAB. For this special case to work, the first line
1031 of the buffer must not be a headline -- it may be empty or some other text.
1032 When used in this way, `org-cycle-hook' is disabled temporarily to make
1033 sure the cursor stays at the beginning of the buffer. When this option is
1034 nil, don't do anything special at the beginning of the buffer."
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-level-after-item/entry-creation t
1039 "Non-nil means cycle entry level or item indentation in new empty entries.
1041 When the cursor is at the end of an empty headline, i.e with only stars
1042 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1043 and then all possible ancestor states, before returning to the original state.
1044 This makes data entry extremely fast: M-RET to create a new headline,
1045 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1047 When the cursor is at the end of an empty plain list item, one TAB will
1048 make it a subitem, two or more tabs will back up to make this an item
1049 higher up in the item hierarchy."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-emulate-tab t
1054 "Where should `org-cycle' emulate TAB.
1055 nil Never
1056 white Only in completely white lines
1057 whitestart Only at the beginning of lines, before the first non-white char
1058 t Everywhere except in headlines
1059 exc-hl-bol Everywhere except at the start of a headline
1060 If TAB is used in a place where it does not emulate TAB, the current subtree
1061 visibility is cycled."
1062 :group 'org-cycle
1063 :type '(choice (const :tag "Never" nil)
1064 (const :tag "Only in completely white lines" white)
1065 (const :tag "Before first char in a line" whitestart)
1066 (const :tag "Everywhere except in headlines" t)
1067 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1070 (defcustom org-cycle-separator-lines 2
1071 "Number of empty lines needed to keep an empty line between collapsed trees.
1072 If you leave an empty line between the end of a subtree and the following
1073 headline, this empty line is hidden when the subtree is folded.
1074 Org-mode will leave (exactly) one empty line visible if the number of
1075 empty lines is equal or larger to the number given in this variable.
1076 So the default 2 means at least 2 empty lines after the end of a subtree
1077 are needed to produce free space between a collapsed subtree and the
1078 following headline.
1080 If the number is negative, and the number of empty lines is at least -N,
1081 all empty lines are shown.
1083 Special case: when 0, never leave empty lines in collapsed view."
1084 :group 'org-cycle
1085 :type 'integer)
1086 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1088 (defcustom org-pre-cycle-hook nil
1089 "Hook that is run before visibility cycling is happening.
1090 The function(s) in this hook must accept a single argument which indicates
1091 the new state that will be set right after running this hook. The
1092 argument is a symbol. Before a global state change, it can have the values
1093 `overview', `content', or `all'. Before a local state change, it can have
1094 the values `folded', `children', or `subtree'."
1095 :group 'org-cycle
1096 :type 'hook)
1098 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1099 org-cycle-hide-drawers
1100 org-cycle-hide-inline-tasks
1101 org-cycle-show-empty-lines
1102 org-optimize-window-after-visibility-change)
1103 "Hook that is run after `org-cycle' has changed the buffer visibility.
1104 The function(s) in this hook must accept a single argument which indicates
1105 the new state that was set by the most recent `org-cycle' command. The
1106 argument is a symbol. After a global state change, it can have the values
1107 `overview', `contents', or `all'. After a local state change, it can have
1108 the values `folded', `children', or `subtree'."
1109 :group 'org-cycle
1110 :type 'hook)
1112 (defgroup org-edit-structure nil
1113 "Options concerning structure editing in Org-mode."
1114 :tag "Org Edit Structure"
1115 :group 'org-structure)
1117 (defcustom org-odd-levels-only nil
1118 "Non-nil means skip even levels and only use odd levels for the outline.
1119 This has the effect that two stars are being added/taken away in
1120 promotion/demotion commands. It also influences how levels are
1121 handled by the exporters.
1122 Changing it requires restart of `font-lock-mode' to become effective
1123 for fontification also in regions already fontified.
1124 You may also set this on a per-file basis by adding one of the following
1125 lines to the buffer:
1127 #+STARTUP: odd
1128 #+STARTUP: oddeven"
1129 :group 'org-edit-structure
1130 :group 'org-appearance
1131 :type 'boolean)
1133 (defcustom org-adapt-indentation t
1134 "Non-nil means adapt indentation to outline node level.
1136 When this variable is set, Org assumes that you write outlines by
1137 indenting text in each node to align with the headline (after the stars).
1138 The following issues are influenced by this variable:
1140 - When this is set and the *entire* text in an entry is indented, the
1141 indentation is increased by one space in a demotion command, and
1142 decreased by one in a promotion command. If any line in the entry
1143 body starts with text at column 0, indentation is not changed at all.
1145 - Property drawers and planning information is inserted indented when
1146 this variable s set. When nil, they will not be indented.
1148 - TAB indents a line relative to context. The lines below a headline
1149 will be indented when this variable is set.
1151 Note that this is all about true indentation, by adding and removing
1152 space characters. See also `org-indent.el' which does level-dependent
1153 indentation in a virtual way, i.e. at display time in Emacs."
1154 :group 'org-edit-structure
1155 :type 'boolean)
1157 (defcustom org-special-ctrl-a/e nil
1158 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1160 When t, `C-a' will bring back the cursor to the beginning of the
1161 headline text, i.e. after the stars and after a possible TODO
1162 keyword. In an item, this will be the position after bullet and
1163 check-box, if any. When the cursor is already at that position,
1164 another `C-a' will bring it to the beginning of the line.
1166 `C-e' will jump to the end of the headline, ignoring the presence
1167 of tags in the headline. A second `C-e' will then jump to the
1168 true end of the line, after any tags. This also means that, when
1169 this variable is non-nil, `C-e' also will never jump beyond the
1170 end of the heading of a folded section, i.e. not after the
1171 ellipses.
1173 When set to the symbol `reversed', the first `C-a' or `C-e' works
1174 normally, going to the true line boundary first. Only a directly
1175 following, identical keypress will bring the cursor to the
1176 special positions.
1178 This may also be a cons cell where the behavior for `C-a' and
1179 `C-e' is set separately."
1180 :group 'org-edit-structure
1181 :type '(choice
1182 (const :tag "off" nil)
1183 (const :tag "on: after stars/bullet and before tags first" t)
1184 (const :tag "reversed: true line boundary first" reversed)
1185 (cons :tag "Set C-a and C-e separately"
1186 (choice :tag "Special C-a"
1187 (const :tag "off" nil)
1188 (const :tag "on: after stars/bullet first" t)
1189 (const :tag "reversed: before stars/bullet first" reversed))
1190 (choice :tag "Special C-e"
1191 (const :tag "off" nil)
1192 (const :tag "on: before tags first" t)
1193 (const :tag "reversed: after tags first" reversed)))))
1194 (if (fboundp 'defvaralias)
1195 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1197 (defcustom org-special-ctrl-k nil
1198 "Non-nil means `C-k' will behave specially in headlines.
1199 When nil, `C-k' will call the default `kill-line' command.
1200 When t, the following will happen while the cursor is in the headline:
1202 - When the cursor is at the beginning of a headline, kill the entire
1203 line and possible the folded subtree below the line.
1204 - When in the middle of the headline text, kill the headline up to the tags.
1205 - When after the headline text, kill the tags."
1206 :group 'org-edit-structure
1207 :type 'boolean)
1209 (defcustom org-ctrl-k-protect-subtree nil
1210 "Non-nil means, do not delete a hidden subtree with C-k.
1211 When set to the symbol `error', simply throw an error when C-k is
1212 used to kill (part-of) a headline that has hidden text behind it.
1213 Any other non-nil value will result in a query to the user, if it is
1214 OK to kill that hidden subtree. When nil, kill without remorse."
1215 :group 'org-edit-structure
1216 :version "24.1"
1217 :type '(choice
1218 (const :tag "Do not protect hidden subtrees" nil)
1219 (const :tag "Protect hidden subtrees with a security query" t)
1220 (const :tag "Never kill a hidden subtree with C-k" error)))
1222 (defcustom org-catch-invisible-edits nil
1223 "Check if in invisible region before inserting or deleting a character.
1224 Valid values are:
1226 nil Do not check, so just do invisible edits.
1227 error Throw an error and do nothing.
1228 show Make point visible, and do the requested edit.
1229 show-and-error Make point visible, then throw an error and abort the edit.
1230 smart Make point visible, and do insertion/deletion if it is
1231 adjacent to visible text and the change feels predictable.
1232 Never delete a previously invisible character or add in the
1233 middle or right after an invisible region. Basically, this
1234 allows insertion and backward-delete right before ellipses.
1235 FIXME: maybe in this case we should not even show?"
1236 :group 'org-edit-structure
1237 :version "24.1"
1238 :type '(choice
1239 (const :tag "Do not check" nil)
1240 (const :tag "Throw error when trying to edit" error)
1241 (const :tag "Unhide, but do not do the edit" show-and-error)
1242 (const :tag "Show invisible part and do the edit" show)
1243 (const :tag "Be smart and do the right thing" smart)))
1245 (defcustom org-yank-folded-subtrees t
1246 "Non-nil means when yanking subtrees, fold them.
1247 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1248 it starts with a heading and all other headings in it are either children
1249 or siblings, then fold all the subtrees. However, do this only if no
1250 text after the yank would be swallowed into a folded tree by this action."
1251 :group 'org-edit-structure
1252 :type 'boolean)
1254 (defcustom org-yank-adjusted-subtrees nil
1255 "Non-nil means when yanking subtrees, adjust the level.
1256 With this setting, `org-paste-subtree' is used to insert the subtree, see
1257 this function for details."
1258 :group 'org-edit-structure
1259 :type 'boolean)
1261 (defcustom org-M-RET-may-split-line '((default . t))
1262 "Non-nil means M-RET will split the line at the cursor position.
1263 When nil, it will go to the end of the line before making a
1264 new line.
1265 You may also set this option in a different way for different
1266 contexts. Valid contexts are:
1268 headline when creating a new headline
1269 item when creating a new item
1270 table in a table field
1271 default the value to be used for all contexts not explicitly
1272 customized"
1273 :group 'org-structure
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "Always" t)
1277 (const :tag "Never" nil)
1278 (repeat :greedy t :tag "Individual contexts"
1279 (cons
1280 (choice :tag "Context"
1281 (const headline)
1282 (const item)
1283 (const table)
1284 (const default))
1285 (boolean)))))
1288 (defcustom org-insert-heading-respect-content nil
1289 "Non-nil means insert new headings after the current subtree.
1290 When nil, the new heading is created directly after the current line.
1291 The commands \\[org-insert-heading-respect-content] and
1292 \\[org-insert-todo-heading-respect-content] turn this variable on
1293 for the duration of the command."
1294 :group 'org-structure
1295 :type 'boolean)
1297 (defcustom org-blank-before-new-entry '((heading . auto)
1298 (plain-list-item . auto))
1299 "Should `org-insert-heading' leave a blank line before new heading/item?
1300 The value is an alist, with `heading' and `plain-list-item' as CAR,
1301 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1302 which case Org will look at the surrounding headings/items and try to
1303 make an intelligent decision whether to insert a blank line or not.
1305 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1306 set, the setting here is ignored and no empty line is inserted, to avoid
1307 breaking the list structure."
1308 :group 'org-edit-structure
1309 :type '(list
1310 (cons (const heading)
1311 (choice (const :tag "Never" nil)
1312 (const :tag "Always" t)
1313 (const :tag "Auto" auto)))
1314 (cons (const plain-list-item)
1315 (choice (const :tag "Never" nil)
1316 (const :tag "Always" t)
1317 (const :tag "Auto" auto)))))
1319 (defcustom org-insert-heading-hook nil
1320 "Hook being run after inserting a new heading."
1321 :group 'org-edit-structure
1322 :type 'hook)
1324 (defcustom org-enable-fixed-width-editor t
1325 "Non-nil means lines starting with \":\" are treated as fixed-width.
1326 This currently only means they are never auto-wrapped.
1327 When nil, such lines will be treated like ordinary lines.
1328 See also the QUOTE keyword."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-goto-auto-isearch t
1333 "Non-nil means typing characters in `org-goto' starts incremental search.
1334 When nil, you can use these keybindings to navigate the buffer:
1336 q Quit the org-goto interface
1337 n Go to the next visible heading
1338 p Go to the previous visible heading
1339 f Go one heading forward on same level
1340 b Go one heading backward on same level
1341 u Go one heading up"
1342 :group 'org-edit-structure
1343 :type 'boolean)
1345 (defgroup org-sparse-trees nil
1346 "Options concerning sparse trees in Org-mode."
1347 :tag "Org Sparse Trees"
1348 :group 'org-structure)
1350 (defcustom org-highlight-sparse-tree-matches t
1351 "Non-nil means highlight all matches that define a sparse tree.
1352 The highlights will automatically disappear the next time the buffer is
1353 changed by an edit command."
1354 :group 'org-sparse-trees
1355 :type 'boolean)
1357 (defcustom org-remove-highlights-with-change t
1358 "Non-nil means any change to the buffer will remove temporary highlights.
1359 Such highlights are created by `org-occur' and `org-clock-display'.
1360 When nil, `C-c C-c needs to be used to get rid of the highlights.
1361 The highlights created by `org-preview-latex-fragment' always need
1362 `C-c C-c' to be removed."
1363 :group 'org-sparse-trees
1364 :group 'org-time
1365 :type 'boolean)
1368 (defcustom org-occur-hook '(org-first-headline-recenter)
1369 "Hook that is run after `org-occur' has constructed a sparse tree.
1370 This can be used to recenter the window to show as much of the structure
1371 as possible."
1372 :group 'org-sparse-trees
1373 :type 'hook)
1375 (defgroup org-imenu-and-speedbar nil
1376 "Options concerning imenu and speedbar in Org-mode."
1377 :tag "Org Imenu and Speedbar"
1378 :group 'org-structure)
1380 (defcustom org-imenu-depth 2
1381 "The maximum level for Imenu access to Org-mode headlines.
1382 This also applied for speedbar access."
1383 :group 'org-imenu-and-speedbar
1384 :type 'integer)
1386 (defgroup org-table nil
1387 "Options concerning tables in Org-mode."
1388 :tag "Org Table"
1389 :group 'org)
1391 (defcustom org-enable-table-editor 'optimized
1392 "Non-nil means lines starting with \"|\" are handled by the table editor.
1393 When nil, such lines will be treated like ordinary lines.
1395 When equal to the symbol `optimized', the table editor will be optimized to
1396 do the following:
1397 - Automatic overwrite mode in front of whitespace in table fields.
1398 This makes the structure of the table stay in tact as long as the edited
1399 field does not exceed the column width.
1400 - Minimize the number of realigns. Normally, the table is aligned each time
1401 TAB or RET are pressed to move to another field. With optimization this
1402 happens only if changes to a field might have changed the column width.
1403 Optimization requires replacing the functions `self-insert-command',
1404 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1405 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1406 very good at guessing when a re-align will be necessary, but you can always
1407 force one with \\[org-ctrl-c-ctrl-c].
1409 If you would like to use the optimized version in Org-mode, but the
1410 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1412 This variable can be used to turn on and off the table editor during a session,
1413 but in order to toggle optimization, a restart is required.
1415 See also the variable `org-table-auto-blank-field'."
1416 :group 'org-table
1417 :type '(choice
1418 (const :tag "off" nil)
1419 (const :tag "on" t)
1420 (const :tag "on, optimized" optimized)))
1422 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1423 (version<= emacs-version "24.1"))
1424 "Non-nil means cluster self-insert commands for undo when possible.
1425 If this is set, then, like in the Emacs command loop, 20 consecutive
1426 characters will be undone together.
1427 This is configurable, because there is some impact on typing performance."
1428 :group 'org-table
1429 :type 'boolean)
1431 (defcustom org-table-tab-recognizes-table.el t
1432 "Non-nil means TAB will automatically notice a table.el table.
1433 When it sees such a table, it moves point into it and - if necessary -
1434 calls `table-recognize-table'."
1435 :group 'org-table-editing
1436 :type 'boolean)
1438 (defgroup org-link nil
1439 "Options concerning links in Org-mode."
1440 :tag "Org Link"
1441 :group 'org)
1443 (defvar org-link-abbrev-alist-local nil
1444 "Buffer-local version of `org-link-abbrev-alist', which see.
1445 The value of this is taken from the #+LINK lines.")
1446 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1448 (defcustom org-link-abbrev-alist nil
1449 "Alist of link abbreviations.
1450 The car of each element is a string, to be replaced at the start of a link.
1451 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1452 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1454 [[linkkey:tag][description]]
1456 The 'linkkey' must be a word word, starting with a letter, followed
1457 by letters, numbers, '-' or '_'.
1459 If REPLACE is a string, the tag will simply be appended to create the link.
1460 If the string contains \"%s\", the tag will be inserted there. If the string
1461 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1462 at that point (see the function `url-hexify-string'). If the string contains
1463 the specifier \"%(my-function)\", then the custom function `my-function' will
1464 be invoked: this function takes the tag as its only argument and must return
1465 a string.
1467 REPLACE may also be a function that will be called with the tag as the
1468 only argument to create the link, which should be returned as a string.
1470 See the manual for examples."
1471 :group 'org-link
1472 :type '(repeat
1473 (cons
1474 (string :tag "Protocol")
1475 (choice
1476 (string :tag "Format")
1477 (function)))))
1479 (defcustom org-descriptive-links t
1480 "Non-nil means Org will display descriptive links.
1481 E.g. [[http://orgmode.org][Org website]] will be displayed as
1482 \"Org Website\", hiding the link itself and just displaying its
1483 description. When set to `nil', Org will display the full links
1484 literally.
1486 You can interactively set the value of this variable by calling
1487 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1488 :group 'org-link
1489 :type 'boolean)
1491 (defcustom org-link-file-path-type 'adaptive
1492 "How the path name in file links should be stored.
1493 Valid values are:
1495 relative Relative to the current directory, i.e. the directory of the file
1496 into which the link is being inserted.
1497 absolute Absolute path, if possible with ~ for home directory.
1498 noabbrev Absolute path, no abbreviation of home directory.
1499 adaptive Use relative path for files in the current directory and sub-
1500 directories of it. For other files, use an absolute path."
1501 :group 'org-link
1502 :type '(choice
1503 (const relative)
1504 (const absolute)
1505 (const noabbrev)
1506 (const adaptive)))
1508 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1509 "Types of links that should be activated in Org-mode files.
1510 This is a list of symbols, each leading to the activation of a certain link
1511 type. In principle, it does not hurt to turn on most link types - there may
1512 be a small gain when turning off unused link types. The types are:
1514 bracket The recommended [[link][description]] or [[link]] links with hiding.
1515 angle Links in angular brackets that may contain whitespace like
1516 <bbdb:Carsten Dominik>.
1517 plain Plain links in normal text, no whitespace, like http://google.com.
1518 radio Text that is matched by a radio target, see manual for details.
1519 tag Tag settings in a headline (link to tag search).
1520 date Time stamps (link to calendar).
1521 footnote Footnote labels.
1523 Changing this variable requires a restart of Emacs to become effective."
1524 :group 'org-link
1525 :type '(set :greedy t
1526 (const :tag "Double bracket links" bracket)
1527 (const :tag "Angular bracket links" angle)
1528 (const :tag "Plain text links" plain)
1529 (const :tag "Radio target matches" radio)
1530 (const :tag "Tags" tag)
1531 (const :tag "Timestamps" date)
1532 (const :tag "Footnotes" footnote)))
1534 (defcustom org-make-link-description-function nil
1535 "Function to use for generating link descriptions from links.
1536 When nil, the link location will be used. This function must take
1537 two parameters: the first one is the link, the second one is the
1538 description generated by `org-insert-link'. The function should
1539 return the description to use."
1540 :group 'org-link
1541 :type 'function)
1543 (defgroup org-link-store nil
1544 "Options concerning storing links in Org-mode."
1545 :tag "Org Store Link"
1546 :group 'org-link)
1548 (defcustom org-url-hexify-p t
1549 "When non-nil, hexify URL when creating a link."
1550 :type 'boolean
1551 :version "24.3"
1552 :group 'org-link-store)
1554 (defcustom org-email-link-description-format "Email %c: %.30s"
1555 "Format of the description part of a link to an email or usenet message.
1556 The following %-escapes will be replaced by corresponding information:
1558 %F full \"From\" field
1559 %f name, taken from \"From\" field, address if no name
1560 %T full \"To\" field
1561 %t first name in \"To\" field, address if no name
1562 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1563 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1564 %s subject
1565 %d date
1566 %m message-id.
1568 You may use normal field width specification between the % and the letter.
1569 This is for example useful to limit the length of the subject.
1571 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1572 :group 'org-link-store
1573 :type 'string)
1575 (defcustom org-from-is-user-regexp
1576 (let (r1 r2)
1577 (when (and user-mail-address (not (string= user-mail-address "")))
1578 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1579 (when (and user-full-name (not (string= user-full-name "")))
1580 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1581 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1582 "Regexp matched against the \"From:\" header of an email or usenet message.
1583 It should match if the message is from the user him/herself."
1584 :group 'org-link-store
1585 :type 'regexp)
1587 (defcustom org-context-in-file-links t
1588 "Non-nil means file links from `org-store-link' contain context.
1589 A search string will be added to the file name with :: as separator and
1590 used to find the context when the link is activated by the command
1591 `org-open-at-point'. When this option is t, the entire active region
1592 will be placed in the search string of the file link. If set to a
1593 positive integer, only the first n lines of context will be stored.
1595 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1596 negates this setting for the duration of the command."
1597 :group 'org-link-store
1598 :type '(choice boolean integer))
1600 (defcustom org-keep-stored-link-after-insertion nil
1601 "Non-nil means keep link in list for entire session.
1603 The command `org-store-link' adds a link pointing to the current
1604 location to an internal list. These links accumulate during a session.
1605 The command `org-insert-link' can be used to insert links into any
1606 Org-mode file (offering completion for all stored links). When this
1607 option is nil, every link which has been inserted once using \\[org-insert-link]
1608 will be removed from the list, to make completing the unused links
1609 more efficient."
1610 :group 'org-link-store
1611 :type 'boolean)
1613 (defgroup org-link-follow nil
1614 "Options concerning following links in Org-mode."
1615 :tag "Org Follow Link"
1616 :group 'org-link)
1618 (defcustom org-link-translation-function nil
1619 "Function to translate links with different syntax to Org syntax.
1620 This can be used to translate links created for example by the Planner
1621 or emacs-wiki packages to Org syntax.
1622 The function must accept two parameters, a TYPE containing the link
1623 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1624 which is everything after the link protocol. It should return a cons
1625 with possibly modified values of type and path.
1626 Org contains a function for this, so if you set this variable to
1627 `org-translate-link-from-planner', you should be able follow many
1628 links created by planner."
1629 :group 'org-link-follow
1630 :type 'function)
1632 (defcustom org-follow-link-hook nil
1633 "Hook that is run after a link has been followed."
1634 :group 'org-link-follow
1635 :type 'hook)
1637 (defcustom org-tab-follows-link nil
1638 "Non-nil means on links TAB will follow the link.
1639 Needs to be set before org.el is loaded.
1640 This really should not be used, it does not make sense, and the
1641 implementation is bad."
1642 :group 'org-link-follow
1643 :type 'boolean)
1645 (defcustom org-return-follows-link nil
1646 "Non-nil means on links RET will follow the link."
1647 :group 'org-link-follow
1648 :type 'boolean)
1650 (defcustom org-mouse-1-follows-link
1651 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1652 "Non-nil means mouse-1 on a link will follow the link.
1653 A longer mouse click will still set point. Does not work on XEmacs.
1654 Needs to be set before org.el is loaded."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-mark-ring-length 4
1659 "Number of different positions to be recorded in the ring.
1660 Changing this requires a restart of Emacs to work correctly."
1661 :group 'org-link-follow
1662 :type 'integer)
1664 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1665 "Non-nil means internal links in Org files must exactly match a headline.
1666 When nil, the link search tries to match a phrase with all words
1667 in the search text."
1668 :group 'org-link-follow
1669 :version "24.1"
1670 :type '(choice
1671 (const :tag "Use fuzzy text search" nil)
1672 (const :tag "Match only exact headline" t)
1673 (const :tag "Match exact headline or query to create it"
1674 query-to-create)))
1676 (defcustom org-link-frame-setup
1677 '((vm . vm-visit-folder-other-frame)
1678 (vm-imap . vm-visit-imap-folder-other-frame)
1679 (gnus . org-gnus-no-new-news)
1680 (file . find-file-other-window)
1681 (wl . wl-other-frame))
1682 "Setup the frame configuration for following links.
1683 When following a link with Emacs, it may often be useful to display
1684 this link in another window or frame. This variable can be used to
1685 set this up for the different types of links.
1686 For VM, use any of
1687 `vm-visit-folder'
1688 `vm-visit-folder-other-window'
1689 `vm-visit-folder-other-frame'
1690 For Gnus, use any of
1691 `gnus'
1692 `gnus-other-frame'
1693 `org-gnus-no-new-news'
1694 For FILE, use any of
1695 `find-file'
1696 `find-file-other-window'
1697 `find-file-other-frame'
1698 For Wanderlust use any of
1699 `wl'
1700 `wl-other-frame'
1701 For the calendar, use the variable `calendar-setup'.
1702 For BBDB, it is currently only possible to display the matches in
1703 another window."
1704 :group 'org-link-follow
1705 :type '(list
1706 (cons (const vm)
1707 (choice
1708 (const vm-visit-folder)
1709 (const vm-visit-folder-other-window)
1710 (const vm-visit-folder-other-frame)))
1711 (cons (const gnus)
1712 (choice
1713 (const gnus)
1714 (const gnus-other-frame)
1715 (const org-gnus-no-new-news)))
1716 (cons (const file)
1717 (choice
1718 (const find-file)
1719 (const find-file-other-window)
1720 (const find-file-other-frame)))
1721 (cons (const wl)
1722 (choice
1723 (const wl)
1724 (const wl-other-frame)))))
1726 (defcustom org-display-internal-link-with-indirect-buffer nil
1727 "Non-nil means use indirect buffer to display infile links.
1728 Activating internal links (from one location in a file to another location
1729 in the same file) normally just jumps to the location. When the link is
1730 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1731 is displayed in
1732 another window. When this option is set, the other window actually displays
1733 an indirect buffer clone of the current buffer, to avoid any visibility
1734 changes to the current buffer."
1735 :group 'org-link-follow
1736 :type 'boolean)
1738 (defcustom org-open-non-existing-files nil
1739 "Non-nil means `org-open-file' will open non-existing files.
1740 When nil, an error will be generated.
1741 This variable applies only to external applications because they
1742 might choke on non-existing files. If the link is to a file that
1743 will be opened in Emacs, the variable is ignored."
1744 :group 'org-link-follow
1745 :type 'boolean)
1747 (defcustom org-open-directory-means-index-dot-org nil
1748 "Non-nil means a link to a directory really means to index.org.
1749 When nil, following a directory link will run dired or open a finder/explorer
1750 window on that directory."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1755 "Function and arguments to call for following mailto links.
1756 This is a list with the first element being a Lisp function, and the
1757 remaining elements being arguments to the function. In string arguments,
1758 %a will be replaced by the address, and %s will be replaced by the subject
1759 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1760 :group 'org-link-follow
1761 :type '(choice
1762 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1763 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1764 (const :tag "message-mail" (message-mail "%a" "%s"))
1765 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1767 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1768 "Non-nil means ask for confirmation before executing shell links.
1769 Shell links can be dangerous: just think about a link
1771 [[shell:rm -rf ~/*][Google Search]]
1773 This link would show up in your Org-mode document as \"Google Search\",
1774 but really it would remove your entire home directory.
1775 Therefore we advise against setting this variable to nil.
1776 Just change it to `y-or-n-p' if you want to confirm with a
1777 single keystroke rather than having to type \"yes\"."
1778 :group 'org-link-follow
1779 :type '(choice
1780 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1781 (const :tag "with y-or-n (faster)" y-or-n-p)
1782 (const :tag "no confirmation (dangerous)" nil)))
1783 (put 'org-confirm-shell-link-function
1784 'safe-local-variable
1785 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1787 (defcustom org-confirm-shell-link-not-regexp ""
1788 "A regexp to skip confirmation for shell links."
1789 :group 'org-link-follow
1790 :version "24.1"
1791 :type 'regexp)
1793 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1794 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1795 Elisp links can be dangerous: just think about a link
1797 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1799 This link would show up in your Org-mode document as \"Google Search\",
1800 but really it would remove your entire home directory.
1801 Therefore we advise against setting this variable to nil.
1802 Just change it to `y-or-n-p' if you want to confirm with a
1803 single keystroke rather than having to type \"yes\"."
1804 :group 'org-link-follow
1805 :type '(choice
1806 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1807 (const :tag "with y-or-n (faster)" y-or-n-p)
1808 (const :tag "no confirmation (dangerous)" nil)))
1809 (put 'org-confirm-shell-link-function
1810 'safe-local-variable
1811 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1813 (defcustom org-confirm-elisp-link-not-regexp ""
1814 "A regexp to skip confirmation for Elisp links."
1815 :group 'org-link-follow
1816 :version "24.1"
1817 :type 'regexp)
1819 (defconst org-file-apps-defaults-gnu
1820 '((remote . emacs)
1821 (system . mailcap)
1822 (t . mailcap))
1823 "Default file applications on a UNIX or GNU/Linux system.
1824 See `org-file-apps'.")
1826 (defconst org-file-apps-defaults-macosx
1827 '((remote . emacs)
1828 (t . "open %s")
1829 (system . "open %s")
1830 ("ps.gz" . "gv %s")
1831 ("eps.gz" . "gv %s")
1832 ("dvi" . "xdvi %s")
1833 ("fig" . "xfig %s"))
1834 "Default file applications on a MacOS X system.
1835 The system \"open\" is known as a default, but we use X11 applications
1836 for some files for which the OS does not have a good default.
1837 See `org-file-apps'.")
1839 (defconst org-file-apps-defaults-windowsnt
1840 (list
1841 '(remote . emacs)
1842 (cons t
1843 (list (if (featurep 'xemacs)
1844 'mswindows-shell-execute
1845 'w32-shell-execute)
1846 "open" 'file))
1847 (cons 'system
1848 (list (if (featurep 'xemacs)
1849 'mswindows-shell-execute
1850 'w32-shell-execute)
1851 "open" 'file)))
1852 "Default file applications on a Windows NT system.
1853 The system \"open\" is used for most files.
1854 See `org-file-apps'.")
1856 (defcustom org-file-apps
1858 (auto-mode . emacs)
1859 ("\\.mm\\'" . default)
1860 ("\\.x?html?\\'" . default)
1861 ("\\.pdf\\'" . default)
1863 "External applications for opening `file:path' items in a document.
1864 Org-mode uses system defaults for different file types, but
1865 you can use this variable to set the application for a given file
1866 extension. The entries in this list are cons cells where the car identifies
1867 files and the cdr the corresponding command. Possible values for the
1868 file identifier are
1869 \"string\" A string as a file identifier can be interpreted in different
1870 ways, depending on its contents:
1872 - Alphanumeric characters only:
1873 Match links with this file extension.
1874 Example: (\"pdf\" . \"evince %s\")
1875 to open PDFs with evince.
1877 - Regular expression: Match links where the
1878 filename matches the regexp. If you want to
1879 use groups here, use shy groups.
1881 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1882 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1883 to open *.html and *.xhtml with firefox.
1885 - Regular expression which contains (non-shy) groups:
1886 Match links where the whole link, including \"::\", and
1887 anything after that, matches the regexp.
1888 In a custom command string, %1, %2, etc. are replaced with
1889 the parts of the link that were matched by the groups.
1890 For backwards compatibility, if a command string is given
1891 that does not use any of the group matches, this case is
1892 handled identically to the second one (i.e. match against
1893 file name only).
1894 In a custom lisp form, you can access the group matches with
1895 (match-string n link).
1897 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1898 to open [[file:document.pdf::5]] with evince at page 5.
1900 `directory' Matches a directory
1901 `remote' Matches a remote file, accessible through tramp or efs.
1902 Remote files most likely should be visited through Emacs
1903 because external applications cannot handle such paths.
1904 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1905 so all files Emacs knows how to handle. Using this with
1906 command `emacs' will open most files in Emacs. Beware that this
1907 will also open html files inside Emacs, unless you add
1908 (\"html\" . default) to the list as well.
1909 t Default for files not matched by any of the other options.
1910 `system' The system command to open files, like `open' on Windows
1911 and Mac OS X, and mailcap under GNU/Linux. This is the command
1912 that will be selected if you call `C-c C-o' with a double
1913 \\[universal-argument] \\[universal-argument] prefix.
1915 Possible values for the command are:
1916 `emacs' The file will be visited by the current Emacs process.
1917 `default' Use the default application for this file type, which is the
1918 association for t in the list, most likely in the system-specific
1919 part.
1920 This can be used to overrule an unwanted setting in the
1921 system-specific variable.
1922 `system' Use the system command for opening files, like \"open\".
1923 This command is specified by the entry whose car is `system'.
1924 Most likely, the system-specific version of this variable
1925 does define this command, but you can overrule/replace it
1926 here.
1927 string A command to be executed by a shell; %s will be replaced
1928 by the path to the file.
1929 sexp A Lisp form which will be evaluated. The file path will
1930 be available in the Lisp variable `file'.
1931 For more examples, see the system specific constants
1932 `org-file-apps-defaults-macosx'
1933 `org-file-apps-defaults-windowsnt'
1934 `org-file-apps-defaults-gnu'."
1935 :group 'org-link-follow
1936 :type '(repeat
1937 (cons (choice :value ""
1938 (string :tag "Extension")
1939 (const :tag "System command to open files" system)
1940 (const :tag "Default for unrecognized files" t)
1941 (const :tag "Remote file" remote)
1942 (const :tag "Links to a directory" directory)
1943 (const :tag "Any files that have Emacs modes"
1944 auto-mode))
1945 (choice :value ""
1946 (const :tag "Visit with Emacs" emacs)
1947 (const :tag "Use default" default)
1948 (const :tag "Use the system command" system)
1949 (string :tag "Command")
1950 (sexp :tag "Lisp form")))))
1952 (defcustom org-doi-server-url "http://dx.doi.org/"
1953 "The URL of the DOI server."
1954 :type 'string
1955 :version "24.3"
1956 :group 'org-link-follow)
1958 (defgroup org-refile nil
1959 "Options concerning refiling entries in Org-mode."
1960 :tag "Org Refile"
1961 :group 'org)
1963 (defcustom org-directory "~/org"
1964 "Directory with org files.
1965 This is just a default location to look for Org files. There is no need
1966 at all to put your files into this directory. It is only used in the
1967 following situations:
1969 1. When a capture template specifies a target file that is not an
1970 absolute path. The path will then be interpreted relative to
1971 `org-directory'
1972 2. When a capture note is filed away in an interactive way (when exiting the
1973 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1974 with `org-directory' as the default path."
1975 :group 'org-refile
1976 :group 'org-remember
1977 :group 'org-capture
1978 :type 'directory)
1980 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1981 "Default target for storing notes.
1982 Used as a fall back file for org-remember.el and org-capture.el, for
1983 templates that do not specify a target file."
1984 :group 'org-refile
1985 :group 'org-remember
1986 :group 'org-capture
1987 :type '(choice
1988 (const :tag "Default from remember-data-file" nil)
1989 file))
1991 (defcustom org-goto-interface 'outline
1992 "The default interface to be used for `org-goto'.
1993 Allowed values are:
1994 outline The interface shows an outline of the relevant file
1995 and the correct heading is found by moving through
1996 the outline or by searching with incremental search.
1997 outline-path-completion Headlines in the current buffer are offered via
1998 completion. This is the interface also used by
1999 the refile command."
2000 :group 'org-refile
2001 :type '(choice
2002 (const :tag "Outline" outline)
2003 (const :tag "Outline-path-completion" outline-path-completion)))
2005 (defcustom org-goto-max-level 5
2006 "Maximum target level when running `org-goto' with refile interface."
2007 :group 'org-refile
2008 :type 'integer)
2010 (defcustom org-reverse-note-order nil
2011 "Non-nil means store new notes at the beginning of a file or entry.
2012 When nil, new notes will be filed to the end of a file or entry.
2013 This can also be a list with cons cells of regular expressions that
2014 are matched against file names, and values."
2015 :group 'org-remember
2016 :group 'org-capture
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Reverse always" t)
2020 (const :tag "Reverse never" nil)
2021 (repeat :tag "By file name regexp"
2022 (cons regexp boolean))))
2024 (defcustom org-log-refile nil
2025 "Information to record when a task is refiled.
2027 Possible values are:
2029 nil Don't add anything
2030 time Add a time stamp to the task
2031 note Prompt for a note and add it with template `org-log-note-headings'
2033 This option can also be set with on a per-file-basis with
2035 #+STARTUP: nologrefile
2036 #+STARTUP: logrefile
2037 #+STARTUP: lognoterefile
2039 You can have local logging settings for a subtree by setting the LOGGING
2040 property to one or more of these keywords.
2042 When bulk-refiling from the agenda, the value `note' is forbidden and
2043 will temporarily be changed to `time'."
2044 :group 'org-refile
2045 :group 'org-progress
2046 :version "24.1"
2047 :type '(choice
2048 (const :tag "No logging" nil)
2049 (const :tag "Record timestamp" time)
2050 (const :tag "Record timestamp with note." note)))
2052 (defcustom org-refile-targets nil
2053 "Targets for refiling entries with \\[org-refile].
2054 This is a list of cons cells. Each cell contains:
2055 - a specification of the files to be considered, either a list of files,
2056 or a symbol whose function or variable value will be used to retrieve
2057 a file name or a list of file names. If you use `org-agenda-files' for
2058 that, all agenda files will be scanned for targets. Nil means consider
2059 headings in the current buffer.
2060 - A specification of how to find candidate refile targets. This may be
2061 any of:
2062 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2063 This tag has to be present in all target headlines, inheritance will
2064 not be considered.
2065 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2066 todo keyword.
2067 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2068 headlines that are refiling targets.
2069 - a cons cell (:level . N). Any headline of level N is considered a target.
2070 Note that, when `org-odd-levels-only' is set, level corresponds to
2071 order in hierarchy, not to the number of stars.
2072 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2073 Note that, when `org-odd-levels-only' is set, level corresponds to
2074 order in hierarchy, not to the number of stars.
2076 Each element of this list generates a set of possible targets.
2077 The union of these sets is presented (with completion) to
2078 the user by `org-refile'.
2080 You can set the variable `org-refile-target-verify-function' to a function
2081 to verify each headline found by the simple criteria above.
2083 When this variable is nil, all top-level headlines in the current buffer
2084 are used, equivalent to the value `((nil . (:level . 1))'."
2085 :group 'org-refile
2086 :type '(repeat
2087 (cons
2088 (choice :value org-agenda-files
2089 (const :tag "All agenda files" org-agenda-files)
2090 (const :tag "Current buffer" nil)
2091 (function) (variable) (file))
2092 (choice :tag "Identify target headline by"
2093 (cons :tag "Specific tag" (const :value :tag) (string))
2094 (cons :tag "TODO keyword" (const :value :todo) (string))
2095 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2096 (cons :tag "Level number" (const :value :level) (integer))
2097 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2099 (defcustom org-refile-target-verify-function nil
2100 "Function to verify if the headline at point should be a refile target.
2101 The function will be called without arguments, with point at the
2102 beginning of the headline. It should return t and leave point
2103 where it is if the headline is a valid target for refiling.
2105 If the target should not be selected, the function must return nil.
2106 In addition to this, it may move point to a place from where the search
2107 should be continued. For example, the function may decide that the entire
2108 subtree of the current entry should be excluded and move point to the end
2109 of the subtree."
2110 :group 'org-refile
2111 :type 'function)
2113 (defcustom org-refile-use-cache nil
2114 "Non-nil means cache refile targets to speed up the process.
2115 The cache for a particular file will be updated automatically when
2116 the buffer has been killed, or when any of the marker used for flagging
2117 refile targets no longer points at a live buffer.
2118 If you have added new entries to a buffer that might themselves be targets,
2119 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2120 find that easier, `C-u C-u C-u C-c C-w'."
2121 :group 'org-refile
2122 :version "24.1"
2123 :type 'boolean)
2125 (defcustom org-refile-use-outline-path nil
2126 "Non-nil means provide refile targets as paths.
2127 So a level 3 headline will be available as level1/level2/level3.
2129 When the value is `file', also include the file name (without directory)
2130 into the path. In this case, you can also stop the completion after
2131 the file name, to get entries inserted as top level in the file.
2133 When `full-file-path', include the full file path."
2134 :group 'org-refile
2135 :type '(choice
2136 (const :tag "Not" nil)
2137 (const :tag "Yes" t)
2138 (const :tag "Start with file name" file)
2139 (const :tag "Start with full file path" full-file-path)))
2141 (defcustom org-outline-path-complete-in-steps t
2142 "Non-nil means complete the outline path in hierarchical steps.
2143 When Org-mode uses the refile interface to select an outline path
2144 \(see variable `org-refile-use-outline-path'), the completion of
2145 the path can be done is a single go, or if can be done in steps down
2146 the headline hierarchy. Going in steps is probably the best if you
2147 do not use a special completion package like `ido' or `icicles'.
2148 However, when using these packages, going in one step can be very
2149 fast, while still showing the whole path to the entry."
2150 :group 'org-refile
2151 :type 'boolean)
2153 (defcustom org-refile-allow-creating-parent-nodes nil
2154 "Non-nil means allow to create new nodes as refile targets.
2155 New nodes are then created by adding \"/new node name\" to the completion
2156 of an existing node. When the value of this variable is `confirm',
2157 new node creation must be confirmed by the user (recommended)
2158 When nil, the completion must match an existing entry.
2160 Note that, if the new heading is not seen by the criteria
2161 listed in `org-refile-targets', multiple instances of the same
2162 heading would be created by trying again to file under the new
2163 heading."
2164 :group 'org-refile
2165 :type '(choice
2166 (const :tag "Never" nil)
2167 (const :tag "Always" t)
2168 (const :tag "Prompt for confirmation" confirm)))
2170 (defcustom org-refile-active-region-within-subtree nil
2171 "Non-nil means also refile active region within a subtree.
2173 By default `org-refile' doesn't allow refiling regions if they
2174 don't contain a set of subtrees, but it might be convenient to
2175 do so sometimes: in that case, the first line of the region is
2176 converted to a headline before refiling."
2177 :group 'org-refile
2178 :version "24.1"
2179 :type 'boolean)
2181 (defgroup org-todo nil
2182 "Options concerning TODO items in Org-mode."
2183 :tag "Org TODO"
2184 :group 'org)
2186 (defgroup org-progress nil
2187 "Options concerning Progress logging in Org-mode."
2188 :tag "Org Progress"
2189 :group 'org-time)
2191 (defvar org-todo-interpretation-widgets
2192 '((:tag "Sequence (cycling hits every state)" sequence)
2193 (:tag "Type (cycling directly to DONE)" type))
2194 "The available interpretation symbols for customizing `org-todo-keywords'.
2195 Interested libraries should add to this list.")
2197 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2198 "List of TODO entry keyword sequences and their interpretation.
2199 \\<org-mode-map>This is a list of sequences.
2201 Each sequence starts with a symbol, either `sequence' or `type',
2202 indicating if the keywords should be interpreted as a sequence of
2203 action steps, or as different types of TODO items. The first
2204 keywords are states requiring action - these states will select a headline
2205 for inclusion into the global TODO list Org-mode produces. If one of
2206 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2207 signify that no further action is necessary. If \"|\" is not found,
2208 the last keyword is treated as the only DONE state of the sequence.
2210 The command \\[org-todo] cycles an entry through these states, and one
2211 additional state where no keyword is present. For details about this
2212 cycling, see the manual.
2214 TODO keywords and interpretation can also be set on a per-file basis with
2215 the special #+SEQ_TODO and #+TYP_TODO lines.
2217 Each keyword can optionally specify a character for fast state selection
2218 \(in combination with the variable `org-use-fast-todo-selection')
2219 and specifiers for state change logging, using the same syntax that
2220 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2221 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2222 indicates to record a time stamp each time this state is selected.
2224 Each keyword may also specify if a timestamp or a note should be
2225 recorded when entering or leaving the state, by adding additional
2226 characters in the parenthesis after the keyword. This looks like this:
2227 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2228 record only the time of the state change. With X and Y being either
2229 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2230 Y when leaving the state if and only if the *target* state does not
2231 define X. You may omit any of the fast-selection key or X or /Y,
2232 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2234 For backward compatibility, this variable may also be just a list
2235 of keywords. In this case the interpretation (sequence or type) will be
2236 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2237 :group 'org-todo
2238 :group 'org-keywords
2239 :type '(choice
2240 (repeat :tag "Old syntax, just keywords"
2241 (string :tag "Keyword"))
2242 (repeat :tag "New syntax"
2243 (cons
2244 (choice
2245 :tag "Interpretation"
2246 ;;Quick and dirty way to see
2247 ;;`org-todo-interpretations'. This takes the
2248 ;;place of item arguments
2249 :convert-widget
2250 (lambda (widget)
2251 (widget-put widget
2252 :args (mapcar
2253 #'(lambda (x)
2254 (widget-convert
2255 (cons 'const x)))
2256 org-todo-interpretation-widgets))
2257 widget))
2258 (repeat
2259 (string :tag "Keyword"))))))
2261 (defvar org-todo-keywords-1 nil
2262 "All TODO and DONE keywords active in a buffer.")
2263 (make-variable-buffer-local 'org-todo-keywords-1)
2264 (defvar org-todo-keywords-for-agenda nil)
2265 (defvar org-done-keywords-for-agenda nil)
2266 (defvar org-drawers-for-agenda nil)
2267 (defvar org-todo-keyword-alist-for-agenda nil)
2268 (defvar org-tag-alist-for-agenda nil)
2269 (defvar org-agenda-contributing-files nil)
2270 (defvar org-not-done-keywords nil)
2271 (make-variable-buffer-local 'org-not-done-keywords)
2272 (defvar org-done-keywords nil)
2273 (make-variable-buffer-local 'org-done-keywords)
2274 (defvar org-todo-heads nil)
2275 (make-variable-buffer-local 'org-todo-heads)
2276 (defvar org-todo-sets nil)
2277 (make-variable-buffer-local 'org-todo-sets)
2278 (defvar org-todo-log-states nil)
2279 (make-variable-buffer-local 'org-todo-log-states)
2280 (defvar org-todo-kwd-alist nil)
2281 (make-variable-buffer-local 'org-todo-kwd-alist)
2282 (defvar org-todo-key-alist nil)
2283 (make-variable-buffer-local 'org-todo-key-alist)
2284 (defvar org-todo-key-trigger nil)
2285 (make-variable-buffer-local 'org-todo-key-trigger)
2287 (defcustom org-todo-interpretation 'sequence
2288 "Controls how TODO keywords are interpreted.
2289 This variable is in principle obsolete and is only used for
2290 backward compatibility, if the interpretation of todo keywords is
2291 not given already in `org-todo-keywords'. See that variable for
2292 more information."
2293 :group 'org-todo
2294 :group 'org-keywords
2295 :type '(choice (const sequence)
2296 (const type)))
2298 (defcustom org-use-fast-todo-selection t
2299 "Non-nil means use the fast todo selection scheme with C-c C-t.
2300 This variable describes if and under what circumstances the cycling
2301 mechanism for TODO keywords will be replaced by a single-key, direct
2302 selection scheme.
2304 When nil, fast selection is never used.
2306 When the symbol `prefix', it will be used when `org-todo' is called
2307 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2308 `C-u t' in an agenda buffer.
2310 When t, fast selection is used by default. In this case, the prefix
2311 argument forces cycling instead.
2313 In all cases, the special interface is only used if access keys have
2314 actually been assigned by the user, i.e. if keywords in the configuration
2315 are followed by a letter in parenthesis, like TODO(t)."
2316 :group 'org-todo
2317 :type '(choice
2318 (const :tag "Never" nil)
2319 (const :tag "By default" t)
2320 (const :tag "Only with C-u C-c C-t" prefix)))
2322 (defcustom org-provide-todo-statistics t
2323 "Non-nil means update todo statistics after insert and toggle.
2324 ALL-HEADLINES means update todo statistics by including headlines
2325 with no TODO keyword as well, counting them as not done.
2326 A list of TODO keywords means the same, but skip keywords that are
2327 not in this list.
2329 When this is set, todo statistics is updated in the parent of the
2330 current entry each time a todo state is changed."
2331 :group 'org-todo
2332 :type '(choice
2333 (const :tag "Yes, only for TODO entries" t)
2334 (const :tag "Yes, including all entries" 'all-headlines)
2335 (repeat :tag "Yes, for TODOs in this list"
2336 (string :tag "TODO keyword"))
2337 (other :tag "No TODO statistics" nil)))
2339 (defcustom org-hierarchical-todo-statistics t
2340 "Non-nil means TODO statistics covers just direct children.
2341 When nil, all entries in the subtree are considered.
2342 This has only an effect if `org-provide-todo-statistics' is set.
2343 To set this to nil for only a single subtree, use a COOKIE_DATA
2344 property and include the word \"recursive\" into the value."
2345 :group 'org-todo
2346 :type 'boolean)
2348 (defcustom org-after-todo-state-change-hook nil
2349 "Hook which is run after the state of a TODO item was changed.
2350 The new state (a string with a TODO keyword, or nil) is available in the
2351 Lisp variable `org-state'."
2352 :group 'org-todo
2353 :type 'hook)
2355 (defvar org-blocker-hook nil
2356 "Hook for functions that are allowed to block a state change.
2358 Functions in this hook should not modify the buffer.
2359 Each function gets as its single argument a property list,
2360 see `org-trigger-hook' for more information about this list.
2362 If any of the functions in this hook returns nil, the state change
2363 is blocked.")
2365 (defvar org-trigger-hook nil
2366 "Hook for functions that are triggered by a state change.
2368 Each function gets as its single argument a property list with at
2369 least the following elements:
2371 (:type type-of-change :position pos-at-entry-start
2372 :from old-state :to new-state)
2374 Depending on the type, more properties may be present.
2376 This mechanism is currently implemented for:
2378 TODO state changes
2379 ------------------
2380 :type todo-state-change
2381 :from previous state (keyword as a string), or nil, or a symbol
2382 'todo' or 'done', to indicate the general type of state.
2383 :to new state, like in :from")
2385 (defcustom org-enforce-todo-dependencies nil
2386 "Non-nil means undone TODO entries will block switching the parent to DONE.
2387 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2388 be blocked if any prior sibling is not yet done.
2389 Finally, if the parent is blocked because of ordered siblings of its own,
2390 the child will also be blocked."
2391 :set (lambda (var val)
2392 (set var val)
2393 (if val
2394 (add-hook 'org-blocker-hook
2395 'org-block-todo-from-children-or-siblings-or-parent)
2396 (remove-hook 'org-blocker-hook
2397 'org-block-todo-from-children-or-siblings-or-parent)))
2398 :group 'org-todo
2399 :type 'boolean)
2401 (defcustom org-enforce-todo-checkbox-dependencies nil
2402 "Non-nil means unchecked boxes will block switching the parent to DONE.
2403 When this is nil, checkboxes have no influence on switching TODO states.
2404 When non-nil, you first need to check off all check boxes before the TODO
2405 entry can be switched to DONE.
2406 This variable needs to be set before org.el is loaded, and you need to
2407 restart Emacs after a change to make the change effective. The only way
2408 to change is while Emacs is running is through the customize interface."
2409 :set (lambda (var val)
2410 (set var val)
2411 (if val
2412 (add-hook 'org-blocker-hook
2413 'org-block-todo-from-checkboxes)
2414 (remove-hook 'org-blocker-hook
2415 'org-block-todo-from-checkboxes)))
2416 :group 'org-todo
2417 :type 'boolean)
2419 (defcustom org-treat-insert-todo-heading-as-state-change nil
2420 "Non-nil means inserting a TODO heading is treated as state change.
2421 So when the command \\[org-insert-todo-heading] is used, state change
2422 logging will apply if appropriate. When nil, the new TODO item will
2423 be inserted directly, and no logging will take place."
2424 :group 'org-todo
2425 :type 'boolean)
2427 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2428 "Non-nil means switching TODO states with S-cursor counts as state change.
2429 This is the default behavior. However, setting this to nil allows a
2430 convenient way to select a TODO state and bypass any logging associated
2431 with that."
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-todo-state-tags-triggers nil
2436 "Tag changes that should be triggered by TODO state changes.
2437 This is a list. Each entry is
2439 (state-change (tag . flag) .......)
2441 State-change can be a string with a state, and empty string to indicate the
2442 state that has no TODO keyword, or it can be one of the symbols `todo'
2443 or `done', meaning any not-done or done state, respectively."
2444 :group 'org-todo
2445 :group 'org-tags
2446 :type '(repeat
2447 (cons (choice :tag "When changing to"
2448 (const :tag "Not-done state" todo)
2449 (const :tag "Done state" done)
2450 (string :tag "State"))
2451 (repeat
2452 (cons :tag "Tag action"
2453 (string :tag "Tag")
2454 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2456 (defcustom org-log-done nil
2457 "Information to record when a task moves to the DONE state.
2459 Possible values are:
2461 nil Don't add anything, just change the keyword
2462 time Add a time stamp to the task
2463 note Prompt for a note and add it with template `org-log-note-headings'
2465 This option can also be set with on a per-file-basis with
2467 #+STARTUP: nologdone
2468 #+STARTUP: logdone
2469 #+STARTUP: lognotedone
2471 You can have local logging settings for a subtree by setting the LOGGING
2472 property to one or more of these keywords."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(choice
2476 (const :tag "No logging" nil)
2477 (const :tag "Record CLOSED timestamp" time)
2478 (const :tag "Record CLOSED timestamp with note." note)))
2480 ;; Normalize old uses of org-log-done.
2481 (cond
2482 ((eq org-log-done t) (setq org-log-done 'time))
2483 ((and (listp org-log-done) (memq 'done org-log-done))
2484 (setq org-log-done 'note)))
2486 (defcustom org-log-reschedule nil
2487 "Information to record when the scheduling date of a tasks is modified.
2489 Possible values are:
2491 nil Don't add anything, just change the date
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologreschedule
2498 #+STARTUP: logreschedule
2499 #+STARTUP: lognotereschedule"
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type '(choice
2503 (const :tag "No logging" nil)
2504 (const :tag "Record timestamp" time)
2505 (const :tag "Record timestamp with note." note)))
2507 (defcustom org-log-redeadline nil
2508 "Information to record when the deadline date of a tasks is modified.
2510 Possible values are:
2512 nil Don't add anything, just change the date
2513 time Add a time stamp to the task
2514 note Prompt for a note and add it with template `org-log-note-headings'
2516 This option can also be set with on a per-file-basis with
2518 #+STARTUP: nologredeadline
2519 #+STARTUP: logredeadline
2520 #+STARTUP: lognoteredeadline
2522 You can have local logging settings for a subtree by setting the LOGGING
2523 property to one or more of these keywords."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type '(choice
2527 (const :tag "No logging" nil)
2528 (const :tag "Record timestamp" time)
2529 (const :tag "Record timestamp with note." note)))
2531 (defcustom org-log-note-clock-out nil
2532 "Non-nil means record a note when clocking out of an item.
2533 This can also be configured on a per-file basis by adding one of
2534 the following lines anywhere in the buffer:
2536 #+STARTUP: lognoteclock-out
2537 #+STARTUP: nolognoteclock-out"
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-done-with-time t
2543 "Non-nil means the CLOSED time stamp will contain date and time.
2544 When nil, only the date will be recorded."
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-log-note-headings
2549 '((done . "CLOSING NOTE %t")
2550 (state . "State %-12s from %-12S %t")
2551 (note . "Note taken on %t")
2552 (reschedule . "Rescheduled from %S on %t")
2553 (delschedule . "Not scheduled, was %S on %t")
2554 (redeadline . "New deadline from %S on %t")
2555 (deldeadline . "Removed deadline, was %S on %t")
2556 (refile . "Refiled on %t")
2557 (clock-out . ""))
2558 "Headings for notes added to entries.
2559 The value is an alist, with the car being a symbol indicating the note
2560 context, and the cdr is the heading to be used. The heading may also be the
2561 empty string.
2562 %t in the heading will be replaced by a time stamp.
2563 %T will be an active time stamp instead the default inactive one
2564 %d will be replaced by a short-format time stamp.
2565 %D will be replaced by an active short-format time stamp.
2566 %s will be replaced by the new TODO state, in double quotes.
2567 %S will be replaced by the old TODO state, in double quotes.
2568 %u will be replaced by the user name.
2569 %U will be replaced by the full user name.
2571 In fact, it is not a good idea to change the `state' entry, because
2572 agenda log mode depends on the format of these entries."
2573 :group 'org-todo
2574 :group 'org-progress
2575 :type '(list :greedy t
2576 (cons (const :tag "Heading when closing an item" done) string)
2577 (cons (const :tag
2578 "Heading when changing todo state (todo sequence only)"
2579 state) string)
2580 (cons (const :tag "Heading when just taking a note" note) string)
2581 (cons (const :tag "Heading when clocking out" clock-out) string)
2582 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2583 (cons (const :tag "Heading when rescheduling" reschedule) string)
2584 (cons (const :tag "Heading when changing deadline" redeadline) string)
2585 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2586 (cons (const :tag "Heading when refiling" refile) string)))
2588 (unless (assq 'note org-log-note-headings)
2589 (push '(note . "%t") org-log-note-headings))
2591 (defcustom org-log-into-drawer nil
2592 "Non-nil means insert state change notes and time stamps into a drawer.
2593 When nil, state changes notes will be inserted after the headline and
2594 any scheduling and clock lines, but not inside a drawer.
2596 The value of this variable should be the name of the drawer to use.
2597 LOGBOOK is proposed as the default drawer for this purpose, you can
2598 also set this to a string to define the drawer of your choice.
2600 A value of t is also allowed, representing \"LOGBOOK\".
2602 A value of t or nil can also be set with on a per-file-basis with
2604 #+STARTUP: logdrawer
2605 #+STARTUP: nologdrawer
2607 If this variable is set, `org-log-state-notes-insert-after-drawers'
2608 will be ignored.
2610 You can set the property LOG_INTO_DRAWER to overrule this setting for
2611 a subtree."
2612 :group 'org-todo
2613 :group 'org-progress
2614 :type '(choice
2615 (const :tag "Not into a drawer" nil)
2616 (const :tag "LOGBOOK" t)
2617 (string :tag "Other")))
2619 (if (fboundp 'defvaralias)
2620 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2622 (defun org-log-into-drawer ()
2623 "Return the value of `org-log-into-drawer', but let properties overrule.
2624 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2625 used instead of the default value."
2626 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2627 (cond
2628 ((not p) org-log-into-drawer)
2629 ((equal p "nil") nil)
2630 ((equal p "t") "LOGBOOK")
2631 (t p))))
2633 (defcustom org-log-state-notes-insert-after-drawers nil
2634 "Non-nil means insert state change notes after any drawers in entry.
2635 Only the drawers that *immediately* follow the headline and the
2636 deadline/scheduled line are skipped.
2637 When nil, insert notes right after the heading and perhaps the line
2638 with deadline/scheduling if present.
2640 This variable will have no effect if `org-log-into-drawer' is
2641 set."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-states-order-reversed t
2647 "Non-nil means the latest state note will be directly after heading.
2648 When nil, the state change notes will be ordered according to time.
2650 This option can also be set with on a per-file-basis with
2652 #+STARTUP: logstatesreversed
2653 #+STARTUP: nologstatesreversed"
2654 :group 'org-todo
2655 :group 'org-progress
2656 :type 'boolean)
2658 (defcustom org-todo-repeat-to-state nil
2659 "The TODO state to which a repeater should return the repeating task.
2660 By default this is the first task in a TODO sequence, or the previous state
2661 in a TODO_TYP set. But you can specify another task here.
2662 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2663 :group 'org-todo
2664 :version "24.1"
2665 :type '(choice (const :tag "Head of sequence" nil)
2666 (string :tag "Specific state")))
2668 (defcustom org-log-repeat 'time
2669 "Non-nil means record moving through the DONE state when triggering repeat.
2670 An auto-repeating task is immediately switched back to TODO when
2671 marked DONE. If you are not logging state changes (by adding \"@\"
2672 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2673 record a closing note, there will be no record of the task moving
2674 through DONE. This variable forces taking a note anyway.
2676 nil Don't force a record
2677 time Record a time stamp
2678 note Prompt for a note and add it with template `org-log-note-headings'
2680 This option can also be set with on a per-file-basis with
2682 #+STARTUP: nologrepeat
2683 #+STARTUP: logrepeat
2684 #+STARTUP: lognoterepeat
2686 You can have local logging settings for a subtree by setting the LOGGING
2687 property to one or more of these keywords."
2688 :group 'org-todo
2689 :group 'org-progress
2690 :type '(choice
2691 (const :tag "Don't force a record" nil)
2692 (const :tag "Force recording the DONE state" time)
2693 (const :tag "Force recording a note with the DONE state" note)))
2696 (defgroup org-priorities nil
2697 "Priorities in Org-mode."
2698 :tag "Org Priorities"
2699 :group 'org-todo)
2701 (defcustom org-enable-priority-commands t
2702 "Non-nil means priority commands are active.
2703 When nil, these commands will be disabled, so that you never accidentally
2704 set a priority."
2705 :group 'org-priorities
2706 :type 'boolean)
2708 (defcustom org-highest-priority ?A
2709 "The highest priority of TODO items. A character like ?A, ?B etc.
2710 Must have a smaller ASCII number than `org-lowest-priority'."
2711 :group 'org-priorities
2712 :type 'character)
2714 (defcustom org-lowest-priority ?C
2715 "The lowest priority of TODO items. A character like ?A, ?B etc.
2716 Must have a larger ASCII number than `org-highest-priority'."
2717 :group 'org-priorities
2718 :type 'character)
2720 (defcustom org-default-priority ?B
2721 "The default priority of TODO items.
2722 This is the priority an item gets if no explicit priority is given.
2723 When starting to cycle on an empty priority the first step in the cycle
2724 depends on `org-priority-start-cycle-with-default'. The resulting first
2725 step priority must not exceed the range from `org-highest-priority' to
2726 `org-lowest-priority' which means that `org-default-priority' has to be
2727 in this range exclusive or inclusive the range boundaries. Else the
2728 first step refuses to set the default and the second will fall back
2729 to (depending on the command used) the highest or lowest priority."
2730 :group 'org-priorities
2731 :type 'character)
2733 (defcustom org-priority-start-cycle-with-default t
2734 "Non-nil means start with default priority when starting to cycle.
2735 When this is nil, the first step in the cycle will be (depending on the
2736 command used) one higher or lower than the default priority.
2737 See also `org-default-priority'."
2738 :group 'org-priorities
2739 :type 'boolean)
2741 (defcustom org-get-priority-function nil
2742 "Function to extract the priority from a string.
2743 The string is normally the headline. If this is nil Org computes the
2744 priority from the priority cookie like [#A] in the headline. It returns
2745 an integer, increasing by 1000 for each priority level.
2746 The user can set a different function here, which should take a string
2747 as an argument and return the numeric priority."
2748 :group 'org-priorities
2749 :version "24.1"
2750 :type 'function)
2752 (defgroup org-time nil
2753 "Options concerning time stamps and deadlines in Org-mode."
2754 :tag "Org Time"
2755 :group 'org)
2757 (defcustom org-insert-labeled-timestamps-at-point nil
2758 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2759 When nil, these labeled time stamps are forces into the second line of an
2760 entry, just after the headline. When scheduling from the global TODO list,
2761 the time stamp will always be forced into the second line."
2762 :group 'org-time
2763 :type 'boolean)
2765 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2766 "Formats for `format-time-string' which are used for time stamps.
2767 It is not recommended to change this constant.")
2769 (defcustom org-time-stamp-rounding-minutes '(0 5)
2770 "Number of minutes to round time stamps to.
2771 These are two values, the first applies when first creating a time stamp.
2772 The second applies when changing it with the commands `S-up' and `S-down'.
2773 When changing the time stamp, this means that it will change in steps
2774 of N minutes, as given by the second value.
2776 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2777 numbers should be factors of 60, so for example 5, 10, 15.
2779 When this is larger than 1, you can still force an exact time stamp by using
2780 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2781 and by using a prefix arg to `S-up/down' to specify the exact number
2782 of minutes to shift."
2783 :group 'org-time
2784 :get #'(lambda (var) ; Make sure both elements are there
2785 (if (integerp (default-value var))
2786 (list (default-value var) 5)
2787 (default-value var)))
2788 :type '(list
2789 (integer :tag "when inserting times")
2790 (integer :tag "when modifying times")))
2792 ;; Normalize old customizations of this variable.
2793 (when (integerp org-time-stamp-rounding-minutes)
2794 (setq org-time-stamp-rounding-minutes
2795 (list org-time-stamp-rounding-minutes
2796 org-time-stamp-rounding-minutes)))
2798 (defcustom org-display-custom-times nil
2799 "Non-nil means overlay custom formats over all time stamps.
2800 The formats are defined through the variable `org-time-stamp-custom-formats'.
2801 To turn this on on a per-file basis, insert anywhere in the file:
2802 #+STARTUP: customtime"
2803 :group 'org-time
2804 :set 'set-default
2805 :type 'sexp)
2806 (make-variable-buffer-local 'org-display-custom-times)
2808 (defcustom org-time-stamp-custom-formats
2809 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2810 "Custom formats for time stamps. See `format-time-string' for the syntax.
2811 These are overlaid over the default ISO format if the variable
2812 `org-display-custom-times' is set. Time like %H:%M should be at the
2813 end of the second format. The custom formats are also honored by export
2814 commands, if custom time display is turned on at the time of export."
2815 :group 'org-time
2816 :type 'sexp)
2818 (defun org-time-stamp-format (&optional long inactive)
2819 "Get the right format for a time string."
2820 (let ((f (if long (cdr org-time-stamp-formats)
2821 (car org-time-stamp-formats))))
2822 (if inactive
2823 (concat "[" (substring f 1 -1) "]")
2824 f)))
2826 (defcustom org-time-clocksum-format
2827 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2828 "The format string used when creating CLOCKSUM lines.
2829 This is also used when Org mode generates a time duration.
2831 The value can be a single format string containing two
2832 %-sequences, which will be filled with the number of hours and
2833 minutes in that order.
2835 Alternatively, the value can be a plist associating any of the
2836 keys :years, :months, :weeks, :days, :hours or :minutes with
2837 format strings. The time duration is formatted using only the
2838 time components that are needed and concatenating the results.
2839 If a time unit in absent, it falls back to the next smallest
2840 unit.
2842 The keys :require-years, :require-months, :require-days,
2843 :require-weeks, :require-hours, :require-minutes are also
2844 meaningful. A non-nil value for these keys indicates that the
2845 corresponding time component should always be included, even if
2846 its value is 0.
2849 For example,
2851 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2852 :require-minutes t)
2854 means durations longer than a day will be expressed in days,
2855 hours and minutes, and durations less than a day will always be
2856 expressed in hours and minutes (even for durations less than an
2857 hour).
2859 The value
2861 \(:days \"%dd\" :minutes \"%dm\")
2863 means durations longer than a day will be expressed in days and
2864 minutes, and durations less than a day will be expressed entirely
2865 in minutes (even for durations longer than an hour)."
2866 :group 'org-time
2867 :group 'org-clock
2868 :version "24.3"
2869 :type '(choice (string :tag "Format string")
2870 (set :tag "Plist"
2871 (group :inline t (const :tag "Years" :years)
2872 (string :tag "Format string"))
2873 (group :inline t
2874 (const :tag "Always show years" :require-years)
2875 (const t))
2876 (group :inline t (const :tag "Months" :months)
2877 (string :tag "Format string"))
2878 (group :inline t
2879 (const :tag "Always show months" :require-months)
2880 (const t))
2881 (group :inline t (const :tag "Weeks" :weeks)
2882 (string :tag "Format string"))
2883 (group :inline t
2884 (const :tag "Always show weeks" :require-weeks)
2885 (const t))
2886 (group :inline t (const :tag "Days" :days)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show days" :require-days)
2890 (const t))
2891 (group :inline t (const :tag "Hours" :hours)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show hours" :require-hours)
2895 (const t))
2896 (group :inline t (const :tag "Minutes" :minutes)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show minutes" :require-minutes)
2900 (const t)))))
2902 (defcustom org-time-clocksum-use-fractional nil
2903 "When non-nil, \\[org-clock-display] uses fractional times.
2904 See `org-time-clocksum-format' for more on time clock formats."
2905 :group 'org-time
2906 :group 'org-clock
2907 :version "24.3"
2908 :type 'boolean)
2910 (defcustom org-time-clocksum-use-effort-durations t
2911 "When non-nil, \\[org-clock-display] uses effort durations.
2912 E.g. by default, one day is considered to be a 8 hours effort,
2913 so a task that has been clocked for 16 hours will be displayed
2914 as during 2 days in the clock display or in the clocktable.
2916 See `org-effort-durations' on how to set effort durations
2917 and `org-time-clocksum-format' for more on time clock formats."
2918 :group 'org-time
2919 :group 'org-clock
2920 :version "24.3"
2921 :type 'boolean)
2923 (defcustom org-time-clocksum-fractional-format "%.2f"
2924 "The format string used when creating CLOCKSUM lines,
2925 or when Org mode generates a time duration, if
2926 `org-time-clocksum-use-fractional' is enabled.
2928 The value can be a single format string containing one
2929 %-sequence, which will be filled with the number of hours as
2930 a float.
2932 Alternatively, the value can be a plist associating any of the
2933 keys :years, :months, :weeks, :days, :hours or :minutes with
2934 a format string. The time duration is formatted using the
2935 largest time unit which gives a non-zero integer part. If all
2936 specified formats have zero integer part, the smallest time unit
2937 is used."
2938 :group 'org-time
2939 :type '(choice (string :tag "Format string")
2940 (set (group :inline t (const :tag "Years" :years)
2941 (string :tag "Format string"))
2942 (group :inline t (const :tag "Months" :months)
2943 (string :tag "Format string"))
2944 (group :inline t (const :tag "Weeks" :weeks)
2945 (string :tag "Format string"))
2946 (group :inline t (const :tag "Days" :days)
2947 (string :tag "Format string"))
2948 (group :inline t (const :tag "Hours" :hours)
2949 (string :tag "Format string"))
2950 (group :inline t (const :tag "Minutes" :minutes)
2951 (string :tag "Format string")))))
2953 (defcustom org-deadline-warning-days 14
2954 "Number of days before expiration during which a deadline becomes active.
2955 This variable governs the display in sparse trees and in the agenda.
2956 When 0 or negative, it means use this number (the absolute value of it)
2957 even if a deadline has a different individual lead time specified.
2959 Custom commands can set this variable in the options section."
2960 :group 'org-time
2961 :group 'org-agenda-daily/weekly
2962 :type 'integer)
2964 (defcustom org-scheduled-delay-days 0
2965 "Number of days before a scheduled item becomes active.
2966 This variable governs the display in sparse trees and in the agenda.
2967 The default value (i.e. 0) means: don't delay scheduled item.
2968 When negative, it means use this number (the absolute value of it)
2969 even if a scheduled item has a different individual delay time
2970 specified.
2972 Custom commands can set this variable in the options section."
2973 :group 'org-time
2974 :group 'org-agenda-daily/weekly
2975 :version "24.3"
2976 :type 'integer)
2978 (defcustom org-read-date-prefer-future t
2979 "Non-nil means assume future for incomplete date input from user.
2980 This affects the following situations:
2981 1. The user gives a month but not a year.
2982 For example, if it is April and you enter \"feb 2\", this will be read
2983 as Feb 2, *next* year. \"May 5\", however, will be this year.
2984 2. The user gives a day, but no month.
2985 For example, if today is the 15th, and you enter \"3\", Org-mode will
2986 read this as the third of *next* month. However, if you enter \"17\",
2987 it will be considered as *this* month.
2989 If you set this variable to the symbol `time', then also the following
2990 will work:
2992 3. If the user gives a time.
2993 If the time is before now, it will be interpreted as tomorrow.
2995 Currently none of this works for ISO week specifications.
2997 When this option is nil, the current day, month and year will always be
2998 used as defaults.
3000 See also `org-agenda-jump-prefer-future'."
3001 :group 'org-time
3002 :type '(choice
3003 (const :tag "Never" nil)
3004 (const :tag "Check month and day" t)
3005 (const :tag "Check month, day, and time" time)))
3007 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3008 "Should the agenda jump command prefer the future for incomplete dates?
3009 The default is to do the same as configured in `org-read-date-prefer-future'.
3010 But you can also set a deviating value here.
3011 This may t or nil, or the symbol `org-read-date-prefer-future'."
3012 :group 'org-agenda
3013 :group 'org-time
3014 :version "24.1"
3015 :type '(choice
3016 (const :tag "Use org-read-date-prefer-future"
3017 org-read-date-prefer-future)
3018 (const :tag "Never" nil)
3019 (const :tag "Always" t)))
3021 (defcustom org-read-date-force-compatible-dates t
3022 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3024 Depending on the system Emacs is running on, certain dates cannot
3025 be represented with the type used internally to represent time.
3026 Dates between 1970-1-1 and 2038-1-1 can always be represented
3027 correctly. Some systems allow for earlier dates, some for later,
3028 some for both. One way to find out it to insert any date into an
3029 Org buffer, putting the cursor on the year and hitting S-up and
3030 S-down to test the range.
3032 When this variable is set to t, the date/time prompt will not let
3033 you specify dates outside the 1970-2037 range, so it is certain that
3034 these dates will work in whatever version of Emacs you are
3035 running, and also that you can move a file from one Emacs implementation
3036 to another. WHenever Org is forcing the year for you, it will display
3037 a message and beep.
3039 When this variable is nil, Org will check if the date is
3040 representable in the specific Emacs implementation you are using.
3041 If not, it will force a year, usually the current year, and beep
3042 to remind you. Currently this setting is not recommended because
3043 the likelihood that you will open your Org files in an Emacs that
3044 has limited date range is not negligible.
3046 A workaround for this problem is to use diary sexp dates for time
3047 stamps outside of this range."
3048 :group 'org-time
3049 :version "24.1"
3050 :type 'boolean)
3052 (defcustom org-read-date-display-live t
3053 "Non-nil means display current interpretation of date prompt live.
3054 This display will be in an overlay, in the minibuffer."
3055 :group 'org-time
3056 :type 'boolean)
3058 (defcustom org-read-date-popup-calendar t
3059 "Non-nil means pop up a calendar when prompting for a date.
3060 In the calendar, the date can be selected with mouse-1. However, the
3061 minibuffer will also be active, and you can simply enter the date as well.
3062 When nil, only the minibuffer will be available."
3063 :group 'org-time
3064 :type 'boolean)
3065 (if (fboundp 'defvaralias)
3066 (defvaralias 'org-popup-calendar-for-date-prompt
3067 'org-read-date-popup-calendar))
3069 (make-obsolete-variable
3070 'org-read-date-minibuffer-setup-hook
3071 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3072 (defcustom org-read-date-minibuffer-setup-hook nil
3073 "Hook to be used to set up keys for the date/time interface.
3074 Add key definitions to `minibuffer-local-map', which will be a
3075 temporary copy.
3077 WARNING: This option is obsolete, you should use
3078 `org-read-date-minibuffer-local-map' to set up keys."
3079 :group 'org-time
3080 :type 'hook)
3082 (defcustom org-extend-today-until 0
3083 "The hour when your day really ends. Must be an integer.
3084 This has influence for the following applications:
3085 - When switching the agenda to \"today\". It it is still earlier than
3086 the time given here, the day recognized as TODAY is actually yesterday.
3087 - When a date is read from the user and it is still before the time given
3088 here, the current date and time will be assumed to be yesterday, 23:59.
3089 Also, timestamps inserted in capture templates follow this rule.
3091 IMPORTANT: This is a feature whose implementation is and likely will
3092 remain incomplete. Really, it is only here because past midnight seems to
3093 be the favorite working time of John Wiegley :-)"
3094 :group 'org-time
3095 :type 'integer)
3097 (defcustom org-use-effective-time nil
3098 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3099 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3100 \"effective time\" of any timestamps between midnight and 8am will be
3101 23:59 of the previous day."
3102 :group 'org-time
3103 :version "24.1"
3104 :type 'boolean)
3106 (defcustom org-use-last-clock-out-time-as-effective-time nil
3107 "When non-nil, use the last clock out time for `org-todo'.
3108 Note that this option has precedence over the combined use of
3109 `org-use-effective-time' and `org-extend-today-until'."
3110 :group 'org-time
3111 ;; :version "24.3"
3112 :type 'boolean)
3114 (defcustom org-edit-timestamp-down-means-later nil
3115 "Non-nil means S-down will increase the time in a time stamp.
3116 When nil, S-up will increase."
3117 :group 'org-time
3118 :type 'boolean)
3120 (defcustom org-calendar-follow-timestamp-change t
3121 "Non-nil means make the calendar window follow timestamp changes.
3122 When a timestamp is modified and the calendar window is visible, it will be
3123 moved to the new date."
3124 :group 'org-time
3125 :type 'boolean)
3127 (defgroup org-tags nil
3128 "Options concerning tags in Org-mode."
3129 :tag "Org Tags"
3130 :group 'org)
3132 (defcustom org-tag-alist nil
3133 "List of tags allowed in Org-mode files.
3134 When this list is nil, Org-mode will base TAG input on what is already in the
3135 buffer.
3136 The value of this variable is an alist, the car of each entry must be a
3137 keyword as a string, the cdr may be a character that is used to select
3138 that tag through the fast-tag-selection interface.
3139 See the manual for details."
3140 :group 'org-tags
3141 :type '(repeat
3142 (choice
3143 (cons (string :tag "Tag name")
3144 (character :tag "Access char"))
3145 (list :tag "Start radio group"
3146 (const :startgroup)
3147 (option (string :tag "Group description")))
3148 (list :tag "End radio group"
3149 (const :endgroup)
3150 (option (string :tag "Group description")))
3151 (const :tag "New line" (:newline)))))
3153 (defcustom org-tag-persistent-alist nil
3154 "List of tags that will always appear in all Org-mode files.
3155 This is in addition to any in buffer settings or customizations
3156 of `org-tag-alist'.
3157 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3158 The value of this variable is an alist, the car of each entry must be a
3159 keyword as a string, the cdr may be a character that is used to select
3160 that tag through the fast-tag-selection interface.
3161 See the manual for details.
3162 To disable these tags on a per-file basis, insert anywhere in the file:
3163 #+STARTUP: noptag"
3164 :group 'org-tags
3165 :type '(repeat
3166 (choice
3167 (cons (string :tag "Tag name")
3168 (character :tag "Access char"))
3169 (const :tag "Start radio group" (:startgroup))
3170 (const :tag "End radio group" (:endgroup))
3171 (const :tag "New line" (:newline)))))
3173 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3174 "If non-nil, always offer completion for all tags of all agenda files.
3175 Instead of customizing this variable directly, you might want to
3176 set it locally for capture buffers, because there no list of
3177 tags in that file can be created dynamically (there are none).
3179 (add-hook 'org-capture-mode-hook
3180 (lambda ()
3181 (set (make-local-variable
3182 'org-complete-tags-always-offer-all-agenda-tags)
3183 t)))"
3184 :group 'org-tags
3185 :version "24.1"
3186 :type 'boolean)
3188 (defvar org-file-tags nil
3189 "List of tags that can be inherited by all entries in the file.
3190 The tags will be inherited if the variable `org-use-tag-inheritance'
3191 says they should be.
3192 This variable is populated from #+FILETAGS lines.")
3194 (defcustom org-use-fast-tag-selection 'auto
3195 "Non-nil means use fast tag selection scheme.
3196 This is a special interface to select and deselect tags with single keys.
3197 When nil, fast selection is never used.
3198 When the symbol `auto', fast selection is used if and only if selection
3199 characters for tags have been configured, either through the variable
3200 `org-tag-alist' or through a #+TAGS line in the buffer.
3201 When t, fast selection is always used and selection keys are assigned
3202 automatically if necessary."
3203 :group 'org-tags
3204 :type '(choice
3205 (const :tag "Always" t)
3206 (const :tag "Never" nil)
3207 (const :tag "When selection characters are configured" 'auto)))
3209 (defcustom org-fast-tag-selection-single-key nil
3210 "Non-nil means fast tag selection exits after first change.
3211 When nil, you have to press RET to exit it.
3212 During fast tag selection, you can toggle this flag with `C-c'.
3213 This variable can also have the value `expert'. In this case, the window
3214 displaying the tags menu is not even shown, until you press C-c again."
3215 :group 'org-tags
3216 :type '(choice
3217 (const :tag "No" nil)
3218 (const :tag "Yes" t)
3219 (const :tag "Expert" expert)))
3221 (defvar org-fast-tag-selection-include-todo nil
3222 "Non-nil means fast tags selection interface will also offer TODO states.
3223 This is an undocumented feature, you should not rely on it.")
3225 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3226 "The column to which tags should be indented in a headline.
3227 If this number is positive, it specifies the column. If it is negative,
3228 it means that the tags should be flushright to that column. For example,
3229 -80 works well for a normal 80 character screen.
3230 When 0, place tags directly after headline text, with only one space in
3231 between."
3232 :group 'org-tags
3233 :type 'integer)
3235 (defcustom org-auto-align-tags t
3236 "Non-nil keeps tags aligned when modifying headlines.
3237 Some operations (i.e. demoting) change the length of a headline and
3238 therefore shift the tags around. With this option turned on, after
3239 each such operation the tags are again aligned to `org-tags-column'."
3240 :group 'org-tags
3241 :type 'boolean)
3243 (defcustom org-use-tag-inheritance t
3244 "Non-nil means tags in levels apply also for sublevels.
3245 When nil, only the tags directly given in a specific line apply there.
3246 This may also be a list of tags that should be inherited, or a regexp that
3247 matches tags that should be inherited. Additional control is possible
3248 with the variable `org-tags-exclude-from-inheritance' which gives an
3249 explicit list of tags to be excluded from inheritance, even if the value of
3250 `org-use-tag-inheritance' would select it for inheritance.
3252 If this option is t, a match early-on in a tree can lead to a large
3253 number of matches in the subtree when constructing the agenda or creating
3254 a sparse tree. If you only want to see the first match in a tree during
3255 a search, check out the variable `org-tags-match-list-sublevels'."
3256 :group 'org-tags
3257 :type '(choice
3258 (const :tag "Not" nil)
3259 (const :tag "Always" t)
3260 (repeat :tag "Specific tags" (string :tag "Tag"))
3261 (regexp :tag "Tags matched by regexp")))
3263 (defcustom org-tags-exclude-from-inheritance nil
3264 "List of tags that should never be inherited.
3265 This is a way to exclude a few tags from inheritance. For way to do
3266 the opposite, to actively allow inheritance for selected tags,
3267 see the variable `org-use-tag-inheritance'."
3268 :group 'org-tags
3269 :type '(repeat (string :tag "Tag")))
3271 (defun org-tag-inherit-p (tag)
3272 "Check if TAG is one that should be inherited."
3273 (cond
3274 ((member tag org-tags-exclude-from-inheritance) nil)
3275 ((eq org-use-tag-inheritance t) t)
3276 ((not org-use-tag-inheritance) nil)
3277 ((stringp org-use-tag-inheritance)
3278 (string-match org-use-tag-inheritance tag))
3279 ((listp org-use-tag-inheritance)
3280 (member tag org-use-tag-inheritance))
3281 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3283 (defcustom org-tags-match-list-sublevels t
3284 "Non-nil means list also sublevels of headlines matching a search.
3285 This variable applies to tags/property searches, and also to stuck
3286 projects because this search is based on a tags match as well.
3288 When set to the symbol `indented', sublevels are indented with
3289 leading dots.
3291 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3292 the sublevels of a headline matching a tag search often also match
3293 the same search. Listing all of them can create very long lists.
3294 Setting this variable to nil causes subtrees of a match to be skipped.
3296 This variable is semi-obsolete and probably should always be true. It
3297 is better to limit inheritance to certain tags using the variables
3298 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3299 :group 'org-tags
3300 :type '(choice
3301 (const :tag "No, don't list them" nil)
3302 (const :tag "Yes, do list them" t)
3303 (const :tag "List them, indented with leading dots" indented)))
3305 (defcustom org-tags-sort-function nil
3306 "When set, tags are sorted using this function as a comparator."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "No sorting" nil)
3310 (const :tag "Alphabetical" string<)
3311 (const :tag "Reverse alphabetical" string>)
3312 (function :tag "Custom function" nil)))
3314 (defvar org-tags-history nil
3315 "History of minibuffer reads for tags.")
3316 (defvar org-last-tags-completion-table nil
3317 "The last used completion table for tags.")
3318 (defvar org-after-tags-change-hook nil
3319 "Hook that is run after the tags in a line have changed.")
3321 (defgroup org-properties nil
3322 "Options concerning properties in Org-mode."
3323 :tag "Org Properties"
3324 :group 'org)
3326 (defcustom org-property-format "%-10s %s"
3327 "How property key/value pairs should be formatted by `indent-line'.
3328 When `indent-line' hits a property definition, it will format the line
3329 according to this format, mainly to make sure that the values are
3330 lined-up with respect to each other."
3331 :group 'org-properties
3332 :type 'string)
3334 (defcustom org-properties-postprocess-alist nil
3335 "Alist of properties and functions to adjust inserted values.
3336 Elements of this alist must be of the form
3338 ([string] [function])
3340 where [string] must be a property name and [function] must be a
3341 lambda expression: this lambda expression must take one argument,
3342 the value to adjust, and return the new value as a string.
3344 For example, this element will allow the property \"Remaining\"
3345 to be updated wrt the relation between the \"Effort\" property
3346 and the clock summary:
3348 ((\"Remaining\" (lambda(value)
3349 (let ((clocksum (org-clock-sum-current-item))
3350 (effort (org-duration-string-to-minutes
3351 (org-entry-get (point) \"Effort\"))))
3352 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3353 :group 'org-properties
3354 :version "24.1"
3355 :type '(alist :key-type (string :tag "Property")
3356 :value-type (function :tag "Function")))
3358 (defcustom org-use-property-inheritance nil
3359 "Non-nil means properties apply also for sublevels.
3361 This setting is chiefly used during property searches. Turning it on can
3362 cause significant overhead when doing a search, which is why it is not
3363 on by default.
3365 When nil, only the properties directly given in the current entry count.
3366 When t, every property is inherited. The value may also be a list of
3367 properties that should have inheritance, or a regular expression matching
3368 properties that should be inherited.
3370 However, note that some special properties use inheritance under special
3371 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3372 and the properties ending in \"_ALL\" when they are used as descriptor
3373 for valid values of a property.
3375 Note for programmers:
3376 When querying an entry with `org-entry-get', you can control if inheritance
3377 should be used. By default, `org-entry-get' looks only at the local
3378 properties. You can request inheritance by setting the inherit argument
3379 to t (to force inheritance) or to `selective' (to respect the setting
3380 in this variable)."
3381 :group 'org-properties
3382 :type '(choice
3383 (const :tag "Not" nil)
3384 (const :tag "Always" t)
3385 (repeat :tag "Specific properties" (string :tag "Property"))
3386 (regexp :tag "Properties matched by regexp")))
3388 (defun org-property-inherit-p (property)
3389 "Check if PROPERTY is one that should be inherited."
3390 (cond
3391 ((eq org-use-property-inheritance t) t)
3392 ((not org-use-property-inheritance) nil)
3393 ((stringp org-use-property-inheritance)
3394 (string-match org-use-property-inheritance property))
3395 ((listp org-use-property-inheritance)
3396 (member property org-use-property-inheritance))
3397 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3399 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3400 "The default column format, if no other format has been defined.
3401 This variable can be set on the per-file basis by inserting a line
3403 #+COLUMNS: %25ITEM ....."
3404 :group 'org-properties
3405 :type 'string)
3407 (defcustom org-columns-ellipses ".."
3408 "The ellipses to be used when a field in column view is truncated.
3409 When this is the empty string, as many characters as possible are shown,
3410 but then there will be no visual indication that the field has been truncated.
3411 When this is a string of length N, the last N characters of a truncated
3412 field are replaced by this string. If the column is narrower than the
3413 ellipses string, only part of the ellipses string will be shown."
3414 :group 'org-properties
3415 :type 'string)
3417 (defcustom org-columns-modify-value-for-display-function nil
3418 "Function that modifies values for display in column view.
3419 For example, it can be used to cut out a certain part from a time stamp.
3420 The function must take 2 arguments:
3422 column-title The title of the column (*not* the property name)
3423 value The value that should be modified.
3425 The function should return the value that should be displayed,
3426 or nil if the normal value should be used."
3427 :group 'org-properties
3428 :type 'function)
3430 (defcustom org-effort-property "Effort"
3431 "The property that is being used to keep track of effort estimates.
3432 Effort estimates given in this property need to have the format H:MM."
3433 :group 'org-properties
3434 :group 'org-progress
3435 :type '(string :tag "Property"))
3437 (defconst org-global-properties-fixed
3438 '(("VISIBILITY_ALL" . "folded children content all")
3439 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3440 "List of property/value pairs that can be inherited by any entry.
3442 These are fixed values, for the preset properties. The user variable
3443 that can be used to add to this list is `org-global-properties'.
3445 The entries in this list are cons cells where the car is a property
3446 name and cdr is a string with the value. If the value represents
3447 multiple items like an \"_ALL\" property, separate the items by
3448 spaces.")
3450 (defcustom org-global-properties nil
3451 "List of property/value pairs that can be inherited by any entry.
3453 This list will be combined with the constant `org-global-properties-fixed'.
3455 The entries in this list are cons cells where the car is a property
3456 name and cdr is a string with the value.
3458 You can set buffer-local values for the same purpose in the variable
3459 `org-file-properties' this by adding lines like
3461 #+PROPERTY: NAME VALUE"
3462 :group 'org-properties
3463 :type '(repeat
3464 (cons (string :tag "Property")
3465 (string :tag "Value"))))
3467 (defvar org-file-properties nil
3468 "List of property/value pairs that can be inherited by any entry.
3469 Valid for the current buffer.
3470 This variable is populated from #+PROPERTY lines.")
3471 (make-variable-buffer-local 'org-file-properties)
3473 (defgroup org-agenda nil
3474 "Options concerning agenda views in Org-mode."
3475 :tag "Org Agenda"
3476 :group 'org)
3478 (defvar org-category nil
3479 "Variable used by org files to set a category for agenda display.
3480 Such files should use a file variable to set it, for example
3482 # -*- mode: org; org-category: \"ELisp\"
3484 or contain a special line
3486 #+CATEGORY: ELisp
3488 If the file does not specify a category, then file's base name
3489 is used instead.")
3490 (make-variable-buffer-local 'org-category)
3491 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3493 (defcustom org-agenda-files nil
3494 "The files to be used for agenda display.
3495 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3496 \\[org-remove-file]. You can also use customize to edit the list.
3498 If an entry is a directory, all files in that directory that are matched by
3499 `org-agenda-file-regexp' will be part of the file list.
3501 If the value of the variable is not a list but a single file name, then
3502 the list of agenda files is actually stored and maintained in that file, one
3503 agenda file per line. In this file paths can be given relative to
3504 `org-directory'. Tilde expansion and environment variable substitution
3505 are also made."
3506 :group 'org-agenda
3507 :type '(choice
3508 (repeat :tag "List of files and directories" file)
3509 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3511 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3512 "Regular expression to match files for `org-agenda-files'.
3513 If any element in the list in that variable contains a directory instead
3514 of a normal file, all files in that directory that are matched by this
3515 regular expression will be included."
3516 :group 'org-agenda
3517 :type 'regexp)
3519 (defcustom org-agenda-text-search-extra-files nil
3520 "List of extra files to be searched by text search commands.
3521 These files will be search in addition to the agenda files by the
3522 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3523 Note that these files will only be searched for text search commands,
3524 not for the other agenda views like todo lists, tag searches or the weekly
3525 agenda. This variable is intended to list notes and possibly archive files
3526 that should also be searched by these two commands.
3527 In fact, if the first element in the list is the symbol `agenda-archives',
3528 than all archive files of all agenda files will be added to the search
3529 scope."
3530 :group 'org-agenda
3531 :type '(set :greedy t
3532 (const :tag "Agenda Archives" agenda-archives)
3533 (repeat :inline t (file))))
3535 (if (fboundp 'defvaralias)
3536 (defvaralias 'org-agenda-multi-occur-extra-files
3537 'org-agenda-text-search-extra-files))
3539 (defcustom org-agenda-skip-unavailable-files nil
3540 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3541 A nil value means to remove them, after a query, from the list."
3542 :group 'org-agenda
3543 :type 'boolean)
3545 (defcustom org-calendar-to-agenda-key [?c]
3546 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3547 The command `org-calendar-goto-agenda' will be bound to this key. The
3548 default is the character `c' because then `c' can be used to switch back and
3549 forth between agenda and calendar."
3550 :group 'org-agenda
3551 :type 'sexp)
3553 (defcustom org-calendar-insert-diary-entry-key [?i]
3554 "The key to be installed in `calendar-mode-map' for adding diary entries.
3555 This option is irrelevant until `org-agenda-diary-file' has been configured
3556 to point to an Org-mode file. When that is the case, the command
3557 `org-agenda-diary-entry' will be bound to the key given here, by default
3558 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3559 if you want to continue doing this, you need to change this to a different
3560 key."
3561 :group 'org-agenda
3562 :type 'sexp)
3564 (defcustom org-agenda-diary-file 'diary-file
3565 "File to which to add new entries with the `i' key in agenda and calendar.
3566 When this is the symbol `diary-file', the functionality in the Emacs
3567 calendar will be used to add entries to the `diary-file'. But when this
3568 points to a file, `org-agenda-diary-entry' will be used instead."
3569 :group 'org-agenda
3570 :type '(choice
3571 (const :tag "The standard Emacs diary file" diary-file)
3572 (file :tag "Special Org file diary entries")))
3574 (eval-after-load "calendar"
3575 '(progn
3576 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3577 'org-calendar-goto-agenda)
3578 (add-hook 'calendar-mode-hook
3579 (lambda ()
3580 (unless (eq org-agenda-diary-file 'diary-file)
3581 (define-key calendar-mode-map
3582 org-calendar-insert-diary-entry-key
3583 'org-agenda-diary-entry))))))
3585 (defgroup org-latex nil
3586 "Options for embedding LaTeX code into Org-mode."
3587 :tag "Org LaTeX"
3588 :group 'org)
3590 (defcustom org-format-latex-options
3591 '(:foreground default :background default :scale 1.0
3592 :html-foreground "Black" :html-background "Transparent"
3593 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3594 "Options for creating images from LaTeX fragments.
3595 This is a property list with the following properties:
3596 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3597 `default' means use the foreground of the default face.
3598 `auto' means use the foreground from the text face.
3599 :background the background color, or \"Transparent\".
3600 `default' means use the background of the default face.
3601 `auto' means use the background from the text face.
3602 :scale a scaling factor for the size of the images, to get more pixels
3603 :html-foreground, :html-background, :html-scale
3604 the same numbers for HTML export.
3605 :matchers a list indicating which matchers should be used to
3606 find LaTeX fragments. Valid members of this list are:
3607 \"begin\" find environments
3608 \"$1\" find single characters surrounded by $.$
3609 \"$\" find math expressions surrounded by $...$
3610 \"$$\" find math expressions surrounded by $$....$$
3611 \"\\(\" find math expressions surrounded by \\(...\\)
3612 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3613 :group 'org-latex
3614 :type 'plist)
3616 (defcustom org-format-latex-signal-error t
3617 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3618 When nil, just push out a message."
3619 :group 'org-latex
3620 :version "24.1"
3621 :type 'boolean)
3623 (defcustom org-latex-to-mathml-jar-file nil
3624 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3625 Use this to specify additional executable file say a jar file.
3627 When using MathToWeb as the converter, specify the full-path to
3628 your mathtoweb.jar file."
3629 :group 'org-latex
3630 :version "24.1"
3631 :type '(choice
3632 (const :tag "None" nil)
3633 (file :tag "JAR file" :must-match t)))
3635 (defcustom org-latex-to-mathml-convert-command nil
3636 "Command to convert LaTeX fragments to MathML.
3637 Replace format-specifiers in the command as noted below and use
3638 `shell-command' to convert LaTeX to MathML.
3639 %j: Executable file in fully expanded form as specified by
3640 `org-latex-to-mathml-jar-file'.
3641 %I: Input LaTeX file in fully expanded form
3642 %o: Output MathML file
3643 This command is used by `org-create-math-formula'.
3645 When using MathToWeb as the converter, set this to
3646 \"java -jar %j -unicode -force -df %o %I\"."
3647 :group 'org-latex
3648 :version "24.1"
3649 :type '(choice
3650 (const :tag "None" nil)
3651 (string :tag "\nShell command")))
3653 (defcustom org-latex-create-formula-image-program 'dvipng
3654 "Program to convert LaTeX fragments with.
3656 dvipng Process the LaTeX fragments to dvi file, then convert
3657 dvi files to png files using dvipng.
3658 This will also include processing of non-math environments.
3659 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3660 to convert pdf files to png files"
3661 :group 'org-latex
3662 :version "24.1"
3663 :type '(choice
3664 (const :tag "dvipng" dvipng)
3665 (const :tag "imagemagick" imagemagick)))
3667 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3668 "Path to store latex preview images.
3669 A relative path here creates many directories relative to the
3670 processed org files paths. An absolute path puts all preview
3671 images at the same place."
3672 :group 'org-latex
3673 :version "24.3"
3674 :type 'string)
3676 (defun org-format-latex-mathml-available-p ()
3677 "Return t if `org-latex-to-mathml-convert-command' is usable."
3678 (save-match-data
3679 (when (and (boundp 'org-latex-to-mathml-convert-command)
3680 org-latex-to-mathml-convert-command)
3681 (let ((executable (car (split-string
3682 org-latex-to-mathml-convert-command))))
3683 (when (executable-find executable)
3684 (if (string-match
3685 "%j" org-latex-to-mathml-convert-command)
3686 (file-readable-p org-latex-to-mathml-jar-file)
3687 t))))))
3689 (defcustom org-format-latex-header "\\documentclass{article}
3690 \\usepackage[usenames]{color}
3691 \\usepackage{amsmath}
3692 \\usepackage[mathscr]{eucal}
3693 \\pagestyle{empty} % do not remove
3694 \[PACKAGES]
3695 \[DEFAULT-PACKAGES]
3696 % The settings below are copied from fullpage.sty
3697 \\setlength{\\textwidth}{\\paperwidth}
3698 \\addtolength{\\textwidth}{-3cm}
3699 \\setlength{\\oddsidemargin}{1.5cm}
3700 \\addtolength{\\oddsidemargin}{-2.54cm}
3701 \\setlength{\\evensidemargin}{\\oddsidemargin}
3702 \\setlength{\\textheight}{\\paperheight}
3703 \\addtolength{\\textheight}{-\\headheight}
3704 \\addtolength{\\textheight}{-\\headsep}
3705 \\addtolength{\\textheight}{-\\footskip}
3706 \\addtolength{\\textheight}{-3cm}
3707 \\setlength{\\topmargin}{1.5cm}
3708 \\addtolength{\\topmargin}{-2.54cm}"
3709 "The document header used for processing LaTeX fragments.
3710 It is imperative that this header make sure that no page number
3711 appears on the page. The package defined in the variables
3712 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3713 will either replace the placeholder \"[PACKAGES]\" in this
3714 header, or they will be appended."
3715 :group 'org-latex
3716 :type 'string)
3718 (defun org-set-packages-alist (var val)
3719 "Set the packages alist and make sure it has 3 elements per entry."
3720 (set var (mapcar (lambda (x)
3721 (if (and (consp x) (= (length x) 2))
3722 (list (car x) (nth 1 x) t)
3724 val)))
3726 (defun org-get-packages-alist (var)
3727 "Get the packages alist and make sure it has 3 elements per entry."
3728 (mapcar (lambda (x)
3729 (if (and (consp x) (= (length x) 2))
3730 (list (car x) (nth 1 x) t)
3732 (default-value var)))
3734 (defcustom org-latex-default-packages-alist
3735 '(("AUTO" "inputenc" t)
3736 ("T1" "fontenc" t)
3737 ("" "fixltx2e" nil)
3738 ("" "graphicx" t)
3739 ("" "longtable" nil)
3740 ("" "float" nil)
3741 ("" "wrapfig" nil)
3742 ("" "soul" t)
3743 ("" "textcomp" t)
3744 ("" "marvosym" t)
3745 ("" "wasysym" t)
3746 ("" "latexsym" t)
3747 ("" "amssymb" t)
3748 ("" "hyperref" nil)
3749 "\\tolerance=1000")
3750 "Alist of default packages to be inserted in the header.
3752 Change this only if one of the packages here causes an
3753 incompatibility with another package you are using.
3755 The packages in this list are needed by one part or another of
3756 Org mode to function properly:
3758 - inputenc, fontenc: for basic font and character selection
3759 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3760 symbols used for interpreting the entities in `org-entities'.
3761 You can skip some of these packages if you don't use any of the
3762 symbols in it.
3763 - graphicx: for including images
3764 - float, wrapfig: for figure placement
3765 - longtable: for long tables
3766 - hyperref: for cross references
3768 Therefore you should not modify this variable unless you know
3769 what you are doing. The one reason to change it anyway is that
3770 you might be loading some other package that conflicts with one
3771 of the default packages. Each cell is of the format
3772 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3773 the package also needs to be included when compiling LaTeX
3774 snippets into images for inclusion into non-LaTeX output."
3775 :group 'org-latex
3776 :group 'org-export-latex
3777 :set 'org-set-packages-alist
3778 :get 'org-get-packages-alist
3779 :version "24.1"
3780 :type '(repeat
3781 (choice
3782 (list :tag "options/package pair"
3783 (string :tag "options")
3784 (string :tag "package")
3785 (boolean :tag "Snippet"))
3786 (string :tag "A line of LaTeX"))))
3788 (defcustom org-latex-packages-alist nil
3789 "Alist of packages to be inserted in every LaTeX header.
3791 These will be inserted after `org-latex-default-packages-alist'.
3792 Each cell is of the format:
3794 \(\"options\" \"package\" snippet-flag)
3796 SNIPPET-FLAG, when t, indicates that this package is also needed
3797 when turning LaTeX snippets into images for inclusion into
3798 non-LaTeX output.
3800 Make sure that you only list packages here which:
3802 - you want in every file
3803 - do not conflict with the setup in `org-format-latex-header'.
3804 - do not conflict with the default packages in
3805 `org-latex-default-packages-alist'."
3806 :group 'org-latex
3807 :group 'org-export-latex
3808 :set 'org-set-packages-alist
3809 :get 'org-get-packages-alist
3810 :type '(repeat
3811 (choice
3812 (list :tag "options/package pair"
3813 (string :tag "options")
3814 (string :tag "package")
3815 (boolean :tag "Snippet"))
3816 (string :tag "A line of LaTeX"))))
3818 (defgroup org-appearance nil
3819 "Settings for Org-mode appearance."
3820 :tag "Org Appearance"
3821 :group 'org)
3823 (defcustom org-level-color-stars-only nil
3824 "Non-nil means fontify only the stars in each headline.
3825 When nil, the entire headline is fontified.
3826 Changing it requires restart of `font-lock-mode' to become effective
3827 also in regions already fontified."
3828 :group 'org-appearance
3829 :type 'boolean)
3831 (defcustom org-hide-leading-stars nil
3832 "Non-nil means hide the first N-1 stars in a headline.
3833 This works by using the face `org-hide' for these stars. This
3834 face is white for a light background, and black for a dark
3835 background. You may have to customize the face `org-hide' to
3836 make this work.
3837 Changing it requires restart of `font-lock-mode' to become effective
3838 also in regions already fontified.
3839 You may also set this on a per-file basis by adding one of the following
3840 lines to the buffer:
3842 #+STARTUP: hidestars
3843 #+STARTUP: showstars"
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hidden-keywords nil
3848 "List of symbols corresponding to keywords to be hidden the org buffer.
3849 For example, a value '(title) for this list will make the document's title
3850 appear in the buffer without the initial #+TITLE: keyword."
3851 :group 'org-appearance
3852 :version "24.1"
3853 :type '(set (const :tag "#+AUTHOR" author)
3854 (const :tag "#+DATE" date)
3855 (const :tag "#+EMAIL" email)
3856 (const :tag "#+TITLE" title)))
3858 (defcustom org-custom-properties nil
3859 "List of properties (as strings) with a special meaning.
3860 The default use of these custom properties is to let the user
3861 hide them with `org-toggle-custom-properties-visibility'."
3862 :group 'org-properties
3863 :group 'org-appearance
3864 :version "24.3"
3865 :type '(repeat (string :tag "Property Name")))
3867 (defcustom org-fontify-done-headline nil
3868 "Non-nil means change the face of a headline if it is marked DONE.
3869 Normally, only the TODO/DONE keyword indicates the state of a headline.
3870 When this is non-nil, the headline after the keyword is set to the
3871 `org-headline-done' as an additional indication."
3872 :group 'org-appearance
3873 :type 'boolean)
3875 (defcustom org-fontify-emphasized-text t
3876 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3877 Changing this variable requires a restart of Emacs to take effect."
3878 :group 'org-appearance
3879 :type 'boolean)
3881 (defcustom org-fontify-whole-heading-line nil
3882 "Non-nil means fontify the whole line for headings.
3883 This is useful when setting a background color for the
3884 org-level-* faces."
3885 :group 'org-appearance
3886 :type 'boolean)
3888 (defcustom org-hide-emphasis-markers nil
3889 "Non-nil mean font-lock should hide the emphasis marker characters."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-pretty-entities nil
3894 "Non-nil means show entities as UTF8 characters.
3895 When nil, the \\name form remains in the buffer."
3896 :group 'org-appearance
3897 :version "24.1"
3898 :type 'boolean)
3900 (defcustom org-pretty-entities-include-sub-superscripts t
3901 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3902 :group 'org-appearance
3903 :version "24.1"
3904 :type 'boolean)
3906 (defvar org-emph-re nil
3907 "Regular expression for matching emphasis.
3908 After a match, the match groups contain these elements:
3909 0 The match of the full regular expression, including the characters
3910 before and after the proper match
3911 1 The character before the proper match, or empty at beginning of line
3912 2 The proper match, including the leading and trailing markers
3913 3 The leading marker like * or /, indicating the type of highlighting
3914 4 The text between the emphasis markers, not including the markers
3915 5 The character after the match, empty at the end of a line")
3916 (defvar org-verbatim-re nil
3917 "Regular expression for matching verbatim text.")
3918 (defvar org-emphasis-regexp-components) ; defined just below
3919 (defvar org-emphasis-alist) ; defined just below
3920 (defun org-set-emph-re (var val)
3921 "Set variable and compute the emphasis regular expression."
3922 (set var val)
3923 (when (and (boundp 'org-emphasis-alist)
3924 (boundp 'org-emphasis-regexp-components)
3925 org-emphasis-alist org-emphasis-regexp-components)
3926 (let* ((e org-emphasis-regexp-components)
3927 (pre (car e))
3928 (post (nth 1 e))
3929 (border (nth 2 e))
3930 (body (nth 3 e))
3931 (nl (nth 4 e))
3932 (body1 (concat body "*?"))
3933 (markers (mapconcat 'car org-emphasis-alist ""))
3934 (vmarkers (mapconcat
3935 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3936 org-emphasis-alist "")))
3937 ;; make sure special characters appear at the right position in the class
3938 (if (string-match "\\^" markers)
3939 (setq markers (concat (replace-match "" t t markers) "^")))
3940 (if (string-match "-" markers)
3941 (setq markers (concat (replace-match "" t t markers) "-")))
3942 (if (string-match "\\^" vmarkers)
3943 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3944 (if (string-match "-" vmarkers)
3945 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3946 (if (> nl 0)
3947 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3948 (int-to-string nl) "\\}")))
3949 ;; Make the regexp
3950 (setq org-emph-re
3951 (concat "\\([" pre "]\\|^\\)"
3952 "\\("
3953 "\\([" markers "]\\)"
3954 "\\("
3955 "[^" border "]\\|"
3956 "[^" border "]"
3957 body1
3958 "[^" border "]"
3959 "\\)"
3960 "\\3\\)"
3961 "\\([" post "]\\|$\\)"))
3962 (setq org-verbatim-re
3963 (concat "\\([" pre "]\\|^\\)"
3964 "\\("
3965 "\\([" vmarkers "]\\)"
3966 "\\("
3967 "[^" border "]\\|"
3968 "[^" border "]"
3969 body1
3970 "[^" border "]"
3971 "\\)"
3972 "\\3\\)"
3973 "\\([" post "]\\|$\\)")))))
3975 (defcustom org-emphasis-regexp-components
3976 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3977 "Components used to build the regular expression for emphasis.
3978 This is a list with five entries. Terminology: In an emphasis string
3979 like \" *strong word* \", we call the initial space PREMATCH, the final
3980 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3981 and \"trong wor\" is the body. The different components in this variable
3982 specify what is allowed/forbidden in each part:
3984 pre Chars allowed as prematch. Beginning of line will be allowed too.
3985 post Chars allowed as postmatch. End of line will be allowed too.
3986 border The chars *forbidden* as border characters.
3987 body-regexp A regexp like \".\" to match a body character. Don't use
3988 non-shy groups here, and don't allow newline here.
3989 newline The maximum number of newlines allowed in an emphasis exp.
3991 Use customize to modify this, or restart Emacs after changing it."
3992 :group 'org-appearance
3993 :set 'org-set-emph-re
3994 :type '(list
3995 (sexp :tag "Allowed chars in pre ")
3996 (sexp :tag "Allowed chars in post ")
3997 (sexp :tag "Forbidden chars in border ")
3998 (sexp :tag "Regexp for body ")
3999 (integer :tag "number of newlines allowed")
4000 (option (boolean :tag "Please ignore this button"))))
4002 (defcustom org-emphasis-alist
4003 `(("*" bold "<b>" "</b>")
4004 ("/" italic "<i>" "</i>")
4005 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4006 ("=" org-code "<code>" "</code>" verbatim)
4007 ("~" org-verbatim "<code>" "</code>" verbatim)
4008 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4009 "<del>" "</del>")
4011 "Special syntax for emphasized text.
4012 Text starting and ending with a special character will be emphasized, for
4013 example *bold*, _underlined_ and /italic/. This variable sets the marker
4014 characters, the face to be used by font-lock for highlighting in Org-mode
4015 Emacs buffers, and the HTML tags to be used for this.
4016 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4017 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4018 Use customize to modify this, or restart Emacs after changing it."
4019 :group 'org-appearance
4020 :set 'org-set-emph-re
4021 :type '(repeat
4022 (list
4023 (string :tag "Marker character")
4024 (choice
4025 (face :tag "Font-lock-face")
4026 (plist :tag "Face property list"))
4027 (string :tag "HTML start tag")
4028 (string :tag "HTML end tag")
4029 (option (const verbatim)))))
4031 (defvar org-syntax-table
4032 (let ((st (make-syntax-table)))
4033 (mapc (lambda(c) (modify-syntax-entry
4034 (string-to-char (car c)) "w p" st))
4035 org-emphasis-alist)
4036 st))
4038 (defvar org-protecting-blocks
4039 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4040 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4041 This is needed for font-lock setup.")
4043 ;;; Miscellaneous options
4045 (defgroup org-completion nil
4046 "Completion in Org-mode."
4047 :tag "Org Completion"
4048 :group 'org)
4050 (defcustom org-completion-use-ido nil
4051 "Non-nil means use ido completion wherever possible.
4052 Note that `ido-mode' must be active for this variable to be relevant.
4053 If you decide to turn this variable on, you might well want to turn off
4054 `org-outline-path-complete-in-steps'.
4055 See also `org-completion-use-iswitchb'."
4056 :group 'org-completion
4057 :type 'boolean)
4059 (defcustom org-completion-use-iswitchb nil
4060 "Non-nil means use iswitchb completion wherever possible.
4061 Note that `iswitchb-mode' must be active for this variable to be relevant.
4062 If you decide to turn this variable on, you might well want to turn off
4063 `org-outline-path-complete-in-steps'.
4064 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4065 :group 'org-completion
4066 :type 'boolean)
4068 (defcustom org-completion-fallback-command 'hippie-expand
4069 "The expansion command called by \\[pcomplete] in normal context.
4070 Normal means, no org-mode-specific context."
4071 :group 'org-completion
4072 :type 'function)
4074 ;;; Functions and variables from their packages
4075 ;; Declared here to avoid compiler warnings
4077 ;; XEmacs only
4078 (defvar outline-mode-menu-heading)
4079 (defvar outline-mode-menu-show)
4080 (defvar outline-mode-menu-hide)
4081 (defvar zmacs-regions) ; XEmacs regions
4083 ;; Emacs only
4084 (defvar mark-active)
4086 ;; Various packages
4087 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4088 (declare-function calendar-forward-day "cal-move" (arg))
4089 (declare-function calendar-goto-date "cal-move" (date))
4090 (declare-function calendar-goto-today "cal-move" ())
4091 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4092 (defvar calc-embedded-close-formula)
4093 (defvar calc-embedded-open-formula)
4094 (declare-function cdlatex-tab "ext:cdlatex" ())
4095 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4096 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4097 (defvar font-lock-unfontify-region-function)
4098 (declare-function iswitchb-read-buffer "iswitchb"
4099 (prompt &optional default require-match start matches-set))
4100 (defvar iswitchb-temp-buflist)
4101 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4102 (defvar org-agenda-tags-todo-honor-ignore-options)
4103 (declare-function org-agenda-skip "org-agenda" ())
4104 (declare-function
4105 org-agenda-format-item "org-agenda"
4106 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4107 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4108 (declare-function org-agenda-change-all-lines "org-agenda"
4109 (newhead hdmarker &optional fixface just-this))
4110 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4111 (declare-function org-agenda-maybe-redo "org-agenda" ())
4112 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4113 (beg end))
4114 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4115 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4116 "org-agenda" (&optional end))
4117 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4118 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4119 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4120 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4121 (declare-function org-indent-mode "org-indent" (&optional arg))
4122 (declare-function parse-time-string "parse-time" (string))
4123 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4124 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4125 (defvar remember-data-file)
4126 (defvar texmathp-why)
4127 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4128 (declare-function table--at-cell-p "table" (position &optional object at-column))
4130 (defvar org-latex-regexps)
4132 ;;; Autoload and prepare some org modules
4134 ;; Some table stuff that needs to be defined here, because it is used
4135 ;; by the functions setting up org-mode or checking for table context.
4137 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4138 "Detect an org-type or table-type table.")
4139 (defconst org-table-line-regexp "^[ \t]*|"
4140 "Detect an org-type table line.")
4141 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4142 "Detect an org-type table line.")
4143 (defconst org-table-hline-regexp "^[ \t]*|-"
4144 "Detect an org-type table hline.")
4145 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4146 "Detect a table-type table hline.")
4147 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4148 "Detect the first line outside a table when searching from within it.
4149 This works for both table types.")
4151 ;; Autoload the functions in org-table.el that are needed by functions here.
4153 (eval-and-compile
4154 (org-autoload "org-table"
4155 '(org-table-begin org-table-blank-field org-table-end)))
4157 ;;;###autoload
4158 (defun turn-on-orgtbl ()
4159 "Unconditionally turn on `orgtbl-mode'."
4160 (require 'org-table)
4161 (orgtbl-mode 1))
4163 (defun org-at-table-p (&optional table-type)
4164 "Return t if the cursor is inside an org-type table.
4165 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4166 (if org-enable-table-editor
4167 (save-excursion
4168 (beginning-of-line 1)
4169 (looking-at (if table-type org-table-any-line-regexp
4170 org-table-line-regexp)))
4171 nil))
4172 (defsubst org-table-p () (org-at-table-p))
4174 (defun org-at-table.el-p ()
4175 "Return t if and only if we are at a table.el table."
4176 (and (org-at-table-p 'any)
4177 (save-excursion
4178 (goto-char (org-table-begin 'any))
4179 (looking-at org-table1-hline-regexp))))
4180 (defun org-table-recognize-table.el ()
4181 "If there is a table.el table nearby, recognize it and move into it."
4182 (if org-table-tab-recognizes-table.el
4183 (if (org-at-table.el-p)
4184 (progn
4185 (beginning-of-line 1)
4186 (if (looking-at org-table-dataline-regexp)
4188 (if (looking-at org-table1-hline-regexp)
4189 (progn
4190 (beginning-of-line 2)
4191 (if (looking-at org-table-any-border-regexp)
4192 (beginning-of-line -1)))))
4193 (if (re-search-forward "|" (org-table-end t) t)
4194 (progn
4195 (require 'table)
4196 (if (table--at-cell-p (point))
4198 (message "recognizing table.el table...")
4199 (table-recognize-table)
4200 (message "recognizing table.el table...done")))
4201 (error "This should not happen"))
4203 nil)
4204 nil))
4206 (defun org-at-table-hline-p ()
4207 "Return t if the cursor is inside a hline in a table."
4208 (if org-enable-table-editor
4209 (save-excursion
4210 (beginning-of-line 1)
4211 (looking-at org-table-hline-regexp))
4212 nil))
4214 (defvar org-table-clean-did-remove-column nil)
4216 (defun org-table-map-tables (function &optional quietly)
4217 "Apply FUNCTION to the start of all tables in the buffer."
4218 (save-excursion
4219 (save-restriction
4220 (widen)
4221 (goto-char (point-min))
4222 (while (re-search-forward org-table-any-line-regexp nil t)
4223 (unless quietly
4224 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4225 (beginning-of-line 1)
4226 (when (and (looking-at org-table-line-regexp)
4227 ;; Exclude tables in src/example/verbatim/clocktable blocks
4228 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4229 (save-excursion (funcall function))
4230 (or (looking-at org-table-line-regexp)
4231 (forward-char 1)))
4232 (re-search-forward org-table-any-border-regexp nil 1))))
4233 (unless quietly (message "Mapping tables: done")))
4235 ;; Declare and autoload functions from ox.el and al.
4237 (declare-function org-export-get-environment "ox"
4238 (&optional backend subtreep ext-plist))
4239 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4241 ;; Declare and autoload functions from org-agenda.el
4243 (eval-and-compile
4244 (org-autoload "org-agenda"
4245 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4247 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4248 (declare-function org-clock-update-mode-line "org-clock" ())
4249 (declare-function org-resolve-clocks "org-clock"
4250 (&optional also-non-dangling-p prompt last-valid))
4251 (defvar org-clock-start-time)
4252 (defvar org-clock-marker (make-marker)
4253 "Marker recording the last clock-in.")
4254 (defvar org-clock-hd-marker (make-marker)
4255 "Marker recording the last clock-in, but the headline position.")
4256 (defvar org-clock-heading ""
4257 "The heading of the current clock entry.")
4258 (defun org-clock-is-active ()
4259 "Return non-nil if clock is currently running.
4260 The return value is actually the clock marker."
4261 (marker-buffer org-clock-marker))
4263 (eval-and-compile
4264 (org-autoload "org-clock" '(org-clock-remove-overlays
4265 org-clock-update-time-maybe
4266 org-clocktable-shift)))
4268 (defun org-check-running-clock ()
4269 "Check if the current buffer contains the running clock.
4270 If yes, offer to stop it and to save the buffer with the changes."
4271 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4272 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4273 (buffer-name))))
4274 (org-clock-out)
4275 (when (y-or-n-p "Save changed buffer?")
4276 (save-buffer))))
4278 (defun org-clocktable-try-shift (dir n)
4279 "Check if this line starts a clock table, if yes, shift the time block."
4280 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4281 (org-clocktable-shift dir n)))
4283 ;;;###autoload
4284 (defun org-clock-persistence-insinuate ()
4285 "Set up hooks for clock persistence."
4286 (require 'org-clock)
4287 (add-hook 'org-mode-hook 'org-clock-load)
4288 (add-hook 'kill-emacs-hook 'org-clock-save))
4290 ;; Define the variable already here, to make sure we have it.
4291 (defvar org-indent-mode nil
4292 "Non-nil if Org-Indent mode is enabled.
4293 Use the command `org-indent-mode' to change this variable.")
4295 ;; Autoload archiving code
4296 ;; The stuff that is needed for cycling and tags has to be defined here.
4298 (defgroup org-archive nil
4299 "Options concerning archiving in Org-mode."
4300 :tag "Org Archive"
4301 :group 'org-structure)
4303 (defcustom org-archive-location "%s_archive::"
4304 "The location where subtrees should be archived.
4306 The value of this variable is a string, consisting of two parts,
4307 separated by a double-colon. The first part is a filename and
4308 the second part is a headline.
4310 When the filename is omitted, archiving happens in the same file.
4311 %s in the filename will be replaced by the current file
4312 name (without the directory part). Archiving to a different file
4313 is useful to keep archived entries from contributing to the
4314 Org-mode Agenda.
4316 The archived entries will be filed as subtrees of the specified
4317 headline. When the headline is omitted, the subtrees are simply
4318 filed away at the end of the file, as top-level entries. Also in
4319 the heading you can use %s to represent the file name, this can be
4320 useful when using the same archive for a number of different files.
4322 Here are a few examples:
4323 \"%s_archive::\"
4324 If the current file is Projects.org, archive in file
4325 Projects.org_archive, as top-level trees. This is the default.
4327 \"::* Archived Tasks\"
4328 Archive in the current file, under the top-level headline
4329 \"* Archived Tasks\".
4331 \"~/org/archive.org::\"
4332 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4334 \"~/org/archive.org::* From %s\"
4335 Archive in file ~/org/archive.org (absolute path), under headlines
4336 \"From FILENAME\" where file name is the current file name.
4338 \"~/org/datetree.org::datetree/* Finished Tasks\"
4339 The \"datetree/\" string is special, signifying to archive
4340 items to the datetree. Items are placed in either the CLOSED
4341 date of the item, or the current date if there is no CLOSED date.
4342 The heading will be a subentry to the current date. There doesn't
4343 need to be a heading, but there always needs to be a slash after
4344 datetree. For example, to store archived items directly in the
4345 datetree, use \"~/org/datetree.org::datetree/\".
4347 \"basement::** Finished Tasks\"
4348 Archive in file ./basement (relative path), as level 3 trees
4349 below the level 2 heading \"** Finished Tasks\".
4351 You may set this option on a per-file basis by adding to the buffer a
4352 line like
4354 #+ARCHIVE: basement::** Finished Tasks
4356 You may also define it locally for a subtree by setting an ARCHIVE property
4357 in the entry. If such a property is found in an entry, or anywhere up
4358 the hierarchy, it will be used."
4359 :group 'org-archive
4360 :type 'string)
4362 (defcustom org-archive-tag "ARCHIVE"
4363 "The tag that marks a subtree as archived.
4364 An archived subtree does not open during visibility cycling, and does
4365 not contribute to the agenda listings.
4366 After changing this, font-lock must be restarted in the relevant buffers to
4367 get the proper fontification."
4368 :group 'org-archive
4369 :group 'org-keywords
4370 :type 'string)
4372 (defcustom org-agenda-skip-archived-trees t
4373 "Non-nil means the agenda will skip any items located in archived trees.
4374 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4375 variable is no longer recommended, you should leave it at the value t.
4376 Instead, use the key `v' to cycle the archives-mode in the agenda."
4377 :group 'org-archive
4378 :group 'org-agenda-skip
4379 :type 'boolean)
4381 (defcustom org-columns-skip-archived-trees t
4382 "Non-nil means ignore archived trees when creating column view."
4383 :group 'org-archive
4384 :group 'org-properties
4385 :type 'boolean)
4387 (defcustom org-cycle-open-archived-trees nil
4388 "Non-nil means `org-cycle' will open archived trees.
4389 An archived tree is a tree marked with the tag ARCHIVE.
4390 When nil, archived trees will stay folded. You can still open them with
4391 normal outline commands like `show-all', but not with the cycling commands."
4392 :group 'org-archive
4393 :group 'org-cycle
4394 :type 'boolean)
4396 (defcustom org-sparse-tree-open-archived-trees nil
4397 "Non-nil means sparse tree construction shows matches in archived trees.
4398 When nil, matches in these trees are highlighted, but the trees are kept in
4399 collapsed state."
4400 :group 'org-archive
4401 :group 'org-sparse-trees
4402 :type 'boolean)
4404 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4405 "The default date type when building a sparse tree.
4406 When this is nil, a date is a scheduled or a deadline timestamp.
4407 Otherwise, these types are allowed:
4409 all: all timestamps
4410 active: only active timestamps (<...>)
4411 inactive: only inactive timestamps (<...)
4412 scheduled: only scheduled timestamps
4413 deadline: only deadline timestamps"
4414 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4415 (const :tag "All timestamps" all)
4416 (const :tag "Only active timestamps" active)
4417 (const :tag "Only inactive timestamps" inactive)
4418 (const :tag "Only scheduled timestamps" scheduled)
4419 (const :tag "Only deadline timestamps" deadline))
4420 :version "24.3"
4421 :group 'org-sparse-trees)
4423 (defun org-cycle-hide-archived-subtrees (state)
4424 "Re-hide all archived subtrees after a visibility state change."
4425 (when (and (not org-cycle-open-archived-trees)
4426 (not (memq state '(overview folded))))
4427 (save-excursion
4428 (let* ((globalp (memq state '(contents all)))
4429 (beg (if globalp (point-min) (point)))
4430 (end (if globalp (point-max) (org-end-of-subtree t))))
4431 (org-hide-archived-subtrees beg end)
4432 (goto-char beg)
4433 (if (looking-at (concat ".*:" org-archive-tag ":"))
4434 (message "%s" (substitute-command-keys
4435 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4437 (defun org-force-cycle-archived ()
4438 "Cycle subtree even if it is archived."
4439 (interactive)
4440 (setq this-command 'org-cycle)
4441 (let ((org-cycle-open-archived-trees t))
4442 (call-interactively 'org-cycle)))
4444 (defun org-hide-archived-subtrees (beg end)
4445 "Re-hide all archived subtrees after a visibility state change."
4446 (save-excursion
4447 (let* ((re (concat ":" org-archive-tag ":")))
4448 (goto-char beg)
4449 (while (re-search-forward re end t)
4450 (when (org-at-heading-p)
4451 (org-flag-subtree t)
4452 (org-end-of-subtree t))))))
4454 (declare-function outline-end-of-heading "outline" ())
4455 (declare-function outline-flag-region "outline" (from to flag))
4456 (defun org-flag-subtree (flag)
4457 (save-excursion
4458 (org-back-to-heading t)
4459 (outline-end-of-heading)
4460 (outline-flag-region (point)
4461 (progn (org-end-of-subtree t) (point))
4462 flag)))
4464 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4466 (eval-and-compile
4467 (org-autoload "org-archive"
4468 '(org-add-archive-files)))
4470 ;; Autoload Column View Code
4472 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4473 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4474 (declare-function org-columns-compute "org-colview" (property))
4476 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4477 '(org-columns-number-to-string
4478 org-columns-get-format-and-top-level
4479 org-columns-compute
4480 org-columns-remove-overlays))
4482 ;; Autoload ID code
4484 (declare-function org-id-store-link "org-id")
4485 (declare-function org-id-locations-load "org-id")
4486 (declare-function org-id-locations-save "org-id")
4487 (defvar org-id-track-globally)
4488 (org-autoload "org-id"
4489 '(org-id-new
4490 org-id-copy
4491 org-id-get-with-outline-path-completion
4492 org-id-get-with-outline-drilling))
4494 ;;; Variables for pre-computed regular expressions, all buffer local
4496 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4497 "Matches first line of a hidden block.")
4498 (make-variable-buffer-local 'org-drawer-regexp)
4499 (defvar org-todo-regexp nil
4500 "Matches any of the TODO state keywords.")
4501 (make-variable-buffer-local 'org-todo-regexp)
4502 (defvar org-not-done-regexp nil
4503 "Matches any of the TODO state keywords except the last one.")
4504 (make-variable-buffer-local 'org-not-done-regexp)
4505 (defvar org-not-done-heading-regexp nil
4506 "Matches a TODO headline that is not done.")
4507 (make-variable-buffer-local 'org-not-done-regexp)
4508 (defvar org-todo-line-regexp nil
4509 "Matches a headline and puts TODO state into group 2 if present.")
4510 (make-variable-buffer-local 'org-todo-line-regexp)
4511 (defvar org-complex-heading-regexp nil
4512 "Matches a headline and puts everything into groups:
4513 group 1: the stars
4514 group 2: The todo keyword, maybe
4515 group 3: Priority cookie
4516 group 4: True headline
4517 group 5: Tags")
4518 (make-variable-buffer-local 'org-complex-heading-regexp)
4519 (defvar org-complex-heading-regexp-format nil
4520 "Printf format to make regexp to match an exact headline.
4521 This regexp will match the headline of any node which has the
4522 exact headline text that is put into the format, but may have any
4523 TODO state, priority and tags.")
4524 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4525 (defvar org-todo-line-tags-regexp nil
4526 "Matches a headline and puts TODO state into group 2 if present.
4527 Also put tags into group 4 if tags are present.")
4528 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4529 (defvar org-ds-keyword-length 12
4530 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4531 (make-variable-buffer-local 'org-ds-keyword-length)
4532 (defvar org-deadline-regexp nil
4533 "Matches the DEADLINE keyword.")
4534 (make-variable-buffer-local 'org-deadline-regexp)
4535 (defvar org-deadline-time-regexp nil
4536 "Matches the DEADLINE keyword together with a time stamp.")
4537 (make-variable-buffer-local 'org-deadline-time-regexp)
4538 (defvar org-deadline-line-regexp nil
4539 "Matches the DEADLINE keyword and the rest of the line.")
4540 (make-variable-buffer-local 'org-deadline-line-regexp)
4541 (defvar org-scheduled-regexp nil
4542 "Matches the SCHEDULED keyword.")
4543 (make-variable-buffer-local 'org-scheduled-regexp)
4544 (defvar org-scheduled-time-regexp nil
4545 "Matches the SCHEDULED keyword together with a time stamp.")
4546 (make-variable-buffer-local 'org-scheduled-time-regexp)
4547 (defvar org-closed-time-regexp nil
4548 "Matches the CLOSED keyword together with a time stamp.")
4549 (make-variable-buffer-local 'org-closed-time-regexp)
4551 (defvar org-keyword-time-regexp nil
4552 "Matches any of the 4 keywords, together with the time stamp.")
4553 (make-variable-buffer-local 'org-keyword-time-regexp)
4554 (defvar org-keyword-time-not-clock-regexp nil
4555 "Matches any of the 3 keywords, together with the time stamp.")
4556 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4557 (defvar org-maybe-keyword-time-regexp nil
4558 "Matches a timestamp, possibly preceded by a keyword.")
4559 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4560 (defvar org-all-time-keywords nil
4561 "List of time keywords.")
4562 (make-variable-buffer-local 'org-all-time-keywords)
4564 (defconst org-plain-time-of-day-regexp
4565 (concat
4566 "\\(\\<[012]?[0-9]"
4567 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4568 "\\(--?"
4569 "\\(\\<[012]?[0-9]"
4570 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4571 "\\)?")
4572 "Regular expression to match a plain time or time range.
4573 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4574 groups carry important information:
4575 0 the full match
4576 1 the first time, range or not
4577 8 the second time, if it is a range.")
4579 (defconst org-plain-time-extension-regexp
4580 (concat
4581 "\\(\\<[012]?[0-9]"
4582 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4583 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4584 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4585 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4586 groups carry important information:
4587 0 the full match
4588 7 hours of duration
4589 9 minutes of duration")
4591 (defconst org-stamp-time-of-day-regexp
4592 (concat
4593 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4594 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4595 "\\(--?"
4596 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4597 "Regular expression to match a timestamp time or time range.
4598 After a match, the following groups carry important information:
4599 0 the full match
4600 1 date plus weekday, for back referencing to make sure both times are on the same day
4601 2 the first time, range or not
4602 4 the second time, if it is a range.")
4604 (defconst org-startup-options
4605 '(("fold" org-startup-folded t)
4606 ("overview" org-startup-folded t)
4607 ("nofold" org-startup-folded nil)
4608 ("showall" org-startup-folded nil)
4609 ("showeverything" org-startup-folded showeverything)
4610 ("content" org-startup-folded content)
4611 ("indent" org-startup-indented t)
4612 ("noindent" org-startup-indented nil)
4613 ("hidestars" org-hide-leading-stars t)
4614 ("showstars" org-hide-leading-stars nil)
4615 ("odd" org-odd-levels-only t)
4616 ("oddeven" org-odd-levels-only nil)
4617 ("align" org-startup-align-all-tables t)
4618 ("noalign" org-startup-align-all-tables nil)
4619 ("inlineimages" org-startup-with-inline-images t)
4620 ("noinlineimages" org-startup-with-inline-images nil)
4621 ("customtime" org-display-custom-times t)
4622 ("logdone" org-log-done time)
4623 ("lognotedone" org-log-done note)
4624 ("nologdone" org-log-done nil)
4625 ("lognoteclock-out" org-log-note-clock-out t)
4626 ("nolognoteclock-out" org-log-note-clock-out nil)
4627 ("logrepeat" org-log-repeat state)
4628 ("lognoterepeat" org-log-repeat note)
4629 ("logdrawer" org-log-into-drawer t)
4630 ("nologdrawer" org-log-into-drawer nil)
4631 ("logstatesreversed" org-log-states-order-reversed t)
4632 ("nologstatesreversed" org-log-states-order-reversed nil)
4633 ("nologrepeat" org-log-repeat nil)
4634 ("logreschedule" org-log-reschedule time)
4635 ("lognotereschedule" org-log-reschedule note)
4636 ("nologreschedule" org-log-reschedule nil)
4637 ("logredeadline" org-log-redeadline time)
4638 ("lognoteredeadline" org-log-redeadline note)
4639 ("nologredeadline" org-log-redeadline nil)
4640 ("logrefile" org-log-refile time)
4641 ("lognoterefile" org-log-refile note)
4642 ("nologrefile" org-log-refile nil)
4643 ("fninline" org-footnote-define-inline t)
4644 ("nofninline" org-footnote-define-inline nil)
4645 ("fnlocal" org-footnote-section nil)
4646 ("fnauto" org-footnote-auto-label t)
4647 ("fnprompt" org-footnote-auto-label nil)
4648 ("fnconfirm" org-footnote-auto-label confirm)
4649 ("fnplain" org-footnote-auto-label plain)
4650 ("fnadjust" org-footnote-auto-adjust t)
4651 ("nofnadjust" org-footnote-auto-adjust nil)
4652 ("constcgs" constants-unit-system cgs)
4653 ("constSI" constants-unit-system SI)
4654 ("noptag" org-tag-persistent-alist nil)
4655 ("hideblocks" org-hide-block-startup t)
4656 ("nohideblocks" org-hide-block-startup nil)
4657 ("beamer" org-startup-with-beamer-mode t)
4658 ("entitiespretty" org-pretty-entities t)
4659 ("entitiesplain" org-pretty-entities nil))
4660 "Variable associated with STARTUP options for org-mode.
4661 Each element is a list of three items: the startup options (as written
4662 in the #+STARTUP line), the corresponding variable, and the value to set
4663 this variable to if the option is found. An optional forth element PUSH
4664 means to push this value onto the list in the variable.")
4666 (defun org-update-property-plist (key val props)
4667 "Update PROPS with KEY and VAL."
4668 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4669 (key (if appending (substring key 0 (- (length key) 1)) key))
4670 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4671 (previous (cdr (assoc key props))))
4672 (if appending
4673 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4674 (cons (cons key val) remainder))))
4676 (defconst org-block-regexp
4677 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4678 "Regular expression for hiding blocks.")
4679 (defconst org-heading-keyword-regexp-format
4680 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4681 "Printf format for a regexp matching an headline with some keyword.
4682 This regexp will match the headline of any node which has the
4683 exact keyword that is put into the format. The keyword isn't in
4684 any group by default, but the stars and the body are.")
4685 (defconst org-heading-keyword-maybe-regexp-format
4686 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4687 "Printf format for a regexp matching an headline, possibly with some keyword.
4688 This regexp can match any headline with the specified keyword, or
4689 without a keyword. The keyword isn't in any group by default,
4690 but the stars and the body are.")
4692 (defun org-set-regexps-and-options ()
4693 "Precompute regular expressions for current buffer."
4694 (when (derived-mode-p 'org-mode)
4695 (org-set-local 'org-todo-kwd-alist nil)
4696 (org-set-local 'org-todo-key-alist nil)
4697 (org-set-local 'org-todo-key-trigger nil)
4698 (org-set-local 'org-todo-keywords-1 nil)
4699 (org-set-local 'org-done-keywords nil)
4700 (org-set-local 'org-todo-heads nil)
4701 (org-set-local 'org-todo-sets nil)
4702 (org-set-local 'org-todo-log-states nil)
4703 (org-set-local 'org-file-properties nil)
4704 (org-set-local 'org-file-tags nil)
4705 (let ((re (org-make-options-regexp
4706 '("CATEGORY" "TODO" "COLUMNS"
4707 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4708 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4709 "OPTIONS")
4710 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4711 (splitre "[ \t]+")
4712 (scripts org-use-sub-superscripts)
4713 kwds kws0 kwsa key log value cat arch tags const links hw dws
4714 tail sep kws1 prio props ftags drawers beamer-p
4715 ext-setup-or-nil setup-contents (start 0))
4716 (save-excursion
4717 (save-restriction
4718 (widen)
4719 (goto-char (point-min))
4720 (while (or (and ext-setup-or-nil
4721 (string-match re ext-setup-or-nil start)
4722 (setq start (match-end 0)))
4723 (and (setq ext-setup-or-nil nil start 0)
4724 (re-search-forward re nil t)))
4725 (setq key (upcase (match-string 1 ext-setup-or-nil))
4726 value (org-match-string-no-properties 2 ext-setup-or-nil))
4727 (if (stringp value) (setq value (org-trim value)))
4728 (cond
4729 ((equal key "CATEGORY")
4730 (setq cat value))
4731 ((member key '("SEQ_TODO" "TODO"))
4732 (push (cons 'sequence (org-split-string value splitre)) kwds))
4733 ((equal key "TYP_TODO")
4734 (push (cons 'type (org-split-string value splitre)) kwds))
4735 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4736 ;; general TODO-like setup
4737 (push (cons (intern (downcase (match-string 1 key)))
4738 (org-split-string value splitre)) kwds))
4739 ((equal key "TAGS")
4740 (setq tags (append tags (if tags '("\\n") nil)
4741 (org-split-string value splitre))))
4742 ((equal key "COLUMNS")
4743 (org-set-local 'org-columns-default-format value))
4744 ((equal key "LINK")
4745 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4746 (push (cons (match-string 1 value)
4747 (org-trim (match-string 2 value)))
4748 links)))
4749 ((equal key "PRIORITIES")
4750 (setq prio (org-split-string value " +")))
4751 ((equal key "PROPERTY")
4752 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4753 (setq props (org-update-property-plist (match-string 1 value)
4754 (match-string 2 value)
4755 props))))
4756 ((equal key "FILETAGS")
4757 (when (string-match "\\S-" value)
4758 (setq ftags
4759 (append
4760 ftags
4761 (apply 'append
4762 (mapcar (lambda (x) (org-split-string x ":"))
4763 (org-split-string value)))))))
4764 ((equal key "DRAWERS")
4765 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4766 ((equal key "CONSTANTS")
4767 (setq const (append const (org-split-string value splitre))))
4768 ((equal key "STARTUP")
4769 (let ((opts (org-split-string value splitre))
4770 l var val)
4771 (while (setq l (pop opts))
4772 (when (setq l (assoc l org-startup-options))
4773 (setq var (nth 1 l) val (nth 2 l))
4774 (if (not (nth 3 l))
4775 (set (make-local-variable var) val)
4776 (if (not (listp (symbol-value var)))
4777 (set (make-local-variable var) nil))
4778 (set (make-local-variable var) (symbol-value var))
4779 (add-to-list var val))))))
4780 ((equal key "ARCHIVE")
4781 (setq arch value)
4782 (remove-text-properties 0 (length arch)
4783 '(face t fontified t) arch))
4784 ((equal key "LATEX_CLASS")
4785 (setq beamer-p (equal value "beamer")))
4786 ((equal key "OPTIONS")
4787 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4788 (setq scripts (read (match-string 2 value)))))
4789 ((equal key "SETUPFILE")
4790 (setq setup-contents (org-file-contents
4791 (expand-file-name
4792 (org-remove-double-quotes value))
4793 'noerror))
4794 (if (not ext-setup-or-nil)
4795 (setq ext-setup-or-nil setup-contents start 0)
4796 (setq ext-setup-or-nil
4797 (concat (substring ext-setup-or-nil 0 start)
4798 "\n" setup-contents "\n"
4799 (substring ext-setup-or-nil start)))))))
4800 ;; search for property blocks
4801 (goto-char (point-min))
4802 (while (re-search-forward org-block-regexp nil t)
4803 (when (equal "PROPERTY" (upcase (match-string 1)))
4804 (setq value (replace-regexp-in-string
4805 "[\n\r]" " " (match-string 4)))
4806 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4807 (setq props (org-update-property-plist (match-string 1 value)
4808 (match-string 2 value)
4809 props)))))))
4810 (org-set-local 'org-use-sub-superscripts scripts)
4811 (when cat
4812 (org-set-local 'org-category (intern cat))
4813 (push (cons "CATEGORY" cat) props))
4814 (when prio
4815 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4816 (setq prio (mapcar 'string-to-char prio))
4817 (org-set-local 'org-highest-priority (nth 0 prio))
4818 (org-set-local 'org-lowest-priority (nth 1 prio))
4819 (org-set-local 'org-default-priority (nth 2 prio)))
4820 (and props (org-set-local 'org-file-properties (nreverse props)))
4821 (and ftags (org-set-local 'org-file-tags
4822 (mapcar 'org-add-prop-inherited ftags)))
4823 (and drawers (org-set-local 'org-drawers drawers))
4824 (and arch (org-set-local 'org-archive-location arch))
4825 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4826 ;; Process the TODO keywords
4827 (unless kwds
4828 ;; Use the global values as if they had been given locally.
4829 (setq kwds (default-value 'org-todo-keywords))
4830 (if (stringp (car kwds))
4831 (setq kwds (list (cons org-todo-interpretation
4832 (default-value 'org-todo-keywords)))))
4833 (setq kwds (reverse kwds)))
4834 (setq kwds (nreverse kwds))
4835 (let (inter kws kw)
4836 (while (setq kws (pop kwds))
4837 (let ((kws (or
4838 (run-hook-with-args-until-success
4839 'org-todo-setup-filter-hook kws)
4840 kws)))
4841 (setq inter (pop kws) sep (member "|" kws)
4842 kws0 (delete "|" (copy-sequence kws))
4843 kwsa nil
4844 kws1 (mapcar
4845 (lambda (x)
4846 ;; 1 2
4847 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4848 (progn
4849 (setq kw (match-string 1 x)
4850 key (and (match-end 2) (match-string 2 x))
4851 log (org-extract-log-state-settings x))
4852 (push (cons kw (and key (string-to-char key))) kwsa)
4853 (and log (push log org-todo-log-states))
4855 (error "Invalid TODO keyword %s" x)))
4856 kws0)
4857 kwsa (if kwsa (append '((:startgroup))
4858 (nreverse kwsa)
4859 '((:endgroup))))
4860 hw (car kws1)
4861 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4862 tail (list inter hw (car dws) (org-last dws))))
4863 (add-to-list 'org-todo-heads hw 'append)
4864 (push kws1 org-todo-sets)
4865 (setq org-done-keywords (append org-done-keywords dws nil))
4866 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4867 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4868 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4869 (setq org-todo-sets (nreverse org-todo-sets)
4870 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4871 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4872 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4873 ;; Process the constants
4874 (when const
4875 (let (e cst)
4876 (while (setq e (pop const))
4877 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4878 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4879 (setq org-table-formula-constants-local cst)))
4881 ;; Process the tags.
4882 (when tags
4883 (let (e tgs)
4884 (while (setq e (pop tags))
4885 (cond
4886 ((equal e "{") (push '(:startgroup) tgs))
4887 ((equal e "}") (push '(:endgroup) tgs))
4888 ((equal e "\\n") (push '(:newline) tgs))
4889 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4890 (push (cons (match-string 1 e)
4891 (string-to-char (match-string 2 e)))
4892 tgs))
4893 (t (push (list e) tgs))))
4894 (org-set-local 'org-tag-alist nil)
4895 (while (setq e (pop tgs))
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))))
4900 ;; Compute the regular expressions and other local variables.
4901 ;; Using `org-outline-regexp-bol' would complicate them much,
4902 ;; because of the fixed white space at the end of that string.
4903 (if (not org-done-keywords)
4904 (setq org-done-keywords (and org-todo-keywords-1
4905 (list (org-last org-todo-keywords-1)))))
4906 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4907 (length org-scheduled-string)
4908 (length org-clock-string)
4909 (length org-closed-string)))
4910 org-drawer-regexp
4911 (concat "^[ \t]*:\\("
4912 (mapconcat 'regexp-quote org-drawers "\\|")
4913 "\\):[ \t]*$")
4914 org-not-done-keywords
4915 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4916 org-todo-regexp
4917 (concat "\\("
4918 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4919 "\\)")
4920 org-not-done-regexp
4921 (concat "\\("
4922 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4923 "\\)")
4924 org-not-done-heading-regexp
4925 (format org-heading-keyword-regexp-format org-not-done-regexp)
4926 org-todo-line-regexp
4927 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4928 org-complex-heading-regexp
4929 (concat "^\\(\\*+\\)"
4930 "\\(?: +" org-todo-regexp "\\)?"
4931 "\\(?: +\\(\\[#.\\]\\)\\)?"
4932 "\\(?: +\\(.*?\\)\\)??"
4933 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4934 "[ \t]*$")
4935 org-complex-heading-regexp-format
4936 (concat "^\\(\\*+\\)"
4937 "\\(?: +" org-todo-regexp "\\)?"
4938 "\\(?: +\\(\\[#.\\]\\)\\)?"
4939 "\\(?: +"
4940 ;; Stats cookies can be stuck to body.
4941 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4942 "\\(%s\\)"
4943 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4944 "\\)"
4945 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4946 "[ \t]*$")
4947 org-todo-line-tags-regexp
4948 (concat "^\\(\\*+\\)"
4949 "\\(?: +" org-todo-regexp "\\)?"
4950 "\\(?: +\\(.*?\\)\\)??"
4951 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4952 "[ \t]*$")
4953 org-deadline-regexp (concat "\\<" org-deadline-string)
4954 org-deadline-time-regexp
4955 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4956 org-deadline-line-regexp
4957 (concat "\\<\\(" org-deadline-string "\\).*")
4958 org-scheduled-regexp
4959 (concat "\\<" org-scheduled-string)
4960 org-scheduled-time-regexp
4961 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4962 org-closed-time-regexp
4963 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4964 org-keyword-time-regexp
4965 (concat "\\<\\(" org-scheduled-string
4966 "\\|" org-deadline-string
4967 "\\|" org-closed-string
4968 "\\|" org-clock-string "\\)"
4969 " *[[<]\\([^]>]+\\)[]>]")
4970 org-keyword-time-not-clock-regexp
4971 (concat "\\<\\(" org-scheduled-string
4972 "\\|" org-deadline-string
4973 "\\|" org-closed-string
4974 "\\)"
4975 " *[[<]\\([^]>]+\\)[]>]")
4976 org-maybe-keyword-time-regexp
4977 (concat "\\(\\<\\(" org-scheduled-string
4978 "\\|" org-deadline-string
4979 "\\|" org-closed-string
4980 "\\|" org-clock-string "\\)\\)?"
4981 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4982 org-all-time-keywords
4983 (mapcar (lambda (w) (substring w 0 -1))
4984 (list org-scheduled-string org-deadline-string
4985 org-clock-string org-closed-string)))
4986 (org-set-font-lock-defaults))))
4988 (defun org-file-contents (file &optional noerror)
4989 "Return the contents of FILE, as a string."
4990 (if (or (not file)
4991 (not (file-readable-p file)))
4992 (if noerror
4993 (progn
4994 (message "Cannot read file \"%s\"" file)
4995 (ding) (sit-for 2)
4997 (error "Cannot read file \"%s\"" file))
4998 (with-temp-buffer
4999 (insert-file-contents file)
5000 (buffer-string))))
5002 (defun org-extract-log-state-settings (x)
5003 "Extract the log state setting from a TODO keyword string.
5004 This will extract info from a string like \"WAIT(w@/!)\"."
5005 (let (kw key log1 log2)
5006 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5007 (setq kw (match-string 1 x)
5008 key (and (match-end 2) (match-string 2 x))
5009 log1 (and (match-end 3) (match-string 3 x))
5010 log2 (and (match-end 4) (match-string 4 x)))
5011 (and (or log1 log2)
5012 (list kw
5013 (and log1 (if (equal log1 "!") 'time 'note))
5014 (and log2 (if (equal log2 "!") 'time 'note)))))))
5016 (defun org-remove-keyword-keys (list)
5017 "Remove a pair of parenthesis at the end of each string in LIST."
5018 (mapcar (lambda (x)
5019 (if (string-match "(.*)$" x)
5020 (substring x 0 (match-beginning 0))
5022 list))
5024 (defun org-assign-fast-keys (alist)
5025 "Assign fast keys to a keyword-key alist.
5026 Respect keys that are already there."
5027 (let (new e (alt ?0))
5028 (while (setq e (pop alist))
5029 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5030 (cdr e)) ;; Key already assigned.
5031 (push e new)
5032 (let ((clist (string-to-list (downcase (car e))))
5033 (used (append new alist)))
5034 (when (= (car clist) ?@)
5035 (pop clist))
5036 (while (and clist (rassoc (car clist) used))
5037 (pop clist))
5038 (unless clist
5039 (while (rassoc alt used)
5040 (incf alt)))
5041 (push (cons (car e) (or (car clist) alt)) new))))
5042 (nreverse new)))
5044 ;;; Some variables used in various places
5046 (defvar org-window-configuration nil
5047 "Used in various places to store a window configuration.")
5048 (defvar org-selected-window nil
5049 "Used in various places to store a window configuration.")
5050 (defvar org-finish-function nil
5051 "Function to be called when `C-c C-c' is used.
5052 This is for getting out of special buffers like capture.")
5055 ;; FIXME: Occasionally check by commenting these, to make sure
5056 ;; no other functions uses these, forgetting to let-bind them.
5057 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5058 (defvar org-last-state)
5059 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5061 ;; Defined somewhere in this file, but used before definition.
5062 (defvar org-entities) ;; defined in org-entities.el
5063 (defvar org-struct-menu)
5064 (defvar org-org-menu)
5065 (defvar org-tbl-menu)
5067 ;;;; Define the Org-mode
5069 ;; We use a before-change function to check if a table might need
5070 ;; an update.
5071 (defvar org-table-may-need-update t
5072 "Indicates that a table might need an update.
5073 This variable is set by `org-before-change-function'.
5074 `org-table-align' sets it back to nil.")
5075 (defun org-before-change-function (beg end)
5076 "Every change indicates that a table might need an update."
5077 (setq org-table-may-need-update t))
5078 (defvar org-mode-map)
5079 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5080 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5081 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5082 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5083 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5084 (defvar org-table-buffer-is-an nil)
5086 (defvar bidi-paragraph-direction)
5087 (defvar buffer-face-mode-face)
5089 (require 'outline)
5090 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5091 (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"))
5092 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5094 ;; Other stuff we need.
5095 (require 'time-date)
5096 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5097 (require 'easymenu)
5098 (require 'overlay)
5100 ;; (require 'org-macs) moved higher up in the file before it is first used
5101 (require 'org-entities)
5102 ;; (require 'org-compat) moved higher up in the file before it is first used
5103 (require 'org-faces)
5104 (require 'org-list)
5105 (require 'org-pcomplete)
5106 (require 'org-src)
5107 (require 'org-footnote)
5109 ;; babel
5110 (require 'ob)
5112 ;;;###autoload
5113 (define-derived-mode org-mode outline-mode "Org"
5114 "Outline-based notes management and organizer, alias
5115 \"Carsten's outline-mode for keeping track of everything.\"
5117 Org-mode develops organizational tasks around a NOTES file which
5118 contains information about projects as plain text. Org-mode is
5119 implemented on top of outline-mode, which is ideal to keep the content
5120 of large files well structured. It supports ToDo items, deadlines and
5121 time stamps, which magically appear in the diary listing of the Emacs
5122 calendar. Tables are easily created with a built-in table editor.
5123 Plain text URL-like links connect to websites, emails (VM), Usenet
5124 messages (Gnus), BBDB entries, and any files related to the project.
5125 For printing and sharing of notes, an Org-mode file (or a part of it)
5126 can be exported as a structured ASCII or HTML file.
5128 The following commands are available:
5130 \\{org-mode-map}"
5132 ;; Get rid of Outline menus, they are not needed
5133 ;; Need to do this here because define-derived-mode sets up
5134 ;; the keymap so late. Still, it is a waste to call this each time
5135 ;; we switch another buffer into org-mode.
5136 (if (featurep 'xemacs)
5137 (when (boundp 'outline-mode-menu-heading)
5138 ;; Assume this is Greg's port, it uses easymenu
5139 (easy-menu-remove outline-mode-menu-heading)
5140 (easy-menu-remove outline-mode-menu-show)
5141 (easy-menu-remove outline-mode-menu-hide))
5142 (define-key org-mode-map [menu-bar headings] 'undefined)
5143 (define-key org-mode-map [menu-bar hide] 'undefined)
5144 (define-key org-mode-map [menu-bar show] 'undefined))
5146 (org-load-modules-maybe)
5147 (easy-menu-add org-org-menu)
5148 (easy-menu-add org-tbl-menu)
5149 (org-install-agenda-files-menu)
5150 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5151 (add-to-invisibility-spec '(org-cwidth))
5152 (add-to-invisibility-spec '(org-hide-block . t))
5153 (when (featurep 'xemacs)
5154 (org-set-local 'line-move-ignore-invisible t))
5155 (org-set-local 'outline-regexp org-outline-regexp)
5156 (org-set-local 'outline-level 'org-outline-level)
5157 (setq bidi-paragraph-direction 'left-to-right)
5158 (when (and org-ellipsis
5159 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5160 (fboundp 'make-glyph-code))
5161 (unless org-display-table
5162 (setq org-display-table (make-display-table)))
5163 (set-display-table-slot
5164 org-display-table 4
5165 (vconcat (mapcar
5166 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5167 org-ellipsis)))
5168 (if (stringp org-ellipsis) org-ellipsis "..."))))
5169 (setq buffer-display-table org-display-table))
5170 (org-set-regexps-and-options)
5171 (when (and org-tag-faces (not org-tags-special-faces-re))
5172 ;; tag faces set outside customize.... force initialization.
5173 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5174 ;; Calc embedded
5175 (org-set-local 'calc-embedded-open-mode "# ")
5176 (modify-syntax-entry ?@ "w")
5177 (modify-syntax-entry ?\" "\"")
5178 (if org-startup-truncated (setq truncate-lines t))
5179 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5180 (org-set-local 'font-lock-unfontify-region-function
5181 'org-unfontify-region)
5182 ;; Activate before-change-function
5183 (org-set-local 'org-table-may-need-update t)
5184 (org-add-hook 'before-change-functions 'org-before-change-function nil
5185 'local)
5186 ;; Check for running clock before killing a buffer
5187 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5188 ;; Initialize macros templates.
5189 (org-macro-initialize-templates)
5190 ;; Initialize radio targets.
5191 (org-update-radio-target-regexp)
5192 ;; Indentation.
5193 (org-set-local 'indent-line-function 'org-indent-line)
5194 (org-set-local 'indent-region-function 'org-indent-region)
5195 ;; Filling and auto-filling.
5196 (org-setup-filling)
5197 ;; Comments.
5198 (org-setup-comments-handling)
5199 ;; Beginning/end of defun
5200 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5201 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5202 ;; Next error for sparse trees
5203 (org-set-local 'next-error-function 'org-occur-next-match)
5204 ;; Make sure dependence stuff works reliably, even for users who set it
5205 ;; too late :-(
5206 (if org-enforce-todo-dependencies
5207 (add-hook 'org-blocker-hook
5208 'org-block-todo-from-children-or-siblings-or-parent)
5209 (remove-hook 'org-blocker-hook
5210 'org-block-todo-from-children-or-siblings-or-parent))
5211 (if org-enforce-todo-checkbox-dependencies
5212 (add-hook 'org-blocker-hook
5213 'org-block-todo-from-checkboxes)
5214 (remove-hook 'org-blocker-hook
5215 'org-block-todo-from-checkboxes))
5217 ;; Align options lines
5218 (org-set-local
5219 'align-mode-rules-list
5220 '((org-in-buffer-settings
5221 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5222 (modes . '(org-mode)))))
5224 ;; Imenu
5225 (org-set-local 'imenu-create-index-function
5226 'org-imenu-get-tree)
5228 ;; Make isearch reveal context
5229 (if (or (featurep 'xemacs)
5230 (not (boundp 'outline-isearch-open-invisible-function)))
5231 ;; Emacs 21 and XEmacs make use of the hook
5232 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5233 ;; Emacs 22 deals with this through a special variable
5234 (org-set-local 'outline-isearch-open-invisible-function
5235 (lambda (&rest ignore) (org-show-context 'isearch))))
5237 ;; Setup the pcomplete hooks
5238 (set (make-local-variable 'pcomplete-command-completion-function)
5239 'org-pcomplete-initial)
5240 (set (make-local-variable 'pcomplete-command-name-function)
5241 'org-command-at-point)
5242 (set (make-local-variable 'pcomplete-default-completion-function)
5243 'ignore)
5244 (set (make-local-variable 'pcomplete-parse-arguments-function)
5245 'org-parse-arguments)
5246 (set (make-local-variable 'pcomplete-termination-string) "")
5247 (when (>= emacs-major-version 23)
5248 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5250 ;; If empty file that did not turn on org-mode automatically, make it to.
5251 (if (and org-insert-mode-line-in-empty-file
5252 (org-called-interactively-p 'any)
5253 (= (point-min) (point-max)))
5254 (insert "# -*- mode: org -*-\n\n"))
5255 (unless org-inhibit-startup
5256 (and org-startup-with-beamer-mode (org-beamer-mode))
5257 (when org-startup-align-all-tables
5258 (let ((bmp (buffer-modified-p)))
5259 (org-table-map-tables 'org-table-align 'quietly)
5260 (set-buffer-modified-p bmp)))
5261 (when org-startup-with-inline-images
5262 (org-display-inline-images))
5263 (unless org-inhibit-startup-visibility-stuff
5264 (org-set-startup-visibility)))
5265 ;; Try to set org-hide correctly
5266 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5268 (when (fboundp 'abbrev-table-put)
5269 (abbrev-table-put org-mode-abbrev-table
5270 :parents (list text-mode-abbrev-table)))
5272 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5275 (defun org-find-invisible-foreground ()
5276 (let ((candidates (remove
5277 "unspecified-bg"
5278 (nconc
5279 (list (face-background 'default)
5280 (face-background 'org-default))
5281 (mapcar
5282 (lambda (alist)
5283 (when (boundp alist)
5284 (cdr (assoc 'background-color (symbol-value alist)))))
5285 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5286 (list (face-foreground 'org-hide))))))
5287 (car (remove nil candidates))))
5289 (defun org-current-time (&optional rounding-minutes)
5290 "Current time, possibly rounded to ROUNDING-MINUTES.
5291 When ROUNDING-MINUTES is not an integer, fall back on the car of
5292 `org-time-stamp-rounding-minutes'."
5293 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5294 (car org-time-stamp-rounding-minutes)))
5295 (time (decode-time)))
5296 (if (> r 1)
5297 (apply 'encode-time
5298 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5299 (nthcdr 2 time)))
5300 (current-time))))
5302 (defun org-today ()
5303 "Return today date, considering `org-extend-today-until'."
5304 (time-to-days
5305 (time-subtract (current-time)
5306 (list 0 (* 3600 org-extend-today-until) 0))))
5308 ;;;; Font-Lock stuff, including the activators
5310 (defvar org-mouse-map (make-sparse-keymap))
5311 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5312 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5313 (when org-mouse-1-follows-link
5314 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5315 (when org-tab-follows-link
5316 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5317 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5319 (require 'font-lock)
5321 (defconst org-non-link-chars "]\t\n\r<>")
5322 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5323 "shell" "elisp" "doi" "message"))
5324 (defvar org-link-types-re nil
5325 "Matches a link that has a url-like prefix like \"http:\"")
5326 (defvar org-link-re-with-space nil
5327 "Matches a link with spaces, optional angular brackets around it.")
5328 (defvar org-link-re-with-space2 nil
5329 "Matches a link with spaces, optional angular brackets around it.")
5330 (defvar org-link-re-with-space3 nil
5331 "Matches a link with spaces, only for internal part in bracket links.")
5332 (defvar org-angle-link-re nil
5333 "Matches link with angular brackets, spaces are allowed.")
5334 (defvar org-plain-link-re nil
5335 "Matches plain link, without spaces.")
5336 (defvar org-bracket-link-regexp nil
5337 "Matches a link in double brackets.")
5338 (defvar org-bracket-link-analytic-regexp nil
5339 "Regular expression used to analyze links.
5340 Here is what the match groups contain after a match:
5341 1: http:
5342 2: http
5343 3: path
5344 4: [desc]
5345 5: desc")
5346 (defvar org-bracket-link-analytic-regexp++ nil
5347 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5348 (defvar org-any-link-re nil
5349 "Regular expression matching any link.")
5351 (defconst org-match-sexp-depth 3
5352 "Number of stacked braces for sub/superscript matching.")
5354 (defun org-create-multibrace-regexp (left right n)
5355 "Create a regular expression which will match a balanced sexp.
5356 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5357 as single character strings.
5358 The regexp returned will match the entire expression including the
5359 delimiters. It will also define a single group which contains the
5360 match except for the outermost delimiters. The maximum depth of
5361 stacked delimiters is N. Escaping delimiters is not possible."
5362 (let* ((nothing (concat "[^" left right "]*?"))
5363 (or "\\|")
5364 (re nothing)
5365 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5366 (while (> n 1)
5367 (setq n (1- n)
5368 re (concat re or next)
5369 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5370 (concat left "\\(" re "\\)" right)))
5372 (defvar org-match-substring-regexp
5373 (concat
5374 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5375 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5376 "\\|"
5377 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5378 "\\|"
5379 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5380 "The regular expression matching a sub- or superscript.")
5382 (defvar org-match-substring-with-braces-regexp
5383 (concat
5384 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5385 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5386 "\\)")
5387 "The regular expression matching a sub- or superscript, forcing braces.")
5389 (defun org-make-link-regexps ()
5390 "Update the link regular expressions.
5391 This should be called after the variable `org-link-types' has changed."
5392 (setq org-link-types-re
5393 (concat
5394 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5395 org-link-re-with-space
5396 (concat
5397 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5398 "\\([^" org-non-link-chars " ]"
5399 "[^" org-non-link-chars "]*"
5400 "[^" org-non-link-chars " ]\\)>?")
5401 org-link-re-with-space2
5402 (concat
5403 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5404 "\\([^" org-non-link-chars " ]"
5405 "[^\t\n\r]*"
5406 "[^" org-non-link-chars " ]\\)>?")
5407 org-link-re-with-space3
5408 (concat
5409 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5410 "\\([^" org-non-link-chars " ]"
5411 "[^\t\n\r]*\\)")
5412 org-angle-link-re
5413 (concat
5414 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5415 "\\([^" org-non-link-chars " ]"
5416 "[^" org-non-link-chars "]*"
5417 "\\)>")
5418 org-plain-link-re
5419 (concat
5420 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5421 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5422 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5423 org-bracket-link-regexp
5424 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5425 org-bracket-link-analytic-regexp
5426 (concat
5427 "\\[\\["
5428 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5429 "\\([^]]+\\)"
5430 "\\]"
5431 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5432 "\\]")
5433 org-bracket-link-analytic-regexp++
5434 (concat
5435 "\\[\\["
5436 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5437 "\\([^]]+\\)"
5438 "\\]"
5439 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5440 "\\]")
5441 org-any-link-re
5442 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5443 org-angle-link-re "\\)\\|\\("
5444 org-plain-link-re "\\)")))
5446 (org-make-link-regexps)
5448 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5449 "Regular expression for fast time stamp matching.")
5450 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5451 "Regular expression for fast time stamp matching.")
5452 (defconst org-ts-regexp0
5453 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5454 "Regular expression matching time strings for analysis.
5455 This one does not require the space after the date, so it can be used
5456 on a string that terminates immediately after the date.")
5457 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5458 "Regular expression matching time strings for analysis.")
5459 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5460 "Regular expression matching time stamps, with groups.")
5461 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5462 "Regular expression matching time stamps (also [..]), with groups.")
5463 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5464 "Regular expression matching a time stamp range.")
5465 (defconst org-tr-regexp-both
5466 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5467 "Regular expression matching a time stamp range.")
5468 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5469 org-ts-regexp "\\)?")
5470 "Regular expression matching a time stamp or time stamp range.")
5471 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5472 org-ts-regexp-both "\\)?")
5473 "Regular expression matching a time stamp or time stamp range.
5474 The time stamps may be either active or inactive.")
5476 (defvar org-emph-face nil)
5478 (defun org-do-emphasis-faces (limit)
5479 "Run through the buffer and add overlays to emphasized strings."
5480 (let (rtn a)
5481 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5482 (if (not (= (char-after (match-beginning 3))
5483 (char-after (match-beginning 4))))
5484 (progn
5485 (setq rtn t)
5486 (setq a (assoc (match-string 3) org-emphasis-alist))
5487 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5488 'face
5489 (nth 1 a))
5490 (and (nth 4 a)
5491 (org-remove-flyspell-overlays-in
5492 (match-beginning 0) (match-end 0)))
5493 (add-text-properties (match-beginning 2) (match-end 2)
5494 '(font-lock-multiline t org-emphasis t))
5495 (when org-hide-emphasis-markers
5496 (add-text-properties (match-end 4) (match-beginning 5)
5497 '(invisible org-link))
5498 (add-text-properties (match-beginning 3) (match-end 3)
5499 '(invisible org-link)))))
5500 (backward-char 1))
5501 rtn))
5503 (defun org-emphasize (&optional char)
5504 "Insert or change an emphasis, i.e. a font like bold or italic.
5505 If there is an active region, change that region to a new emphasis.
5506 If there is no region, just insert the marker characters and position
5507 the cursor between them.
5508 CHAR should be either the marker character, or the first character of the
5509 HTML tag associated with that emphasis. If CHAR is a space, the means
5510 to remove the emphasis of the selected region.
5511 If char is not given (for example in an interactive call) it
5512 will be prompted for."
5513 (interactive)
5514 (let ((eal org-emphasis-alist) e det
5515 (erc org-emphasis-regexp-components)
5516 (prompt "")
5517 (string "") beg end move tag c s)
5518 (if (org-region-active-p)
5519 (setq beg (region-beginning) end (region-end)
5520 string (buffer-substring beg end))
5521 (setq move t))
5523 (while (setq e (pop eal))
5524 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5525 c (aref tag 0))
5526 (push (cons c (string-to-char (car e))) det)
5527 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5528 (substring tag 1)))))
5529 (setq det (nreverse det))
5530 (unless char
5531 (message "%s" (concat "Emphasis marker or tag:" prompt))
5532 (setq char (read-char-exclusive)))
5533 (setq char (or (cdr (assoc char det)) char))
5534 (if (equal char ?\ )
5535 (setq s "" move nil)
5536 (unless (assoc (char-to-string char) org-emphasis-alist)
5537 (error "No such emphasis marker: \"%c\"" char))
5538 (setq s (char-to-string char)))
5539 (while (and (> (length string) 1)
5540 (equal (substring string 0 1) (substring string -1))
5541 (assoc (substring string 0 1) org-emphasis-alist))
5542 (setq string (substring string 1 -1)))
5543 (setq string (concat s string s))
5544 (if beg (delete-region beg end))
5545 (unless (or (bolp)
5546 (string-match (concat "[" (nth 0 erc) "\n]")
5547 (char-to-string (char-before (point)))))
5548 (insert " "))
5549 (unless (or (eobp)
5550 (string-match (concat "[" (nth 1 erc) "\n]")
5551 (char-to-string (char-after (point)))))
5552 (insert " ") (backward-char 1))
5553 (insert string)
5554 (and move (backward-char 1))))
5556 (defconst org-nonsticky-props
5557 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5559 (defsubst org-rear-nonsticky-at (pos)
5560 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5562 (defun org-activate-plain-links (limit)
5563 "Run through the buffer and add overlays to links."
5564 (catch 'exit
5565 (let (f hl)
5566 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5567 (not (org-in-src-block-p)))
5568 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5569 (setq f (get-text-property (match-beginning 0) 'face))
5570 (setq hl (org-match-string-no-properties 0))
5571 (if (or (eq f 'org-tag)
5572 (and (listp f) (memq 'org-tag f)))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'face 'org-link
5577 'htmlize-link `(:uri ,hl)
5578 'keymap org-mouse-map))
5579 (org-rear-nonsticky-at (match-end 0)))
5580 t))))
5582 (defun org-activate-code (limit)
5583 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5584 (progn
5585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5586 (remove-text-properties (match-beginning 0) (match-end 0)
5587 '(display t invisible t intangible t))
5588 t)))
5590 (defcustom org-src-fontify-natively nil
5591 "When non-nil, fontify code in code blocks."
5592 :type 'boolean
5593 :version "24.1"
5594 :group 'org-appearance
5595 :group 'org-babel)
5597 (defcustom org-allow-promoting-top-level-subtree nil
5598 "When non-nil, allow promoting a top level subtree.
5599 The leading star of the top level headline will be replaced
5600 by a #."
5601 :type 'boolean
5602 :version "24.1"
5603 :group 'org-appearance)
5605 (defun org-fontify-meta-lines-and-blocks (limit)
5606 (condition-case nil
5607 (org-fontify-meta-lines-and-blocks-1 limit)
5608 (error (message "org-mode fontification error"))))
5610 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5611 "Fontify #+ lines and blocks, in the correct ways."
5612 (let ((case-fold-search t))
5613 (if (re-search-forward
5614 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5615 limit t)
5616 (let ((beg (match-beginning 0))
5617 (block-start (match-end 0))
5618 (block-end nil)
5619 (lang (match-string 7))
5620 (beg1 (line-beginning-position 2))
5621 (dc1 (downcase (match-string 2)))
5622 (dc3 (downcase (match-string 3)))
5623 end end1 quoting block-type ovl)
5624 (cond
5625 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5626 ;; a single line of backend-specific content
5627 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5628 (remove-text-properties (match-beginning 0) (match-end 0)
5629 '(display t invisible t intangible t))
5630 (add-text-properties (match-beginning 1) (match-end 3)
5631 '(font-lock-fontified t face org-meta-line))
5632 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5633 '(font-lock-fontified t face org-block))
5634 ; for backend-specific code
5636 ((and (match-end 4) (equal dc3 "+begin"))
5637 ;; Truly a block
5638 (setq block-type (downcase (match-string 5))
5639 quoting (member block-type org-protecting-blocks))
5640 (when (re-search-forward
5641 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5642 nil t) ;; on purpose, we look further than LIMIT
5643 (setq end (min (point-max) (match-end 0))
5644 end1 (min (point-max) (1- (match-beginning 0))))
5645 (setq block-end (match-beginning 0))
5646 (when quoting
5647 (remove-text-properties beg end
5648 '(display t invisible t intangible t)))
5649 (add-text-properties
5650 beg end
5651 '(font-lock-fontified t font-lock-multiline t))
5652 (add-text-properties beg beg1 '(face org-meta-line))
5653 (add-text-properties end1 (min (point-max) (1+ end))
5654 '(face org-meta-line)) ; for end_src
5655 (cond
5656 ((and lang (not (string= lang "")) org-src-fontify-natively)
5657 (org-src-font-lock-fontify-block lang block-start block-end)
5658 ;; remove old background overlays
5659 (mapc (lambda (ov)
5660 (if (eq (overlay-get ov 'face) 'org-block-background)
5661 (delete-overlay ov)))
5662 (overlays-at (/ (+ beg1 block-end) 2)))
5663 ;; add a background overlay
5664 (setq ovl (make-overlay beg1 block-end))
5665 (overlay-put ovl 'face 'org-block-background)
5666 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5667 (quoting
5668 (add-text-properties beg1 (min (point-max) (1+ end1))
5669 '(face org-block))) ; end of source block
5670 ((not org-fontify-quote-and-verse-blocks))
5671 ((string= block-type "quote")
5672 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5673 ((string= block-type "verse")
5674 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5675 (add-text-properties beg beg1 '(face org-block-begin-line))
5676 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5677 '(face org-block-end-line))
5679 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5680 (add-text-properties
5681 beg (match-end 3)
5682 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5683 '(font-lock-fontified t invisible t)
5684 '(font-lock-fontified t face org-document-info-keyword)))
5685 (add-text-properties
5686 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5687 (if (string-equal dc1 "+title:")
5688 '(font-lock-fontified t face org-document-title)
5689 '(font-lock-fontified t face org-document-info))))
5690 ((or (equal dc1 "+results")
5691 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5692 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5693 "+call:" "+header:" "+headers:" "+name:"))
5694 (and (match-end 4) (equal dc3 "+attr")))
5695 (add-text-properties
5696 beg (match-end 0)
5697 '(font-lock-fontified t face org-meta-line))
5699 ((member dc3 '(" " ""))
5700 (add-text-properties
5701 beg (match-end 0)
5702 '(font-lock-fontified t face font-lock-comment-face)))
5703 ((not (member (char-after beg) '(?\ ?\t)))
5704 ;; just any other in-buffer setting, but not indented
5705 (add-text-properties
5706 beg (match-end 0)
5707 '(font-lock-fontified t face org-meta-line))
5709 (t nil))))))
5711 (defun org-activate-angle-links (limit)
5712 "Run through the buffer and add overlays to links."
5713 (if (and (re-search-forward org-angle-link-re limit t)
5714 (not (org-in-src-block-p)))
5715 (progn
5716 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5717 (add-text-properties (match-beginning 0) (match-end 0)
5718 (list 'mouse-face 'highlight
5719 'keymap org-mouse-map))
5720 (org-rear-nonsticky-at (match-end 0))
5721 t)))
5723 (defun org-activate-footnote-links (limit)
5724 "Run through the buffer and add overlays to footnotes."
5725 (let ((fn (org-footnote-next-reference-or-definition limit)))
5726 (when fn
5727 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5728 (org-remove-flyspell-overlays-in beg end)
5729 (add-text-properties beg end
5730 (list 'mouse-face 'highlight
5731 'keymap org-mouse-map
5732 'help-echo
5733 (if (= (point-at-bol) beg)
5734 "Footnote definition"
5735 "Footnote reference")
5736 'font-lock-fontified t
5737 'font-lock-multiline t
5738 'face 'org-footnote))))))
5740 (defun org-activate-bracket-links (limit)
5741 "Run through the buffer and add overlays to bracketed links."
5742 (if (and (re-search-forward org-bracket-link-regexp limit t)
5743 (not (org-in-src-block-p)))
5744 (let* ((hl (org-match-string-no-properties 1))
5745 (help (concat "LINK: " hl))
5746 ;; FIXME: Above we should remove the escapes. But that
5747 ;; requires another match, protecting match data, a lot
5748 ;; of overhead for font-lock.
5749 (ip (org-maybe-intangible
5750 (list 'invisible 'org-link
5751 'keymap org-mouse-map 'mouse-face 'highlight
5752 'font-lock-multiline t 'help-echo help
5753 'htmlize-link `(:uri ,hl))))
5754 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5755 'font-lock-multiline t 'help-echo help
5756 'htmlize-link `(:uri ,hl))))
5757 ;; We need to remove the invisible property here. Table narrowing
5758 ;; may have made some of this invisible.
5759 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5760 (remove-text-properties (match-beginning 0) (match-end 0)
5761 '(invisible nil))
5762 (if (match-end 3)
5763 (progn
5764 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5765 (org-rear-nonsticky-at (match-beginning 3))
5766 (add-text-properties (match-beginning 3) (match-end 3) vp)
5767 (org-rear-nonsticky-at (match-end 3))
5768 (add-text-properties (match-end 3) (match-end 0) ip)
5769 (org-rear-nonsticky-at (match-end 0)))
5770 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5771 (org-rear-nonsticky-at (match-beginning 1))
5772 (add-text-properties (match-beginning 1) (match-end 1) vp)
5773 (org-rear-nonsticky-at (match-end 1))
5774 (add-text-properties (match-end 1) (match-end 0) ip)
5775 (org-rear-nonsticky-at (match-end 0)))
5776 t)))
5778 (defun org-activate-dates (limit)
5779 "Run through the buffer and add overlays to dates."
5780 (if (re-search-forward org-tsr-regexp-both limit t)
5781 (progn
5782 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5783 (add-text-properties (match-beginning 0) (match-end 0)
5784 (list 'mouse-face 'highlight
5785 'keymap org-mouse-map))
5786 (org-rear-nonsticky-at (match-end 0))
5787 (when org-display-custom-times
5788 (if (match-end 3)
5789 (org-display-custom-time (match-beginning 3) (match-end 3)))
5790 (org-display-custom-time (match-beginning 1) (match-end 1)))
5791 t)))
5793 (defvar org-target-link-regexp nil
5794 "Regular expression matching radio targets in plain text.")
5795 (make-variable-buffer-local 'org-target-link-regexp)
5796 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5797 "Regular expression matching a link target.")
5798 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5799 "Regular expression matching a radio target.")
5800 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5801 "Regular expression matching any target.")
5803 (defun org-activate-target-links (limit)
5804 "Run through the buffer and add overlays to target matches."
5805 (when org-target-link-regexp
5806 (let ((case-fold-search t))
5807 (if (re-search-forward org-target-link-regexp limit t)
5808 (progn
5809 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5810 (add-text-properties (match-beginning 0) (match-end 0)
5811 (list 'mouse-face 'highlight
5812 'keymap org-mouse-map
5813 'help-echo "Radio target link"
5814 'org-linked-text t))
5815 (org-rear-nonsticky-at (match-end 0))
5816 t)))))
5818 (defun org-update-radio-target-regexp ()
5819 "Find all radio targets in this file and update the regular expression."
5820 (interactive)
5821 (when (memq 'radio org-activate-links)
5822 (setq org-target-link-regexp
5823 (org-make-target-link-regexp (org-all-targets 'radio)))
5824 (org-restart-font-lock)))
5826 (defun org-hide-wide-columns (limit)
5827 (let (s e)
5828 (setq s (text-property-any (point) (or limit (point-max))
5829 'org-cwidth t))
5830 (when s
5831 (setq e (next-single-property-change s 'org-cwidth))
5832 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5833 (goto-char e)
5834 t)))
5836 (defvar org-match-substring-regexp)
5837 (defvar org-match-substring-with-braces-regexp)
5839 (defun org-restart-font-lock ()
5840 "Restart `font-lock-mode', to force refontification."
5841 (when (and (boundp 'font-lock-mode) font-lock-mode)
5842 (font-lock-mode -1)
5843 (font-lock-mode 1)))
5845 (defun org-all-targets (&optional radio)
5846 "Return a list of all targets in this file.
5847 When optional argument RADIO is non-nil, only find radio
5848 targets."
5849 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5850 (save-excursion
5851 (goto-char (point-min))
5852 (while (re-search-forward re nil t)
5853 ;; Make sure point is really within the object.
5854 (backward-char)
5855 (let ((obj (org-element-context)))
5856 (when (memq (org-element-type obj) '(radio-target target))
5857 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5858 rtn)))
5860 (defun org-make-target-link-regexp (targets)
5861 "Make regular expression matching all strings in TARGETS.
5862 The regular expression finds the targets also if there is a line break
5863 between words."
5864 (and targets
5865 (concat
5866 "\\<\\("
5867 (mapconcat
5868 (lambda (x)
5869 (setq x (regexp-quote x))
5870 (while (string-match " +" x)
5871 (setq x (replace-match "\\s-+" t t x)))
5873 targets
5874 "\\|")
5875 "\\)\\>")))
5877 (defun org-activate-tags (limit)
5878 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5879 (progn
5880 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5881 (add-text-properties (match-beginning 1) (match-end 1)
5882 (list 'mouse-face 'highlight
5883 'keymap org-mouse-map))
5884 (org-rear-nonsticky-at (match-end 1))
5885 t)))
5887 (defun org-outline-level ()
5888 "Compute the outline level of the heading at point.
5889 If this is called at a normal headline, the level is the number of stars.
5890 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5891 (save-excursion
5892 (if (not (condition-case nil
5893 (org-back-to-heading t)
5894 (error nil)))
5896 (looking-at org-outline-regexp)
5897 (1- (- (match-end 0) (match-beginning 0))))))
5899 (defvar org-font-lock-keywords nil)
5901 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5902 "Regular expression matching a property line.")
5904 (defvar org-font-lock-hook nil
5905 "Functions to be called for special font lock stuff.")
5907 (defvar org-font-lock-set-keywords-hook nil
5908 "Functions that can manipulate `org-font-lock-extra-keywords'.
5909 This is called after `org-font-lock-extra-keywords' is defined, but before
5910 it is installed to be used by font lock. This can be useful if something
5911 needs to be inserted at a specific position in the font-lock sequence.")
5913 (defun org-font-lock-hook (limit)
5914 "Run `org-font-lock-hook' within LIMIT."
5915 (run-hook-with-args 'org-font-lock-hook limit))
5917 (defun org-set-font-lock-defaults ()
5918 "Set font lock defaults for the current buffer."
5919 (let* ((em org-fontify-emphasized-text)
5920 (lk org-activate-links)
5921 (org-font-lock-extra-keywords
5922 (list
5923 ;; Call the hook
5924 '(org-font-lock-hook)
5925 ;; Headlines
5926 `(,(if org-fontify-whole-heading-line
5927 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5928 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5929 (1 (org-get-level-face 1))
5930 (2 (org-get-level-face 2))
5931 (3 (org-get-level-face 3)))
5932 ;; Table lines
5933 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5934 (1 'org-table t))
5935 ;; Table internals
5936 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5937 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5938 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5939 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5940 ;; Drawers
5941 (list org-drawer-regexp '(0 'org-special-keyword t))
5942 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5943 ;; Properties
5944 (list org-property-re
5945 '(1 'org-special-keyword t)
5946 '(3 'org-property-value t))
5947 ;; Links
5948 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5949 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5950 (if (memq 'plain lk) '(org-activate-plain-links))
5951 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5952 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5953 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5954 (if (memq 'footnote lk) '(org-activate-footnote-links))
5955 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5956 '(org-hide-wide-columns (0 nil append))
5957 ;; TODO keyword
5958 (list (format org-heading-keyword-regexp-format
5959 org-todo-regexp)
5960 '(2 (org-get-todo-face 2) t))
5961 ;; DONE
5962 (if org-fontify-done-headline
5963 (list (format org-heading-keyword-regexp-format
5964 (concat
5965 "\\(?:"
5966 (mapconcat 'regexp-quote org-done-keywords "\\|")
5967 "\\)"))
5968 '(2 'org-headline-done t))
5969 nil)
5970 ;; Priorities
5971 '(org-font-lock-add-priority-faces)
5972 ;; Tags
5973 '(org-font-lock-add-tag-faces)
5974 ;; Special keywords
5975 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5976 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5977 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5978 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5979 ;; Emphasis
5980 (if em
5981 (if (featurep 'xemacs)
5982 '(org-do-emphasis-faces (0 nil append))
5983 '(org-do-emphasis-faces)))
5984 ;; Checkboxes
5985 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5986 1 'org-checkbox prepend)
5987 (if (cdr (assq 'checkbox org-list-automatic-rules))
5988 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5989 (0 (org-get-checkbox-statistics-face) t)))
5990 ;; Description list items
5991 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5992 1 'org-list-dt prepend)
5993 ;; ARCHIVEd headings
5994 (list (concat
5995 org-outline-regexp-bol
5996 "\\(.*:" org-archive-tag ":.*\\)")
5997 '(1 'org-archived prepend))
5998 ;; Specials
5999 '(org-fontify-entities)
6000 '(org-raise-scripts)
6001 ;; Code
6002 '(org-activate-code (1 'org-code t))
6003 ;; COMMENT
6004 (list (format org-heading-keyword-regexp-format
6005 (concat "\\("
6006 org-comment-string "\\|" org-quote-string
6007 "\\)"))
6008 '(2 'org-special-keyword t))
6009 ;; Blocks and meta lines
6010 '(org-fontify-meta-lines-and-blocks)
6012 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6013 (run-hooks 'org-font-lock-set-keywords-hook)
6014 ;; Now set the full font-lock-keywords
6015 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6016 (org-set-local 'font-lock-defaults
6017 '(org-font-lock-keywords t nil nil backward-paragraph))
6018 (kill-local-variable 'font-lock-keywords) nil))
6020 (defun org-toggle-pretty-entities ()
6021 "Toggle the composition display of entities as UTF8 characters."
6022 (interactive)
6023 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6024 (org-restart-font-lock)
6025 (if org-pretty-entities
6026 (message "Entities are displayed as UTF8 characters")
6027 (save-restriction
6028 (widen)
6029 (org-decompose-region (point-min) (point-max))
6030 (message "Entities are displayed plain"))))
6032 (defvar org-custom-properties-overlays nil
6033 "List of overlays used for custom properties.")
6034 (make-variable-buffer-local 'org-custom-properties-overlays)
6036 (defun org-toggle-custom-properties-visibility ()
6037 "Display or hide properties in `org-custom-properties'."
6038 (interactive)
6039 (if org-custom-properties-overlays
6040 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6041 (setq org-custom-properties-overlays nil))
6042 (unless (not org-custom-properties)
6043 (save-excursion
6044 (save-restriction
6045 (widen)
6046 (goto-char (point-min))
6047 (while (re-search-forward org-property-re nil t)
6048 (mapc (lambda(p)
6049 (when (equal p (substring (match-string 1) 1 -1))
6050 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6051 (overlay-put o 'invisible t)
6052 (overlay-put o 'org-custom-property t)
6053 (push o org-custom-properties-overlays))))
6054 org-custom-properties)))))))
6056 (defun org-fontify-entities (limit)
6057 "Find an entity to fontify."
6058 (let (ee)
6059 (when org-pretty-entities
6060 (catch 'match
6061 (while (re-search-forward
6062 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6063 limit t)
6064 (if (and (not (org-in-indented-comment-line))
6065 (setq ee (org-entity-get (match-string 1)))
6066 (= (length (nth 6 ee)) 1))
6067 (let*
6068 ((end (if (equal (match-string 2) "{}")
6069 (match-end 2)
6070 (match-end 1))))
6071 (add-text-properties
6072 (match-beginning 0) end
6073 (list 'font-lock-fontified t))
6074 (compose-region (match-beginning 0) end
6075 (nth 6 ee) nil)
6076 (backward-char 1)
6077 (throw 'match t))))
6078 nil))))
6080 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6081 "Fontify string S like in Org-mode."
6082 (with-temp-buffer
6083 (insert s)
6084 (let ((org-odd-levels-only odd-levels))
6085 (org-mode)
6086 (font-lock-fontify-buffer)
6087 (buffer-string))))
6089 (defvar org-m nil)
6090 (defvar org-l nil)
6091 (defvar org-f nil)
6092 (defun org-get-level-face (n)
6093 "Get the right face for match N in font-lock matching of headlines."
6094 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6095 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6096 (if org-cycle-level-faces
6097 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6098 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6099 (cond
6100 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6101 ((eq n 2) org-f)
6102 (t (if org-level-color-stars-only nil org-f))))
6105 (defun org-get-todo-face (kwd)
6106 "Get the right face for a TODO keyword KWD.
6107 If KWD is a number, get the corresponding match group."
6108 (if (numberp kwd) (setq kwd (match-string kwd)))
6109 (or (org-face-from-face-or-color
6110 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6111 (and (member kwd org-done-keywords) 'org-done)
6112 'org-todo))
6114 (defun org-face-from-face-or-color (context inherit face-or-color)
6115 "Create a face list that inherits INHERIT, but sets the foreground color.
6116 When FACE-OR-COLOR is not a string, just return it."
6117 (if (stringp face-or-color)
6118 (list :inherit inherit
6119 (cdr (assoc context org-faces-easy-properties))
6120 face-or-color)
6121 face-or-color))
6123 (defun org-font-lock-add-tag-faces (limit)
6124 "Add the special tag faces."
6125 (when (and org-tag-faces org-tags-special-faces-re)
6126 (while (re-search-forward org-tags-special-faces-re limit t)
6127 (add-text-properties (match-beginning 1) (match-end 1)
6128 (list 'face (org-get-tag-face 1)
6129 'font-lock-fontified t))
6130 (backward-char 1))))
6132 (defun org-font-lock-add-priority-faces (limit)
6133 "Add the special priority faces."
6134 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6135 (when (save-match-data (org-at-heading-p))
6136 (add-text-properties
6137 (match-beginning 0) (match-end 0)
6138 (list 'face (or (org-face-from-face-or-color
6139 'priority 'org-priority
6140 (cdr (assoc (char-after (match-beginning 1))
6141 org-priority-faces)))
6142 'org-priority)
6143 'font-lock-fontified t)))))
6145 (defun org-get-tag-face (kwd)
6146 "Get the right face for a TODO keyword KWD.
6147 If KWD is a number, get the corresponding match group."
6148 (if (numberp kwd) (setq kwd (match-string kwd)))
6149 (or (org-face-from-face-or-color
6150 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6151 'org-tag))
6153 (defun org-unfontify-region (beg end &optional maybe_loudly)
6154 "Remove fontification and activation overlays from links."
6155 (font-lock-default-unfontify-region beg end)
6156 (let* ((buffer-undo-list t)
6157 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6158 (inhibit-modification-hooks t)
6159 deactivate-mark buffer-file-name buffer-file-truename)
6160 (org-decompose-region beg end)
6161 (remove-text-properties beg end
6162 '(mouse-face t keymap t org-linked-text t
6163 invisible t intangible t
6164 org-no-flyspell t org-emphasis t))
6165 (org-remove-font-lock-display-properties beg end)))
6167 (defconst org-script-display '(((raise -0.3) (height 0.7))
6168 ((raise 0.3) (height 0.7))
6169 ((raise -0.5))
6170 ((raise 0.5)))
6171 "Display properties for showing superscripts and subscripts.")
6173 (defun org-remove-font-lock-display-properties (beg end)
6174 "Remove specific display properties that have been added by font lock.
6175 The will remove the raise properties that are used to show superscripts
6176 and subscripts."
6177 (let (next prop)
6178 (while (< beg end)
6179 (setq next (next-single-property-change beg 'display nil end)
6180 prop (get-text-property beg 'display))
6181 (if (member prop org-script-display)
6182 (put-text-property beg next 'display nil))
6183 (setq beg next))))
6185 (defun org-raise-scripts (limit)
6186 "Add raise properties to sub/superscripts."
6187 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6188 (if (re-search-forward
6189 (if (eq org-use-sub-superscripts t)
6190 org-match-substring-regexp
6191 org-match-substring-with-braces-regexp)
6192 limit t)
6193 (let* ((pos (point)) table-p comment-p
6194 (mpos (match-beginning 3))
6195 (emph-p (get-text-property mpos 'org-emphasis))
6196 (link-p (get-text-property mpos 'mouse-face))
6197 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6198 (goto-char (point-at-bol))
6199 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6200 comment-p (org-looking-at-p "[ \t]*#"))
6201 (goto-char pos)
6202 ;; FIXME: Should we go back one character here, for a_b^c
6203 ;; (goto-char (1- pos)) ;????????????????????
6204 (if (or comment-p emph-p link-p keyw-p)
6206 (put-text-property (match-beginning 3) (match-end 0)
6207 'display
6208 (if (equal (char-after (match-beginning 2)) ?^)
6209 (nth (if table-p 3 1) org-script-display)
6210 (nth (if table-p 2 0) org-script-display)))
6211 (add-text-properties (match-beginning 2) (match-end 2)
6212 (list 'invisible t
6213 'org-dwidth t 'org-dwidth-n 1))
6214 (if (and (eq (char-after (match-beginning 3)) ?{)
6215 (eq (char-before (match-end 3)) ?}))
6216 (progn
6217 (add-text-properties
6218 (match-beginning 3) (1+ (match-beginning 3))
6219 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6220 (add-text-properties
6221 (1- (match-end 3)) (match-end 3)
6222 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6223 t)))))
6225 ;;;; Visibility cycling, including org-goto and indirect buffer
6227 ;;; Cycling
6229 (defvar org-cycle-global-status nil)
6230 (make-variable-buffer-local 'org-cycle-global-status)
6231 (put 'org-cycle-global-status 'org-state t)
6232 (defvar org-cycle-subtree-status nil)
6233 (make-variable-buffer-local 'org-cycle-subtree-status)
6234 (put 'org-cycle-subtree-status 'org-state t)
6236 (defvar org-inlinetask-min-level)
6238 ;;;###autoload
6239 (defun org-cycle (&optional arg)
6240 "TAB-action and visibility cycling for Org-mode.
6242 This is the command invoked in Org-mode by the TAB key. Its main purpose
6243 is outline visibility cycling, but it also invokes other actions
6244 in special contexts.
6246 - When this function is called with a prefix argument, rotate the entire
6247 buffer through 3 states (global cycling)
6248 1. OVERVIEW: Show only top-level headlines.
6249 2. CONTENTS: Show all headlines of all levels, but no body text.
6250 3. SHOW ALL: Show everything.
6251 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6252 determined by the variable `org-startup-folded', and by any VISIBILITY
6253 properties in the buffer.
6254 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6255 including any drawers.
6257 - When inside a table, re-align the table and move to the next field.
6259 - When point is at the beginning of a headline, rotate the subtree started
6260 by this line through 3 different states (local cycling)
6261 1. FOLDED: Only the main headline is shown.
6262 2. CHILDREN: The main headline and the direct children are shown.
6263 From this state, you can move to one of the children
6264 and zoom in further.
6265 3. SUBTREE: Show the entire subtree, including body text.
6266 If there is no subtree, switch directly from CHILDREN to FOLDED.
6268 - When point is at the beginning of an empty headline and the variable
6269 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6270 of the headline by demoting and promoting it to likely levels. This
6271 speeds up creation document structure by pressing TAB once or several
6272 times right after creating a new headline.
6274 - When there is a numeric prefix, go up to a heading with level ARG, do
6275 a `show-subtree' and return to the previous cursor position. If ARG
6276 is negative, go up that many levels.
6278 - When point is not at the beginning of a headline, execute the global
6279 binding for TAB, which is re-indenting the line. See the option
6280 `org-cycle-emulate-tab' for details.
6282 - Special case: if point is at the beginning of the buffer and there is
6283 no headline in line 1, this function will act as if called with prefix arg
6284 (C-u TAB, same as S-TAB) also when called without prefix arg.
6285 But only if also the variable `org-cycle-global-at-bob' is t."
6286 (interactive "P")
6287 (org-load-modules-maybe)
6288 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6289 (and org-cycle-level-after-item/entry-creation
6290 (or (org-cycle-level)
6291 (org-cycle-item-indentation))))
6292 (let* (message-log-max ; Don't populate the *Messages* buffer
6293 (limit-level
6294 (or org-cycle-max-level
6295 (and (boundp 'org-inlinetask-min-level)
6296 org-inlinetask-min-level
6297 (1- org-inlinetask-min-level))))
6298 (nstars (and limit-level
6299 (if org-odd-levels-only
6300 (and limit-level (1- (* limit-level 2)))
6301 limit-level)))
6302 (org-outline-regexp
6303 (if (not (derived-mode-p 'org-mode))
6304 outline-regexp
6305 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6306 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6307 (not (looking-at org-outline-regexp))))
6308 (org-cycle-hook
6309 (if bob-special
6310 (delq 'org-optimize-window-after-visibility-change
6311 (copy-sequence org-cycle-hook))
6312 org-cycle-hook))
6313 (pos (point)))
6315 (if (or bob-special (equal arg '(4)))
6316 ;; special case: use global cycling
6317 (setq arg t))
6319 (cond
6321 ((equal arg '(16))
6322 (setq last-command 'dummy)
6323 (org-set-startup-visibility)
6324 (message "Startup visibility, plus VISIBILITY properties"))
6326 ((equal arg '(64))
6327 (show-all)
6328 (message "Entire buffer visible, including drawers"))
6330 ;; Table: enter it or move to the next field.
6331 ((org-at-table-p 'any)
6332 (if (org-at-table.el-p)
6333 (message "Use C-c ' to edit table.el tables")
6334 (if arg (org-table-edit-field t)
6335 (org-table-justify-field-maybe)
6336 (call-interactively 'org-table-next-field))))
6338 ((run-hook-with-args-until-success
6339 'org-tab-after-check-for-table-hook))
6341 ;; Global cycling: delegate to `org-cycle-internal-global'.
6342 ((eq arg t) (org-cycle-internal-global))
6344 ;; Drawers: delegate to `org-flag-drawer'.
6345 ((and org-drawers org-drawer-regexp
6346 (save-excursion
6347 (beginning-of-line 1)
6348 (looking-at org-drawer-regexp)))
6349 (org-flag-drawer ; toggle block visibility
6350 (not (get-char-property (match-end 0) 'invisible))))
6352 ;; Show-subtree, ARG levels up from here.
6353 ((integerp arg)
6354 (save-excursion
6355 (org-back-to-heading)
6356 (outline-up-heading (if (< arg 0) (- arg)
6357 (- (funcall outline-level) arg)))
6358 (org-show-subtree)))
6360 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6361 ((and (featurep 'org-inlinetask)
6362 (org-inlinetask-at-task-p)
6363 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6364 (org-inlinetask-toggle-visibility))
6366 ((org-try-cdlatex-tab))
6368 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6369 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6370 (save-excursion (beginning-of-line 1)
6371 (looking-at org-outline-regexp)))
6372 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6373 (org-cycle-internal-local))
6375 ;; From there: TAB emulation and template completion.
6376 (buffer-read-only (org-back-to-heading))
6378 ((run-hook-with-args-until-success
6379 'org-tab-after-check-for-cycling-hook))
6381 ((org-try-structure-completion))
6383 ((run-hook-with-args-until-success
6384 'org-tab-before-tab-emulation-hook))
6386 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6387 (or (not (bolp))
6388 (not (looking-at org-outline-regexp))))
6389 (call-interactively (global-key-binding "\t")))
6391 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6392 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6393 (or (and (eq org-cycle-emulate-tab 'white)
6394 (= (match-end 0) (point-at-eol)))
6395 (and (eq org-cycle-emulate-tab 'whitestart)
6396 (>= (match-end 0) pos))))
6398 (eq org-cycle-emulate-tab t))
6399 (call-interactively (global-key-binding "\t")))
6401 (t (save-excursion
6402 (org-back-to-heading)
6403 (org-cycle)))))))
6405 (defun org-cycle-internal-global ()
6406 "Do the global cycling action."
6407 ;; Hack to avoid display of messages for .org attachments in Gnus
6408 (let (message-log-max ; Don't populate the *Messages* buffer
6409 (ga (string-match "\\*fontification" (buffer-name))))
6410 (cond
6411 ((and (eq last-command this-command)
6412 (eq org-cycle-global-status 'overview))
6413 ;; We just created the overview - now do table of contents
6414 ;; This can be slow in very large buffers, so indicate action
6415 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6416 (unless ga (message "CONTENTS..."))
6417 (org-content)
6418 (unless ga (message "CONTENTS...done"))
6419 (setq org-cycle-global-status 'contents)
6420 (run-hook-with-args 'org-cycle-hook 'contents))
6422 ((and (eq last-command this-command)
6423 (eq org-cycle-global-status 'contents))
6424 ;; We just showed the table of contents - now show everything
6425 (run-hook-with-args 'org-pre-cycle-hook 'all)
6426 (show-all)
6427 (unless ga (message "SHOW ALL"))
6428 (setq org-cycle-global-status 'all)
6429 (run-hook-with-args 'org-cycle-hook 'all))
6432 ;; Default action: go to overview
6433 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6434 (org-overview)
6435 (unless ga (message "OVERVIEW"))
6436 (setq org-cycle-global-status 'overview)
6437 (run-hook-with-args 'org-cycle-hook 'overview)))))
6439 (defun org-cycle-internal-local ()
6440 "Do the local cycling action."
6441 (let (message-log-max ; Don't populate the *Messages* buffer
6442 (goal-column 0) eoh eol eos has-children children-skipped struct)
6443 ;; First, determine end of headline (EOH), end of subtree or item
6444 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6445 (save-excursion
6446 (if (org-at-item-p)
6447 (progn
6448 (beginning-of-line)
6449 (setq struct (org-list-struct))
6450 (setq eoh (point-at-eol))
6451 (setq eos (org-list-get-item-end-before-blank (point) struct))
6452 (setq has-children (org-list-has-child-p (point) struct)))
6453 (org-back-to-heading)
6454 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6455 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6456 (setq has-children
6457 (or (save-excursion
6458 (let ((level (funcall outline-level)))
6459 (outline-next-heading)
6460 (and (org-at-heading-p t)
6461 (> (funcall outline-level) level))))
6462 (save-excursion
6463 (org-list-search-forward (org-item-beginning-re) eos t)))))
6464 ;; Determine end invisible part of buffer (EOL)
6465 (beginning-of-line 2)
6466 ;; XEmacs doesn't have `next-single-char-property-change'
6467 (if (featurep 'xemacs)
6468 (while (and (not (eobp)) ;; this is like `next-line'
6469 (get-char-property (1- (point)) 'invisible))
6470 (beginning-of-line 2))
6471 (while (and (not (eobp)) ;; this is like `next-line'
6472 (get-char-property (1- (point)) 'invisible))
6473 (goto-char (next-single-char-property-change (point) 'invisible))
6474 (and (eolp) (beginning-of-line 2))))
6475 (setq eol (point)))
6476 ;; Find out what to do next and set `this-command'
6477 (cond
6478 ((= eos eoh)
6479 ;; Nothing is hidden behind this heading
6480 (unless (org-before-first-heading-p)
6481 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6482 (message "EMPTY ENTRY")
6483 (setq org-cycle-subtree-status nil)
6484 (save-excursion
6485 (goto-char eos)
6486 (outline-next-heading)
6487 (if (outline-invisible-p) (org-flag-heading nil))))
6488 ((and (or (>= eol eos)
6489 (not (string-match "\\S-" (buffer-substring eol eos))))
6490 (or has-children
6491 (not (setq children-skipped
6492 org-cycle-skip-children-state-if-no-children))))
6493 ;; Entire subtree is hidden in one line: children view
6494 (unless (org-before-first-heading-p)
6495 (run-hook-with-args 'org-pre-cycle-hook 'children))
6496 (if (org-at-item-p)
6497 (org-list-set-item-visibility (point-at-bol) struct 'children)
6498 (org-show-entry)
6499 (org-with-limited-levels (show-children))
6500 ;; FIXME: This slows down the func way too much.
6501 ;; How keep drawers hidden in subtree anyway?
6502 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6503 ;; (org-cycle-hide-drawers 'subtree))
6505 ;; Fold every list in subtree to top-level items.
6506 (when (eq org-cycle-include-plain-lists 'integrate)
6507 (save-excursion
6508 (org-back-to-heading)
6509 (while (org-list-search-forward (org-item-beginning-re) eos t)
6510 (beginning-of-line 1)
6511 (let* ((struct (org-list-struct))
6512 (prevs (org-list-prevs-alist struct))
6513 (end (org-list-get-bottom-point struct)))
6514 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6515 (org-list-get-all-items (point) struct prevs))
6516 (goto-char end))))))
6517 (message "CHILDREN")
6518 (save-excursion
6519 (goto-char eos)
6520 (outline-next-heading)
6521 (if (outline-invisible-p) (org-flag-heading nil)))
6522 (setq org-cycle-subtree-status 'children)
6523 (unless (org-before-first-heading-p)
6524 (run-hook-with-args 'org-cycle-hook 'children)))
6525 ((or children-skipped
6526 (and (eq last-command this-command)
6527 (eq org-cycle-subtree-status 'children)))
6528 ;; We just showed the children, or no children are there,
6529 ;; now show everything.
6530 (unless (org-before-first-heading-p)
6531 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6532 (outline-flag-region eoh eos nil)
6533 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6534 (setq org-cycle-subtree-status 'subtree)
6535 (unless (org-before-first-heading-p)
6536 (run-hook-with-args 'org-cycle-hook 'subtree)))
6538 ;; Default action: hide the subtree.
6539 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6540 (outline-flag-region eoh eos t)
6541 (message "FOLDED")
6542 (setq org-cycle-subtree-status 'folded)
6543 (unless (org-before-first-heading-p)
6544 (run-hook-with-args 'org-cycle-hook 'folded))))))
6546 ;;;###autoload
6547 (defun org-global-cycle (&optional arg)
6548 "Cycle the global visibility. For details see `org-cycle'.
6549 With \\[universal-argument] prefix arg, switch to startup visibility.
6550 With a numeric prefix, show all headlines up to that level."
6551 (interactive "P")
6552 (let ((org-cycle-include-plain-lists
6553 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6554 (cond
6555 ((integerp arg)
6556 (show-all)
6557 (hide-sublevels arg)
6558 (setq org-cycle-global-status 'contents))
6559 ((equal arg '(4))
6560 (org-set-startup-visibility)
6561 (message "Startup visibility, plus VISIBILITY properties."))
6563 (org-cycle '(4))))))
6565 (defun org-set-startup-visibility ()
6566 "Set the visibility required by startup options and properties."
6567 (cond
6568 ((eq org-startup-folded t)
6569 (org-cycle '(4)))
6570 ((eq org-startup-folded 'content)
6571 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6572 (org-cycle '(4)) (org-cycle '(4)))))
6573 (unless (eq org-startup-folded 'showeverything)
6574 (if org-hide-block-startup (org-hide-block-all))
6575 (org-set-visibility-according-to-property 'no-cleanup)
6576 (org-cycle-hide-archived-subtrees 'all)
6577 (org-cycle-hide-drawers 'all)
6578 (org-cycle-show-empty-lines t)))
6580 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6581 "Switch subtree visibilities according to :VISIBILITY: property."
6582 (interactive)
6583 (let (org-show-entry-below state)
6584 (save-excursion
6585 (goto-char (point-min))
6586 (while (re-search-forward
6587 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6588 nil t)
6589 (setq state (match-string 1))
6590 (save-excursion
6591 (org-back-to-heading t)
6592 (hide-subtree)
6593 (org-reveal)
6594 (cond
6595 ((equal state '("fold" "folded"))
6596 (hide-subtree))
6597 ((equal state "children")
6598 (org-show-hidden-entry)
6599 (show-children))
6600 ((equal state "content")
6601 (save-excursion
6602 (save-restriction
6603 (org-narrow-to-subtree)
6604 (org-content))))
6605 ((member state '("all" "showall"))
6606 (show-subtree)))))
6607 (unless no-cleanup
6608 (org-cycle-hide-archived-subtrees 'all)
6609 (org-cycle-hide-drawers 'all)
6610 (org-cycle-show-empty-lines 'all)))))
6612 ;; This function uses outline-regexp instead of the more fundamental
6613 ;; org-outline-regexp so that org-cycle-global works outside of Org
6614 ;; buffers, where outline-regexp is needed.
6615 (defun org-overview ()
6616 "Switch to overview mode, showing only top-level headlines.
6617 Really, this shows all headlines with level equal or greater than the level
6618 of the first headline in the buffer. This is important, because if the
6619 first headline is not level one, then (hide-sublevels 1) gives confusing
6620 results."
6621 (interactive)
6622 (let ((level (save-excursion
6623 (goto-char (point-min))
6624 (if (re-search-forward (concat "^" outline-regexp) nil t)
6625 (progn
6626 (goto-char (match-beginning 0))
6627 (funcall outline-level))))))
6628 (and level (hide-sublevels level))))
6630 (defun org-content (&optional arg)
6631 "Show all headlines in the buffer, like a table of contents.
6632 With numerical argument N, show content up to level N."
6633 (interactive "P")
6634 (save-excursion
6635 ;; Visit all headings and show their offspring
6636 (and (integerp arg) (org-overview))
6637 (goto-char (point-max))
6638 (catch 'exit
6639 (while (and (progn (condition-case nil
6640 (outline-previous-visible-heading 1)
6641 (error (goto-char (point-min))))
6643 (looking-at org-outline-regexp))
6644 (if (integerp arg)
6645 (show-children (1- arg))
6646 (show-branches))
6647 (if (bobp) (throw 'exit nil))))))
6650 (defun org-optimize-window-after-visibility-change (state)
6651 "Adjust the window after a change in outline visibility.
6652 This function is the default value of the hook `org-cycle-hook'."
6653 (when (get-buffer-window (current-buffer))
6654 (cond
6655 ((eq state 'content) nil)
6656 ((eq state 'all) nil)
6657 ((eq state 'folded) nil)
6658 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6659 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6661 (defun org-remove-empty-overlays-at (pos)
6662 "Remove outline overlays that do not contain non-white stuff."
6663 (mapc
6664 (lambda (o)
6665 (and (eq 'outline (overlay-get o 'invisible))
6666 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6667 (overlay-end o))))
6668 (delete-overlay o)))
6669 (overlays-at pos)))
6671 (defun org-clean-visibility-after-subtree-move ()
6672 "Fix visibility issues after moving a subtree."
6673 ;; First, find a reasonable region to look at:
6674 ;; Start two siblings above, end three below
6675 (let* ((beg (save-excursion
6676 (and (org-get-last-sibling)
6677 (org-get-last-sibling))
6678 (point)))
6679 (end (save-excursion
6680 (and (org-get-next-sibling)
6681 (org-get-next-sibling)
6682 (org-get-next-sibling))
6683 (if (org-at-heading-p)
6684 (point-at-eol)
6685 (point))))
6686 (level (looking-at "\\*+"))
6687 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6688 (save-excursion
6689 (save-restriction
6690 (narrow-to-region beg end)
6691 (when re
6692 ;; Properly fold already folded siblings
6693 (goto-char (point-min))
6694 (while (re-search-forward re nil t)
6695 (if (and (not (outline-invisible-p))
6696 (save-excursion
6697 (goto-char (point-at-eol)) (outline-invisible-p)))
6698 (hide-entry))))
6699 (org-cycle-show-empty-lines 'overview)
6700 (org-cycle-hide-drawers 'overview)))))
6702 (defun org-cycle-show-empty-lines (state)
6703 "Show empty lines above all visible headlines.
6704 The region to be covered depends on STATE when called through
6705 `org-cycle-hook'. Lisp program can use t for STATE to get the
6706 entire buffer covered. Note that an empty line is only shown if there
6707 are at least `org-cycle-separator-lines' empty lines before the headline."
6708 (when (not (= org-cycle-separator-lines 0))
6709 (save-excursion
6710 (let* ((n (abs org-cycle-separator-lines))
6711 (re (cond
6712 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6713 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6714 (t (let ((ns (number-to-string (- n 2))))
6715 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6716 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6717 beg end b e)
6718 (cond
6719 ((memq state '(overview contents t))
6720 (setq beg (point-min) end (point-max)))
6721 ((memq state '(children folded))
6722 (setq beg (point) end (progn (org-end-of-subtree t t)
6723 (beginning-of-line 2)
6724 (point)))))
6725 (when beg
6726 (goto-char beg)
6727 (while (re-search-forward re end t)
6728 (unless (get-char-property (match-end 1) 'invisible)
6729 (setq e (match-end 1))
6730 (if (< org-cycle-separator-lines 0)
6731 (setq b (save-excursion
6732 (goto-char (match-beginning 0))
6733 (org-back-over-empty-lines)
6734 (if (save-excursion
6735 (goto-char (max (point-min) (1- (point))))
6736 (org-at-heading-p))
6737 (1- (point))
6738 (point))))
6739 (setq b (match-beginning 1)))
6740 (outline-flag-region b e nil)))))))
6741 ;; Never hide empty lines at the end of the file.
6742 (save-excursion
6743 (goto-char (point-max))
6744 (outline-previous-heading)
6745 (outline-end-of-heading)
6746 (if (and (looking-at "[ \t\n]+")
6747 (= (match-end 0) (point-max)))
6748 (outline-flag-region (point) (match-end 0) nil))))
6750 (defun org-show-empty-lines-in-parent ()
6751 "Move to the parent and re-show empty lines before visible headlines."
6752 (save-excursion
6753 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6754 (org-cycle-show-empty-lines context))))
6756 (defun org-files-list ()
6757 "Return `org-agenda-files' list, plus all open org-mode files.
6758 This is useful for operations that need to scan all of a user's
6759 open and agenda-wise Org files."
6760 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6761 (dolist (buf (buffer-list))
6762 (with-current-buffer buf
6763 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6764 (let ((file (expand-file-name (buffer-file-name))))
6765 (unless (member file files)
6766 (push file files))))))
6767 files))
6769 (defsubst org-entry-beginning-position ()
6770 "Return the beginning position of the current entry."
6771 (save-excursion (outline-back-to-heading t) (point)))
6773 (defsubst org-entry-end-position ()
6774 "Return the end position of the current entry."
6775 (save-excursion (outline-next-heading) (point)))
6777 (defun org-cycle-hide-drawers (state)
6778 "Re-hide all drawers after a visibility state change."
6779 (when (and (derived-mode-p 'org-mode)
6780 (not (memq state '(overview folded contents))))
6781 (save-excursion
6782 (let* ((globalp (memq state '(contents all)))
6783 (beg (if globalp (point-min) (point)))
6784 (end (if globalp (point-max)
6785 (if (eq state 'children)
6786 (save-excursion (outline-next-heading) (point))
6787 (org-end-of-subtree t)))))
6788 (goto-char beg)
6789 (while (re-search-forward org-drawer-regexp end t)
6790 (org-flag-drawer t))))))
6792 (defun org-cycle-hide-inline-tasks (state)
6793 "Re-hide inline task when switching to 'contents visibility state."
6794 (when (and (eq state 'contents)
6795 (boundp 'org-inlinetask-min-level)
6796 org-inlinetask-min-level)
6797 (hide-sublevels (1- org-inlinetask-min-level))))
6799 (defun org-flag-drawer (flag)
6800 "When FLAG is non-nil, hide the drawer we are within.
6801 Otherwise make it visible."
6802 (save-excursion
6803 (beginning-of-line 1)
6804 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6805 (let ((b (match-end 0)))
6806 (if (re-search-forward
6807 "^[ \t]*:END:"
6808 (save-excursion (outline-next-heading) (point)) t)
6809 (outline-flag-region b (point-at-eol) flag)
6810 (error ":END: line missing at position %s" b))))))
6812 (defun org-subtree-end-visible-p ()
6813 "Is the end of the current subtree visible?"
6814 (pos-visible-in-window-p
6815 (save-excursion (org-end-of-subtree t) (point))))
6817 (defun org-first-headline-recenter (&optional N)
6818 "Move cursor to the first headline and recenter the headline.
6819 Optional argument N means put the headline into the Nth line of the window."
6820 (goto-char (point-min))
6821 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6822 (beginning-of-line)
6823 (recenter (prefix-numeric-value N))))
6825 ;;; Saving and restoring visibility
6827 (defun org-outline-overlay-data (&optional use-markers)
6828 "Return a list of the locations of all outline overlays.
6829 These are overlays with the `invisible' property value `outline'.
6830 The return value is a list of cons cells, with start and stop
6831 positions for each overlay.
6832 If USE-MARKERS is set, return the positions as markers."
6833 (let (beg end)
6834 (save-excursion
6835 (save-restriction
6836 (widen)
6837 (delq nil
6838 (mapcar (lambda (o)
6839 (when (eq (overlay-get o 'invisible) 'outline)
6840 (setq beg (overlay-start o)
6841 end (overlay-end o))
6842 (and beg end (> end beg)
6843 (if use-markers
6844 (cons (move-marker (make-marker) beg)
6845 (move-marker (make-marker) end))
6846 (cons beg end)))))
6847 (overlays-in (point-min) (point-max))))))))
6849 (defun org-set-outline-overlay-data (data)
6850 "Create visibility overlays for all positions in DATA.
6851 DATA should have been made by `org-outline-overlay-data'."
6852 (let (o)
6853 (save-excursion
6854 (save-restriction
6855 (widen)
6856 (show-all)
6857 (mapc (lambda (c)
6858 (outline-flag-region (car c) (cdr c) t))
6859 data)))))
6861 ;;; Folding of blocks
6863 (defvar org-hide-block-overlays nil
6864 "Overlays hiding blocks.")
6865 (make-variable-buffer-local 'org-hide-block-overlays)
6867 (defun org-block-map (function &optional start end)
6868 "Call FUNCTION at the head of all source blocks in the current buffer.
6869 Optional arguments START and END can be used to limit the range."
6870 (let ((start (or start (point-min)))
6871 (end (or end (point-max))))
6872 (save-excursion
6873 (goto-char start)
6874 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6875 (save-excursion
6876 (save-match-data
6877 (goto-char (match-beginning 0))
6878 (funcall function)))))))
6880 (defun org-hide-block-toggle-all ()
6881 "Toggle the visibility of all blocks in the current buffer."
6882 (org-block-map #'org-hide-block-toggle))
6884 (defun org-hide-block-all ()
6885 "Fold all blocks in the current buffer."
6886 (interactive)
6887 (org-show-block-all)
6888 (org-block-map #'org-hide-block-toggle-maybe))
6890 (defun org-show-block-all ()
6891 "Unfold all blocks in the current buffer."
6892 (interactive)
6893 (mapc 'delete-overlay org-hide-block-overlays)
6894 (setq org-hide-block-overlays nil))
6896 (defun org-hide-block-toggle-maybe ()
6897 "Toggle visibility of block at point."
6898 (interactive)
6899 (let ((case-fold-search t))
6900 (if (save-excursion
6901 (beginning-of-line 1)
6902 (looking-at org-block-regexp))
6903 (progn (org-hide-block-toggle)
6904 t) ;; to signal that we took action
6905 nil))) ;; to signal that we did not
6907 (defun org-hide-block-toggle (&optional force)
6908 "Toggle the visibility of the current block."
6909 (interactive)
6910 (save-excursion
6911 (beginning-of-line)
6912 (if (re-search-forward org-block-regexp nil t)
6913 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6914 (end (match-end 0)) ;; end of entire body
6916 (if (memq t (mapcar (lambda (overlay)
6917 (eq (overlay-get overlay 'invisible)
6918 'org-hide-block))
6919 (overlays-at start)))
6920 (if (or (not force) (eq force 'off))
6921 (mapc (lambda (ov)
6922 (when (member ov org-hide-block-overlays)
6923 (setq org-hide-block-overlays
6924 (delq ov org-hide-block-overlays)))
6925 (when (eq (overlay-get ov 'invisible)
6926 'org-hide-block)
6927 (delete-overlay ov)))
6928 (overlays-at start)))
6929 (setq ov (make-overlay start end))
6930 (overlay-put ov 'invisible 'org-hide-block)
6931 ;; make the block accessible to isearch
6932 (overlay-put
6933 ov 'isearch-open-invisible
6934 (lambda (ov)
6935 (when (member ov org-hide-block-overlays)
6936 (setq org-hide-block-overlays
6937 (delq ov org-hide-block-overlays)))
6938 (when (eq (overlay-get ov 'invisible)
6939 'org-hide-block)
6940 (delete-overlay ov))))
6941 (push ov org-hide-block-overlays)))
6942 (error "Not looking at a source block"))))
6944 ;; org-tab-after-check-for-cycling-hook
6945 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6946 ;; Remove overlays when changing major mode
6947 (add-hook 'org-mode-hook
6948 (lambda () (org-add-hook 'change-major-mode-hook
6949 'org-show-block-all 'append 'local)))
6951 ;;; Org-goto
6953 (defvar org-goto-window-configuration nil)
6954 (defvar org-goto-marker nil)
6955 (defvar org-goto-map)
6956 (defun org-goto-map ()
6957 "Set the keymap `org-goto'."
6958 (setq org-goto-map
6959 (let ((map (make-sparse-keymap)))
6960 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6961 mouse-drag-region universal-argument org-occur))
6962 cmd)
6963 (while (setq cmd (pop cmds))
6964 (substitute-key-definition cmd cmd map global-map)))
6965 (suppress-keymap map)
6966 (org-defkey map "\C-m" 'org-goto-ret)
6967 (org-defkey map [(return)] 'org-goto-ret)
6968 (org-defkey map [(left)] 'org-goto-left)
6969 (org-defkey map [(right)] 'org-goto-right)
6970 (org-defkey map [(control ?g)] 'org-goto-quit)
6971 (org-defkey map "\C-i" 'org-cycle)
6972 (org-defkey map [(tab)] 'org-cycle)
6973 (org-defkey map [(down)] 'outline-next-visible-heading)
6974 (org-defkey map [(up)] 'outline-previous-visible-heading)
6975 (if org-goto-auto-isearch
6976 (if (fboundp 'define-key-after)
6977 (define-key-after map [t] 'org-goto-local-auto-isearch)
6978 nil)
6979 (org-defkey map "q" 'org-goto-quit)
6980 (org-defkey map "n" 'outline-next-visible-heading)
6981 (org-defkey map "p" 'outline-previous-visible-heading)
6982 (org-defkey map "f" 'outline-forward-same-level)
6983 (org-defkey map "b" 'outline-backward-same-level)
6984 (org-defkey map "u" 'outline-up-heading))
6985 (org-defkey map "/" 'org-occur)
6986 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6987 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6988 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6989 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6990 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6991 map)))
6993 (defconst org-goto-help
6994 "Browse buffer copy, to find location or copy text.%s
6995 RET=jump to location C-g=quit and return to previous location
6996 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6998 (defvar org-goto-start-pos) ; dynamically scoped parameter
7000 ;; FIXME: Docstring does not mention both interfaces
7001 (defun org-goto (&optional alternative-interface)
7002 "Look up a different location in the current file, keeping current visibility.
7004 When you want look-up or go to a different location in a
7005 document, the fastest way is often to fold the entire buffer and
7006 then dive into the tree. This method has the disadvantage, that
7007 the previous location will be folded, which may not be what you
7008 want.
7010 This command works around this by showing a copy of the current
7011 buffer in an indirect buffer, in overview mode. You can dive
7012 into the tree in that copy, use org-occur and incremental search
7013 to find a location. When pressing RET or `Q', the command
7014 returns to the original buffer in which the visibility is still
7015 unchanged. After RET it will also jump to the location selected
7016 in the indirect buffer and expose the headline hierarchy above.
7018 With a prefix argument, use the alternative interface: e.g. if
7019 `org-goto-interface' is 'outline use 'outline-path-completion."
7020 (interactive "P")
7021 (org-goto-map)
7022 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7023 (org-refile-use-outline-path t)
7024 (org-refile-target-verify-function nil)
7025 (interface
7026 (if (not alternative-interface)
7027 org-goto-interface
7028 (if (eq org-goto-interface 'outline)
7029 'outline-path-completion
7030 'outline)))
7031 (org-goto-start-pos (point))
7032 (selected-point
7033 (if (eq interface 'outline)
7034 (car (org-get-location (current-buffer) org-goto-help))
7035 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7036 (org-refile-check-position pa)
7037 (nth 3 pa)))))
7038 (if selected-point
7039 (progn
7040 (org-mark-ring-push org-goto-start-pos)
7041 (goto-char selected-point)
7042 (if (or (outline-invisible-p) (org-invisible-p2))
7043 (org-show-context 'org-goto)))
7044 (message "Quit"))))
7046 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7047 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7048 (defvar org-goto-local-auto-isearch-map) ; defined below
7050 (defun org-get-location (buf help)
7051 "Let the user select a location in the Org-mode buffer BUF.
7052 This function uses a recursive edit. It returns the selected position
7053 or nil."
7054 (org-no-popups
7055 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7056 (isearch-hide-immediately nil)
7057 (isearch-search-fun-function
7058 (lambda () 'org-goto-local-search-headings))
7059 (org-goto-selected-point org-goto-exit-command))
7060 (save-excursion
7061 (save-window-excursion
7062 (delete-other-windows)
7063 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7064 (org-pop-to-buffer-same-window
7065 (condition-case nil
7066 (make-indirect-buffer (current-buffer) "*org-goto*")
7067 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7068 (with-output-to-temp-buffer "*Org Help*"
7069 (princ (format help (if org-goto-auto-isearch
7070 " Just type for auto-isearch."
7071 " n/p/f/b/u to navigate, q to quit."))))
7072 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7073 (setq buffer-read-only nil)
7074 (let ((org-startup-truncated t)
7075 (org-startup-folded nil)
7076 (org-startup-align-all-tables nil))
7077 (org-mode)
7078 (org-overview))
7079 (setq buffer-read-only t)
7080 (if (and (boundp 'org-goto-start-pos)
7081 (integer-or-marker-p org-goto-start-pos))
7082 (let ((org-show-hierarchy-above t)
7083 (org-show-siblings t)
7084 (org-show-following-heading t))
7085 (goto-char org-goto-start-pos)
7086 (and (outline-invisible-p) (org-show-context)))
7087 (goto-char (point-min)))
7088 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7089 (message "Select location and press RET")
7090 (use-local-map org-goto-map)
7091 (recursive-edit)))
7092 (kill-buffer "*org-goto*")
7093 (cons org-goto-selected-point org-goto-exit-command))))
7095 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7096 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7097 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7098 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7100 (defun org-goto-local-search-headings (string bound noerror)
7101 "Search and make sure that any matches are in headlines."
7102 (catch 'return
7103 (while (if isearch-forward
7104 (search-forward string bound noerror)
7105 (search-backward string bound noerror))
7106 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7107 (and (member :headline context)
7108 (not (member :tags context))))
7109 (throw 'return (point))))))
7111 (defun org-goto-local-auto-isearch ()
7112 "Start isearch."
7113 (interactive)
7114 (goto-char (point-min))
7115 (let ((keys (this-command-keys)))
7116 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7117 (isearch-mode t)
7118 (isearch-process-search-char (string-to-char keys)))))
7120 (defun org-goto-ret (&optional arg)
7121 "Finish `org-goto' by going to the new location."
7122 (interactive "P")
7123 (setq org-goto-selected-point (point)
7124 org-goto-exit-command 'return)
7125 (throw 'exit nil))
7127 (defun org-goto-left ()
7128 "Finish `org-goto' by going to the new location."
7129 (interactive)
7130 (if (org-at-heading-p)
7131 (progn
7132 (beginning-of-line 1)
7133 (setq org-goto-selected-point (point)
7134 org-goto-exit-command 'left)
7135 (throw 'exit nil))
7136 (error "Not on a heading")))
7138 (defun org-goto-right ()
7139 "Finish `org-goto' by going to the new location."
7140 (interactive)
7141 (if (org-at-heading-p)
7142 (progn
7143 (setq org-goto-selected-point (point)
7144 org-goto-exit-command 'right)
7145 (throw 'exit nil))
7146 (error "Not on a heading")))
7148 (defun org-goto-quit ()
7149 "Finish `org-goto' without cursor motion."
7150 (interactive)
7151 (setq org-goto-selected-point nil)
7152 (setq org-goto-exit-command 'quit)
7153 (throw 'exit nil))
7155 ;;; Indirect buffer display of subtrees
7157 (defvar org-indirect-dedicated-frame nil
7158 "This is the frame being used for indirect tree display.")
7159 (defvar org-last-indirect-buffer nil)
7161 (defun org-tree-to-indirect-buffer (&optional arg)
7162 "Create indirect buffer and narrow it to current subtree.
7163 With a numerical prefix ARG, go up to this level and then take that tree.
7164 If ARG is negative, go up that many levels.
7166 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7167 indirect buffer previously made with this command, to avoid proliferation of
7168 indirect buffers. However, when you call the command with a \
7169 \\[universal-argument] prefix, or
7170 when `org-indirect-buffer-display' is `new-frame', the last buffer
7171 is kept so that you can work with several indirect buffers at the same time.
7172 If `org-indirect-buffer-display' is `dedicated-frame', the \
7173 \\[universal-argument] prefix also
7174 requests that a new frame be made for the new buffer, so that the dedicated
7175 frame is not changed."
7176 (interactive "P")
7177 (let ((cbuf (current-buffer))
7178 (cwin (selected-window))
7179 (pos (point))
7180 beg end level heading ibuf)
7181 (save-excursion
7182 (org-back-to-heading t)
7183 (when (numberp arg)
7184 (setq level (org-outline-level))
7185 (if (< arg 0) (setq arg (+ level arg)))
7186 (while (> (setq level (org-outline-level)) arg)
7187 (org-up-heading-safe)))
7188 (setq beg (point)
7189 heading (org-get-heading))
7190 (org-end-of-subtree t t)
7191 (if (org-at-heading-p) (backward-char 1))
7192 (setq end (point)))
7193 (if (and (buffer-live-p org-last-indirect-buffer)
7194 (not (eq org-indirect-buffer-display 'new-frame))
7195 (not arg))
7196 (kill-buffer org-last-indirect-buffer))
7197 (setq ibuf (org-get-indirect-buffer cbuf)
7198 org-last-indirect-buffer ibuf)
7199 (cond
7200 ((or (eq org-indirect-buffer-display 'new-frame)
7201 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7202 (select-frame (make-frame))
7203 (delete-other-windows)
7204 (org-pop-to-buffer-same-window ibuf)
7205 (org-set-frame-title heading))
7206 ((eq org-indirect-buffer-display 'dedicated-frame)
7207 (raise-frame
7208 (select-frame (or (and org-indirect-dedicated-frame
7209 (frame-live-p org-indirect-dedicated-frame)
7210 org-indirect-dedicated-frame)
7211 (setq org-indirect-dedicated-frame (make-frame)))))
7212 (delete-other-windows)
7213 (org-pop-to-buffer-same-window ibuf)
7214 (org-set-frame-title (concat "Indirect: " heading)))
7215 ((eq org-indirect-buffer-display 'current-window)
7216 (org-pop-to-buffer-same-window ibuf))
7217 ((eq org-indirect-buffer-display 'other-window)
7218 (pop-to-buffer ibuf))
7219 (t (error "Invalid value")))
7220 (if (featurep 'xemacs)
7221 (save-excursion (org-mode) (turn-on-font-lock)))
7222 (narrow-to-region beg end)
7223 (show-all)
7224 (goto-char pos)
7225 (run-hook-with-args 'org-cycle-hook 'all)
7226 (and (window-live-p cwin) (select-window cwin))))
7228 (defun org-get-indirect-buffer (&optional buffer)
7229 (setq buffer (or buffer (current-buffer)))
7230 (let ((n 1) (base (buffer-name buffer)) bname)
7231 (while (buffer-live-p
7232 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7233 (setq n (1+ n)))
7234 (condition-case nil
7235 (make-indirect-buffer buffer bname 'clone)
7236 (error (make-indirect-buffer buffer bname)))))
7238 (defun org-set-frame-title (title)
7239 "Set the title of the current frame to the string TITLE."
7240 ;; FIXME: how to name a single frame in XEmacs???
7241 (unless (featurep 'xemacs)
7242 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7244 ;;;; Structure editing
7246 ;;; Inserting headlines
7248 (defun org-previous-line-empty-p ()
7249 (save-excursion
7250 (and (not (bobp))
7251 (or (beginning-of-line 0) t)
7252 (save-match-data
7253 (looking-at "[ \t]*$")))))
7255 (defun org-insert-heading (&optional force-heading invisible-ok)
7256 "Insert a new heading or item with same depth at point.
7257 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7258 If point is at the beginning of a headline, insert a sibling before the
7259 current headline. If point is not at the beginning, split the line,
7260 create the new headline with the text in the current line after point
7261 \(but see also the variable `org-M-RET-may-split-line').
7263 With a double prefix arg, force the heading to be inserted at the
7264 end of the parent subtree.
7266 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7267 This is important for non-interactive uses of the command."
7268 (interactive "P")
7269 (if (or (= (buffer-size) 0)
7270 (and (not (save-excursion
7271 (and (ignore-errors (org-back-to-heading invisible-ok))
7272 (org-at-heading-p))))
7273 (or force-heading (not (org-in-item-p)))))
7274 (progn
7275 (insert "\n* ")
7276 (run-hooks 'org-insert-heading-hook))
7277 (when (or force-heading (not (org-insert-item)))
7278 (let* ((empty-line-p nil)
7279 (level nil)
7280 (on-heading (org-at-heading-p))
7281 (head (save-excursion
7282 (condition-case nil
7283 (progn
7284 (org-back-to-heading invisible-ok)
7285 (when (and (not on-heading)
7286 (featurep 'org-inlinetask)
7287 (integerp org-inlinetask-min-level)
7288 (>= (length (match-string 0))
7289 org-inlinetask-min-level))
7290 ;; Find a heading level before the inline task
7291 (while (and (setq level (org-up-heading-safe))
7292 (>= level org-inlinetask-min-level)))
7293 (if (org-at-heading-p)
7294 (org-back-to-heading invisible-ok)
7295 (error "This should not happen")))
7296 (setq empty-line-p (org-previous-line-empty-p))
7297 (match-string 0))
7298 (error "*"))))
7299 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7300 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7301 pos hide-previous previous-pos)
7302 (cond
7303 ((and (org-at-heading-p) (bolp)
7304 (or (bobp)
7305 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7306 ;; insert before the current line
7307 (open-line (if blank 2 1)))
7308 ((and (bolp)
7309 (not org-insert-heading-respect-content)
7310 (or (bobp)
7311 (save-excursion
7312 (backward-char 1) (not (outline-invisible-p)))))
7313 ;; insert right here
7314 nil)
7316 ;; somewhere in the line
7317 (save-excursion
7318 (setq previous-pos (point-at-bol))
7319 (end-of-line)
7320 (setq hide-previous (outline-invisible-p)))
7321 (and org-insert-heading-respect-content (org-show-subtree))
7322 (let ((split
7323 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7324 (save-excursion
7325 (let ((p (point)))
7326 (goto-char (point-at-bol))
7327 (and (looking-at org-complex-heading-regexp)
7328 (match-beginning 4)
7329 (> p (match-beginning 4)))))))
7330 tags pos)
7331 (cond
7332 (org-insert-heading-respect-content
7333 (if (not (equal force-heading '(16)))
7334 (org-end-of-subtree nil t)
7335 (org-up-heading-safe)
7336 (org-end-of-subtree nil t))
7337 (when (featurep 'org-inlinetask)
7338 (while (and (not (eobp))
7339 (looking-at "\\(\\*+\\)[ \t]+")
7340 (>= (length (match-string 1))
7341 org-inlinetask-min-level))
7342 (org-end-of-subtree nil t)))
7343 (or (bolp) (newline))
7344 (or (org-previous-line-empty-p)
7345 (and blank (newline)))
7346 (open-line 1))
7347 ((org-at-heading-p)
7348 (when hide-previous
7349 (show-children)
7350 (org-show-entry))
7351 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7352 (setq tags (and (match-end 2) (match-string 2)))
7353 (and (match-end 1)
7354 (delete-region (match-beginning 1) (match-end 1)))
7355 (setq pos (point-at-bol))
7356 (or split (end-of-line 1))
7357 (delete-horizontal-space)
7358 (if (string-match "\\`\\*+\\'"
7359 (buffer-substring (point-at-bol) (point)))
7360 (insert " "))
7361 (newline (if blank 2 1))
7362 (when tags
7363 (save-excursion
7364 (goto-char pos)
7365 (end-of-line 1)
7366 (insert " " tags)
7367 (org-set-tags nil 'align))))
7369 (or split (end-of-line 1))
7370 (newline (if blank 2 1)))))))
7371 (insert head) (just-one-space)
7372 (setq pos (point))
7373 (end-of-line 1)
7374 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7375 (when (and org-insert-heading-respect-content hide-previous)
7376 (save-excursion
7377 (goto-char previous-pos)
7378 (hide-subtree)))
7379 (run-hooks 'org-insert-heading-hook)))))
7381 (defun org-get-heading (&optional no-tags no-todo)
7382 "Return the heading of the current entry, without the stars.
7383 When NO-TAGS is non-nil, don't include tags.
7384 When NO-TODO is non-nil, don't include TODO keywords."
7385 (save-excursion
7386 (org-back-to-heading t)
7387 (cond
7388 ((and no-tags no-todo)
7389 (looking-at org-complex-heading-regexp)
7390 (match-string 4))
7391 (no-tags
7392 (looking-at (concat org-outline-regexp
7393 "\\(.*?\\)"
7394 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7395 (match-string 1))
7396 (no-todo
7397 (looking-at org-todo-line-regexp)
7398 (match-string 3))
7399 (t (looking-at org-heading-regexp)
7400 (match-string 2)))))
7402 (defun org-heading-components ()
7403 "Return the components of the current heading.
7404 This is a list with the following elements:
7405 - the level as an integer
7406 - the reduced level, different if `org-odd-levels-only' is set.
7407 - the TODO keyword, or nil
7408 - the priority character, like ?A, or nil if no priority is given
7409 - the headline text itself, or the tags string if no headline text
7410 - the tags string, or nil."
7411 (save-excursion
7412 (org-back-to-heading t)
7413 (if (let (case-fold-search)
7414 (looking-at
7415 (if orgstruct-mode
7416 org-heading-regexp
7417 org-complex-heading-regexp)))
7418 (if orgstruct-mode
7419 (list (length (match-string 1))
7420 (org-reduced-level (length (match-string 1)))
7423 (match-string 2)
7424 nil)
7425 (list (length (match-string 1))
7426 (org-reduced-level (length (match-string 1)))
7427 (org-match-string-no-properties 2)
7428 (and (match-end 3) (aref (match-string 3) 2))
7429 (org-match-string-no-properties 4)
7430 (org-match-string-no-properties 5))))))
7432 (defun org-get-entry ()
7433 "Get the entry text, after heading, entire subtree."
7434 (save-excursion
7435 (org-back-to-heading t)
7436 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7438 (defun org-insert-heading-after-current ()
7439 "Insert a new heading with same level as current, after current subtree."
7440 (interactive)
7441 (org-back-to-heading)
7442 (org-insert-heading)
7443 (org-move-subtree-down)
7444 (end-of-line 1))
7446 (defun org-insert-heading-respect-content ()
7447 (interactive)
7448 (let ((org-insert-heading-respect-content t))
7449 (org-insert-heading t)))
7451 (defun org-insert-todo-heading-respect-content (&optional force-state)
7452 (interactive "P")
7453 (let ((org-insert-heading-respect-content t))
7454 (org-insert-todo-heading force-state t)))
7456 (defun org-insert-todo-heading (arg &optional force-heading)
7457 "Insert a new heading with the same level and TODO state as current heading.
7458 If the heading has no TODO state, or if the state is DONE, use the first
7459 state (TODO by default). Also one prefix arg, force first state. With two
7460 prefix args, force inserting at the end of the parent subtree."
7461 (interactive "P")
7462 (when (or force-heading (not (org-insert-item 'checkbox)))
7463 (org-insert-heading (or (and (equal arg '(16)) '(16))
7464 force-heading))
7465 (save-excursion
7466 (org-back-to-heading)
7467 (outline-previous-heading)
7468 (looking-at org-todo-line-regexp))
7469 (let*
7470 ((new-mark-x
7471 (if (or arg
7472 (not (match-beginning 2))
7473 (member (match-string 2) org-done-keywords))
7474 (car org-todo-keywords-1)
7475 (match-string 2)))
7476 (new-mark
7478 (run-hook-with-args-until-success
7479 'org-todo-get-default-hook new-mark-x nil)
7480 new-mark-x)))
7481 (beginning-of-line 1)
7482 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7483 (if org-treat-insert-todo-heading-as-state-change
7484 (org-todo new-mark)
7485 (insert new-mark " "))))
7486 (when org-provide-todo-statistics
7487 (org-update-parent-todo-statistics))))
7489 (defun org-insert-subheading (arg)
7490 "Insert a new subheading and demote it.
7491 Works for outline headings and for plain lists alike."
7492 (interactive "P")
7493 (org-insert-heading arg)
7494 (cond
7495 ((org-at-heading-p) (org-do-demote))
7496 ((org-at-item-p) (org-indent-item))))
7498 (defun org-insert-todo-subheading (arg)
7499 "Insert a new subheading with TODO keyword or checkbox and demote it.
7500 Works for outline headings and for plain lists alike."
7501 (interactive "P")
7502 (org-insert-todo-heading arg)
7503 (cond
7504 ((org-at-heading-p) (org-do-demote))
7505 ((org-at-item-p) (org-indent-item))))
7507 ;;; Promotion and Demotion
7509 (defvar org-after-demote-entry-hook nil
7510 "Hook run after an entry has been demoted.
7511 The cursor will be at the beginning of the entry.
7512 When a subtree is being demoted, the hook will be called for each node.")
7514 (defvar org-after-promote-entry-hook nil
7515 "Hook run after an entry has been promoted.
7516 The cursor will be at the beginning of the entry.
7517 When a subtree is being promoted, the hook will be called for each node.")
7519 (defun org-promote-subtree ()
7520 "Promote the entire subtree.
7521 See also `org-promote'."
7522 (interactive)
7523 (save-excursion
7524 (org-with-limited-levels (org-map-tree 'org-promote)))
7525 (org-fix-position-after-promote))
7527 (defun org-demote-subtree ()
7528 "Demote the entire subtree. See `org-demote'.
7529 See also `org-promote'."
7530 (interactive)
7531 (save-excursion
7532 (org-with-limited-levels (org-map-tree 'org-demote)))
7533 (org-fix-position-after-promote))
7536 (defun org-do-promote ()
7537 "Promote the current heading higher up the tree.
7538 If the region is active in `transient-mark-mode', promote all headings
7539 in the region."
7540 (interactive)
7541 (save-excursion
7542 (if (org-region-active-p)
7543 (org-map-region 'org-promote (region-beginning) (region-end))
7544 (org-promote)))
7545 (org-fix-position-after-promote))
7547 (defun org-do-demote ()
7548 "Demote the current heading lower down the tree.
7549 If the region is active in `transient-mark-mode', demote all headings
7550 in the region."
7551 (interactive)
7552 (save-excursion
7553 (if (org-region-active-p)
7554 (org-map-region 'org-demote (region-beginning) (region-end))
7555 (org-demote)))
7556 (org-fix-position-after-promote))
7558 (defun org-fix-position-after-promote ()
7559 "Make sure that after pro/demotion cursor position is right."
7560 (let ((pos (point)))
7561 (when (save-excursion
7562 (beginning-of-line 1)
7563 (looking-at org-todo-line-regexp)
7564 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7565 (cond ((eobp) (insert " "))
7566 ((eolp) (insert " "))
7567 ((equal (char-after) ?\ ) (forward-char 1))))))
7569 (defun org-current-level ()
7570 "Return the level of the current entry, or nil if before the first headline.
7571 The level is the number of stars at the beginning of the headline."
7572 (save-excursion
7573 (org-with-limited-levels
7574 (if (ignore-errors (org-back-to-heading t))
7575 (funcall outline-level)))))
7577 (defun org-get-previous-line-level ()
7578 "Return the outline depth of the last headline before the current line.
7579 Returns 0 for the first headline in the buffer, and nil if before the
7580 first headline."
7581 (let ((current-level (org-current-level))
7582 (prev-level (when (> (line-number-at-pos) 1)
7583 (save-excursion
7584 (beginning-of-line 0)
7585 (org-current-level)))))
7586 (cond ((null current-level) nil) ; Before first headline
7587 ((null prev-level) 0) ; At first headline
7588 (prev-level))))
7590 (defun org-reduced-level (l)
7591 "Compute the effective level of a heading.
7592 This takes into account the setting of `org-odd-levels-only'."
7593 (cond
7594 ((zerop l) 0)
7595 (org-odd-levels-only (1+ (floor (/ l 2))))
7596 (t l)))
7598 (defun org-level-increment ()
7599 "Return the number of stars that will be added or removed at a
7600 time to headlines when structure editing, based on the value of
7601 `org-odd-levels-only'."
7602 (if org-odd-levels-only 2 1))
7604 (defun org-get-valid-level (level &optional change)
7605 "Rectify a level change under the influence of `org-odd-levels-only'
7606 LEVEL is a current level, CHANGE is by how much the level should be
7607 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7608 even level numbers will become the next higher odd number."
7609 (if org-odd-levels-only
7610 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7611 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7612 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7613 (max 1 (+ level (or change 0)))))
7615 (if (boundp 'define-obsolete-function-alias)
7616 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7617 (define-obsolete-function-alias 'org-get-legal-level
7618 'org-get-valid-level)
7619 (define-obsolete-function-alias 'org-get-legal-level
7620 'org-get-valid-level "23.1")))
7622 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7623 ;; ̀org-with-limited-levels'
7624 (defun org-promote ()
7625 "Promote the current heading higher up the tree.
7626 If the region is active in `transient-mark-mode', promote all headings
7627 in the region."
7628 (org-back-to-heading t)
7629 (let* ((level (save-match-data (funcall outline-level)))
7630 (after-change-functions (remove 'flyspell-after-change-function
7631 after-change-functions))
7632 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7633 (diff (abs (- level (length up-head) -1))))
7634 (cond ((and (= level 1) org-called-with-limited-levels
7635 org-allow-promoting-top-level-subtree)
7636 (replace-match "# " nil t))
7637 ((= level 1)
7638 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7639 (t (replace-match up-head nil t)))
7640 ;; Fixup tag positioning
7641 (unless (= level 1)
7642 (and org-auto-align-tags (org-set-tags nil t))
7643 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7644 (run-hooks 'org-after-promote-entry-hook)))
7646 (defun org-demote ()
7647 "Demote the current heading lower down the tree.
7648 If the region is active in `transient-mark-mode', demote all headings
7649 in the region."
7650 (org-back-to-heading t)
7651 (let* ((level (save-match-data (funcall outline-level)))
7652 (after-change-functions (remove 'flyspell-after-change-function
7653 after-change-functions))
7654 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7655 (diff (abs (- level (length down-head) -1))))
7656 (replace-match down-head nil t)
7657 ;; Fixup tag positioning
7658 (and org-auto-align-tags (org-set-tags nil t))
7659 (if org-adapt-indentation (org-fixup-indentation diff))
7660 (run-hooks 'org-after-demote-entry-hook)))
7662 (defun org-cycle-level ()
7663 "Cycle the level of an empty headline through possible states.
7664 This goes first to child, then to parent, level, then up the hierarchy.
7665 After top level, it switches back to sibling level."
7666 (interactive)
7667 (let ((org-adapt-indentation nil))
7668 (when (org-point-at-end-of-empty-headline)
7669 (setq this-command 'org-cycle-level) ; Only needed for caching
7670 (let ((cur-level (org-current-level))
7671 (prev-level (org-get-previous-line-level)))
7672 (cond
7673 ;; If first headline in file, promote to top-level.
7674 ((= prev-level 0)
7675 (loop repeat (/ (- cur-level 1) (org-level-increment))
7676 do (org-do-promote)))
7677 ;; If same level as prev, demote one.
7678 ((= prev-level cur-level)
7679 (org-do-demote))
7680 ;; If parent is top-level, promote to top level if not already.
7681 ((= prev-level 1)
7682 (loop repeat (/ (- cur-level 1) (org-level-increment))
7683 do (org-do-promote)))
7684 ;; If top-level, return to prev-level.
7685 ((= cur-level 1)
7686 (loop repeat (/ (- prev-level 1) (org-level-increment))
7687 do (org-do-demote)))
7688 ;; If less than prev-level, promote one.
7689 ((< cur-level prev-level)
7690 (org-do-promote))
7691 ;; If deeper than prev-level, promote until higher than
7692 ;; prev-level.
7693 ((> cur-level prev-level)
7694 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7695 do (org-do-promote))))
7696 t))))
7698 (defun org-map-tree (fun)
7699 "Call FUN for every heading underneath the current one."
7700 (org-back-to-heading)
7701 (let ((level (funcall outline-level)))
7702 (save-excursion
7703 (funcall fun)
7704 (while (and (progn
7705 (outline-next-heading)
7706 (> (funcall outline-level) level))
7707 (not (eobp)))
7708 (funcall fun)))))
7710 (defun org-map-region (fun beg end)
7711 "Call FUN for every heading between BEG and END."
7712 (let ((org-ignore-region t))
7713 (save-excursion
7714 (setq end (copy-marker end))
7715 (goto-char beg)
7716 (if (and (re-search-forward org-outline-regexp-bol nil t)
7717 (< (point) end))
7718 (funcall fun))
7719 (while (and (progn
7720 (outline-next-heading)
7721 (< (point) end))
7722 (not (eobp)))
7723 (funcall fun)))))
7725 (defvar org-property-end-re) ; silence byte-compiler
7726 (defun org-fixup-indentation (diff)
7727 "Change the indentation in the current entry by DIFF.
7728 However, if any line in the current entry has no indentation, or if it
7729 would end up with no indentation after the change, nothing at all is done."
7730 (save-excursion
7731 (let ((end (save-excursion (outline-next-heading)
7732 (point-marker)))
7733 (prohibit (if (> diff 0)
7734 "^\\S-"
7735 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7736 col)
7737 (unless (save-excursion (end-of-line 1)
7738 (re-search-forward prohibit end t))
7739 (while (and (< (point) end)
7740 (re-search-forward "^[ \t]+" end t))
7741 (goto-char (match-end 0))
7742 (setq col (current-column))
7743 (if (< diff 0) (replace-match ""))
7744 (org-indent-to-column (+ diff col))))
7745 (move-marker end nil))))
7747 (defun org-convert-to-odd-levels ()
7748 "Convert an org-mode file with all levels allowed to one with odd levels.
7749 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7750 level 5 etc."
7751 (interactive)
7752 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7753 (let ((outline-level 'org-outline-level)
7754 (org-odd-levels-only nil) n)
7755 (save-excursion
7756 (goto-char (point-min))
7757 (while (re-search-forward "^\\*\\*+ " nil t)
7758 (setq n (- (length (match-string 0)) 2))
7759 (while (>= (setq n (1- n)) 0)
7760 (org-demote))
7761 (end-of-line 1))))))
7763 (defun org-convert-to-oddeven-levels ()
7764 "Convert an org-mode file with only odd levels to one with odd/even levels.
7765 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7766 file contains a section with an even level, conversion would
7767 destroy the structure of the file. An error is signaled in this
7768 case."
7769 (interactive)
7770 (goto-char (point-min))
7771 ;; First check if there are no even levels
7772 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7773 (org-show-context t)
7774 (error "Not all levels are odd in this file. Conversion not possible"))
7775 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7776 (let ((outline-regexp org-outline-regexp)
7777 (outline-level 'org-outline-level)
7778 (org-odd-levels-only nil) n)
7779 (save-excursion
7780 (goto-char (point-min))
7781 (while (re-search-forward "^\\*\\*+ " nil t)
7782 (setq n (/ (1- (length (match-string 0))) 2))
7783 (while (>= (setq n (1- n)) 0)
7784 (org-promote))
7785 (end-of-line 1))))))
7787 (defun org-tr-level (n)
7788 "Make N odd if required."
7789 (if org-odd-levels-only (1+ (/ n 2)) n))
7791 ;;; Vertical tree motion, cutting and pasting of subtrees
7793 (defun org-move-subtree-up (&optional arg)
7794 "Move the current subtree up past ARG headlines of the same level."
7795 (interactive "p")
7796 (org-move-subtree-down (- (prefix-numeric-value arg))))
7798 (defun org-move-subtree-down (&optional arg)
7799 "Move the current subtree down past ARG headlines of the same level."
7800 (interactive "p")
7801 (setq arg (prefix-numeric-value arg))
7802 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7803 'org-get-last-sibling))
7804 (ins-point (make-marker))
7805 (cnt (abs arg))
7806 (col (current-column))
7807 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7808 ;; Select the tree
7809 (org-back-to-heading)
7810 (setq beg0 (point))
7811 (save-excursion
7812 (setq ne-beg (org-back-over-empty-lines))
7813 (setq beg (point)))
7814 (save-match-data
7815 (save-excursion (outline-end-of-heading)
7816 (setq folded (outline-invisible-p)))
7817 (outline-end-of-subtree))
7818 (outline-next-heading)
7819 (setq ne-end (org-back-over-empty-lines))
7820 (setq end (point))
7821 (goto-char beg0)
7822 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7823 ;; include less whitespace
7824 (save-excursion
7825 (goto-char beg)
7826 (forward-line (- ne-beg ne-end))
7827 (setq beg (point))))
7828 ;; Find insertion point, with error handling
7829 (while (> cnt 0)
7830 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7831 (progn (goto-char beg0)
7832 (error "Cannot move past superior level or buffer limit")))
7833 (setq cnt (1- cnt)))
7834 (if (> arg 0)
7835 ;; Moving forward - still need to move over subtree
7836 (progn (org-end-of-subtree t t)
7837 (save-excursion
7838 (org-back-over-empty-lines)
7839 (or (bolp) (newline)))))
7840 (setq ne-ins (org-back-over-empty-lines))
7841 (move-marker ins-point (point))
7842 (setq txt (buffer-substring beg end))
7843 (org-save-markers-in-region beg end)
7844 (delete-region beg end)
7845 (org-remove-empty-overlays-at beg)
7846 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7847 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7848 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7849 (let ((bbb (point)))
7850 (insert-before-markers txt)
7851 (org-reinstall-markers-in-region bbb)
7852 (move-marker ins-point bbb))
7853 (or (bolp) (insert "\n"))
7854 (setq ins-end (point))
7855 (goto-char ins-point)
7856 (org-skip-whitespace)
7857 (when (and (< arg 0)
7858 (org-first-sibling-p)
7859 (> ne-ins ne-beg))
7860 ;; Move whitespace back to beginning
7861 (save-excursion
7862 (goto-char ins-end)
7863 (let ((kill-whole-line t))
7864 (kill-line (- ne-ins ne-beg)) (point)))
7865 (insert (make-string (- ne-ins ne-beg) ?\n)))
7866 (move-marker ins-point nil)
7867 (if folded
7868 (hide-subtree)
7869 (org-show-entry)
7870 (show-children)
7871 (org-cycle-hide-drawers 'children))
7872 (org-clean-visibility-after-subtree-move)
7873 ;; move back to the initial column we were at
7874 (move-to-column col)))
7876 (defvar org-subtree-clip ""
7877 "Clipboard for cut and paste of subtrees.
7878 This is actually only a copy of the kill, because we use the normal kill
7879 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7881 (defvar org-subtree-clip-folded nil
7882 "Was the last copied subtree folded?
7883 This is used to fold the tree back after pasting.")
7885 (defun org-cut-subtree (&optional n)
7886 "Cut the current subtree into the clipboard.
7887 With prefix arg N, cut this many sequential subtrees.
7888 This is a short-hand for marking the subtree and then cutting it."
7889 (interactive "p")
7890 (org-copy-subtree n 'cut))
7892 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7893 "Cut the current subtree into the clipboard.
7894 With prefix arg N, cut this many sequential subtrees.
7895 This is a short-hand for marking the subtree and then copying it.
7896 If CUT is non-nil, actually cut the subtree.
7897 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7898 of some markers in the region, even if CUT is non-nil. This is
7899 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7900 (interactive "p")
7901 (let (beg end folded (beg0 (point)))
7902 (if (org-called-interactively-p 'any)
7903 (org-back-to-heading nil) ; take what looks like a subtree
7904 (org-back-to-heading t)) ; take what is really there
7905 (setq beg (point))
7906 (skip-chars-forward " \t\r\n")
7907 (save-match-data
7908 (if nosubtrees
7909 (outline-next-heading)
7910 (save-excursion (outline-end-of-heading)
7911 (setq folded (outline-invisible-p)))
7912 (condition-case nil
7913 (org-forward-heading-same-level (1- n) t)
7914 (error nil))
7915 (org-end-of-subtree t t)))
7916 (setq end (point))
7917 (goto-char beg0)
7918 (when (> end beg)
7919 (setq org-subtree-clip-folded folded)
7920 (when (or cut force-store-markers)
7921 (org-save-markers-in-region beg end))
7922 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7923 (setq org-subtree-clip (current-kill 0))
7924 (message "%s: Subtree(s) with %d characters"
7925 (if cut "Cut" "Copied")
7926 (length org-subtree-clip)))))
7928 (defun org-paste-subtree (&optional level tree for-yank)
7929 "Paste the clipboard as a subtree, with modification of headline level.
7930 The entire subtree is promoted or demoted in order to match a new headline
7931 level.
7933 If the cursor is at the beginning of a headline, the same level as
7934 that headline is used to paste the tree.
7936 If not, the new level is derived from the *visible* headings
7937 before and after the insertion point, and taken to be the inferior headline
7938 level of the two. So if the previous visible heading is level 3 and the
7939 next is level 4 (or vice versa), level 4 will be used for insertion.
7940 This makes sure that the subtree remains an independent subtree and does
7941 not swallow low level entries.
7943 You can also force a different level, either by using a numeric prefix
7944 argument, or by inserting the heading marker by hand. For example, if the
7945 cursor is after \"*****\", then the tree will be shifted to level 5.
7947 If optional TREE is given, use this text instead of the kill ring.
7949 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7950 move back over whitespace before inserting, and move point to the end of
7951 the inserted text when done."
7952 (interactive "P")
7953 (setq tree (or tree (and kill-ring (current-kill 0))))
7954 (unless (org-kill-is-subtree-p tree)
7955 (error "%s"
7956 (substitute-command-keys
7957 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7958 (org-with-limited-levels
7959 (let* ((visp (not (outline-invisible-p)))
7960 (txt tree)
7961 (^re_ "\\(\\*+\\)[ \t]*")
7962 (old-level (if (string-match org-outline-regexp-bol txt)
7963 (- (match-end 0) (match-beginning 0) 1)
7964 -1))
7965 (force-level (cond (level (prefix-numeric-value level))
7966 ((and (looking-at "[ \t]*$")
7967 (string-match
7968 "^\\*+$" (buffer-substring
7969 (point-at-bol) (point))))
7970 (- (match-end 1) (match-beginning 1)))
7971 ((and (bolp)
7972 (looking-at org-outline-regexp))
7973 (- (match-end 0) (point) 1))))
7974 (previous-level (save-excursion
7975 (condition-case nil
7976 (progn
7977 (outline-previous-visible-heading 1)
7978 (if (looking-at ^re_)
7979 (- (match-end 0) (match-beginning 0) 1)
7981 (error 1))))
7982 (next-level (save-excursion
7983 (condition-case nil
7984 (progn
7985 (or (looking-at org-outline-regexp)
7986 (outline-next-visible-heading 1))
7987 (if (looking-at ^re_)
7988 (- (match-end 0) (match-beginning 0) 1)
7990 (error 1))))
7991 (new-level (or force-level (max previous-level next-level)))
7992 (shift (if (or (= old-level -1)
7993 (= new-level -1)
7994 (= old-level new-level))
7996 (- new-level old-level)))
7997 (delta (if (> shift 0) -1 1))
7998 (func (if (> shift 0) 'org-demote 'org-promote))
7999 (org-odd-levels-only nil)
8000 beg end newend)
8001 ;; Remove the forced level indicator
8002 (if force-level
8003 (delete-region (point-at-bol) (point)))
8004 ;; Paste
8005 (beginning-of-line (if (bolp) 1 2))
8006 (setq beg (point))
8007 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8008 (insert-before-markers txt)
8009 (unless (string-match "\n\\'" txt) (insert "\n"))
8010 (setq newend (point))
8011 (org-reinstall-markers-in-region beg)
8012 (setq end (point))
8013 (goto-char beg)
8014 (skip-chars-forward " \t\n\r")
8015 (setq beg (point))
8016 (if (and (outline-invisible-p) visp)
8017 (save-excursion (outline-show-heading)))
8018 ;; Shift if necessary
8019 (unless (= shift 0)
8020 (save-restriction
8021 (narrow-to-region beg end)
8022 (while (not (= shift 0))
8023 (org-map-region func (point-min) (point-max))
8024 (setq shift (+ delta shift)))
8025 (goto-char (point-min))
8026 (setq newend (point-max))))
8027 (when (or (org-called-interactively-p 'interactive) for-yank)
8028 (message "Clipboard pasted as level %d subtree" new-level))
8029 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8030 kill-ring
8031 (eq org-subtree-clip (current-kill 0))
8032 org-subtree-clip-folded)
8033 ;; The tree was folded before it was killed/copied
8034 (hide-subtree))
8035 (and for-yank (goto-char newend)))))
8037 (defun org-kill-is-subtree-p (&optional txt)
8038 "Check if the current kill is an outline subtree, or a set of trees.
8039 Returns nil if kill does not start with a headline, or if the first
8040 headline level is not the largest headline level in the tree.
8041 So this will actually accept several entries of equal levels as well,
8042 which is OK for `org-paste-subtree'.
8043 If optional TXT is given, check this string instead of the current kill."
8044 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8045 (re (org-get-limited-outline-regexp))
8046 (^re (concat "^" re))
8047 (start-level (and kill
8048 (string-match
8049 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8050 kill)
8051 (- (match-end 2) (match-beginning 2) 1)))
8052 (start (1+ (or (match-beginning 2) -1))))
8053 (if (not start-level)
8054 (progn
8055 nil) ;; does not even start with a heading
8056 (catch 'exit
8057 (while (setq start (string-match ^re kill (1+ start)))
8058 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8059 (throw 'exit nil)))
8060 t))))
8062 (defvar org-markers-to-move nil
8063 "Markers that should be moved with a cut-and-paste operation.
8064 Those markers are stored together with their positions relative to
8065 the start of the region.")
8067 (defun org-save-markers-in-region (beg end)
8068 "Check markers in region.
8069 If these markers are between BEG and END, record their position relative
8070 to BEG, so that after moving the block of text, we can put the markers back
8071 into place.
8072 This function gets called just before an entry or tree gets cut from the
8073 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8074 called immediately, to move the markers with the entries."
8075 (setq org-markers-to-move nil)
8076 (when (featurep 'org-clock)
8077 (org-clock-save-markers-for-cut-and-paste beg end))
8078 (when (featurep 'org-agenda)
8079 (org-agenda-save-markers-for-cut-and-paste beg end)))
8081 (defun org-check-and-save-marker (marker beg end)
8082 "Check if MARKER is between BEG and END.
8083 If yes, remember the marker and the distance to BEG."
8084 (when (and (marker-buffer marker)
8085 (equal (marker-buffer marker) (current-buffer)))
8086 (if (and (>= marker beg) (< marker end))
8087 (push (cons marker (- marker beg)) org-markers-to-move))))
8089 (defun org-reinstall-markers-in-region (beg)
8090 "Move all remembered markers to their position relative to BEG."
8091 (mapc (lambda (x)
8092 (move-marker (car x) (+ beg (cdr x))))
8093 org-markers-to-move)
8094 (setq org-markers-to-move nil))
8096 (defun org-narrow-to-subtree ()
8097 "Narrow buffer to the current subtree."
8098 (interactive)
8099 (save-excursion
8100 (save-match-data
8101 (org-with-limited-levels
8102 (narrow-to-region
8103 (progn (org-back-to-heading t) (point))
8104 (progn (org-end-of-subtree t t)
8105 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8106 (point)))))))
8108 (defun org-narrow-to-block ()
8109 "Narrow buffer to the current block."
8110 (interactive)
8111 (let* ((case-fold-search t)
8112 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8113 "^[ \t]*#\\+end_.*")))
8114 (if blockp
8115 (narrow-to-region (car blockp) (cdr blockp))
8116 (error "Not in a block"))))
8118 (eval-when-compile
8119 (defvar org-property-drawer-re))
8121 (defvar org-property-start-re) ;; defined below
8122 (defun org-clone-subtree-with-time-shift (n &optional shift)
8123 "Clone the task (subtree) at point N times.
8124 The clones will be inserted as siblings.
8126 In interactive use, the user will be prompted for the number of
8127 clones to be produced, and for a time SHIFT, which may be a
8128 repeater as used in time stamps, for example `+3d'.
8130 When a valid repeater is given and the entry contains any time
8131 stamps, the clones will become a sequence in time, with time
8132 stamps in the subtree shifted for each clone produced. If SHIFT
8133 is nil or the empty string, time stamps will be left alone. The
8134 ID property of the original subtree is removed.
8136 If the original subtree did contain time stamps with a repeater,
8137 the following will happen:
8138 - the repeater will be removed in each clone
8139 - an additional clone will be produced, with the current, unshifted
8140 date(s) in the entry.
8141 - the original entry will be placed *after* all the clones, with
8142 repeater intact.
8143 - the start days in the repeater in the original entry will be shifted
8144 to past the last clone.
8145 In this way you can spell out a number of instances of a repeating task,
8146 and still retain the repeater to cover future instances of the task."
8147 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8148 (let (beg end template task idprop
8149 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8150 (drawer-re org-drawer-regexp))
8151 (if (not (and (integerp n) (> n 0)))
8152 (error "Invalid number of replications %s" n))
8153 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8154 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8155 shift)))
8156 (error "Invalid shift specification %s" shift))
8157 (when doshift
8158 (setq shift-n (string-to-number (match-string 1 shift))
8159 shift-what (cdr (assoc (match-string 2 shift)
8160 '(("d" . day) ("w" . week)
8161 ("m" . month) ("y" . year))))))
8162 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8163 (setq nmin 1 nmax n)
8164 (org-back-to-heading t)
8165 (setq beg (point))
8166 (setq idprop (org-entry-get nil "ID"))
8167 (org-end-of-subtree t t)
8168 (or (bolp) (insert "\n"))
8169 (setq end (point))
8170 (setq template (buffer-substring beg end))
8171 (when (and doshift
8172 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8173 (delete-region beg end)
8174 (setq end beg)
8175 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8176 (goto-char end)
8177 (loop for n from nmin to nmax do
8178 ;; prepare clone
8179 (with-temp-buffer
8180 (insert template)
8181 (org-mode)
8182 (goto-char (point-min))
8183 (org-show-subtree)
8184 (and idprop (if org-clone-delete-id
8185 (org-entry-delete nil "ID")
8186 (org-id-get-create t)))
8187 (unless (= n 0)
8188 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8189 (kill-whole-line))
8190 (goto-char (point-min))
8191 (while (re-search-forward drawer-re nil t)
8192 (mapc (lambda (d)
8193 (org-remove-empty-drawer-at d (point))) org-drawers)))
8194 (goto-char (point-min))
8195 (when doshift
8196 (while (re-search-forward org-ts-regexp-both nil t)
8197 (org-timestamp-change (* n shift-n) shift-what))
8198 (unless (= n n-no-remove)
8199 (goto-char (point-min))
8200 (while (re-search-forward org-ts-regexp nil t)
8201 (save-excursion
8202 (goto-char (match-beginning 0))
8203 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8204 (delete-region (match-beginning 1) (match-end 1)))))))
8205 (setq task (buffer-string)))
8206 (insert task))
8207 (goto-char beg)))
8209 ;;; Outline Sorting
8211 (defun org-sort (with-case)
8212 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8213 Optional argument WITH-CASE means sort case-sensitively."
8214 (interactive "P")
8215 (cond
8216 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8217 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8219 (org-call-with-arg 'org-sort-entries with-case))))
8221 (defun org-sort-remove-invisible (s)
8222 (remove-text-properties 0 (length s) org-rm-props s)
8223 (while (string-match org-bracket-link-regexp s)
8224 (setq s (replace-match (if (match-end 2)
8225 (match-string 3 s)
8226 (match-string 1 s)) t t s)))
8229 (defvar org-priority-regexp) ; defined later in the file
8231 (defvar org-after-sorting-entries-or-items-hook nil
8232 "Hook that is run after a bunch of entries or items have been sorted.
8233 When children are sorted, the cursor is in the parent line when this
8234 hook gets called. When a region or a plain list is sorted, the cursor
8235 will be in the first entry of the sorted region/list.")
8237 (defun org-sort-entries
8238 (&optional with-case sorting-type getkey-func compare-func property)
8239 "Sort entries on a certain level of an outline tree.
8240 If there is an active region, the entries in the region are sorted.
8241 Else, if the cursor is before the first entry, sort the top-level items.
8242 Else, the children of the entry at point are sorted.
8244 Sorting can be alphabetically, numerically, by date/time as given by
8245 a time stamp, by a property or by priority.
8247 The command prompts for the sorting type unless it has been given to the
8248 function through the SORTING-TYPE argument, which needs to be a character,
8249 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8250 precise meaning of each character:
8252 n Numerically, by converting the beginning of the entry/item to a number.
8253 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8254 o By order of TODO keywords.
8255 t By date/time, either the first active time stamp in the entry, or, if
8256 none exist, by the first inactive one.
8257 s By the scheduled date/time.
8258 d By deadline date/time.
8259 c By creation time, which is assumed to be the first inactive time stamp
8260 at the beginning of a line.
8261 p By priority according to the cookie.
8262 r By the value of a property.
8264 Capital letters will reverse the sort order.
8266 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8267 called with point at the beginning of the record. It must return either
8268 a string or a number that should serve as the sorting key for that record.
8270 Comparing entries ignores case by default. However, with an optional argument
8271 WITH-CASE, the sorting considers case as well."
8272 (interactive "P")
8273 (let ((case-func (if with-case 'identity 'downcase))
8274 (cmstr
8275 ;; The clock marker is lost when using `sort-subr', let's
8276 ;; store the clocking string.
8277 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8278 (save-excursion
8279 (goto-char org-clock-marker)
8280 (looking-back "^.*") (match-string-no-properties 0))))
8281 start beg end stars re re2
8282 txt what tmp)
8283 ;; Find beginning and end of region to sort
8284 (cond
8285 ((org-region-active-p)
8286 ;; we will sort the region
8287 (setq end (region-end)
8288 what "region")
8289 (goto-char (region-beginning))
8290 (if (not (org-at-heading-p)) (outline-next-heading))
8291 (setq start (point)))
8292 ((or (org-at-heading-p)
8293 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8294 ;; we will sort the children of the current headline
8295 (org-back-to-heading)
8296 (setq start (point)
8297 end (progn (org-end-of-subtree t t)
8298 (or (bolp) (insert "\n"))
8299 (org-back-over-empty-lines)
8300 (point))
8301 what "children")
8302 (goto-char start)
8303 (show-subtree)
8304 (outline-next-heading))
8306 ;; we will sort the top-level entries in this file
8307 (goto-char (point-min))
8308 (or (org-at-heading-p) (outline-next-heading))
8309 (setq start (point))
8310 (goto-char (point-max))
8311 (beginning-of-line 1)
8312 (when (looking-at ".*?\\S-")
8313 ;; File ends in a non-white line
8314 (end-of-line 1)
8315 (insert "\n"))
8316 (setq end (point-max))
8317 (setq what "top-level")
8318 (goto-char start)
8319 (show-all)))
8321 (setq beg (point))
8322 (if (>= beg end) (error "Nothing to sort"))
8324 (looking-at "\\(\\*+\\)")
8325 (setq stars (match-string 1)
8326 re (concat "^" (regexp-quote stars) " +")
8327 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8328 txt (buffer-substring beg end))
8329 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8330 (if (and (not (equal stars "*")) (string-match re2 txt))
8331 (error "Region to sort contains a level above the first entry"))
8333 (unless sorting-type
8334 (message
8335 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8336 [t]ime [s]cheduled [d]eadline [c]reated
8337 A/N/P/R/O/F/T/S/D/C means reversed:"
8338 what)
8339 (setq sorting-type (read-char-exclusive))
8341 (unless getkey-func
8342 (and (= (downcase sorting-type) ?f)
8343 (setq getkey-func
8344 (org-icompleting-read "Sort using function: "
8345 obarray 'fboundp t nil nil))
8346 (setq getkey-func (intern getkey-func))))
8348 (and (= (downcase sorting-type) ?r)
8349 (not property)
8350 (setq property
8351 (org-icompleting-read "Property: "
8352 (mapcar 'list (org-buffer-property-keys t))
8353 nil t))))
8355 (message "Sorting entries...")
8357 (save-restriction
8358 (narrow-to-region start end)
8359 (let ((dcst (downcase sorting-type))
8360 (case-fold-search nil)
8361 (now (current-time)))
8362 (sort-subr
8363 (/= dcst sorting-type)
8364 ;; This function moves to the beginning character of the "record" to
8365 ;; be sorted.
8366 (lambda nil
8367 (if (re-search-forward re nil t)
8368 (goto-char (match-beginning 0))
8369 (goto-char (point-max))))
8370 ;; This function moves to the last character of the "record" being
8371 ;; sorted.
8372 (lambda nil
8373 (save-match-data
8374 (condition-case nil
8375 (outline-forward-same-level 1)
8376 (error
8377 (goto-char (point-max))))))
8378 ;; This function returns the value that gets sorted against.
8379 (lambda nil
8380 (cond
8381 ((= dcst ?n)
8382 (if (looking-at org-complex-heading-regexp)
8383 (string-to-number (match-string 4))
8384 nil))
8385 ((= dcst ?a)
8386 (if (looking-at org-complex-heading-regexp)
8387 (funcall case-func (match-string 4))
8388 nil))
8389 ((= dcst ?t)
8390 (let ((end (save-excursion (outline-next-heading) (point))))
8391 (if (or (re-search-forward org-ts-regexp end t)
8392 (re-search-forward org-ts-regexp-both end t))
8393 (org-time-string-to-seconds (match-string 0))
8394 (org-float-time now))))
8395 ((= dcst ?c)
8396 (let ((end (save-excursion (outline-next-heading) (point))))
8397 (if (re-search-forward
8398 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8399 end t)
8400 (org-time-string-to-seconds (match-string 0))
8401 (org-float-time now))))
8402 ((= dcst ?s)
8403 (let ((end (save-excursion (outline-next-heading) (point))))
8404 (if (re-search-forward org-scheduled-time-regexp end t)
8405 (org-time-string-to-seconds (match-string 1))
8406 (org-float-time now))))
8407 ((= dcst ?d)
8408 (let ((end (save-excursion (outline-next-heading) (point))))
8409 (if (re-search-forward org-deadline-time-regexp end t)
8410 (org-time-string-to-seconds (match-string 1))
8411 (org-float-time now))))
8412 ((= dcst ?p)
8413 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8414 (string-to-char (match-string 2))
8415 org-default-priority))
8416 ((= dcst ?r)
8417 (or (org-entry-get nil property) ""))
8418 ((= dcst ?o)
8419 (if (looking-at org-complex-heading-regexp)
8420 (- 9999 (length (member (match-string 2)
8421 org-todo-keywords-1)))))
8422 ((= dcst ?f)
8423 (if getkey-func
8424 (progn
8425 (setq tmp (funcall getkey-func))
8426 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8427 tmp)
8428 (error "Invalid key function `%s'" getkey-func)))
8429 (t (error "Invalid sorting type `%c'" sorting-type))))
8431 (cond
8432 ((= dcst ?a) 'string<)
8433 ((= dcst ?f) compare-func)
8434 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8435 (run-hooks 'org-after-sorting-entries-or-items-hook)
8436 ;; Reset the clock marker if needed
8437 (when cmstr
8438 (save-excursion
8439 (goto-char start)
8440 (search-forward cmstr nil t)
8441 (move-marker org-clock-marker (point))))
8442 (message "Sorting entries...done")))
8444 (defun org-do-sort (table what &optional with-case sorting-type)
8445 "Sort TABLE of WHAT according to SORTING-TYPE.
8446 The user will be prompted for the SORTING-TYPE if the call to this
8447 function does not specify it. WHAT is only for the prompt, to indicate
8448 what is being sorted. The sorting key will be extracted from
8449 the car of the elements of the table.
8450 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8451 (unless sorting-type
8452 (message
8453 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8454 what)
8455 (setq sorting-type (read-char-exclusive)))
8456 (let ((dcst (downcase sorting-type))
8457 extractfun comparefun)
8458 ;; Define the appropriate functions
8459 (cond
8460 ((= dcst ?n)
8461 (setq extractfun 'string-to-number
8462 comparefun (if (= dcst sorting-type) '< '>)))
8463 ((= dcst ?a)
8464 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8465 (lambda(x) (downcase (org-sort-remove-invisible x))))
8466 comparefun (if (= dcst sorting-type)
8467 'string<
8468 (lambda (a b) (and (not (string< a b))
8469 (not (string= a b)))))))
8470 ((= dcst ?t)
8471 (setq extractfun
8472 (lambda (x)
8473 (if (or (string-match org-ts-regexp x)
8474 (string-match org-ts-regexp-both x))
8475 (org-float-time
8476 (org-time-string-to-time (match-string 0 x)))
8478 comparefun (if (= dcst sorting-type) '< '>)))
8479 (t (error "Invalid sorting type `%c'" sorting-type)))
8481 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8482 table)
8483 (lambda (a b) (funcall comparefun (car a) (car b))))))
8486 ;;; The orgstruct minor mode
8488 ;; Define a minor mode which can be used in other modes in order to
8489 ;; integrate the org-mode structure editing commands.
8491 ;; This is really a hack, because the org-mode structure commands use
8492 ;; keys which normally belong to the major mode. Here is how it
8493 ;; works: The minor mode defines all the keys necessary to operate the
8494 ;; structure commands, but wraps the commands into a function which
8495 ;; tests if the cursor is currently at a headline or a plain list
8496 ;; item. If that is the case, the structure command is used,
8497 ;; temporarily setting many Org-mode variables like regular
8498 ;; expressions for filling etc. However, when any of those keys is
8499 ;; used at a different location, function uses `key-binding' to look
8500 ;; up if the key has an associated command in another currently active
8501 ;; keymap (minor modes, major mode, global), and executes that
8502 ;; command. There might be problems if any of the keys is otherwise
8503 ;; used as a prefix key.
8505 (defcustom orgstruct-heading-prefix-regexp ""
8506 "Regexp that matches the custom prefix of Org headlines in
8507 orgstruct(++)-mode."
8508 :group 'org
8509 :type 'string)
8510 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8512 (defcustom orgstruct-setup-hook nil
8513 "Hook run after orgstruct-mode-map is filled."
8514 :group 'org
8515 :type 'hook)
8517 (defvar orgstruct-initialized nil)
8519 (defvar org-local-vars nil
8520 "List of local variables, for use by `orgstruct-mode'.")
8522 ;;;###autoload
8523 (define-minor-mode orgstruct-mode
8524 "Toggle the minor mode `orgstruct-mode'.
8525 This mode is for using Org-mode structure commands in other
8526 modes. The following keys behave as if Org-mode were active, if
8527 the cursor is on a headline, or on a plain list item (both as
8528 defined by Org-mode)."
8529 nil " OrgStruct" (make-sparse-keymap)
8530 (when orgstruct-mode
8531 (org-load-modules-maybe)
8532 (unless orgstruct-initialized
8533 (orgstruct-setup)
8534 (setq orgstruct-initialized t))))
8536 ;;;###autoload
8537 (defun turn-on-orgstruct ()
8538 "Unconditionally turn on `orgstruct-mode'."
8539 (orgstruct-mode 1))
8541 (defvar org-fb-vars nil)
8542 (make-variable-buffer-local 'org-fb-vars)
8543 (defun orgstruct++-mode (&optional arg)
8544 "Toggle `orgstruct-mode', the enhanced version of it.
8545 In addition to setting orgstruct-mode, this also exports all
8546 indentation and autofilling variables from org-mode into the
8547 buffer. It will also recognize item context in multiline items."
8548 (interactive "P")
8549 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8550 (if (< arg 1)
8551 (progn (orgstruct-mode -1)
8552 (mapc (lambda(v)
8553 (org-set-local (car v)
8554 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8555 org-fb-vars))
8556 (orgstruct-mode 1)
8557 (setq org-fb-vars nil)
8558 (let (var val)
8559 (mapc
8560 (lambda (x)
8561 (when (string-match
8562 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8563 (symbol-name (car x)))
8564 (setq var (car x) val (nth 1 x))
8565 (push (list var `(quote ,(eval var))) org-fb-vars)
8566 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8567 org-local-vars)
8568 (org-set-local 'orgstruct-is-++ t))))
8570 (defvar orgstruct-is-++ nil
8571 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8572 (make-variable-buffer-local 'orgstruct-is-++)
8574 ;;;###autoload
8575 (defun turn-on-orgstruct++ ()
8576 "Unconditionally turn on `orgstruct++-mode'."
8577 (orgstruct++-mode 1))
8579 (defun orgstruct-error ()
8580 "Error when there is no default binding for a structure key."
8581 (interactive)
8582 (error "This key has no function outside structure elements"))
8584 (defun orgstruct-setup ()
8585 "Setup orgstruct keymap."
8586 (dolist (f
8587 '("org-meta"
8588 "org-shiftmeta"
8589 org-shifttab
8590 org-backward-element
8591 org-backward-heading-same-level
8592 org-ctrl-c-ret
8593 org-cycle
8594 org-forward-heading-same-level
8595 org-insert-heading
8596 org-insert-heading-respect-content
8597 org-kill-note-or-show-branches
8598 org-mark-subtree
8599 org-narrow-to-subtree
8600 org-promote-subtree
8601 org-reveal
8602 org-show-subtree
8603 org-sort
8604 org-up-element
8605 outline-demote
8606 outline-next-visible-heading
8607 outline-previous-visible-heading
8608 outline-promote
8609 outline-up-heading
8610 show-children))
8611 (dolist (f (if (stringp f)
8612 (let ((flist))
8613 (dolist (postfix
8614 '("-return" "tab" "left" "right" "up" "down")
8615 flist)
8616 (let ((f (intern (concat f postfix))))
8617 (when (fboundp f)
8618 (push f flist)))))
8619 (list f)))
8620 (dolist (binding (nconc (where-is-internal f org-mode-map)
8621 (where-is-internal f outline-mode-map)))
8622 ;; TODO use local-function-key-map
8623 (dolist (rep '(("<tab>" . "TAB")
8624 ("<ret>" . "RET")
8625 ("<esc>" . "ESC")
8626 ("<del>" . "DEL")))
8627 (setq binding (read-kbd-macro (replace-regexp-in-string
8628 (regexp-quote (car rep))
8629 (cdr rep)
8630 (key-description binding)))))
8631 (let ((key (lookup-key orgstruct-mode-map binding)))
8632 (when (or (not key) (numberp key))
8633 (org-defkey orgstruct-mode-map
8634 binding
8635 (orgstruct-make-binding f binding)))))))
8636 (run-hooks 'orgstruct-setup-hook))
8638 (defun orgstruct-make-binding (fun key)
8639 "Create a function for binding in the structure minor mode.
8640 FUN is the command to call inside a table. KEY is the key that
8641 should be checked in for a command to execute outside of tables."
8642 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8643 (let ((nname name)
8644 (i 0))
8645 (while (fboundp (intern nname))
8646 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8647 (setq name (intern nname)))
8648 (eval
8649 `(defun ,name (arg)
8650 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8651 "Outside of structure, run the binding of `"
8652 (key-description key) "'.")
8653 (interactive "p")
8654 (unless
8655 (let* ((org-heading-regexp
8656 (concat "^"
8657 orgstruct-heading-prefix-regexp
8658 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8659 (org-outline-regexp
8660 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8661 (org-outline-regexp-bol
8662 (concat "^" org-outline-regexp))
8663 (outline-regexp org-outline-regexp)
8664 (outline-heading-end-regexp "\n")
8665 (outline-level 'outline-level)
8666 (outline-heading-alist))
8667 (when (org-context-p 'headline 'item
8668 ,(when (memq fun '(org-insert-heading))
8669 '(when orgstruct-is-++
8670 'item-body)))
8671 (org-run-like-in-org-mode ',fun)
8673 (let ((binding (let ((orgstruct-mode)) (key-binding ,key))))
8674 (if (keymapp binding)
8675 (set-temporary-overlay-map binding)
8676 (call-interactively
8677 (or binding 'orgstruct-error)))))))
8678 name))
8680 (defun org-contextualize-keys (alist contexts)
8681 "Return valid elements in ALIST depending on CONTEXTS.
8683 `org-agenda-custom-commands' or `org-capture-templates' are the
8684 values used for ALIST, and `org-agenda-custom-commands-contexts'
8685 or `org-capture-templates-contexts' are the associated contexts
8686 definitions."
8687 (let ((contexts
8688 ;; normalize contexts
8689 (mapcar
8690 (lambda(c) (cond ((listp (cadr c))
8691 (list (car c) (car c) (cadr c)))
8692 ((string= "" (cadr c))
8693 (list (car c) (car c) (caddr c)))
8694 (t c))) contexts))
8695 (a alist) c r s)
8696 ;; loop over all commands or templates
8697 (while (setq c (pop a))
8698 (let (vrules repl)
8699 (cond
8700 ((not (assoc (car c) contexts))
8701 (push c r))
8702 ((and (assoc (car c) contexts)
8703 (setq vrules (org-contextualize-validate-key
8704 (car c) contexts)))
8705 (mapc (lambda (vr)
8706 (when (not (equal (car vr) (cadr vr)))
8707 (setq repl vr))) vrules)
8708 (if (not repl) (push c r)
8709 (push (cadr repl) s)
8710 (push
8711 (cons (car c)
8712 (cdr (or (assoc (cadr repl) alist)
8713 (error "Undefined key `%s' as contextual replacement for `%s'"
8714 (cadr repl) (car c)))))
8715 r))))))
8716 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8717 (delq
8719 (delete-dups
8720 (mapcar (lambda (x)
8721 (let ((tpl (car x)))
8722 (when (not (delq
8724 (mapcar (lambda(y)
8725 (equal y tpl)) s))) x)))
8726 (reverse r))))))
8728 (defun org-contextualize-validate-key (key contexts)
8729 "Check CONTEXTS for agenda or capture KEY."
8730 (let (r rr res)
8731 (while (setq r (pop contexts))
8732 (mapc
8733 (lambda (rr)
8734 (when
8735 (and (equal key (car r))
8736 (if (functionp rr) (funcall rr)
8737 (or (and (eq (car rr) 'in-file)
8738 (buffer-file-name)
8739 (string-match (cdr rr) (buffer-file-name)))
8740 (and (eq (car rr) 'in-mode)
8741 (string-match (cdr rr) (symbol-name major-mode)))
8742 (and (eq (car rr) 'in-buffer)
8743 (string-match (cdr rr) (buffer-name)))
8744 (when (and (eq (car rr) 'not-in-file)
8745 (buffer-file-name))
8746 (not (string-match (cdr rr) (buffer-file-name))))
8747 (when (eq (car rr) 'not-in-mode)
8748 (not (string-match (cdr rr) (symbol-name major-mode))))
8749 (when (eq (car rr) 'not-in-buffer)
8750 (not (string-match (cdr rr) (buffer-name)))))))
8751 (push r res)))
8752 (car (last r))))
8753 (delete-dups (delq nil res))))
8755 (defun org-context-p (&rest contexts)
8756 "Check if local context is any of CONTEXTS.
8757 Possible values in the list of contexts are `table', `headline', and `item'."
8758 (let ((pos (point)))
8759 (goto-char (point-at-bol))
8760 (prog1 (or (and (memq 'table contexts)
8761 (looking-at "[ \t]*|"))
8762 (and (memq 'headline contexts)
8763 (looking-at org-outline-regexp))
8764 (and (memq 'item contexts)
8765 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8766 (and (memq 'item-body contexts)
8767 (org-in-item-p)))
8768 (goto-char pos))))
8770 (defun org-get-local-variables ()
8771 "Return a list of all local variables in an Org mode buffer."
8772 (let (varlist)
8773 (with-current-buffer (get-buffer-create "*Org tmp*")
8774 (erase-buffer)
8775 (org-mode)
8776 (setq varlist (buffer-local-variables)))
8777 (kill-buffer "*Org tmp*")
8778 (delq nil
8779 (mapcar
8780 (lambda (x)
8781 (setq x
8782 (if (symbolp x)
8783 (list x)
8784 (list (car x) (cdr x))))
8785 (if (and (not (get (car x) 'org-state))
8786 (string-match
8787 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8788 (symbol-name (car x))))
8789 x nil))
8790 varlist))))
8792 (defun org-clone-local-variables (from-buffer &optional regexp)
8793 "Clone local variables from FROM-BUFFER.
8794 Optional argument REGEXP selects variables to clone."
8795 (mapc
8796 (lambda (pair)
8797 (and (symbolp (car pair))
8798 (or (null regexp)
8799 (string-match regexp (symbol-name (car pair))))
8800 (set (make-local-variable (car pair))
8801 (cdr pair))))
8802 (buffer-local-variables from-buffer)))
8804 ;;;###autoload
8805 (defun org-run-like-in-org-mode (cmd)
8806 "Run a command, pretending that the current buffer is in Org-mode.
8807 This will temporarily bind local variables that are typically bound in
8808 Org-mode to the values they have in Org-mode, and then interactively
8809 call CMD."
8810 (org-load-modules-maybe)
8811 (unless org-local-vars
8812 (setq org-local-vars (org-get-local-variables)))
8813 (let (symbols values)
8814 (dolist (var org-local-vars)
8815 (when (or (not (boundp (car var)))
8816 (eq (symbol-value (car var))
8817 (default-value (car var))))
8818 (push (car var) symbols)
8819 (push (cadr var) values)))
8820 (progv symbols values
8821 (call-interactively cmd))))
8823 ;;;; Archiving
8825 (defun org-get-category (&optional pos force-refresh)
8826 "Get the category applying to position POS."
8827 (save-match-data
8828 (if force-refresh (org-refresh-category-properties))
8829 (let ((pos (or pos (point))))
8830 (or (get-text-property pos 'org-category)
8831 (progn (org-refresh-category-properties)
8832 (get-text-property pos 'org-category))))))
8834 (defun org-refresh-category-properties ()
8835 "Refresh category text properties in the buffer."
8836 (let ((case-fold-search t)
8837 (inhibit-read-only t)
8838 (def-cat (cond
8839 ((null org-category)
8840 (if buffer-file-name
8841 (file-name-sans-extension
8842 (file-name-nondirectory buffer-file-name))
8843 "???"))
8844 ((symbolp org-category) (symbol-name org-category))
8845 (t org-category)))
8846 beg end cat pos optionp)
8847 (org-unmodified
8848 (save-excursion
8849 (save-restriction
8850 (widen)
8851 (goto-char (point-min))
8852 (put-text-property (point) (point-max) 'org-category def-cat)
8853 (while (re-search-forward
8854 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8855 (setq pos (match-end 0)
8856 optionp (equal (char-after (match-beginning 0)) ?#)
8857 cat (org-trim (match-string 2)))
8858 (if optionp
8859 (setq beg (point-at-bol) end (point-max))
8860 (org-back-to-heading t)
8861 (setq beg (point) end (org-end-of-subtree t t)))
8862 (put-text-property beg end 'org-category cat)
8863 (put-text-property beg end 'org-category-position beg)
8864 (goto-char pos)))))))
8866 (defun org-refresh-properties (dprop tprop)
8867 "Refresh buffer text properties.
8868 DPROP is the drawer property and TPROP is the corresponding text
8869 property to set."
8870 (let ((case-fold-search t)
8871 (inhibit-read-only t) p)
8872 (org-unmodified
8873 (save-excursion
8874 (save-restriction
8875 (widen)
8876 (goto-char (point-min))
8877 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8878 (setq p (org-match-string-no-properties 1))
8879 (save-excursion
8880 (org-back-to-heading t)
8881 (put-text-property
8882 (point-at-bol) (point-at-eol) tprop p))))))))
8885 ;;;; Link Stuff
8887 ;;; Link abbreviations
8889 (defun org-link-expand-abbrev (link)
8890 "Apply replacements as defined in `org-link-abbrev-alist'."
8891 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8892 (let* ((key (match-string 1 link))
8893 (as (or (assoc key org-link-abbrev-alist-local)
8894 (assoc key org-link-abbrev-alist)))
8895 (tag (and (match-end 2) (match-string 3 link)))
8896 rpl)
8897 (if (not as)
8898 link
8899 (setq rpl (cdr as))
8900 (cond
8901 ((symbolp rpl) (funcall rpl tag))
8902 ((string-match "%(\\([^)]+\\))" rpl)
8903 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8904 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8905 ((string-match "%h" rpl)
8906 (replace-match (url-hexify-string (or tag "")) t t rpl))
8907 (t (concat rpl tag)))))
8908 link))
8910 ;;; Storing and inserting links
8912 (defvar org-insert-link-history nil
8913 "Minibuffer history for links inserted with `org-insert-link'.")
8915 (defvar org-stored-links nil
8916 "Contains the links stored with `org-store-link'.")
8918 (defvar org-store-link-plist nil
8919 "Plist with info about the most recently link created with `org-store-link'.")
8921 (defvar org-link-protocols nil
8922 "Link protocols added to Org-mode using `org-add-link-type'.")
8924 (defvar org-store-link-functions nil
8925 "List of functions that are called to create and store a link.
8926 Each function will be called in turn until one returns a non-nil
8927 value. Each function should check if it is responsible for creating
8928 this link (for example by looking at the major mode).
8929 If not, it must exit and return nil.
8930 If yes, it should return a non-nil value after a calling
8931 `org-store-link-props' with a list of properties and values.
8932 Special properties are:
8934 :type The link prefix, like \"http\". This must be given.
8935 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8936 This is obligatory as well.
8937 :description Optional default description for the second pair
8938 of brackets in an Org-mode link. The user can still change
8939 this when inserting this link into an Org-mode buffer.
8941 In addition to these, any additional properties can be specified
8942 and then used in capture templates.")
8944 (defun org-add-link-type (type &optional follow export)
8945 "Add TYPE to the list of `org-link-types'.
8946 Re-compute all regular expressions depending on `org-link-types'
8948 FOLLOW and EXPORT are two functions.
8950 FOLLOW should take the link path as the single argument and do whatever
8951 is necessary to follow the link, for example find a file or display
8952 a mail message.
8954 EXPORT should format the link path for export to one of the export formats.
8955 It should be a function accepting three arguments:
8957 path the path of the link, the text after the prefix (like \"http:\")
8958 desc the description of the link, if any, or a description added by
8959 org-export-normalize-links if there is none
8960 format the export format, a symbol like `html' or `latex' or `ascii'..
8962 The function may use the FORMAT information to return different values
8963 depending on the format. The return value will be put literally into
8964 the exported file. If the return value is nil, this means Org should
8965 do what it normally does with links which do not have EXPORT defined.
8967 Org-mode has a built-in default for exporting links. If you are happy with
8968 this default, there is no need to define an export function for the link
8969 type. For a simple example of an export function, see `org-bbdb.el'."
8970 (add-to-list 'org-link-types type t)
8971 (org-make-link-regexps)
8972 (if (assoc type org-link-protocols)
8973 (setcdr (assoc type org-link-protocols) (list follow export))
8974 (push (list type follow export) org-link-protocols)))
8976 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8977 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8979 ;;;###autoload
8980 (defun org-store-link (arg)
8981 "\\<org-mode-map>Store an org-link to the current location.
8982 This link is added to `org-stored-links' and can later be inserted
8983 into an org-buffer with \\[org-insert-link].
8985 For some link types, a prefix arg is interpreted.
8986 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8987 For file links, arg negates `org-context-in-file-links'.
8989 A double prefix arg force skipping storing functions that are not
8990 part of Org's core."
8991 (interactive "P")
8992 (org-load-modules-maybe)
8993 (setq org-store-link-plist nil) ; reset
8994 (org-with-limited-levels
8995 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8996 (cond
8997 ((and (not (equal arg '(16)))
8998 (setq sfuns
8999 (delq
9000 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9001 org-store-link-functions))
9002 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9003 (or (and (cdr sfuns)
9004 (funcall (intern
9005 (completing-read "Which function for creating the link? "
9006 sfunsn t (car sfunsn)))))
9007 (funcall (caar sfuns)))
9008 (setq link (plist-get org-store-link-plist :link)
9009 desc (or (plist-get org-store-link-plist :description) link))))
9010 ((org-src-edit-buffer-p)
9011 (let (label gc)
9012 (while (or (not label)
9013 (save-excursion
9014 (save-restriction
9015 (widen)
9016 (goto-char (point-min))
9017 (re-search-forward
9018 (regexp-quote (format org-coderef-label-format label))
9019 nil t))))
9020 (when label (message "Label exists already") (sit-for 2))
9021 (setq label (read-string "Code line label: " label)))
9022 (end-of-line 1)
9023 (setq link (format org-coderef-label-format label))
9024 (setq gc (- 79 (length link)))
9025 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9026 (insert link)
9027 (setq link (concat "(" label ")") desc nil)))
9029 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9030 ;; We are in the agenda, link to referenced location
9031 (let ((m (or (get-text-property (point) 'org-hd-marker)
9032 (get-text-property (point) 'org-marker))))
9033 (when m
9034 (org-with-point-at m
9035 (setq agenda-link
9036 (if (org-called-interactively-p 'any)
9037 (call-interactively 'org-store-link)
9038 (org-store-link nil)))))))
9040 ((eq major-mode 'calendar-mode)
9041 (let ((cd (calendar-cursor-to-date)))
9042 (setq link
9043 (format-time-string
9044 (car org-time-stamp-formats)
9045 (apply 'encode-time
9046 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9047 nil nil nil))))
9048 (org-store-link-props :type "calendar" :date cd)))
9050 ((eq major-mode 'help-mode)
9051 (setq link (concat "help:" (save-excursion
9052 (goto-char (point-min))
9053 (looking-at "^[^ ]+")
9054 (match-string 0))))
9055 (org-store-link-props :type "help"))
9057 ((eq major-mode 'w3-mode)
9058 (setq cpltxt (if (and (buffer-name)
9059 (not (string-match "Untitled" (buffer-name))))
9060 (buffer-name)
9061 (url-view-url t))
9062 link (url-view-url t))
9063 (org-store-link-props :type "w3" :url (url-view-url t)))
9065 ((setq search (run-hook-with-args-until-success
9066 'org-create-file-search-functions))
9067 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9068 "::" search))
9069 (setq cpltxt (or description link)))
9071 ((eq major-mode 'image-mode)
9072 (setq cpltxt (concat "file:"
9073 (abbreviate-file-name buffer-file-name))
9074 link cpltxt)
9075 (org-store-link-props :type "image" :file buffer-file-name))
9077 ((eq major-mode 'dired-mode)
9078 ;; link to the file in the current line
9079 (let ((file (dired-get-filename nil t)))
9080 (setq file (if file
9081 (abbreviate-file-name
9082 (expand-file-name (dired-get-filename nil t)))
9083 ;; otherwise, no file so use current directory.
9084 default-directory))
9085 (setq cpltxt (concat "file:" file)
9086 link cpltxt)))
9088 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9089 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9090 (cond
9091 ((org-in-regexp "<<\\(.*?\\)>>")
9092 (setq cpltxt
9093 (concat "file:"
9094 (abbreviate-file-name
9095 (buffer-file-name (buffer-base-buffer)))
9096 "::" (match-string 1))
9097 link cpltxt))
9098 ((and (featurep 'org-id)
9099 (or (eq org-id-link-to-org-use-id t)
9100 (and (org-called-interactively-p 'any)
9101 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9102 (and (eq org-id-link-to-org-use-id
9103 'create-if-interactive-and-no-custom-id)
9104 (not custom-id))))
9105 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9106 ;; We can make a link using the ID.
9107 (setq link (condition-case nil
9108 (prog1 (org-id-store-link)
9109 (setq desc (plist-get org-store-link-plist :description)))
9110 (error
9111 ;; probably before first headline, link to file only
9112 (concat "file:"
9113 (abbreviate-file-name
9114 (buffer-file-name (buffer-base-buffer))))))))
9116 ;; Just link to current headline
9117 (setq cpltxt (concat "file:"
9118 (abbreviate-file-name
9119 (buffer-file-name (buffer-base-buffer)))))
9120 ;; Add a context search string
9121 (when (org-xor org-context-in-file-links arg)
9122 (let* ((ee (org-element-at-point))
9123 (et (org-element-type ee))
9124 (ev (plist-get (cadr ee) :value)))
9125 (setq txt (cond
9126 ((org-at-heading-p) nil)
9127 ((eq et 'keyword) ev)
9128 ((org-region-active-p)
9129 (buffer-substring (region-beginning) (region-end)))))
9130 (when (or (null txt) (string-match "\\S-" txt))
9131 (setq cpltxt
9132 (concat cpltxt "::"
9133 (condition-case nil
9134 (org-make-org-heading-search-string txt)
9135 (error "")))
9136 desc (or (and (eq et 'keyword) ev)
9137 (nth 4 (ignore-errors (org-heading-components)))
9138 "NONE")))))
9139 (if (string-match "::\\'" cpltxt)
9140 (setq cpltxt (substring cpltxt 0 -2)))
9141 (setq link cpltxt))))
9143 ((buffer-file-name (buffer-base-buffer))
9144 ;; Just link to this file here.
9145 (setq cpltxt (concat "file:"
9146 (abbreviate-file-name
9147 (buffer-file-name (buffer-base-buffer)))))
9148 ;; Add a context string
9149 (when (org-xor org-context-in-file-links arg)
9150 (setq txt (if (org-region-active-p)
9151 (buffer-substring (region-beginning) (region-end))
9152 (buffer-substring (point-at-bol) (point-at-eol))))
9153 ;; Only use search option if there is some text.
9154 (when (string-match "\\S-" txt)
9155 (setq cpltxt
9156 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9157 desc "NONE")))
9158 (setq link cpltxt))
9160 ((org-called-interactively-p 'interactive)
9161 (user-error "No method for storing a link from this buffer"))
9163 (t (setq link nil)))
9165 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9166 (setq link (or link cpltxt)
9167 desc (or desc cpltxt))
9168 (cond ((equal desc "NONE") (setq desc nil))
9169 ((string-match org-bracket-link-regexp desc)
9170 (setq desc (replace-regexp-in-string
9171 org-bracket-link-regexp
9172 (concat "\\3" (if (equal (length (match-string 0 desc))
9173 (length desc)) "*" "")) desc))))
9175 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9176 (progn
9177 (setq org-stored-links
9178 (cons (list link desc) org-stored-links))
9179 (message "Stored: %s" (or desc link))
9180 (when custom-id
9181 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9182 "::#" custom-id))
9183 (setq org-stored-links
9184 (cons (list link desc) org-stored-links))))
9185 (or agenda-link (and link (org-make-link-string link desc)))))))
9187 (defun org-store-link-props (&rest plist)
9188 "Store link properties, extract names and addresses."
9189 (let (x adr)
9190 (when (setq x (plist-get plist :from))
9191 (setq adr (mail-extract-address-components x))
9192 (setq plist (plist-put plist :fromname (car adr)))
9193 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9194 (when (setq x (plist-get plist :to))
9195 (setq adr (mail-extract-address-components x))
9196 (setq plist (plist-put plist :toname (car adr)))
9197 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9198 (let ((from (plist-get plist :from))
9199 (to (plist-get plist :to)))
9200 (when (and from to org-from-is-user-regexp)
9201 (setq plist
9202 (plist-put plist :fromto
9203 (if (string-match org-from-is-user-regexp from)
9204 (concat "to %t")
9205 (concat "from %f"))))))
9206 (setq org-store-link-plist plist))
9208 (defun org-add-link-props (&rest plist)
9209 "Add these properties to the link property list."
9210 (let (key value)
9211 (while plist
9212 (setq key (pop plist) value (pop plist))
9213 (setq org-store-link-plist
9214 (plist-put org-store-link-plist key value)))))
9216 (defun org-email-link-description (&optional fmt)
9217 "Return the description part of an email link.
9218 This takes information from `org-store-link-plist' and formats it
9219 according to FMT (default from `org-email-link-description-format')."
9220 (setq fmt (or fmt org-email-link-description-format))
9221 (let* ((p org-store-link-plist)
9222 (to (plist-get p :toaddress))
9223 (from (plist-get p :fromaddress))
9224 (table
9225 (list
9226 (cons "%c" (plist-get p :fromto))
9227 (cons "%F" (plist-get p :from))
9228 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9229 (cons "%T" (plist-get p :to))
9230 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9231 (cons "%s" (plist-get p :subject))
9232 (cons "%d" (plist-get p :date))
9233 (cons "%m" (plist-get p :message-id)))))
9234 (when (string-match "%c" fmt)
9235 ;; Check if the user wrote this message
9236 (if (and org-from-is-user-regexp from to
9237 (save-match-data (string-match org-from-is-user-regexp from)))
9238 (setq fmt (replace-match "to %t" t t fmt))
9239 (setq fmt (replace-match "from %f" t t fmt))))
9240 (org-replace-escapes fmt table)))
9242 (defun org-make-org-heading-search-string (&optional string)
9243 "Make search string for the current headline or STRING."
9244 (let ((s (or string
9245 (and (derived-mode-p 'org-mode)
9246 (save-excursion
9247 (org-back-to-heading t)
9248 (plist-get (cadr (org-element-at-point))
9249 :raw-value)))))
9250 (lines org-context-in-file-links))
9251 (or string (setq s (concat "*" s))) ; Add * for headlines
9252 (when (and string (integerp lines) (> lines 0))
9253 (let ((slines (org-split-string s "\n")))
9254 (when (< lines (length slines))
9255 (setq s (mapconcat
9256 'identity
9257 (reverse (nthcdr (- (length slines) lines)
9258 (reverse slines))) "\n")))))
9259 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9261 (defun org-make-link-string (link &optional description)
9262 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9263 (unless (string-match "\\S-" link)
9264 (error "Empty link"))
9265 (when (and description
9266 (stringp description)
9267 (not (string-match "\\S-" description)))
9268 (setq description nil))
9269 (when (stringp description)
9270 ;; Remove brackets from the description, they are fatal.
9271 (while (string-match "\\[" description)
9272 (setq description (replace-match "{" t t description)))
9273 (while (string-match "\\]" description)
9274 (setq description (replace-match "}" t t description))))
9275 (when (equal link description)
9276 ;; No description needed, it is identical
9277 (setq description nil))
9278 (when (and (not description)
9279 (not (string-match (org-image-file-name-regexp) link))
9280 (not (equal link (org-link-escape link))))
9281 (setq description (org-extract-attributes link)))
9282 (setq link
9283 (cond ((string-match (org-image-file-name-regexp) link) link)
9284 ((string-match org-link-types-re link)
9285 (concat (match-string 1 link)
9286 (org-link-escape (substring link (match-end 1)))))
9287 (t (org-link-escape link))))
9288 (concat "[[" link "]"
9289 (if description (concat "[" description "]") "")
9290 "]"))
9292 (defconst org-link-escape-chars
9293 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9294 "List of characters that should be escaped in link.
9295 This is the list that is used for internal purposes.")
9297 (defconst org-link-escape-chars-browser
9298 '(?\ )
9299 "List of escapes for characters that are problematic in links.
9300 This is the list that is used before handing over to the browser.")
9302 (defun org-link-escape (text &optional table merge)
9303 "Return percent escaped representation of TEXT.
9304 TEXT is a string with the text to escape.
9305 Optional argument TABLE is a list with characters that should be
9306 escaped. When nil, `org-link-escape-chars' is used.
9307 If optional argument MERGE is set, merge TABLE into
9308 `org-link-escape-chars'."
9309 (cond
9310 ((and table merge)
9311 (mapc (lambda (defchr)
9312 (unless (member defchr table)
9313 (setq table (cons defchr table)))) org-link-escape-chars))
9314 ((null table)
9315 (setq table org-link-escape-chars)))
9316 (mapconcat
9317 (lambda (char)
9318 (if (or (member char table)
9319 (and (or (< char 32) (= char 37) (> char 126))
9320 org-url-hexify-p))
9321 (mapconcat (lambda (sequence-element)
9322 (format "%%%.2X" sequence-element))
9323 (or (encode-coding-char char 'utf-8)
9324 (error "Unable to percent escape character: %s"
9325 (char-to-string char))) "")
9326 (char-to-string char))) text ""))
9328 (defun org-link-unescape (str)
9329 "Unhex hexified Unicode strings as returned from the JavaScript function
9330 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9331 (unless (and (null str) (string= "" str))
9332 (let ((pos 0) (case-fold-search t) unhexed)
9333 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9334 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9335 (setq str (replace-match unhexed t t str))
9336 (setq pos (+ pos (length unhexed))))))
9337 str)
9339 (defun org-link-unescape-compound (hex)
9340 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9341 Note: this function also decodes single byte encodings like
9342 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9343 (save-match-data
9344 (let* ((bytes (cdr (split-string hex "%")))
9345 (ret "")
9346 (eat 0)
9347 (sum 0))
9348 (while bytes
9349 (let* ((val (string-to-number (pop bytes) 16))
9350 (shift-xor
9351 (if (= 0 eat)
9352 (cond
9353 ((>= val 252) (cons 6 252))
9354 ((>= val 248) (cons 5 248))
9355 ((>= val 240) (cons 4 240))
9356 ((>= val 224) (cons 3 224))
9357 ((>= val 192) (cons 2 192))
9358 (t (cons 0 0)))
9359 (cons 6 128))))
9360 (if (>= val 192) (setq eat (car shift-xor)))
9361 (setq val (logxor val (cdr shift-xor)))
9362 (setq sum (+ (lsh sum (car shift-xor)) val))
9363 (if (> eat 0) (setq eat (- eat 1)))
9364 (cond
9365 ((= 0 eat) ;multi byte
9366 (setq ret (concat ret (org-char-to-string sum)))
9367 (setq sum 0))
9368 ((not bytes) ; single byte(s)
9369 (setq ret (org-link-unescape-single-byte-sequence hex))))
9370 )) ;; end (while bytes
9371 ret )))
9373 (defun org-link-unescape-single-byte-sequence (hex)
9374 "Unhexify hex-encoded single byte character sequences."
9375 (mapconcat (lambda (byte)
9376 (char-to-string (string-to-number byte 16)))
9377 (cdr (split-string hex "%")) ""))
9379 (defun org-xor (a b)
9380 "Exclusive or."
9381 (if a (not b) b))
9383 (defun org-fixup-message-id-for-http (s)
9384 "Replace special characters in a message id, so it can be used in an http query."
9385 (when (string-match "%" s)
9386 (setq s (mapconcat (lambda (c)
9387 (if (eq c ?%)
9388 "%25"
9389 (char-to-string c)))
9390 s "")))
9391 (while (string-match "<" s)
9392 (setq s (replace-match "%3C" t t s)))
9393 (while (string-match ">" s)
9394 (setq s (replace-match "%3E" t t s)))
9395 (while (string-match "@" s)
9396 (setq s (replace-match "%40" t t s)))
9399 (defun org-link-prettify (link)
9400 "Return a human-readable representation of LINK.
9401 The car of LINK must be a raw link the cdr of LINK must be either
9402 a link description or nil."
9403 (let ((desc (or (cadr link) "<no description>")))
9404 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9405 "<" (car link) ">")))
9407 ;;;###autoload
9408 (defun org-insert-link-global ()
9409 "Insert a link like Org-mode does.
9410 This command can be called in any mode to insert a link in Org-mode syntax."
9411 (interactive)
9412 (org-load-modules-maybe)
9413 (org-run-like-in-org-mode 'org-insert-link))
9415 (defun org-insert-all-links (&optional keep)
9416 "Insert all links in `org-stored-links'."
9417 (interactive "P")
9418 (let ((links (copy-sequence org-stored-links)) l)
9419 (while (setq l (if keep (pop links) (pop org-stored-links)))
9420 (insert "- ")
9421 (org-insert-link nil (car l) (cadr l))
9422 (insert "\n"))))
9424 (defun org-link-fontify-links-to-this-file ()
9425 "Fontify links to the current file in `org-stored-links'."
9426 (let ((f (buffer-file-name)) a b)
9427 (setq a (mapcar (lambda(l)
9428 (let ((ll (car l)))
9429 (when (and (string-match "^file:\\(.+\\)::" ll)
9430 (equal f (expand-file-name (match-string 1 ll))))
9431 ll)))
9432 org-stored-links))
9433 (when (featurep 'org-id)
9434 (setq b (mapcar (lambda(l)
9435 (let ((ll (car l)))
9436 (when (and (string-match "^id:\\(.+\\)$" ll)
9437 (equal f (expand-file-name
9438 (or (org-id-find-id-file
9439 (match-string 1 ll)) ""))))
9440 ll)))
9441 org-stored-links)))
9442 (mapcar (lambda(l)
9443 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9444 (delq nil (append a b)))))
9446 (defvar org-link-links-in-this-file nil)
9447 (defun org-insert-link (&optional complete-file link-location default-description)
9448 "Insert a link. At the prompt, enter the link.
9450 Completion can be used to insert any of the link protocol prefixes like
9451 http or ftp in use.
9453 The history can be used to select a link previously stored with
9454 `org-store-link'. When the empty string is entered (i.e. if you just
9455 press RET at the prompt), the link defaults to the most recently
9456 stored link. As SPC triggers completion in the minibuffer, you need to
9457 use M-SPC or C-q SPC to force the insertion of a space character.
9459 You will also be prompted for a description, and if one is given, it will
9460 be displayed in the buffer instead of the link.
9462 If there is already a link at point, this command will allow you to edit link
9463 and description parts.
9465 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9466 be selected using completion. The path to the file will be relative to the
9467 current directory if the file is in the current directory or a subdirectory.
9468 Otherwise, the link will be the absolute path as completed in the minibuffer
9469 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9470 option `org-link-file-path-type'.
9472 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9473 the current directory or below.
9475 With three \\[universal-argument] prefixes, negate the meaning of
9476 `org-keep-stored-link-after-insertion'.
9478 If `org-make-link-description-function' is non-nil, this function will be
9479 called with the link target, and the result will be the default
9480 link description.
9482 If the LINK-LOCATION parameter is non-nil, this value will be
9483 used as the link location instead of reading one interactively.
9485 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9486 be used as the default description."
9487 (interactive "P")
9488 (let* ((wcf (current-window-configuration))
9489 (origbuf (current-buffer))
9490 (region (if (org-region-active-p)
9491 (buffer-substring (region-beginning) (region-end))))
9492 (remove (and region (list (region-beginning) (region-end))))
9493 (desc region)
9494 tmphist ; byte-compile incorrectly complains about this
9495 (link link-location)
9496 (abbrevs org-link-abbrev-alist-local)
9497 entry file all-prefixes auto-desc)
9498 (cond
9499 (link-location) ; specified by arg, just use it.
9500 ((org-in-regexp org-bracket-link-regexp 1)
9501 ;; We do have a link at point, and we are going to edit it.
9502 (setq remove (list (match-beginning 0) (match-end 0)))
9503 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9504 (setq link (read-string "Link: "
9505 (org-link-unescape
9506 (org-match-string-no-properties 1)))))
9507 ((or (org-in-regexp org-angle-link-re)
9508 (org-in-regexp org-plain-link-re))
9509 ;; Convert to bracket link
9510 (setq remove (list (match-beginning 0) (match-end 0))
9511 link (read-string "Link: "
9512 (org-remove-angle-brackets (match-string 0)))))
9513 ((member complete-file '((4) (16)))
9514 ;; Completing read for file names.
9515 (setq link (org-file-complete-link complete-file)))
9517 ;; Read link, with completion for stored links.
9518 (org-link-fontify-links-to-this-file)
9519 (org-switch-to-buffer-other-window "*Org Links*")
9520 (with-current-buffer "*Org Links*"
9521 (erase-buffer)
9522 (insert "Insert a link.
9523 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9524 (when org-stored-links
9525 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9526 (insert (mapconcat 'org-link-prettify
9527 (reverse org-stored-links) "\n")))
9528 (goto-char (point-min)))
9529 (let ((cw (selected-window)))
9530 (select-window (get-buffer-window "*Org Links*" 'visible))
9531 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9532 (unless (pos-visible-in-window-p (point-max))
9533 (org-fit-window-to-buffer))
9534 (and (window-live-p cw) (select-window cw)))
9535 ;; Fake a link history, containing the stored links.
9536 (setq tmphist (append (mapcar 'car org-stored-links)
9537 org-insert-link-history))
9538 (setq all-prefixes (append (mapcar 'car abbrevs)
9539 (mapcar 'car org-link-abbrev-alist)
9540 org-link-types))
9541 (unwind-protect
9542 (progn
9543 (setq link
9544 (org-completing-read
9545 "Link: "
9546 (append
9547 (mapcar (lambda (x) (concat x ":"))
9548 all-prefixes)
9549 (mapcar 'car org-stored-links))
9550 nil nil nil
9551 'tmphist
9552 (caar org-stored-links)))
9553 (if (not (string-match "\\S-" link))
9554 (error "No link selected"))
9555 (mapc (lambda(l)
9556 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9557 org-stored-links)
9558 (if (or (member link all-prefixes)
9559 (and (equal ":" (substring link -1))
9560 (member (substring link 0 -1) all-prefixes)
9561 (setq link (substring link 0 -1))))
9562 (setq link (with-current-buffer origbuf
9563 (org-link-try-special-completion link)))))
9564 (set-window-configuration wcf)
9565 (kill-buffer "*Org Links*"))
9566 (setq entry (assoc link org-stored-links))
9567 (or entry (push link org-insert-link-history))
9568 (setq desc (or desc (nth 1 entry)))))
9570 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9571 (not org-keep-stored-link-after-insertion))
9572 (setq org-stored-links (delq (assoc link org-stored-links)
9573 org-stored-links)))
9575 (if (string-match org-plain-link-re link)
9576 ;; URL-like link, normalize the use of angular brackets.
9577 (setq link (org-remove-angle-brackets link)))
9579 ;; Check if we are linking to the current file with a search
9580 ;; option If yes, simplify the link by using only the search
9581 ;; option.
9582 (when (and buffer-file-name
9583 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9584 (let* ((path (match-string 1 link))
9585 (case-fold-search nil)
9586 (search (match-string 2 link)))
9587 (save-match-data
9588 (if (equal (file-truename buffer-file-name) (file-truename path))
9589 ;; We are linking to this same file, with a search option
9590 (setq link search)))))
9592 ;; Check if we can/should use a relative path. If yes, simplify the link
9593 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9594 (let* ((type (match-string 1 link))
9595 (path (match-string 2 link))
9596 (origpath path)
9597 (case-fold-search nil))
9598 (cond
9599 ((or (eq org-link-file-path-type 'absolute)
9600 (equal complete-file '(16)))
9601 (setq path (abbreviate-file-name (expand-file-name path))))
9602 ((eq org-link-file-path-type 'noabbrev)
9603 (setq path (expand-file-name path)))
9604 ((eq org-link-file-path-type 'relative)
9605 (setq path (file-relative-name path)))
9607 (save-match-data
9608 (if (string-match (concat "^" (regexp-quote
9609 (expand-file-name
9610 (file-name-as-directory
9611 default-directory))))
9612 (expand-file-name path))
9613 ;; We are linking a file with relative path name.
9614 (setq path (substring (expand-file-name path)
9615 (match-end 0)))
9616 (setq path (abbreviate-file-name (expand-file-name path)))))))
9617 (setq link (concat type path))
9618 (if (equal desc origpath)
9619 (setq desc path))))
9621 (if org-make-link-description-function
9622 (setq desc
9623 (or (condition-case nil
9624 (funcall org-make-link-description-function link desc)
9625 (error (progn (message "Can't get link description from `%s'"
9626 (symbol-name org-make-link-description-function))
9627 (sit-for 2) nil)))
9628 (read-string "Description: " default-description)))
9629 (if default-description (setq desc default-description)
9630 (setq desc (or (and auto-desc desc)
9631 (read-string "Description: " desc)))))
9633 (unless (string-match "\\S-" desc) (setq desc nil))
9634 (if remove (apply 'delete-region remove))
9635 (insert (org-make-link-string link desc))))
9637 (defun org-link-try-special-completion (type)
9638 "If there is completion support for link type TYPE, offer it."
9639 (let ((fun (intern (concat "org-" type "-complete-link"))))
9640 (if (functionp fun)
9641 (funcall fun)
9642 (read-string "Link (no completion support): " (concat type ":")))))
9644 (defun org-file-complete-link (&optional arg)
9645 "Create a file link using completion."
9646 (let (file link)
9647 (setq file (org-iread-file-name "File: "))
9648 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9649 (pwd1 (file-name-as-directory (abbreviate-file-name
9650 (expand-file-name ".")))))
9651 (cond
9652 ((equal arg '(16))
9653 (setq link (concat
9654 "file:"
9655 (abbreviate-file-name (expand-file-name file)))))
9656 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9657 (setq link (concat "file:" (match-string 1 file))))
9658 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9659 (expand-file-name file))
9660 (setq link (concat
9661 "file:" (match-string 1 (expand-file-name file)))))
9662 (t (setq link (concat "file:" file)))))
9663 link))
9665 (defun org-iread-file-name (&rest args)
9666 "Read-file-name using `ido-mode' speedup if available.
9667 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9668 See `read-file-name' for a description of parameters."
9669 (org-without-partial-completion
9670 (if (and org-completion-use-ido
9671 (fboundp 'ido-read-file-name)
9672 (boundp 'ido-mode) ido-mode
9673 (listp (second args)))
9674 (let ((ido-enter-matching-directory nil))
9675 (apply 'ido-read-file-name args))
9676 (apply 'read-file-name args))))
9678 (defun org-completing-read (&rest args)
9679 "Completing-read with SPACE being a normal character."
9680 (let ((enable-recursive-minibuffers t)
9681 (minibuffer-local-completion-map
9682 (copy-keymap minibuffer-local-completion-map)))
9683 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9684 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9685 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9686 (apply 'org-icompleting-read args)))
9688 (defun org-completing-read-no-i (&rest args)
9689 (let (org-completion-use-ido org-completion-use-iswitchb)
9690 (apply 'org-completing-read args)))
9692 (defun org-iswitchb-completing-read (prompt choices &rest args)
9693 "Use iswitch as a completing-read replacement to choose from choices.
9694 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9695 from."
9696 (let* ((iswitchb-use-virtual-buffers nil)
9697 (iswitchb-make-buflist-hook
9698 (lambda ()
9699 (setq iswitchb-temp-buflist choices))))
9700 (iswitchb-read-buffer prompt)))
9702 (defun org-icompleting-read (&rest args)
9703 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9704 (org-without-partial-completion
9705 (if (and org-completion-use-ido
9706 (fboundp 'ido-completing-read)
9707 (boundp 'ido-mode) ido-mode
9708 (listp (second args)))
9709 (let ((ido-enter-matching-directory nil))
9710 (apply 'ido-completing-read (concat (car args))
9711 (if (consp (car (nth 1 args)))
9712 (mapcar 'car (nth 1 args))
9713 (nth 1 args))
9714 (cddr args)))
9715 (if (and org-completion-use-iswitchb
9716 (boundp 'iswitchb-mode) iswitchb-mode
9717 (listp (second args)))
9718 (apply 'org-iswitchb-completing-read (concat (car args))
9719 (if (consp (car (nth 1 args)))
9720 (mapcar 'car (nth 1 args))
9721 (nth 1 args))
9722 (cddr args))
9723 (apply 'completing-read args)))))
9725 (defun org-extract-attributes (s)
9726 "Extract the attributes cookie from a string and set as text property."
9727 (let (a attr (start 0) key value)
9728 (save-match-data
9729 (when (string-match "{{\\([^}]+\\)}}$" s)
9730 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9731 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9732 (setq key (match-string 1 a) value (match-string 2 a)
9733 start (match-end 0)
9734 attr (plist-put attr (intern key) value))))
9735 (org-add-props s nil 'org-attr attr))
9738 (defun org-extract-attributes-from-string (tag)
9739 (let (key value attr)
9740 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9741 (setq key (match-string 1 tag) value (match-string 2 tag)
9742 tag (replace-match "" t t tag)
9743 attr (plist-put attr (intern key) value)))
9744 (cons tag attr)))
9746 (defun org-attributes-to-string (plist)
9747 "Format a property list into an HTML attribute list."
9748 (let ((s "") key value)
9749 (while plist
9750 (setq key (pop plist) value (pop plist))
9751 (and value
9752 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9755 ;;; Opening/following a link
9757 (defvar org-link-search-failed nil)
9759 (defvar org-open-link-functions nil
9760 "Hook for functions finding a plain text link.
9761 These functions must take a single argument, the link content.
9762 They will be called for links that look like [[link text][description]]
9763 when LINK TEXT does not have a protocol like \"http:\" and does not look
9764 like a filename (e.g. \"./blue.png\").
9766 These functions will be called *before* Org attempts to resolve the
9767 link by doing text searches in the current buffer - so if you want a
9768 link \"[[target]]\" to still find \"<<target>>\", your function should
9769 handle this as a special case.
9771 When the function does handle the link, it must return a non-nil value.
9772 If it decides that it is not responsible for this link, it must return
9773 nil to indicate that that Org-mode can continue with other options
9774 like exact and fuzzy text search.")
9776 (defun org-next-link ()
9777 "Move forward to the next link.
9778 If the link is in hidden text, expose it."
9779 (interactive)
9780 (when (and org-link-search-failed (eq this-command last-command))
9781 (goto-char (point-min))
9782 (message "Link search wrapped back to beginning of buffer"))
9783 (setq org-link-search-failed nil)
9784 (let* ((pos (point))
9785 (ct (org-context))
9786 (a (assoc :link ct)))
9787 (if a (goto-char (nth 2 a)))
9788 (if (re-search-forward org-any-link-re nil t)
9789 (progn
9790 (goto-char (match-beginning 0))
9791 (if (outline-invisible-p) (org-show-context)))
9792 (goto-char pos)
9793 (setq org-link-search-failed t)
9794 (error "No further link found"))))
9796 (defun org-previous-link ()
9797 "Move backward to the previous link.
9798 If the link is in hidden text, expose it."
9799 (interactive)
9800 (when (and org-link-search-failed (eq this-command last-command))
9801 (goto-char (point-max))
9802 (message "Link search wrapped back to end of buffer"))
9803 (setq org-link-search-failed nil)
9804 (let* ((pos (point))
9805 (ct (org-context))
9806 (a (assoc :link ct)))
9807 (if a (goto-char (nth 1 a)))
9808 (if (re-search-backward org-any-link-re nil t)
9809 (progn
9810 (goto-char (match-beginning 0))
9811 (if (outline-invisible-p) (org-show-context)))
9812 (goto-char pos)
9813 (setq org-link-search-failed t)
9814 (error "No further link found"))))
9816 (defun org-translate-link (s)
9817 "Translate a link string if a translation function has been defined."
9818 (if (and org-link-translation-function
9819 (fboundp org-link-translation-function)
9820 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9821 (progn
9822 (setq s (funcall org-link-translation-function
9823 (match-string 1 s) (match-string 2 s)))
9824 (concat (car s) ":" (cdr s)))
9827 (defun org-translate-link-from-planner (type path)
9828 "Translate a link from Emacs Planner syntax so that Org can follow it.
9829 This is still an experimental function, your mileage may vary."
9830 (cond
9831 ((member type '("http" "https" "news" "ftp"))
9832 ;; standard Internet links are the same.
9833 nil)
9834 ((and (equal type "irc") (string-match "^//" path))
9835 ;; Planner has two / at the beginning of an irc link, we have 1.
9836 ;; We should have zero, actually....
9837 (setq path (substring path 1)))
9838 ((and (equal type "lisp") (string-match "^/" path))
9839 ;; Planner has a slash, we do not.
9840 (setq type "elisp" path (substring path 1)))
9841 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9842 ;; A typical message link. Planner has the id after the final slash,
9843 ;; we separate it with a hash mark
9844 (setq path (concat (match-string 1 path) "#"
9845 (org-remove-angle-brackets (match-string 2 path)))))
9847 (cons type path))
9849 (defun org-find-file-at-mouse (ev)
9850 "Open file link or URL at mouse."
9851 (interactive "e")
9852 (mouse-set-point ev)
9853 (org-open-at-point 'in-emacs))
9855 (defun org-open-at-mouse (ev)
9856 "Open file link or URL at mouse.
9857 See the docstring of `org-open-file' for details."
9858 (interactive "e")
9859 (mouse-set-point ev)
9860 (if (eq major-mode 'org-agenda-mode)
9861 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9862 (org-open-at-point))
9864 (defvar org-window-config-before-follow-link nil
9865 "The window configuration before following a link.
9866 This is saved in case the need arises to restore it.")
9868 (defvar org-open-link-marker (make-marker)
9869 "Marker pointing to the location where `org-open-at-point; was called.")
9871 ;;;###autoload
9872 (defun org-open-at-point-global ()
9873 "Follow a link like Org-mode does.
9874 This command can be called in any mode to follow a link that has
9875 Org-mode syntax."
9876 (interactive)
9877 (org-run-like-in-org-mode 'org-open-at-point))
9879 ;;;###autoload
9880 (defun org-open-link-from-string (s &optional arg reference-buffer)
9881 "Open a link in the string S, as if it was in Org-mode."
9882 (interactive "sLink: \nP")
9883 (let ((reference-buffer (or reference-buffer (current-buffer))))
9884 (with-temp-buffer
9885 (let ((org-inhibit-startup (not reference-buffer)))
9886 (org-mode)
9887 (insert s)
9888 (goto-char (point-min))
9889 (when reference-buffer
9890 (setq org-link-abbrev-alist-local
9891 (with-current-buffer reference-buffer
9892 org-link-abbrev-alist-local)))
9893 (org-open-at-point arg reference-buffer)))))
9895 (defvar org-open-at-point-functions nil
9896 "Hook that is run when following a link at point.
9898 Functions in this hook must return t if they identify and follow
9899 a link at point. If they don't find anything interesting at point,
9900 they must return nil.")
9902 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9903 (defun org-open-at-point (&optional arg reference-buffer)
9904 "Open link at or after point.
9905 If there is no link at point, this function will search forward up to
9906 the end of the current line.
9907 Normally, files will be opened by an appropriate application. If the
9908 optional prefix argument ARG is non-nil, Emacs will visit the file.
9909 With a double prefix argument, try to open outside of Emacs, in the
9910 application the system uses for this file type."
9911 (interactive "P")
9912 ;; if in a code block, then open the block's results
9913 (unless (call-interactively #'org-babel-open-src-block-result)
9914 (org-load-modules-maybe)
9915 (move-marker org-open-link-marker (point))
9916 (setq org-window-config-before-follow-link (current-window-configuration))
9917 (org-remove-occur-highlights nil nil t)
9918 (cond
9919 ((and (org-at-heading-p)
9920 (not (org-at-timestamp-p t))
9921 (not (org-in-regexp
9922 (concat org-plain-link-re "\\|"
9923 org-bracket-link-regexp "\\|"
9924 org-angle-link-re "\\|"
9925 "[ \t]:[^ \t\n]+:[ \t]*$")))
9926 (not (get-text-property (point) 'org-linked-text)))
9927 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9928 (lk0 (car lkall))
9929 (lk (if (stringp lk0) (list lk0) lk0))
9930 (lkend (cdr lkall)))
9931 (mapcar (lambda(l)
9932 (search-forward l nil lkend)
9933 (goto-char (match-beginning 0))
9934 (org-open-at-point))
9935 lk))
9936 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9937 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9938 ((and (org-at-timestamp-p t)
9939 (not (org-in-regexp org-bracket-link-regexp)))
9940 (org-follow-timestamp-link))
9941 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9942 (not (org-in-regexp org-any-link-re)))
9943 (org-footnote-action))
9945 (let (type path link line search (pos (point)))
9946 (catch 'match
9947 (save-excursion
9948 (skip-chars-forward "^]\n\r")
9949 (when (org-in-regexp org-bracket-link-regexp 1)
9950 (setq link (org-extract-attributes
9951 (org-link-unescape (org-match-string-no-properties 1))))
9952 (while (string-match " *\n *" link)
9953 (setq link (replace-match " " t t link)))
9954 (setq link (org-link-expand-abbrev link))
9955 (cond
9956 ((or (file-name-absolute-p link)
9957 (string-match "^\\.\\.?/" link))
9958 (setq type "file" path link))
9959 ((string-match org-link-re-with-space3 link)
9960 (setq type (match-string 1 link) path (match-string 2 link)))
9961 ((string-match "^help:+\\(.+\\)" link)
9962 (setq type "help" path (match-string 1 link)))
9963 (t (setq type "thisfile" path link)))
9964 (throw 'match t)))
9966 (when (get-text-property (point) 'org-linked-text)
9967 (setq type "thisfile"
9968 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9969 (1+ (point)) (point))
9970 path (buffer-substring
9971 (or (previous-single-property-change pos 'org-linked-text)
9972 (point-min))
9973 (or (next-single-property-change pos 'org-linked-text)
9974 (point-max))))
9975 (throw 'match t))
9977 (save-excursion
9978 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9979 (when (or (org-in-regexp org-angle-link-re)
9980 (and plinkpos (goto-char (car plinkpos))
9981 (save-match-data (not (looking-back "\\[\\[")))))
9982 (setq type (match-string 1)
9983 path (org-link-unescape (match-string 2)))
9984 (throw 'match t))))
9985 (save-excursion
9986 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9987 (setq type "tags"
9988 path (match-string 1))
9989 (while (string-match ":" path)
9990 (setq path (replace-match "+" t t path)))
9991 (throw 'match t)))
9992 (when (org-in-regexp "<\\([^><\n]+\\)>")
9993 (setq type "tree-match"
9994 path (match-string 1))
9995 (throw 'match t)))
9996 (unless path
9997 (user-error "No link found"))
9999 ;; switch back to reference buffer
10000 ;; needed when if called in a temporary buffer through
10001 ;; org-open-link-from-string
10002 (with-current-buffer (or reference-buffer (current-buffer))
10004 ;; Remove any trailing spaces in path
10005 (if (string-match " +\\'" path)
10006 (setq path (replace-match "" t t path)))
10007 (if (and org-link-translation-function
10008 (fboundp org-link-translation-function))
10009 ;; Check if we need to translate the link
10010 (let ((tmp (funcall org-link-translation-function type path)))
10011 (setq type (car tmp) path (cdr tmp))))
10013 (cond
10015 ((assoc type org-link-protocols)
10016 (funcall (nth 1 (assoc type org-link-protocols)) path))
10018 ((equal type "help")
10019 (let ((f-or-v (intern path)))
10020 (cond ((fboundp f-or-v)
10021 (describe-function f-or-v))
10022 ((boundp f-or-v)
10023 (describe-variable f-or-v))
10024 (t (error "Not a known function or variable")))))
10026 ((equal type "mailto")
10027 (let ((cmd (car org-link-mailto-program))
10028 (args (cdr org-link-mailto-program)) args1
10029 (address path) (subject "") a)
10030 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10031 (setq address (match-string 1 path)
10032 subject (org-link-escape (match-string 2 path))))
10033 (while args
10034 (cond
10035 ((not (stringp (car args))) (push (pop args) args1))
10036 (t (setq a (pop args))
10037 (if (string-match "%a" a)
10038 (setq a (replace-match address t t a)))
10039 (if (string-match "%s" a)
10040 (setq a (replace-match subject t t a)))
10041 (push a args1))))
10042 (apply cmd (nreverse args1))))
10044 ((member type '("http" "https" "ftp" "news"))
10045 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10046 (org-link-escape
10047 path org-link-escape-chars-browser)
10048 path))))
10050 ((string= type "doi")
10051 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10052 (org-link-escape
10053 path org-link-escape-chars-browser)
10054 path))))
10056 ((member type '("message"))
10057 (browse-url (concat type ":" path)))
10059 ((string= type "tags")
10060 (org-tags-view arg path))
10062 ((string= type "tree-match")
10063 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10065 ((string= type "file")
10066 (if (string-match "::\\([0-9]+\\)\\'" path)
10067 (setq line (string-to-number (match-string 1 path))
10068 path (substring path 0 (match-beginning 0)))
10069 (if (string-match "::\\(.+\\)\\'" path)
10070 (setq search (match-string 1 path)
10071 path (substring path 0 (match-beginning 0)))))
10072 (if (string-match "[*?{]" (file-name-nondirectory path))
10073 (dired path)
10074 (org-open-file path arg line search)))
10076 ((string= type "shell")
10077 (let ((buf (generate-new-buffer "*Org Shell Output"))
10078 (cmd path))
10079 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10080 (string-match org-confirm-shell-link-not-regexp cmd))
10081 (not org-confirm-shell-link-function)
10082 (funcall org-confirm-shell-link-function
10083 (format "Execute \"%s\" in shell? "
10084 (org-add-props cmd nil
10085 'face 'org-warning))))
10086 (progn
10087 (message "Executing %s" cmd)
10088 (shell-command cmd buf)
10089 (if (featurep 'midnight)
10090 (setq clean-buffer-list-kill-buffer-names
10091 (cons buf clean-buffer-list-kill-buffer-names))))
10092 (error "Abort"))))
10094 ((string= type "elisp")
10095 (let ((cmd path))
10096 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10097 (string-match org-confirm-elisp-link-not-regexp cmd))
10098 (not org-confirm-elisp-link-function)
10099 (funcall org-confirm-elisp-link-function
10100 (format "Execute \"%s\" as elisp? "
10101 (org-add-props cmd nil
10102 'face 'org-warning))))
10103 (message "%s => %s" cmd
10104 (if (equal (string-to-char cmd) ?\()
10105 (eval (read cmd))
10106 (call-interactively (read cmd))))
10107 (error "Abort"))))
10109 ((and (string= type "thisfile")
10110 (run-hook-with-args-until-success
10111 'org-open-link-functions path)))
10113 ((string= type "thisfile")
10114 (if arg
10115 (switch-to-buffer-other-window
10116 (org-get-buffer-for-internal-link (current-buffer)))
10117 (org-mark-ring-push))
10118 (let ((cmd `(org-link-search
10119 ,path
10120 ,(cond ((equal arg '(4)) ''occur)
10121 ((equal arg '(16)) ''org-occur))
10122 ,pos)))
10123 (condition-case nil (let ((org-link-search-inhibit-query t))
10124 (eval cmd))
10125 (error (progn (widen) (eval cmd))))))
10127 (t (browse-url-at-point)))))))
10128 (move-marker org-open-link-marker nil)
10129 (run-hook-with-args 'org-follow-link-hook)))
10131 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10132 "Offer links in the current entry and return the selected link.
10133 If there is only one link, return it.
10134 If NTH is an integer, return the NTH link found.
10135 If ZERO is a string, check also this string for a link, and if
10136 there is one, return it."
10137 (with-current-buffer buffer
10138 (save-excursion
10139 (save-restriction
10140 (widen)
10141 (goto-char marker)
10142 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10143 "\\(" org-angle-link-re "\\)\\|"
10144 "\\(" org-plain-link-re "\\)"))
10145 (cnt ?0)
10146 (in-emacs (if (integerp nth) nil nth))
10147 have-zero end links link c)
10148 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10149 (push (match-string 0 zero) links)
10150 (setq cnt (1- cnt) have-zero t))
10151 (save-excursion
10152 (org-back-to-heading t)
10153 (setq end (save-excursion (outline-next-heading) (point)))
10154 (while (re-search-forward re end t)
10155 (push (match-string 0) links))
10156 (setq links (org-uniquify (reverse links))))
10157 (cond
10158 ((null links)
10159 (message "No links"))
10160 ((equal (length links) 1)
10161 (setq link (car links)))
10162 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10163 (setq link (nth (if have-zero nth (1- nth)) links)))
10164 (t ; we have to select a link
10165 (save-excursion
10166 (save-window-excursion
10167 (delete-other-windows)
10168 (with-output-to-temp-buffer "*Select Link*"
10169 (mapc (lambda (l)
10170 (if (not (string-match org-bracket-link-regexp l))
10171 (princ (format "[%c] %s\n" (incf cnt)
10172 (org-remove-angle-brackets l)))
10173 (if (match-end 3)
10174 (princ (format "[%c] %s (%s)\n" (incf cnt)
10175 (match-string 3 l) (match-string 1 l)))
10176 (princ (format "[%c] %s\n" (incf cnt)
10177 (match-string 1 l))))))
10178 links))
10179 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10180 (message "Select link to open, RET to open all:")
10181 (setq c (read-char-exclusive))
10182 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10183 (when (equal c ?q) (error "Abort"))
10184 (if (equal c ?\C-m)
10185 (setq link links)
10186 (setq nth (- c ?0))
10187 (if have-zero (setq nth (1+ nth)))
10188 (unless (and (integerp nth) (>= (length links) nth))
10189 (error "Invalid link selection"))
10190 (setq link (nth (1- nth) links)))))
10191 (cons link end))))))
10193 ;; Add special file links that specify the way of opening
10195 (org-add-link-type "file+sys" 'org-open-file-with-system)
10196 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10197 (defun org-open-file-with-system (path)
10198 "Open file at PATH using the system way of opening it."
10199 (org-open-file path 'system))
10200 (defun org-open-file-with-emacs (path)
10201 "Open file at PATH in Emacs."
10202 (org-open-file path 'emacs))
10205 ;;; File search
10207 (defvar org-create-file-search-functions nil
10208 "List of functions to construct the right search string for a file link.
10209 These functions are called in turn with point at the location to
10210 which the link should point.
10212 A function in the hook should first test if it would like to
10213 handle this file type, for example by checking the `major-mode'
10214 or the file extension. If it decides not to handle this file, it
10215 should just return nil to give other functions a chance. If it
10216 does handle the file, it must return the search string to be used
10217 when following the link. The search string will be part of the
10218 file link, given after a double colon, and `org-open-at-point'
10219 will automatically search for it. If special measures must be
10220 taken to make the search successful, another function should be
10221 added to the companion hook `org-execute-file-search-functions',
10222 which see.
10224 A function in this hook may also use `setq' to set the variable
10225 `description' to provide a suggestion for the descriptive text to
10226 be used for this link when it gets inserted into an Org-mode
10227 buffer with \\[org-insert-link].")
10229 (defvar org-execute-file-search-functions nil
10230 "List of functions to execute a file search triggered by a link.
10232 Functions added to this hook must accept a single argument, the
10233 search string that was part of the file link, the part after the
10234 double colon. The function must first check if it would like to
10235 handle this search, for example by checking the `major-mode' or
10236 the file extension. If it decides not to handle this search, it
10237 should just return nil to give other functions a chance. If it
10238 does handle the search, it must return a non-nil value to keep
10239 other functions from trying.
10241 Each function can access the current prefix argument through the
10242 variable `current-prefix-argument'. Note that a single prefix is
10243 used to force opening a link in Emacs, so it may be good to only
10244 use a numeric or double prefix to guide the search function.
10246 In case this is needed, a function in this hook can also restore
10247 the window configuration before `org-open-at-point' was called using:
10249 (set-window-configuration org-window-config-before-follow-link)")
10251 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10252 (defun org-link-search (s &optional type avoid-pos stealth)
10253 "Search for a link search option.
10254 If S is surrounded by forward slashes, it is interpreted as a
10255 regular expression. In org-mode files, this will create an `org-occur'
10256 sparse tree. In ordinary files, `occur' will be used to list matches.
10257 If the current buffer is in `dired-mode', grep will be used to search
10258 in all files. If AVOID-POS is given, ignore matches near that position.
10260 When optional argument STEALTH is non-nil, do not modify
10261 visibility around point, thus ignoring
10262 `org-show-hierarchy-above', `org-show-following-heading' and
10263 `org-show-siblings' variables."
10264 (let ((case-fold-search t)
10265 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10266 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10267 (append '(("") (" ") ("\t") ("\n"))
10268 org-emphasis-alist)
10269 "\\|") "\\)"))
10270 (pos (point))
10271 (pre nil) (post nil)
10272 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10273 (cond
10274 ;; First check if there are any special search functions
10275 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10276 ;; Now try the builtin stuff
10277 ((and (equal (string-to-char s0) ?#)
10278 (> (length s0) 1)
10279 (save-excursion
10280 (goto-char (point-min))
10281 (and
10282 (re-search-forward
10283 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10284 (setq type 'dedicated
10285 pos (match-beginning 0))))
10286 ;; There is an exact target for this
10287 (goto-char pos)
10288 (org-back-to-heading t)))
10289 ((save-excursion
10290 (goto-char (point-min))
10291 (and
10292 (re-search-forward
10293 (concat "<<" (regexp-quote s0) ">>") nil t)
10294 (setq type 'dedicated
10295 pos (match-beginning 0))))
10296 ;; There is an exact target for this
10297 (goto-char pos))
10298 ((save-excursion
10299 (goto-char (point-min))
10300 (and
10301 (re-search-forward
10302 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10303 (setq type 'dedicated pos (match-beginning 0))))
10304 ;; Found an invisible target.
10305 (goto-char pos))
10306 ((save-excursion
10307 (goto-char (point-min))
10308 (and
10309 (re-search-forward
10310 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10311 (setq type 'dedicated pos (match-beginning 0))))
10312 ;; Found an element with a matching #+name affiliated keyword.
10313 (goto-char pos))
10314 ((and (string-match "^(\\(.*\\))$" s0)
10315 (save-excursion
10316 (goto-char (point-min))
10317 (and
10318 (re-search-forward
10319 (concat "[^[]" (regexp-quote
10320 (format org-coderef-label-format
10321 (match-string 1 s0))))
10322 nil t)
10323 (setq type 'dedicated
10324 pos (1+ (match-beginning 0))))))
10325 ;; There is a coderef target for this
10326 (goto-char pos))
10327 ((string-match "^/\\(.*\\)/$" s)
10328 ;; A regular expression
10329 (cond
10330 ((derived-mode-p 'org-mode)
10331 (org-occur (match-string 1 s)))
10332 ;;((eq major-mode 'dired-mode)
10333 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10334 (t (org-do-occur (match-string 1 s)))))
10335 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10336 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10337 (goto-char (point-min))
10338 (cond
10339 ((let (case-fold-search)
10340 (re-search-forward (format org-complex-heading-regexp-format
10341 (regexp-quote s))
10342 nil t))
10343 ;; OK, found a match
10344 (setq type 'dedicated)
10345 (goto-char (match-beginning 0)))
10346 ((and (not org-link-search-inhibit-query)
10347 (eq org-link-search-must-match-exact-headline 'query-to-create)
10348 (y-or-n-p "No match - create this as a new heading? "))
10349 (goto-char (point-max))
10350 (or (bolp) (newline))
10351 (insert "* " s "\n")
10352 (beginning-of-line 0))
10354 (goto-char pos)
10355 (error "No match"))))
10357 ;; A normal search string
10358 (when (equal (string-to-char s) ?*)
10359 ;; Anchor on headlines, post may include tags.
10360 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10361 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10362 s (substring s 1)))
10363 (remove-text-properties
10364 0 (length s)
10365 '(face nil mouse-face nil keymap nil fontified nil) s)
10366 ;; Make a series of regular expressions to find a match
10367 (setq words (org-split-string s "[ \n\r\t]+")
10369 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10370 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10371 "\\)" markers)
10372 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10373 re2a (concat "[ \t\r\n]" re2a_)
10374 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10375 re4 (concat "[^a-zA-Z_]" re4_)
10377 re1 (concat pre re2 post)
10378 re3 (concat pre (if pre re4_ re4) post)
10379 re5 (concat pre ".*" re4)
10380 re2 (concat pre re2)
10381 re2a (concat pre (if pre re2a_ re2a))
10382 re4 (concat pre (if pre re4_ re4))
10383 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10384 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10385 re5 "\\)"
10387 (cond
10388 ((eq type 'org-occur) (org-occur reall))
10389 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10390 (t (goto-char (point-min))
10391 (setq type 'fuzzy)
10392 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10393 (org-search-not-self 1 re1 nil t)
10394 (org-search-not-self 1 re2 nil t)
10395 (org-search-not-self 1 re2a nil t)
10396 (org-search-not-self 1 re3 nil t)
10397 (org-search-not-self 1 re4 nil t)
10398 (org-search-not-self 1 re5 nil t)
10400 (goto-char (match-beginning 1))
10401 (goto-char pos)
10402 (error "No match"))))))
10403 (and (derived-mode-p 'org-mode)
10404 (not stealth)
10405 (org-show-context 'link-search))
10406 type))
10408 (defun org-search-not-self (group &rest args)
10409 "Execute `re-search-forward', but only accept matches that do not
10410 enclose the position of `org-open-link-marker'."
10411 (let ((m org-open-link-marker))
10412 (catch 'exit
10413 (while (apply 're-search-forward args)
10414 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10415 (goto-char (match-end group))
10416 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10417 (> (match-beginning 0) (marker-position m))
10418 (< (match-end 0) (marker-position m)))
10419 (save-match-data
10420 (or (not (org-in-regexp
10421 org-bracket-link-analytic-regexp 1))
10422 (not (match-end 4)) ; no description
10423 (and (<= (match-beginning 4) (point))
10424 (>= (match-end 4) (point))))))
10425 (throw 'exit (point))))))))
10427 (defun org-get-buffer-for-internal-link (buffer)
10428 "Return a buffer to be used for displaying the link target of internal links."
10429 (cond
10430 ((not org-display-internal-link-with-indirect-buffer)
10431 buffer)
10432 ((string-match "(Clone)$" (buffer-name buffer))
10433 (message "Buffer is already a clone, not making another one")
10434 ;; we also do not modify visibility in this case
10435 buffer)
10436 (t ; make a new indirect buffer for displaying the link
10437 (let* ((bn (buffer-name buffer))
10438 (ibn (concat bn "(Clone)"))
10439 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10440 (with-current-buffer ib (org-overview))
10441 ib))))
10443 (defun org-do-occur (regexp &optional cleanup)
10444 "Call the Emacs command `occur'.
10445 If CLEANUP is non-nil, remove the printout of the regular expression
10446 in the *Occur* buffer. This is useful if the regex is long and not useful
10447 to read."
10448 (occur regexp)
10449 (when cleanup
10450 (let ((cwin (selected-window)) win beg end)
10451 (when (setq win (get-buffer-window "*Occur*"))
10452 (select-window win))
10453 (goto-char (point-min))
10454 (when (re-search-forward "match[a-z]+" nil t)
10455 (setq beg (match-end 0))
10456 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10457 (setq end (1- (match-beginning 0)))))
10458 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10459 (goto-char (point-min))
10460 (select-window cwin))))
10462 ;;; The mark ring for links jumps
10464 (defvar org-mark-ring nil
10465 "Mark ring for positions before jumps in Org-mode.")
10466 (defvar org-mark-ring-last-goto nil
10467 "Last position in the mark ring used to go back.")
10468 ;; Fill and close the ring
10469 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10470 (loop for i from 1 to org-mark-ring-length do
10471 (push (make-marker) org-mark-ring))
10472 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10473 org-mark-ring)
10475 (defun org-mark-ring-push (&optional pos buffer)
10476 "Put the current position or POS into the mark ring and rotate it."
10477 (interactive)
10478 (setq pos (or pos (point)))
10479 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10480 (move-marker (car org-mark-ring)
10481 (or pos (point))
10482 (or buffer (current-buffer)))
10483 (message "%s"
10484 (substitute-command-keys
10485 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10487 (defun org-mark-ring-goto (&optional n)
10488 "Jump to the previous position in the mark ring.
10489 With prefix arg N, jump back that many stored positions. When
10490 called several times in succession, walk through the entire ring.
10491 Org-mode commands jumping to a different position in the current file,
10492 or to another Org-mode file, automatically push the old position
10493 onto the ring."
10494 (interactive "p")
10495 (let (p m)
10496 (if (eq last-command this-command)
10497 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10498 (setq p org-mark-ring))
10499 (setq org-mark-ring-last-goto p)
10500 (setq m (car p))
10501 (org-pop-to-buffer-same-window (marker-buffer m))
10502 (goto-char m)
10503 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10505 (defun org-remove-angle-brackets (s)
10506 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10507 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10509 (defun org-add-angle-brackets (s)
10510 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10511 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10513 (defun org-remove-double-quotes (s)
10514 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10515 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10518 ;;; Following specific links
10520 (defun org-follow-timestamp-link ()
10521 "Open an agenda view for the time-stamp date/range at point."
10522 (cond
10523 ((org-at-date-range-p t)
10524 (let ((org-agenda-start-on-weekday)
10525 (t1 (match-string 1))
10526 (t2 (match-string 2)) tt1 tt2)
10527 (setq tt1 (time-to-days (org-time-string-to-time t1))
10528 tt2 (time-to-days (org-time-string-to-time t2)))
10529 (let ((org-agenda-buffer-tmp-name
10530 (format "*Org Agenda(a:%s)"
10531 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10532 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10533 ((org-at-timestamp-p t)
10534 (let ((org-agenda-buffer-tmp-name
10535 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10536 (org-agenda-list nil (time-to-days (org-time-string-to-time
10537 (substring (match-string 1) 0 10)))
10538 1)))
10539 (t (error "This should not happen"))))
10542 ;;; Following file links
10543 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10544 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10545 (declare-function mailcap-mime-info
10546 "mailcap" (string &optional request no-decode))
10547 (defvar org-wait nil)
10548 (defun org-open-file (path &optional in-emacs line search)
10549 "Open the file at PATH.
10550 First, this expands any special file name abbreviations. Then the
10551 configuration variable `org-file-apps' is checked if it contains an
10552 entry for this file type, and if yes, the corresponding command is launched.
10554 If no application is found, Emacs simply visits the file.
10556 With optional prefix argument IN-EMACS, Emacs will visit the file.
10557 With a double \\[universal-argument] \\[universal-argument] \
10558 prefix arg, Org tries to avoid opening in Emacs
10559 and to use an external application to visit the file.
10561 Optional LINE specifies a line to go to, optional SEARCH a string
10562 to search for. If LINE or SEARCH is given, the file will be
10563 opened in Emacs, unless an entry from org-file-apps that makes
10564 use of groups in a regexp matches.
10566 If you want to change the way frames are used when following a
10567 link, please customize `org-link-frame-setup'.
10569 If the file does not exist, an error is thrown."
10570 (let* ((file (if (equal path "")
10571 buffer-file-name
10572 (substitute-in-file-name (expand-file-name path))))
10573 (file-apps (append org-file-apps (org-default-apps)))
10574 (apps (org-remove-if
10575 'org-file-apps-entry-match-against-dlink-p file-apps))
10576 (apps-dlink (org-remove-if-not
10577 'org-file-apps-entry-match-against-dlink-p file-apps))
10578 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10579 (dirp (if remp nil (file-directory-p file)))
10580 (file (if (and dirp org-open-directory-means-index-dot-org)
10581 (concat (file-name-as-directory file) "index.org")
10582 file))
10583 (a-m-a-p (assq 'auto-mode apps))
10584 (dfile (downcase file))
10585 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10586 (link (cond ((and (eq line nil)
10587 (eq search nil))
10588 file)
10589 (line
10590 (concat file "::" (number-to-string line)))
10591 (search
10592 (concat file "::" search))))
10593 (dlink (downcase link))
10594 (old-buffer (current-buffer))
10595 (old-pos (point))
10596 (old-mode major-mode)
10597 ext cmd link-match-data)
10598 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10599 (setq ext (match-string 1 dfile))
10600 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10601 (setq ext (match-string 1 dfile))))
10602 (cond
10603 ((member in-emacs '((16) system))
10604 (setq cmd (cdr (assoc 'system apps))))
10605 (in-emacs (setq cmd 'emacs))
10607 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10608 (and dirp (cdr (assoc 'directory apps)))
10609 ; first, try matching against apps-dlink
10610 ; if we get a match here, store the match data for later
10611 (let ((match (assoc-default dlink apps-dlink
10612 'string-match)))
10613 (if match
10614 (progn (setq link-match-data (match-data))
10615 match)
10616 (progn (setq in-emacs (or in-emacs line search))
10617 nil))) ; if we have no match in apps-dlink,
10618 ; always open the file in emacs if line or search
10619 ; is given (for backwards compatibility)
10620 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10621 'string-match)
10622 (cdr (assoc ext apps))
10623 (cdr (assoc t apps))))))
10624 (when (eq cmd 'system)
10625 (setq cmd (cdr (assoc 'system apps))))
10626 (when (eq cmd 'default)
10627 (setq cmd (cdr (assoc t apps))))
10628 (when (eq cmd 'mailcap)
10629 (require 'mailcap)
10630 (mailcap-parse-mailcaps)
10631 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10632 (command (mailcap-mime-info mime-type)))
10633 (if (stringp command)
10634 (setq cmd command)
10635 (setq cmd 'emacs))))
10636 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10637 (not (file-exists-p file))
10638 (not org-open-non-existing-files))
10639 (error "No such file: %s" file))
10640 (cond
10641 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10642 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10643 (while (string-match "['\"]%s['\"]" cmd)
10644 (setq cmd (replace-match "%s" t t cmd)))
10645 (while (string-match "%s" cmd)
10646 (setq cmd (replace-match
10647 (save-match-data
10648 (shell-quote-argument
10649 (convert-standard-filename file)))
10650 t t cmd)))
10652 ;; Replace "%1", "%2" etc. in command with group matches from regex
10653 (save-match-data
10654 (let ((match-index 1)
10655 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10656 (set-match-data link-match-data)
10657 (while (<= match-index number-of-groups)
10658 (let ((regex (concat "%" (number-to-string match-index)))
10659 (replace-with (match-string match-index dlink)))
10660 (while (string-match regex cmd)
10661 (setq cmd (replace-match replace-with t t cmd))))
10662 (setq match-index (+ match-index 1)))))
10664 (save-window-excursion
10665 (message "Running %s...done" cmd)
10666 (start-process-shell-command cmd nil cmd)
10667 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10668 ((or (stringp cmd)
10669 (eq cmd 'emacs))
10670 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10671 (widen)
10672 (if line (org-goto-line line)
10673 (if search (org-link-search search))))
10674 ((consp cmd)
10675 (let ((file (convert-standard-filename file)))
10676 (save-match-data
10677 (set-match-data link-match-data)
10678 (eval cmd))))
10679 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10680 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10681 (or (not (equal old-buffer (current-buffer)))
10682 (not (equal old-pos (point))))
10683 (org-mark-ring-push old-pos old-buffer))))
10685 (defun org-file-apps-entry-match-against-dlink-p (entry)
10686 "This function returns non-nil if `entry' uses a regular
10687 expression which should be matched against the whole link by
10688 org-open-file.
10690 It assumes that is the case when the entry uses a regular
10691 expression which has at least one grouping construct and the
10692 action is either a lisp form or a command string containing
10693 '%1', i.e. using at least one subexpression match as a
10694 parameter."
10695 (let ((selector (car entry))
10696 (action (cdr entry)))
10697 (if (stringp selector)
10698 (and (> (regexp-opt-depth selector) 0)
10699 (or (and (stringp action)
10700 (string-match "%[0-9]" action))
10701 (consp action)))
10702 nil)))
10704 (defun org-default-apps ()
10705 "Return the default applications for this operating system."
10706 (cond
10707 ((eq system-type 'darwin)
10708 org-file-apps-defaults-macosx)
10709 ((eq system-type 'windows-nt)
10710 org-file-apps-defaults-windowsnt)
10711 (t org-file-apps-defaults-gnu)))
10713 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10714 "Convert extensions to regular expressions in the cars of LIST.
10715 Also, weed out any non-string entries, because the return value is used
10716 only for regexp matching.
10717 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10718 point to the symbol `emacs', indicating that the file should
10719 be opened in Emacs."
10720 (append
10721 (delq nil
10722 (mapcar (lambda (x)
10723 (if (not (stringp (car x)))
10725 (if (string-match "\\W" (car x))
10727 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10728 list))
10729 (if add-auto-mode
10730 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10732 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10733 (defun org-file-remote-p (file)
10734 "Test whether FILE specifies a location on a remote system.
10735 Return non-nil if the location is indeed remote.
10737 For example, the filename \"/user@host:/foo\" specifies a location
10738 on the system \"/user@host:\"."
10739 (cond ((fboundp 'file-remote-p)
10740 (file-remote-p file))
10741 ((fboundp 'tramp-handle-file-remote-p)
10742 (tramp-handle-file-remote-p file))
10743 ((and (boundp 'ange-ftp-name-format)
10744 (string-match (car ange-ftp-name-format) file))
10745 t)))
10748 ;;;; Refiling
10750 (defun org-get-org-file ()
10751 "Read a filename, with default directory `org-directory'."
10752 (let ((default (or org-default-notes-file remember-data-file)))
10753 (read-file-name (format "File name [%s]: " default)
10754 (file-name-as-directory org-directory)
10755 default)))
10757 (defun org-notes-order-reversed-p ()
10758 "Check if the current file should receive notes in reversed order."
10759 (cond
10760 ((not org-reverse-note-order) nil)
10761 ((eq t org-reverse-note-order) t)
10762 ((not (listp org-reverse-note-order)) nil)
10763 (t (catch 'exit
10764 (let ((all org-reverse-note-order)
10765 entry)
10766 (while (setq entry (pop all))
10767 (if (string-match (car entry) buffer-file-name)
10768 (throw 'exit (cdr entry))))
10769 nil)))))
10771 (defvar org-refile-target-table nil
10772 "The list of refile targets, created by `org-refile'.")
10774 (defvar org-agenda-new-buffers nil
10775 "Buffers created to visit agenda files.")
10777 (defvar org-refile-cache nil
10778 "Cache for refile targets.")
10780 (defvar org-refile-markers nil
10781 "All the markers used for caching refile locations.")
10783 (defun org-refile-marker (pos)
10784 "Get a new refile marker, but only if caching is in use."
10785 (if (not org-refile-use-cache)
10787 (let ((m (make-marker)))
10788 (move-marker m pos)
10789 (push m org-refile-markers)
10790 m)))
10792 (defun org-refile-cache-clear ()
10793 "Clear the refile cache and disable all the markers."
10794 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10795 (setq org-refile-markers nil)
10796 (setq org-refile-cache nil)
10797 (message "Refile cache has been cleared"))
10799 (defun org-refile-cache-check-set (set)
10800 "Check if all the markers in the cache still have live buffers."
10801 (let (marker)
10802 (catch 'exit
10803 (while (and set (setq marker (nth 3 (pop set))))
10804 ;; if org-refile-use-outline-path is 'file, marker may be nil
10805 (when (and marker (null (marker-buffer marker)))
10806 (message "not found") (sit-for 3)
10807 (throw 'exit nil)))
10808 t)))
10810 (defun org-refile-cache-put (set &rest identifiers)
10811 "Push the refile targets SET into the cache, under IDENTIFIERS."
10812 (let* ((key (sha1 (prin1-to-string identifiers)))
10813 (entry (assoc key org-refile-cache)))
10814 (if entry
10815 (setcdr entry set)
10816 (push (cons key set) org-refile-cache))))
10818 (defun org-refile-cache-get (&rest identifiers)
10819 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10820 (cond
10821 ((not org-refile-cache) nil)
10822 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10824 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10825 org-refile-cache))))
10826 (and set (org-refile-cache-check-set set) set)))))
10828 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10829 "Produce a table with refile targets."
10830 (let ((case-fold-search nil)
10831 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10832 (entries (or org-refile-targets '((nil . (:level . 1)))))
10833 targets tgs txt re files f desc descre fast-path-p level pos0)
10834 (message "Getting targets...")
10835 (with-current-buffer (or default-buffer (current-buffer))
10836 (while (setq entry (pop entries))
10837 (setq files (car entry) desc (cdr entry))
10838 (setq fast-path-p nil)
10839 (cond
10840 ((null files) (setq files (list (current-buffer))))
10841 ((eq files 'org-agenda-files)
10842 (setq files (org-agenda-files 'unrestricted)))
10843 ((and (symbolp files) (fboundp files))
10844 (setq files (funcall files)))
10845 ((and (symbolp files) (boundp files))
10846 (setq files (symbol-value files))))
10847 (if (stringp files) (setq files (list files)))
10848 (cond
10849 ((eq (car desc) :tag)
10850 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10851 ((eq (car desc) :todo)
10852 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10853 ((eq (car desc) :regexp)
10854 (setq descre (cdr desc)))
10855 ((eq (car desc) :level)
10856 (setq descre (concat "^\\*\\{" (number-to-string
10857 (if org-odd-levels-only
10858 (1- (* 2 (cdr desc)))
10859 (cdr desc)))
10860 "\\}[ \t]")))
10861 ((eq (car desc) :maxlevel)
10862 (setq fast-path-p t)
10863 (setq descre (concat "^\\*\\{1," (number-to-string
10864 (if org-odd-levels-only
10865 (1- (* 2 (cdr desc)))
10866 (cdr desc)))
10867 "\\}[ \t]")))
10868 (t (error "Bad refiling target description %s" desc)))
10869 (while (setq f (pop files))
10870 (with-current-buffer
10871 (if (bufferp f) f (org-get-agenda-file-buffer f))
10873 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10874 (progn
10875 (if (bufferp f) (setq f (buffer-file-name
10876 (buffer-base-buffer f))))
10877 (setq f (and f (expand-file-name f)))
10878 (if (eq org-refile-use-outline-path 'file)
10879 (push (list (file-name-nondirectory f) f nil nil) tgs))
10880 (save-excursion
10881 (save-restriction
10882 (widen)
10883 (goto-char (point-min))
10884 (while (re-search-forward descre nil t)
10885 (goto-char (setq pos0 (point-at-bol)))
10886 (catch 'next
10887 (when org-refile-target-verify-function
10888 (save-match-data
10889 (or (funcall org-refile-target-verify-function)
10890 (throw 'next t))))
10891 (when (and (looking-at org-complex-heading-regexp)
10892 (not (member (match-string 4) excluded-entries))
10893 (match-string 4))
10894 (setq level (org-reduced-level
10895 (- (match-end 1) (match-beginning 1)))
10896 txt (org-link-display-format (match-string 4))
10897 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10898 re (format org-complex-heading-regexp-format
10899 (regexp-quote (match-string 4))))
10900 (when org-refile-use-outline-path
10901 (setq txt (mapconcat
10902 'org-protect-slash
10903 (append
10904 (if (eq org-refile-use-outline-path
10905 'file)
10906 (list (file-name-nondirectory
10907 (buffer-file-name
10908 (buffer-base-buffer))))
10909 (if (eq org-refile-use-outline-path
10910 'full-file-path)
10911 (list (buffer-file-name
10912 (buffer-base-buffer)))))
10913 (org-get-outline-path fast-path-p
10914 level txt)
10915 (list txt))
10916 "/")))
10917 (push (list txt f re (org-refile-marker (point)))
10918 tgs)))
10919 (when (= (point) pos0)
10920 ;; verification function has not moved point
10921 (goto-char (point-at-eol))))))))
10922 (when org-refile-use-cache
10923 (org-refile-cache-put tgs (buffer-file-name) descre))
10924 (setq targets (append tgs targets))
10925 ))))
10926 (message "Getting targets...done")
10927 (nreverse targets)))
10929 (defun org-protect-slash (s)
10930 (while (string-match "/" s)
10931 (setq s (replace-match "\\" t t s)))
10934 (defvar org-olpa (make-vector 20 nil))
10936 (defun org-get-outline-path (&optional fastp level heading)
10937 "Return the outline path to the current entry, as a list.
10939 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10940 routine which makes outline path derivations for an entire file,
10941 avoiding backtracing. Refile target collection makes use of that."
10942 (if fastp
10943 (progn
10944 (if (> level 19)
10945 (error "Outline path failure, more than 19 levels"))
10946 (loop for i from level upto 19 do
10947 (aset org-olpa i nil))
10948 (prog1
10949 (delq nil (append org-olpa nil))
10950 (aset org-olpa level heading)))
10951 (let (rtn case-fold-search)
10952 (save-excursion
10953 (save-restriction
10954 (widen)
10955 (while (org-up-heading-safe)
10956 (when (looking-at org-complex-heading-regexp)
10957 (push (org-match-string-no-properties 4) rtn)))
10958 rtn)))))
10960 (defun org-format-outline-path (path &optional width prefix separator)
10961 "Format the outline path PATH for display.
10962 WIDTH is the maximum number of characters that is available.
10963 PREFIX is a prefix to be included in the returned string,
10964 such as the file name.
10965 SEPARATOR is inserted between the different parts of the path,
10966 the default is \"/\"."
10967 (setq width (or width 79))
10968 (if prefix (setq width (- width (length prefix))))
10969 (if (not path)
10970 (or prefix "")
10971 (let* ((nsteps (length path))
10972 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10973 (maxwidth (if (<= total-width width)
10974 10000 ;; everything fits
10975 ;; we need to shorten the level headings
10976 (/ (- width nsteps) nsteps)))
10977 (org-odd-levels-only nil)
10978 (n 0)
10979 (total (1+ (length prefix))))
10980 (setq maxwidth (max maxwidth 10))
10981 (concat prefix
10982 (if prefix (or separator "/"))
10983 (mapconcat
10984 (lambda (h)
10985 (setq n (1+ n))
10986 (if (and (= n nsteps) (< maxwidth 10000))
10987 (setq maxwidth (- total-width total)))
10988 (if (< (length h) maxwidth)
10989 (progn (setq total (+ total (length h) 1)) h)
10990 (setq h (substring h 0 (- maxwidth 2))
10991 total (+ total maxwidth 1))
10992 (if (string-match "[ \t]+\\'" h)
10993 (setq h (substring h 0 (match-beginning 0))))
10994 (setq h (concat h "..")))
10995 (org-add-props h nil 'face
10996 (nth (% (1- n) org-n-level-faces)
10997 org-level-faces))
10999 path (or separator "/"))))))
11001 (defun org-display-outline-path (&optional file current separator just-return-string)
11002 "Display the current outline path in the echo area.
11004 If FILE is non-nil, prepend the output with the file name.
11005 If CURRENT is non-nil, append the current heading to the output.
11006 SEPARATOR is passed through to `org-format-outline-path'. It separates
11007 the different parts of the path and defaults to \"/\".
11008 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11009 (interactive "P")
11010 (let* (case-fold-search
11011 message-log-max ; Don't populate the *Messages* buffer
11012 (bfn (buffer-file-name (buffer-base-buffer)))
11013 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11014 res)
11015 (if current (setq path (append path
11016 (save-excursion
11017 (org-back-to-heading t)
11018 (if (looking-at org-complex-heading-regexp)
11019 (list (match-string 4)))))))
11020 (setq res
11021 (org-format-outline-path
11022 path
11023 (1- (frame-width))
11024 (and file bfn (concat (file-name-nondirectory bfn) separator))
11025 separator))
11026 (if just-return-string
11027 (org-no-properties res)
11028 (message "%s" res))))
11030 (defvar org-refile-history nil
11031 "History for refiling operations.")
11033 (defvar org-after-refile-insert-hook nil
11034 "Hook run after `org-refile' has inserted its stuff at the new location.
11035 Note that this is still *before* the stuff will be removed from
11036 the *old* location.")
11038 (defvar org-capture-last-stored-marker)
11039 (defvar org-refile-keep nil
11040 "Non-nil means `org-refile' will copy instead of refile.")
11042 (defun org-copy ()
11043 "Like `org-refile', but copy."
11044 (interactive)
11045 (let ((org-refile-keep t))
11046 (funcall 'org-refile nil nil nil "Copy")))
11048 (defun org-refile (&optional goto default-buffer rfloc msg)
11049 "Move the entry or entries at point to another heading.
11050 The list of target headings is compiled using the information in
11051 `org-refile-targets', which see.
11053 At the target location, the entry is filed as a subitem of the target
11054 heading. Depending on `org-reverse-note-order', the new subitem will
11055 either be the first or the last subitem.
11057 If there is an active region, all entries in that region will be moved.
11058 However, the region must fulfill the requirement that the first heading
11059 is the first one sets the top-level of the moved text - at most siblings
11060 below it are allowed.
11062 With prefix arg GOTO, the command will only visit the target location
11063 and not actually move anything.
11065 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11066 go to the location where the last refiling operation has put the subtree.
11067 With a prefix argument of `2', refile to the running clock.
11069 RFLOC can be a refile location obtained in a different way.
11071 MSG is a string to replace \"Refile\" in the default prompt with
11072 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11074 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11076 If you are using target caching (see `org-refile-use-cache'),
11077 you have to clear the target cache in order to find new targets.
11078 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11079 prefix argument (`C-u C-u C-u C-c C-w')."
11081 (interactive "P")
11082 (if (member goto '(0 (64)))
11083 (org-refile-cache-clear)
11084 (let* ((actionmsg (or msg "Refile"))
11085 (cbuf (current-buffer))
11086 (regionp (org-region-active-p))
11087 (region-start (and regionp (region-beginning)))
11088 (region-end (and regionp (region-end)))
11089 (region-length (and regionp (- region-end region-start)))
11090 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11091 pos it nbuf file re level reversed)
11092 (setq last-command nil)
11093 (when regionp
11094 (goto-char region-start)
11095 (or (bolp) (goto-char (point-at-bol)))
11096 (setq region-start (point))
11097 (unless (or (org-kill-is-subtree-p
11098 (buffer-substring region-start region-end))
11099 (prog1 org-refile-active-region-within-subtree
11100 (org-toggle-heading)))
11101 (error "The region is not a (sequence of) subtree(s)")))
11102 (if (equal goto '(16))
11103 (org-refile-goto-last-stored)
11104 (when (or
11105 (and (equal goto 2)
11106 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11107 (prog1
11108 (setq it (list (or org-clock-heading "running clock")
11109 (buffer-file-name
11110 (marker-buffer org-clock-hd-marker))
11112 (marker-position org-clock-hd-marker)))
11113 (setq goto nil)))
11114 (setq it (or rfloc
11115 (let (heading-text)
11116 (save-excursion
11117 (unless goto
11118 (org-back-to-heading t)
11119 (setq heading-text
11120 (nth 4 (org-heading-components))))
11122 (org-refile-get-location
11123 (cond (goto "Goto")
11124 (regionp (concat actionmsg " region to"))
11125 (t (concat actionmsg " subtree \""
11126 heading-text "\" to")))
11127 default-buffer
11128 (and (not (equal '(4) goto))
11129 org-refile-allow-creating-parent-nodes)
11130 goto))))))
11131 (setq file (nth 1 it)
11132 re (nth 2 it)
11133 pos (nth 3 it))
11134 (if (and (not goto)
11136 (equal (buffer-file-name) file)
11137 (if regionp
11138 (and (>= pos region-start)
11139 (<= pos region-end))
11140 (and (>= pos (point))
11141 (< pos (save-excursion
11142 (org-end-of-subtree t t))))))
11143 (error "Cannot refile to position inside the tree or region"))
11145 (setq nbuf (or (find-buffer-visiting file)
11146 (find-file-noselect file)))
11147 (if goto
11148 (progn
11149 (org-pop-to-buffer-same-window nbuf)
11150 (goto-char pos)
11151 (org-show-context 'org-goto))
11152 (if regionp
11153 (progn
11154 (org-kill-new (buffer-substring region-start region-end))
11155 (org-save-markers-in-region region-start region-end))
11156 (org-copy-subtree 1 nil t))
11157 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11158 (find-file-noselect file)))
11159 (setq reversed (org-notes-order-reversed-p))
11160 (save-excursion
11161 (save-restriction
11162 (widen)
11163 (if pos
11164 (progn
11165 (goto-char pos)
11166 (looking-at org-outline-regexp)
11167 (setq level (org-get-valid-level (funcall outline-level) 1))
11168 (goto-char
11169 (if reversed
11170 (or (outline-next-heading) (point-max))
11171 (or (save-excursion (org-get-next-sibling))
11172 (org-end-of-subtree t t)
11173 (point-max)))))
11174 (setq level 1)
11175 (if (not reversed)
11176 (goto-char (point-max))
11177 (goto-char (point-min))
11178 (or (outline-next-heading) (goto-char (point-max)))))
11179 (if (not (bolp)) (newline))
11180 (org-paste-subtree level)
11181 (when org-log-refile
11182 (org-add-log-setup 'refile nil nil 'findpos
11183 org-log-refile)
11184 (unless (eq org-log-refile 'note)
11185 (save-excursion (org-add-log-note))))
11186 (and org-auto-align-tags
11187 (let ((org-loop-over-headlines-in-active-region nil))
11188 (org-set-tags nil t)))
11189 (with-demoted-errors
11190 (bookmark-set "org-refile-last-stored"))
11191 ;; If we are refiling for capture, make sure that the
11192 ;; last-capture pointers point here
11193 (when (org-bound-and-true-p org-refile-for-capture)
11194 (with-demoted-errors
11195 (bookmark-set "org-capture-last-stored-marker"))
11196 (move-marker org-capture-last-stored-marker (point)))
11197 (if (fboundp 'deactivate-mark) (deactivate-mark))
11198 (run-hooks 'org-after-refile-insert-hook))))
11199 (unless org-refile-keep
11200 (if regionp
11201 (delete-region (point) (+ (point) region-length))
11202 (org-cut-subtree)))
11203 (when (featurep 'org-inlinetask)
11204 (org-inlinetask-remove-END-maybe))
11205 (setq org-markers-to-move nil)
11206 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11208 (defun org-refile-goto-last-stored ()
11209 "Go to the location where the last refile was stored."
11210 (interactive)
11211 (bookmark-jump "org-refile-last-stored")
11212 (message "This is the location of the last refile"))
11214 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11215 no-exclude)
11216 "Prompt the user for a refile location, using PROMPT.
11217 PROMPT should not be suffixed with a colon and a space, because
11218 this function appends the default value from
11219 `org-refile-history' automatically, if that is not empty.
11220 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11221 this is used for the GOTO interface."
11222 (let ((org-refile-targets org-refile-targets)
11223 (org-refile-use-outline-path org-refile-use-outline-path)
11224 excluded-entries)
11225 (when (and (derived-mode-p 'org-mode)
11226 (not org-refile-use-cache)
11227 (not no-exclude))
11228 (org-map-tree
11229 (lambda()
11230 (setq excluded-entries
11231 (append excluded-entries (list (org-get-heading t t)))))))
11232 (setq org-refile-target-table
11233 (org-refile-get-targets default-buffer excluded-entries)))
11234 (unless org-refile-target-table
11235 (error "No refile targets"))
11236 (let* ((cbuf (current-buffer))
11237 (partial-completion-mode nil)
11238 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11239 (cfunc (if (and org-refile-use-outline-path
11240 org-outline-path-complete-in-steps)
11241 'org-olpath-completing-read
11242 'org-icompleting-read))
11243 (extra (if org-refile-use-outline-path "/" ""))
11244 (cbnex (concat (buffer-name) extra))
11245 (filename (and cfn (expand-file-name cfn)))
11246 (tbl (mapcar
11247 (lambda (x)
11248 (if (and (not (member org-refile-use-outline-path
11249 '(file full-file-path)))
11250 (not (equal filename (nth 1 x))))
11251 (cons (concat (car x) extra " ("
11252 (file-name-nondirectory (nth 1 x)) ")")
11253 (cdr x))
11254 (cons (concat (car x) extra) (cdr x))))
11255 org-refile-target-table))
11256 (completion-ignore-case t)
11257 cdef
11258 (prompt (concat prompt
11259 (or (and (car org-refile-history)
11260 (concat " (default " (car org-refile-history) ")"))
11261 (and (assoc cbnex tbl) (setq cdef cbnex)
11262 (concat " (default " cbnex ")"))) ": "))
11263 pa answ parent-target child parent old-hist)
11264 (setq old-hist org-refile-history)
11265 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11266 nil 'org-refile-history (or cdef (car org-refile-history))))
11267 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11268 (org-refile-check-position pa)
11269 (if pa
11270 (progn
11271 (when (or (not org-refile-history)
11272 (not (eq old-hist org-refile-history))
11273 (not (equal (car pa) (car org-refile-history))))
11274 (setq org-refile-history
11275 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11276 org-refile-history
11277 (cdr org-refile-history))))
11278 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11279 (pop org-refile-history)))
11281 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11282 (progn
11283 (setq parent (match-string 1 answ)
11284 child (match-string 2 answ))
11285 (setq parent-target (or (assoc parent tbl)
11286 (assoc (concat parent "/") tbl)))
11287 (when (and parent-target
11288 (or (eq new-nodes t)
11289 (and (eq new-nodes 'confirm)
11290 (y-or-n-p (format "Create new node \"%s\"? "
11291 child)))))
11292 (org-refile-new-child parent-target child)))
11293 (error "Invalid target location")))))
11295 (declare-function org-string-nw-p "org-macs" (s))
11296 (defun org-refile-check-position (refile-pointer)
11297 "Check if the refile pointer matches the headline to which it points."
11298 (let* ((file (nth 1 refile-pointer))
11299 (re (nth 2 refile-pointer))
11300 (pos (nth 3 refile-pointer))
11301 buffer)
11302 (if (and (not (markerp pos)) (not file))
11303 (error "Please save the buffer to a file before refiling")
11304 (when (org-string-nw-p re)
11305 (setq buffer (if (markerp pos)
11306 (marker-buffer pos)
11307 (or (find-buffer-visiting file)
11308 (find-file-noselect file))))
11309 (with-current-buffer buffer
11310 (save-excursion
11311 (save-restriction
11312 (widen)
11313 (goto-char pos)
11314 (beginning-of-line 1)
11315 (unless (org-looking-at-p re)
11316 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11318 (defun org-refile-new-child (parent-target child)
11319 "Use refile target PARENT-TARGET to add new CHILD below it."
11320 (unless parent-target
11321 (error "Cannot find parent for new node"))
11322 (let ((file (nth 1 parent-target))
11323 (pos (nth 3 parent-target))
11324 level)
11325 (with-current-buffer (or (find-buffer-visiting file)
11326 (find-file-noselect file))
11327 (save-excursion
11328 (save-restriction
11329 (widen)
11330 (if pos
11331 (goto-char pos)
11332 (goto-char (point-max))
11333 (if (not (bolp)) (newline)))
11334 (when (looking-at org-outline-regexp)
11335 (setq level (funcall outline-level))
11336 (org-end-of-subtree t t))
11337 (org-back-over-empty-lines)
11338 (insert "\n" (make-string
11339 (if pos (org-get-valid-level level 1) 1) ?*)
11340 " " child "\n")
11341 (beginning-of-line 0)
11342 (list (concat (car parent-target) "/" child) file "" (point)))))))
11344 (defun org-olpath-completing-read (prompt collection &rest args)
11345 "Read an outline path like a file name."
11346 (let ((thetable collection)
11347 (org-completion-use-ido nil) ; does not work with ido.
11348 (org-completion-use-iswitchb nil)) ; or iswitchb
11349 (apply
11350 'org-icompleting-read prompt
11351 (lambda (string predicate &optional flag)
11352 (let (rtn r f (l (length string)))
11353 (cond
11354 ((eq flag nil)
11355 ;; try completion
11356 (try-completion string thetable))
11357 ((eq flag t)
11358 ;; all-completions
11359 (setq rtn (all-completions string thetable predicate))
11360 (mapcar
11361 (lambda (x)
11362 (setq r (substring x l))
11363 (if (string-match " ([^)]*)$" x)
11364 (setq f (match-string 0 x))
11365 (setq f ""))
11366 (if (string-match "/" r)
11367 (concat string (substring r 0 (match-end 0)) f)
11369 rtn))
11370 ((eq flag 'lambda)
11371 ;; exact match?
11372 (assoc string thetable)))))
11373 args)))
11375 ;;;; Dynamic blocks
11377 (defun org-find-dblock (name)
11378 "Find the first dynamic block with name NAME in the buffer.
11379 If not found, stay at current position and return nil."
11380 (let ((case-fold-search t) pos)
11381 (save-excursion
11382 (goto-char (point-min))
11383 (setq pos (and (re-search-forward
11384 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11385 (match-beginning 0))))
11386 (if pos (goto-char pos))
11387 pos))
11389 (defconst org-dblock-start-re
11390 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11391 "Matches the start line of a dynamic block, with parameters.")
11393 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11394 "Matches the end of a dynamic block.")
11396 (defun org-create-dblock (plist)
11397 "Create a dynamic block section, with parameters taken from PLIST.
11398 PLIST must contain a :name entry which is used as name of the block."
11399 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11400 (end-of-line 1)
11401 (newline))
11402 (let ((col (current-column))
11403 (name (plist-get plist :name)))
11404 (insert "#+BEGIN: " name)
11405 (while plist
11406 (if (eq (car plist) :name)
11407 (setq plist (cddr plist))
11408 (insert " " (prin1-to-string (pop plist)))))
11409 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11410 (beginning-of-line -2)))
11412 (defun org-prepare-dblock ()
11413 "Prepare dynamic block for refresh.
11414 This empties the block, puts the cursor at the insert position and returns
11415 the property list including an extra property :name with the block name."
11416 (unless (looking-at org-dblock-start-re)
11417 (error "Not at a dynamic block"))
11418 (let* ((begdel (1+ (match-end 0)))
11419 (name (org-no-properties (match-string 1)))
11420 (params (append (list :name name)
11421 (read (concat "(" (match-string 3) ")")))))
11422 (save-excursion
11423 (beginning-of-line 1)
11424 (skip-chars-forward " \t")
11425 (setq params (plist-put params :indentation-column (current-column))))
11426 (unless (re-search-forward org-dblock-end-re nil t)
11427 (error "Dynamic block not terminated"))
11428 (setq params
11429 (append params
11430 (list :content (buffer-substring
11431 begdel (match-beginning 0)))))
11432 (delete-region begdel (match-beginning 0))
11433 (goto-char begdel)
11434 (open-line 1)
11435 params))
11437 (defun org-map-dblocks (&optional command)
11438 "Apply COMMAND to all dynamic blocks in the current buffer.
11439 If COMMAND is not given, use `org-update-dblock'."
11440 (let ((cmd (or command 'org-update-dblock)))
11441 (save-excursion
11442 (goto-char (point-min))
11443 (while (re-search-forward org-dblock-start-re nil t)
11444 (goto-char (match-beginning 0))
11445 (save-excursion
11446 (condition-case nil
11447 (funcall cmd)
11448 (error (message "Error during update of dynamic block"))))
11449 (unless (re-search-forward org-dblock-end-re nil t)
11450 (error "Dynamic block not terminated"))))))
11452 (defun org-dblock-update (&optional arg)
11453 "User command for updating dynamic blocks.
11454 Update the dynamic block at point. With prefix ARG, update all dynamic
11455 blocks in the buffer."
11456 (interactive "P")
11457 (if arg
11458 (org-update-all-dblocks)
11459 (or (looking-at org-dblock-start-re)
11460 (org-beginning-of-dblock))
11461 (org-update-dblock)))
11463 (defun org-update-dblock ()
11464 "Update the dynamic block at point.
11465 This means to empty the block, parse for parameters and then call
11466 the correct writing function."
11467 (interactive)
11468 (save-window-excursion
11469 (let* ((pos (point))
11470 (line (org-current-line))
11471 (params (org-prepare-dblock))
11472 (name (plist-get params :name))
11473 (indent (plist-get params :indentation-column))
11474 (cmd (intern (concat "org-dblock-write:" name))))
11475 (message "Updating dynamic block `%s' at line %d..." name line)
11476 (funcall cmd params)
11477 (message "Updating dynamic block `%s' at line %d...done" name line)
11478 (goto-char pos)
11479 (when (and indent (> indent 0))
11480 (setq indent (make-string indent ?\ ))
11481 (save-excursion
11482 (org-beginning-of-dblock)
11483 (forward-line 1)
11484 (while (not (looking-at org-dblock-end-re))
11485 (insert indent)
11486 (beginning-of-line 2))
11487 (when (looking-at org-dblock-end-re)
11488 (and (looking-at "[ \t]+")
11489 (replace-match ""))
11490 (insert indent)))))))
11492 (defun org-beginning-of-dblock ()
11493 "Find the beginning of the dynamic block at point.
11494 Error if there is no such block at point."
11495 (let ((pos (point))
11496 beg)
11497 (end-of-line 1)
11498 (if (and (re-search-backward org-dblock-start-re nil t)
11499 (setq beg (match-beginning 0))
11500 (re-search-forward org-dblock-end-re nil t)
11501 (> (match-end 0) pos))
11502 (goto-char beg)
11503 (goto-char pos)
11504 (error "Not in a dynamic block"))))
11506 (defun org-update-all-dblocks ()
11507 "Update all dynamic blocks in the buffer.
11508 This function can be used in a hook."
11509 (interactive)
11510 (when (derived-mode-p 'org-mode)
11511 (org-map-dblocks 'org-update-dblock)))
11514 ;;;; Completion
11516 (defun org-get-export-keywords ()
11517 "Return a list of all currently understood export keywords.
11518 Export keywords include options, block names, attributes and
11519 keywords relative to each registered export back-end."
11520 (delq nil
11521 (let (keywords)
11522 (mapc
11523 (lambda (back-end)
11524 (let ((props (cdr back-end)))
11525 ;; Back-end name (for keywords, like #+LATEX:)
11526 (push (upcase (symbol-name (car back-end))) keywords)
11527 ;; Back-end options.
11528 (mapc (lambda (option) (push (cadr option) keywords))
11529 (plist-get (cdr back-end) :options-alist))))
11530 (org-bound-and-true-p org-export-registered-backends))
11531 keywords)))
11533 (defconst org-options-keywords
11534 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11535 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11536 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11537 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11538 "TITLE:" "TODO:" "TYP_TODO:"))
11540 (defcustom org-structure-template-alist
11541 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11542 "<src lang=\"?\">\n\n</src>")
11543 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11544 "<example>\n?\n</example>")
11545 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11546 "<quote>\n?\n</quote>")
11547 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11548 "<verse>\n?\n</verse>")
11549 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11550 "<verbatim>\n?\n</verbatim>")
11551 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11552 "<center>\n?\n</center>")
11553 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11554 "<literal style=\"latex\">\n?\n</literal>")
11555 ("L" "#+LaTeX: "
11556 "<literal style=\"latex\">?</literal>")
11557 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11558 "<literal style=\"html\">\n?\n</literal>")
11559 ("H" "#+HTML: "
11560 "<literal style=\"html\">?</literal>")
11561 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11562 ("A" "#+ASCII: ")
11563 ("i" "#+INDEX: ?"
11564 "#+INDEX: ?")
11565 ("I" "#+INCLUDE: %file ?"
11566 "<include file=%file markup=\"?\">"))
11567 "Structure completion elements.
11568 This is a list of abbreviation keys and values. The value gets inserted
11569 if you type `<' followed by the key and then press the completion key,
11570 usually `M-TAB'. %file will be replaced by a file name after prompting
11571 for the file using completion. The cursor will be placed at the position
11572 of the `?` in the template.
11573 There are two templates for each key, the first uses the original Org syntax,
11574 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11575 the default when the /org-mtags.el/ module has been loaded. See also the
11576 variable `org-mtags-prefer-muse-templates'."
11577 :group 'org-completion
11578 :type '(repeat
11579 (string :tag "Key")
11580 (string :tag "Template")
11581 (string :tag "Muse Template")))
11583 (defun org-try-structure-completion ()
11584 "Try to complete a structure template before point.
11585 This looks for strings like \"<e\" on an otherwise empty line and
11586 expands them."
11587 (let ((l (buffer-substring (point-at-bol) (point)))
11589 (when (and (looking-at "[ \t]*$")
11590 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11591 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11592 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11593 (match-beginning 1)) a)
11594 t)))
11596 (defun org-complete-expand-structure-template (start cell)
11597 "Expand a structure template."
11598 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11599 (rpl (nth (if musep 2 1) cell))
11600 (ind ""))
11601 (delete-region start (point))
11602 (when (string-match "\\`#\\+" rpl)
11603 (cond
11604 ((bolp))
11605 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11606 (setq ind (buffer-substring (point-at-bol) (point))))
11607 (t (newline))))
11608 (setq start (point))
11609 (if (string-match "%file" rpl)
11610 (setq rpl (replace-match
11611 (concat
11612 "\""
11613 (save-match-data
11614 (abbreviate-file-name (read-file-name "Include file: ")))
11615 "\"")
11616 t t rpl)))
11617 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11618 (concat "\n" ind)))
11619 (insert rpl)
11620 (if (re-search-backward "\\?" start t) (delete-char 1))))
11622 ;;;; TODO, DEADLINE, Comments
11624 (defun org-toggle-comment ()
11625 "Change the COMMENT state of an entry."
11626 (interactive)
11627 (save-excursion
11628 (org-back-to-heading)
11629 (let (case-fold-search)
11630 (cond
11631 ((looking-at (format org-heading-keyword-regexp-format
11632 org-comment-string))
11633 (goto-char (match-end 1))
11634 (looking-at (concat " +" org-comment-string))
11635 (replace-match "" t t)
11636 (when (eolp) (insert " ")))
11637 ((looking-at org-outline-regexp)
11638 (goto-char (match-end 0))
11639 (insert org-comment-string " "))))))
11641 (defvar org-last-todo-state-is-todo nil
11642 "This is non-nil when the last TODO state change led to a TODO state.
11643 If the last change removed the TODO tag or switched to DONE, then
11644 this is nil.")
11646 (defvar org-setting-tags nil) ; dynamically skipped
11648 (defvar org-todo-setup-filter-hook nil
11649 "Hook for functions that pre-filter todo specs.
11650 Each function takes a todo spec and returns either nil or the spec
11651 transformed into canonical form." )
11653 (defvar org-todo-get-default-hook nil
11654 "Hook for functions that get a default item for todo.
11655 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11656 nil or a string to be used for the todo mark." )
11658 (defvar org-agenda-headline-snapshot-before-repeat)
11660 (defun org-current-effective-time ()
11661 "Return current time adjusted for `org-extend-today-until' variable."
11662 (let* ((ct (org-current-time))
11663 (dct (decode-time ct))
11664 (ct1
11665 (cond
11666 (org-use-last-clock-out-time-as-effective-time
11667 (or (org-clock-get-last-clock-out-time) ct))
11668 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11669 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11670 (t ct))))
11671 ct1))
11673 (defun org-todo-yesterday (&optional arg)
11674 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11675 (interactive "P")
11676 (if (eq major-mode 'org-agenda-mode)
11677 (apply 'org-agenda-todo-yesterday arg)
11678 (let* ((hour (third (decode-time
11679 (org-current-time))))
11680 (org-extend-today-until (1+ hour)))
11681 (org-todo arg))))
11683 (defvar org-block-entry-blocking ""
11684 "First entry preventing the TODO state change.")
11686 (defun org-todo (&optional arg)
11687 "Change the TODO state of an item.
11688 The state of an item is given by a keyword at the start of the heading,
11689 like
11690 *** TODO Write paper
11691 *** DONE Call mom
11693 The different keywords are specified in the variable `org-todo-keywords'.
11694 By default the available states are \"TODO\" and \"DONE\".
11695 So for this example: when the item starts with TODO, it is changed to DONE.
11696 When it starts with DONE, the DONE is removed. And when neither TODO nor
11697 DONE are present, add TODO at the beginning of the heading.
11699 With \\[universal-argument] prefix arg, use completion to determine the new \
11700 state.
11701 With numeric prefix arg, switch to that state.
11702 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11703 keywords (nextset).
11704 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11705 With a numeric prefix arg of 0, inhibit note taking for the change.
11707 For calling through lisp, arg is also interpreted in the following way:
11708 'none -> empty state
11709 \"\"(empty string) -> switch to empty state
11710 'done -> switch to DONE
11711 'nextset -> switch to the next set of keywords
11712 'previousset -> switch to the previous set of keywords
11713 \"WAITING\" -> switch to the specified keyword, but only if it
11714 really is a member of `org-todo-keywords'."
11715 (interactive "P")
11716 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11717 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11718 'region-start-level 'region))
11719 org-loop-over-headlines-in-active-region)
11720 (org-map-entries
11721 `(org-todo ,arg)
11722 org-loop-over-headlines-in-active-region
11723 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11724 (if (equal arg '(16)) (setq arg 'nextset))
11725 (let ((org-blocker-hook org-blocker-hook)
11726 commentp
11727 case-fold-search)
11728 (when (equal arg '(64))
11729 (setq arg nil org-blocker-hook nil))
11730 (when (and org-blocker-hook
11731 (or org-inhibit-blocking
11732 (org-entry-get nil "NOBLOCKING")))
11733 (setq org-blocker-hook nil))
11734 (save-excursion
11735 (catch 'exit
11736 (org-back-to-heading t)
11737 (when (looking-at (concat "^\\*+ " org-comment-string))
11738 (org-toggle-comment)
11739 (setq commentp t))
11740 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11741 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11742 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11743 (let* ((match-data (match-data))
11744 (startpos (point-at-bol))
11745 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11746 (org-log-done org-log-done)
11747 (org-log-repeat org-log-repeat)
11748 (org-todo-log-states org-todo-log-states)
11749 (org-inhibit-logging
11750 (if (equal arg 0)
11751 (progn (setq arg nil) 'note) org-inhibit-logging))
11752 (this (match-string 1))
11753 (hl-pos (match-beginning 0))
11754 (head (org-get-todo-sequence-head this))
11755 (ass (assoc head org-todo-kwd-alist))
11756 (interpret (nth 1 ass))
11757 (done-word (nth 3 ass))
11758 (final-done-word (nth 4 ass))
11759 (org-last-state (or this ""))
11760 (completion-ignore-case t)
11761 (member (member this org-todo-keywords-1))
11762 (tail (cdr member))
11763 (org-state (cond
11764 ((and org-todo-key-trigger
11765 (or (and (equal arg '(4))
11766 (eq org-use-fast-todo-selection 'prefix))
11767 (and (not arg) org-use-fast-todo-selection
11768 (not (eq org-use-fast-todo-selection
11769 'prefix)))))
11770 ;; Use fast selection
11771 (org-fast-todo-selection))
11772 ((and (equal arg '(4))
11773 (or (not org-use-fast-todo-selection)
11774 (not org-todo-key-trigger)))
11775 ;; Read a state with completion
11776 (org-icompleting-read
11777 "State: " (mapcar (lambda(x) (list x))
11778 org-todo-keywords-1)
11779 nil t))
11780 ((eq arg 'right)
11781 (if this
11782 (if tail (car tail) nil)
11783 (car org-todo-keywords-1)))
11784 ((eq arg 'left)
11785 (if (equal member org-todo-keywords-1)
11787 (if this
11788 (nth (- (length org-todo-keywords-1)
11789 (length tail) 2)
11790 org-todo-keywords-1)
11791 (org-last org-todo-keywords-1))))
11792 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11793 (setq arg nil))) ; hack to fall back to cycling
11794 (arg
11795 ;; user or caller requests a specific state
11796 (cond
11797 ((equal arg "") nil)
11798 ((eq arg 'none) nil)
11799 ((eq arg 'done) (or done-word (car org-done-keywords)))
11800 ((eq arg 'nextset)
11801 (or (car (cdr (member head org-todo-heads)))
11802 (car org-todo-heads)))
11803 ((eq arg 'previousset)
11804 (let ((org-todo-heads (reverse org-todo-heads)))
11805 (or (car (cdr (member head org-todo-heads)))
11806 (car org-todo-heads))))
11807 ((car (member arg org-todo-keywords-1)))
11808 ((stringp arg)
11809 (error "State `%s' not valid in this file" arg))
11810 ((nth (1- (prefix-numeric-value arg))
11811 org-todo-keywords-1))))
11812 ((null member) (or head (car org-todo-keywords-1)))
11813 ((equal this final-done-word) nil) ;; -> make empty
11814 ((null tail) nil) ;; -> first entry
11815 ((memq interpret '(type priority))
11816 (if (eq this-command last-command)
11817 (car tail)
11818 (if (> (length tail) 0)
11819 (or done-word (car org-done-keywords))
11820 nil)))
11822 (car tail))))
11823 (org-state (or
11824 (run-hook-with-args-until-success
11825 'org-todo-get-default-hook org-state org-last-state)
11826 org-state))
11827 (next (if org-state (concat " " org-state " ") " "))
11828 (change-plist (list :type 'todo-state-change :from this :to org-state
11829 :position startpos))
11830 dolog now-done-p)
11831 (when org-blocker-hook
11832 (setq org-last-todo-state-is-todo
11833 (not (member this org-done-keywords)))
11834 (unless (save-excursion
11835 (save-match-data
11836 (org-with-wide-buffer
11837 (run-hook-with-args-until-failure
11838 'org-blocker-hook change-plist))))
11839 (if (org-called-interactively-p 'interactive)
11840 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11841 this org-state org-block-entry-blocking)
11842 ;; fail silently
11843 (message "TODO state change from %s to %s blocked (by \"%s\")"
11844 this org-state org-block-entry-blocking)
11845 (throw 'exit nil))))
11846 (store-match-data match-data)
11847 (replace-match next t t)
11848 (unless (pos-visible-in-window-p hl-pos)
11849 (message "TODO state changed to %s" (org-trim next)))
11850 (unless head
11851 (setq head (org-get-todo-sequence-head org-state)
11852 ass (assoc head org-todo-kwd-alist)
11853 interpret (nth 1 ass)
11854 done-word (nth 3 ass)
11855 final-done-word (nth 4 ass)))
11856 (when (memq arg '(nextset previousset))
11857 (message "Keyword-Set %d/%d: %s"
11858 (- (length org-todo-sets) -1
11859 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11860 (length org-todo-sets)
11861 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11862 (setq org-last-todo-state-is-todo
11863 (not (member org-state org-done-keywords)))
11864 (setq now-done-p (and (member org-state org-done-keywords)
11865 (not (member this org-done-keywords))))
11866 (and logging (org-local-logging logging))
11867 (when (and (or org-todo-log-states org-log-done)
11868 (not (eq org-inhibit-logging t))
11869 (not (memq arg '(nextset previousset))))
11870 ;; we need to look at recording a time and note
11871 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11872 (nth 2 (assoc this org-todo-log-states))))
11873 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11874 (setq dolog 'time))
11875 (when (and org-state
11876 (member org-state org-not-done-keywords)
11877 (not (member this org-not-done-keywords)))
11878 ;; This is now a todo state and was not one before
11879 ;; If there was a CLOSED time stamp, get rid of it.
11880 (org-add-planning-info nil nil 'closed))
11881 (when (and now-done-p org-log-done)
11882 ;; It is now done, and it was not done before
11883 (org-add-planning-info 'closed (org-current-effective-time))
11884 (if (and (not dolog) (eq 'note org-log-done))
11885 (org-add-log-setup 'done org-state this 'findpos 'note)))
11886 (when (and org-state dolog)
11887 ;; This is a non-nil state, and we need to log it
11888 (org-add-log-setup 'state org-state this 'findpos dolog)))
11889 ;; Fixup tag positioning
11890 (org-todo-trigger-tag-changes org-state)
11891 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11892 (when org-provide-todo-statistics
11893 (org-update-parent-todo-statistics))
11894 (run-hooks 'org-after-todo-state-change-hook)
11895 (if (and arg (not (member org-state org-done-keywords)))
11896 (setq head (org-get-todo-sequence-head org-state)))
11897 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11898 ;; Do we need to trigger a repeat?
11899 (when now-done-p
11900 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11901 ;; This is for the agenda, take a snapshot of the headline.
11902 (save-match-data
11903 (setq org-agenda-headline-snapshot-before-repeat
11904 (org-get-heading))))
11905 (org-auto-repeat-maybe org-state))
11906 ;; Fixup cursor location if close to the keyword
11907 (if (and (outline-on-heading-p)
11908 (not (bolp))
11909 (save-excursion (beginning-of-line 1)
11910 (looking-at org-todo-line-regexp))
11911 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11912 (progn
11913 (goto-char (or (match-end 2) (match-end 1)))
11914 (and (looking-at " ") (just-one-space))))
11915 (when org-trigger-hook
11916 (save-excursion
11917 (run-hook-with-args 'org-trigger-hook change-plist)))
11918 (when commentp (org-toggle-comment))))))))
11920 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11921 "Block turning an entry into a TODO, using the hierarchy.
11922 This checks whether the current task should be blocked from state
11923 changes. Such blocking occurs when:
11925 1. The task has children which are not all in a completed state.
11927 2. A task has a parent with the property :ORDERED:, and there
11928 are siblings prior to the current task with incomplete
11929 status.
11931 3. The parent of the task is blocked because it has siblings that should
11932 be done first, or is child of a block grandparent TODO entry."
11934 (if (not org-enforce-todo-dependencies)
11935 t ; if locally turned off don't block
11936 (catch 'dont-block
11937 ;; If this is not a todo state change, or if this entry is already DONE,
11938 ;; do not block
11939 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11940 (member (plist-get change-plist :from)
11941 (cons 'done org-done-keywords))
11942 (member (plist-get change-plist :to)
11943 (cons 'todo org-not-done-keywords))
11944 (not (plist-get change-plist :to)))
11945 (throw 'dont-block t))
11946 ;; If this task has children, and any are undone, it's blocked
11947 (save-excursion
11948 (org-back-to-heading t)
11949 (let ((this-level (funcall outline-level)))
11950 (outline-next-heading)
11951 (let ((child-level (funcall outline-level)))
11952 (while (and (not (eobp))
11953 (> child-level this-level))
11954 ;; this todo has children, check whether they are all
11955 ;; completed
11956 (if (and (not (org-entry-is-done-p))
11957 (org-entry-is-todo-p))
11958 (progn (setq org-block-entry-blocking (org-get-heading))
11959 (throw 'dont-block nil)))
11960 (outline-next-heading)
11961 (setq child-level (funcall outline-level))))))
11962 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11963 ;; any previous siblings are undone, it's blocked
11964 (save-excursion
11965 (org-back-to-heading t)
11966 (let* ((pos (point))
11967 (parent-pos (and (org-up-heading-safe) (point))))
11968 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11969 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11970 (forward-line 1)
11971 (re-search-forward org-not-done-heading-regexp pos t))
11972 (setq org-block-entry-blocking (match-string 0))
11973 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11974 ;; Search further up the hierarchy, to see if an ancestor is blocked
11975 (while t
11976 (goto-char parent-pos)
11977 (if (not (looking-at org-not-done-heading-regexp))
11978 (throw 'dont-block t)) ; do not block, parent is not a TODO
11979 (setq pos (point))
11980 (setq parent-pos (and (org-up-heading-safe) (point)))
11981 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11982 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11983 (forward-line 1)
11984 (re-search-forward org-not-done-heading-regexp pos t)
11985 (setq org-block-entry-blocking (org-get-heading)))
11986 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11988 (defcustom org-track-ordered-property-with-tag nil
11989 "Should the ORDERED property also be shown as a tag?
11990 The ORDERED property decides if an entry should require subtasks to be
11991 completed in sequence. Since a property is not very visible, setting
11992 this option means that toggling the ORDERED property with the command
11993 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11994 not relevant for the behavior, but it makes things more visible.
11996 Note that toggling the tag with tags commands will not change the property
11997 and therefore not influence behavior!
11999 This can be t, meaning the tag ORDERED should be used, It can also be a
12000 string to select a different tag for this task."
12001 :group 'org-todo
12002 :type '(choice
12003 (const :tag "No tracking" nil)
12004 (const :tag "Track with ORDERED tag" t)
12005 (string :tag "Use other tag")))
12007 (defun org-toggle-ordered-property ()
12008 "Toggle the ORDERED property of the current entry.
12009 For better visibility, you can track the value of this property with a tag.
12010 See variable `org-track-ordered-property-with-tag'."
12011 (interactive)
12012 (let* ((t1 org-track-ordered-property-with-tag)
12013 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12014 (save-excursion
12015 (org-back-to-heading)
12016 (if (org-entry-get nil "ORDERED")
12017 (progn
12018 (org-delete-property "ORDERED")
12019 (and tag (org-toggle-tag tag 'off))
12020 (message "Subtasks can be completed in arbitrary order"))
12021 (org-entry-put nil "ORDERED" "t")
12022 (and tag (org-toggle-tag tag 'on))
12023 (message "Subtasks must be completed in sequence")))))
12025 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12026 (defun org-block-todo-from-checkboxes (change-plist)
12027 "Block turning an entry into a TODO, using checkboxes.
12028 This checks whether the current task should be blocked from state
12029 changes because there are unchecked boxes in this entry."
12030 (if (not org-enforce-todo-checkbox-dependencies)
12031 t ; if locally turned off don't block
12032 (catch 'dont-block
12033 ;; If this is not a todo state change, or if this entry is already DONE,
12034 ;; do not block
12035 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12036 (member (plist-get change-plist :from)
12037 (cons 'done org-done-keywords))
12038 (member (plist-get change-plist :to)
12039 (cons 'todo org-not-done-keywords))
12040 (not (plist-get change-plist :to)))
12041 (throw 'dont-block t))
12042 ;; If this task has checkboxes that are not checked, it's blocked
12043 (save-excursion
12044 (org-back-to-heading t)
12045 (let ((beg (point)) end)
12046 (outline-next-heading)
12047 (setq end (point))
12048 (goto-char beg)
12049 (if (org-list-search-forward
12050 (concat (org-item-beginning-re)
12051 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12052 "\\[[- ]\\]")
12053 end t)
12054 (progn
12055 (if (boundp 'org-blocked-by-checkboxes)
12056 (setq org-blocked-by-checkboxes t))
12057 (throw 'dont-block nil)))))
12058 t))) ; do not block
12060 (defun org-entry-blocked-p ()
12061 "Is the current entry blocked?"
12062 (org-with-buffer-modified-unmodified
12063 (if (org-entry-get nil "NOBLOCKING")
12064 nil ;; Never block this entry
12065 (not
12066 (run-hook-with-args-until-failure
12067 'org-blocker-hook
12068 (list :type 'todo-state-change
12069 :position (point)
12070 :from 'todo
12071 :to 'done))))))
12073 (defun org-update-statistics-cookies (all)
12074 "Update the statistics cookie, either from TODO or from checkboxes.
12075 This should be called with the cursor in a line with a statistics cookie."
12076 (interactive "P")
12077 (if all
12078 (progn
12079 (org-update-checkbox-count 'all)
12080 (org-map-entries 'org-update-parent-todo-statistics))
12081 (if (not (org-at-heading-p))
12082 (org-update-checkbox-count)
12083 (let ((pos (point-marker))
12084 end l1 l2)
12085 (ignore-errors (org-back-to-heading t))
12086 (if (not (org-at-heading-p))
12087 (org-update-checkbox-count)
12088 (setq l1 (org-outline-level))
12089 (setq end (save-excursion
12090 (outline-next-heading)
12091 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12092 (point)))
12093 (if (and (save-excursion
12094 (re-search-forward
12095 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12096 (not (save-excursion (re-search-forward
12097 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12098 (org-update-checkbox-count)
12099 (if (and l2 (> l2 l1))
12100 (progn
12101 (goto-char end)
12102 (org-update-parent-todo-statistics))
12103 (goto-char pos)
12104 (beginning-of-line 1)
12105 (while (re-search-forward
12106 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12107 (point-at-eol) t)
12108 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12109 (goto-char pos)
12110 (move-marker pos nil)))))
12112 (defvar org-entry-property-inherited-from) ;; defined below
12113 (defun org-update-parent-todo-statistics ()
12114 "Update any statistics cookie in the parent of the current headline.
12115 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12116 the entire subtree and this will travel up the hierarchy and update
12117 statistics everywhere."
12118 (let* ((prop (save-excursion (org-up-heading-safe)
12119 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12120 (recursive (or (not org-hierarchical-todo-statistics)
12121 (and prop (string-match "\\<recursive\\>" prop))))
12122 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12124 (first t)
12125 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12126 level ltoggle l1 new ndel
12127 (cnt-all 0) (cnt-done 0) is-percent kwd
12128 checkbox-beg ov ovs ove cookie-present)
12129 (catch 'exit
12130 (save-excursion
12131 (beginning-of-line 1)
12132 (setq ltoggle (funcall outline-level))
12133 ;; Three situations are to consider:
12135 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12136 ;; to the top-level ancestor on the headline;
12138 ;; 2. If parent has "recursive" property, repeat up to the
12139 ;; headline setting that property, taking inheritance into
12140 ;; account;
12142 ;; 3. Else, move up to direct parent and proceed only once.
12143 (while (and (setq level (org-up-heading-safe))
12144 (or recursive first)
12145 (>= (point) lim))
12146 (setq first nil cookie-present nil)
12147 (unless (and level
12148 (not (string-match
12149 "\\<checkbox\\>"
12150 (downcase (or (org-entry-get nil "COOKIE_DATA")
12151 "")))))
12152 (throw 'exit nil))
12153 (while (re-search-forward box-re (point-at-eol) t)
12154 (setq cnt-all 0 cnt-done 0 cookie-present t)
12155 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12156 (save-match-data
12157 (unless (outline-next-heading) (throw 'exit nil))
12158 (while (and (looking-at org-complex-heading-regexp)
12159 (> (setq l1 (length (match-string 1))) level))
12160 (setq kwd (and (or recursive (= l1 ltoggle))
12161 (match-string 2)))
12162 (if (or (eq org-provide-todo-statistics 'all-headlines)
12163 (and (listp org-provide-todo-statistics)
12164 (or (member kwd org-provide-todo-statistics)
12165 (member kwd org-done-keywords))))
12166 (setq cnt-all (1+ cnt-all))
12167 (if (eq org-provide-todo-statistics t)
12168 (and kwd (setq cnt-all (1+ cnt-all)))))
12169 (and (member kwd org-done-keywords)
12170 (setq cnt-done (1+ cnt-done)))
12171 (outline-next-heading)))
12172 (setq new
12173 (if is-percent
12174 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12175 (format "[%d/%d]" cnt-done cnt-all))
12176 ndel (- (match-end 0) checkbox-beg))
12177 ;; handle overlays when updating cookie from column view
12178 (when (setq ov (car (overlays-at checkbox-beg)))
12179 (setq ovs (overlay-start ov) ove (overlay-end ov))
12180 (delete-overlay ov))
12181 (goto-char checkbox-beg)
12182 (insert new)
12183 (delete-region (point) (+ (point) ndel))
12184 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12185 (when ov (move-overlay ov ovs ove)))
12186 (when cookie-present
12187 (run-hook-with-args 'org-after-todo-statistics-hook
12188 cnt-done (- cnt-all cnt-done))))))
12189 (run-hooks 'org-todo-statistics-hook)))
12191 (defvar org-after-todo-statistics-hook nil
12192 "Hook that is called after a TODO statistics cookie has been updated.
12193 Each function is called with two arguments: the number of not-done entries
12194 and the number of done entries.
12196 For example, the following function, when added to this hook, will switch
12197 an entry to DONE when all children are done, and back to TODO when new
12198 entries are set to a TODO status. Note that this hook is only called
12199 when there is a statistics cookie in the headline!
12201 (defun org-summary-todo (n-done n-not-done)
12202 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12203 (let (org-log-done org-log-states) ; turn off logging
12204 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12207 (defvar org-todo-statistics-hook nil
12208 "Hook that is run whenever Org thinks TODO statistics should be updated.
12209 This hook runs even if there is no statistics cookie present, in which case
12210 `org-after-todo-statistics-hook' would not run.")
12212 (defun org-todo-trigger-tag-changes (state)
12213 "Apply the changes defined in `org-todo-state-tags-triggers'."
12214 (let ((l org-todo-state-tags-triggers)
12215 changes)
12216 (when (or (not state) (equal state ""))
12217 (setq changes (append changes (cdr (assoc "" l)))))
12218 (when (and (stringp state) (> (length state) 0))
12219 (setq changes (append changes (cdr (assoc state l)))))
12220 (when (member state org-not-done-keywords)
12221 (setq changes (append changes (cdr (assoc 'todo l)))))
12222 (when (member state org-done-keywords)
12223 (setq changes (append changes (cdr (assoc 'done l)))))
12224 (dolist (c changes)
12225 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12227 (defun org-local-logging (value)
12228 "Get logging settings from a property VALUE."
12229 (let* (words w a)
12230 ;; directly set the variables, they are already local.
12231 (setq org-log-done nil
12232 org-log-repeat nil
12233 org-todo-log-states nil)
12234 (setq words (org-split-string value))
12235 (while (setq w (pop words))
12236 (cond
12237 ((setq a (assoc w org-startup-options))
12238 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12239 (set (nth 1 a) (nth 2 a))))
12240 ((setq a (org-extract-log-state-settings w))
12241 (and (member (car a) org-todo-keywords-1)
12242 (push a org-todo-log-states)))))))
12244 (defun org-get-todo-sequence-head (kwd)
12245 "Return the head of the TODO sequence to which KWD belongs.
12246 If KWD is not set, check if there is a text property remembering the
12247 right sequence."
12248 (let (p)
12249 (cond
12250 ((not kwd)
12251 (or (get-text-property (point-at-bol) 'org-todo-head)
12252 (progn
12253 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12254 nil (point-at-eol)))
12255 (get-text-property p 'org-todo-head))))
12256 ((not (member kwd org-todo-keywords-1))
12257 (car org-todo-keywords-1))
12258 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12260 (defun org-fast-todo-selection ()
12261 "Fast TODO keyword selection with single keys.
12262 Returns the new TODO keyword, or nil if no state change should occur."
12263 (let* ((fulltable org-todo-key-alist)
12264 (done-keywords org-done-keywords) ;; needed for the faces.
12265 (maxlen (apply 'max (mapcar
12266 (lambda (x)
12267 (if (stringp (car x)) (string-width (car x)) 0))
12268 fulltable)))
12269 (expert nil)
12270 (fwidth (+ maxlen 3 1 3))
12271 (ncol (/ (- (window-width) 4) fwidth))
12272 tg cnt e c tbl
12273 groups ingroup)
12274 (save-excursion
12275 (save-window-excursion
12276 (if expert
12277 (set-buffer (get-buffer-create " *Org todo*"))
12278 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12279 (erase-buffer)
12280 (org-set-local 'org-done-keywords done-keywords)
12281 (setq tbl fulltable cnt 0)
12282 (while (setq e (pop tbl))
12283 (cond
12284 ((equal e '(:startgroup))
12285 (push '() groups) (setq ingroup t)
12286 (when (not (= cnt 0))
12287 (setq cnt 0)
12288 (insert "\n"))
12289 (insert "{ "))
12290 ((equal e '(:endgroup))
12291 (setq ingroup nil cnt 0)
12292 (insert "}\n"))
12293 ((equal e '(:newline))
12294 (when (not (= cnt 0))
12295 (setq cnt 0)
12296 (insert "\n")
12297 (setq e (car tbl))
12298 (while (equal (car tbl) '(:newline))
12299 (insert "\n")
12300 (setq tbl (cdr tbl)))))
12302 (setq tg (car e) c (cdr e))
12303 (if ingroup (push tg (car groups)))
12304 (setq tg (org-add-props tg nil 'face
12305 (org-get-todo-face tg)))
12306 (if (and (= cnt 0) (not ingroup)) (insert " "))
12307 (insert "[" c "] " tg (make-string
12308 (- fwidth 4 (length tg)) ?\ ))
12309 (when (= (setq cnt (1+ cnt)) ncol)
12310 (insert "\n")
12311 (if ingroup (insert " "))
12312 (setq cnt 0)))))
12313 (insert "\n")
12314 (goto-char (point-min))
12315 (if (not expert) (org-fit-window-to-buffer))
12316 (message "[a-z..]:Set [SPC]:clear")
12317 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12318 (cond
12319 ((or (= c ?\C-g)
12320 (and (= c ?q) (not (rassoc c fulltable))))
12321 (setq quit-flag t))
12322 ((= c ?\ ) nil)
12323 ((setq e (rassoc c fulltable) tg (car e))
12325 (t (setq quit-flag t)))))))
12327 (defun org-entry-is-todo-p ()
12328 (member (org-get-todo-state) org-not-done-keywords))
12330 (defun org-entry-is-done-p ()
12331 (member (org-get-todo-state) org-done-keywords))
12333 (defun org-get-todo-state ()
12334 (save-excursion
12335 (org-back-to-heading t)
12336 (and (looking-at org-todo-line-regexp)
12337 (match-end 2)
12338 (match-string 2))))
12340 (defun org-at-date-range-p (&optional inactive-ok)
12341 "Is the cursor inside a date range?"
12342 (interactive)
12343 (save-excursion
12344 (catch 'exit
12345 (let ((pos (point)))
12346 (skip-chars-backward "^[<\r\n")
12347 (skip-chars-backward "<[")
12348 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12349 (>= (match-end 0) pos)
12350 (throw 'exit t))
12351 (skip-chars-backward "^<[\r\n")
12352 (skip-chars-backward "<[")
12353 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12354 (>= (match-end 0) pos)
12355 (throw 'exit t)))
12356 nil)))
12358 (defun org-get-repeat (&optional tagline)
12359 "Check if there is a deadline/schedule with repeater in this entry."
12360 (save-match-data
12361 (save-excursion
12362 (org-back-to-heading t)
12363 (and (re-search-forward (if tagline
12364 (concat tagline "\\s-*" org-repeat-re)
12365 org-repeat-re)
12366 (org-entry-end-position) t)
12367 (match-string-no-properties 1)))))
12369 (defvar org-last-changed-timestamp)
12370 (defvar org-last-inserted-timestamp)
12371 (defvar org-log-post-message)
12372 (defvar org-log-note-purpose)
12373 (defvar org-log-note-how)
12374 (defvar org-log-note-extra)
12375 (defun org-auto-repeat-maybe (done-word)
12376 "Check if the current headline contains a repeated deadline/schedule.
12377 If yes, set TODO state back to what it was and change the base date
12378 of repeating deadline/scheduled time stamps to new date.
12379 This function is run automatically after each state change to a DONE state."
12380 ;; last-state is dynamically scoped into this function
12381 (let* ((repeat (org-get-repeat))
12382 (aa (assoc org-last-state org-todo-kwd-alist))
12383 (interpret (nth 1 aa))
12384 (head (nth 2 aa))
12385 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12386 (msg "Entry repeats: ")
12387 (org-log-done nil)
12388 (org-todo-log-states nil)
12389 re type n what ts time to-state)
12390 (when repeat
12391 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12392 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12393 org-todo-repeat-to-state))
12394 (unless (and to-state (member to-state org-todo-keywords-1))
12395 (setq to-state (if (eq interpret 'type) org-last-state head)))
12396 (org-todo to-state)
12397 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12398 (org-entry-put nil "LAST_REPEAT" (format-time-string
12399 (org-time-stamp-format t t))))
12400 (when org-log-repeat
12401 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12402 (memq 'org-add-log-note post-command-hook))
12403 ;; OK, we are already setup for some record
12404 (if (eq org-log-repeat 'note)
12405 ;; make sure we take a note, not only a time stamp
12406 (setq org-log-note-how 'note))
12407 ;; Set up for taking a record
12408 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12409 org-last-state
12410 'findpos org-log-repeat)))
12411 (org-back-to-heading t)
12412 (org-add-planning-info nil nil 'closed)
12413 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12414 org-deadline-time-regexp "\\)\\|\\("
12415 org-ts-regexp "\\)"))
12416 (while (re-search-forward
12417 re (save-excursion (outline-next-heading) (point)) t)
12418 (setq type (if (match-end 1) org-scheduled-string
12419 (if (match-end 3) org-deadline-string "Plain:"))
12420 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12421 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12422 (setq n (string-to-number (match-string 2 ts))
12423 what (match-string 3 ts))
12424 (if (equal what "w") (setq n (* n 7) what "d"))
12425 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12426 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12427 ;; Preparation, see if we need to modify the start date for the change
12428 (when (match-end 1)
12429 (setq time (save-match-data (org-time-string-to-time ts)))
12430 (cond
12431 ((equal (match-string 1 ts) ".")
12432 ;; Shift starting date to today
12433 (org-timestamp-change
12434 (- (org-today) (time-to-days time))
12435 'day))
12436 ((equal (match-string 1 ts) "+")
12437 (let ((nshiftmax 10) (nshift 0))
12438 (while (or (= nshift 0)
12439 (<= (time-to-days time)
12440 (time-to-days (current-time))))
12441 (when (= (incf nshift) nshiftmax)
12442 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12443 (error "Abort")))
12444 (org-timestamp-change n (cdr (assoc what whata)))
12445 (org-at-timestamp-p t)
12446 (setq ts (match-string 1))
12447 (setq time (save-match-data (org-time-string-to-time ts)))))
12448 (org-timestamp-change (- n) (cdr (assoc what whata)))
12449 ;; rematch, so that we have everything in place for the real shift
12450 (org-at-timestamp-p t)
12451 (setq ts (match-string 1))
12452 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12453 (org-timestamp-change n (cdr (assoc what whata)) nil t)
12454 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12455 (setq org-log-post-message msg)
12456 (message "%s" msg))))
12458 (defun org-show-todo-tree (arg)
12459 "Make a compact tree which shows all headlines marked with TODO.
12460 The tree will show the lines where the regexp matches, and all higher
12461 headlines above the match.
12462 With a \\[universal-argument] prefix, prompt for a regexp to match.
12463 With a numeric prefix N, construct a sparse tree for the Nth element
12464 of `org-todo-keywords-1'."
12465 (interactive "P")
12466 (let ((case-fold-search nil)
12467 (kwd-re
12468 (cond ((null arg) org-not-done-regexp)
12469 ((equal arg '(4))
12470 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12471 (mapcar 'list org-todo-keywords-1))))
12472 (concat "\\("
12473 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12474 "\\)\\>")))
12475 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12476 (regexp-quote (nth (1- (prefix-numeric-value arg))
12477 org-todo-keywords-1)))
12478 (t (error "Invalid prefix argument: %s" arg)))))
12479 (message "%d TODO entries found"
12480 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12482 (defun org-deadline (&optional arg time)
12483 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12484 With one universal prefix argument, remove any deadline from the item.
12485 With two universal prefix arguments, prompt for a warning delay.
12486 With argument TIME, set the deadline at the corresponding date. TIME
12487 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12488 (interactive "P")
12489 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12490 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12491 'region-start-level 'region))
12492 org-loop-over-headlines-in-active-region)
12493 (org-map-entries
12494 `(org-deadline ',arg ,time)
12495 org-loop-over-headlines-in-active-region
12496 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12497 (let* ((old-date (org-entry-get nil "DEADLINE"))
12498 (repeater (and old-date
12499 (string-match
12500 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12501 old-date)
12502 (match-string 1 old-date))))
12503 (cond
12504 ((equal arg '(4))
12505 (when (and old-date org-log-redeadline)
12506 (org-add-log-setup 'deldeadline nil old-date 'findpos
12507 org-log-redeadline))
12508 (org-remove-timestamp-with-keyword org-deadline-string)
12509 (message "Item no longer has a deadline."))
12510 ((equal arg '(16))
12511 (save-excursion
12512 (if (re-search-forward
12513 org-deadline-time-regexp
12514 (save-excursion (outline-next-heading) (point)) t)
12515 (let* ((rpl0 (match-string 1))
12516 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12517 (replace-match
12518 (concat org-deadline-string
12519 " <" rpl
12520 (format " -%dd" (abs
12521 (- (time-to-days
12522 (save-match-data
12523 (org-read-date nil t nil "Warn starting from")))
12524 (time-to-days nil))))
12525 ">") t t))
12526 (user-error "No deadline information to update"))))
12528 (org-add-planning-info 'deadline time 'closed)
12529 (when (and old-date org-log-redeadline
12530 (not (equal old-date
12531 (substring org-last-inserted-timestamp 1 -1))))
12532 (org-add-log-setup 'redeadline nil old-date 'findpos
12533 org-log-redeadline))
12534 (when repeater
12535 (save-excursion
12536 (org-back-to-heading t)
12537 (when (re-search-forward (concat org-deadline-string " "
12538 org-last-inserted-timestamp)
12539 (save-excursion
12540 (outline-next-heading) (point)) t)
12541 (goto-char (1- (match-end 0)))
12542 (insert " " repeater)
12543 (setq org-last-inserted-timestamp
12544 (concat (substring org-last-inserted-timestamp 0 -1)
12545 " " repeater
12546 (substring org-last-inserted-timestamp -1))))))
12547 (message "Deadline on %s" org-last-inserted-timestamp))))))
12549 (defun org-schedule (&optional arg time)
12550 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12551 With one universal prefix argument, remove any scheduling date from the item.
12552 With two universal prefix arguments, prompt for a delay cookie.
12553 With argument TIME, scheduled at the corresponding date. TIME can
12554 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12555 (interactive "P")
12556 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12557 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12558 'region-start-level 'region))
12559 org-loop-over-headlines-in-active-region)
12560 (org-map-entries
12561 `(org-schedule ',arg ,time)
12562 org-loop-over-headlines-in-active-region
12563 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12564 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12565 (repeater (and old-date
12566 (string-match
12567 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12568 old-date)
12569 (match-string 1 old-date))))
12570 (cond
12571 ((equal arg '(4))
12572 (progn
12573 (when (and old-date org-log-reschedule)
12574 (org-add-log-setup 'delschedule nil old-date 'findpos
12575 org-log-reschedule))
12576 (org-remove-timestamp-with-keyword org-scheduled-string)
12577 (message "Item is no longer scheduled.")))
12578 ((equal arg '(16))
12579 (save-excursion
12580 (if (re-search-forward
12581 org-scheduled-time-regexp
12582 (save-excursion (outline-next-heading) (point)) t)
12583 (let* ((rpl0 (match-string 1))
12584 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12585 (replace-match
12586 (concat org-scheduled-string
12587 " <" rpl
12588 (format " -%dd" (abs
12589 (- (time-to-days
12590 (save-match-data
12591 (org-read-date nil t nil "Delay until")))
12592 (time-to-days nil))))
12593 ">") t t))
12594 (user-error "No scheduled information to update"))))
12596 (org-add-planning-info 'scheduled time 'closed)
12597 (when (and old-date org-log-reschedule
12598 (not (equal old-date
12599 (substring org-last-inserted-timestamp 1 -1))))
12600 (org-add-log-setup 'reschedule nil old-date 'findpos
12601 org-log-reschedule))
12602 (when repeater
12603 (save-excursion
12604 (org-back-to-heading t)
12605 (when (re-search-forward (concat org-scheduled-string " "
12606 org-last-inserted-timestamp)
12607 (save-excursion
12608 (outline-next-heading) (point)) t)
12609 (goto-char (1- (match-end 0)))
12610 (insert " " repeater)
12611 (setq org-last-inserted-timestamp
12612 (concat (substring org-last-inserted-timestamp 0 -1)
12613 " " repeater
12614 (substring org-last-inserted-timestamp -1))))))
12615 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12617 (defun org-get-scheduled-time (pom &optional inherit)
12618 "Get the scheduled time as a time tuple, of a format suitable
12619 for calling org-schedule with, or if there is no scheduling,
12620 returns nil."
12621 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12622 (when time
12623 (apply 'encode-time (org-parse-time-string time)))))
12625 (defun org-get-deadline-time (pom &optional inherit)
12626 "Get the deadline as a time tuple, of a format suitable for
12627 calling org-deadline with, or if there is no scheduling, returns
12628 nil."
12629 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12630 (when time
12631 (apply 'encode-time (org-parse-time-string time)))))
12633 (defun org-remove-timestamp-with-keyword (keyword)
12634 "Remove all time stamps with KEYWORD in the current entry."
12635 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12636 beg)
12637 (save-excursion
12638 (org-back-to-heading t)
12639 (setq beg (point))
12640 (outline-next-heading)
12641 (while (re-search-backward re beg t)
12642 (replace-match "")
12643 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12644 (equal (char-before) ?\ ))
12645 (backward-delete-char 1)
12646 (if (string-match "^[ \t]*$" (buffer-substring
12647 (point-at-bol) (point-at-eol)))
12648 (delete-region (point-at-bol)
12649 (min (point-max) (1+ (point-at-eol))))))))))
12651 (defun org-add-planning-info (what &optional time &rest remove)
12652 "Insert new timestamp with keyword in the line directly after the headline.
12653 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12654 If non is given, the user is prompted for a date.
12655 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12656 be removed."
12657 (interactive)
12658 (let (org-time-was-given org-end-time-was-given ts
12659 end default-time default-input)
12661 (catch 'exit
12662 (when (and (memq what '(scheduled deadline))
12663 (or (not time)
12664 (and (stringp time)
12665 (string-match "^[-+]+[0-9]" time))))
12666 ;; Try to get a default date/time from existing timestamp
12667 (save-excursion
12668 (org-back-to-heading t)
12669 (setq end (save-excursion (outline-next-heading) (point)))
12670 (when (re-search-forward (if (eq what 'scheduled)
12671 org-scheduled-time-regexp
12672 org-deadline-time-regexp)
12673 end t)
12674 (setq ts (match-string 1)
12675 default-time
12676 (apply 'encode-time (org-parse-time-string ts))
12677 default-input (and ts (org-get-compact-tod ts))))))
12678 (when what
12679 (setq time
12680 (if (stringp time)
12681 ;; This is a string (relative or absolute), set proper date
12682 (apply 'encode-time
12683 (org-read-date-analyze
12684 time default-time (decode-time default-time)))
12685 ;; If necessary, get the time from the user
12686 (or time (org-read-date nil 'to-time nil nil
12687 default-time default-input)))))
12689 (when (and org-insert-labeled-timestamps-at-point
12690 (member what '(scheduled deadline)))
12691 (insert
12692 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12693 (org-insert-time-stamp time org-time-was-given
12694 nil nil nil (list org-end-time-was-given))
12695 (setq what nil))
12696 (save-excursion
12697 (save-restriction
12698 (let (col list elt ts buffer-invisibility-spec)
12699 (org-back-to-heading t)
12700 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12701 (goto-char (match-end 1))
12702 (setq col (current-column))
12703 (goto-char (match-end 0))
12704 (if (eobp) (insert "\n") (forward-char 1))
12705 (when (and (not what)
12706 (not (looking-at
12707 (concat "[ \t]*"
12708 org-keyword-time-not-clock-regexp))))
12709 ;; Nothing to add, nothing to remove...... :-)
12710 (throw 'exit nil))
12711 (if (and (not (looking-at org-outline-regexp))
12712 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12713 "[^\r\n]*"))
12714 (not (equal (match-string 1) org-clock-string)))
12715 (narrow-to-region (match-beginning 0) (match-end 0))
12716 (insert-before-markers "\n")
12717 (backward-char 1)
12718 (narrow-to-region (point) (point))
12719 (and org-adapt-indentation (org-indent-to-column col)))
12720 ;; Check if we have to remove something.
12721 (setq list (cons what remove))
12722 (while list
12723 (setq elt (pop list))
12724 (when (or (and (eq elt 'scheduled)
12725 (re-search-forward org-scheduled-time-regexp nil t))
12726 (and (eq elt 'deadline)
12727 (re-search-forward org-deadline-time-regexp nil t))
12728 (and (eq elt 'closed)
12729 (re-search-forward org-closed-time-regexp nil t)))
12730 (replace-match "")
12731 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12732 (and (looking-at "[ \t]+") (replace-match ""))
12733 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12734 (when what
12735 (insert
12736 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12737 (cond ((eq what 'scheduled) org-scheduled-string)
12738 ((eq what 'deadline) org-deadline-string)
12739 ((eq what 'closed) org-closed-string))
12740 " ")
12741 (setq ts (org-insert-time-stamp
12742 time
12743 (or org-time-was-given
12744 (and (eq what 'closed) org-log-done-with-time))
12745 (eq what 'closed)
12746 nil nil (list org-end-time-was-given)))
12747 (insert
12748 (if (not (or (bolp) (eq (char-before) ?\ )
12749 (memq (char-after) '(32 10))
12750 (eobp))) " " ""))
12751 (end-of-line 1))
12752 (goto-char (point-min))
12753 (widen)
12754 (if (and (looking-at "[ \t]*\n")
12755 (equal (char-before) ?\n))
12756 (delete-region (1- (point)) (point-at-eol)))
12757 ts))))))
12759 (defvar org-log-note-marker (make-marker))
12760 (defvar org-log-note-purpose nil)
12761 (defvar org-log-note-state nil)
12762 (defvar org-log-note-previous-state nil)
12763 (defvar org-log-note-how nil)
12764 (defvar org-log-note-extra nil)
12765 (defvar org-log-note-window-configuration nil)
12766 (defvar org-log-note-return-to (make-marker))
12767 (defvar org-log-note-effective-time nil
12768 "Remembered current time so that dynamically scoped
12769 `org-extend-today-until' affects tha timestamps in state change
12770 log")
12772 (defvar org-log-post-message nil
12773 "Message to be displayed after a log note has been stored.
12774 The auto-repeater uses this.")
12776 (defun org-add-note ()
12777 "Add a note to the current entry.
12778 This is done in the same way as adding a state change note."
12779 (interactive)
12780 (org-add-log-setup 'note nil nil 'findpos nil))
12782 (defvar org-property-end-re)
12783 (defun org-add-log-setup (&optional purpose state prev-state
12784 findpos how extra)
12785 "Set up the post command hook to take a note.
12786 If this is about to TODO state change, the new state is expected in STATE.
12787 When FINDPOS is non-nil, find the correct position for the note in
12788 the current entry. If not, assume that it can be inserted at point.
12789 HOW is an indicator what kind of note should be created.
12790 EXTRA is additional text that will be inserted into the notes buffer."
12791 (let* ((org-log-into-drawer (org-log-into-drawer))
12792 (drawer (cond ((stringp org-log-into-drawer)
12793 org-log-into-drawer)
12794 (org-log-into-drawer "LOGBOOK"))))
12795 (save-restriction
12796 (save-excursion
12797 (when findpos
12798 (org-back-to-heading t)
12799 (narrow-to-region (point) (save-excursion
12800 (outline-next-heading) (point)))
12801 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12802 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12803 "[^\r\n]*\\)?"))
12804 (goto-char (match-end 0))
12805 (cond
12806 (drawer
12807 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12808 nil t)
12809 (progn
12810 (goto-char (match-end 0))
12811 (or org-log-states-order-reversed
12812 (and (re-search-forward org-property-end-re nil t)
12813 (goto-char (1- (match-beginning 0))))))
12814 (insert "\n:" drawer ":\n:END:")
12815 (beginning-of-line 0)
12816 (org-indent-line)
12817 (beginning-of-line 2)
12818 (org-indent-line)
12819 (end-of-line 0)))
12820 ((and org-log-state-notes-insert-after-drawers
12821 (save-excursion
12822 (forward-line) (looking-at org-drawer-regexp)))
12823 (forward-line)
12824 (while (looking-at org-drawer-regexp)
12825 (goto-char (match-end 0))
12826 (re-search-forward org-property-end-re (point-max) t)
12827 (forward-line))
12828 (forward-line -1)))
12829 (unless org-log-states-order-reversed
12830 (and (= (char-after) ?\n) (forward-char 1))
12831 (org-skip-over-state-notes)
12832 (skip-chars-backward " \t\n\r")))
12833 (move-marker org-log-note-marker (point))
12834 (setq org-log-note-purpose purpose
12835 org-log-note-state state
12836 org-log-note-previous-state prev-state
12837 org-log-note-how how
12838 org-log-note-extra extra
12839 org-log-note-effective-time (org-current-effective-time))
12840 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12842 (defun org-skip-over-state-notes ()
12843 "Skip past the list of State notes in an entry."
12844 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12845 (when (ignore-errors (goto-char (org-in-item-p)))
12846 (let* ((struct (org-list-struct))
12847 (prevs (org-list-prevs-alist struct)))
12848 (while (looking-at "[ \t]*- State")
12849 (goto-char (or (org-list-get-next-item (point) struct prevs)
12850 (org-list-get-item-end (point) struct)))))))
12852 (defun org-add-log-note (&optional purpose)
12853 "Pop up a window for taking a note, and add this note later at point."
12854 (remove-hook 'post-command-hook 'org-add-log-note)
12855 (setq org-log-note-window-configuration (current-window-configuration))
12856 (delete-other-windows)
12857 (move-marker org-log-note-return-to (point))
12858 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12859 (goto-char org-log-note-marker)
12860 (org-switch-to-buffer-other-window "*Org Note*")
12861 (erase-buffer)
12862 (if (memq org-log-note-how '(time state))
12863 (let (current-prefix-arg) (org-store-log-note))
12864 (let ((org-inhibit-startup t)) (org-mode))
12865 (insert (format "# Insert note for %s.
12866 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12867 (cond
12868 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12869 ((eq org-log-note-purpose 'done) "closed todo item")
12870 ((eq org-log-note-purpose 'state)
12871 (format "state change from \"%s\" to \"%s\""
12872 (or org-log-note-previous-state "")
12873 (or org-log-note-state "")))
12874 ((eq org-log-note-purpose 'reschedule)
12875 "rescheduling")
12876 ((eq org-log-note-purpose 'delschedule)
12877 "no longer scheduled")
12878 ((eq org-log-note-purpose 'redeadline)
12879 "changing deadline")
12880 ((eq org-log-note-purpose 'deldeadline)
12881 "removing deadline")
12882 ((eq org-log-note-purpose 'refile)
12883 "refiling")
12884 ((eq org-log-note-purpose 'note)
12885 "this entry")
12886 (t (error "This should not happen")))))
12887 (if org-log-note-extra (insert org-log-note-extra))
12888 (org-set-local 'org-finish-function 'org-store-log-note)
12889 (run-hooks 'org-log-buffer-setup-hook)))
12891 (defvar org-note-abort nil) ; dynamically scoped
12892 (defun org-store-log-note ()
12893 "Finish taking a log note, and insert it to where it belongs."
12894 (let ((txt (buffer-string)))
12895 (kill-buffer (current-buffer))
12896 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12897 lines ind bul)
12898 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12899 (setq txt (replace-match "" t t txt)))
12900 (if (string-match "\\s-+\\'" txt)
12901 (setq txt (replace-match "" t t txt)))
12902 (setq lines (org-split-string txt "\n"))
12903 (when (and note (string-match "\\S-" note))
12904 (setq note
12905 (org-replace-escapes
12906 note
12907 (list (cons "%u" (user-login-name))
12908 (cons "%U" user-full-name)
12909 (cons "%t" (format-time-string
12910 (org-time-stamp-format 'long 'inactive)
12911 org-log-note-effective-time))
12912 (cons "%T" (format-time-string
12913 (org-time-stamp-format 'long nil)
12914 org-log-note-effective-time))
12915 (cons "%d" (format-time-string
12916 (org-time-stamp-format nil 'inactive)
12917 org-log-note-effective-time))
12918 (cons "%D" (format-time-string
12919 (org-time-stamp-format nil nil)
12920 org-log-note-effective-time))
12921 (cons "%s" (if org-log-note-state
12922 (concat "\"" org-log-note-state "\"")
12923 ""))
12924 (cons "%S" (if org-log-note-previous-state
12925 (concat "\"" org-log-note-previous-state "\"")
12926 "\"\"")))))
12927 (if lines (setq note (concat note " \\\\")))
12928 (push note lines))
12929 (when (or current-prefix-arg org-note-abort)
12930 (when org-log-into-drawer
12931 (org-remove-empty-drawer-at
12932 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12933 org-log-note-marker))
12934 (setq lines nil))
12935 (when lines
12936 (with-current-buffer (marker-buffer org-log-note-marker)
12937 (save-excursion
12938 (goto-char org-log-note-marker)
12939 (move-marker org-log-note-marker nil)
12940 (end-of-line 1)
12941 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12942 (setq ind (save-excursion
12943 (if (ignore-errors (goto-char (org-in-item-p)))
12944 (let ((struct (org-list-struct)))
12945 (org-list-get-ind
12946 (org-list-get-top-point struct) struct))
12947 (skip-chars-backward " \r\t\n")
12948 (cond
12949 ((and (org-at-heading-p)
12950 org-adapt-indentation)
12951 (1+ (org-current-level)))
12952 ((org-at-heading-p) 0)
12953 (t (org-get-indentation))))))
12954 (setq bul (org-list-bullet-string "-"))
12955 (org-indent-line-to ind)
12956 (insert bul (pop lines))
12957 (let ((ind-body (+ (length bul) ind)))
12958 (while lines
12959 (insert "\n")
12960 (org-indent-line-to ind-body)
12961 (insert (pop lines))))
12962 (message "Note stored")
12963 (org-back-to-heading t)
12964 (org-cycle-hide-drawers 'children))))))
12965 (set-window-configuration org-log-note-window-configuration)
12966 (with-current-buffer (marker-buffer org-log-note-return-to)
12967 (goto-char org-log-note-return-to))
12968 (move-marker org-log-note-return-to nil)
12969 (and org-log-post-message (message "%s" org-log-post-message)))
12971 (defun org-remove-empty-drawer-at (drawer pos)
12972 "Remove an empty drawer DRAWER at position POS.
12973 POS may also be a marker."
12974 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12975 (save-excursion
12976 (save-restriction
12977 (widen)
12978 (goto-char pos)
12979 (if (org-in-regexp
12980 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12981 (replace-match ""))))))
12983 (defvar org-ts-type nil)
12984 (defun org-sparse-tree (&optional arg type)
12985 "Create a sparse tree, prompt for the details.
12986 This command can create sparse trees. You first need to select the type
12987 of match used to create the tree:
12989 t Show all TODO entries.
12990 T Show entries with a specific TODO keyword.
12991 m Show entries selected by a tags/property match.
12992 p Enter a property name and its value (both with completion on existing
12993 names/values) and show entries with that property.
12994 r Show entries matching a regular expression (`/' can be used as well).
12995 b Show deadlines and scheduled items before a date.
12996 a Show deadlines and scheduled items after a date.
12997 d Show deadlines due within `org-deadline-warning-days'.
12998 D Show deadlines and scheduled items between a date range."
12999 (interactive "P")
13000 (let (ans kwd value ts-type)
13001 (setq type (or type org-sparse-tree-default-date-type))
13002 (setq org-ts-type type)
13003 (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"
13004 (cond ((eq type 'all) "all timestamps")
13005 ((eq type 'scheduled) "only scheduled")
13006 ((eq type 'deadline) "only deadline")
13007 ((eq type 'active) "only active timestamps")
13008 ((eq type 'inactive) "only inactive timestamps")
13009 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13010 (t "scheduled/deadline")))
13011 (setq ans (read-char-exclusive))
13012 (cond
13013 ((equal ans ?c)
13014 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13015 ((equal ans ?d)
13016 (call-interactively 'org-check-deadlines))
13017 ((equal ans ?b)
13018 (call-interactively 'org-check-before-date))
13019 ((equal ans ?a)
13020 (call-interactively 'org-check-after-date))
13021 ((equal ans ?D)
13022 (call-interactively 'org-check-dates-range))
13023 ((equal ans ?t)
13024 (call-interactively 'org-show-todo-tree))
13025 ((equal ans ?T)
13026 (org-show-todo-tree '(4)))
13027 ((member ans '(?T ?m))
13028 (call-interactively 'org-match-sparse-tree))
13029 ((member ans '(?p ?P))
13030 (setq kwd (org-icompleting-read "Property: "
13031 (mapcar 'list (org-buffer-property-keys))))
13032 (setq value (org-icompleting-read "Value: "
13033 (mapcar 'list (org-property-values kwd))))
13034 (unless (string-match "\\`{.*}\\'" value)
13035 (setq value (concat "\"" value "\"")))
13036 (org-match-sparse-tree arg (concat kwd "=" value)))
13037 ((member ans '(?r ?R ?/))
13038 (call-interactively 'org-occur))
13039 (t (error "No such sparse tree command \"%c\"" ans)))))
13041 (defvar org-occur-highlights nil
13042 "List of overlays used for occur matches.")
13043 (make-variable-buffer-local 'org-occur-highlights)
13044 (defvar org-occur-parameters nil
13045 "Parameters of the active org-occur calls.
13046 This is a list, each call to org-occur pushes as cons cell,
13047 containing the regular expression and the callback, onto the list.
13048 The list can contain several entries if `org-occur' has been called
13049 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13050 will only contain one set of parameters. When the highlights are
13051 removed (for example with `C-c C-c', or with the next edit (depending
13052 on `org-remove-highlights-with-change'), this variable is emptied
13053 as well.")
13054 (make-variable-buffer-local 'org-occur-parameters)
13056 (defun org-occur (regexp &optional keep-previous callback)
13057 "Make a compact tree which shows all matches of REGEXP.
13058 The tree will show the lines where the regexp matches, and all higher
13059 headlines above the match. It will also show the heading after the match,
13060 to make sure editing the matching entry is easy.
13061 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13062 call to `org-occur' will be kept, to allow stacking of calls to this
13063 command.
13064 If CALLBACK is non-nil, it is a function which is called to confirm
13065 that the match should indeed be shown."
13066 (interactive "sRegexp: \nP")
13067 (when (equal regexp "")
13068 (error "Regexp cannot be empty"))
13069 (unless keep-previous
13070 (org-remove-occur-highlights nil nil t))
13071 (push (cons regexp callback) org-occur-parameters)
13072 (let ((cnt 0))
13073 (save-excursion
13074 (goto-char (point-min))
13075 (if (or (not keep-previous) ; do not want to keep
13076 (not org-occur-highlights)) ; no previous matches
13077 ;; hide everything
13078 (org-overview))
13079 (while (re-search-forward regexp nil t)
13080 (when (or (not callback)
13081 (save-match-data (funcall callback)))
13082 (setq cnt (1+ cnt))
13083 (when org-highlight-sparse-tree-matches
13084 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13085 (org-show-context 'occur-tree))))
13086 (when org-remove-highlights-with-change
13087 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13088 nil 'local))
13089 (unless org-sparse-tree-open-archived-trees
13090 (org-hide-archived-subtrees (point-min) (point-max)))
13091 (run-hooks 'org-occur-hook)
13092 (if (org-called-interactively-p 'interactive)
13093 (message "%d match(es) for regexp %s" cnt regexp))
13094 cnt))
13096 (defun org-occur-next-match (&optional n reset)
13097 "Function for `next-error-function' to find sparse tree matches.
13098 N is the number of matches to move, when negative move backwards.
13099 RESET is entirely ignored - this function always goes back to the
13100 starting point when no match is found."
13101 (let* ((limit (if (< n 0) (point-min) (point-max)))
13102 (search-func (if (< n 0)
13103 'previous-single-char-property-change
13104 'next-single-char-property-change))
13105 (n (abs n))
13106 (pos (point))
13108 (catch 'exit
13109 (while (setq p1 (funcall search-func (point) 'org-type))
13110 (when (equal p1 limit)
13111 (goto-char pos)
13112 (error "No more matches"))
13113 (when (equal (get-char-property p1 'org-type) 'org-occur)
13114 (setq n (1- n))
13115 (when (= n 0)
13116 (goto-char p1)
13117 (throw 'exit (point))))
13118 (goto-char p1))
13119 (goto-char p1)
13120 (error "No more matches"))))
13122 (defun org-show-context (&optional key)
13123 "Make sure point and context are visible.
13124 How much context is shown depends upon the variables
13125 `org-show-hierarchy-above', `org-show-following-heading',
13126 `org-show-entry-below' and `org-show-siblings'."
13127 (let ((heading-p (org-at-heading-p t))
13128 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13129 (following-p (org-get-alist-option org-show-following-heading key))
13130 (entry-p (org-get-alist-option org-show-entry-below key))
13131 (siblings-p (org-get-alist-option org-show-siblings key)))
13132 (catch 'exit
13133 ;; Show heading or entry text
13134 (if (and heading-p (not entry-p))
13135 (org-flag-heading nil) ; only show the heading
13136 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13137 (org-show-hidden-entry))) ; show entire entry
13138 (when following-p
13139 ;; Show next sibling, or heading below text
13140 (save-excursion
13141 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13142 (org-flag-heading nil))))
13143 (when siblings-p (org-show-siblings))
13144 (when hierarchy-p
13145 ;; show all higher headings, possibly with siblings
13146 (save-excursion
13147 (while (and (condition-case nil
13148 (progn (org-up-heading-all 1) t)
13149 (error nil))
13150 (not (bobp)))
13151 (org-flag-heading nil)
13152 (when siblings-p (org-show-siblings))))))))
13154 (defvar org-reveal-start-hook nil
13155 "Hook run before revealing a location.")
13157 (defun org-reveal (&optional siblings)
13158 "Show current entry, hierarchy above it, and the following headline.
13159 This can be used to show a consistent set of context around locations
13160 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13161 not t for the search context.
13163 With optional argument SIBLINGS, on each level of the hierarchy all
13164 siblings are shown. This repairs the tree structure to what it would
13165 look like when opened with hierarchical calls to `org-cycle'.
13166 With double optional argument \\[universal-argument] \\[universal-argument], \
13167 go to the parent and show the
13168 entire tree."
13169 (interactive "P")
13170 (run-hooks 'org-reveal-start-hook)
13171 (let ((org-show-hierarchy-above t)
13172 (org-show-following-heading t)
13173 (org-show-siblings (if siblings t org-show-siblings)))
13174 (org-show-context nil))
13175 (when (equal siblings '(16))
13176 (save-excursion
13177 (when (org-up-heading-safe)
13178 (org-show-subtree)
13179 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13181 (defun org-highlight-new-match (beg end)
13182 "Highlight from BEG to END and mark the highlight is an occur headline."
13183 (let ((ov (make-overlay beg end)))
13184 (overlay-put ov 'face 'secondary-selection)
13185 (overlay-put ov 'org-type 'org-occur)
13186 (push ov org-occur-highlights)))
13188 (defun org-remove-occur-highlights (&optional beg end noremove)
13189 "Remove the occur highlights from the buffer.
13190 BEG and END are ignored. If NOREMOVE is nil, remove this function
13191 from the `before-change-functions' in the current buffer."
13192 (interactive)
13193 (unless org-inhibit-highlight-removal
13194 (mapc 'delete-overlay org-occur-highlights)
13195 (setq org-occur-highlights nil)
13196 (setq org-occur-parameters nil)
13197 (unless noremove
13198 (remove-hook 'before-change-functions
13199 'org-remove-occur-highlights 'local))))
13201 ;;;; Priorities
13203 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13204 "Regular expression matching the priority indicator.")
13206 (defvar org-remove-priority-next-time nil)
13208 (defun org-priority-up ()
13209 "Increase the priority of the current item."
13210 (interactive)
13211 (org-priority 'up))
13213 (defun org-priority-down ()
13214 "Decrease the priority of the current item."
13215 (interactive)
13216 (org-priority 'down))
13218 (defun org-priority (&optional action show)
13219 "Change the priority of an item.
13220 ACTION can be `set', `up', `down', or a character."
13221 (interactive "P")
13222 (if (equal action '(4))
13223 (org-show-priority)
13224 (unless org-enable-priority-commands
13225 (error "Priority commands are disabled"))
13226 (setq action (or action 'set))
13227 (let (current new news have remove)
13228 (save-excursion
13229 (org-back-to-heading t)
13230 (if (looking-at org-priority-regexp)
13231 (setq current (string-to-char (match-string 2))
13232 have t))
13233 (cond
13234 ((eq action 'remove)
13235 (setq remove t new ?\ ))
13236 ((or (eq action 'set)
13237 (if (featurep 'xemacs) (characterp action) (integerp action)))
13238 (if (not (eq action 'set))
13239 (setq new action)
13240 (message "Priority %c-%c, SPC to remove: "
13241 org-highest-priority org-lowest-priority)
13242 (save-match-data
13243 (setq new (read-char-exclusive))))
13244 (if (and (= (upcase org-highest-priority) org-highest-priority)
13245 (= (upcase org-lowest-priority) org-lowest-priority))
13246 (setq new (upcase new)))
13247 (cond ((equal new ?\ ) (setq remove t))
13248 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13249 (error "Priority must be between `%c' and `%c'"
13250 org-highest-priority org-lowest-priority))))
13251 ((eq action 'up)
13252 (setq new (if have
13253 (1- current) ; normal cycling
13254 ;; last priority was empty
13255 (if (eq last-command this-command)
13256 org-lowest-priority ; wrap around empty to lowest
13257 ;; default
13258 (if org-priority-start-cycle-with-default
13259 org-default-priority
13260 (1- org-default-priority))))))
13261 ((eq action 'down)
13262 (setq new (if have
13263 (1+ current) ; normal cycling
13264 ;; last priority was empty
13265 (if (eq last-command this-command)
13266 org-highest-priority ; wrap around empty to highest
13267 ;; default
13268 (if org-priority-start-cycle-with-default
13269 org-default-priority
13270 (1+ org-default-priority))))))
13271 (t (error "Invalid action")))
13272 (if (or (< (upcase new) org-highest-priority)
13273 (> (upcase new) org-lowest-priority))
13274 (if (and (memq action '(up down))
13275 (not have) (not (eq last-command this-command)))
13276 ;; `new' is from default priority
13277 (error
13278 "The default can not be set, see `org-default-priority' why")
13279 ;; normal cycling: `new' is beyond highest/lowest priority
13280 ;; and is wrapped around to the empty priority
13281 (setq remove t)))
13282 (setq news (format "%c" new))
13283 (if have
13284 (if remove
13285 (replace-match "" t t nil 1)
13286 (replace-match news t t nil 2))
13287 (if remove
13288 (error "No priority cookie found in line")
13289 (let ((case-fold-search nil))
13290 (looking-at org-todo-line-regexp))
13291 (if (match-end 2)
13292 (progn
13293 (goto-char (match-end 2))
13294 (insert " [#" news "]"))
13295 (goto-char (match-beginning 3))
13296 (insert "[#" news "] "))))
13297 (org-preserve-lc (org-set-tags nil 'align)))
13298 (if remove
13299 (message "Priority removed")
13300 (message "Priority of current item set to %s" news)))))
13302 (defun org-show-priority ()
13303 "Show the priority of the current item.
13304 This priority is composed of the main priority given with the [#A] cookies,
13305 and by additional input from the age of a schedules or deadline entry."
13306 (interactive)
13307 (let ((pri (if (eq major-mode 'org-agenda-mode)
13308 (org-get-at-bol 'priority)
13309 (save-excursion
13310 (save-match-data
13311 (beginning-of-line)
13312 (and (looking-at org-heading-regexp)
13313 (org-get-priority (match-string 0))))))))
13314 (message "Priority is %d" (if pri pri -1000))))
13316 (defun org-get-priority (s)
13317 "Find priority cookie and return priority."
13318 (save-match-data
13319 (if (functionp org-get-priority-function)
13320 (funcall org-get-priority-function)
13321 (if (not (string-match org-priority-regexp s))
13322 (* 1000 (- org-lowest-priority org-default-priority))
13323 (* 1000 (- org-lowest-priority
13324 (string-to-char (match-string 2 s))))))))
13326 ;;;; Tags
13328 (defvar org-agenda-archives-mode)
13329 (defvar org-map-continue-from nil
13330 "Position from where mapping should continue.
13331 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13333 (defvar org-scanner-tags nil
13334 "The current tag list while the tags scanner is running.")
13335 (defvar org-trust-scanner-tags nil
13336 "Should `org-get-tags-at' use the tags for the scanner.
13337 This is for internal dynamical scoping only.
13338 When this is non-nil, the function `org-get-tags-at' will return the value
13339 of `org-scanner-tags' instead of building the list by itself. This
13340 can lead to large speed-ups when the tags scanner is used in a file with
13341 many entries, and when the list of tags is retrieved, for example to
13342 obtain a list of properties. Building the tags list for each entry in such
13343 a file becomes an N^2 operation - but with this variable set, it scales
13344 as N.")
13346 (defun org-scan-tags (action matcher todo-only &optional start-level)
13347 "Scan headline tags with inheritance and produce output ACTION.
13349 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13350 or `agenda' to produce an entry list for an agenda view. It can also be
13351 a Lisp form or a function that should be called at each matched headline, in
13352 this case the return value is a list of all return values from these calls.
13354 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13355 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13356 only lines with a not-done TODO keyword are included in the output.
13357 This should be the same variable that was scoped into
13358 and set by `org-make-tags-matcher' when it constructed MATCHER.
13360 START-LEVEL can be a string with asterisks, reducing the scope to
13361 headlines matching this string."
13362 (require 'org-agenda)
13363 (let* ((re (concat "^"
13364 (if start-level
13365 ;; Get the correct level to match
13366 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13367 org-outline-regexp)
13368 " *\\(\\<\\("
13369 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13370 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13371 (props (list 'face 'default
13372 'done-face 'org-agenda-done
13373 'undone-face 'default
13374 'mouse-face 'highlight
13375 'org-not-done-regexp org-not-done-regexp
13376 'org-todo-regexp org-todo-regexp
13377 'org-complex-heading-regexp org-complex-heading-regexp
13378 'help-echo
13379 (format "mouse-2 or RET jump to org file %s"
13380 (abbreviate-file-name
13381 (or (buffer-file-name (buffer-base-buffer))
13382 (buffer-name (buffer-base-buffer)))))))
13383 (case-fold-search nil)
13384 (org-map-continue-from nil)
13385 lspos tags tags-list
13386 (tags-alist (list (cons 0 org-file-tags)))
13387 (llast 0) rtn rtn1 level category i txt
13388 todo marker entry priority)
13389 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13390 (setq action (list 'lambda nil action)))
13391 (save-excursion
13392 (goto-char (point-min))
13393 (when (eq action 'sparse-tree)
13394 (org-overview)
13395 (org-remove-occur-highlights))
13396 (while (re-search-forward re nil t)
13397 (setq org-map-continue-from nil)
13398 (catch :skip
13399 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13400 tags (if (match-end 4) (org-match-string-no-properties 4)))
13401 (goto-char (setq lspos (match-beginning 0)))
13402 (setq level (org-reduced-level (org-outline-level))
13403 category (org-get-category))
13404 (setq i llast llast level)
13405 ;; remove tag lists from same and sublevels
13406 (while (>= i level)
13407 (when (setq entry (assoc i tags-alist))
13408 (setq tags-alist (delete entry tags-alist)))
13409 (setq i (1- i)))
13410 ;; add the next tags
13411 (when tags
13412 (setq tags (org-split-string tags ":")
13413 tags-alist
13414 (cons (cons level tags) tags-alist)))
13415 ;; compile tags for current headline
13416 (setq tags-list
13417 (if org-use-tag-inheritance
13418 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13419 tags)
13420 org-scanner-tags tags-list)
13421 (when org-use-tag-inheritance
13422 (setcdr (car tags-alist)
13423 (mapcar (lambda (x)
13424 (setq x (copy-sequence x))
13425 (org-add-prop-inherited x))
13426 (cdar tags-alist))))
13427 (when (and tags org-use-tag-inheritance
13428 (or (not (eq t org-use-tag-inheritance))
13429 org-tags-exclude-from-inheritance))
13430 ;; selective inheritance, remove uninherited ones
13431 (setcdr (car tags-alist)
13432 (org-remove-uninherited-tags (cdar tags-alist))))
13433 (when (and
13435 ;; eval matcher only when the todo condition is OK
13436 (and (or (not todo-only) (member todo org-not-done-keywords))
13437 (let ((case-fold-search t) (org-trust-scanner-tags t))
13438 (eval matcher)))
13440 ;; Call the skipper, but return t if it does not skip,
13441 ;; so that the `and' form continues evaluating
13442 (progn
13443 (unless (eq action 'sparse-tree) (org-agenda-skip))
13446 ;; Check if timestamps are deselecting this entry
13447 (or (not todo-only)
13448 (and (member todo org-not-done-keywords)
13449 (or (not org-agenda-tags-todo-honor-ignore-options)
13450 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13452 ;; select this headline
13453 (cond
13454 ((eq action 'sparse-tree)
13455 (and org-highlight-sparse-tree-matches
13456 (org-get-heading) (match-end 0)
13457 (org-highlight-new-match
13458 (match-beginning 1) (match-end 1)))
13459 (org-show-context 'tags-tree))
13460 ((eq action 'agenda)
13461 (setq txt (org-agenda-format-item
13463 (concat
13464 (if (eq org-tags-match-list-sublevels 'indented)
13465 (make-string (1- level) ?.) "")
13466 (org-get-heading))
13467 level category
13468 tags-list)
13469 priority (org-get-priority txt))
13470 (goto-char lspos)
13471 (setq marker (org-agenda-new-marker))
13472 (org-add-props txt props
13473 'org-marker marker 'org-hd-marker marker 'org-category category
13474 'todo-state todo
13475 'priority priority 'type "tagsmatch")
13476 (push txt rtn))
13477 ((functionp action)
13478 (setq org-map-continue-from nil)
13479 (save-excursion
13480 (setq rtn1 (funcall action))
13481 (push rtn1 rtn)))
13482 (t (error "Invalid action")))
13484 ;; if we are to skip sublevels, jump to end of subtree
13485 (unless org-tags-match-list-sublevels
13486 (org-end-of-subtree t)
13487 (backward-char 1))))
13488 ;; Get the correct position from where to continue
13489 (if org-map-continue-from
13490 (goto-char org-map-continue-from)
13491 (and (= (point) lspos) (end-of-line 1)))))
13492 (when (and (eq action 'sparse-tree)
13493 (not org-sparse-tree-open-archived-trees))
13494 (org-hide-archived-subtrees (point-min) (point-max)))
13495 (nreverse rtn)))
13497 (defun org-remove-uninherited-tags (tags)
13498 "Remove all tags that are not inherited from the list TAGS."
13499 (cond
13500 ((eq org-use-tag-inheritance t)
13501 (if org-tags-exclude-from-inheritance
13502 (org-delete-all org-tags-exclude-from-inheritance tags)
13503 tags))
13504 ((not org-use-tag-inheritance) nil)
13505 ((stringp org-use-tag-inheritance)
13506 (delq nil (mapcar
13507 (lambda (x)
13508 (if (and (string-match org-use-tag-inheritance x)
13509 (not (member x org-tags-exclude-from-inheritance)))
13510 x nil))
13511 tags)))
13512 ((listp org-use-tag-inheritance)
13513 (delq nil (mapcar
13514 (lambda (x)
13515 (if (member x org-use-tag-inheritance) x nil))
13516 tags)))))
13518 (defun org-match-sparse-tree (&optional todo-only match)
13519 "Create a sparse tree according to tags string MATCH.
13520 MATCH can contain positive and negative selection of tags, like
13521 \"+WORK+URGENT-WITHBOSS\".
13522 If optional argument TODO-ONLY is non-nil, only select lines that are
13523 also TODO lines."
13524 (interactive "P")
13525 (org-agenda-prepare-buffers (list (current-buffer)))
13526 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13528 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13530 (defvar org-cached-props nil)
13531 (defun org-cached-entry-get (pom property)
13532 (if (or (eq t org-use-property-inheritance)
13533 (and (stringp org-use-property-inheritance)
13534 (string-match org-use-property-inheritance property))
13535 (and (listp org-use-property-inheritance)
13536 (member property org-use-property-inheritance)))
13537 ;; Caching is not possible, check it directly
13538 (org-entry-get pom property 'inherit)
13539 ;; Get all properties, so that we can do complicated checks easily
13540 (cdr (assoc property (or org-cached-props
13541 (setq org-cached-props
13542 (org-entry-properties pom)))))))
13544 (defun org-global-tags-completion-table (&optional files)
13545 "Return the list of all tags in all agenda buffer/files.
13546 Optional FILES argument is a list of files which can be used
13547 instead of the agenda files."
13548 (save-excursion
13549 (org-uniquify
13550 (delq nil
13551 (apply 'append
13552 (mapcar
13553 (lambda (file)
13554 (set-buffer (find-file-noselect file))
13555 (append (org-get-buffer-tags)
13556 (mapcar (lambda (x) (if (stringp (car-safe x))
13557 (list (car-safe x)) nil))
13558 org-tag-alist)))
13559 (if (and files (car files))
13560 files
13561 (org-agenda-files))))))))
13563 (defun org-make-tags-matcher (match)
13564 "Create the TAGS/TODO matcher form for the selection string MATCH.
13566 The variable `todo-only' is scoped dynamically into this function.
13567 It will be set to t if the matcher restricts matching to TODO entries,
13568 otherwise will not be touched.
13570 Returns a cons of the selection string MATCH and the constructed
13571 lisp form implementing the matcher. The matcher is to be evaluated
13572 at an Org entry, with point on the headline, and returns t if the
13573 entry matches the selection string MATCH. The returned lisp form
13574 references two variables with information about the entry, which
13575 must be bound around the form's evaluation: todo, the TODO keyword
13576 at the entry (or nil of none); and tags-list, the list of all tags
13577 at the entry including inherited ones. Additionally, the category
13578 of the entry (if any) must be specified as the text property
13579 'org-category on the headline.
13581 See also `org-scan-tags'.
13583 (declare (special todo-only))
13584 (unless (boundp 'todo-only)
13585 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13586 (unless match
13587 ;; Get a new match request, with completion
13588 (let ((org-last-tags-completion-table
13589 (org-global-tags-completion-table)))
13590 (setq match (org-completing-read-no-i
13591 "Match: " 'org-tags-completion-function nil nil nil
13592 'org-tags-history))))
13594 ;; Parse the string and create a lisp form
13595 (let ((match0 match)
13596 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13597 minus tag mm
13598 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13599 orterms term orlist re-p str-p level-p level-op time-p
13600 prop-p pn pv po gv rest)
13601 (if (string-match "/+" match)
13602 ;; match contains also a todo-matching request
13603 (progn
13604 (setq tagsmatch (substring match 0 (match-beginning 0))
13605 todomatch (substring match (match-end 0)))
13606 (if (string-match "^!" todomatch)
13607 (setq todo-only t todomatch (substring todomatch 1)))
13608 (if (string-match "^\\s-*$" todomatch)
13609 (setq todomatch nil)))
13610 ;; only matching tags
13611 (setq tagsmatch match todomatch nil))
13613 ;; Make the tags matcher
13614 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13615 (setq tagsmatcher t)
13616 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13617 (while (setq term (pop orterms))
13618 (while (and (equal (substring term -1) "\\") orterms)
13619 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13620 (while (string-match re term)
13621 (setq rest (substring term (match-end 0))
13622 minus (and (match-end 1)
13623 (equal (match-string 1 term) "-"))
13624 tag (save-match-data (replace-regexp-in-string
13625 "\\\\-" "-"
13626 (match-string 2 term)))
13627 re-p (equal (string-to-char tag) ?{)
13628 level-p (match-end 4)
13629 prop-p (match-end 5)
13630 mm (cond
13631 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13632 (level-p
13633 (setq level-op (org-op-to-function (match-string 3 term)))
13634 `(,level-op level ,(string-to-number
13635 (match-string 4 term))))
13636 (prop-p
13637 (setq pn (match-string 5 term)
13638 po (match-string 6 term)
13639 pv (match-string 7 term)
13640 re-p (equal (string-to-char pv) ?{)
13641 str-p (equal (string-to-char pv) ?\")
13642 time-p (save-match-data
13643 (string-match "^\"[[<].*[]>]\"$" pv))
13644 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13645 (if time-p (setq pv (org-matcher-time pv)))
13646 (setq po (org-op-to-function po (if time-p 'time str-p)))
13647 (cond
13648 ((equal pn "CATEGORY")
13649 (setq gv '(get-text-property (point) 'org-category)))
13650 ((equal pn "TODO")
13651 (setq gv 'todo))
13653 (setq gv `(org-cached-entry-get nil ,pn))))
13654 (if re-p
13655 (if (eq po 'org<>)
13656 `(not (string-match ,pv (or ,gv "")))
13657 `(string-match ,pv (or ,gv "")))
13658 (if str-p
13659 `(,po (or ,gv "") ,pv)
13660 `(,po (string-to-number (or ,gv ""))
13661 ,(string-to-number pv) ))))
13662 (t `(member ,tag tags-list)))
13663 mm (if minus (list 'not mm) mm)
13664 term rest)
13665 (push mm tagsmatcher))
13666 (push (if (> (length tagsmatcher) 1)
13667 (cons 'and tagsmatcher)
13668 (car tagsmatcher))
13669 orlist)
13670 (setq tagsmatcher nil))
13671 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13672 (setq tagsmatcher
13673 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13674 ;; Make the todo matcher
13675 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13676 (setq todomatcher t)
13677 (setq orterms (org-split-string todomatch "|") orlist nil)
13678 (while (setq term (pop orterms))
13679 (while (string-match re term)
13680 (setq minus (and (match-end 1)
13681 (equal (match-string 1 term) "-"))
13682 kwd (match-string 2 term)
13683 re-p (equal (string-to-char kwd) ?{)
13684 term (substring term (match-end 0))
13685 mm (if re-p
13686 `(string-match ,(substring kwd 1 -1) todo)
13687 (list 'equal 'todo kwd))
13688 mm (if minus (list 'not mm) mm))
13689 (push mm todomatcher))
13690 (push (if (> (length todomatcher) 1)
13691 (cons 'and todomatcher)
13692 (car todomatcher))
13693 orlist)
13694 (setq todomatcher nil))
13695 (setq todomatcher (if (> (length orlist) 1)
13696 (cons 'or orlist) (car orlist))))
13698 ;; Return the string and lisp forms of the matcher
13699 (setq matcher (if todomatcher
13700 (list 'and tagsmatcher todomatcher)
13701 tagsmatcher))
13702 (when todo-only
13703 (setq matcher (list 'and '(member todo org-not-done-keywords)
13704 matcher)))
13705 (cons match0 matcher)))
13707 (defun org-op-to-function (op &optional stringp)
13708 "Turn an operator into the appropriate function."
13709 (setq op
13710 (cond
13711 ((equal op "<" ) '(< string< org-time<))
13712 ((equal op ">" ) '(> org-string> org-time>))
13713 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13714 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13715 ((member op '("=" "==")) '(= string= org-time=))
13716 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13717 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13719 (defun org<> (a b) (not (= a b)))
13720 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13721 (defun org-string>= (a b) (not (string< a b)))
13722 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13723 (defun org-string<> (a b) (not (string= a b)))
13724 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13725 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13726 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13727 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13728 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13729 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13730 (defun org-2ft (s)
13731 "Convert S to a floating point time.
13732 If S is already a number, just return it. If it is a string, parse
13733 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13734 (cond
13735 ((numberp s) s)
13736 ((stringp s)
13737 (condition-case nil
13738 (float-time (apply 'encode-time (org-parse-time-string s)))
13739 (error 0.)))
13740 (t 0.)))
13742 (defun org-time-today ()
13743 "Time in seconds today at 0:00.
13744 Returns the float number of seconds since the beginning of the
13745 epoch to the beginning of today (00:00)."
13746 (float-time (apply 'encode-time
13747 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13749 (defun org-matcher-time (s)
13750 "Interpret a time comparison value."
13751 (save-match-data
13752 (cond
13753 ((string= s "<now>") (float-time))
13754 ((string= s "<today>") (org-time-today))
13755 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13756 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13757 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13758 (+ (org-time-today)
13759 (* (string-to-number (match-string 1 s))
13760 (cdr (assoc (match-string 2 s)
13761 '(("d" . 86400.0) ("w" . 604800.0)
13762 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13763 (t (org-2ft s)))))
13765 (defun org-match-any-p (re list)
13766 "Does re match any element of list?"
13767 (setq list (mapcar (lambda (x) (string-match re x)) list))
13768 (delq nil list))
13770 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13771 (defvar org-tags-overlay (make-overlay 1 1))
13772 (org-detach-overlay org-tags-overlay)
13774 (defun org-get-local-tags-at (&optional pos)
13775 "Get a list of tags defined in the current headline."
13776 (org-get-tags-at pos 'local))
13778 (defun org-get-local-tags ()
13779 "Get a list of tags defined in the current headline."
13780 (org-get-tags-at nil 'local))
13782 (defun org-get-tags-at (&optional pos local)
13783 "Get a list of all headline tags applicable at POS.
13784 POS defaults to point. If tags are inherited, the list contains
13785 the targets in the same sequence as the headlines appear, i.e.
13786 the tags of the current headline come last.
13787 When LOCAL is non-nil, only return tags from the current headline,
13788 ignore inherited ones."
13789 (interactive)
13790 (if (and org-trust-scanner-tags
13791 (or (not pos) (equal pos (point)))
13792 (not local))
13793 org-scanner-tags
13794 (let (tags ltags lastpos parent)
13795 (save-excursion
13796 (save-restriction
13797 (widen)
13798 (goto-char (or pos (point)))
13799 (save-match-data
13800 (catch 'done
13801 (condition-case nil
13802 (progn
13803 (org-back-to-heading t)
13804 (while (not (equal lastpos (point)))
13805 (setq lastpos (point))
13806 (when (looking-at
13807 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13808 (setq ltags (org-split-string
13809 (org-match-string-no-properties 1) ":"))
13810 (when parent
13811 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13812 (setq tags (append
13813 (if parent
13814 (org-remove-uninherited-tags ltags)
13815 ltags)
13816 tags)))
13817 (or org-use-tag-inheritance (throw 'done t))
13818 (if local (throw 'done t))
13819 (or (org-up-heading-safe) (error nil))
13820 (setq parent t)))
13821 (error nil)))))
13822 (if local
13823 tags
13824 (reverse (delete-dups
13825 (reverse (append
13826 (org-remove-uninherited-tags
13827 org-file-tags) tags)))))))))
13829 (defun org-add-prop-inherited (s)
13830 (add-text-properties 0 (length s) '(inherited t) s)
13833 (defun org-toggle-tag (tag &optional onoff)
13834 "Toggle the tag TAG for the current line.
13835 If ONOFF is `on' or `off', don't toggle but set to this state."
13836 (let (res current)
13837 (save-excursion
13838 (org-back-to-heading t)
13839 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13840 (point-at-eol) t)
13841 (progn
13842 (setq current (match-string 1))
13843 (replace-match ""))
13844 (setq current ""))
13845 (setq current (nreverse (org-split-string current ":")))
13846 (cond
13847 ((eq onoff 'on)
13848 (setq res t)
13849 (or (member tag current) (push tag current)))
13850 ((eq onoff 'off)
13851 (or (not (member tag current)) (setq current (delete tag current))))
13852 (t (if (member tag current)
13853 (setq current (delete tag current))
13854 (setq res t)
13855 (push tag current))))
13856 (end-of-line 1)
13857 (if current
13858 (progn
13859 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13860 (org-set-tags nil t))
13861 (delete-horizontal-space))
13862 (run-hooks 'org-after-tags-change-hook))
13863 res))
13865 (defun org-align-tags-here (to-col)
13866 ;; Assumes that this is a headline
13867 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13868 (beginning-of-line 1)
13869 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13870 (< pos (match-beginning 2)))
13871 (progn
13872 (setq tags-l (- (match-end 2) (match-beginning 2)))
13873 (goto-char (match-beginning 1))
13874 (insert " ")
13875 (delete-region (point) (1+ (match-beginning 2)))
13876 (setq ncol (max (current-column)
13877 (1+ col)
13878 (if (> to-col 0)
13879 to-col
13880 (- (abs to-col) tags-l))))
13881 (setq p (point))
13882 (insert (make-string (- ncol (current-column)) ?\ ))
13883 (setq ncol (current-column))
13884 (when indent-tabs-mode (tabify p (point-at-eol)))
13885 (org-move-to-column (min ncol col) t))
13886 (goto-char pos))))
13888 (defun org-set-tags-command (&optional arg just-align)
13889 "Call the set-tags command for the current entry."
13890 (interactive "P")
13891 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13892 (org-set-tags arg just-align)
13893 (save-excursion
13894 (org-back-to-heading t)
13895 (org-set-tags arg just-align))))
13897 (defun org-set-tags-to (data)
13898 "Set the tags of the current entry to DATA, replacing the current tags.
13899 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13900 If DATA is nil or the empty string, any tags will be removed."
13901 (interactive "sTags: ")
13902 (setq data
13903 (cond
13904 ((eq data nil) "")
13905 ((equal data "") "")
13906 ((stringp data)
13907 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13908 ":"))
13909 ((listp data)
13910 (concat ":" (mapconcat 'identity data ":") ":"))))
13911 (when data
13912 (save-excursion
13913 (org-back-to-heading t)
13914 (when (looking-at org-complex-heading-regexp)
13915 (if (match-end 5)
13916 (progn
13917 (goto-char (match-beginning 5))
13918 (insert data)
13919 (delete-region (point) (point-at-eol))
13920 (org-set-tags nil 'align))
13921 (goto-char (point-at-eol))
13922 (insert " " data)
13923 (org-set-tags nil 'align)))
13924 (beginning-of-line 1)
13925 (if (looking-at ".*?\\([ \t]+\\)$")
13926 (delete-region (match-beginning 1) (match-end 1))))))
13928 (defun org-align-all-tags ()
13929 "Align the tags i all headings."
13930 (interactive)
13931 (save-excursion
13932 (or (ignore-errors (org-back-to-heading t))
13933 (outline-next-heading))
13934 (if (org-at-heading-p)
13935 (org-set-tags t)
13936 (message "No headings"))))
13938 (defvar org-indent-indentation-per-level)
13939 (defun org-set-tags (&optional arg just-align)
13940 "Set the tags for the current headline.
13941 With prefix ARG, realign all tags in headings in the current buffer."
13942 (interactive "P")
13943 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13944 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13945 'region-start-level 'region))
13946 org-loop-over-headlines-in-active-region)
13947 (org-map-entries
13948 ;; We don't use ARG and JUST-ALIGN here these args are not
13949 ;; useful when looping over headlines
13950 `(org-set-tags)
13951 org-loop-over-headlines-in-active-region
13952 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13953 (let* ((re org-outline-regexp-bol)
13954 (current (unless arg (org-get-tags-string)))
13955 (col (current-column))
13956 (org-setting-tags t)
13957 table current-tags inherited-tags ; computed below when needed
13958 tags p0 c0 c1 rpl di tc level)
13959 (if arg
13960 (save-excursion
13961 (goto-char (point-min))
13962 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13963 (while (re-search-forward re nil t)
13964 (org-set-tags nil t)
13965 (end-of-line 1)))
13966 (message "All tags realigned to column %d" org-tags-column))
13967 (if just-align
13968 (setq tags current)
13969 ;; Get a new set of tags from the user
13970 (save-excursion
13971 (setq table (append org-tag-persistent-alist
13972 (or org-tag-alist (org-get-buffer-tags))
13973 (and
13974 org-complete-tags-always-offer-all-agenda-tags
13975 (org-global-tags-completion-table
13976 (org-agenda-files))))
13977 org-last-tags-completion-table table
13978 current-tags (org-split-string current ":")
13979 inherited-tags (nreverse
13980 (nthcdr (length current-tags)
13981 (nreverse (org-get-tags-at))))
13982 tags
13983 (if (or (eq t org-use-fast-tag-selection)
13984 (and org-use-fast-tag-selection
13985 (delq nil (mapcar 'cdr table))))
13986 (org-fast-tag-selection
13987 current-tags inherited-tags table
13988 (if org-fast-tag-selection-include-todo
13989 org-todo-key-alist))
13990 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13991 (org-trim
13992 (org-icompleting-read "Tags: "
13993 'org-tags-completion-function
13994 nil nil current 'org-tags-history))))))
13995 (while (string-match "[-+&]+" tags)
13996 ;; No boolean logic, just a list
13997 (setq tags (replace-match ":" t t tags))))
13999 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14001 (if org-tags-sort-function
14002 (setq tags (mapconcat 'identity
14003 (sort (org-split-string
14004 tags (org-re "[^[:alnum:]_@#%]+"))
14005 org-tags-sort-function) ":")))
14007 (if (string-match "\\`[\t ]*\\'" tags)
14008 (setq tags "")
14009 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14010 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14012 ;; Insert new tags at the correct column
14013 (beginning-of-line 1)
14014 (setq level (or (and (looking-at org-outline-regexp)
14015 (- (match-end 0) (point) 1))
14017 (cond
14018 ((and (equal current "") (equal tags "")))
14019 ((re-search-forward
14020 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14021 (point-at-eol) t)
14022 (if (equal tags "")
14023 (setq rpl "")
14024 (goto-char (match-beginning 0))
14025 (setq c0 (current-column)
14026 ;; compute offset for the case of org-indent-mode active
14027 di (if org-indent-mode
14028 (* (1- org-indent-indentation-per-level) (1- level))
14030 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14031 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14032 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14033 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14034 (replace-match rpl t t)
14035 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14036 tags)
14037 (t (error "Tags alignment failed")))
14038 (org-move-to-column col)
14039 (unless just-align
14040 (run-hooks 'org-after-tags-change-hook))))))
14042 (defun org-change-tag-in-region (beg end tag off)
14043 "Add or remove TAG for each entry in the region.
14044 This works in the agenda, and also in an org-mode buffer."
14045 (interactive
14046 (list (region-beginning) (region-end)
14047 (let ((org-last-tags-completion-table
14048 (if (derived-mode-p 'org-mode)
14049 (org-get-buffer-tags)
14050 (org-global-tags-completion-table))))
14051 (org-icompleting-read
14052 "Tag: " 'org-tags-completion-function nil nil nil
14053 'org-tags-history))
14054 (progn
14055 (message "[s]et or [r]emove? ")
14056 (equal (read-char-exclusive) ?r))))
14057 (if (fboundp 'deactivate-mark) (deactivate-mark))
14058 (let ((agendap (equal major-mode 'org-agenda-mode))
14059 l1 l2 m buf pos newhead (cnt 0))
14060 (goto-char end)
14061 (setq l2 (1- (org-current-line)))
14062 (goto-char beg)
14063 (setq l1 (org-current-line))
14064 (loop for l from l1 to l2 do
14065 (org-goto-line l)
14066 (setq m (get-text-property (point) 'org-hd-marker))
14067 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14068 (and agendap m))
14069 (setq buf (if agendap (marker-buffer m) (current-buffer))
14070 pos (if agendap m (point)))
14071 (with-current-buffer buf
14072 (save-excursion
14073 (save-restriction
14074 (goto-char pos)
14075 (setq cnt (1+ cnt))
14076 (org-toggle-tag tag (if off 'off 'on))
14077 (setq newhead (org-get-heading)))))
14078 (and agendap (org-agenda-change-all-lines newhead m))))
14079 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14081 (defun org-tags-completion-function (string predicate &optional flag)
14082 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14083 (confirm (lambda (x) (stringp (car x)))))
14084 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14085 (setq s1 (match-string 1 string)
14086 s2 (match-string 2 string))
14087 (setq s1 "" s2 string))
14088 (cond
14089 ((eq flag nil)
14090 ;; try completion
14091 (setq rtn (try-completion s2 ctable confirm))
14092 (if (stringp rtn)
14093 (setq rtn
14094 (concat s1 s2 (substring rtn (length s2))
14095 (if (and org-add-colon-after-tag-completion
14096 (assoc rtn ctable))
14097 ":" ""))))
14098 rtn)
14099 ((eq flag t)
14100 ;; all-completions
14101 (all-completions s2 ctable confirm)
14103 ((eq flag 'lambda)
14104 ;; exact match?
14105 (assoc s2 ctable)))
14108 (defun org-fast-tag-insert (kwd tags face &optional end)
14109 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14110 (insert (format "%-12s" (concat kwd ":"))
14111 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14112 (or end "")))
14114 (defun org-fast-tag-show-exit (flag)
14115 (save-excursion
14116 (org-goto-line 3)
14117 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14118 (replace-match ""))
14119 (when flag
14120 (end-of-line 1)
14121 (org-move-to-column (- (window-width) 19) t)
14122 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14124 (defun org-set-current-tags-overlay (current prefix)
14125 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14126 (if (featurep 'xemacs)
14127 (org-overlay-display org-tags-overlay (concat prefix s)
14128 'secondary-selection)
14129 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14130 (org-overlay-display org-tags-overlay (concat prefix s)))))
14132 (defvar org-last-tag-selection-key nil)
14133 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14134 "Fast tag selection with single keys.
14135 CURRENT is the current list of tags in the headline, INHERITED is the
14136 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14137 possibly with grouping information. TODO-TABLE is a similar table with
14138 TODO keywords, should these have keys assigned to them.
14139 If the keys are nil, a-z are automatically assigned.
14140 Returns the new tags string, or nil to not change the current settings."
14141 (let* ((fulltable (append table todo-table))
14142 (maxlen (apply 'max (mapcar
14143 (lambda (x)
14144 (if (stringp (car x)) (string-width (car x)) 0))
14145 fulltable)))
14146 (buf (current-buffer))
14147 (expert (eq org-fast-tag-selection-single-key 'expert))
14148 (buffer-tags nil)
14149 (fwidth (+ maxlen 3 1 3))
14150 (ncol (/ (- (window-width) 4) fwidth))
14151 (i-face 'org-done)
14152 (c-face 'org-todo)
14153 tg cnt e c char c1 c2 ntable tbl rtn
14154 ov-start ov-end ov-prefix
14155 (exit-after-next org-fast-tag-selection-single-key)
14156 (done-keywords org-done-keywords)
14157 groups ingroup)
14158 (save-excursion
14159 (beginning-of-line 1)
14160 (if (looking-at
14161 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14162 (setq ov-start (match-beginning 1)
14163 ov-end (match-end 1)
14164 ov-prefix "")
14165 (setq ov-start (1- (point-at-eol))
14166 ov-end (1+ ov-start))
14167 (skip-chars-forward "^\n\r")
14168 (setq ov-prefix
14169 (concat
14170 (buffer-substring (1- (point)) (point))
14171 (if (> (current-column) org-tags-column)
14173 (make-string (- org-tags-column (current-column)) ?\ ))))))
14174 (move-overlay org-tags-overlay ov-start ov-end)
14175 (save-window-excursion
14176 (if expert
14177 (set-buffer (get-buffer-create " *Org tags*"))
14178 (delete-other-windows)
14179 (split-window-vertically)
14180 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14181 (erase-buffer)
14182 (org-set-local 'org-done-keywords done-keywords)
14183 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14184 (org-fast-tag-insert "Current" current c-face "\n\n")
14185 (org-fast-tag-show-exit exit-after-next)
14186 (org-set-current-tags-overlay current ov-prefix)
14187 (setq tbl fulltable char ?a cnt 0)
14188 (while (setq e (pop tbl))
14189 (cond
14190 ((equal (car e) :startgroup)
14191 (push '() groups) (setq ingroup t)
14192 (when (not (= cnt 0))
14193 (setq cnt 0)
14194 (insert "\n"))
14195 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14196 ((equal (car e) :endgroup)
14197 (setq ingroup nil cnt 0)
14198 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14199 ((equal e '(:newline))
14200 (when (not (= cnt 0))
14201 (setq cnt 0)
14202 (insert "\n")
14203 (setq e (car tbl))
14204 (while (equal (car tbl) '(:newline))
14205 (insert "\n")
14206 (setq tbl (cdr tbl)))))
14208 (setq tg (copy-sequence (car e)) c2 nil)
14209 (if (cdr e)
14210 (setq c (cdr e))
14211 ;; automatically assign a character.
14212 (setq c1 (string-to-char
14213 (downcase (substring
14214 tg (if (= (string-to-char tg) ?@) 1 0)))))
14215 (if (or (rassoc c1 ntable) (rassoc c1 table))
14216 (while (or (rassoc char ntable) (rassoc char table))
14217 (setq char (1+ char)))
14218 (setq c2 c1))
14219 (setq c (or c2 char)))
14220 (if ingroup (push tg (car groups)))
14221 (setq tg (org-add-props tg nil 'face
14222 (cond
14223 ((not (assoc tg table))
14224 (org-get-todo-face tg))
14225 ((member tg current) c-face)
14226 ((member tg inherited) i-face))))
14227 (if (and (= cnt 0) (not ingroup)) (insert " "))
14228 (insert "[" c "] " tg (make-string
14229 (- fwidth 4 (length tg)) ?\ ))
14230 (push (cons tg c) ntable)
14231 (when (= (setq cnt (1+ cnt)) ncol)
14232 (insert "\n")
14233 (if ingroup (insert " "))
14234 (setq cnt 0)))))
14235 (setq ntable (nreverse ntable))
14236 (insert "\n")
14237 (goto-char (point-min))
14238 (if (not expert) (org-fit-window-to-buffer))
14239 (setq rtn
14240 (catch 'exit
14241 (while t
14242 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14243 (if (not groups) "no " "")
14244 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14245 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14246 (setq org-last-tag-selection-key c)
14247 (cond
14248 ((= c ?\r) (throw 'exit t))
14249 ((= c ?!)
14250 (setq groups (not groups))
14251 (goto-char (point-min))
14252 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14253 ((= c ?\C-c)
14254 (if (not expert)
14255 (org-fast-tag-show-exit
14256 (setq exit-after-next (not exit-after-next)))
14257 (setq expert nil)
14258 (delete-other-windows)
14259 (set-window-buffer (split-window-vertically) " *Org tags*")
14260 (org-switch-to-buffer-other-window " *Org tags*")
14261 (org-fit-window-to-buffer)))
14262 ((or (= c ?\C-g)
14263 (and (= c ?q) (not (rassoc c ntable))))
14264 (org-detach-overlay org-tags-overlay)
14265 (setq quit-flag t))
14266 ((= c ?\ )
14267 (setq current nil)
14268 (if exit-after-next (setq exit-after-next 'now)))
14269 ((= c ?\t)
14270 (condition-case nil
14271 (setq tg (org-icompleting-read
14272 "Tag: "
14273 (or buffer-tags
14274 (with-current-buffer buf
14275 (org-get-buffer-tags)))))
14276 (quit (setq tg "")))
14277 (when (string-match "\\S-" tg)
14278 (add-to-list 'buffer-tags (list tg))
14279 (if (member tg current)
14280 (setq current (delete tg current))
14281 (push tg current)))
14282 (if exit-after-next (setq exit-after-next 'now)))
14283 ((setq e (rassoc c todo-table) tg (car e))
14284 (with-current-buffer buf
14285 (save-excursion (org-todo tg)))
14286 (if exit-after-next (setq exit-after-next 'now)))
14287 ((setq e (rassoc c ntable) tg (car e))
14288 (if (member tg current)
14289 (setq current (delete tg current))
14290 (loop for g in groups do
14291 (if (member tg g)
14292 (mapc (lambda (x)
14293 (setq current (delete x current)))
14294 g)))
14295 (push tg current))
14296 (if exit-after-next (setq exit-after-next 'now))))
14298 ;; Create a sorted list
14299 (setq current
14300 (sort current
14301 (lambda (a b)
14302 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14303 (if (eq exit-after-next 'now) (throw 'exit t))
14304 (goto-char (point-min))
14305 (beginning-of-line 2)
14306 (delete-region (point) (point-at-eol))
14307 (org-fast-tag-insert "Current" current c-face)
14308 (org-set-current-tags-overlay current ov-prefix)
14309 (while (re-search-forward
14310 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14311 (setq tg (match-string 1))
14312 (add-text-properties
14313 (match-beginning 1) (match-end 1)
14314 (list 'face
14315 (cond
14316 ((member tg current) c-face)
14317 ((member tg inherited) i-face)
14318 (t (get-text-property (match-beginning 1) 'face))))))
14319 (goto-char (point-min)))))
14320 (org-detach-overlay org-tags-overlay)
14321 (if rtn
14322 (mapconcat 'identity current ":")
14323 nil))))
14325 (defun org-get-tags-string ()
14326 "Get the TAGS string in the current headline."
14327 (unless (org-at-heading-p t)
14328 (error "Not on a heading"))
14329 (save-excursion
14330 (beginning-of-line 1)
14331 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14332 (org-match-string-no-properties 1)
14333 "")))
14335 (defun org-get-tags ()
14336 "Get the list of tags specified in the current headline."
14337 (org-split-string (org-get-tags-string) ":"))
14339 (defun org-get-buffer-tags ()
14340 "Get a table of all tags used in the buffer, for completion."
14341 (let (tags)
14342 (save-excursion
14343 (goto-char (point-min))
14344 (while (re-search-forward
14345 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14346 (when (equal (char-after (point-at-bol 0)) ?*)
14347 (mapc (lambda (x) (add-to-list 'tags x))
14348 (org-split-string (org-match-string-no-properties 1) ":")))))
14349 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14350 (mapcar 'list tags)))
14352 ;;;; The mapping API
14354 (defun org-map-entries (func &optional match scope &rest skip)
14355 "Call FUNC at each headline selected by MATCH in SCOPE.
14357 FUNC is a function or a lisp form. The function will be called without
14358 arguments, with the cursor positioned at the beginning of the headline.
14359 The return values of all calls to the function will be collected and
14360 returned as a list.
14362 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14363 does not need to preserve point. After evaluation, the cursor will be
14364 moved to the end of the line (presumably of the headline of the
14365 processed entry) and search continues from there. Under some
14366 circumstances, this may not produce the wanted results. For example,
14367 if you have removed (e.g. archived) the current (sub)tree it could
14368 mean that the next entry will be skipped entirely. In such cases, you
14369 can specify the position from where search should continue by making
14370 FUNC set the variable `org-map-continue-from' to the desired buffer
14371 position.
14373 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14374 Only headlines that are matched by this query will be considered during
14375 the iteration. When MATCH is nil or t, all headlines will be
14376 visited by the iteration.
14378 SCOPE determines the scope of this command. It can be any of:
14380 nil The current buffer, respecting the restriction if any
14381 tree The subtree started with the entry at point
14382 region The entries within the active region, if any
14383 region-start-level
14384 The entries within the active region, but only those at
14385 the same level than the first one.
14386 file The current buffer, without restriction
14387 file-with-archives
14388 The current buffer, and any archives associated with it
14389 agenda All agenda files
14390 agenda-with-archives
14391 All agenda files with any archive files associated with them
14392 \(file1 file2 ...)
14393 If this is a list, all files in the list will be scanned
14395 The remaining args are treated as settings for the skipping facilities of
14396 the scanner. The following items can be given here:
14398 archive skip trees with the archive tag.
14399 comment skip trees with the COMMENT keyword
14400 function or Emacs Lisp form:
14401 will be used as value for `org-agenda-skip-function', so whenever
14402 the function returns t, FUNC will not be called for that
14403 entry and search will continue from the point where the
14404 function leaves it.
14406 If your function needs to retrieve the tags including inherited tags
14407 at the *current* entry, you can use the value of the variable
14408 `org-scanner-tags' which will be much faster than getting the value
14409 with `org-get-tags-at'. If your function gets properties with
14410 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14411 to t around the call to `org-entry-properties' to get the same speedup.
14412 Note that if your function moves around to retrieve tags and properties at
14413 a *different* entry, you cannot use these techniques."
14414 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14415 (not (org-region-active-p)))
14416 (let* ((org-agenda-archives-mode nil) ; just to make sure
14417 (org-agenda-skip-archived-trees (memq 'archive skip))
14418 (org-agenda-skip-comment-trees (memq 'comment skip))
14419 (org-agenda-skip-function
14420 (car (org-delete-all '(comment archive) skip)))
14421 (org-tags-match-list-sublevels t)
14422 (start-level (eq scope 'region-start-level))
14423 matcher file res
14424 org-todo-keywords-for-agenda
14425 org-done-keywords-for-agenda
14426 org-todo-keyword-alist-for-agenda
14427 org-drawers-for-agenda
14428 org-tag-alist-for-agenda
14429 todo-only)
14431 (cond
14432 ((eq match t) (setq matcher t))
14433 ((eq match nil) (setq matcher t))
14434 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14436 (save-excursion
14437 (save-restriction
14438 (cond ((eq scope 'tree)
14439 (org-back-to-heading t)
14440 (org-narrow-to-subtree)
14441 (setq scope nil))
14442 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14443 (org-region-active-p))
14444 ;; If needed, set start-level to a string like "2"
14445 (when start-level
14446 (save-excursion
14447 (goto-char (region-beginning))
14448 (unless (org-at-heading-p) (outline-next-heading))
14449 (setq start-level (org-current-level))))
14450 (narrow-to-region (region-beginning)
14451 (save-excursion
14452 (goto-char (region-end))
14453 (unless (and (bolp) (org-at-heading-p))
14454 (outline-next-heading))
14455 (point)))
14456 (setq scope nil)))
14458 (if (not scope)
14459 (progn
14460 (org-agenda-prepare-buffers
14461 (list (buffer-file-name (current-buffer))))
14462 (setq res (org-scan-tags func matcher todo-only start-level)))
14463 ;; Get the right scope
14464 (cond
14465 ((and scope (listp scope) (symbolp (car scope)))
14466 (setq scope (eval scope)))
14467 ((eq scope 'agenda)
14468 (setq scope (org-agenda-files t)))
14469 ((eq scope 'agenda-with-archives)
14470 (setq scope (org-agenda-files t))
14471 (setq scope (org-add-archive-files scope)))
14472 ((eq scope 'file)
14473 (setq scope (list (buffer-file-name))))
14474 ((eq scope 'file-with-archives)
14475 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14476 (org-agenda-prepare-buffers scope)
14477 (while (setq file (pop scope))
14478 (with-current-buffer (org-find-base-buffer-visiting file)
14479 (save-excursion
14480 (save-restriction
14481 (widen)
14482 (goto-char (point-min))
14483 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14484 res)))
14486 ;;;; Properties
14488 ;;; Setting and retrieving properties
14490 (defconst org-special-properties
14491 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14492 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14493 "The special properties valid in Org-mode.
14495 These are properties that are not defined in the property drawer,
14496 but in some other way.")
14498 (defconst org-default-properties
14499 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14500 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14501 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14502 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14503 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14504 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14505 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14506 "Some properties that are used by Org-mode for various purposes.
14507 Being in this list makes sure that they are offered for completion.")
14509 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14510 "Regular expression matching the first line of a property drawer.")
14512 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14513 "Regular expression matching the last line of a property drawer.")
14515 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14516 "Regular expression matching the first line of a property drawer.")
14518 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14519 "Regular expression matching the first line of a property drawer.")
14521 (defconst org-property-drawer-re
14522 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14523 org-property-end-re "\\)\n?")
14524 "Matches an entire property drawer.")
14526 (defconst org-clock-drawer-re
14527 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14528 org-property-end-re "\\)\n?")
14529 "Matches an entire clock drawer.")
14531 (defsubst org-re-property (property)
14532 "Return a regexp matching a PROPERTY line.
14533 Match group 1 will be set to the value."
14534 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14536 (defsubst org-re-property-keyword (property)
14537 "Return a regexp matching a PROPERTY line, possibly with no
14538 value for the property."
14539 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14541 (defun org-property-action ()
14542 "Do an action on properties."
14543 (interactive)
14544 (let (c)
14545 (org-at-property-p)
14546 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14547 (setq c (read-char-exclusive))
14548 (cond
14549 ((equal c ?s)
14550 (call-interactively 'org-set-property))
14551 ((equal c ?d)
14552 (call-interactively 'org-delete-property))
14553 ((equal c ?D)
14554 (call-interactively 'org-delete-property-globally))
14555 ((equal c ?c)
14556 (call-interactively 'org-compute-property-at-point))
14557 (t (error "No such property action %c" c)))))
14559 (defun org-inc-effort ()
14560 "Increment the value of the effort property in the current entry."
14561 (interactive)
14562 (org-set-effort nil t))
14564 (defun org-set-effort (&optional value increment)
14565 "Set the effort property of the current entry.
14566 With numerical prefix arg, use the nth allowed value, 0 stands for the
14567 10th allowed value.
14569 When INCREMENT is non-nil, set the property to the next allowed value."
14570 (interactive "P")
14571 (if (equal value 0) (setq value 10))
14572 (let* ((completion-ignore-case t)
14573 (prop org-effort-property)
14574 (cur (org-entry-get nil prop))
14575 (allowed (org-property-get-allowed-values nil prop 'table))
14576 (existing (mapcar 'list (org-property-values prop)))
14578 (val (cond
14579 ((stringp value) value)
14580 ((and allowed (integerp value))
14581 (or (car (nth (1- value) allowed))
14582 (car (org-last allowed))))
14583 ((and allowed increment)
14584 (or (caadr (member (list cur) allowed))
14585 (error "Allowed effort values are not set")))
14586 (allowed
14587 (message "Select 1-9,0, [RET%s]: %s"
14588 (if cur (concat "=" cur) "")
14589 (mapconcat 'car allowed " "))
14590 (setq rpl (read-char-exclusive))
14591 (if (equal rpl ?\r)
14593 (setq rpl (- rpl ?0))
14594 (if (equal rpl 0) (setq rpl 10))
14595 (if (and (> rpl 0) (<= rpl (length allowed)))
14596 (car (nth (1- rpl) allowed))
14597 (org-completing-read "Effort: " allowed nil))))
14599 (let (org-completion-use-ido org-completion-use-iswitchb)
14600 (org-completing-read
14601 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14602 (concat "[" cur "]") "")
14603 ": ")
14604 existing nil nil "" nil cur))))))
14605 (unless (equal (org-entry-get nil prop) val)
14606 (org-entry-put nil prop val))
14607 (save-excursion
14608 (org-back-to-heading t)
14609 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14610 (message "%s is now %s" prop val)))
14612 (defun org-at-property-p ()
14613 "Is cursor inside a property drawer?"
14614 (save-excursion
14615 (beginning-of-line 1)
14616 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14617 (save-match-data ;; Used by calling procedures
14618 (let ((p (point))
14619 (range (unless (org-before-first-heading-p)
14620 (org-get-property-block))))
14621 (and range (<= (car range) p) (< p (cdr range))))))))
14623 (defun org-get-property-block (&optional beg end force)
14624 "Return the (beg . end) range of the body of the property drawer.
14625 BEG and END are the beginning and end of the current subtree, or of
14626 the part before the first headline. If they are not given, they will
14627 be found. If the drawer does not exist and FORCE is non-nil, create
14628 the drawer."
14629 (catch 'exit
14630 (save-excursion
14631 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14632 (progn (org-back-to-heading t) (point))))
14633 (end (or end (and (not (outline-next-heading)) (point-max))
14634 (point))))
14635 (goto-char beg)
14636 (if (re-search-forward org-property-start-re end t)
14637 (setq beg (1+ (match-end 0)))
14638 (if force
14639 (save-excursion
14640 (org-insert-property-drawer)
14641 (setq end (progn (outline-next-heading) (point))))
14642 (throw 'exit nil))
14643 (goto-char beg)
14644 (if (re-search-forward org-property-start-re end t)
14645 (setq beg (1+ (match-end 0)))))
14646 (if (re-search-forward org-property-end-re end t)
14647 (setq end (match-beginning 0))
14648 (or force (throw 'exit nil))
14649 (goto-char beg)
14650 (setq end beg)
14651 (org-indent-line)
14652 (insert ":END:\n"))
14653 (cons beg end)))))
14655 (defun org-entry-properties (&optional pom which specific)
14656 "Get all properties of the entry at point-or-marker POM.
14657 This includes the TODO keyword, the tags, time strings for deadline,
14658 scheduled, and clocking, and any additional properties defined in the
14659 entry. The return value is an alist, keys may occur multiple times
14660 if the property key was used several times.
14661 POM may also be nil, in which case the current entry is used.
14662 If WHICH is nil or `all', get all properties. If WHICH is
14663 `special' or `standard', only get that subclass. If WHICH
14664 is a string only get exactly this property. SPECIFIC can be a string, the
14665 specific property we are interested in. Specifying it can speed
14666 things up because then unnecessary parsing is avoided."
14667 (setq which (or which 'all))
14668 (org-with-point-at pom
14669 (let ((clockstr (substring org-clock-string 0 -1))
14670 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14671 (case-fold-search nil)
14672 beg end range props sum-props key key1 value string clocksum clocksumt)
14673 (save-excursion
14674 (when (condition-case nil
14675 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14676 (error nil))
14677 (setq beg (point))
14678 (setq sum-props (get-text-property (point) 'org-summaries))
14679 (setq clocksum (get-text-property (point) :org-clock-minutes)
14680 clocksumt (get-text-property (point) :org-clock-minutes-today))
14681 (outline-next-heading)
14682 (setq end (point))
14683 (when (memq which '(all special))
14684 ;; Get the special properties, like TODO and tags
14685 (goto-char beg)
14686 (when (and (or (not specific) (string= specific "TODO"))
14687 (looking-at org-todo-line-regexp) (match-end 2))
14688 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14689 (when (and (or (not specific) (string= specific "PRIORITY"))
14690 (looking-at org-priority-regexp))
14691 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14692 (when (or (not specific) (string= specific "FILE"))
14693 (push (cons "FILE" buffer-file-name) props))
14694 (when (and (or (not specific) (string= specific "TAGS"))
14695 (setq value (org-get-tags-string))
14696 (string-match "\\S-" value))
14697 (push (cons "TAGS" value) props))
14698 (when (and (or (not specific) (string= specific "ALLTAGS"))
14699 (setq value (org-get-tags-at)))
14700 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14701 ":"))
14702 props))
14703 (when (or (not specific) (string= specific "BLOCKED"))
14704 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14705 (when (or (not specific)
14706 (member specific
14707 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14708 "TIMESTAMP" "TIMESTAMP_IA")))
14709 (catch 'match
14710 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14711 (setq key (if (match-end 1)
14712 (substring (org-match-string-no-properties 1)
14713 0 -1))
14714 string (if (equal key clockstr)
14715 (org-trim
14716 (buffer-substring-no-properties
14717 (match-beginning 3) (goto-char
14718 (point-at-eol))))
14719 (substring (org-match-string-no-properties 3)
14720 1 -1)))
14721 ;; Get the correct property name from the key. This is
14722 ;; necessary if the user has configured time keywords.
14723 (setq key1 (concat key ":"))
14724 (cond
14725 ((not key)
14726 (setq key
14727 (if (= (char-after (match-beginning 3)) ?\[)
14728 "TIMESTAMP_IA" "TIMESTAMP")))
14729 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14730 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14731 ((equal key1 org-closed-string) (setq key "CLOSED"))
14732 ((equal key1 org-clock-string) (setq key "CLOCK")))
14733 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14734 (progn
14735 (push (cons key string) props)
14736 ;; no need to search further if match is found
14737 (throw 'match t))
14738 (when (or (equal key "CLOCK") (not (assoc key props)))
14739 (push (cons key string) props)))))))
14741 (when (memq which '(all standard))
14742 ;; Get the standard properties, like :PROP: ...
14743 (setq range (org-get-property-block beg end))
14744 (when range
14745 (goto-char (car range))
14746 (while (re-search-forward
14747 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14748 (cdr range) t)
14749 (setq key (org-match-string-no-properties 1)
14750 value (org-trim (or (org-match-string-no-properties 2) "")))
14751 (unless (member key excluded)
14752 (push (cons key (or value "")) props)))))
14753 (if clocksum
14754 (push (cons "CLOCKSUM"
14755 (org-columns-number-to-string (/ (float clocksum) 60.)
14756 'add_times))
14757 props))
14758 (if clocksumt
14759 (push (cons "CLOCKSUM_T"
14760 (org-columns-number-to-string (/ (float clocksumt) 60.)
14761 'add_times))
14762 props))
14763 (unless (assoc "CATEGORY" props)
14764 (push (cons "CATEGORY" (org-get-category)) props))
14765 (append sum-props (nreverse props)))))))
14767 (defun org-entry-get (pom property &optional inherit literal-nil)
14768 "Get value of PROPERTY for entry or content at point-or-marker POM.
14769 If INHERIT is non-nil and the entry does not have the property,
14770 then also check higher levels of the hierarchy.
14771 If INHERIT is the symbol `selective', use inheritance only if the setting
14772 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14773 If the property is present but empty, the return value is the empty string.
14774 If the property is not present at all, nil is returned.
14776 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14777 do not interpret it as the list atom nil. This is used for inheritance
14778 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14779 (org-with-point-at pom
14780 (if (and inherit (if (eq inherit 'selective)
14781 (org-property-inherit-p property)
14783 (org-entry-get-with-inheritance property literal-nil)
14784 (if (member property org-special-properties)
14785 ;; We need a special property. Use `org-entry-properties' to
14786 ;; retrieve it, but specify the wanted property
14787 (cdr (assoc property (org-entry-properties nil 'special property)))
14788 (let ((range (org-get-property-block)))
14789 (when (and range (not (eq (car range) (cdr range))))
14790 (let* ((props (list (or (assoc property org-file-properties)
14791 (assoc property org-global-properties)
14792 (assoc property org-global-properties-fixed))))
14793 (ap (lambda (key)
14794 (when (re-search-forward
14795 (org-re-property key) (cdr range) t)
14796 (setq props
14797 (org-update-property-plist
14799 (if (match-end 1)
14800 (org-match-string-no-properties 1) "")
14801 props)))))
14802 val)
14803 (goto-char (car range))
14804 (funcall ap property)
14805 (goto-char (car range))
14806 (while (funcall ap (concat property "+")))
14807 (setq val (cdr (assoc property props)))
14808 (when val (if literal-nil val (org-not-nil val))))))))))
14810 (defun org-property-or-variable-value (var &optional inherit)
14811 "Check if there is a property fixing the value of VAR.
14812 If yes, return this value. If not, return the current value of the variable."
14813 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14814 (if (and prop (stringp prop) (string-match "\\S-" prop))
14815 (read prop)
14816 (symbol-value var))))
14818 (defun org-entry-delete (pom property)
14819 "Delete the property PROPERTY from entry at point-or-marker POM."
14820 (org-with-point-at pom
14821 (if (member property org-special-properties)
14822 nil ; cannot delete these properties.
14823 (let ((range (org-get-property-block)))
14824 (if (and range
14825 (goto-char (car range))
14826 (re-search-forward
14827 (org-re-property property)
14828 (cdr range) t))
14829 (progn
14830 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14832 nil)))))
14834 ;; Multi-values properties are properties that contain multiple values
14835 ;; These values are assumed to be single words, separated by whitespace.
14836 (defun org-entry-add-to-multivalued-property (pom property value)
14837 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14838 (let* ((old (org-entry-get pom property))
14839 (values (and old (org-split-string old "[ \t]"))))
14840 (setq value (org-entry-protect-space value))
14841 (unless (member value values)
14842 (setq values (cons value values))
14843 (org-entry-put pom property
14844 (mapconcat 'identity values " ")))))
14846 (defun org-entry-remove-from-multivalued-property (pom property value)
14847 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14848 (let* ((old (org-entry-get pom property))
14849 (values (and old (org-split-string old "[ \t]"))))
14850 (setq value (org-entry-protect-space value))
14851 (when (member value values)
14852 (setq values (delete value values))
14853 (org-entry-put pom property
14854 (mapconcat 'identity values " ")))))
14856 (defun org-entry-member-in-multivalued-property (pom property value)
14857 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14858 (let* ((old (org-entry-get pom property))
14859 (values (and old (org-split-string old "[ \t]"))))
14860 (setq value (org-entry-protect-space value))
14861 (member value values)))
14863 (defun org-entry-get-multivalued-property (pom property)
14864 "Return a list of values in a multivalued property."
14865 (let* ((value (org-entry-get pom property))
14866 (values (and value (org-split-string value "[ \t]"))))
14867 (mapcar 'org-entry-restore-space values)))
14869 (defun org-entry-put-multivalued-property (pom property &rest values)
14870 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14871 VALUES should be a list of strings. Spaces will be protected."
14872 (org-entry-put pom property
14873 (mapconcat 'org-entry-protect-space values " "))
14874 (let* ((value (org-entry-get pom property))
14875 (values (and value (org-split-string value "[ \t]"))))
14876 (mapcar 'org-entry-restore-space values)))
14878 (defun org-entry-protect-space (s)
14879 "Protect spaces and newline in string S."
14880 (while (string-match " " s)
14881 (setq s (replace-match "%20" t t s)))
14882 (while (string-match "\n" s)
14883 (setq s (replace-match "%0A" t t s)))
14886 (defun org-entry-restore-space (s)
14887 "Restore spaces and newline in string S."
14888 (while (string-match "%20" s)
14889 (setq s (replace-match " " t t s)))
14890 (while (string-match "%0A" s)
14891 (setq s (replace-match "\n" t t s)))
14894 (defvar org-entry-property-inherited-from (make-marker)
14895 "Marker pointing to the entry from where a property was inherited.
14896 Each call to `org-entry-get-with-inheritance' will set this marker to the
14897 location of the entry where the inheritance search matched. If there was
14898 no match, the marker will point nowhere.
14899 Note that also `org-entry-get' calls this function, if the INHERIT flag
14900 is set.")
14902 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14903 "Get PROPERTY of entry or content at point, search higher levels if needed.
14904 The search will stop at the first ancestor which has the property defined.
14905 If the value found is \"nil\", return nil to show that the property
14906 should be considered as undefined (this is the meaning of nil here).
14907 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14908 (move-marker org-entry-property-inherited-from nil)
14909 (let (tmp)
14910 (save-excursion
14911 (save-restriction
14912 (widen)
14913 (catch 'ex
14914 (while t
14915 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14916 (or (ignore-errors (org-back-to-heading t))
14917 (goto-char (point-min)))
14918 (move-marker org-entry-property-inherited-from (point))
14919 (throw 'ex tmp))
14920 (or (ignore-errors (org-up-heading-safe))
14921 (throw 'ex nil))))))
14922 (setq tmp (or tmp
14923 (cdr (assoc property org-file-properties))
14924 (cdr (assoc property org-global-properties))
14925 (cdr (assoc property org-global-properties-fixed))))
14926 (if literal-nil tmp (org-not-nil tmp))))
14928 (defvar org-property-changed-functions nil
14929 "Hook called when the value of a property has changed.
14930 Each hook function should accept two arguments, the name of the property
14931 and the new value.")
14933 (defun org-entry-put (pom property value)
14934 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14935 (org-with-point-at pom
14936 (org-back-to-heading t)
14937 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14938 range)
14939 (cond
14940 ((equal property "TODO")
14941 (when (and (stringp value) (string-match "\\S-" value)
14942 (not (member value org-todo-keywords-1)))
14943 (error "\"%s\" is not a valid TODO state" value))
14944 (if (or (not value)
14945 (not (string-match "\\S-" value)))
14946 (setq value 'none))
14947 (org-todo value)
14948 (org-set-tags nil 'align))
14949 ((equal property "PRIORITY")
14950 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14951 (string-to-char value) ?\ ))
14952 (org-set-tags nil 'align))
14953 ((equal property "CLOCKSUM")
14954 (if (not (re-search-forward
14955 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14956 (error "Cannot find a clock log")
14957 (goto-char (- (match-end 1) 2))
14958 (cond
14959 ((eq value 'earlier) (org-timestamp-down))
14960 ((eq value 'later) (org-timestamp-up)))
14961 (org-clock-sum-current-item)))
14962 ((equal property "SCHEDULED")
14963 (if (re-search-forward org-scheduled-time-regexp end t)
14964 (cond
14965 ((eq value 'earlier) (org-timestamp-change -1 'day))
14966 ((eq value 'later) (org-timestamp-change 1 'day))
14967 (t (call-interactively 'org-schedule)))
14968 (call-interactively 'org-schedule)))
14969 ((equal property "DEADLINE")
14970 (if (re-search-forward org-deadline-time-regexp end t)
14971 (cond
14972 ((eq value 'earlier) (org-timestamp-change -1 'day))
14973 ((eq value 'later) (org-timestamp-change 1 'day))
14974 (t (call-interactively 'org-deadline)))
14975 (call-interactively 'org-deadline)))
14976 ((member property org-special-properties)
14977 (error "The %s property can not yet be set with `org-entry-put'"
14978 property))
14979 (t ; a non-special property
14980 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14981 (setq range (org-get-property-block beg end 'force))
14982 (goto-char (car range))
14983 (if (re-search-forward
14984 (org-re-property-keyword property) (cdr range) t)
14985 (progn
14986 (delete-region (match-beginning 0) (match-end 0))
14987 (goto-char (match-beginning 0)))
14988 (goto-char (cdr range))
14989 (insert "\n")
14990 (backward-char 1)
14991 (org-indent-line))
14992 (insert ":" property ":")
14993 (and value (insert " " value))
14994 (org-indent-line)))))
14995 (run-hook-with-args 'org-property-changed-functions property value)))
14997 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14998 "Get all property keys in the current buffer.
14999 With INCLUDE-SPECIALS, also list the special properties that reflect things
15000 like tags and TODO state.
15001 With INCLUDE-DEFAULTS, also include properties that has special meaning
15002 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15003 and others.
15004 With INCLUDE-COLUMNS, also include property names given in COLUMN
15005 formats in the current buffer."
15006 (let (rtn range cfmt s p)
15007 (save-excursion
15008 (save-restriction
15009 (widen)
15010 (goto-char (point-min))
15011 (while (re-search-forward org-property-start-re nil t)
15012 (setq range (org-get-property-block))
15013 (goto-char (car range))
15014 (while (re-search-forward
15015 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15016 (cdr range) t)
15017 (add-to-list 'rtn (org-match-string-no-properties 1)))
15018 (outline-next-heading))))
15020 (when include-specials
15021 (setq rtn (append org-special-properties rtn)))
15023 (when include-defaults
15024 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15025 (add-to-list 'rtn org-effort-property))
15027 (when include-columns
15028 (save-excursion
15029 (save-restriction
15030 (widen)
15031 (goto-char (point-min))
15032 (while (re-search-forward
15033 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15034 nil t)
15035 (setq cfmt (match-string 2) s 0)
15036 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15037 cfmt s)
15038 (setq s (match-end 0)
15039 p (match-string 1 cfmt))
15040 (unless (or (equal p "ITEM")
15041 (member p org-special-properties))
15042 (add-to-list 'rtn (match-string 1 cfmt))))))))
15044 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15046 (defun org-property-values (key)
15047 "Return a list of all values of property KEY in the current buffer."
15048 (save-excursion
15049 (save-restriction
15050 (widen)
15051 (goto-char (point-min))
15052 (let ((re (org-re-property key))
15053 values)
15054 (while (re-search-forward re nil t)
15055 (add-to-list 'values (org-trim (match-string 1))))
15056 (delete "" values)))))
15058 (defun org-insert-property-drawer ()
15059 "Insert a property drawer into the current entry."
15060 (org-back-to-heading t)
15061 (looking-at org-outline-regexp)
15062 (let ((indent (if org-adapt-indentation
15063 (- (match-end 0) (match-beginning 0))
15065 (beg (point))
15066 (re (concat "^[ \t]*" org-keyword-time-regexp))
15067 end hiddenp)
15068 (outline-next-heading)
15069 (setq end (point))
15070 (goto-char beg)
15071 (while (re-search-forward re end t))
15072 (setq hiddenp (outline-invisible-p))
15073 (end-of-line 1)
15074 (and (equal (char-after) ?\n) (forward-char 1))
15075 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15076 (if (member (match-string 1) '("CLOCK:" ":END:"))
15077 ;; just skip this line
15078 (beginning-of-line 2)
15079 ;; Drawer start, find the end
15080 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15081 (beginning-of-line 1)))
15082 (org-skip-over-state-notes)
15083 (skip-chars-backward " \t\n\r")
15084 (if (eq (char-before) ?*) (forward-char 1))
15085 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15086 (beginning-of-line 0)
15087 (org-indent-to-column indent)
15088 (beginning-of-line 2)
15089 (org-indent-to-column indent)
15090 (beginning-of-line 0)
15091 (if hiddenp
15092 (save-excursion
15093 (org-back-to-heading t)
15094 (hide-entry))
15095 (org-flag-drawer t))))
15097 (defun org-insert-drawer (&optional arg drawer)
15098 "Insert a drawer at point.
15100 Optional argument DRAWER, when non-nil, is a string representing
15101 drawer's name. Otherwise, the user is prompted for a name.
15103 If a region is active, insert the drawer around that region
15104 instead.
15106 Point is left between drawer's boundaries."
15107 (interactive "P")
15108 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15109 "LOGBOOK"))
15110 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15111 ;; internally by Org. They are meant to be inserted
15112 ;; automatically.
15113 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15114 ;; Remove system drawers from list. Note: For some reason,
15115 ;; `org-completing-read' ignores the predicate while
15116 ;; `completing-read' handles it fine.
15117 (drawer (if arg "PROPERTIES"
15118 (or drawer
15119 (completing-read
15120 "Drawer: " org-drawers
15121 (lambda (d) (not (member d system-drawers))))))))
15122 (cond
15123 ;; With C-u, fall back on `org-insert-property-drawer'
15124 (arg (org-insert-property-drawer))
15125 ;; With an active region, insert a drawer at point.
15126 ((not (org-region-active-p))
15127 (progn
15128 (unless (bolp) (insert "\n"))
15129 (insert (format ":%s:\n\n:END:\n" drawer))
15130 (forward-line -2)))
15131 ;; Otherwise, insert the drawer at point
15133 (let ((rbeg (region-beginning))
15134 (rend (copy-marker (region-end))))
15135 (unwind-protect
15136 (progn
15137 (goto-char rbeg)
15138 (beginning-of-line)
15139 (when (save-excursion
15140 (re-search-forward org-outline-regexp-bol rend t))
15141 (error "Drawers cannot contain headlines"))
15142 ;; Position point at the beginning of the first
15143 ;; non-blank line in region. Insert drawer's opening
15144 ;; there, then indent it.
15145 (org-skip-whitespace)
15146 (beginning-of-line)
15147 (insert ":" drawer ":\n")
15148 (forward-line -1)
15149 (indent-for-tab-command)
15150 ;; Move point to the beginning of the first blank line
15151 ;; after the last non-blank line in region. Insert
15152 ;; drawer's closing, then indent it.
15153 (goto-char rend)
15154 (skip-chars-backward " \r\t\n")
15155 (insert "\n:END:")
15156 (deactivate-mark t)
15157 (indent-for-tab-command)
15158 (unless (eolp) (insert "\n")))
15159 ;; Clear marker, whatever the outcome of insertion is.
15160 (set-marker rend nil)))))))
15162 (defvar org-property-set-functions-alist nil
15163 "Property set function alist.
15164 Each entry should have the following format:
15166 (PROPERTY . READ-FUNCTION)
15168 The read function will be called with the same argument as
15169 `org-completing-read'.")
15171 (defun org-set-property-function (property)
15172 "Get the function that should be used to set PROPERTY.
15173 This is computed according to `org-property-set-functions-alist'."
15174 (or (cdr (assoc property org-property-set-functions-alist))
15175 'org-completing-read))
15177 (defun org-read-property-value (property)
15178 "Read PROPERTY value from user."
15179 (let* ((completion-ignore-case t)
15180 (allowed (org-property-get-allowed-values nil property 'table))
15181 (cur (org-entry-get nil property))
15182 (prompt (concat property " value"
15183 (if (and cur (string-match "\\S-" cur))
15184 (concat " [" cur "]") "") ": "))
15185 (set-function (org-set-property-function property))
15186 (val (if allowed
15187 (funcall set-function prompt allowed nil
15188 (not (get-text-property 0 'org-unrestricted
15189 (caar allowed))))
15190 (let (org-completion-use-ido org-completion-use-iswitchb)
15191 (funcall set-function prompt
15192 (mapcar 'list (org-property-values property))
15193 nil nil "" nil cur)))))
15194 (if (equal val "")
15196 val)))
15198 (defvar org-last-set-property nil)
15199 (defvar org-last-set-property-value nil)
15200 (defun org-read-property-name ()
15201 "Read a property name."
15202 (let* ((completion-ignore-case t)
15203 (keys (org-buffer-property-keys nil t t))
15204 (default-prop (or (save-excursion
15205 (save-match-data
15206 (beginning-of-line)
15207 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15208 (null (string= (match-string 1) "END"))
15209 (match-string 1))))
15210 org-last-set-property))
15211 (property (org-icompleting-read
15212 (concat "Property"
15213 (if default-prop (concat " [" default-prop "]") "")
15214 ": ")
15215 (mapcar 'list keys)
15216 nil nil nil nil
15217 default-prop)))
15218 (if (member property keys)
15219 property
15220 (or (cdr (assoc (downcase property)
15221 (mapcar (lambda (x) (cons (downcase x) x))
15222 keys)))
15223 property))))
15225 (defun org-set-property-and-value (use-last)
15226 "Allow to set [PROPERTY]: [value] direction from prompt.
15227 When use-default, don't even ask, just use the last
15228 \"[PROPERTY]: [value]\" string from the history."
15229 (interactive "P")
15230 (let* ((completion-ignore-case t)
15231 (pv (or (and use-last org-last-set-property-value)
15232 (org-completing-read
15233 "Enter a \"[Property]: [value]\" pair: "
15234 nil nil nil nil nil
15235 org-last-set-property-value)))
15236 prop val)
15237 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15238 (setq prop (match-string 1 pv)
15239 val (match-string 2 pv))
15240 (org-set-property prop val))))
15242 (defun org-set-property (property value)
15243 "In the current entry, set PROPERTY to VALUE.
15244 When called interactively, this will prompt for a property name, offering
15245 completion on existing and default properties. And then it will prompt
15246 for a value, offering completion either on allowed values (via an inherited
15247 xxx_ALL property) or on existing values in other instances of this property
15248 in the current file."
15249 (interactive (list nil nil))
15250 (let* ((property (or property (org-read-property-name)))
15251 (value (or value (org-read-property-value property)))
15252 (fn (cdr (assoc property org-properties-postprocess-alist))))
15253 (setq org-last-set-property property)
15254 (setq org-last-set-property-value (concat property ": " value))
15255 ;; Possibly postprocess the inserted value:
15256 (when fn (setq value (funcall fn value)))
15257 (unless (equal (org-entry-get nil property) value)
15258 (org-entry-put nil property value))))
15260 (defun org-delete-property (property)
15261 "In the current entry, delete PROPERTY."
15262 (interactive
15263 (let* ((completion-ignore-case t)
15264 (prop (org-icompleting-read "Property: "
15265 (org-entry-properties nil 'standard))))
15266 (list prop)))
15267 (message "Property %s %s" property
15268 (if (org-entry-delete nil property)
15269 "deleted"
15270 "was not present in the entry")))
15272 (defun org-delete-property-globally (property)
15273 "Remove PROPERTY globally, from all entries."
15274 (interactive
15275 (let* ((completion-ignore-case t)
15276 (prop (org-icompleting-read
15277 "Globally remove property: "
15278 (mapcar 'list (org-buffer-property-keys)))))
15279 (list prop)))
15280 (save-excursion
15281 (save-restriction
15282 (widen)
15283 (goto-char (point-min))
15284 (let ((cnt 0))
15285 (while (re-search-forward
15286 (org-re-property property)
15287 nil t)
15288 (setq cnt (1+ cnt))
15289 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15290 (message "Property \"%s\" removed from %d entries" property cnt)))))
15292 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15294 (defun org-compute-property-at-point ()
15295 "Compute the property at point.
15296 This looks for an enclosing column format, extracts the operator and
15297 then applies it to the property in the column format's scope."
15298 (interactive)
15299 (unless (org-at-property-p)
15300 (error "Not at a property"))
15301 (let ((prop (org-match-string-no-properties 2)))
15302 (org-columns-get-format-and-top-level)
15303 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15304 (error "No operator defined for property %s" prop))
15305 (org-columns-compute prop)))
15307 (defvar org-property-allowed-value-functions nil
15308 "Hook for functions supplying allowed values for a specific property.
15309 The functions must take a single argument, the name of the property, and
15310 return a flat list of allowed values. If \":ETC\" is one of
15311 the values, this means that these values are intended as defaults for
15312 completion, but that other values should be allowed too.
15313 The functions must return nil if they are not responsible for this
15314 property.")
15316 (defun org-property-get-allowed-values (pom property &optional table)
15317 "Get allowed values for the property PROPERTY.
15318 When TABLE is non-nil, return an alist that can directly be used for
15319 completion."
15320 (let (vals)
15321 (cond
15322 ((equal property "TODO")
15323 (setq vals (org-with-point-at pom
15324 (append org-todo-keywords-1 '("")))))
15325 ((equal property "PRIORITY")
15326 (let ((n org-lowest-priority))
15327 (while (>= n org-highest-priority)
15328 (push (char-to-string n) vals)
15329 (setq n (1- n)))))
15330 ((member property org-special-properties))
15331 ((setq vals (run-hook-with-args-until-success
15332 'org-property-allowed-value-functions property)))
15334 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15335 (when (and vals (string-match "\\S-" vals))
15336 (setq vals (car (read-from-string (concat "(" vals ")"))))
15337 (setq vals (mapcar (lambda (x)
15338 (cond ((stringp x) x)
15339 ((numberp x) (number-to-string x))
15340 ((symbolp x) (symbol-name x))
15341 (t "???")))
15342 vals)))))
15343 (when (member ":ETC" vals)
15344 (setq vals (remove ":ETC" vals))
15345 (org-add-props (car vals) '(org-unrestricted t)))
15346 (if table (mapcar 'list vals) vals)))
15348 (defun org-property-previous-allowed-value (&optional previous)
15349 "Switch to the next allowed value for this property."
15350 (interactive)
15351 (org-property-next-allowed-value t))
15353 (defun org-property-next-allowed-value (&optional previous)
15354 "Switch to the next allowed value for this property."
15355 (interactive)
15356 (unless (org-at-property-p)
15357 (error "Not at a property"))
15358 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15359 (key (match-string 2))
15360 (value (match-string 3))
15361 (allowed (or (org-property-get-allowed-values (point) key)
15362 (and (member value '("[ ]" "[-]" "[X]"))
15363 '("[ ]" "[X]"))))
15364 nval)
15365 (unless allowed
15366 (error "Allowed values for this property have not been defined"))
15367 (if previous (setq allowed (reverse allowed)))
15368 (if (member value allowed)
15369 (setq nval (car (cdr (member value allowed)))))
15370 (setq nval (or nval (car allowed)))
15371 (if (equal nval value)
15372 (error "Only one allowed value for this property"))
15373 (org-at-property-p)
15374 (replace-match (concat " :" key ": " nval) t t)
15375 (org-indent-line)
15376 (beginning-of-line 1)
15377 (skip-chars-forward " \t")
15378 (when (equal prop org-effort-property)
15379 (save-excursion
15380 (org-back-to-heading t)
15381 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15382 (run-hook-with-args 'org-property-changed-functions key nval)))
15384 (defun org-find-olp (path &optional this-buffer)
15385 "Return a marker pointing to the entry at outline path OLP.
15386 If anything goes wrong, throw an error.
15387 You can wrap this call to catch the error like this:
15389 (condition-case msg
15390 (org-mobile-locate-entry (match-string 4))
15391 (error (nth 1 msg)))
15393 The return value will then be either a string with the error message,
15394 or a marker if everything is OK.
15396 If THIS-BUFFER is set, the outline path does not contain a file,
15397 only headings."
15398 (let* ((file (if this-buffer buffer-file-name (pop path)))
15399 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15400 (level 1)
15401 (lmin 1)
15402 (lmax 1)
15403 limit re end found pos heading cnt flevel)
15404 (unless buffer (error "File not found :%s" file))
15405 (with-current-buffer buffer
15406 (save-excursion
15407 (save-restriction
15408 (widen)
15409 (setq limit (point-max))
15410 (goto-char (point-min))
15411 (while (setq heading (pop path))
15412 (setq re (format org-complex-heading-regexp-format
15413 (regexp-quote heading)))
15414 (setq cnt 0 pos (point))
15415 (while (re-search-forward re end t)
15416 (setq level (- (match-end 1) (match-beginning 1)))
15417 (if (and (>= level lmin) (<= level lmax))
15418 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15419 (when (= cnt 0) (error "Heading not found on level %d: %s"
15420 lmax heading))
15421 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15422 lmax heading))
15423 (goto-char found)
15424 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15425 (setq end (save-excursion (org-end-of-subtree t t))))
15426 (when (org-at-heading-p)
15427 (point-marker)))))))
15429 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15430 "Find node HEADING in BUFFER.
15431 Return a marker to the heading if it was found, or nil if not.
15432 If POS-ONLY is set, return just the position instead of a marker.
15434 The heading text must match exact, but it may have a TODO keyword,
15435 a priority cookie and tags in the standard locations."
15436 (with-current-buffer (or buffer (current-buffer))
15437 (save-excursion
15438 (save-restriction
15439 (widen)
15440 (goto-char (point-min))
15441 (let (case-fold-search)
15442 (if (re-search-forward
15443 (format org-complex-heading-regexp-format
15444 (regexp-quote heading)) nil t)
15445 (if pos-only
15446 (match-beginning 0)
15447 (move-marker (make-marker) (match-beginning 0)))))))))
15449 (defun org-find-exact-heading-in-directory (heading &optional dir)
15450 "Find Org node headline HEADING in all .org files in directory DIR.
15451 When the target headline is found, return a marker to this location."
15452 (let ((files (directory-files (or dir default-directory)
15453 nil "\\`[^.#].*\\.org\\'"))
15454 file visiting m buffer)
15455 (catch 'found
15456 (while (setq file (pop files))
15457 (message "trying %s" file)
15458 (setq visiting (org-find-base-buffer-visiting file))
15459 (setq buffer (or visiting (find-file-noselect file)))
15460 (setq m (org-find-exact-headline-in-buffer
15461 heading buffer))
15462 (when (and (not m) (not visiting)) (kill-buffer buffer))
15463 (and m (throw 'found m))))))
15465 (defun org-find-entry-with-id (ident)
15466 "Locate the entry that contains the ID property with exact value IDENT.
15467 IDENT can be a string, a symbol or a number, this function will search for
15468 the string representation of it.
15469 Return the position where this entry starts, or nil if there is no such entry."
15470 (interactive "sID: ")
15471 (let ((id (cond
15472 ((stringp ident) ident)
15473 ((symbol-name ident) (symbol-name ident))
15474 ((numberp ident) (number-to-string ident))
15475 (t (error "IDENT %s must be a string, symbol or number" ident))))
15476 (case-fold-search nil))
15477 (save-excursion
15478 (save-restriction
15479 (widen)
15480 (goto-char (point-min))
15481 (when (re-search-forward
15482 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15483 nil t)
15484 (org-back-to-heading t)
15485 (point))))))
15487 ;;;; Timestamps
15489 (defvar org-last-changed-timestamp nil)
15490 (defvar org-last-inserted-timestamp nil
15491 "The last time stamp inserted with `org-insert-time-stamp'.")
15492 (defvar org-time-was-given) ; dynamically scoped parameter
15493 (defvar org-end-time-was-given) ; dynamically scoped parameter
15494 (defvar org-ts-what) ; dynamically scoped parameter
15496 (defun org-time-stamp (arg &optional inactive)
15497 "Prompt for a date/time and insert a time stamp.
15498 If the user specifies a time like HH:MM or if this command is
15499 called with at least one prefix argument, the time stamp contains
15500 the date and the time. Otherwise, only the date is be included.
15502 All parts of a date not specified by the user is filled in from
15503 the current date/time. So if you just press return without
15504 typing anything, the time stamp will represent the current
15505 date/time.
15507 If there is already a timestamp at the cursor, it will be
15508 modified.
15510 With two universal prefix arguments, insert an active timestamp
15511 with the current time without prompting the user."
15512 (interactive "P")
15513 (let* ((ts nil)
15514 (default-time
15515 ;; Default time is either today, or, when entering a range,
15516 ;; the range start.
15517 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15518 (save-excursion
15519 (re-search-backward
15520 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15521 (- (point) 20) t)))
15522 (apply 'encode-time (org-parse-time-string (match-string 1)))
15523 (current-time)))
15524 (default-input (and ts (org-get-compact-tod ts)))
15525 (repeater (save-excursion
15526 (save-match-data
15527 (beginning-of-line)
15528 (when (re-search-forward
15529 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15530 (save-excursion (progn (end-of-line) (point))) t)
15531 (match-string 0)))))
15532 org-time-was-given org-end-time-was-given time)
15533 (cond
15534 ((and (org-at-timestamp-p t)
15535 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15536 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15537 (insert "--")
15538 (setq time (let ((this-command this-command))
15539 (org-read-date arg 'totime nil nil
15540 default-time default-input inactive)))
15541 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15542 ((org-at-timestamp-p t)
15543 (setq time (let ((this-command this-command))
15544 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15545 (when (org-at-timestamp-p t) ; just to get the match data
15546 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15547 (replace-match "")
15548 (setq org-last-changed-timestamp
15549 (org-insert-time-stamp
15550 time (or org-time-was-given arg)
15551 inactive nil nil (list org-end-time-was-given)))
15552 (when repeater (goto-char (1- (point))) (insert " " repeater)
15553 (setq org-last-changed-timestamp
15554 (concat (substring org-last-inserted-timestamp 0 -1)
15555 " " repeater ">"))))
15556 (message "Timestamp updated"))
15557 ((equal arg '(16))
15558 (org-insert-time-stamp (current-time) t))
15560 (setq time (let ((this-command this-command))
15561 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15562 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15563 nil nil (list org-end-time-was-given))))))
15565 ;; FIXME: can we use this for something else, like computing time differences?
15566 (defun org-get-compact-tod (s)
15567 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15568 (let* ((t1 (match-string 1 s))
15569 (h1 (string-to-number (match-string 2 s)))
15570 (m1 (string-to-number (match-string 3 s)))
15571 (t2 (and (match-end 4) (match-string 5 s)))
15572 (h2 (and t2 (string-to-number (match-string 6 s))))
15573 (m2 (and t2 (string-to-number (match-string 7 s))))
15574 dh dm)
15575 (if (not t2)
15577 (setq dh (- h2 h1) dm (- m2 m1))
15578 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15579 (concat t1 "+" (number-to-string dh)
15580 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15582 (defun org-time-stamp-inactive (&optional arg)
15583 "Insert an inactive time stamp.
15584 An inactive time stamp is enclosed in square brackets instead of angle
15585 brackets. It is inactive in the sense that it does not trigger agenda entries,
15586 does not link to the calendar and cannot be changed with the S-cursor keys.
15587 So these are more for recording a certain time/date."
15588 (interactive "P")
15589 (org-time-stamp arg 'inactive))
15591 (defvar org-date-ovl (make-overlay 1 1))
15592 (overlay-put org-date-ovl 'face 'org-date-selected)
15593 (org-detach-overlay org-date-ovl)
15595 (defvar org-ans1) ; dynamically scoped parameter
15596 (defvar org-ans2) ; dynamically scoped parameter
15598 (defvar org-plain-time-of-day-regexp) ; defined below
15600 (defvar org-overriding-default-time nil) ; dynamically scoped
15601 (defvar org-read-date-overlay nil)
15602 (defvar org-dcst nil) ; dynamically scoped
15603 (defvar org-read-date-history nil)
15604 (defvar org-read-date-final-answer nil)
15605 (defvar org-read-date-analyze-futurep nil)
15606 (defvar org-read-date-analyze-forced-year nil)
15607 (defvar org-read-date-inactive)
15609 (defvar org-read-date-minibuffer-local-map
15610 (let ((map (make-sparse-keymap)))
15611 (set-keymap-parent map minibuffer-local-map)
15612 (org-defkey map (kbd ".")
15613 (lambda () (interactive)
15614 (org-eval-in-calendar '(calendar-goto-today))))
15615 (org-defkey map [(meta shift left)]
15616 (lambda () (interactive)
15617 (org-eval-in-calendar '(calendar-backward-month 1))))
15618 (org-defkey map [(meta shift right)]
15619 (lambda () (interactive)
15620 (org-eval-in-calendar '(calendar-forward-month 1))))
15621 (org-defkey map [(meta shift up)]
15622 (lambda () (interactive)
15623 (org-eval-in-calendar '(calendar-backward-year 1))))
15624 (org-defkey map [(meta shift down)]
15625 (lambda () (interactive)
15626 (org-eval-in-calendar '(calendar-forward-year 1))))
15627 (org-defkey map [?\e (shift left)]
15628 (lambda () (interactive)
15629 (org-eval-in-calendar '(calendar-backward-month 1))))
15630 (org-defkey map [?\e (shift right)]
15631 (lambda () (interactive)
15632 (org-eval-in-calendar '(calendar-forward-month 1))))
15633 (org-defkey map [?\e (shift up)]
15634 (lambda () (interactive)
15635 (org-eval-in-calendar '(calendar-backward-year 1))))
15636 (org-defkey map [?\e (shift down)]
15637 (lambda () (interactive)
15638 (org-eval-in-calendar '(calendar-forward-year 1))))
15639 (org-defkey map [(shift up)]
15640 (lambda () (interactive)
15641 (org-eval-in-calendar '(calendar-backward-week 1))))
15642 (org-defkey map [(shift down)]
15643 (lambda () (interactive)
15644 (org-eval-in-calendar '(calendar-forward-week 1))))
15645 (org-defkey map [(shift left)]
15646 (lambda () (interactive)
15647 (org-eval-in-calendar '(calendar-backward-day 1))))
15648 (org-defkey map [(shift right)]
15649 (lambda () (interactive)
15650 (org-eval-in-calendar '(calendar-forward-day 1))))
15651 (org-defkey map "!"
15652 (lambda () (interactive)
15653 (org-eval-in-calendar '(diary-view-entries))
15654 (message "")))
15655 (org-defkey map ">"
15656 (lambda () (interactive)
15657 (org-eval-in-calendar '(scroll-calendar-left 1))))
15658 (org-defkey map "<"
15659 (lambda () (interactive)
15660 (org-eval-in-calendar '(scroll-calendar-right 1))))
15661 (org-defkey map "\C-v"
15662 (lambda () (interactive)
15663 (org-eval-in-calendar
15664 '(calendar-scroll-left-three-months 1))))
15665 (org-defkey map "\M-v"
15666 (lambda () (interactive)
15667 (org-eval-in-calendar
15668 '(calendar-scroll-right-three-months 1))))
15669 map)
15670 "Keymap for minibuffer commands when using `org-read-date'.")
15672 (defun org-read-date (&optional org-with-time to-time from-string prompt
15673 default-time default-input inactive)
15674 "Read a date, possibly a time, and make things smooth for the user.
15675 The prompt will suggest to enter an ISO date, but you can also enter anything
15676 which will at least partially be understood by `parse-time-string'.
15677 Unrecognized parts of the date will default to the current day, month, year,
15678 hour and minute. If this command is called to replace a timestamp at point,
15679 or to enter the second timestamp of a range, the default time is taken
15680 from the existing stamp. Furthermore, the command prefers the future,
15681 so if you are giving a date where the year is not given, and the day-month
15682 combination is already past in the current year, it will assume you
15683 mean next year. For details, see the manual. A few examples:
15685 3-2-5 --> 2003-02-05
15686 feb 15 --> currentyear-02-15
15687 2/15 --> currentyear-02-15
15688 sep 12 9 --> 2009-09-12
15689 12:45 --> today 12:45
15690 22 sept 0:34 --> currentyear-09-22 0:34
15691 12 --> currentyear-currentmonth-12
15692 Fri --> nearest Friday (today or later)
15693 etc.
15695 Furthermore you can specify a relative date by giving, as the *first* thing
15696 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15697 change in days weeks, months, years.
15698 With a single plus or minus, the date is relative to today. With a double
15699 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15700 +4d --> four days from today
15701 +4 --> same as above
15702 +2w --> two weeks from today
15703 ++5 --> five days from default date
15705 The function understands only English month and weekday abbreviations.
15707 While prompting, a calendar is popped up - you can also select the
15708 date with the mouse (button 1). The calendar shows a period of three
15709 months. To scroll it to other months, use the keys `>' and `<'.
15710 If you don't like the calendar, turn it off with
15711 \(setq org-read-date-popup-calendar nil)
15713 With optional argument TO-TIME, the date will immediately be converted
15714 to an internal time.
15715 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15716 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15717 still enter a time, and this function will inform the calling routine
15718 about this change. The calling routine may then choose to change the
15719 format used to insert the time stamp into the buffer to include the time.
15720 With optional argument FROM-STRING, read from this string instead from
15721 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15722 the time/date that is used for everything that is not specified by the
15723 user."
15724 (require 'parse-time)
15725 (let* ((org-time-stamp-rounding-minutes
15726 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15727 (org-dcst org-display-custom-times)
15728 (ct (org-current-time))
15729 (org-def (or org-overriding-default-time default-time ct))
15730 (org-defdecode (decode-time org-def))
15731 (dummy (progn
15732 (when (< (nth 2 org-defdecode) org-extend-today-until)
15733 (setcar (nthcdr 2 org-defdecode) -1)
15734 (setcar (nthcdr 1 org-defdecode) 59)
15735 (setq org-def (apply 'encode-time org-defdecode)
15736 org-defdecode (decode-time org-def)))))
15737 (mouse-autoselect-window nil) ; Don't let the mouse jump
15738 (calendar-frame-setup nil)
15739 (calendar-setup nil)
15740 (calendar-move-hook nil)
15741 (calendar-view-diary-initially-flag nil)
15742 (calendar-view-holidays-initially-flag nil)
15743 (timestr (format-time-string
15744 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15745 (prompt (concat (if prompt (concat prompt " ") "")
15746 (format "Date+time [%s]: " timestr)))
15747 ans (org-ans0 "") org-ans1 org-ans2 final)
15749 (cond
15750 (from-string (setq ans from-string))
15751 (org-read-date-popup-calendar
15752 (save-excursion
15753 (save-window-excursion
15754 (calendar)
15755 (org-eval-in-calendar '(setq cursor-type nil) t)
15756 (unwind-protect
15757 (progn
15758 (calendar-forward-day (- (time-to-days org-def)
15759 (calendar-absolute-from-gregorian
15760 (calendar-current-date))))
15761 (org-eval-in-calendar nil t)
15762 (let* ((old-map (current-local-map))
15763 (map (copy-keymap calendar-mode-map))
15764 (minibuffer-local-map
15765 (copy-keymap org-read-date-minibuffer-local-map)))
15766 (org-defkey map (kbd "RET") 'org-calendar-select)
15767 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15768 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15769 (unwind-protect
15770 (progn
15771 (use-local-map map)
15772 (setq org-read-date-inactive inactive)
15773 (add-hook 'post-command-hook 'org-read-date-display)
15774 (setq org-ans0 (read-string prompt default-input
15775 'org-read-date-history nil))
15776 ;; org-ans0: from prompt
15777 ;; org-ans1: from mouse click
15778 ;; org-ans2: from calendar motion
15779 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15780 (remove-hook 'post-command-hook 'org-read-date-display)
15781 (use-local-map old-map)
15782 (when org-read-date-overlay
15783 (delete-overlay org-read-date-overlay)
15784 (setq org-read-date-overlay nil)))))
15785 (bury-buffer "*Calendar*")))))
15787 (t ; Naked prompt only
15788 (unwind-protect
15789 (setq ans (read-string prompt default-input
15790 'org-read-date-history timestr))
15791 (when org-read-date-overlay
15792 (delete-overlay org-read-date-overlay)
15793 (setq org-read-date-overlay nil)))))
15795 (setq final (org-read-date-analyze ans org-def org-defdecode))
15797 (when org-read-date-analyze-forced-year
15798 (message "Year was forced into %s"
15799 (if org-read-date-force-compatible-dates
15800 "compatible range (1970-2037)"
15801 "range representable on this machine"))
15802 (ding))
15804 ;; One round trip to get rid of 34th of August and stuff like that....
15805 (setq final (decode-time (apply 'encode-time final)))
15807 (setq org-read-date-final-answer ans)
15809 (if to-time
15810 (apply 'encode-time final)
15811 (if (and (boundp 'org-time-was-given) org-time-was-given)
15812 (format "%04d-%02d-%02d %02d:%02d"
15813 (nth 5 final) (nth 4 final) (nth 3 final)
15814 (nth 2 final) (nth 1 final))
15815 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15817 (defvar org-def)
15818 (defvar org-defdecode)
15819 (defvar org-with-time)
15820 (defun org-read-date-display ()
15821 "Display the current date prompt interpretation in the minibuffer."
15822 (when org-read-date-display-live
15823 (when org-read-date-overlay
15824 (delete-overlay org-read-date-overlay))
15825 (when (minibufferp (current-buffer))
15826 (save-excursion
15827 (end-of-line 1)
15828 (while (not (equal (buffer-substring
15829 (max (point-min) (- (point) 4)) (point))
15830 " "))
15831 (insert " ")))
15832 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15833 " " (or org-ans1 org-ans2)))
15834 (org-end-time-was-given nil)
15835 (f (org-read-date-analyze ans org-def org-defdecode))
15836 (fmts (if org-dcst
15837 org-time-stamp-custom-formats
15838 org-time-stamp-formats))
15839 (fmt (if (or org-with-time
15840 (and (boundp 'org-time-was-given) org-time-was-given))
15841 (cdr fmts)
15842 (car fmts)))
15843 (txt (format-time-string fmt (apply 'encode-time f)))
15844 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15845 (txt (concat "=> " txt)))
15846 (when (and org-end-time-was-given
15847 (string-match org-plain-time-of-day-regexp txt))
15848 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15849 org-end-time-was-given
15850 (substring txt (match-end 0)))))
15851 (when org-read-date-analyze-futurep
15852 (setq txt (concat txt " (=>F)")))
15853 (setq org-read-date-overlay
15854 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15855 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15857 (defun org-read-date-analyze (ans org-def org-defdecode)
15858 "Analyze the combined answer of the date prompt."
15859 ;; FIXME: cleanup and comment
15860 (let ((nowdecode (decode-time (current-time)))
15861 delta deltan deltaw deltadef year month day
15862 hour minute second wday pm h2 m2 tl wday1
15863 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15864 (setq org-read-date-analyze-futurep nil
15865 org-read-date-analyze-forced-year nil)
15866 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15867 (setq ans "+0"))
15869 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15870 (setq ans (replace-match "" t t ans)
15871 deltan (car delta)
15872 deltaw (nth 1 delta)
15873 deltadef (nth 2 delta)))
15875 ;; Check if there is an iso week date in there. If yes, store the
15876 ;; info and postpone interpreting it until the rest of the parsing
15877 ;; is done.
15878 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15879 (setq iso-year (if (match-end 1)
15880 (org-small-year-to-year
15881 (string-to-number (match-string 1 ans))))
15882 iso-weekday (if (match-end 3)
15883 (string-to-number (match-string 3 ans)))
15884 iso-week (string-to-number (match-string 2 ans)))
15885 (setq ans (replace-match "" t t ans)))
15887 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15888 (when (string-match
15889 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15890 (setq year (if (match-end 2)
15891 (string-to-number (match-string 2 ans))
15892 (progn (setq kill-year t)
15893 (string-to-number (format-time-string "%Y"))))
15894 month (string-to-number (match-string 3 ans))
15895 day (string-to-number (match-string 4 ans)))
15896 (if (< year 100) (setq year (+ 2000 year)))
15897 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15898 t nil ans)))
15900 ;; Help matching dotted european dates
15901 (when (string-match
15902 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15903 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15904 (setq kill-year t)
15905 (string-to-number (format-time-string "%Y")))
15906 day (string-to-number (match-string 1 ans))
15907 month (string-to-number (match-string 2 ans))
15908 ans (replace-match (format "%04d-%02d-%02d" year month day)
15909 t nil ans)))
15911 ;; Help matching american dates, like 5/30 or 5/30/7
15912 (when (string-match
15913 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15914 (setq year (if (match-end 4)
15915 (string-to-number (match-string 4 ans))
15916 (progn (setq kill-year t)
15917 (string-to-number (format-time-string "%Y"))))
15918 month (string-to-number (match-string 1 ans))
15919 day (string-to-number (match-string 2 ans)))
15920 (if (< year 100) (setq year (+ 2000 year)))
15921 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15922 t nil ans)))
15923 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15924 ;; If there is a time with am/pm, and *no* time without it, we convert
15925 ;; so that matching will be successful.
15926 (loop for i from 1 to 2 do ; twice, for end time as well
15927 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15928 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15929 (setq hour (string-to-number (match-string 1 ans))
15930 minute (if (match-end 3)
15931 (string-to-number (match-string 3 ans))
15933 pm (equal ?p
15934 (string-to-char (downcase (match-string 4 ans)))))
15935 (if (and (= hour 12) (not pm))
15936 (setq hour 0)
15937 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15938 (setq ans (replace-match (format "%02d:%02d" hour minute)
15939 t t ans))))
15941 ;; Check if a time range is given as a duration
15942 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15943 (setq hour (string-to-number (match-string 1 ans))
15944 h2 (+ hour (string-to-number (match-string 3 ans)))
15945 minute (string-to-number (match-string 2 ans))
15946 m2 (+ minute (if (match-end 5) (string-to-number
15947 (match-string 5 ans))0)))
15948 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15949 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15950 t t ans)))
15952 ;; Check if there is a time range
15953 (when (boundp 'org-end-time-was-given)
15954 (setq org-time-was-given nil)
15955 (when (and (string-match org-plain-time-of-day-regexp ans)
15956 (match-end 8))
15957 (setq org-end-time-was-given (match-string 8 ans))
15958 (setq ans (concat (substring ans 0 (match-beginning 7))
15959 (substring ans (match-end 7))))))
15961 (setq tl (parse-time-string ans)
15962 day (or (nth 3 tl) (nth 3 org-defdecode))
15963 month (or (nth 4 tl)
15964 (if (and org-read-date-prefer-future
15965 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15966 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15967 (nth 4 org-defdecode)))
15968 year (or (and (not kill-year) (nth 5 tl))
15969 (if (and org-read-date-prefer-future
15970 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15971 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15972 (nth 5 org-defdecode)))
15973 hour (or (nth 2 tl) (nth 2 org-defdecode))
15974 minute (or (nth 1 tl) (nth 1 org-defdecode))
15975 second (or (nth 0 tl) 0)
15976 wday (nth 6 tl))
15978 (when (and (eq org-read-date-prefer-future 'time)
15979 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15980 (equal day (nth 3 nowdecode))
15981 (equal month (nth 4 nowdecode))
15982 (equal year (nth 5 nowdecode))
15983 (nth 2 tl)
15984 (or (< (nth 2 tl) (nth 2 nowdecode))
15985 (and (= (nth 2 tl) (nth 2 nowdecode))
15986 (nth 1 tl)
15987 (< (nth 1 tl) (nth 1 nowdecode)))))
15988 (setq day (1+ day)
15989 futurep t))
15991 ;; Special date definitions below
15992 (cond
15993 (iso-week
15994 ;; There was an iso week
15995 (require 'cal-iso)
15996 (setq futurep nil)
15997 (setq year (or iso-year year)
15998 day (or iso-weekday wday 1)
15999 wday nil ; to make sure that the trigger below does not match
16000 iso-date (calendar-gregorian-from-absolute
16001 (calendar-absolute-from-iso
16002 (list iso-week day year))))
16003 ; FIXME: Should we also push ISO weeks into the future?
16004 ; (when (and org-read-date-prefer-future
16005 ; (not iso-year)
16006 ; (< (calendar-absolute-from-gregorian iso-date)
16007 ; (time-to-days (current-time))))
16008 ; (setq year (1+ year)
16009 ; iso-date (calendar-gregorian-from-absolute
16010 ; (calendar-absolute-from-iso
16011 ; (list iso-week day year)))))
16012 (setq month (car iso-date)
16013 year (nth 2 iso-date)
16014 day (nth 1 iso-date)))
16015 (deltan
16016 (setq futurep nil)
16017 (unless deltadef
16018 (let ((now (decode-time (current-time))))
16019 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16020 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16021 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16022 ((equal deltaw "m") (setq month (+ month deltan)))
16023 ((equal deltaw "y") (setq year (+ year deltan)))))
16024 ((and wday (not (nth 3 tl)))
16025 ;; Weekday was given, but no day, so pick that day in the week
16026 ;; on or after the derived date.
16027 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16028 (unless (equal wday wday1)
16029 (setq day (+ day (% (- wday wday1 -7) 7))))))
16030 (if (and (boundp 'org-time-was-given)
16031 (nth 2 tl))
16032 (setq org-time-was-given t))
16033 (if (< year 100) (setq year (+ 2000 year)))
16034 ;; Check of the date is representable
16035 (if org-read-date-force-compatible-dates
16036 (progn
16037 (if (< year 1970)
16038 (setq year 1970 org-read-date-analyze-forced-year t))
16039 (if (> year 2037)
16040 (setq year 2037 org-read-date-analyze-forced-year t)))
16041 (condition-case nil
16042 (ignore (encode-time second minute hour day month year))
16043 (error
16044 (setq year (nth 5 org-defdecode))
16045 (setq org-read-date-analyze-forced-year t))))
16046 (setq org-read-date-analyze-futurep futurep)
16047 (list second minute hour day month year)))
16049 (defvar parse-time-weekdays)
16050 (defun org-read-date-get-relative (s today default)
16051 "Check string S for special relative date string.
16052 TODAY and DEFAULT are internal times, for today and for a default.
16053 Return shift list (N what def-flag)
16054 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16055 N is the number of WHATs to shift.
16056 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16057 the DEFAULT date rather than TODAY."
16058 (require 'parse-time)
16059 (when (and
16060 (string-match
16061 (concat
16062 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16063 "\\([0-9]+\\)?"
16064 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16065 "\\([ \t]\\|$\\)") s)
16066 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16067 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16068 (string-to-char (substring (match-string 1 s) -1))
16069 ?+))
16070 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16071 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16072 (what (if (match-end 3) (match-string 3 s) "d"))
16073 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16074 (date (if rel default today))
16075 (wday (nth 6 (decode-time date)))
16076 delta)
16077 (if wday1
16078 (progn
16079 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16080 (if (= dir ?-) (setq delta (- delta 7)))
16081 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16082 (list delta "d" rel))
16083 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16085 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16086 "Turn a user-specified date into the internal representation.
16087 The internal representation needed by the calendar is (month day year).
16088 This is a wrapper to handle the brain-dead convention in calendar that
16089 user function argument order change dependent on argument order."
16090 (if (boundp 'calendar-date-style)
16091 (cond
16092 ((eq calendar-date-style 'american)
16093 (list arg1 arg2 arg3))
16094 ((eq calendar-date-style 'european)
16095 (list arg2 arg1 arg3))
16096 ((eq calendar-date-style 'iso)
16097 (list arg2 arg3 arg1)))
16098 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16099 (if (org-bound-and-true-p european-calendar-style)
16100 (list arg2 arg1 arg3)
16101 (list arg1 arg2 arg3)))))
16103 (defun org-eval-in-calendar (form &optional keepdate)
16104 "Eval FORM in the calendar window and return to current window.
16105 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16106 otherwise stick to the current value of `org-ans2'."
16107 (let ((sf (selected-frame))
16108 (sw (selected-window)))
16109 (select-window (get-buffer-window "*Calendar*" t))
16110 (eval form)
16111 (when (and (not keepdate) (calendar-cursor-to-date))
16112 (let* ((date (calendar-cursor-to-date))
16113 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16114 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16115 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16116 (select-window sw)
16117 (org-select-frame-set-input-focus sf)))
16119 (defun org-calendar-select ()
16120 "Return to `org-read-date' with the date currently selected.
16121 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16122 (interactive)
16123 (when (calendar-cursor-to-date)
16124 (let* ((date (calendar-cursor-to-date))
16125 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16126 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16127 (if (active-minibuffer-window) (exit-minibuffer))))
16129 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16130 "Insert a date stamp for the date given by the internal TIME.
16131 WITH-HM means use the stamp format that includes the time of the day.
16132 INACTIVE means use square brackets instead of angular ones, so that the
16133 stamp will not contribute to the agenda.
16134 PRE and POST are optional strings to be inserted before and after the
16135 stamp.
16136 The command returns the inserted time stamp."
16137 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16138 stamp)
16139 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16140 (insert-before-markers (or pre ""))
16141 (when (listp extra)
16142 (setq extra (car extra))
16143 (if (and (stringp extra)
16144 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16145 (setq extra (format "-%02d:%02d"
16146 (string-to-number (match-string 1 extra))
16147 (string-to-number (match-string 2 extra))))
16148 (setq extra nil)))
16149 (when extra
16150 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16151 (insert-before-markers (setq stamp (format-time-string fmt time)))
16152 (insert-before-markers (or post ""))
16153 (setq org-last-inserted-timestamp stamp)))
16155 (defun org-toggle-time-stamp-overlays ()
16156 "Toggle the use of custom time stamp formats."
16157 (interactive)
16158 (setq org-display-custom-times (not org-display-custom-times))
16159 (unless org-display-custom-times
16160 (let ((p (point-min)) (bmp (buffer-modified-p)))
16161 (while (setq p (next-single-property-change p 'display))
16162 (if (and (get-text-property p 'display)
16163 (eq (get-text-property p 'face) 'org-date))
16164 (remove-text-properties
16165 p (setq p (next-single-property-change p 'display))
16166 '(display t))))
16167 (set-buffer-modified-p bmp)))
16168 (if (featurep 'xemacs)
16169 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16170 (org-restart-font-lock)
16171 (setq org-table-may-need-update t)
16172 (if org-display-custom-times
16173 (message "Time stamps are overlaid with custom format")
16174 (message "Time stamp overlays removed")))
16176 (defun org-display-custom-time (beg end)
16177 "Overlay modified time stamp format over timestamp between BEG and END."
16178 (let* ((ts (buffer-substring beg end))
16179 t1 w1 with-hm tf time str w2 (off 0))
16180 (save-match-data
16181 (setq t1 (org-parse-time-string ts t))
16182 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16183 (setq off (- (match-end 0) (match-beginning 0)))))
16184 (setq end (- end off))
16185 (setq w1 (- end beg)
16186 with-hm (and (nth 1 t1) (nth 2 t1))
16187 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16188 time (org-fix-decoded-time t1)
16189 str (org-add-props
16190 (format-time-string
16191 (substring tf 1 -1) (apply 'encode-time time))
16192 nil 'mouse-face 'highlight)
16193 w2 (length str))
16194 (if (not (= w2 w1))
16195 (add-text-properties (1+ beg) (+ 2 beg)
16196 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16197 (if (featurep 'xemacs)
16198 (progn
16199 (put-text-property beg end 'invisible t)
16200 (put-text-property beg end 'end-glyph (make-glyph str)))
16201 (put-text-property beg end 'display str))))
16203 (defun org-translate-time (string)
16204 "Translate all timestamps in STRING to custom format.
16205 But do this only if the variable `org-display-custom-times' is set."
16206 (when org-display-custom-times
16207 (save-match-data
16208 (let* ((start 0)
16209 (re org-ts-regexp-both)
16210 t1 with-hm inactive tf time str beg end)
16211 (while (setq start (string-match re string start))
16212 (setq beg (match-beginning 0)
16213 end (match-end 0)
16214 t1 (save-match-data
16215 (org-parse-time-string (substring string beg end) t))
16216 with-hm (and (nth 1 t1) (nth 2 t1))
16217 inactive (equal (substring string beg (1+ beg)) "[")
16218 tf (funcall (if with-hm 'cdr 'car)
16219 org-time-stamp-custom-formats)
16220 time (org-fix-decoded-time t1)
16221 str (format-time-string
16222 (concat
16223 (if inactive "[" "<") (substring tf 1 -1)
16224 (if inactive "]" ">"))
16225 (apply 'encode-time time))
16226 string (replace-match str t t string)
16227 start (+ start (length str)))))))
16228 string)
16230 (defun org-fix-decoded-time (time)
16231 "Set 0 instead of nil for the first 6 elements of time.
16232 Don't touch the rest."
16233 (let ((n 0))
16234 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16236 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16238 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16239 "Difference between TIMESTAMP-STRING and now in days.
16240 If SECONDS is non-nil, return the difference in seconds."
16241 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16242 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16243 (funcall fdiff (current-time)))))
16245 (defun org-deadline-close (timestamp-string &optional ndays)
16246 "Is the time in TIMESTAMP-STRING close to the current date?"
16247 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16248 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16249 (not (org-entry-is-done-p))))
16251 (defun org-get-wdays (ts &optional delay zero-delay)
16252 "Get the deadline lead time appropriate for timestring TS.
16253 When DELAY is non-nil, get the delay time for scheduled items
16254 instead of the deadline lead time. When ZERO-DELAY is non-nil
16255 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16256 don't try to find the delay cookie in the scheduled timestamp."
16257 (let ((tv (if delay org-scheduled-delay-days
16258 org-deadline-warning-days)))
16259 (cond
16260 ((or (and delay (< tv 0))
16261 (and delay zero-delay (<= tv 0))
16262 (and (not delay) (<= tv 0)))
16263 ;; Enforce this value no matter what
16264 (- tv))
16265 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16266 ;; lead time is specified.
16267 (floor (* (string-to-number (match-string 1 ts))
16268 (cdr (assoc (match-string 2 ts)
16269 '(("d" . 1) ("w" . 7)
16270 ("m" . 30.4) ("y" . 365.25)
16271 ("h" . 0.041667)))))))
16272 ;; go for the default.
16273 (t tv))))
16275 (defun org-calendar-select-mouse (ev)
16276 "Return to `org-read-date' with the date currently selected.
16277 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16278 (interactive "e")
16279 (mouse-set-point ev)
16280 (when (calendar-cursor-to-date)
16281 (let* ((date (calendar-cursor-to-date))
16282 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16283 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16284 (if (active-minibuffer-window) (exit-minibuffer))))
16286 (defun org-check-deadlines (ndays)
16287 "Check if there are any deadlines due or past due.
16288 A deadline is considered due if it happens within `org-deadline-warning-days'
16289 days from today's date. If the deadline appears in an entry marked DONE,
16290 it is not shown. The prefix arg NDAYS can be used to test that many
16291 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16292 (interactive "P")
16293 (let* ((org-warn-days
16294 (cond
16295 ((equal ndays '(4)) 100000)
16296 (ndays (prefix-numeric-value ndays))
16297 (t (abs org-deadline-warning-days))))
16298 (case-fold-search nil)
16299 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16300 (callback
16301 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16303 (message "%d deadlines past-due or due within %d days"
16304 (org-occur regexp nil callback)
16305 org-warn-days)))
16307 (defsubst org-re-timestamp (type)
16308 "Return a regexp for timestamp TYPE.
16309 Allowed values for TYPE are:
16311 all: all timestamps
16312 active: only active timestamps (<...>)
16313 inactive: only inactive timestamps ([...])
16314 scheduled: only scheduled timestamps
16315 deadline: only deadline timestamps
16317 When TYPE is nil, fall back on returning a regexp that matches
16318 both scheduled and deadline timestamps."
16319 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16320 ((eq type 'active) org-ts-regexp)
16321 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16322 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16323 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16324 ((eq type 'scheduled-or-deadline)
16325 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16327 (defun org-check-before-date (date)
16328 "Check if there are deadlines or scheduled entries before DATE."
16329 (interactive (list (org-read-date)))
16330 (let ((case-fold-search nil)
16331 (regexp (org-re-timestamp org-ts-type))
16332 (callback
16333 (lambda () (time-less-p
16334 (org-time-string-to-time (match-string 1))
16335 (org-time-string-to-time date)))))
16336 (message "%d entries before %s"
16337 (org-occur regexp nil callback) date)))
16339 (defun org-check-after-date (date)
16340 "Check if there are deadlines or scheduled entries after DATE."
16341 (interactive (list (org-read-date)))
16342 (let ((case-fold-search nil)
16343 (regexp (org-re-timestamp org-ts-type))
16344 (callback
16345 (lambda () (not
16346 (time-less-p
16347 (org-time-string-to-time (match-string 1))
16348 (org-time-string-to-time date))))))
16349 (message "%d entries after %s"
16350 (org-occur regexp nil callback) date)))
16352 (defun org-check-dates-range (start-date end-date)
16353 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16354 (interactive (list (org-read-date nil nil nil "Range starts")
16355 (org-read-date nil nil nil "Range end")))
16356 (let ((case-fold-search nil)
16357 (regexp (org-re-timestamp org-ts-type))
16358 (callback
16359 (lambda ()
16360 (let ((match (match-string 1)))
16361 (and
16362 (not (time-less-p
16363 (org-time-string-to-time match)
16364 (org-time-string-to-time start-date)))
16365 (time-less-p
16366 (org-time-string-to-time match)
16367 (org-time-string-to-time end-date)))))))
16368 (message "%d entries between %s and %s"
16369 (org-occur regexp nil callback) start-date end-date)))
16371 (defun org-evaluate-time-range (&optional to-buffer)
16372 "Evaluate a time range by computing the difference between start and end.
16373 Normally the result is just printed in the echo area, but with prefix arg
16374 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16375 If the time range is actually in a table, the result is inserted into the
16376 next column.
16377 For time difference computation, a year is assumed to be exactly 365
16378 days in order to avoid rounding problems."
16379 (interactive "P")
16381 (org-clock-update-time-maybe)
16382 (save-excursion
16383 (unless (org-at-date-range-p t)
16384 (goto-char (point-at-bol))
16385 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16386 (if (not (org-at-date-range-p t))
16387 (error "Not at a time-stamp range, and none found in current line")))
16388 (let* ((ts1 (match-string 1))
16389 (ts2 (match-string 2))
16390 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16391 (match-end (match-end 0))
16392 (time1 (org-time-string-to-time ts1))
16393 (time2 (org-time-string-to-time ts2))
16394 (t1 (org-float-time time1))
16395 (t2 (org-float-time time2))
16396 (diff (abs (- t2 t1)))
16397 (negative (< (- t2 t1) 0))
16398 ;; (ys (floor (* 365 24 60 60)))
16399 (ds (* 24 60 60))
16400 (hs (* 60 60))
16401 (fy "%dy %dd %02d:%02d")
16402 (fy1 "%dy %dd")
16403 (fd "%dd %02d:%02d")
16404 (fd1 "%dd")
16405 (fh "%02d:%02d")
16406 y d h m align)
16407 (if havetime
16408 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16410 d (floor (/ diff ds)) diff (mod diff ds)
16411 h (floor (/ diff hs)) diff (mod diff hs)
16412 m (floor (/ diff 60)))
16413 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16415 d (floor (+ (/ diff ds) 0.5))
16416 h 0 m 0))
16417 (if (not to-buffer)
16418 (message "%s" (org-make-tdiff-string y d h m))
16419 (if (org-at-table-p)
16420 (progn
16421 (goto-char match-end)
16422 (setq align t)
16423 (and (looking-at " *|") (goto-char (match-end 0))))
16424 (goto-char match-end))
16425 (if (looking-at
16426 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16427 (replace-match ""))
16428 (if negative (insert " -"))
16429 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16430 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16431 (insert " " (format fh h m))))
16432 (if align (org-table-align))
16433 (message "Time difference inserted")))))
16435 (defun org-make-tdiff-string (y d h m)
16436 (let ((fmt "")
16437 (l nil))
16438 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16439 l (push y l)))
16440 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16441 l (push d l)))
16442 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16443 l (push h l)))
16444 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16445 l (push m l)))
16446 (apply 'format fmt (nreverse l))))
16448 (defun org-time-string-to-time (s &optional buffer pos)
16449 "Convert a timestamp string into internal time."
16450 (condition-case errdata
16451 (apply 'encode-time (org-parse-time-string s))
16452 (error (error "Bad timestamp `%s'%s\nError was: %s"
16453 s (if (not (and buffer pos))
16455 (format " at %d in buffer `%s'" pos buffer))
16456 (cdr errdata)))))
16458 (defun org-time-string-to-seconds (s)
16459 "Convert a timestamp string to a number of seconds."
16460 (org-float-time (org-time-string-to-time s)))
16462 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16463 "Convert a time stamp to an absolute day number.
16464 If there is a specifier for a cyclic time stamp, get the closest
16465 date to DAYNR.
16466 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16467 The variable date is bound by the calendar when this is called."
16468 (cond
16469 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16470 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16471 daynr
16472 (+ daynr 1000)))
16473 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16474 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16475 (time-to-days (current-time))) (match-string 0 s)
16476 prefer show-all))
16477 (t (time-to-days
16478 (condition-case errdata
16479 (apply 'encode-time (org-parse-time-string s))
16480 (error (error "Bad timestamp `%s'%s\nError was: %s"
16481 s (if (not (and buffer pos))
16483 (format " at %d in buffer `%s'" pos buffer))
16484 (cdr errdata))))))))
16486 (defun org-days-to-iso-week (days)
16487 "Return the iso week number."
16488 (require 'cal-iso)
16489 (car (calendar-iso-from-absolute days)))
16491 (defun org-small-year-to-year (year)
16492 "Convert 2-digit years into 4-digit years.
16493 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16494 The year 2000 cannot be abbreviated. Any year larger than 99
16495 is returned unchanged."
16496 (if (< year 38)
16497 (setq year (+ 2000 year))
16498 (if (< year 100)
16499 (setq year (+ 1900 year))))
16500 year)
16502 (defun org-time-from-absolute (d)
16503 "Return the time corresponding to date D.
16504 D may be an absolute day number, or a calendar-type list (month day year)."
16505 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16506 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16508 (defun org-calendar-holiday ()
16509 "List of holidays, for Diary display in Org-mode."
16510 (require 'holidays)
16511 (let ((hl (funcall
16512 (if (fboundp 'calendar-check-holidays)
16513 'calendar-check-holidays 'check-calendar-holidays) date)))
16514 (if hl (mapconcat 'identity hl "; "))))
16516 (defun org-diary-sexp-entry (sexp entry date)
16517 "Process a SEXP diary ENTRY for DATE."
16518 (require 'diary-lib)
16519 (let ((result (if calendar-debug-sexp
16520 (let ((stack-trace-on-error t))
16521 (eval (car (read-from-string sexp))))
16522 (condition-case nil
16523 (eval (car (read-from-string sexp)))
16524 (error
16525 (beep)
16526 (message "Bad sexp at line %d in %s: %s"
16527 (org-current-line)
16528 (buffer-file-name) sexp)
16529 (sleep-for 2))))))
16530 (cond ((stringp result) (split-string result "; "))
16531 ((and (consp result)
16532 (not (consp (cdr result)))
16533 (stringp (cdr result))) (cdr result))
16534 ((and (consp result)
16535 (stringp (car result))) result)
16536 (result entry))))
16538 (defun org-diary-to-ical-string (frombuf)
16539 "Get iCalendar entries from diary entries in buffer FROMBUF.
16540 This uses the icalendar.el library."
16541 (let* ((tmpdir (if (featurep 'xemacs)
16542 (temp-directory)
16543 temporary-file-directory))
16544 (tmpfile (make-temp-name
16545 (expand-file-name "orgics" tmpdir)))
16546 buf rtn b e)
16547 (with-current-buffer frombuf
16548 (icalendar-export-region (point-min) (point-max) tmpfile)
16549 (setq buf (find-buffer-visiting tmpfile))
16550 (set-buffer buf)
16551 (goto-char (point-min))
16552 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16553 (setq b (match-beginning 0)))
16554 (goto-char (point-max))
16555 (if (re-search-backward "^END:VEVENT" nil t)
16556 (setq e (match-end 0)))
16557 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16558 (kill-buffer buf)
16559 (delete-file tmpfile)
16560 rtn))
16562 (defun org-closest-date (start current change prefer show-all)
16563 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16564 When PREFER is `past', return a date that is either CURRENT or past.
16565 When PREFER is `future', return a date that is either CURRENT or future.
16566 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16567 ;; Make the proper lists from the dates
16568 (catch 'exit
16569 (let ((a1 '(("h" . hour)
16570 ("d" . day)
16571 ("w" . week)
16572 ("m" . month)
16573 ("y" . year)))
16574 (shour (nth 2 (org-parse-time-string start)))
16575 dn dw sday cday n1 n2 n0
16576 d m y y1 y2 date1 date2 nmonths nm ny m2)
16578 (setq start (org-date-to-gregorian start)
16579 current (org-date-to-gregorian
16580 (if show-all
16581 current
16582 (time-to-days (current-time))))
16583 sday (calendar-absolute-from-gregorian start)
16584 cday (calendar-absolute-from-gregorian current))
16586 (if (<= cday sday) (throw 'exit sday))
16588 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16589 (setq dn (string-to-number (match-string 1 change))
16590 dw (cdr (assoc (match-string 2 change) a1)))
16591 (error "Invalid change specifier: %s" change))
16592 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16593 (cond
16594 ((eq dw 'hour)
16595 (let ((missing-hours
16596 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16597 dn)))
16598 (setq n1 (if (zerop missing-hours) cday
16599 (- cday (1+ (floor (/ missing-hours 24)))))
16600 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16601 ((eq dw 'day)
16602 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16603 n2 (+ n1 dn)))
16604 ((eq dw 'year)
16605 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16606 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16607 (setq date1 (list m d y1)
16608 n1 (calendar-absolute-from-gregorian date1)
16609 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16610 n2 (calendar-absolute-from-gregorian date2)))
16611 ((eq dw 'month)
16612 ;; approx number of month between the two dates
16613 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16614 ;; How often does dn fit in there?
16615 (setq d (nth 1 start) m (car start) y (nth 2 start)
16616 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16617 m (+ m nm)
16618 ny (floor (/ m 12))
16619 y (+ y ny)
16620 m (- m (* ny 12)))
16621 (while (> m 12) (setq m (- m 12) y (1+ y)))
16622 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16623 (setq m2 (+ m dn) y2 y)
16624 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16625 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16626 (while (<= n2 cday)
16627 (setq n1 n2 m m2 y y2)
16628 (setq m2 (+ m dn) y2 y)
16629 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16630 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16631 ;; Make sure n1 is the earlier date
16632 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16633 (if show-all
16634 (cond
16635 ((eq prefer 'past) (if (= cday n2) n2 n1))
16636 ((eq prefer 'future) (if (= cday n1) n1 n2))
16637 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16638 (cond
16639 ((eq prefer 'past) (if (= cday n2) n2 n1))
16640 ((eq prefer 'future) (if (= cday n1) n1 n2))
16641 (t (if (= cday n1) n1 n2)))))))
16643 (defun org-date-to-gregorian (date)
16644 "Turn any specification of DATE into a Gregorian date for the calendar."
16645 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16646 ((and (listp date) (= (length date) 3)) date)
16647 ((stringp date)
16648 (setq date (org-parse-time-string date))
16649 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16650 ((listp date)
16651 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16653 (defun org-parse-time-string (s &optional nodefault)
16654 "Parse the standard Org-mode time string.
16655 This should be a lot faster than the normal `parse-time-string'.
16656 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16657 hour and minute fields will be nil if not given."
16658 (cond ((string-match org-ts-regexp0 s)
16659 (list 0
16660 (if (or (match-beginning 8) (not nodefault))
16661 (string-to-number (or (match-string 8 s) "0")))
16662 (if (or (match-beginning 7) (not nodefault))
16663 (string-to-number (or (match-string 7 s) "0")))
16664 (string-to-number (match-string 4 s))
16665 (string-to-number (match-string 3 s))
16666 (string-to-number (match-string 2 s))
16667 nil nil nil))
16668 ((string-match "^<[^>]+>$" s)
16669 (decode-time (seconds-to-time (org-matcher-time s))))
16670 (t (error "Not a standard Org-mode time string: %s" s))))
16672 (defun org-timestamp-up (&optional arg)
16673 "Increase the date item at the cursor by one.
16674 If the cursor is on the year, change the year. If it is on the month,
16675 the day or the time, change that.
16676 With prefix ARG, change by that many units."
16677 (interactive "p")
16678 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16680 (defun org-timestamp-down (&optional arg)
16681 "Decrease the date item at the cursor by one.
16682 If the cursor is on the year, change the year. If it is on the month,
16683 the day or the time, change that.
16684 With prefix ARG, change by that many units."
16685 (interactive "p")
16686 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16688 (defun org-timestamp-up-day (&optional arg)
16689 "Increase the date in the time stamp by one day.
16690 With prefix ARG, change that many days."
16691 (interactive "p")
16692 (if (and (not (org-at-timestamp-p t))
16693 (org-at-heading-p))
16694 (org-todo 'up)
16695 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16697 (defun org-timestamp-down-day (&optional arg)
16698 "Decrease the date in the time stamp by one day.
16699 With prefix ARG, change that many days."
16700 (interactive "p")
16701 (if (and (not (org-at-timestamp-p t))
16702 (org-at-heading-p))
16703 (org-todo 'down)
16704 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16706 (defun org-at-timestamp-p (&optional inactive-ok)
16707 "Determine if the cursor is in or at a timestamp."
16708 (interactive)
16709 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16710 (pos (point))
16711 (ans (or (looking-at tsr)
16712 (save-excursion
16713 (skip-chars-backward "^[<\n\r\t")
16714 (if (> (point) (point-min)) (backward-char 1))
16715 (and (looking-at tsr)
16716 (> (- (match-end 0) pos) -1))))))
16717 (and ans
16718 (boundp 'org-ts-what)
16719 (setq org-ts-what
16720 (cond
16721 ((= pos (match-beginning 0)) 'bracket)
16722 ;; Point is considered to be "on the bracket" whether
16723 ;; it's really on it or right after it.
16724 ((= pos (1- (match-end 0))) 'bracket)
16725 ((= pos (match-end 0)) 'after)
16726 ((org-pos-in-match-range pos 2) 'year)
16727 ((org-pos-in-match-range pos 3) 'month)
16728 ((org-pos-in-match-range pos 7) 'hour)
16729 ((org-pos-in-match-range pos 8) 'minute)
16730 ((or (org-pos-in-match-range pos 4)
16731 (org-pos-in-match-range pos 5)) 'day)
16732 ((and (> pos (or (match-end 8) (match-end 5)))
16733 (< pos (match-end 0)))
16734 (- pos (or (match-end 8) (match-end 5))))
16735 (t 'day))))
16736 ans))
16738 (defun org-toggle-timestamp-type ()
16739 "Toggle the type (<active> or [inactive]) of a time stamp."
16740 (interactive)
16741 (when (org-at-timestamp-p t)
16742 (let ((beg (match-beginning 0)) (end (match-end 0))
16743 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16744 (save-excursion
16745 (goto-char beg)
16746 (while (re-search-forward "[][<>]" end t)
16747 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16748 t t)))
16749 (message "Timestamp is now %sactive"
16750 (if (equal (char-after beg) ?<) "" "in")))))
16752 (defvar org-clock-history) ; defined in org-clock.el
16753 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16754 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16755 "Change the date in the time stamp at point.
16756 The date will be changed by N times WHAT. WHAT can be `day', `month',
16757 `year', `minute', `second'. If WHAT is not given, the cursor position
16758 in the timestamp determines what will be changed.
16759 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16760 (let ((origin (point)) origin-cat
16761 with-hm inactive
16762 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16763 org-ts-what
16764 extra rem
16765 ts time time0 fixnext clrgx)
16766 (if (not (org-at-timestamp-p t))
16767 (error "Not at a timestamp"))
16768 (if (and (not what) (eq org-ts-what 'bracket))
16769 (org-toggle-timestamp-type)
16770 ;; Point isn't on brackets. Remember the part of the time-stamp
16771 ;; the point was in. Indeed, size of time-stamps may change,
16772 ;; but point must be kept in the same category nonetheless.
16773 (setq origin-cat org-ts-what)
16774 (if (and (not what) (not (eq org-ts-what 'day))
16775 org-display-custom-times
16776 (get-text-property (point) 'display)
16777 (not (get-text-property (1- (point)) 'display)))
16778 (setq org-ts-what 'day))
16779 (setq org-ts-what (or what org-ts-what)
16780 inactive (= (char-after (match-beginning 0)) ?\[)
16781 ts (match-string 0))
16782 (replace-match "")
16783 (when (string-match
16784 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16786 (setq extra (match-string 1 ts))
16787 (if suppress-tmp-delay
16788 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16789 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16790 (setq with-hm t))
16791 (setq time0 (org-parse-time-string ts))
16792 (when (and updown
16793 (eq org-ts-what 'minute)
16794 (not current-prefix-arg))
16795 ;; This looks like s-up and s-down. Change by one rounding step.
16796 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16797 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16798 (setcar (cdr time0) (+ (nth 1 time0)
16799 (if (> n 0) (- rem) (- dm rem))))))
16800 (setq time
16801 (encode-time (or (car time0) 0)
16802 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16803 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16804 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16805 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16806 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16807 (nthcdr 6 time0)))
16808 (when (and (member org-ts-what '(hour minute))
16809 extra
16810 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16811 (setq extra (org-modify-ts-extra
16812 extra
16813 (if (eq org-ts-what 'hour) 2 5)
16814 n dm)))
16815 (when (integerp org-ts-what)
16816 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16817 (if (eq what 'calendar)
16818 (let ((cal-date (org-get-date-from-calendar)))
16819 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16820 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16821 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16822 (setcar time0 (or (car time0) 0))
16823 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16824 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16825 (setq time (apply 'encode-time time0))))
16826 ;; Insert the new time-stamp, and ensure point stays in the same
16827 ;; category as before (i.e. not after the last position in that
16828 ;; category).
16829 (let ((pos (point)))
16830 ;; Stay before inserted string. `save-excursion' is of no use.
16831 (setq org-last-changed-timestamp
16832 (org-insert-time-stamp time with-hm inactive nil nil extra))
16833 (goto-char pos))
16834 (save-match-data
16835 (looking-at org-ts-regexp3)
16836 (goto-char (cond
16837 ;; `day' category ends before `hour' if any, or at
16838 ;; the end of the day name.
16839 ((eq origin-cat 'day)
16840 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16841 ((eq origin-cat 'hour) (min (match-end 7) origin))
16842 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16843 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16844 ;; `year' and `month' have both fixed size: point
16845 ;; couldn't have moved into another part.
16846 (t origin))))
16847 ;; Update clock if on a CLOCK line.
16848 (org-clock-update-time-maybe)
16849 ;; Maybe adjust the closest clock in `org-clock-history'
16850 (when org-clock-adjust-closest
16851 (if (not (and (org-at-clock-log-p)
16852 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16853 org-clock-history))))))
16854 (message "No clock to adjust")
16855 (cond ((save-excursion ; fix previous clock?
16856 (re-search-backward org-ts-regexp0 nil t)
16857 (org-looking-back (concat org-clock-string " \\[")))
16858 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16859 ((save-excursion ; fix next clock?
16860 (re-search-backward org-ts-regexp0 nil t)
16861 (looking-at (concat org-ts-regexp0 "\\] =>")))
16862 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16863 (save-window-excursion
16864 ;; Find closest clock to point, adjust the previous/next one in history
16865 (let* ((p (save-excursion (org-back-to-heading t)))
16866 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16867 (clfixnth
16868 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16869 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16870 (if (not clfixpos)
16871 (message "No clock to adjust")
16872 (save-excursion
16873 (org-goto-marker-or-bmk clfixpos)
16874 (org-show-subtree)
16875 (when (re-search-forward clrgx nil t)
16876 (goto-char (match-beginning 1))
16877 (let (org-clock-adjust-closest)
16878 (org-timestamp-change n org-ts-what updown))
16879 (message "Clock adjusted in %s for heading: %s"
16880 (file-name-nondirectory (buffer-file-name))
16881 (org-get-heading t t)))))))))
16882 ;; Try to recenter the calendar window, if any.
16883 (if (and org-calendar-follow-timestamp-change
16884 (get-buffer-window "*Calendar*" t)
16885 (memq org-ts-what '(day month year)))
16886 (org-recenter-calendar (time-to-days time))))))
16888 (defun org-modify-ts-extra (s pos n dm)
16889 "Change the different parts of the lead-time and repeat fields in timestamp."
16890 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16891 ng h m new rem)
16892 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16893 (cond
16894 ((or (org-pos-in-match-range pos 2)
16895 (org-pos-in-match-range pos 3))
16896 (setq m (string-to-number (match-string 3 s))
16897 h (string-to-number (match-string 2 s)))
16898 (if (org-pos-in-match-range pos 2)
16899 (setq h (+ h n))
16900 (setq n (* dm (org-no-warnings (signum n))))
16901 (when (not (= 0 (setq rem (% m dm))))
16902 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16903 (setq m (+ m n)))
16904 (if (< m 0) (setq m (+ m 60) h (1- h)))
16905 (if (> m 59) (setq m (- m 60) h (1+ h)))
16906 (setq h (min 24 (max 0 h)))
16907 (setq ng 1 new (format "-%02d:%02d" h m)))
16908 ((org-pos-in-match-range pos 6)
16909 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16910 ((org-pos-in-match-range pos 5)
16911 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16913 ((org-pos-in-match-range pos 9)
16914 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16915 ((org-pos-in-match-range pos 8)
16916 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16918 (when ng
16919 (setq s (concat
16920 (substring s 0 (match-beginning ng))
16922 (substring s (match-end ng))))))
16925 (defun org-recenter-calendar (date)
16926 "If the calendar is visible, recenter it to DATE."
16927 (let ((cwin (get-buffer-window "*Calendar*" t)))
16928 (when cwin
16929 (let ((calendar-move-hook nil))
16930 (with-selected-window cwin
16931 (calendar-goto-date (if (listp date) date
16932 (calendar-gregorian-from-absolute date))))))))
16934 (defun org-goto-calendar (&optional arg)
16935 "Go to the Emacs calendar at the current date.
16936 If there is a time stamp in the current line, go to that date.
16937 A prefix ARG can be used to force the current date."
16938 (interactive "P")
16939 (let ((tsr org-ts-regexp) diff
16940 (calendar-move-hook nil)
16941 (calendar-view-holidays-initially-flag nil)
16942 (calendar-view-diary-initially-flag nil))
16943 (if (or (org-at-timestamp-p)
16944 (save-excursion
16945 (beginning-of-line 1)
16946 (looking-at (concat ".*" tsr))))
16947 (let ((d1 (time-to-days (current-time)))
16948 (d2 (time-to-days
16949 (org-time-string-to-time (match-string 1)))))
16950 (setq diff (- d2 d1))))
16951 (calendar)
16952 (calendar-goto-today)
16953 (if (and diff (not arg)) (calendar-forward-day diff))))
16955 (defun org-get-date-from-calendar ()
16956 "Return a list (month day year) of date at point in calendar."
16957 (with-current-buffer "*Calendar*"
16958 (save-match-data
16959 (calendar-cursor-to-date))))
16961 (defun org-date-from-calendar ()
16962 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16963 If there is already a time stamp at the cursor position, update it."
16964 (interactive)
16965 (if (org-at-timestamp-p t)
16966 (org-timestamp-change 0 'calendar)
16967 (let ((cal-date (org-get-date-from-calendar)))
16968 (org-insert-time-stamp
16969 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16971 (defcustom org-effort-durations
16972 `(("h" . 60)
16973 ("d" . ,(* 60 8))
16974 ("w" . ,(* 60 8 5))
16975 ("m" . ,(* 60 8 5 4))
16976 ("y" . ,(* 60 8 5 40)))
16977 "Conversion factor to minutes for an effort modifier.
16979 Each entry has the form (MODIFIER . MINUTES).
16981 In an effort string, a number followed by MODIFIER is multiplied
16982 by the specified number of MINUTES to obtain an effort in
16983 minutes.
16985 For example, if the value of this variable is ((\"hours\" . 60)), then an
16986 effort string \"2hours\" is equivalent to 120 minutes."
16987 :group 'org-agenda
16988 :version "24.1"
16989 :type '(alist :key-type (string :tag "Modifier")
16990 :value-type (number :tag "Minutes")))
16992 (defun org-minutes-to-clocksum-string (m)
16993 "Format number of minutes as a clocksum string.
16994 The format is determined by `org-time-clocksum-format',
16995 `org-time-clocksum-use-fractional' and
16996 `org-time-clocksum-fractional-format' and
16997 `org-time-clocksum-use-effort-durations'."
16998 (let ((clocksum "") h d w mo y fmt n)
16999 (setq h (if org-time-clocksum-use-effort-durations
17000 (cdr (assoc "h" org-effort-durations)) 60)
17001 d (if org-time-clocksum-use-effort-durations
17002 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17003 w (if org-time-clocksum-use-effort-durations
17004 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17005 mo (if org-time-clocksum-use-effort-durations
17006 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17007 y (if org-time-clocksum-use-effort-durations
17008 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17009 ;; fractional format
17010 (if org-time-clocksum-use-fractional
17011 (cond
17012 ;; single format string
17013 ((stringp org-time-clocksum-fractional-format)
17014 (format org-time-clocksum-fractional-format (/ m (float h))))
17015 ;; choice of fractional formats for different time units
17016 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17017 (> (/ (truncate m) (* y d h)) 0))
17018 (format fmt (/ m (* y d (float h)))))
17019 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17020 (> (/ (truncate m) (* mo d h)) 0))
17021 (format fmt (/ m (* mo d (float h)))))
17022 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17023 (> (/ (truncate m) (* w d h)) 0))
17024 (format fmt (/ m (* w d (float h)))))
17025 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17026 (> (/ (truncate m) (* d h)) 0))
17027 (format fmt (/ m (* d (float h)))))
17028 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17029 (> (/ (truncate m) h) 0))
17030 (format fmt (/ m (float h))))
17031 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17032 (format fmt m))
17033 ;; fall back to smallest time unit with a format
17034 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17035 (format fmt (/ m (float h))))
17036 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17037 (format fmt (/ m (* d (float h)))))
17038 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17039 (format fmt (/ m (* w d (float h)))))
17040 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17041 (format fmt (/ m (* mo d (float h)))))
17042 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17043 (format fmt (/ m (* y d (float h))))))
17044 ;; standard (non-fractional) format, with single format string
17045 (if (stringp org-time-clocksum-format)
17046 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17047 ;; separate formats components
17048 (and (setq fmt (plist-get org-time-clocksum-format :years))
17049 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17050 (plist-get org-time-clocksum-format :require-years))
17051 (setq clocksum (concat clocksum (format fmt n))
17052 m (- m (* n y d h))))
17053 (and (setq fmt (plist-get org-time-clocksum-format :months))
17054 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17055 (plist-get org-time-clocksum-format :require-months))
17056 (setq clocksum (concat clocksum (format fmt n))
17057 m (- m (* n mo d h))))
17058 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17059 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17060 (plist-get org-time-clocksum-format :require-weeks))
17061 (setq clocksum (concat clocksum (format fmt n))
17062 m (- m (* n w d h))))
17063 (and (setq fmt (plist-get org-time-clocksum-format :days))
17064 (or (> (setq n (/ (truncate m) (* d h))) 0)
17065 (plist-get org-time-clocksum-format :require-days))
17066 (setq clocksum (concat clocksum (format fmt n))
17067 m (- m (* n d h))))
17068 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17069 (or (> (setq n (/ (truncate m) h)) 0)
17070 (plist-get org-time-clocksum-format :require-hours))
17071 (setq clocksum (concat clocksum (format fmt n))
17072 m (- m (* n h))))
17073 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17074 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17075 (setq clocksum (concat clocksum (format fmt m))))
17076 ;; return formatted time duration
17077 clocksum))))
17079 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17080 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17081 "Org mode version 8.0")
17083 (defun org-hours-to-clocksum-string (n)
17084 (org-minutes-to-clocksum-string (* n 60)))
17086 (defun org-hh:mm-string-to-minutes (s)
17087 "Convert a string H:MM to a number of minutes.
17088 If the string is just a number, interpret it as minutes.
17089 In fact, the first hh:mm or number in the string will be taken,
17090 there can be extra stuff in the string.
17091 If no number is found, the return value is 0."
17092 (cond
17093 ((integerp s) s)
17094 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17095 (+ (* (string-to-number (match-string 1 s)) 60)
17096 (string-to-number (match-string 2 s))))
17097 ((string-match "\\([0-9]+\\)" s)
17098 (string-to-number (match-string 1 s)))
17099 (t 0)))
17101 (defcustom org-image-actual-width t
17102 "Should we use the actual width of images when inlining them?
17104 When set to `t', always use the image width.
17106 When set to a number, use imagemagick (when available) to set
17107 the image's width to this value.
17109 When set to a number in a list, try to get the width from the
17110 #+ATTR.* keyword if it matches a width specification like
17111 width=\"[0-9]+\", and fall back on that number if none is found.
17113 When set to nil, try to get the width from an #+ATTR.* keyword
17114 and fall back on the original width if none is found.
17116 This requires Emacs >= 24.1, build with imagemagick support."
17117 :group 'org-appearance
17118 :version "24.3"
17119 :type '(choice
17120 (const :tag "Use the image width" t)
17121 (integer :tag "Use a number of pixels")
17122 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17123 (const :tag "Use #+ATTR* or don't resize" nil)))
17125 (defcustom org-agenda-inhibit-startup t
17126 "Inhibit startup when preparing agenda buffers.
17127 When this variable is `t' (the default), the initialization of
17128 the Org agenda buffers is inhibited: e.g. the visibility state
17129 is not set, the tables are not re-aligned, etc."
17130 :type 'boolean
17131 :version "24.3"
17132 :group 'org-agenda)
17134 (defun org-duration-string-to-minutes (s &optional output-to-string)
17135 "Convert a duration string S to minutes.
17137 A bare number is interpreted as minutes, modifiers can be set by
17138 customizing `org-effort-durations' (which see).
17140 Entries containing a colon are interpreted as H:MM by
17141 `org-hh:mm-string-to-minutes'."
17142 (let ((result 0)
17143 (re (concat "\\([0-9.]+\\) *\\("
17144 (regexp-opt (mapcar 'car org-effort-durations))
17145 "\\)")))
17146 (while (string-match re s)
17147 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17148 (string-to-number (match-string 1 s))))
17149 (setq s (replace-match "" nil t s)))
17150 (setq result (floor result))
17151 (incf result (org-hh:mm-string-to-minutes s))
17152 (if output-to-string (number-to-string result) result)))
17154 ;;;; Files
17156 (defun org-save-all-org-buffers ()
17157 "Save all Org-mode buffers without user confirmation."
17158 (interactive)
17159 (message "Saving all Org-mode buffers...")
17160 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17161 (when (featurep 'org-id) (org-id-locations-save))
17162 (message "Saving all Org-mode buffers... done"))
17164 (defun org-revert-all-org-buffers ()
17165 "Revert all Org-mode buffers.
17166 Prompt for confirmation when there are unsaved changes.
17167 Be sure you know what you are doing before letting this function
17168 overwrite your changes.
17170 This function is useful in a setup where one tracks org files
17171 with a version control system, to revert on one machine after pulling
17172 changes from another. I believe the procedure must be like this:
17174 1. M-x org-save-all-org-buffers
17175 2. Pull changes from the other machine, resolve conflicts
17176 3. M-x org-revert-all-org-buffers"
17177 (interactive)
17178 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17179 (error "Abort"))
17180 (save-excursion
17181 (save-window-excursion
17182 (mapc
17183 (lambda (b)
17184 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17185 (with-current-buffer b buffer-file-name))
17186 (org-pop-to-buffer-same-window b)
17187 (revert-buffer t 'no-confirm)))
17188 (buffer-list))
17189 (when (and (featurep 'org-id) org-id-track-globally)
17190 (org-id-locations-load)))))
17192 ;;;; Agenda files
17194 ;;;###autoload
17195 (defun org-switchb (&optional arg)
17196 "Switch between Org buffers.
17197 With one prefix argument, restrict available buffers to files.
17198 With two prefix arguments, restrict available buffers to agenda files.
17200 Defaults to `iswitchb' for buffer name completion.
17201 Set `org-completion-use-ido' to make it use ido instead."
17202 (interactive "P")
17203 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17204 ((equal arg '(16)) (org-buffer-list 'agenda))
17205 (t (org-buffer-list))))
17206 (org-completion-use-iswitchb org-completion-use-iswitchb)
17207 (org-completion-use-ido org-completion-use-ido))
17208 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17209 (setq org-completion-use-iswitchb t))
17210 (org-pop-to-buffer-same-window
17211 (org-icompleting-read "Org buffer: "
17212 (mapcar 'list (mapcar 'buffer-name blist))
17213 nil t))))
17215 ;;; Define some older names previously used for this functionality
17216 ;;;###autoload
17217 (defalias 'org-ido-switchb 'org-switchb)
17218 ;;;###autoload
17219 (defalias 'org-iswitchb 'org-switchb)
17221 (defun org-buffer-list (&optional predicate exclude-tmp)
17222 "Return a list of Org buffers.
17223 PREDICATE can be `export', `files' or `agenda'.
17225 export restrict the list to Export buffers.
17226 files restrict the list to buffers visiting Org files.
17227 agenda restrict the list to buffers visiting agenda files.
17229 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17230 (let* ((bfn nil)
17231 (agenda-files (and (eq predicate 'agenda)
17232 (mapcar 'file-truename (org-agenda-files t))))
17233 (filter
17234 (cond
17235 ((eq predicate 'files)
17236 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17237 ((eq predicate 'export)
17238 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17239 ((eq predicate 'agenda)
17240 (lambda (b)
17241 (with-current-buffer b
17242 (and (derived-mode-p 'org-mode)
17243 (setq bfn (buffer-file-name b))
17244 (member (file-truename bfn) agenda-files)))))
17245 (t (lambda (b) (with-current-buffer b
17246 (or (derived-mode-p 'org-mode)
17247 (string-match "\*Org .*Export"
17248 (buffer-name b)))))))))
17249 (delq nil
17250 (mapcar
17251 (lambda(b)
17252 (if (and (funcall filter b)
17253 (or (not exclude-tmp)
17254 (not (string-match "tmp" (buffer-name b)))))
17256 nil))
17257 (buffer-list)))))
17259 (defun org-agenda-files (&optional unrestricted archives)
17260 "Get the list of agenda files.
17261 Optional UNRESTRICTED means return the full list even if a restriction
17262 is currently in place.
17263 When ARCHIVES is t, include all archive files that are really being
17264 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17265 `org-agenda-archives-mode' is t."
17266 (let ((files
17267 (cond
17268 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17269 ((stringp org-agenda-files) (org-read-agenda-file-list))
17270 ((listp org-agenda-files) org-agenda-files)
17271 (t (error "Invalid value of `org-agenda-files'")))))
17272 (setq files (apply 'append
17273 (mapcar (lambda (f)
17274 (if (file-directory-p f)
17275 (directory-files
17276 f t org-agenda-file-regexp)
17277 (list f)))
17278 files)))
17279 (when org-agenda-skip-unavailable-files
17280 (setq files (delq nil
17281 (mapcar (function
17282 (lambda (file)
17283 (and (file-readable-p file) file)))
17284 files))))
17285 (when (or (eq archives t)
17286 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17287 (setq files (org-add-archive-files files)))
17288 files))
17290 (defun org-agenda-file-p (&optional file)
17291 "Return non-nil, if FILE is an agenda file.
17292 If FILE is omitted, use the file associated with the current
17293 buffer."
17294 (member (or file (buffer-file-name))
17295 (org-agenda-files t)))
17297 (defun org-edit-agenda-file-list ()
17298 "Edit the list of agenda files.
17299 Depending on setup, this either uses customize to edit the variable
17300 `org-agenda-files', or it visits the file that is holding the list. In the
17301 latter case, the buffer is set up in a way that saving it automatically kills
17302 the buffer and restores the previous window configuration."
17303 (interactive)
17304 (if (stringp org-agenda-files)
17305 (let ((cw (current-window-configuration)))
17306 (find-file org-agenda-files)
17307 (org-set-local 'org-window-configuration cw)
17308 (org-add-hook 'after-save-hook
17309 (lambda ()
17310 (set-window-configuration
17311 (prog1 org-window-configuration
17312 (kill-buffer (current-buffer))))
17313 (org-install-agenda-files-menu)
17314 (message "New agenda file list installed"))
17315 nil 'local)
17316 (message "%s" (substitute-command-keys
17317 "Edit list and finish with \\[save-buffer]")))
17318 (customize-variable 'org-agenda-files)))
17320 (defun org-store-new-agenda-file-list (list)
17321 "Set new value for the agenda file list and save it correctly."
17322 (if (stringp org-agenda-files)
17323 (let ((fe (org-read-agenda-file-list t)) b u)
17324 (while (setq b (find-buffer-visiting org-agenda-files))
17325 (kill-buffer b))
17326 (with-temp-file org-agenda-files
17327 (insert
17328 (mapconcat
17329 (lambda (f) ;; Keep un-expanded entries.
17330 (if (setq u (assoc f fe))
17331 (cdr u)
17333 list "\n")
17334 "\n")))
17335 (let ((org-mode-hook nil) (org-inhibit-startup t)
17336 (org-insert-mode-line-in-empty-file nil))
17337 (setq org-agenda-files list)
17338 (customize-save-variable 'org-agenda-files org-agenda-files))))
17340 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17341 "Read the list of agenda files from a file.
17342 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17343 filenames, used by `org-store-new-agenda-file-list' to write back
17344 un-expanded file names."
17345 (when (file-directory-p org-agenda-files)
17346 (error "`org-agenda-files' cannot be a single directory"))
17347 (when (stringp org-agenda-files)
17348 (with-temp-buffer
17349 (insert-file-contents org-agenda-files)
17350 (mapcar
17351 (lambda (f)
17352 (let ((e (expand-file-name (substitute-in-file-name f)
17353 org-directory)))
17354 (if pair-with-expansion
17355 (cons e f)
17356 e)))
17357 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17359 ;;;###autoload
17360 (defun org-cycle-agenda-files ()
17361 "Cycle through the files in `org-agenda-files'.
17362 If the current buffer visits an agenda file, find the next one in the list.
17363 If the current buffer does not, find the first agenda file."
17364 (interactive)
17365 (let* ((fs (org-agenda-files t))
17366 (files (append fs (list (car fs))))
17367 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17368 file)
17369 (unless files (error "No agenda files"))
17370 (catch 'exit
17371 (while (setq file (pop files))
17372 (if (equal (file-truename file) tcf)
17373 (when (car files)
17374 (find-file (car files))
17375 (throw 'exit t))))
17376 (find-file (car fs)))
17377 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17379 (defun org-agenda-file-to-front (&optional to-end)
17380 "Move/add the current file to the top of the agenda file list.
17381 If the file is not present in the list, it is added to the front. If it is
17382 present, it is moved there. With optional argument TO-END, add/move to the
17383 end of the list."
17384 (interactive "P")
17385 (let ((org-agenda-skip-unavailable-files nil)
17386 (file-alist (mapcar (lambda (x)
17387 (cons (file-truename x) x))
17388 (org-agenda-files t)))
17389 (ctf (file-truename
17390 (or buffer-file-name
17391 (error "Please save the current buffer to a file"))))
17392 x had)
17393 (setq x (assoc ctf file-alist) had x)
17395 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17396 (if to-end
17397 (setq file-alist (append (delq x file-alist) (list x)))
17398 (setq file-alist (cons x (delq x file-alist))))
17399 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17400 (org-install-agenda-files-menu)
17401 (message "File %s to %s of agenda file list"
17402 (if had "moved" "added") (if to-end "end" "front"))))
17404 (defun org-remove-file (&optional file)
17405 "Remove current file from the list of files in variable `org-agenda-files'.
17406 These are the files which are being checked for agenda entries.
17407 Optional argument FILE means use this file instead of the current."
17408 (interactive)
17409 (let* ((org-agenda-skip-unavailable-files nil)
17410 (file (or file buffer-file-name
17411 (error "Current buffer does not visit a file")))
17412 (true-file (file-truename file))
17413 (afile (abbreviate-file-name file))
17414 (files (delq nil (mapcar
17415 (lambda (x)
17416 (if (equal true-file
17417 (file-truename x))
17418 nil x))
17419 (org-agenda-files t)))))
17420 (if (not (= (length files) (length (org-agenda-files t))))
17421 (progn
17422 (org-store-new-agenda-file-list files)
17423 (org-install-agenda-files-menu)
17424 (message "Removed file: %s" afile))
17425 (message "File was not in list: %s (not removed)" afile))))
17427 (defun org-file-menu-entry (file)
17428 (vector file (list 'find-file file) t))
17430 (defun org-check-agenda-file (file)
17431 "Make sure FILE exists. If not, ask user what to do."
17432 (when (not (file-exists-p file))
17433 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17434 (abbreviate-file-name file))
17435 (let ((r (downcase (read-char-exclusive))))
17436 (cond
17437 ((equal r ?r)
17438 (org-remove-file file)
17439 (throw 'nextfile t))
17440 (t (error "Abort"))))))
17442 (defun org-get-agenda-file-buffer (file)
17443 "Get a buffer visiting FILE. If the buffer needs to be created, add
17444 it to the list of buffers which might be released later."
17445 (let ((buf (org-find-base-buffer-visiting file)))
17446 (if buf
17447 buf ; just return it
17448 ;; Make a new buffer and remember it
17449 (setq buf (find-file-noselect file))
17450 (if buf (push buf org-agenda-new-buffers))
17451 buf)))
17453 (defun org-release-buffers (blist)
17454 "Release all buffers in list, asking the user for confirmation when needed.
17455 When a buffer is unmodified, it is just killed. When modified, it is saved
17456 \(if the user agrees) and then killed."
17457 (let (buf file)
17458 (while (setq buf (pop blist))
17459 (setq file (buffer-file-name buf))
17460 (when (and (buffer-modified-p buf)
17461 file
17462 (y-or-n-p (format "Save file %s? " file)))
17463 (with-current-buffer buf (save-buffer)))
17464 (kill-buffer buf))))
17466 (defun org-agenda-prepare-buffers (files)
17467 "Create buffers for all agenda files, protect archived trees and comments."
17468 (interactive)
17469 (let ((pa '(:org-archived t))
17470 (pc '(:org-comment t))
17471 (pall '(:org-archived t :org-comment t))
17472 (inhibit-read-only t)
17473 (org-inhibit-startup org-agenda-inhibit-startup)
17474 (rea (concat ":" org-archive-tag ":"))
17475 file re)
17476 (save-excursion
17477 (save-restriction
17478 (while (setq file (pop files))
17479 (catch 'nextfile
17480 (if (bufferp file)
17481 (set-buffer file)
17482 (org-check-agenda-file file)
17483 (set-buffer (org-get-agenda-file-buffer file)))
17484 (widen)
17485 (org-unmodified
17486 (org-refresh-category-properties)
17487 (org-refresh-properties org-effort-property 'org-effort)
17488 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17489 (setq org-todo-keywords-for-agenda
17490 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17491 (setq org-done-keywords-for-agenda
17492 (append org-done-keywords-for-agenda org-done-keywords))
17493 (setq org-todo-keyword-alist-for-agenda
17494 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17495 (setq org-drawers-for-agenda
17496 (append org-drawers-for-agenda org-drawers))
17497 (setq org-tag-alist-for-agenda
17498 (append org-tag-alist-for-agenda org-tag-alist))
17500 (save-excursion
17501 (remove-text-properties (point-min) (point-max) pall)
17502 (when org-agenda-skip-archived-trees
17503 (goto-char (point-min))
17504 (while (re-search-forward rea nil t)
17505 (if (org-at-heading-p t)
17506 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17507 (goto-char (point-min))
17508 (setq re (format org-heading-keyword-regexp-format
17509 org-comment-string))
17510 (while (re-search-forward re nil t)
17511 (add-text-properties
17512 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17513 (setq org-todo-keywords-for-agenda
17514 (org-uniquify org-todo-keywords-for-agenda))
17515 (setq org-todo-keyword-alist-for-agenda
17516 (org-uniquify org-todo-keyword-alist-for-agenda)
17517 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17521 ;;;; CDLaTeX minor mode
17523 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17524 "Keymap for the minor `org-cdlatex-mode'.")
17526 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17527 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17528 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17529 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17530 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17532 (defvar org-cdlatex-texmathp-advice-is-done nil
17533 "Flag remembering if we have applied the advice to texmathp already.")
17535 (define-minor-mode org-cdlatex-mode
17536 "Toggle the minor `org-cdlatex-mode'.
17537 This mode supports entering LaTeX environment and math in LaTeX fragments
17538 in Org-mode.
17539 \\{org-cdlatex-mode-map}"
17540 nil " OCDL" nil
17541 (when org-cdlatex-mode
17542 (require 'cdlatex)
17543 (run-hooks 'cdlatex-mode-hook)
17544 (cdlatex-compute-tables))
17545 (unless org-cdlatex-texmathp-advice-is-done
17546 (setq org-cdlatex-texmathp-advice-is-done t)
17547 (defadvice texmathp (around org-math-always-on activate)
17548 "Always return t in org-mode buffers.
17549 This is because we want to insert math symbols without dollars even outside
17550 the LaTeX math segments. If Orgmode thinks that point is actually inside
17551 an embedded LaTeX fragment, let texmathp do its job.
17552 \\[org-cdlatex-mode-map]"
17553 (interactive)
17554 (let (p)
17555 (cond
17556 ((not (derived-mode-p 'org-mode)) ad-do-it)
17557 ((eq this-command 'cdlatex-math-symbol)
17558 (setq ad-return-value t
17559 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17561 (let ((p (org-inside-LaTeX-fragment-p)))
17562 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17563 (setq ad-return-value t
17564 texmathp-why '("Org-mode embedded math" . 0))
17565 (if p ad-do-it)))))))))
17567 (defun turn-on-org-cdlatex ()
17568 "Unconditionally turn on `org-cdlatex-mode'."
17569 (org-cdlatex-mode 1))
17571 (defun org-try-cdlatex-tab ()
17572 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17573 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17574 - inside a LaTeX fragment, or
17575 - after the first word in a line, where an abbreviation expansion could
17576 insert a LaTeX environment."
17577 (when org-cdlatex-mode
17578 (cond
17579 ;; Before any word on the line: No expansion possible.
17580 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17581 ;; Just after first word on the line: Expand it. Make sure it
17582 ;; cannot happen on headlines, though.
17583 ((save-excursion
17584 (skip-chars-backward "a-zA-Z0-9*")
17585 (skip-chars-backward " \t")
17586 (and (bolp) (not (org-at-heading-p))))
17587 (cdlatex-tab) t)
17588 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17590 (defun org-cdlatex-underscore-caret (&optional arg)
17591 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17592 Revert to the normal definition outside of these fragments."
17593 (interactive "P")
17594 (if (org-inside-LaTeX-fragment-p)
17595 (call-interactively 'cdlatex-sub-superscript)
17596 (let (org-cdlatex-mode)
17597 (call-interactively (key-binding (vector last-input-event))))))
17599 (defun org-cdlatex-math-modify (&optional arg)
17600 "Execute `cdlatex-math-modify' in LaTeX fragments.
17601 Revert to the normal definition outside of these fragments."
17602 (interactive "P")
17603 (if (org-inside-LaTeX-fragment-p)
17604 (call-interactively 'cdlatex-math-modify)
17605 (let (org-cdlatex-mode)
17606 (call-interactively (key-binding (vector last-input-event))))))
17610 ;;;; LaTeX fragments
17612 (defvar org-latex-regexps
17613 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17614 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17615 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17616 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17617 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17618 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17619 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17620 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17621 "Regular expressions for matching embedded LaTeX.")
17623 (defun org-inside-LaTeX-fragment-p ()
17624 "Test if point is inside a LaTeX fragment.
17625 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17626 sequence appearing also before point.
17627 Even though the matchers for math are configurable, this function assumes
17628 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17629 delimiters are skipped when they have been removed by customization.
17630 The return value is nil, or a cons cell with the delimiter and the
17631 position of this delimiter.
17633 This function does a reasonably good job, but can locally be fooled by
17634 for example currency specifications. For example it will assume being in
17635 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17636 fragments that are properly closed, but during editing, we have to live
17637 with the uncertainty caused by missing closing delimiters. This function
17638 looks only before point, not after."
17639 (catch 'exit
17640 (let ((pos (point))
17641 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17642 (lim (progn
17643 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17644 (point)))
17645 dd-on str (start 0) m re)
17646 (goto-char pos)
17647 (when dodollar
17648 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17649 re (nth 1 (assoc "$" org-latex-regexps)))
17650 (while (string-match re str start)
17651 (cond
17652 ((= (match-end 0) (length str))
17653 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17654 ((= (match-end 0) (- (length str) 5))
17655 (throw 'exit nil))
17656 (t (setq start (match-end 0))))))
17657 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17658 (goto-char pos)
17659 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17660 (and (match-beginning 2) (throw 'exit nil))
17661 ;; count $$
17662 (while (re-search-backward "\\$\\$" lim t)
17663 (setq dd-on (not dd-on)))
17664 (goto-char pos)
17665 (if dd-on (cons "$$" m))))))
17667 (defun org-inside-latex-macro-p ()
17668 "Is point inside a LaTeX macro or its arguments?"
17669 (save-match-data
17670 (org-in-regexp
17671 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17673 (defvar org-latex-fragment-image-overlays nil
17674 "List of overlays carrying the images of latex fragments.")
17675 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17677 (defun org-remove-latex-fragment-image-overlays ()
17678 "Remove all overlays with LaTeX fragment images in current buffer."
17679 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17680 (setq org-latex-fragment-image-overlays nil))
17682 (defun org-preview-latex-fragment (&optional subtree)
17683 "Preview the LaTeX fragment at point, or all locally or globally.
17684 If the cursor is in a LaTeX fragment, create the image and overlay
17685 it over the source code. If there is no fragment at point, display
17686 all fragments in the current text, from one headline to the next. With
17687 prefix SUBTREE, display all fragments in the current subtree. With a
17688 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17689 the cursor is before the first headline,
17690 display all fragments in the buffer.
17691 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17692 (interactive "P")
17693 (unless buffer-file-name
17694 (error "Can't preview LaTeX fragment in a non-file buffer"))
17695 (org-remove-latex-fragment-image-overlays)
17696 (save-excursion
17697 (save-restriction
17698 (let (beg end at msg)
17699 (cond
17700 ((or (equal subtree '(16))
17701 (not (save-excursion
17702 (re-search-backward org-outline-regexp-bol nil t))))
17703 (setq beg (point-min) end (point-max)
17704 msg "Creating images for buffer...%s"))
17705 ((equal subtree '(4))
17706 (org-back-to-heading)
17707 (setq beg (point) end (org-end-of-subtree t)
17708 msg "Creating images for subtree...%s"))
17710 (if (setq at (org-inside-LaTeX-fragment-p))
17711 (goto-char (max (point-min) (- (cdr at) 2)))
17712 (org-back-to-heading))
17713 (setq beg (point) end (progn (outline-next-heading) (point))
17714 msg (if at "Creating image...%s"
17715 "Creating images for entry...%s"))))
17716 (message msg "")
17717 (narrow-to-region beg end)
17718 (goto-char beg)
17719 (org-format-latex
17720 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17721 (file-name-nondirectory
17722 buffer-file-name)))
17723 default-directory 'overlays msg at 'forbuffer
17724 org-latex-create-formula-image-program)
17725 (message msg "done. Use `C-c C-c' to remove images.")))))
17727 (defun org-format-latex (prefix &optional dir overlays msg at
17728 forbuffer processing-type)
17729 "Replace LaTeX fragments with links to an image, and produce images.
17730 Some of the options can be changed using the variable
17731 `org-format-latex-options'."
17732 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17733 (let* ((prefixnodir (file-name-nondirectory prefix))
17734 (absprefix (expand-file-name prefix dir))
17735 (todir (file-name-directory absprefix))
17736 (opt org-format-latex-options)
17737 (optnew org-format-latex-options)
17738 (matchers (plist-get opt :matchers))
17739 (re-list org-latex-regexps)
17740 (cnt 0) txt hash link beg end re e checkdir
17741 string
17742 m n block-type block linkfile movefile ov)
17743 ;; Check the different regular expressions
17744 (while (setq e (pop re-list))
17745 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17746 block (if block-type "\n\n" ""))
17747 (when (member m matchers)
17748 (goto-char (point-min))
17749 (while (re-search-forward re nil t)
17750 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17751 (or (not overlays)
17752 (not (eq (get-char-property (match-beginning n)
17753 'org-overlay-type)
17754 'org-latex-overlay))))
17755 (cond
17756 ((eq processing-type 'verbatim))
17757 ((eq processing-type 'mathjax)
17758 ;; Prepare for MathJax processing.
17759 (setq string (match-string n))
17760 (when (member m '("$" "$1"))
17761 (save-excursion
17762 (delete-region (match-beginning n) (match-end n))
17763 (goto-char (match-beginning n))
17764 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17765 ((or (eq processing-type 'dvipng)
17766 (eq processing-type 'imagemagick))
17767 ;; Process to an image.
17768 (setq txt (match-string n)
17769 beg (match-beginning n) end (match-end n)
17770 cnt (1+ cnt))
17771 (let ((face (face-at-point))
17772 (fg (plist-get opt :foreground))
17773 (bg (plist-get opt :background))
17774 ;; Ensure full list is printed.
17775 print-length print-level)
17776 (when forbuffer
17777 ;; Get the colors from the face at point.
17778 (goto-char beg)
17779 (when (eq fg 'auto)
17780 (setq fg (face-attribute face :foreground nil 'default)))
17781 (when (eq bg 'auto)
17782 (setq bg (face-attribute face :background nil 'default)))
17783 (setq optnew (copy-sequence opt))
17784 (plist-put optnew :foreground fg)
17785 (plist-put optnew :background bg))
17786 (setq hash (sha1 (prin1-to-string
17787 (list org-format-latex-header
17788 org-latex-default-packages-alist
17789 org-latex-packages-alist
17790 org-format-latex-options
17791 forbuffer txt fg bg)))
17792 linkfile (format "%s_%s.png" prefix hash)
17793 movefile (format "%s_%s.png" absprefix hash)))
17794 (setq link (concat block "[[file:" linkfile "]]" block))
17795 (if msg (message msg cnt))
17796 (goto-char beg)
17797 (unless checkdir ; Ensure the directory exists.
17798 (setq checkdir t)
17799 (or (file-directory-p todir) (make-directory todir t)))
17800 (unless (file-exists-p movefile)
17801 (org-create-formula-image
17802 txt movefile optnew forbuffer processing-type))
17803 (if overlays
17804 (progn
17805 (mapc (lambda (o)
17806 (if (eq (overlay-get o 'org-overlay-type)
17807 'org-latex-overlay)
17808 (delete-overlay o)))
17809 (overlays-in beg end))
17810 (setq ov (make-overlay beg end))
17811 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17812 (if (featurep 'xemacs)
17813 (progn
17814 (overlay-put ov 'invisible t)
17815 (overlay-put
17816 ov 'end-glyph
17817 (make-glyph (vector 'png :file movefile))))
17818 (overlay-put
17819 ov 'display
17820 (list 'image :type 'png :file movefile :ascent 'center)))
17821 (push ov org-latex-fragment-image-overlays)
17822 (goto-char end))
17823 (delete-region beg end)
17824 (insert (org-add-props link
17825 (list 'org-latex-src
17826 (replace-regexp-in-string
17827 "\"" "" txt)
17828 'org-latex-src-embed-type
17829 (if block-type 'paragraph 'character))))))
17830 ((eq processing-type 'mathml)
17831 ;; Process to MathML
17832 (unless (save-match-data (org-format-latex-mathml-available-p))
17833 (error "LaTeX to MathML converter not configured"))
17834 (setq txt (match-string n)
17835 beg (match-beginning n) end (match-end n)
17836 cnt (1+ cnt))
17837 (if msg (message msg cnt))
17838 (goto-char beg)
17839 (delete-region beg end)
17840 (insert (org-format-latex-as-mathml
17841 txt block-type prefix dir)))
17843 (error "Unknown conversion type %s for latex fragments"
17844 processing-type)))))))))
17846 (defun org-create-math-formula (latex-frag &optional mathml-file)
17847 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17848 Use `org-latex-to-mathml-convert-command'. If the conversion is
17849 sucessful, return the portion between \"<math...> </math>\"
17850 elements otherwise return nil. When MATHML-FILE is specified,
17851 write the results in to that file. When invoked as an
17852 interactive command, prompt for LATEX-FRAG, with initial value
17853 set to the current active region and echo the results for user
17854 inspection."
17855 (interactive (list (let ((frag (when (org-region-active-p)
17856 (buffer-substring-no-properties
17857 (region-beginning) (region-end)))))
17858 (read-string "LaTeX Fragment: " frag nil frag))))
17859 (unless latex-frag (error "Invalid latex-frag"))
17860 (let* ((tmp-in-file (file-relative-name
17861 (make-temp-name (expand-file-name "ltxmathml-in"))))
17862 (ignore (write-region latex-frag nil tmp-in-file))
17863 (tmp-out-file (file-relative-name
17864 (make-temp-name (expand-file-name "ltxmathml-out"))))
17865 (cmd (format-spec
17866 org-latex-to-mathml-convert-command
17867 `((?j . ,(shell-quote-argument
17868 (expand-file-name org-latex-to-mathml-jar-file)))
17869 (?I . ,(shell-quote-argument tmp-in-file))
17870 (?o . ,(shell-quote-argument tmp-out-file)))))
17871 mathml shell-command-output)
17872 (when (org-called-interactively-p 'any)
17873 (unless (org-format-latex-mathml-available-p)
17874 (error "LaTeX to MathML converter not configured")))
17875 (message "Running %s" cmd)
17876 (setq shell-command-output (shell-command-to-string cmd))
17877 (setq mathml
17878 (when (file-readable-p tmp-out-file)
17879 (with-current-buffer (find-file-noselect tmp-out-file t)
17880 (goto-char (point-min))
17881 (when (re-search-forward
17882 (concat
17883 (regexp-quote
17884 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17885 "\\(.\\|\n\\)*"
17886 (regexp-quote "</math>")) nil t)
17887 (prog1 (match-string 0) (kill-buffer))))))
17888 (cond
17889 (mathml
17890 (setq mathml
17891 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17892 (when mathml-file
17893 (write-region mathml nil mathml-file))
17894 (when (org-called-interactively-p 'any)
17895 (message mathml)))
17896 ((message "LaTeX to MathML conversion failed")
17897 (message shell-command-output)))
17898 (delete-file tmp-in-file)
17899 (when (file-exists-p tmp-out-file)
17900 (delete-file tmp-out-file))
17901 mathml))
17903 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17904 prefix &optional dir)
17905 "Use `org-create-math-formula' but check local cache first."
17906 (let* ((absprefix (expand-file-name prefix dir))
17907 (print-length nil) (print-level nil)
17908 (formula-id (concat
17909 "formula-"
17910 (sha1
17911 (prin1-to-string
17912 (list latex-frag
17913 org-latex-to-mathml-convert-command)))))
17914 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17915 (formula-cache-dir (file-name-directory formula-cache)))
17917 (unless (file-directory-p formula-cache-dir)
17918 (make-directory formula-cache-dir t))
17920 (unless (file-exists-p formula-cache)
17921 (org-create-math-formula latex-frag formula-cache))
17923 (if (file-exists-p formula-cache)
17924 ;; Successful conversion. Return the link to MathML file.
17925 (org-add-props
17926 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17927 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17928 'org-latex-src-embed-type (if latex-frag-type
17929 'paragraph 'character)))
17930 ;; Failed conversion. Return the LaTeX fragment verbatim
17931 latex-frag)))
17933 (defun org-create-formula-image (string tofile options buffer &optional type)
17934 "Create an image from LaTeX source using dvipng or convert.
17935 This function calls either `org-create-formula-image-with-dvipng'
17936 or `org-create-formula-image-with-imagemagick' depending on the
17937 value of `org-latex-create-formula-image-program' or on the value
17938 of the optional TYPE variable.
17940 Note: ultimately these two function should be combined as they
17941 share a good deal of logic."
17942 (org-check-external-command
17943 "latex" "needed to convert LaTeX fragments to images")
17944 (funcall
17945 (case (or type org-latex-create-formula-image-program)
17946 ('dvipng
17947 (org-check-external-command
17948 "dvipng" "needed to convert LaTeX fragments to images")
17949 #'org-create-formula-image-with-dvipng)
17950 ('imagemagick
17951 (org-check-external-command
17952 "convert" "you need to install imagemagick")
17953 #'org-create-formula-image-with-imagemagick)
17954 (t (error
17955 "invalid value of `org-latex-create-formula-image-program'")))
17956 string tofile options buffer))
17958 ;; This function borrows from Ganesh Swami's latex2png.el
17959 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17960 "This calls dvipng."
17961 (let* ((tmpdir (if (featurep 'xemacs)
17962 (temp-directory)
17963 temporary-file-directory))
17964 (texfilebase (make-temp-name
17965 (expand-file-name "orgtex" tmpdir)))
17966 (texfile (concat texfilebase ".tex"))
17967 (dvifile (concat texfilebase ".dvi"))
17968 (pngfile (concat texfilebase ".png"))
17969 (fnh (if (featurep 'xemacs)
17970 (font-height (face-font 'default))
17971 (face-attribute 'default :height nil)))
17972 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17973 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17974 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17975 "Black"))
17976 (bg (or (plist-get options (if buffer :background :html-background))
17977 "Transparent")))
17978 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17979 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17980 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17981 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17982 (with-temp-file texfile
17983 (require 'ox-latex)
17984 (insert (org-latex-guess-inputenc
17985 (org-splice-latex-header
17986 org-format-latex-header
17987 org-latex-default-packages-alist
17988 org-latex-packages-alist t)))
17989 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17990 (let ((dir default-directory))
17991 (condition-case nil
17992 (progn
17993 (cd tmpdir)
17994 (call-process "latex" nil nil nil texfile))
17995 (error nil))
17996 (cd dir))
17997 (if (not (file-exists-p dvifile))
17998 (progn (message "Failed to create dvi file from %s" texfile) nil)
17999 (condition-case nil
18000 (if (featurep 'xemacs)
18001 (call-process "dvipng" nil nil nil
18002 "-fg" fg "-bg" bg
18003 "-T" "tight"
18004 "-o" pngfile
18005 dvifile)
18006 (call-process "dvipng" nil nil nil
18007 "-fg" fg "-bg" bg
18008 "-D" dpi
18009 ;;"-x" scale "-y" scale
18010 "-T" "tight"
18011 "-o" pngfile
18012 dvifile))
18013 (error nil))
18014 (if (not (file-exists-p pngfile))
18015 (if org-format-latex-signal-error
18016 (error "Failed to create png file from %s" texfile)
18017 (message "Failed to create png file from %s" texfile)
18018 nil)
18019 ;; Use the requested file name and clean up
18020 (copy-file pngfile tofile 'replace)
18021 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18022 (if (file-exists-p (concat texfilebase e))
18023 (delete-file (concat texfilebase e))))
18024 pngfile))))
18026 (defvar org-latex-pdf-process) ; From ox-latex.el
18027 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18028 "This calls convert, which is included into imagemagick."
18029 (let* ((tmpdir (if (featurep 'xemacs)
18030 (temp-directory)
18031 temporary-file-directory))
18032 (texfilebase (make-temp-name
18033 (expand-file-name "orgtex" tmpdir)))
18034 (texfile (concat texfilebase ".tex"))
18035 (pdffile (concat texfilebase ".pdf"))
18036 (pngfile (concat texfilebase ".png"))
18037 (fnh (if (featurep 'xemacs)
18038 (font-height (face-font 'default))
18039 (face-attribute 'default :height nil)))
18040 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18041 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18042 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18043 "black"))
18044 (bg (or (plist-get options (if buffer :background :html-background))
18045 "white")))
18046 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18047 (setq fg (org-latex-color-format fg)))
18048 (if (eq bg 'default) (setq bg (org-latex-color :background))
18049 (setq bg (org-latex-color-format
18050 (if (string= bg "Transparent") "white" bg))))
18051 (with-temp-file texfile
18052 (require 'ox-latex)
18053 (insert (org-latex-guess-inputenc
18054 (org-splice-latex-header
18055 org-format-latex-header
18056 org-latex-default-packages-alist
18057 org-latex-packages-alist t)))
18058 (insert "\n\\begin{document}\n"
18059 "\\definecolor{fg}{rgb}{" fg "}\n"
18060 "\\definecolor{bg}{rgb}{" bg "}\n"
18061 "\n\\pagecolor{bg}\n"
18062 "\n{\\color{fg}\n"
18063 string
18064 "\n}\n"
18065 "\n\\end{document}\n"))
18066 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18067 (condition-case nil
18068 (progn
18069 (cd tmpdir)
18070 (setq cmds org-latex-pdf-process)
18071 (while cmds
18072 (setq latex-frags-cmds (pop cmds))
18073 (if (listp latex-frags-cmds)
18074 (setq cmds nil)
18075 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18076 (while latex-frags-cmds
18077 (setq cmd (pop latex-frags-cmds))
18078 (while (string-match "%b" cmd)
18079 (setq cmd (replace-match
18080 (save-match-data
18081 (shell-quote-argument texfile))
18082 t t cmd)))
18083 (while (string-match "%f" cmd)
18084 (setq cmd (replace-match
18085 (save-match-data
18086 (shell-quote-argument
18087 (file-name-nondirectory texfile)))
18088 t t cmd)))
18089 (while (string-match "%o" cmd)
18090 (setq cmd (replace-match
18091 (save-match-data
18092 (shell-quote-argument
18093 (file-name-directory texfile)))
18094 t t cmd)))
18095 (setq cmd (split-string cmd))
18096 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18097 (error nil))
18098 (cd dir))
18099 (if (not (file-exists-p pdffile))
18100 (progn (message "Failed to create pdf file from %s" texfile) nil)
18101 (condition-case nil
18102 (if (featurep 'xemacs)
18103 (call-process "convert" nil nil nil
18104 "-density" "96"
18105 "-trim"
18106 "-antialias"
18107 pdffile
18108 "-quality" "100"
18109 ;; "-sharpen" "0x1.0"
18110 pngfile)
18111 (call-process "convert" nil nil nil
18112 "-density" dpi
18113 "-trim"
18114 "-antialias"
18115 pdffile
18116 "-quality" "100"
18117 ;; "-sharpen" "0x1.0"
18118 pngfile))
18119 (error nil))
18120 (if (not (file-exists-p pngfile))
18121 (if org-format-latex-signal-error
18122 (error "Failed to create png file from %s" texfile)
18123 (message "Failed to create png file from %s" texfile)
18124 nil)
18125 ;; Use the requested file name and clean up
18126 (copy-file pngfile tofile 'replace)
18127 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18128 (if (file-exists-p (concat texfilebase e))
18129 (delete-file (concat texfilebase e))))
18130 pngfile))))
18132 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18133 "Fill a LaTeX header template TPL.
18134 In the template, the following place holders will be recognized:
18136 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18137 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18138 [PACKAGES] \\usepackage statements for PKG
18139 [NO-PACKAGES] do not include PKG
18140 [EXTRA] the string EXTRA
18141 [NO-EXTRA] do not include EXTRA
18143 For backward compatibility, if both the positive and the negative place
18144 holder is missing, the positive one (without the \"NO-\") will be
18145 assumed to be present at the end of the template.
18146 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18147 EXTRA is a string.
18148 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18149 (let (rpl (end ""))
18150 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18151 (setq rpl (if (or (match-end 1) (not def-pkg))
18152 "" (org-latex-packages-to-string def-pkg snippets-p t))
18153 tpl (replace-match rpl t t tpl))
18154 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18156 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18157 (setq rpl (if (or (match-end 1) (not pkg))
18158 "" (org-latex-packages-to-string pkg snippets-p t))
18159 tpl (replace-match rpl t t tpl))
18160 (if pkg (setq end
18161 (concat end "\n"
18162 (org-latex-packages-to-string pkg snippets-p)))))
18164 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18165 (setq rpl (if (or (match-end 1) (not extra))
18166 "" (concat extra "\n"))
18167 tpl (replace-match rpl t t tpl))
18168 (if (and extra (string-match "\\S-" extra))
18169 (setq end (concat end "\n" extra))))
18171 (if (string-match "\\S-" end)
18172 (concat tpl "\n" end)
18173 tpl)))
18175 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18176 "Turn an alist of packages into a string with the \\usepackage macros."
18177 (setq pkg (mapconcat (lambda(p)
18178 (cond
18179 ((stringp p) p)
18180 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18181 (format "%% Package %s omitted" (cadr p)))
18182 ((equal "" (car p))
18183 (format "\\usepackage{%s}" (cadr p)))
18185 (format "\\usepackage[%s]{%s}"
18186 (car p) (cadr p)))))
18188 "\n"))
18189 (if newline (concat pkg "\n") pkg))
18191 (defun org-dvipng-color (attr)
18192 "Return a RGB color specification for dvipng."
18193 (apply 'format "rgb %s %s %s"
18194 (mapcar 'org-normalize-color
18195 (if (featurep 'xemacs)
18196 (color-rgb-components
18197 (face-property 'default
18198 (cond ((eq attr :foreground) 'foreground)
18199 ((eq attr :background) 'background))))
18200 (color-values (face-attribute 'default attr nil))))))
18202 (defun org-dvipng-color-format (color-name)
18203 "Convert COLOR-NAME to a RGB color value for dvipng."
18204 (apply 'format "rgb %s %s %s"
18205 (mapcar 'org-normalize-color
18206 (color-values color-name))))
18208 (defun org-latex-color (attr)
18209 "Return a RGB color for the LaTeX color package."
18210 (apply 'format "%s,%s,%s"
18211 (mapcar 'org-normalize-color
18212 (if (featurep 'xemacs)
18213 (color-rgb-components
18214 (face-property 'default
18215 (cond ((eq attr :foreground) 'foreground)
18216 ((eq attr :background) 'background))))
18217 (color-values (face-attribute 'default attr nil))))))
18219 (defun org-latex-color-format (color-name)
18220 "Convert COLOR-NAME to a RGB color value."
18221 (apply 'format "%s,%s,%s"
18222 (mapcar 'org-normalize-color
18223 (color-values color-name))))
18225 (defun org-normalize-color (value)
18226 "Return string to be used as color value for an RGB component."
18227 (format "%g" (/ value 65535.0)))
18231 ;; Image display
18233 (defvar org-inline-image-overlays nil)
18234 (make-variable-buffer-local 'org-inline-image-overlays)
18236 (defun org-toggle-inline-images (&optional include-linked)
18237 "Toggle the display of inline images.
18238 INCLUDE-LINKED is passed to `org-display-inline-images'."
18239 (interactive "P")
18240 (if org-inline-image-overlays
18241 (progn
18242 (org-remove-inline-images)
18243 (message "Inline image display turned off"))
18244 (org-display-inline-images include-linked)
18245 (if (and (org-called-interactively-p)
18246 org-inline-image-overlays)
18247 (message "%d images displayed inline"
18248 (length org-inline-image-overlays))
18249 (message "No images to display inline"))))
18251 (defun org-redisplay-inline-images ()
18252 "Refresh the display of inline images."
18253 (interactive)
18254 (if (not org-inline-image-overlays)
18255 (org-toggle-inline-images)
18256 (org-toggle-inline-images)
18257 (org-toggle-inline-images)))
18259 (defun org-display-inline-images (&optional include-linked refresh beg end)
18260 "Display inline images.
18261 Normally only links without a description part are inlined, because this
18262 is how it will work for export. When INCLUDE-LINKED is set, also links
18263 with a description part will be inlined. This can be nice for a quick
18264 look at those images, but it does not reflect what exported files will look
18265 like.
18266 When REFRESH is set, refresh existing images between BEG and END.
18267 This will create new image displays only if necessary.
18268 BEG and END default to the buffer boundaries."
18269 (interactive "P")
18270 (unless refresh
18271 (org-remove-inline-images)
18272 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18273 (save-excursion
18274 (save-restriction
18275 (widen)
18276 (setq beg (or beg (point-min)) end (or end (point-max)))
18277 (goto-char beg)
18278 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18279 (substring (org-image-file-name-regexp) 0 -2)
18280 "\\)\\]" (if include-linked "" "\\]")))
18281 old file ov img type attrwidth width)
18282 (while (re-search-forward re end t)
18283 (setq old (get-char-property-and-overlay (match-beginning 1)
18284 'org-image-overlay)
18285 file (expand-file-name
18286 (concat (or (match-string 3) "") (match-string 4))))
18287 (when (image-type-available-p 'imagemagick)
18288 (setq attrwidth (if (or (listp org-image-actual-width)
18289 (null org-image-actual-width))
18290 (save-excursion
18291 (save-match-data
18292 (when (re-search-backward
18293 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18294 (save-excursion
18295 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18296 (string-to-number (match-string 1))))))
18297 width (cond ((eq org-image-actual-width t) nil)
18298 ((null org-image-actual-width) attrwidth)
18299 ((numberp org-image-actual-width)
18300 org-image-actual-width)
18301 ((listp org-image-actual-width)
18302 (or attrwidth (car org-image-actual-width))))
18303 type (if width 'imagemagick)))
18304 (when (file-exists-p file)
18305 (if (and (car-safe old) refresh)
18306 (image-refresh (overlay-get (cdr old) 'display))
18307 (setq img (save-match-data (create-image file type nil :width width)))
18308 (when img
18309 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18310 (overlay-put ov 'display img)
18311 (overlay-put ov 'face 'default)
18312 (overlay-put ov 'org-image-overlay t)
18313 (overlay-put ov 'modification-hooks
18314 (list 'org-display-inline-remove-overlay))
18315 (push ov org-inline-image-overlays)))))))))
18317 (define-obsolete-function-alias
18318 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18320 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18321 "Remove inline-display overlay if a corresponding region is modified."
18322 (let ((inhibit-modification-hooks t))
18323 (when (and ov after)
18324 (delete ov org-inline-image-overlays)
18325 (delete-overlay ov))))
18327 (defun org-remove-inline-images ()
18328 "Remove inline display of images."
18329 (interactive)
18330 (mapc 'delete-overlay org-inline-image-overlays)
18331 (setq org-inline-image-overlays nil))
18333 ;;;; Key bindings
18335 ;; Outline functions from `outline-mode-prefix-map'
18336 ;; that can be remapped in Org:
18337 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18338 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18339 (define-key org-mode-map [remap outline-forward-same-level]
18340 'org-forward-heading-same-level)
18341 (define-key org-mode-map [remap outline-backward-same-level]
18342 'org-backward-heading-same-level)
18343 (define-key org-mode-map [remap show-branches]
18344 'org-kill-note-or-show-branches)
18345 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18346 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18347 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18349 ;; Outline functions from `outline-mode-prefix-map' that can not
18350 ;; be remapped in Org:
18352 ;; - the column "key binding" shows whether the Outline function is still
18353 ;; available in Org mode on the same key that it has been bound to in
18354 ;; Outline mode:
18355 ;; - "overridden": key used for a different functionality in Org mode
18356 ;; - else: key still bound to the same Outline function in Org mode
18358 ;; | Outline function | key binding | Org replacement |
18359 ;; |------------------------------------+-------------+-----------------------|
18360 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18361 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18362 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18363 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18364 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18365 ;; | `show-entry' | overridden | no replacement |
18366 ;; | `show-children' | `C-c C-i' | visibility cycling |
18367 ;; | `show-branches' | `C-c C-k' | still same function |
18368 ;; | `show-subtree' | overridden | visibility cycling |
18369 ;; | `show-all' | overridden | no replacement |
18370 ;; | `hide-subtree' | overridden | visibility cycling |
18371 ;; | `hide-body' | overridden | no replacement |
18372 ;; | `hide-entry' | overridden | visibility cycling |
18373 ;; | `hide-leaves' | overridden | no replacement |
18374 ;; | `hide-sublevels' | overridden | no replacement |
18375 ;; | `hide-other' | overridden | no replacement |
18377 ;; Make `C-c C-x' a prefix key
18378 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18380 ;; TAB key with modifiers
18381 (org-defkey org-mode-map "\C-i" 'org-cycle)
18382 (org-defkey org-mode-map [(tab)] 'org-cycle)
18383 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18384 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18385 ;; The following line is necessary under Suse GNU/Linux
18386 (unless (featurep 'xemacs)
18387 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18388 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18389 (define-key org-mode-map [backtab] 'org-shifttab)
18391 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18392 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18393 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18395 ;; Cursor keys with modifiers
18396 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18397 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18398 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18399 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18401 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18402 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18403 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18404 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18406 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18407 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18408 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18409 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18411 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18412 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18413 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18414 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18416 ;; Babel keys
18417 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18418 (mapc (lambda (pair)
18419 (define-key org-babel-map (car pair) (cdr pair)))
18420 org-babel-key-bindings)
18422 ;;; Extra keys for tty access.
18423 ;; We only set them when really needed because otherwise the
18424 ;; menus don't show the simple keys
18426 (when (or org-use-extra-keys
18427 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18428 (not window-system))
18429 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18430 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18431 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18432 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18433 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18434 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18435 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18436 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18437 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18438 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18439 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18440 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18441 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18442 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18443 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18444 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18445 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18446 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18447 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18448 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18449 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18450 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18451 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18452 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18453 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18454 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18455 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18456 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18458 ;; All the other keys
18460 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18461 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18462 (if (boundp 'narrow-map)
18463 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18464 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18465 (if (boundp 'narrow-map)
18466 (org-defkey narrow-map "b" 'org-narrow-to-block)
18467 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18468 (if (boundp 'narrow-map)
18469 (org-defkey narrow-map "e" 'org-narrow-to-element)
18470 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18471 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18472 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18473 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18474 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18475 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18476 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18477 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18478 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18479 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18480 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18481 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18482 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18483 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18484 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18485 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18486 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18487 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18488 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18489 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18490 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18491 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18492 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18493 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18494 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18495 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18496 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18497 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18498 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18499 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18500 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18501 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18502 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18503 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18504 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18505 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18506 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18507 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18508 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18509 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18510 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18511 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18512 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18513 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18514 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18515 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18516 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18517 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18518 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18519 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18520 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18521 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18522 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18523 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18524 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18525 (org-defkey org-mode-map "\C-c^" 'org-sort)
18526 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18527 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18528 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18529 (org-defkey org-mode-map "\C-m" 'org-return)
18530 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18531 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18532 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18533 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18534 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18535 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18536 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18537 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18538 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18539 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18540 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18541 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18542 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18543 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18544 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18545 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18546 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18547 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18548 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18549 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18550 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18551 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18552 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18554 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18555 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18556 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18558 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18559 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18560 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18561 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18562 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18563 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18564 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18565 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18566 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18567 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18568 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18569 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18570 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18571 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18572 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18573 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18574 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18575 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18576 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18577 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18578 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18579 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18580 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18582 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18583 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18584 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18585 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18586 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18588 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18590 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18592 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18593 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18595 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18598 (when (featurep 'xemacs)
18599 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18602 (defconst org-speed-commands-default
18604 ("Outline Navigation")
18605 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18606 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18607 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18608 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18609 ("F" . org-next-block)
18610 ("B" . org-previous-block)
18611 ("u" . (org-speed-move-safe 'outline-up-heading))
18612 ("j" . org-goto)
18613 ("g" . (org-refile t))
18614 ("Outline Visibility")
18615 ("c" . org-cycle)
18616 ("C" . org-shifttab)
18617 (" " . org-display-outline-path)
18618 ("=" . org-columns)
18619 ("Outline Structure Editing")
18620 ("U" . org-shiftmetaup)
18621 ("D" . org-shiftmetadown)
18622 ("r" . org-metaright)
18623 ("l" . org-metaleft)
18624 ("R" . org-shiftmetaright)
18625 ("L" . org-shiftmetaleft)
18626 ("i" . (progn (forward-char 1) (call-interactively
18627 'org-insert-heading-respect-content)))
18628 ("^" . org-sort)
18629 ("w" . org-refile)
18630 ("a" . org-archive-subtree-default-with-confirmation)
18631 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18632 ("#" . org-toggle-comment)
18633 ("Clock Commands")
18634 ("I" . org-clock-in)
18635 ("O" . org-clock-out)
18636 ("Meta Data Editing")
18637 ("t" . org-todo)
18638 ("," . (org-priority))
18639 ("0" . (org-priority ?\ ))
18640 ("1" . (org-priority ?A))
18641 ("2" . (org-priority ?B))
18642 ("3" . (org-priority ?C))
18643 (":" . org-set-tags-command)
18644 ("e" . org-set-effort)
18645 ("E" . org-inc-effort)
18646 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18647 (org-entry-put (point) "APPT_WARNTIME" m)))
18648 ("Agenda Views etc")
18649 ("v" . org-agenda)
18650 ("/" . org-sparse-tree)
18651 ("Misc")
18652 ("o" . org-open-at-point)
18653 ("?" . org-speed-command-help)
18654 ("<" . (org-agenda-set-restriction-lock 'subtree))
18655 (">" . (org-agenda-remove-restriction-lock))
18657 "The default speed commands.")
18659 (defun org-print-speed-command (e)
18660 (if (> (length (car e)) 1)
18661 (progn
18662 (princ "\n")
18663 (princ (car e))
18664 (princ "\n")
18665 (princ (make-string (length (car e)) ?-))
18666 (princ "\n"))
18667 (princ (car e))
18668 (princ " ")
18669 (if (symbolp (cdr e))
18670 (princ (symbol-name (cdr e)))
18671 (prin1 (cdr e)))
18672 (princ "\n")))
18674 (defun org-speed-command-help ()
18675 "Show the available speed commands."
18676 (interactive)
18677 (if (not org-use-speed-commands)
18678 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18679 (with-output-to-temp-buffer "*Help*"
18680 (princ "User-defined Speed commands\n===========================\n")
18681 (mapc 'org-print-speed-command org-speed-commands-user)
18682 (princ "\n")
18683 (princ "Built-in Speed commands\n=======================\n")
18684 (mapc 'org-print-speed-command org-speed-commands-default))
18685 (with-current-buffer "*Help*"
18686 (setq truncate-lines t))))
18688 (defun org-speed-move-safe (cmd)
18689 "Execute CMD, but make sure that the cursor always ends up in a headline.
18690 If not, return to the original position and throw an error."
18691 (interactive)
18692 (let ((pos (point)))
18693 (call-interactively cmd)
18694 (unless (and (bolp) (org-at-heading-p))
18695 (goto-char pos)
18696 (error "Boundary reached while executing %s" cmd))))
18698 (defvar org-self-insert-command-undo-counter 0)
18700 (defvar org-table-auto-blank-field) ; defined in org-table.el
18701 (defvar org-speed-command nil)
18703 (define-obsolete-function-alias
18704 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18706 (defun org-speed-command-activate (keys)
18707 "Hook for activating single-letter speed commands.
18708 `org-speed-commands-default' specifies a minimal command set.
18709 Use `org-speed-commands-user' for further customization."
18710 (when (or (and (bolp) (looking-at org-outline-regexp))
18711 (and (functionp org-use-speed-commands)
18712 (funcall org-use-speed-commands)))
18713 (cdr (assoc keys (append org-speed-commands-user
18714 org-speed-commands-default)))))
18716 (define-obsolete-function-alias
18717 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18719 (defun org-babel-speed-command-activate (keys)
18720 "Hook for activating single-letter code block commands."
18721 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18722 (cdr (assoc keys org-babel-key-bindings))))
18724 (defcustom org-speed-command-hook
18725 '(org-speed-command-default-hook org-babel-speed-command-hook)
18726 "Hook for activating speed commands at strategic locations.
18727 Hook functions are called in sequence until a valid handler is
18728 found.
18730 Each hook takes a single argument, a user-pressed command key
18731 which is also a `self-insert-command' from the global map.
18733 Within the hook, examine the cursor position and the command key
18734 and return nil or a valid handler as appropriate. Handler could
18735 be one of an interactive command, a function, or a form.
18737 Set `org-use-speed-commands' to non-nil value to enable this
18738 hook. The default setting is `org-speed-command-activate'."
18739 :group 'org-structure
18740 :version "24.1"
18741 :type 'hook)
18743 (defun org-self-insert-command (N)
18744 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18745 If the cursor is in a table looking at whitespace, the whitespace is
18746 overwritten, and the table is not marked as requiring realignment."
18747 (interactive "p")
18748 (org-check-before-invisible-edit 'insert)
18749 (cond
18750 ((and org-use-speed-commands
18751 (setq org-speed-command
18752 (run-hook-with-args-until-success
18753 'org-speed-command-hook (this-command-keys))))
18754 (cond
18755 ((commandp org-speed-command)
18756 (setq this-command org-speed-command)
18757 (call-interactively org-speed-command))
18758 ((functionp org-speed-command)
18759 (funcall org-speed-command))
18760 ((and org-speed-command (listp org-speed-command))
18761 (eval org-speed-command))
18762 (t (let (org-use-speed-commands)
18763 (call-interactively 'org-self-insert-command)))))
18764 ((and
18765 (org-table-p)
18766 (progn
18767 ;; check if we blank the field, and if that triggers align
18768 (and (featurep 'org-table) org-table-auto-blank-field
18769 (member last-command
18770 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18771 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18772 ;; got extra space, this field does not determine column width
18773 (let (org-table-may-need-update) (org-table-blank-field))
18774 ;; no extra space, this field may determine column width
18775 (org-table-blank-field)))
18777 (eq N 1)
18778 (looking-at "[^|\n]* |"))
18779 (let (org-table-may-need-update)
18780 (goto-char (1- (match-end 0)))
18781 (backward-delete-char 1)
18782 (goto-char (match-beginning 0))
18783 (self-insert-command N)))
18785 (setq org-table-may-need-update t)
18786 (self-insert-command N)
18787 (org-fix-tags-on-the-fly)
18788 (if org-self-insert-cluster-for-undo
18789 (if (not (eq last-command 'org-self-insert-command))
18790 (setq org-self-insert-command-undo-counter 1)
18791 (if (>= org-self-insert-command-undo-counter 20)
18792 (setq org-self-insert-command-undo-counter 1)
18793 (and (> org-self-insert-command-undo-counter 0)
18794 buffer-undo-list (listp buffer-undo-list)
18795 (not (cadr buffer-undo-list)) ; remove nil entry
18796 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18797 (setq org-self-insert-command-undo-counter
18798 (1+ org-self-insert-command-undo-counter))))))))
18800 (defun org-check-before-invisible-edit (kind)
18801 "Check is editing if kind KIND would be dangerous with invisible text around.
18802 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18803 ;; First, try to get out of here as quickly as possible, to reduce overhead
18804 (if (and org-catch-invisible-edits
18805 (or (not (boundp 'visible-mode)) (not visible-mode))
18806 (or (get-char-property (point) 'invisible)
18807 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18808 ;; OK, we need to take a closer look
18809 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18810 (invisible-before-point (if (bobp) nil (get-char-property
18811 (1- (point)) 'invisible)))
18812 (border-and-ok-direction
18814 ;; Check if we are acting predictably before invisible text
18815 (and invisible-at-point (not invisible-before-point)
18816 (memq kind '(insert delete-backward)))
18817 ;; Check if we are acting predictably after invisible text
18818 ;; This works not well, and I have turned it off. It seems
18819 ;; better to always show and stop after invisible text.
18820 ;; (and (not invisible-at-point) invisible-before-point
18821 ;; (memq kind '(insert delete)))
18823 (when (or (memq invisible-at-point '(outline org-hide-block t))
18824 (memq invisible-before-point '(outline org-hide-block t)))
18825 (if (eq org-catch-invisible-edits 'error)
18826 (error "Editing in invisible areas is prohibited - make visible first"))
18827 (if (and org-custom-properties-overlays
18828 (y-or-n-p "Display invisible properties in this buffer? "))
18829 (org-toggle-custom-properties-visibility)
18830 ;; Make the area visible
18831 (save-excursion
18832 (if invisible-before-point
18833 (goto-char (previous-single-char-property-change
18834 (point) 'invisible)))
18835 (org-cycle))
18836 (cond
18837 ((eq org-catch-invisible-edits 'show)
18838 ;; That's it, we do the edit after showing
18839 (message
18840 "Unfolding invisible region around point before editing")
18841 (sit-for 1))
18842 ((and (eq org-catch-invisible-edits 'smart)
18843 border-and-ok-direction)
18844 (message "Unfolding invisible region around point before editing"))
18846 ;; Don't do the edit, make the user repeat it in full visibility
18847 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18849 (defun org-fix-tags-on-the-fly ()
18850 (when (and (equal (char-after (point-at-bol)) ?*)
18851 (org-at-heading-p))
18852 (org-align-tags-here org-tags-column)))
18854 (defun org-delete-backward-char (N)
18855 "Like `delete-backward-char', insert whitespace at field end in tables.
18856 When deleting backwards, in tables this function will insert whitespace in
18857 front of the next \"|\" separator, to keep the table aligned. The table will
18858 still be marked for re-alignment if the field did fill the entire column,
18859 because, in this case the deletion might narrow the column."
18860 (interactive "p")
18861 (save-match-data
18862 (org-check-before-invisible-edit 'delete-backward)
18863 (if (and (org-table-p)
18864 (eq N 1)
18865 (string-match "|" (buffer-substring (point-at-bol) (point)))
18866 (looking-at ".*?|"))
18867 (let ((pos (point))
18868 (noalign (looking-at "[^|\n\r]* |"))
18869 (c org-table-may-need-update))
18870 (backward-delete-char N)
18871 (if (not overwrite-mode)
18872 (progn
18873 (skip-chars-forward "^|")
18874 (insert " ")
18875 (goto-char (1- pos))))
18876 ;; noalign: if there were two spaces at the end, this field
18877 ;; does not determine the width of the column.
18878 (if noalign (setq org-table-may-need-update c)))
18879 (backward-delete-char N)
18880 (org-fix-tags-on-the-fly))))
18882 (defun org-delete-char (N)
18883 "Like `delete-char', but insert whitespace at field end in tables.
18884 When deleting characters, in tables this function will insert whitespace in
18885 front of the next \"|\" separator, to keep the table aligned. The table will
18886 still be marked for re-alignment if the field did fill the entire column,
18887 because, in this case the deletion might narrow the column."
18888 (interactive "p")
18889 (save-match-data
18890 (org-check-before-invisible-edit 'delete)
18891 (if (and (org-table-p)
18892 (not (bolp))
18893 (not (= (char-after) ?|))
18894 (eq N 1))
18895 (if (looking-at ".*?|")
18896 (let ((pos (point))
18897 (noalign (looking-at "[^|\n\r]* |"))
18898 (c org-table-may-need-update))
18899 (replace-match (concat
18900 (substring (match-string 0) 1 -1)
18901 " |"))
18902 (goto-char pos)
18903 ;; noalign: if there were two spaces at the end, this field
18904 ;; does not determine the width of the column.
18905 (if noalign (setq org-table-may-need-update c)))
18906 (delete-char N))
18907 (delete-char N)
18908 (org-fix-tags-on-the-fly))))
18910 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18911 (put 'org-self-insert-command 'delete-selection t)
18912 (put 'orgtbl-self-insert-command 'delete-selection t)
18913 (put 'org-delete-char 'delete-selection 'supersede)
18914 (put 'org-delete-backward-char 'delete-selection 'supersede)
18915 (put 'org-yank 'delete-selection 'yank)
18917 ;; Make `flyspell-mode' delay after some commands
18918 (put 'org-self-insert-command 'flyspell-delayed t)
18919 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18920 (put 'org-delete-char 'flyspell-delayed t)
18921 (put 'org-delete-backward-char 'flyspell-delayed t)
18923 ;; Make pabbrev-mode expand after org-mode commands
18924 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18925 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18927 ;; How to do this: Measure non-white length of current string
18928 ;; If equal to column width, we should realign.
18930 (defun org-remap (map &rest commands)
18931 "In MAP, remap the functions given in COMMANDS.
18932 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18933 (let (new old)
18934 (while commands
18935 (setq old (pop commands) new (pop commands))
18936 (if (fboundp 'command-remapping)
18937 (org-defkey map (vector 'remap old) new)
18938 (substitute-key-definition old new map global-map)))))
18940 (when (eq org-enable-table-editor 'optimized)
18941 ;; If the user wants maximum table support, we need to hijack
18942 ;; some standard editing functions
18943 (org-remap org-mode-map
18944 'self-insert-command 'org-self-insert-command
18945 'delete-char 'org-delete-char
18946 'delete-backward-char 'org-delete-backward-char)
18947 (org-defkey org-mode-map "|" 'org-force-self-insert))
18949 (defvar org-ctrl-c-ctrl-c-hook nil
18950 "Hook for functions attaching themselves to `C-c C-c'.
18952 This can be used to add additional functionality to the C-c C-c
18953 key which executes context-dependent commands. This hook is run
18954 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18955 run after the last test.
18957 Each function will be called with no arguments. The function
18958 must check if the context is appropriate for it to act. If yes,
18959 it should do its thing and then return a non-nil value. If the
18960 context is wrong, just do nothing and return nil.")
18962 (defvar org-ctrl-c-ctrl-c-final-hook nil
18963 "Hook for functions attaching themselves to `C-c C-c'.
18965 This can be used to add additional functionality to the C-c C-c
18966 key which executes context-dependent commands. This hook is run
18967 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18968 before the first test.
18970 Each function will be called with no arguments. The function
18971 must check if the context is appropriate for it to act. If yes,
18972 it should do its thing and then return a non-nil value. If the
18973 context is wrong, just do nothing and return nil.")
18975 (defvar org-tab-first-hook nil
18976 "Hook for functions to attach themselves to TAB.
18977 See `org-ctrl-c-ctrl-c-hook' for more information.
18978 This hook runs as the first action when TAB is pressed, even before
18979 `org-cycle' messes around with the `outline-regexp' to cater for
18980 inline tasks and plain list item folding.
18981 If any function in this hook returns t, any other actions that
18982 would have been caused by TAB (such as table field motion or visibility
18983 cycling) will not occur.")
18985 (defvar org-tab-after-check-for-table-hook nil
18986 "Hook for functions to attach themselves to TAB.
18987 See `org-ctrl-c-ctrl-c-hook' for more information.
18988 This hook runs after it has been established that the cursor is not in a
18989 table, but before checking if the cursor is in a headline or if global cycling
18990 should be done.
18991 If any function in this hook returns t, not other actions like visibility
18992 cycling will be done.")
18994 (defvar org-tab-after-check-for-cycling-hook nil
18995 "Hook for functions to attach themselves to TAB.
18996 See `org-ctrl-c-ctrl-c-hook' for more information.
18997 This hook runs after it has been established that not table field motion and
18998 not visibility should be done because of current context. This is probably
18999 the place where a package like yasnippets can hook in.")
19001 (defvar org-tab-before-tab-emulation-hook nil
19002 "Hook for functions to attach themselves to TAB.
19003 See `org-ctrl-c-ctrl-c-hook' for more information.
19004 This hook runs after every other options for TAB have been exhausted, but
19005 before indentation and \t insertion takes place.")
19007 (defvar org-metaleft-hook nil
19008 "Hook for functions attaching themselves to `M-left'.
19009 See `org-ctrl-c-ctrl-c-hook' for more information.")
19010 (defvar org-metaright-hook nil
19011 "Hook for functions attaching themselves to `M-right'.
19012 See `org-ctrl-c-ctrl-c-hook' for more information.")
19013 (defvar org-metaup-hook nil
19014 "Hook for functions attaching themselves to `M-up'.
19015 See `org-ctrl-c-ctrl-c-hook' for more information.")
19016 (defvar org-metadown-hook nil
19017 "Hook for functions attaching themselves to `M-down'.
19018 See `org-ctrl-c-ctrl-c-hook' for more information.")
19019 (defvar org-shiftmetaleft-hook nil
19020 "Hook for functions attaching themselves to `M-S-left'.
19021 See `org-ctrl-c-ctrl-c-hook' for more information.")
19022 (defvar org-shiftmetaright-hook nil
19023 "Hook for functions attaching themselves to `M-S-right'.
19024 See `org-ctrl-c-ctrl-c-hook' for more information.")
19025 (defvar org-shiftmetaup-hook nil
19026 "Hook for functions attaching themselves to `M-S-up'.
19027 See `org-ctrl-c-ctrl-c-hook' for more information.")
19028 (defvar org-shiftmetadown-hook nil
19029 "Hook for functions attaching themselves to `M-S-down'.
19030 See `org-ctrl-c-ctrl-c-hook' for more information.")
19031 (defvar org-metareturn-hook nil
19032 "Hook for functions attaching themselves to `M-RET'.
19033 See `org-ctrl-c-ctrl-c-hook' for more information.")
19034 (defvar org-shiftup-hook nil
19035 "Hook for functions attaching themselves to `S-up'.
19036 See `org-ctrl-c-ctrl-c-hook' for more information.")
19037 (defvar org-shiftup-final-hook nil
19038 "Hook for functions attaching themselves to `S-up'.
19039 This one runs after all other options except shift-select have been excluded.
19040 See `org-ctrl-c-ctrl-c-hook' for more information.")
19041 (defvar org-shiftdown-hook nil
19042 "Hook for functions attaching themselves to `S-down'.
19043 See `org-ctrl-c-ctrl-c-hook' for more information.")
19044 (defvar org-shiftdown-final-hook nil
19045 "Hook for functions attaching themselves to `S-down'.
19046 This one runs after all other options except shift-select have been excluded.
19047 See `org-ctrl-c-ctrl-c-hook' for more information.")
19048 (defvar org-shiftleft-hook nil
19049 "Hook for functions attaching themselves to `S-left'.
19050 See `org-ctrl-c-ctrl-c-hook' for more information.")
19051 (defvar org-shiftleft-final-hook nil
19052 "Hook for functions attaching themselves to `S-left'.
19053 This one runs after all other options except shift-select have been excluded.
19054 See `org-ctrl-c-ctrl-c-hook' for more information.")
19055 (defvar org-shiftright-hook nil
19056 "Hook for functions attaching themselves to `S-right'.
19057 See `org-ctrl-c-ctrl-c-hook' for more information.")
19058 (defvar org-shiftright-final-hook nil
19059 "Hook for functions attaching themselves to `S-right'.
19060 This one runs after all other options except shift-select have been excluded.
19061 See `org-ctrl-c-ctrl-c-hook' for more information.")
19063 (defun org-modifier-cursor-error ()
19064 "Throw an error, a modified cursor command was applied in wrong context."
19065 (error "This command is active in special context like tables, headlines or items"))
19067 (defun org-shiftselect-error ()
19068 "Throw an error because Shift-Cursor command was applied in wrong context."
19069 (if (and (boundp 'shift-select-mode) shift-select-mode)
19070 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19071 (error "This command works only in special context like headlines or timestamps")))
19073 (defun org-call-for-shift-select (cmd)
19074 (let ((this-command-keys-shift-translated t))
19075 (call-interactively cmd)))
19077 (defun org-shifttab (&optional arg)
19078 "Global visibility cycling or move to previous table field.
19079 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19080 on context.
19081 See the individual commands for more information."
19082 (interactive "P")
19083 (cond
19084 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19085 ((integerp arg)
19086 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19087 (message "Content view to level: %d" arg)
19088 (org-content (prefix-numeric-value arg2))
19089 (setq org-cycle-global-status 'overview)))
19090 (t (call-interactively 'org-global-cycle))))
19092 (defun org-shiftmetaleft ()
19093 "Promote subtree or delete table column.
19094 Calls `org-promote-subtree', `org-outdent-item-tree', or
19095 `org-table-delete-column', depending on context. See the
19096 individual commands for more information."
19097 (interactive)
19098 (cond
19099 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19100 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19101 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19102 ((if (not (org-region-active-p)) (org-at-item-p)
19103 (save-excursion (goto-char (region-beginning))
19104 (org-at-item-p)))
19105 (call-interactively 'org-outdent-item-tree))
19106 (t (org-modifier-cursor-error))))
19108 (defun org-shiftmetaright ()
19109 "Demote subtree or insert table column.
19110 Calls `org-demote-subtree', `org-indent-item-tree', or
19111 `org-table-insert-column', depending on context. See the
19112 individual commands for more information."
19113 (interactive)
19114 (cond
19115 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19116 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19117 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19118 ((if (not (org-region-active-p)) (org-at-item-p)
19119 (save-excursion (goto-char (region-beginning))
19120 (org-at-item-p)))
19121 (call-interactively 'org-indent-item-tree))
19122 (t (org-modifier-cursor-error))))
19124 (defun org-shiftmetaup (&optional arg)
19125 "Move subtree up or kill table row.
19126 Calls `org-move-subtree-up' or `org-table-kill-row' or
19127 `org-move-item-up' or `org-timestamp-up', depending on context.
19128 See the individual commands for more information."
19129 (interactive "P")
19130 (cond
19131 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19132 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19133 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19134 ((org-at-item-p) (call-interactively 'org-move-item-up))
19135 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19136 (call-interactively 'org-timestamp-up)))
19137 (t (org-modifier-cursor-error))))
19139 (defun org-shiftmetadown (&optional arg)
19140 "Move subtree down or insert table row.
19141 Calls `org-move-subtree-down' or `org-table-insert-row' or
19142 `org-move-item-down' or `org-timestamp-up', depending on context.
19143 See the individual commands for more information."
19144 (interactive "P")
19145 (cond
19146 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19147 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19148 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19149 ((org-at-item-p) (call-interactively 'org-move-item-down))
19150 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19151 (call-interactively 'org-timestamp-down)))
19152 (t (org-modifier-cursor-error))))
19154 (defsubst org-hidden-tree-error ()
19155 (error
19156 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19158 (defun org-metaleft (&optional arg)
19159 "Promote heading or move table column to left.
19160 Calls `org-do-promote' or `org-table-move-column', depending on context.
19161 With no specific context, calls the Emacs default `backward-word'.
19162 See the individual commands for more information."
19163 (interactive "P")
19164 (cond
19165 ((run-hook-with-args-until-success 'org-metaleft-hook))
19166 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19167 ((org-with-limited-levels
19168 (or (org-at-heading-p)
19169 (and (org-region-active-p)
19170 (save-excursion
19171 (goto-char (region-beginning))
19172 (org-at-heading-p)))))
19173 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19174 (call-interactively 'org-do-promote))
19175 ;; At an inline task.
19176 ((org-at-heading-p)
19177 (call-interactively 'org-inlinetask-promote))
19178 ((or (org-at-item-p)
19179 (and (org-region-active-p)
19180 (save-excursion
19181 (goto-char (region-beginning))
19182 (org-at-item-p))))
19183 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19184 (call-interactively 'org-outdent-item))
19185 (t (call-interactively 'backward-word))))
19187 (defun org-metaright (&optional arg)
19188 "Demote a subtree, a list item or move table column to right.
19189 In front of a drawer or a block keyword, indent it correctly.
19190 With no specific context, calls the Emacs default `forward-word'.
19191 See the individual commands for more information."
19192 (interactive "P")
19193 (cond
19194 ((run-hook-with-args-until-success 'org-metaright-hook))
19195 ((org-at-table-p) (call-interactively 'org-table-move-column))
19196 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19197 ((org-at-block-p) (call-interactively 'org-indent-block))
19198 ((org-with-limited-levels
19199 (or (org-at-heading-p)
19200 (and (org-region-active-p)
19201 (save-excursion
19202 (goto-char (region-beginning))
19203 (org-at-heading-p)))))
19204 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19205 (call-interactively 'org-do-demote))
19206 ;; At an inline task.
19207 ((org-at-heading-p)
19208 (call-interactively 'org-inlinetask-demote))
19209 ((or (org-at-item-p)
19210 (and (org-region-active-p)
19211 (save-excursion
19212 (goto-char (region-beginning))
19213 (org-at-item-p))))
19214 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19215 (call-interactively 'org-indent-item))
19216 (t (call-interactively 'forward-word))))
19218 (defun org-check-for-hidden (what)
19219 "Check if there are hidden headlines/items in the current visual line.
19220 WHAT can be either `headlines' or `items'. If the current line is
19221 an outline or item heading and it has a folded subtree below it,
19222 this function returns t, nil otherwise."
19223 (let ((re (cond
19224 ((eq what 'headlines) org-outline-regexp-bol)
19225 ((eq what 'items) (org-item-beginning-re))
19226 (t (error "This should not happen"))))
19227 beg end)
19228 (save-excursion
19229 (catch 'exit
19230 (unless (org-region-active-p)
19231 (setq beg (point-at-bol))
19232 (beginning-of-line 2)
19233 (while (and (not (eobp)) ;; this is like `next-line'
19234 (get-char-property (1- (point)) 'invisible))
19235 (beginning-of-line 2))
19236 (setq end (point))
19237 (goto-char beg)
19238 (goto-char (point-at-eol))
19239 (setq end (max end (point)))
19240 (while (re-search-forward re end t)
19241 (if (get-char-property (match-beginning 0) 'invisible)
19242 (throw 'exit t))))
19243 nil))))
19245 (defun org-metaup (&optional arg)
19246 "Move subtree up or move table row up.
19247 Calls `org-move-subtree-up' or `org-table-move-row' or
19248 `org-move-item-up', depending on context. See the individual commands
19249 for more information."
19250 (interactive "P")
19251 (cond
19252 ((run-hook-with-args-until-success 'org-metaup-hook))
19253 ((org-region-active-p)
19254 (let* ((a (min (region-beginning) (region-end)))
19255 (b (1- (max (region-beginning) (region-end))))
19256 (c (save-excursion (goto-char a)
19257 (move-beginning-of-line 0)))
19258 (d (save-excursion (goto-char a)
19259 (move-end-of-line 0) (point))))
19260 (transpose-regions a b c d)
19261 (goto-char c)))
19262 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19263 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19264 ((org-at-item-p) (call-interactively 'org-move-item-up))
19265 (t (org-drag-element-backward))))
19267 (defun org-metadown (&optional arg)
19268 "Move subtree down or move table row down.
19269 Calls `org-move-subtree-down' or `org-table-move-row' or
19270 `org-move-item-down', depending on context. See the individual
19271 commands for more information."
19272 (interactive "P")
19273 (cond
19274 ((run-hook-with-args-until-success 'org-metadown-hook))
19275 ((org-region-active-p)
19276 (let* ((a (min (region-beginning) (region-end)))
19277 (b (max (region-beginning) (region-end)))
19278 (c (save-excursion (goto-char b)
19279 (move-beginning-of-line 1)))
19280 (d (save-excursion (goto-char b)
19281 (move-end-of-line 1) (1+ (point)))))
19282 (transpose-regions a b c d)
19283 (goto-char d)))
19284 ((org-at-table-p) (call-interactively 'org-table-move-row))
19285 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19286 ((org-at-item-p) (call-interactively 'org-move-item-down))
19287 (t (org-drag-element-forward))))
19289 (defun org-shiftup (&optional arg)
19290 "Increase item in timestamp or increase priority of current headline.
19291 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19292 depending on context. See the individual commands for more information."
19293 (interactive "P")
19294 (cond
19295 ((run-hook-with-args-until-success 'org-shiftup-hook))
19296 ((and org-support-shift-select (org-region-active-p))
19297 (org-call-for-shift-select 'previous-line))
19298 ((org-at-timestamp-p t)
19299 (call-interactively (if org-edit-timestamp-down-means-later
19300 'org-timestamp-down 'org-timestamp-up)))
19301 ((and (not (eq org-support-shift-select 'always))
19302 org-enable-priority-commands
19303 (org-at-heading-p))
19304 (call-interactively 'org-priority-up))
19305 ((and (not org-support-shift-select) (org-at-item-p))
19306 (call-interactively 'org-previous-item))
19307 ((org-clocktable-try-shift 'up arg))
19308 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19309 (org-support-shift-select
19310 (org-call-for-shift-select 'previous-line))
19311 (t (org-shiftselect-error))))
19313 (defun org-shiftdown (&optional arg)
19314 "Decrease item in timestamp or decrease priority of current headline.
19315 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19316 depending on context. See the individual commands for more information."
19317 (interactive "P")
19318 (cond
19319 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19320 ((and org-support-shift-select (org-region-active-p))
19321 (org-call-for-shift-select 'next-line))
19322 ((org-at-timestamp-p t)
19323 (call-interactively (if org-edit-timestamp-down-means-later
19324 'org-timestamp-up 'org-timestamp-down)))
19325 ((and (not (eq org-support-shift-select 'always))
19326 org-enable-priority-commands
19327 (org-at-heading-p))
19328 (call-interactively 'org-priority-down))
19329 ((and (not org-support-shift-select) (org-at-item-p))
19330 (call-interactively 'org-next-item))
19331 ((org-clocktable-try-shift 'down arg))
19332 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19333 (org-support-shift-select
19334 (org-call-for-shift-select 'next-line))
19335 (t (org-shiftselect-error))))
19337 (defun org-shiftright (&optional arg)
19338 "Cycle the thing at point or in the current line, depending on context.
19339 Depending on context, this does one of the following:
19341 - switch a timestamp at point one day into the future
19342 - on a headline, switch to the next TODO keyword.
19343 - on an item, switch entire list to the next bullet type
19344 - on a property line, switch to the next allowed value
19345 - on a clocktable definition line, move time block into the future"
19346 (interactive "P")
19347 (cond
19348 ((run-hook-with-args-until-success 'org-shiftright-hook))
19349 ((and org-support-shift-select (org-region-active-p))
19350 (org-call-for-shift-select 'forward-char))
19351 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19352 ((and (not (eq org-support-shift-select 'always))
19353 (org-at-heading-p))
19354 (let ((org-inhibit-logging
19355 (not org-treat-S-cursor-todo-selection-as-state-change))
19356 (org-inhibit-blocking
19357 (not org-treat-S-cursor-todo-selection-as-state-change)))
19358 (org-call-with-arg 'org-todo 'right)))
19359 ((or (and org-support-shift-select
19360 (not (eq org-support-shift-select 'always))
19361 (org-at-item-bullet-p))
19362 (and (not org-support-shift-select) (org-at-item-p)))
19363 (org-call-with-arg 'org-cycle-list-bullet nil))
19364 ((and (not (eq org-support-shift-select 'always))
19365 (org-at-property-p))
19366 (call-interactively 'org-property-next-allowed-value))
19367 ((org-clocktable-try-shift 'right arg))
19368 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19369 (org-support-shift-select
19370 (org-call-for-shift-select 'forward-char))
19371 (t (org-shiftselect-error))))
19373 (defun org-shiftleft (&optional arg)
19374 "Cycle the thing at point or in the current line, depending on context.
19375 Depending on context, this does one of the following:
19377 - switch a timestamp at point one day into the past
19378 - on a headline, switch to the previous TODO keyword.
19379 - on an item, switch entire list to the previous bullet type
19380 - on a property line, switch to the previous allowed value
19381 - on a clocktable definition line, move time block into the past"
19382 (interactive "P")
19383 (cond
19384 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19385 ((and org-support-shift-select (org-region-active-p))
19386 (org-call-for-shift-select 'backward-char))
19387 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19388 ((and (not (eq org-support-shift-select 'always))
19389 (org-at-heading-p))
19390 (let ((org-inhibit-logging
19391 (not org-treat-S-cursor-todo-selection-as-state-change))
19392 (org-inhibit-blocking
19393 (not org-treat-S-cursor-todo-selection-as-state-change)))
19394 (org-call-with-arg 'org-todo 'left)))
19395 ((or (and org-support-shift-select
19396 (not (eq org-support-shift-select 'always))
19397 (org-at-item-bullet-p))
19398 (and (not org-support-shift-select) (org-at-item-p)))
19399 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19400 ((and (not (eq org-support-shift-select 'always))
19401 (org-at-property-p))
19402 (call-interactively 'org-property-previous-allowed-value))
19403 ((org-clocktable-try-shift 'left arg))
19404 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19405 (org-support-shift-select
19406 (org-call-for-shift-select 'backward-char))
19407 (t (org-shiftselect-error))))
19409 (defun org-shiftcontrolright ()
19410 "Switch to next TODO set."
19411 (interactive)
19412 (cond
19413 ((and org-support-shift-select (org-region-active-p))
19414 (org-call-for-shift-select 'forward-word))
19415 ((and (not (eq org-support-shift-select 'always))
19416 (org-at-heading-p))
19417 (org-call-with-arg 'org-todo 'nextset))
19418 (org-support-shift-select
19419 (org-call-for-shift-select 'forward-word))
19420 (t (org-shiftselect-error))))
19422 (defun org-shiftcontrolleft ()
19423 "Switch to previous TODO set."
19424 (interactive)
19425 (cond
19426 ((and org-support-shift-select (org-region-active-p))
19427 (org-call-for-shift-select 'backward-word))
19428 ((and (not (eq org-support-shift-select 'always))
19429 (org-at-heading-p))
19430 (org-call-with-arg 'org-todo 'previousset))
19431 (org-support-shift-select
19432 (org-call-for-shift-select 'backward-word))
19433 (t (org-shiftselect-error))))
19435 (defun org-shiftcontrolup (&optional n)
19436 "Change timestamps synchronously up in CLOCK log lines.
19437 Optional argument N tells to change by that many units."
19438 (interactive "P")
19439 (cond ((and (not org-support-shift-select)
19440 (org-at-clock-log-p)
19441 (org-at-timestamp-p t))
19442 (org-clock-timestamps-up n))
19443 (t (org-shiftselect-error))))
19445 (defun org-shiftcontroldown (&optional n)
19446 "Change timestamps synchronously down in CLOCK log lines.
19447 Optional argument N tells to change by that many units."
19448 (interactive "P")
19449 (cond ((and (not org-support-shift-select)
19450 (org-at-clock-log-p)
19451 (org-at-timestamp-p t))
19452 (org-clock-timestamps-down n))
19453 (t (org-shiftselect-error))))
19455 (defun org-ctrl-c-ret ()
19456 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19457 (interactive)
19458 (cond
19459 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19460 (t (call-interactively 'org-insert-heading))))
19462 (defun org-find-visible ()
19463 (let ((s (point)))
19464 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19465 (get-char-property s 'invisible)))
19467 (defun org-find-invisible ()
19468 (let ((s (point)))
19469 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19470 (not (get-char-property s 'invisible))))
19473 (defun org-copy-visible (beg end)
19474 "Copy the visible parts of the region."
19475 (interactive "r")
19476 (let (snippets s)
19477 (save-excursion
19478 (save-restriction
19479 (narrow-to-region beg end)
19480 (setq s (goto-char (point-min)))
19481 (while (not (= (point) (point-max)))
19482 (goto-char (org-find-invisible))
19483 (push (buffer-substring s (point)) snippets)
19484 (setq s (goto-char (org-find-visible))))))
19485 (kill-new (apply 'concat (nreverse snippets)))))
19487 (defun org-copy-special ()
19488 "Copy region in table or copy current subtree.
19489 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19490 See the individual commands for more information."
19491 (interactive)
19492 (call-interactively
19493 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19495 (defun org-cut-special ()
19496 "Cut region in table or cut current subtree.
19497 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19498 See the individual commands for more information."
19499 (interactive)
19500 (call-interactively
19501 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19503 (defun org-paste-special (arg)
19504 "Paste rectangular region into table, or past subtree relative to level.
19505 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19506 See the individual commands for more information."
19507 (interactive "P")
19508 (if (org-at-table-p)
19509 (org-table-paste-rectangle)
19510 (org-paste-subtree arg)))
19512 (defsubst org-in-fixed-width-region-p ()
19513 "Is point in a fixed-width region?"
19514 (save-match-data
19515 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19517 (defun org-edit-special (&optional arg)
19518 "Call a special editor for the element at point.
19519 When at a table, call the formula editor with `org-table-edit-formulas'.
19520 When in a source code block, call `org-edit-src-code'.
19521 When in a fixed-width region, call `org-edit-fixed-width-region'.
19522 When at an #+INCLUDE keyword, visit the included file.
19523 On a link, call `ffap' to visit the link at point.
19524 Otherwise, return a user error."
19525 (interactive)
19526 (let ((element (org-element-at-point)))
19527 (assert (not buffer-read-only) nil
19528 "Buffer is read-only: %s" (buffer-name))
19529 (case (org-element-type element)
19530 (src-block
19531 (if (not arg) (org-edit-src-code)
19532 (let* ((info (org-babel-get-src-block-info))
19533 (lang (nth 0 info))
19534 (params (nth 2 info))
19535 (session (cdr (assq :session params))))
19536 (if (not session) (org-edit-src-code)
19537 ;; At a src-block with a session and function called with
19538 ;; an ARG: switch to the buffer related to the inferior
19539 ;; process.
19540 (funcall (intern (concat "org-babel-prep-session:" lang))
19541 session params)))))
19542 (keyword
19543 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19544 (find-file
19545 (org-remove-double-quotes
19546 (car (org-split-string (org-element-property :value element)))))
19547 (user-error "No special environment to edit here")))
19548 (table
19549 (if (eq (org-element-property :type element) 'table.el)
19550 (org-edit-src-code)
19551 (call-interactively 'org-table-edit-formulas)))
19552 ;; Only Org tables contain `table-row' type elements.
19553 (table-row (call-interactively 'org-table-edit-formulas))
19554 ((example-block export-block) (org-edit-src-code))
19555 (fixed-width (org-edit-fixed-width-region))
19556 (otherwise
19557 ;; No notable element at point. Though, we may be at a link,
19558 ;; which is an object. Thus, scan deeper.
19559 (if (eq (org-element-type (org-element-context element)) 'link)
19560 (call-interactively 'ffap)
19561 (user-error "No special environment to edit here"))))))
19563 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19564 (defun org-ctrl-c-ctrl-c (&optional arg)
19565 "Set tags in headline, or update according to changed information at point.
19567 This command does many different things, depending on context:
19569 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19570 this is what we do.
19572 - If the cursor is on a statistics cookie, update it.
19574 - If the cursor is in a headline, prompt for tags and insert them
19575 into the current line, aligned to `org-tags-column'. When called
19576 with prefix arg, realign all tags in the current buffer.
19578 - If the cursor is in one of the special #+KEYWORD lines, this
19579 triggers scanning the buffer for these lines and updating the
19580 information.
19582 - If the cursor is inside a table, realign the table. This command
19583 works even if the automatic table editor has been turned off.
19585 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19586 the entire table.
19588 - If the cursor is at a footnote reference or definition, jump to
19589 the corresponding definition or references, respectively.
19591 - If the cursor is a the beginning of a dynamic block, update it.
19593 - If the current buffer is a capture buffer, close note and file it.
19595 - If the cursor is on a <<<target>>>, update radio targets and
19596 corresponding links in this buffer.
19598 - If the cursor is on a numbered item in a plain list, renumber the
19599 ordered list.
19601 - If the cursor is on a checkbox, toggle it.
19603 - If the cursor is on a code block, evaluate it. The variable
19604 `org-confirm-babel-evaluate' can be used to control prompting
19605 before code block evaluation, by default every code block
19606 evaluation requires confirmation. Code block evaluation can be
19607 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19608 (interactive "P")
19609 (cond
19610 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19611 org-occur-highlights
19612 org-latex-fragment-image-overlays)
19613 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19614 (org-remove-occur-highlights)
19615 (org-remove-latex-fragment-image-overlays)
19616 (message "Temporary highlights/overlays removed from current buffer"))
19617 ((and (local-variable-p 'org-finish-function (current-buffer))
19618 (fboundp org-finish-function))
19619 (funcall org-finish-function))
19620 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19622 (let* ((context (org-element-context)) (type (org-element-type context)))
19623 ;; Test if point is within blanks at the end of an element.
19624 (if (save-excursion
19625 (or (not context)
19626 (beginning-of-line)
19627 (and (looking-at "[ \t]*$")
19628 (skip-chars-forward " \r\t\n")
19629 (>= (point) (org-element-property :end context)))))
19630 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19631 (user-error "C-c C-c can do nothing useful at this location"))
19632 ;; For convenience: at the first line of a paragraph on the
19633 ;; same line as an item, apply function on that item instead.
19634 (when (eq type 'paragraph)
19635 (let ((parent (org-element-property :parent context)))
19636 (when (and (eq (org-element-type parent) 'item)
19637 (= (point-at-bol) (org-element-property :begin parent)))
19638 (setq context parent type 'item))))
19639 ;; Act according to type of element or object at point.
19640 (case type
19641 (clock (org-clock-update-time-maybe))
19642 (dynamic-block
19643 (save-excursion
19644 (goto-char (org-element-property :post-affiliated context))
19645 (org-update-dblock)))
19646 (footnote-definition
19647 (goto-char (org-element-property :post-affiliated context))
19648 (call-interactively 'org-footnote-action))
19649 (footnote-reference (call-interactively 'org-footnote-action))
19650 ((headline inlinetask)
19651 (save-excursion (goto-char (org-element-property :begin context))
19652 (call-interactively 'org-set-tags)))
19653 (item
19654 ;; At an item: a double C-u set checkbox to "[-]"
19655 ;; unconditionally, whereas a single one will toggle its
19656 ;; presence. Without an universal argument, if the item
19657 ;; has a checkbox, toggle it. Otherwise repair the list.
19658 (let* ((box (org-element-property :checkbox context))
19659 (struct (org-element-property :structure context))
19660 (old-struct (copy-tree struct))
19661 (parents (org-list-parents-alist struct))
19662 (prevs (org-list-prevs-alist struct))
19663 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19664 (org-list-set-checkbox
19665 (org-element-property :begin context) struct
19666 (cond ((equal arg '(16)) "[-]")
19667 ((and (not box) (equal arg '(4))) "[ ]")
19668 ((or (not box) (equal arg '(4))) nil)
19669 ((eq box 'on) "[ ]")
19670 (t "[X]")))
19671 ;; Mimic `org-list-write-struct' but with grabbing
19672 ;; a return value from `org-list-struct-fix-box'.
19673 (org-list-struct-fix-ind struct parents 2)
19674 (org-list-struct-fix-item-end struct)
19675 (org-list-struct-fix-bul struct prevs)
19676 (org-list-struct-fix-ind struct parents)
19677 (let ((block-item
19678 (org-list-struct-fix-box struct parents prevs orderedp)))
19679 (if (and box (equal struct old-struct))
19680 (if (equal arg '(16))
19681 (message "Checkboxes already reset")
19682 (user-error "Cannot toggle this checkbox: %s"
19683 (if (eq box 'on)
19684 "all subitems checked"
19685 "unchecked subitems")))
19686 (org-list-struct-apply-struct struct old-struct)
19687 (org-update-checkbox-count-maybe))
19688 (when block-item
19689 (message "Checkboxes were removed due to empty box at line %d"
19690 (org-current-line block-item))))))
19691 (keyword
19692 (let ((org-inhibit-startup-visibility-stuff t)
19693 (org-startup-align-all-tables nil))
19694 (when (boundp 'org-table-coordinate-overlays)
19695 (mapc 'delete-overlay org-table-coordinate-overlays)
19696 (setq org-table-coordinate-overlays nil))
19697 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19698 (message "Local setup has been refreshed"))
19699 (plain-list
19700 ;; At a plain list, with a double C-u argument, set
19701 ;; checkboxes of each item to "[-]", whereas a single one
19702 ;; will toggle their presence according to the state of the
19703 ;; first item in the list. Without an argument, repair the
19704 ;; list.
19705 (let* ((begin (org-element-property :contents-begin context))
19706 (struct (org-element-property :structure context))
19707 (old-struct (copy-tree struct))
19708 (first-box (save-excursion
19709 (goto-char begin)
19710 (looking-at org-list-full-item-re)
19711 (match-string-no-properties 3)))
19712 (new-box (cond ((equal arg '(16)) "[-]")
19713 ((equal arg '(4)) (unless first-box "[ ]"))
19714 ((equal first-box "[X]") "[ ]")
19715 (t "[X]"))))
19716 (cond
19717 (arg
19718 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19719 (org-list-get-all-items
19720 begin struct (org-list-prevs-alist struct))))
19721 ((and first-box (eq (point) begin))
19722 ;; For convenience, when point is at bol on the first
19723 ;; item of the list and no argument is provided, simply
19724 ;; toggle checkbox of that item, if any.
19725 (org-list-set-checkbox begin struct new-box)))
19726 (org-list-write-struct
19727 struct (org-list-parents-alist struct) old-struct)
19728 (org-update-checkbox-count-maybe)
19729 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19730 ((property-drawer node-property)
19731 (call-interactively 'org-property-action))
19732 ((radio-target target)
19733 (call-interactively 'org-update-radio-target-regexp))
19734 (statistics-cookie
19735 (call-interactively 'org-update-statistics-cookies))
19736 ((table table-cell table-row)
19737 ;; At a table, recalculate every field and align it. Also
19738 ;; send the table if necessary. If the table has
19739 ;; a `table.el' type, just give up. At a table row or
19740 ;; cell, maybe recalculate line but always align table.
19741 (if (eq (org-element-property :type context) 'table.el)
19742 (message "Use C-c ' to edit table.el tables")
19743 (let ((org-enable-table-editor t))
19744 (if (or (eq type 'table)
19745 ;; Check if point is at a TBLFM line.
19746 (and (eq type 'table-row)
19747 (= (point) (org-element-property :end context))))
19748 (save-excursion
19749 (goto-char (org-element-property :contents-begin context))
19750 (org-call-with-arg 'org-table-recalculate (or arg t))
19751 (orgtbl-send-table 'maybe))
19752 (org-table-maybe-eval-formula)
19753 (cond (arg (call-interactively 'org-table-recalculate))
19754 ((org-table-maybe-recalculate-line))
19755 (t (org-table-align)))))))
19756 (timestamp (org-timestamp-change 0 'day))
19757 (otherwise
19758 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19759 (user-error
19760 "C-c C-c can do nothing useful at this location")))))))))
19762 (defun org-mode-restart ()
19763 "Restart Org-mode, to scan again for special lines.
19764 Also updates the keyword regular expressions."
19765 (interactive)
19766 (org-mode)
19767 (message "Org-mode restarted"))
19769 (defun org-kill-note-or-show-branches ()
19770 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19771 (interactive)
19772 (if (not org-finish-function)
19773 (progn
19774 (hide-subtree)
19775 (call-interactively 'show-branches))
19776 (let ((org-note-abort t))
19777 (funcall org-finish-function))))
19779 (defun org-return (&optional indent)
19780 "Goto next table row or insert a newline.
19781 Calls `org-table-next-row' or `newline', depending on context.
19782 See the individual commands for more information."
19783 (interactive)
19784 (let (org-ts-what)
19785 (cond
19786 ((or (bobp) (org-in-src-block-p))
19787 (if indent (newline-and-indent) (newline)))
19788 ((org-at-table-p)
19789 (org-table-justify-field-maybe)
19790 (call-interactively 'org-table-next-row))
19791 ;; when `newline-and-indent' is called within a list, make sure
19792 ;; text moved stays inside the item.
19793 ((and (org-in-item-p) indent)
19794 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19795 (progn
19796 (save-match-data (newline))
19797 (org-indent-line-to (length (match-string 0))))
19798 (let ((ind (org-get-indentation)))
19799 (newline)
19800 (if (org-looking-back org-list-end-re)
19801 (org-indent-line)
19802 (org-indent-line-to ind)))))
19803 ((and org-return-follows-link
19804 (org-at-timestamp-p t)
19805 (not (eq org-ts-what 'after)))
19806 (org-follow-timestamp-link))
19807 ((and org-return-follows-link
19808 (let ((tprop (get-text-property (point) 'face)))
19809 (or (eq tprop 'org-link)
19810 (and (listp tprop) (memq 'org-link tprop)))))
19811 (call-interactively 'org-open-at-point))
19812 ((and (org-at-heading-p)
19813 (looking-at
19814 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19815 (org-show-entry)
19816 (end-of-line 1)
19817 (newline))
19818 (t (if indent (newline-and-indent) (newline))))))
19820 (defun org-return-indent ()
19821 "Goto next table row or insert a newline and indent.
19822 Calls `org-table-next-row' or `newline-and-indent', depending on
19823 context. See the individual commands for more information."
19824 (interactive)
19825 (org-return t))
19827 (defun org-ctrl-c-star ()
19828 "Compute table, or change heading status of lines.
19829 Calls `org-table-recalculate' or `org-toggle-heading',
19830 depending on context."
19831 (interactive)
19832 (cond
19833 ((org-at-table-p)
19834 (call-interactively 'org-table-recalculate))
19836 ;; Convert all lines in region to list items
19837 (call-interactively 'org-toggle-heading))))
19839 (defun org-ctrl-c-minus ()
19840 "Insert separator line in table or modify bullet status of line.
19841 Also turns a plain line or a region of lines into list items.
19842 Calls `org-table-insert-hline', `org-toggle-item', or
19843 `org-cycle-list-bullet', depending on context."
19844 (interactive)
19845 (cond
19846 ((org-at-table-p)
19847 (call-interactively 'org-table-insert-hline))
19848 ((org-region-active-p)
19849 (call-interactively 'org-toggle-item))
19850 ((org-in-item-p)
19851 (call-interactively 'org-cycle-list-bullet))
19853 (call-interactively 'org-toggle-item))))
19855 (defun org-toggle-item (arg)
19856 "Convert headings or normal lines to items, items to normal lines.
19857 If there is no active region, only the current line is considered.
19859 If the first non blank line in the region is an headline, convert
19860 all headlines to items, shifting text accordingly.
19862 If it is an item, convert all items to normal lines.
19864 If it is normal text, change region into an item. With a prefix
19865 argument ARG, change each line in region into an item."
19866 (interactive "P")
19867 (let ((shift-text
19868 (function
19869 ;; Shift text in current section to IND, from point to END.
19870 ;; The function leaves point to END line.
19871 (lambda (ind end)
19872 (let ((min-i 1000) (end (copy-marker end)))
19873 ;; First determine the minimum indentation (MIN-I) of
19874 ;; the text.
19875 (save-excursion
19876 (catch 'exit
19877 (while (< (point) end)
19878 (let ((i (org-get-indentation)))
19879 (cond
19880 ;; Skip blank lines and inline tasks.
19881 ((looking-at "^[ \t]*$"))
19882 ((looking-at org-outline-regexp-bol))
19883 ;; We can't find less than 0 indentation.
19884 ((zerop i) (throw 'exit (setq min-i 0)))
19885 ((< i min-i) (setq min-i i))))
19886 (forward-line))))
19887 ;; Then indent each line so that a line indented to
19888 ;; MIN-I becomes indented to IND. Ignore blank lines
19889 ;; and inline tasks in the process.
19890 (let ((delta (- ind min-i)))
19891 (while (< (point) end)
19892 (unless (or (looking-at "^[ \t]*$")
19893 (looking-at org-outline-regexp-bol))
19894 (org-indent-line-to (+ (org-get-indentation) delta)))
19895 (forward-line)))))))
19896 (skip-blanks
19897 (function
19898 ;; Return beginning of first non-blank line, starting from
19899 ;; line at POS.
19900 (lambda (pos)
19901 (save-excursion
19902 (goto-char pos)
19903 (skip-chars-forward " \r\t\n")
19904 (point-at-bol)))))
19905 beg end)
19906 ;; Determine boundaries of changes.
19907 (if (org-region-active-p)
19908 (setq beg (funcall skip-blanks (region-beginning))
19909 end (copy-marker (region-end)))
19910 (setq beg (funcall skip-blanks (point-at-bol))
19911 end (copy-marker (point-at-eol))))
19912 ;; Depending on the starting line, choose an action on the text
19913 ;; between BEG and END.
19914 (org-with-limited-levels
19915 (save-excursion
19916 (goto-char beg)
19917 (cond
19918 ;; Case 1. Start at an item: de-itemize. Note that it only
19919 ;; happens when a region is active: `org-ctrl-c-minus'
19920 ;; would call `org-cycle-list-bullet' otherwise.
19921 ((org-at-item-p)
19922 (while (< (point) end)
19923 (when (org-at-item-p)
19924 (skip-chars-forward " \t")
19925 (delete-region (point) (match-end 0)))
19926 (forward-line)))
19927 ;; Case 2. Start at an heading: convert to items.
19928 ((org-at-heading-p)
19929 (let* ((bul (org-list-bullet-string "-"))
19930 (bul-len (length bul))
19931 ;; Indentation of the first heading. It should be
19932 ;; relative to the indentation of its parent, if any.
19933 (start-ind (save-excursion
19934 (cond
19935 ((not org-adapt-indentation) 0)
19936 ((not (outline-previous-heading)) 0)
19937 (t (length (match-string 0))))))
19938 ;; Level of first heading. Further headings will be
19939 ;; compared to it to determine hierarchy in the list.
19940 (ref-level (org-reduced-level (org-outline-level))))
19941 (while (< (point) end)
19942 (let* ((level (org-reduced-level (org-outline-level)))
19943 (delta (max 0 (- level ref-level))))
19944 ;; If current headline is less indented than the first
19945 ;; one, set it as reference, in order to preserve
19946 ;; subtrees.
19947 (when (< level ref-level) (setq ref-level level))
19948 (replace-match bul t t)
19949 (org-indent-line-to (+ start-ind (* delta bul-len)))
19950 ;; Ensure all text down to END (or SECTION-END) belongs
19951 ;; to the newly created item.
19952 (let ((section-end (save-excursion
19953 (or (outline-next-heading) (point)))))
19954 (forward-line)
19955 (funcall shift-text
19956 (+ start-ind (* (1+ delta) bul-len))
19957 (min end section-end)))))))
19958 ;; Case 3. Normal line with ARG: turn each non-item line into
19959 ;; an item.
19960 (arg
19961 (while (< (point) end)
19962 (unless (or (org-at-heading-p) (org-at-item-p))
19963 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19964 (replace-match
19965 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19966 (forward-line)))
19967 ;; Case 4. Normal line without ARG: make the first line of
19968 ;; region an item, and shift indentation of others
19969 ;; lines to set them as item's body.
19970 (t (let* ((bul (org-list-bullet-string "-"))
19971 (bul-len (length bul))
19972 (ref-ind (org-get-indentation)))
19973 (skip-chars-forward " \t")
19974 (insert bul)
19975 (forward-line)
19976 (while (< (point) end)
19977 ;; Ensure that lines less indented than first one
19978 ;; still get included in item body.
19979 (funcall shift-text
19980 (+ ref-ind bul-len)
19981 (min end (save-excursion (or (outline-next-heading)
19982 (point)))))
19983 (forward-line)))))))))
19985 (defun org-toggle-heading (&optional nstars)
19986 "Convert headings to normal text, or items or text to headings.
19987 If there is no active region, only the current line is considered.
19989 With a \\[universal-argument] prefix, convert the whole list at
19990 point into heading.
19992 In a region:
19994 - If the first non blank line is an headline, remove the stars
19995 from all headlines in the region.
19997 - If it is a normal line turn each and every normal line (i.e. not an
19998 heading or an item) in the region into a heading.
20000 - If it is a plain list item, turn all plain list items into headings.
20002 When converting a line into a heading, the number of stars is chosen
20003 such that the lines become children of the current entry. However,
20004 when a prefix argument is given, its value determines the number of
20005 stars to add."
20006 (interactive "P")
20007 (let ((skip-blanks
20008 (function
20009 ;; Return beginning of first non-blank line, starting from
20010 ;; line at POS.
20011 (lambda (pos)
20012 (save-excursion
20013 (goto-char pos)
20014 (while (org-at-comment-p) (forward-line))
20015 (skip-chars-forward " \r\t\n")
20016 (point-at-bol)))))
20017 beg end toggled)
20018 ;; Determine boundaries of changes. If a universal prefix has
20019 ;; been given, put the list in a region. If region ends at a bol,
20020 ;; do not consider the last line to be in the region.
20022 (when (and current-prefix-arg (org-at-item-p))
20023 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20024 (org-mark-element))
20026 (if (org-region-active-p)
20027 (setq beg (funcall skip-blanks (region-beginning))
20028 end (copy-marker (save-excursion
20029 (goto-char (region-end))
20030 (if (bolp) (point) (point-at-eol)))))
20031 (setq beg (funcall skip-blanks (point-at-bol))
20032 end (copy-marker (point-at-eol))))
20033 ;; Ensure inline tasks don't count as headings.
20034 (org-with-limited-levels
20035 (save-excursion
20036 (goto-char beg)
20037 (cond
20038 ;; Case 1. Started at an heading: de-star headings.
20039 ((org-at-heading-p)
20040 (while (< (point) end)
20041 (when (org-at-heading-p t)
20042 (looking-at org-outline-regexp) (replace-match "")
20043 (setq toggled t))
20044 (forward-line)))
20045 ;; Case 2. Started at an item: change items into headlines.
20046 ;; One star will be added by `org-list-to-subtree'.
20047 ((org-at-item-p)
20048 (let* ((stars (make-string
20049 (if nstars
20050 ;; subtract the star that will be added again by
20051 ;; `org-list-to-subtree'
20052 (1- (prefix-numeric-value current-prefix-arg))
20053 (or (org-current-level) 0))
20054 ?*))
20055 (add-stars
20056 (cond (nstars "") ; stars from prefix only
20057 ((equal stars "") "") ; before first heading
20058 (org-odd-levels-only "*") ; inside heading, odd
20059 (t "")))) ; inside heading, oddeven
20060 (while (< (point) end)
20061 (when (org-at-item-p)
20062 ;; Pay attention to cases when region ends before list.
20063 (let* ((struct (org-list-struct))
20064 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20065 (save-restriction
20066 (narrow-to-region (point) list-end)
20067 (insert
20068 (org-list-to-subtree
20069 (org-list-parse-list t)
20070 '(:istart (concat stars add-stars (funcall get-stars depth))
20071 :icount (concat stars add-stars (funcall get-stars depth)))))))
20072 (setq toggled t))
20073 (forward-line))))
20074 ;; Case 3. Started at normal text: make every line an heading,
20075 ;; skipping headlines and items.
20076 (t (let* ((stars (make-string
20077 (if nstars
20078 (prefix-numeric-value current-prefix-arg)
20079 (or (org-current-level) 0))
20080 ?*))
20081 (add-stars
20082 (cond (nstars "") ; stars from prefix only
20083 ((equal stars "") "*") ; before first heading
20084 (org-odd-levels-only "**") ; inside heading, odd
20085 (t "*"))) ; inside heading, oddeven
20086 (rpl (concat stars add-stars " ")))
20087 (while (< (point) end)
20088 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20089 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20090 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20091 (forward-line)))))))
20092 (unless toggled (message "Cannot toggle heading from here"))))
20094 (defun org-meta-return (&optional arg)
20095 "Insert a new heading or wrap a region in a table.
20096 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20097 See the individual commands for more information."
20098 (interactive "P")
20099 (cond
20100 ((run-hook-with-args-until-success 'org-metareturn-hook))
20101 ((or (org-at-drawer-p) (org-at-property-p))
20102 (newline-and-indent))
20103 ((org-at-table-p)
20104 (call-interactively 'org-table-wrap-region))
20105 (t (call-interactively 'org-insert-heading))))
20107 ;;; Menu entries
20109 (defsubst org-in-subtree-not-table-p ()
20110 "Are we in a subtree and not in a table?"
20111 (and (not (org-before-first-heading-p))
20112 (not (org-at-table-p))))
20114 ;; Define the Org-mode menus
20115 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20116 '("Tbl"
20117 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20118 ["Next Field" org-cycle (org-at-table-p)]
20119 ["Previous Field" org-shifttab (org-at-table-p)]
20120 ["Next Row" org-return (org-at-table-p)]
20121 "--"
20122 ["Blank Field" org-table-blank-field (org-at-table-p)]
20123 ["Edit Field" org-table-edit-field (org-at-table-p)]
20124 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20125 "--"
20126 ("Column"
20127 ["Move Column Left" org-metaleft (org-at-table-p)]
20128 ["Move Column Right" org-metaright (org-at-table-p)]
20129 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20130 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20131 ("Row"
20132 ["Move Row Up" org-metaup (org-at-table-p)]
20133 ["Move Row Down" org-metadown (org-at-table-p)]
20134 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20135 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20136 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20137 "--"
20138 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20139 ("Rectangle"
20140 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20141 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20142 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20143 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20144 "--"
20145 ("Calculate"
20146 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20147 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20148 ["Edit Formulas" org-edit-special (org-at-table-p)]
20149 "--"
20150 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20151 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20152 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20153 "--"
20154 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20155 "--"
20156 ["Sum Column/Rectangle" org-table-sum
20157 (or (org-at-table-p) (org-region-active-p))]
20158 ["Which Column?" org-table-current-column (org-at-table-p)])
20159 ["Debug Formulas"
20160 org-table-toggle-formula-debugger
20161 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20162 ["Show Col/Row Numbers"
20163 org-table-toggle-coordinate-overlays
20164 :style toggle
20165 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20166 "--"
20167 ["Create" org-table-create (and (not (org-at-table-p))
20168 org-enable-table-editor)]
20169 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20170 ["Import from File" org-table-import (not (org-at-table-p))]
20171 ["Export to File" org-table-export (org-at-table-p)]
20172 "--"
20173 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20175 (easy-menu-define org-org-menu org-mode-map "Org menu"
20176 '("Org"
20177 ("Show/Hide"
20178 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20179 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20180 ["Sparse Tree..." org-sparse-tree t]
20181 ["Reveal Context" org-reveal t]
20182 ["Show All" show-all t]
20183 "--"
20184 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20185 "--"
20186 ["New Heading" org-insert-heading t]
20187 ("Navigate Headings"
20188 ["Up" outline-up-heading t]
20189 ["Next" outline-next-visible-heading t]
20190 ["Previous" outline-previous-visible-heading t]
20191 ["Next Same Level" outline-forward-same-level t]
20192 ["Previous Same Level" outline-backward-same-level t]
20193 "--"
20194 ["Jump" org-goto t])
20195 ("Edit Structure"
20196 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20197 "--"
20198 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20199 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20200 "--"
20201 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20202 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20203 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20204 "--"
20205 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20206 "--"
20207 ["Copy visible text" org-copy-visible t]
20208 "--"
20209 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20210 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20211 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20212 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20213 "--"
20214 ["Sort Region/Children" org-sort t]
20215 "--"
20216 ["Convert to odd levels" org-convert-to-odd-levels t]
20217 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20218 ("Editing"
20219 ["Emphasis..." org-emphasize t]
20220 ["Edit Source Example" org-edit-special t]
20221 "--"
20222 ["Footnote new/jump" org-footnote-action t]
20223 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20224 ("Archive"
20225 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20226 "--"
20227 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20228 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20229 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20231 "--"
20232 ("Hyperlinks"
20233 ["Store Link (Global)" org-store-link t]
20234 ["Find existing link to here" org-occur-link-in-agenda-files t]
20235 ["Insert Link" org-insert-link t]
20236 ["Follow Link" org-open-at-point t]
20237 "--"
20238 ["Next link" org-next-link t]
20239 ["Previous link" org-previous-link t]
20240 "--"
20241 ["Descriptive Links"
20242 org-toggle-link-display
20243 :style radio
20244 :selected org-descriptive-links
20246 ["Literal Links"
20247 org-toggle-link-display
20248 :style radio
20249 :selected (not org-descriptive-links)])
20250 "--"
20251 ("TODO Lists"
20252 ["TODO/DONE/-" org-todo t]
20253 ("Select keyword"
20254 ["Next keyword" org-shiftright (org-at-heading-p)]
20255 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20256 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20257 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20258 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20259 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20260 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20261 "--"
20262 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20263 :selected org-enforce-todo-dependencies :style toggle :active t]
20264 "Settings for tree at point"
20265 ["Do Children sequentially" org-toggle-ordered-property :style radio
20266 :selected (org-entry-get nil "ORDERED")
20267 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20268 ["Do Children parallel" org-toggle-ordered-property :style radio
20269 :selected (not (org-entry-get nil "ORDERED"))
20270 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20271 "--"
20272 ["Set Priority" org-priority t]
20273 ["Priority Up" org-shiftup t]
20274 ["Priority Down" org-shiftdown t]
20275 "--"
20276 ["Get news from all feeds" org-feed-update-all t]
20277 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20278 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20279 ("TAGS and Properties"
20280 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20281 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20282 "--"
20283 ["Set property" org-set-property (not (org-before-first-heading-p))]
20284 ["Column view of properties" org-columns t]
20285 ["Insert Column View DBlock" org-insert-columns-dblock t])
20286 ("Dates and Scheduling"
20287 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20288 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20289 ("Change Date"
20290 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20291 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20292 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20293 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20294 ["Compute Time Range" org-evaluate-time-range t]
20295 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20296 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20297 "--"
20298 ["Custom time format" org-toggle-time-stamp-overlays
20299 :style radio :selected org-display-custom-times]
20300 "--"
20301 ["Goto Calendar" org-goto-calendar t]
20302 ["Date from Calendar" org-date-from-calendar t]
20303 "--"
20304 ["Start/Restart Timer" org-timer-start t]
20305 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20306 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20307 ["Insert Timer String" org-timer t]
20308 ["Insert Timer Item" org-timer-item t])
20309 ("Logging work"
20310 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20311 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20312 ["Clock out" org-clock-out t]
20313 ["Clock cancel" org-clock-cancel t]
20314 "--"
20315 ["Mark as default task" org-clock-mark-default-task t]
20316 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20317 ["Goto running clock" org-clock-goto t]
20318 "--"
20319 ["Display times" org-clock-display t]
20320 ["Create clock table" org-clock-report t]
20321 "--"
20322 ["Record DONE time"
20323 (progn (setq org-log-done (not org-log-done))
20324 (message "Switching to %s will %s record a timestamp"
20325 (car org-done-keywords)
20326 (if org-log-done "automatically" "not")))
20327 :style toggle :selected org-log-done])
20328 "--"
20329 ["Agenda Command..." org-agenda t]
20330 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20331 ("File List for Agenda")
20332 ("Special views current file"
20333 ["TODO Tree" org-show-todo-tree t]
20334 ["Check Deadlines" org-check-deadlines t]
20335 ["Timeline" org-timeline t]
20336 ["Tags/Property tree" org-match-sparse-tree t])
20337 "--"
20338 ["Export/Publish..." org-export-dispatch t]
20339 ("LaTeX"
20340 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20341 :selected org-cdlatex-mode]
20342 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20343 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20344 ["Modify math symbol" org-cdlatex-math-modify
20345 (org-inside-LaTeX-fragment-p)]
20346 ["Insert citation" org-reftex-citation t]
20347 "--"
20348 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20349 "--"
20350 ("MobileOrg"
20351 ["Push Files and Views" org-mobile-push t]
20352 ["Get Captured and Flagged" org-mobile-pull t]
20353 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20354 "--"
20355 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20356 "--"
20357 ("Documentation"
20358 ["Show Version" org-version t]
20359 ["Info Documentation" org-info t])
20360 ("Customize"
20361 ["Browse Org Group" org-customize t]
20362 "--"
20363 ["Expand This Menu" org-create-customize-menu
20364 (fboundp 'customize-menu-create)])
20365 ["Send bug report" org-submit-bug-report t]
20366 "--"
20367 ("Refresh/Reload"
20368 ["Refresh setup current buffer" org-mode-restart t]
20369 ["Reload Org (after update)" org-reload t]
20370 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20373 (defun org-info (&optional node)
20374 "Read documentation for Org-mode in the info system.
20375 With optional NODE, go directly to that node."
20376 (interactive)
20377 (info (format "(org)%s" (or node ""))))
20379 ;;;###autoload
20380 (defun org-submit-bug-report ()
20381 "Submit a bug report on Org-mode via mail.
20383 Don't hesitate to report any problems or inaccurate documentation.
20385 If you don't have setup sending mail from (X)Emacs, please copy the
20386 output buffer into your mail program, as it gives us important
20387 information about your Org-mode version and configuration."
20388 (interactive)
20389 (require 'reporter)
20390 (org-load-modules-maybe)
20391 (org-require-autoloaded-modules)
20392 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20393 (reporter-submit-bug-report
20394 "emacs-orgmode@gnu.org"
20395 (org-version nil 'full)
20396 (let (list)
20397 (save-window-excursion
20398 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20399 (delete-other-windows)
20400 (erase-buffer)
20401 (insert "You are about to submit a bug report to the Org-mode mailing list.
20403 We would like to add your full Org-mode and Outline configuration to the
20404 bug report. This greatly simplifies the work of the maintainer and
20405 other experts on the mailing list.
20407 HOWEVER, some variables you have customized may contain private
20408 information. The names of customers, colleagues, or friends, might
20409 appear in the form of file names, tags, todo states, or search strings.
20410 If you answer yes to the prompt, you might want to check and remove
20411 such private information before sending the email.")
20412 (add-text-properties (point-min) (point-max) '(face org-warning))
20413 (when (yes-or-no-p "Include your Org-mode configuration ")
20414 (mapatoms
20415 (lambda (v)
20416 (and (boundp v)
20417 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20418 (or (and (symbol-value v)
20419 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20420 (and
20421 (get v 'custom-type) (get v 'standard-value)
20422 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20423 (push v list)))))
20424 (kill-buffer (get-buffer "*Warn about privacy*"))
20425 list))
20426 nil nil
20427 "Remember to cover the basics, that is, what you expected to happen and
20428 what in fact did happen. You don't know how to make a good report? See
20430 http://orgmode.org/manual/Feedback.html#Feedback
20432 Your bug report will be posted to the Org-mode mailing list.
20433 ------------------------------------------------------------------------")
20434 (save-excursion
20435 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20436 (replace-match "\\1Bug: \\3 [\\2]")))))
20439 (defun org-install-agenda-files-menu ()
20440 (let ((bl (buffer-list)))
20441 (save-excursion
20442 (while bl
20443 (set-buffer (pop bl))
20444 (if (derived-mode-p 'org-mode) (setq bl nil)))
20445 (when (derived-mode-p 'org-mode)
20446 (easy-menu-change
20447 '("Org") "File List for Agenda"
20448 (append
20449 (list
20450 ["Edit File List" (org-edit-agenda-file-list) t]
20451 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20452 ["Remove Current File from List" org-remove-file t]
20453 ["Cycle through agenda files" org-cycle-agenda-files t]
20454 ["Occur in all agenda files" org-occur-in-agenda-files t]
20455 "--")
20456 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20458 ;;;; Documentation
20460 (defun org-require-autoloaded-modules ()
20461 (interactive)
20462 (mapc 'require
20463 '(org-agenda org-archive org-attach org-clock org-colview org-id
20464 org-remember org-table org-timer)))
20466 ;;;###autoload
20467 (defun org-reload (&optional uncompiled)
20468 "Reload all org lisp files.
20469 With prefix arg UNCOMPILED, load the uncompiled versions."
20470 (interactive "P")
20471 (require 'loadhist)
20472 (let* ((org-dir (org-find-library-dir "org"))
20473 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20474 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20475 (remove-re (mapconcat 'identity
20476 (mapcar (lambda (f) (concat "^" f "$"))
20477 (list (if (featurep 'xemacs)
20478 "org-colview"
20479 "org-colview-xemacs")
20480 "org" "org-loaddefs" "org-version"))
20481 "\\|"))
20482 (feats (delete-dups
20483 (mapcar 'file-name-sans-extension
20484 (mapcar 'file-name-nondirectory
20485 (delq nil
20486 (mapcar 'feature-file
20487 features))))))
20488 (lfeat (append
20489 (sort
20490 (setq feats
20491 (delq nil (mapcar
20492 (lambda (f)
20493 (if (and (string-match feature-re f)
20494 (not (string-match remove-re f)))
20495 f nil))
20496 feats)))
20497 'string-lessp)
20498 (list "org-version" "org")))
20499 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20500 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20501 load-uncore load-misses)
20502 (setq load-misses
20503 (delq 't
20504 (mapcar (lambda (f)
20505 (or (org-load-noerror-mustsuffix (concat org-dir f))
20506 (and (string= org-dir contrib-dir)
20507 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20508 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20509 (add-to-list 'load-uncore f 'append)
20512 lfeat)))
20513 (if load-uncore
20514 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20515 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20516 (if load-misses
20517 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20518 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20519 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20521 ;;;###autoload
20522 (defun org-customize ()
20523 "Call the customize function with org as argument."
20524 (interactive)
20525 (org-load-modules-maybe)
20526 (org-require-autoloaded-modules)
20527 (customize-browse 'org))
20529 (defun org-create-customize-menu ()
20530 "Create a full customization menu for Org-mode, insert it into the menu."
20531 (interactive)
20532 (org-load-modules-maybe)
20533 (org-require-autoloaded-modules)
20534 (if (fboundp 'customize-menu-create)
20535 (progn
20536 (easy-menu-change
20537 '("Org") "Customize"
20538 `(["Browse Org group" org-customize t]
20539 "--"
20540 ,(customize-menu-create 'org)
20541 ["Set" Custom-set t]
20542 ["Save" Custom-save t]
20543 ["Reset to Current" Custom-reset-current t]
20544 ["Reset to Saved" Custom-reset-saved t]
20545 ["Reset to Standard Settings" Custom-reset-standard t]))
20546 (message "\"Org\"-menu now contains full customization menu"))
20547 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20549 ;;;; Miscellaneous stuff
20551 ;;; Generally useful functions
20553 (defun org-get-at-bol (property)
20554 "Get text property PROPERTY at beginning of line."
20555 (get-text-property (point-at-bol) property))
20557 (defun org-find-text-property-in-string (prop s)
20558 "Return the first non-nil value of property PROP in string S."
20559 (or (get-text-property 0 prop s)
20560 (get-text-property (or (next-single-property-change 0 prop s) 0)
20561 prop s)))
20563 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20564 "Display the given MESSAGE as a warning."
20565 (if (fboundp 'display-warning)
20566 (display-warning 'org message
20567 (if (featurep 'xemacs) 'warning :warning))
20568 (let ((buf (get-buffer-create "*Org warnings*")))
20569 (with-current-buffer buf
20570 (goto-char (point-max))
20571 (insert "Warning (Org): " message)
20572 (unless (bolp)
20573 (newline)))
20574 (display-buffer buf)
20575 (sit-for 0))))
20577 (defun org-eval (form)
20578 "Eval FORM and return result."
20579 (condition-case error
20580 (eval form)
20581 (error (format "%%![Error: %s]" error))))
20583 (defun org-in-clocktable-p ()
20584 "Check if the cursor is in a clocktable."
20585 (let ((pos (point)) start)
20586 (save-excursion
20587 (end-of-line 1)
20588 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20589 (setq start (match-beginning 0))
20590 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20591 (>= (match-end 0) pos)
20592 start))))
20594 (defun org-in-commented-line ()
20595 "Is point in a line starting with `#'?"
20596 (equal (char-after (point-at-bol)) ?#))
20598 (defun org-in-indented-comment-line ()
20599 "Is point in a line starting with `#' after some white space?"
20600 (save-excursion
20601 (save-match-data
20602 (goto-char (point-at-bol))
20603 (looking-at "[ \t]*#"))))
20605 (defun org-in-verbatim-emphasis ()
20606 (save-match-data
20607 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20609 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20610 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20611 (if (and marker (marker-buffer marker)
20612 (buffer-live-p (marker-buffer marker)))
20613 (progn
20614 (org-pop-to-buffer-same-window (marker-buffer marker))
20615 (if (or (> marker (point-max)) (< marker (point-min)))
20616 (widen))
20617 (goto-char marker)
20618 (org-show-context 'org-goto))
20619 (if bookmark
20620 (bookmark-jump bookmark)
20621 (error "Cannot find location"))))
20623 (defun org-quote-csv-field (s)
20624 "Quote field for inclusion in CSV material."
20625 (if (string-match "[\",]" s)
20626 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20629 (defun org-force-self-insert (N)
20630 "Needed to enforce self-insert under remapping."
20631 (interactive "p")
20632 (self-insert-command N))
20634 (defun org-string-width (s)
20635 "Compute width of string, ignoring invisible characters.
20636 This ignores character with invisibility property `org-link', and also
20637 characters with property `org-cwidth', because these will become invisible
20638 upon the next fontification round."
20639 (let (b l)
20640 (when (or (eq t buffer-invisibility-spec)
20641 (assq 'org-link buffer-invisibility-spec))
20642 (while (setq b (text-property-any 0 (length s)
20643 'invisible 'org-link s))
20644 (setq s (concat (substring s 0 b)
20645 (substring s (or (next-single-property-change
20646 b 'invisible s) (length s)))))))
20647 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20648 (setq s (concat (substring s 0 b)
20649 (substring s (or (next-single-property-change
20650 b 'org-cwidth s) (length s))))))
20651 (setq l (string-width s) b -1)
20652 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20653 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20656 (defun org-shorten-string (s maxlength)
20657 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20658 If the string is shorter or has length MAXLENGTH, just return the
20659 original string. If it is longer, the functions finds a space in the
20660 string, breaks this string off at that locations and adds three dots
20661 as ellipsis. Including the ellipsis, the string will not be longer
20662 than MAXLENGTH. If finding a good breaking point in the string does
20663 not work, the string is just chopped off in the middle of a word
20664 if necessary."
20665 (if (<= (length s) maxlength)
20667 (let* ((n (max (- maxlength 4) 1))
20668 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20669 (if (string-match re s)
20670 (concat (match-string 1 s) "...")
20671 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20673 (defun org-get-indentation (&optional line)
20674 "Get the indentation of the current line, interpreting tabs.
20675 When LINE is given, assume it represents a line and compute its indentation."
20676 (if line
20677 (if (string-match "^ *" (org-remove-tabs line))
20678 (match-end 0))
20679 (save-excursion
20680 (beginning-of-line 1)
20681 (skip-chars-forward " \t")
20682 (current-column))))
20684 (defun org-get-string-indentation (s)
20685 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20686 (let ((n -1) (i 0) (w tab-width) c)
20687 (catch 'exit
20688 (while (< (setq n (1+ n)) (length s))
20689 (setq c (aref s n))
20690 (cond ((= c ?\ ) (setq i (1+ i)))
20691 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20692 (t (throw 'exit t)))))
20695 (defun org-remove-tabs (s &optional width)
20696 "Replace tabulators in S with spaces.
20697 Assumes that s is a single line, starting in column 0."
20698 (setq width (or width tab-width))
20699 (while (string-match "\t" s)
20700 (setq s (replace-match
20701 (make-string
20702 (- (* width (/ (+ (match-beginning 0) width) width))
20703 (match-beginning 0)) ?\ )
20704 t t s)))
20707 (defun org-fix-indentation (line ind)
20708 "Fix indentation in LINE.
20709 IND is a cons cell with target and minimum indentation.
20710 If the current indentation in LINE is smaller than the minimum,
20711 leave it alone. If it is larger than ind, set it to the target."
20712 (let* ((l (org-remove-tabs line))
20713 (i (org-get-indentation l))
20714 (i1 (car ind)) (i2 (cdr ind)))
20715 (if (>= i i2) (setq l (substring line i2)))
20716 (if (> i1 0)
20717 (concat (make-string i1 ?\ ) l)
20718 l)))
20720 (defun org-remove-indentation (code &optional n)
20721 "Remove the maximum common indentation from the lines in CODE.
20722 N may optionally be the number of spaces to remove."
20723 (with-temp-buffer
20724 (insert code)
20725 (org-do-remove-indentation n)
20726 (buffer-string)))
20728 (defun org-do-remove-indentation (&optional n)
20729 "Remove the maximum common indentation from the buffer."
20730 (untabify (point-min) (point-max))
20731 (let ((min 10000) re)
20732 (if n
20733 (setq min n)
20734 (goto-char (point-min))
20735 (while (re-search-forward "^ *[^ \n]" nil t)
20736 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20737 (unless (or (= min 0) (= min 10000))
20738 (setq re (format "^ \\{%d\\}" min))
20739 (goto-char (point-min))
20740 (while (re-search-forward re nil t)
20741 (replace-match "")
20742 (end-of-line 1))
20743 min)))
20745 (defun org-fill-template (template alist)
20746 "Find each %key of ALIST in TEMPLATE and replace it."
20747 (let ((case-fold-search nil)
20748 entry key value)
20749 (setq alist (sort (copy-sequence alist)
20750 (lambda (a b) (< (length (car a)) (length (car b))))))
20751 (while (setq entry (pop alist))
20752 (setq template
20753 (replace-regexp-in-string
20754 (concat "%" (regexp-quote (car entry)))
20755 (or (cdr entry) "") template t t)))
20756 template))
20758 (defun org-base-buffer (buffer)
20759 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20760 (if (not buffer)
20761 buffer
20762 (or (buffer-base-buffer buffer)
20763 buffer)))
20765 (defun org-trim (s)
20766 "Remove whitespace at beginning and end of string."
20767 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20768 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20771 (defun org-wrap (string &optional width lines)
20772 "Wrap string to either a number of lines, or a width in characters.
20773 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20774 that costs. If there is a word longer than WIDTH, the text is actually
20775 wrapped to the length of that word.
20776 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20777 many lines, whatever width that takes.
20778 The return value is a list of lines, without newlines at the end."
20779 (let* ((words (org-split-string string "[ \t\n]+"))
20780 (maxword (apply 'max (mapcar 'org-string-width words)))
20781 w ll)
20782 (cond (width
20783 (org-do-wrap words (max maxword width)))
20784 (lines
20785 (setq w maxword)
20786 (setq ll (org-do-wrap words maxword))
20787 (if (<= (length ll) lines)
20789 (setq ll words)
20790 (while (> (length ll) lines)
20791 (setq w (1+ w))
20792 (setq ll (org-do-wrap words w)))
20793 ll))
20794 (t (error "Cannot wrap this")))))
20796 (defun org-do-wrap (words width)
20797 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20798 (let (lines line)
20799 (while words
20800 (setq line (pop words))
20801 (while (and words (< (+ (length line) (length (car words))) width))
20802 (setq line (concat line " " (pop words))))
20803 (setq lines (push line lines)))
20804 (nreverse lines)))
20806 (defun org-split-string (string &optional separators)
20807 "Splits STRING into substrings at SEPARATORS.
20808 No empty strings are returned if there are matches at the beginning
20809 and end of string."
20810 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20811 (start 0)
20812 notfirst
20813 (list nil))
20814 (while (and (string-match rexp string
20815 (if (and notfirst
20816 (= start (match-beginning 0))
20817 (< start (length string)))
20818 (1+ start) start))
20819 (< (match-beginning 0) (length string)))
20820 (setq notfirst t)
20821 (or (eq (match-beginning 0) 0)
20822 (and (eq (match-beginning 0) (match-end 0))
20823 (eq (match-beginning 0) start))
20824 (setq list
20825 (cons (substring string start (match-beginning 0))
20826 list)))
20827 (setq start (match-end 0)))
20828 (or (eq start (length string))
20829 (setq list
20830 (cons (substring string start)
20831 list)))
20832 (nreverse list)))
20834 (defun org-quote-vert (s)
20835 "Replace \"|\" with \"\\vert\"."
20836 (while (string-match "|" s)
20837 (setq s (replace-match "\\vert" t t s)))
20840 (defun org-uuidgen-p (s)
20841 "Is S an ID created by UUIDGEN?"
20842 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20844 (defun org-in-src-block-p (&optional inside)
20845 "Whether point is in a code source block.
20846 When INSIDE is non-nil, don't consider we are within a src block
20847 when point is at #+BEGIN_SRC or #+END_SRC."
20848 (let ((case-fold-search t) ov)
20849 (or (and (setq ov (overlays-at (point)))
20850 (memq 'org-block-background
20851 (overlay-properties (car ov))))
20852 (and (not inside)
20853 (save-match-data
20854 (save-excursion
20855 (beginning-of-line)
20856 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20858 (defun org-context ()
20859 "Return a list of contexts of the current cursor position.
20860 If several contexts apply, all are returned.
20861 Each context entry is a list with a symbol naming the context, and
20862 two positions indicating start and end of the context. Possible
20863 contexts are:
20865 :headline anywhere in a headline
20866 :headline-stars on the leading stars in a headline
20867 :todo-keyword on a TODO keyword (including DONE) in a headline
20868 :tags on the TAGS in a headline
20869 :priority on the priority cookie in a headline
20870 :item on the first line of a plain list item
20871 :item-bullet on the bullet/number of a plain list item
20872 :checkbox on the checkbox in a plain list item
20873 :table in an org-mode table
20874 :table-special on a special filed in a table
20875 :table-table in a table.el table
20876 :clocktable in a clocktable
20877 :src-block in a source block
20878 :link on a hyperlink
20879 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20880 :target on a <<target>>
20881 :radio-target on a <<<radio-target>>>
20882 :latex-fragment on a LaTeX fragment
20883 :latex-preview on a LaTeX fragment with overlaid preview image
20885 This function expects the position to be visible because it uses font-lock
20886 faces as a help to recognize the following contexts: :table-special, :link,
20887 and :keyword."
20888 (let* ((f (get-text-property (point) 'face))
20889 (faces (if (listp f) f (list f)))
20890 (case-fold-search t)
20891 (p (point)) clist o)
20892 ;; First the large context
20893 (cond
20894 ((org-at-heading-p t)
20895 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20896 (when (progn
20897 (beginning-of-line 1)
20898 (looking-at org-todo-line-tags-regexp))
20899 (push (org-point-in-group p 1 :headline-stars) clist)
20900 (push (org-point-in-group p 2 :todo-keyword) clist)
20901 (push (org-point-in-group p 4 :tags) clist))
20902 (goto-char p)
20903 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20904 (if (looking-at "\\[#[A-Z0-9]\\]")
20905 (push (org-point-in-group p 0 :priority) clist)))
20907 ((org-at-item-p)
20908 (push (org-point-in-group p 2 :item-bullet) clist)
20909 (push (list :item (point-at-bol)
20910 (save-excursion (org-end-of-item) (point)))
20911 clist)
20912 (and (org-at-item-checkbox-p)
20913 (push (org-point-in-group p 0 :checkbox) clist)))
20915 ((org-at-table-p)
20916 (push (list :table (org-table-begin) (org-table-end)) clist)
20917 (if (memq 'org-formula faces)
20918 (push (list :table-special
20919 (previous-single-property-change p 'face)
20920 (next-single-property-change p 'face)) clist)))
20921 ((org-at-table-p 'any)
20922 (push (list :table-table) clist)))
20923 (goto-char p)
20925 (let ((case-fold-search t))
20926 ;; New the "medium" contexts: clocktables, source blocks
20927 (cond ((org-in-clocktable-p)
20928 (push (list :clocktable
20929 (and (or (looking-at "#\\+BEGIN: clocktable")
20930 (search-backward "#+BEGIN: clocktable" nil t))
20931 (match-beginning 0))
20932 (and (re-search-forward "#\\+END:?" nil t)
20933 (match-end 0))) clist))
20934 ((org-in-src-block-p)
20935 (push (list :src-block
20936 (and (or (looking-at "#\\+BEGIN_SRC")
20937 (search-backward "#+BEGIN_SRC" nil t))
20938 (match-beginning 0))
20939 (and (search-forward "#+END_SRC" nil t)
20940 (match-beginning 0))) clist))))
20941 (goto-char p)
20943 ;; Now the small context
20944 (cond
20945 ((org-at-timestamp-p)
20946 (push (org-point-in-group p 0 :timestamp) clist))
20947 ((memq 'org-link faces)
20948 (push (list :link
20949 (previous-single-property-change p 'face)
20950 (next-single-property-change p 'face)) clist))
20951 ((memq 'org-special-keyword faces)
20952 (push (list :keyword
20953 (previous-single-property-change p 'face)
20954 (next-single-property-change p 'face)) clist))
20955 ((org-at-target-p)
20956 (push (org-point-in-group p 0 :target) clist)
20957 (goto-char (1- (match-beginning 0)))
20958 (if (looking-at org-radio-target-regexp)
20959 (push (org-point-in-group p 0 :radio-target) clist))
20960 (goto-char p))
20961 ((setq o (car (delq nil
20962 (mapcar
20963 (lambda (x)
20964 (if (memq x org-latex-fragment-image-overlays) x))
20965 (overlays-at (point))))))
20966 (push (list :latex-fragment
20967 (overlay-start o) (overlay-end o)) clist)
20968 (push (list :latex-preview
20969 (overlay-start o) (overlay-end o)) clist))
20970 ((org-inside-LaTeX-fragment-p)
20971 ;; FIXME: positions wrong.
20972 (push (list :latex-fragment (point) (point)) clist)))
20974 (setq clist (nreverse (delq nil clist)))
20975 clist))
20977 ;; FIXME: Compare with at-regexp-p Do we need both?
20978 (defun org-in-regexp (re &optional nlines visually)
20979 "Check if point is inside a match of regexp.
20980 Normally only the current line is checked, but you can include NLINES extra
20981 lines both before and after point into the search.
20982 If VISUALLY is set, require that the cursor is not after the match but
20983 really on, so that the block visually is on the match."
20984 (catch 'exit
20985 (let ((pos (point))
20986 (eol (point-at-eol (+ 1 (or nlines 0))))
20987 (inc (if visually 1 0)))
20988 (save-excursion
20989 (beginning-of-line (- 1 (or nlines 0)))
20990 (while (re-search-forward re eol t)
20991 (if (and (<= (match-beginning 0) pos)
20992 (>= (+ inc (match-end 0)) pos))
20993 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20995 (defun org-at-regexp-p (regexp)
20996 "Is point inside a match of REGEXP in the current line?"
20997 (catch 'exit
20998 (save-excursion
20999 (let ((pos (point)) (end (point-at-eol)))
21000 (beginning-of-line 1)
21001 (while (re-search-forward regexp end t)
21002 (if (and (<= (match-beginning 0) pos)
21003 (>= (match-end 0) pos))
21004 (throw 'exit t)))
21005 nil))))
21007 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21008 "Non-nil when point is between matches of START-RE and END-RE.
21010 Also return a non-nil value when point is on one of the matches.
21012 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21013 buffer positions. Default values are the positions of headlines
21014 surrounding the point.
21016 The functions returns a cons cell whose car (resp. cdr) is the
21017 position before START-RE (resp. after END-RE)."
21018 (save-match-data
21019 (let ((pos (point))
21020 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21021 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21022 beg end)
21023 (save-excursion
21024 ;; Point is on a block when on START-RE or if START-RE can be
21025 ;; found before it...
21026 (and (or (org-at-regexp-p start-re)
21027 (re-search-backward start-re limit-up t))
21028 (setq beg (match-beginning 0))
21029 ;; ... and END-RE after it...
21030 (goto-char (match-end 0))
21031 (re-search-forward end-re limit-down t)
21032 (> (setq end (match-end 0)) pos)
21033 ;; ... without another START-RE in-between.
21034 (goto-char (match-beginning 0))
21035 (not (re-search-backward start-re (1+ beg) t))
21036 ;; Return value.
21037 (cons beg end))))))
21039 (defun org-in-block-p (names)
21040 "Non-nil when point belongs to a block whose name belongs to NAMES.
21042 NAMES is a list of strings containing names of blocks.
21044 Return first block name matched, or nil. Beware that in case of
21045 nested blocks, the returned name may not belong to the closest
21046 block from point."
21047 (save-match-data
21048 (catch 'exit
21049 (let ((case-fold-search t)
21050 (lim-up (save-excursion (outline-previous-heading)))
21051 (lim-down (save-excursion (outline-next-heading))))
21052 (mapc (lambda (name)
21053 (let ((n (regexp-quote name)))
21054 (when (org-between-regexps-p
21055 (concat "^[ \t]*#\\+begin_" n)
21056 (concat "^[ \t]*#\\+end_" n)
21057 lim-up lim-down)
21058 (throw 'exit n))))
21059 names))
21060 nil)))
21062 (defun org-occur-in-agenda-files (regexp &optional nlines)
21063 "Call `multi-occur' with buffers for all agenda files."
21064 (interactive "sOrg-files matching: \np")
21065 (let* ((files (org-agenda-files))
21066 (tnames (mapcar 'file-truename files))
21067 (extra org-agenda-text-search-extra-files)
21069 (when (eq (car extra) 'agenda-archives)
21070 (setq extra (cdr extra))
21071 (setq files (org-add-archive-files files)))
21072 (while (setq f (pop extra))
21073 (unless (member (file-truename f) tnames)
21074 (add-to-list 'files f 'append)
21075 (add-to-list 'tnames (file-truename f) 'append)))
21076 (multi-occur
21077 (mapcar (lambda (x)
21078 (with-current-buffer
21079 (or (get-file-buffer x) (find-file-noselect x))
21080 (widen)
21081 (current-buffer)))
21082 files)
21083 regexp)))
21085 (if (boundp 'occur-mode-find-occurrence-hook)
21086 ;; Emacs 23
21087 (add-hook 'occur-mode-find-occurrence-hook
21088 (lambda ()
21089 (when (derived-mode-p 'org-mode)
21090 (org-reveal))))
21091 ;; Emacs 22
21092 (defadvice occur-mode-goto-occurrence
21093 (after org-occur-reveal activate)
21094 (and (derived-mode-p 'org-mode) (org-reveal)))
21095 (defadvice occur-mode-goto-occurrence-other-window
21096 (after org-occur-reveal activate)
21097 (and (derived-mode-p 'org-mode) (org-reveal)))
21098 (defadvice occur-mode-display-occurrence
21099 (after org-occur-reveal activate)
21100 (when (derived-mode-p 'org-mode)
21101 (let ((pos (occur-mode-find-occurrence)))
21102 (with-current-buffer (marker-buffer pos)
21103 (save-excursion
21104 (goto-char pos)
21105 (org-reveal)))))))
21107 (defun org-occur-link-in-agenda-files ()
21108 "Create a link and search for it in the agendas.
21109 The link is not stored in `org-stored-links', it is just created
21110 for the search purpose."
21111 (interactive)
21112 (let ((link (condition-case nil
21113 (org-store-link nil)
21114 (error "Unable to create a link to here"))))
21115 (org-occur-in-agenda-files (regexp-quote link))))
21117 (defun org-uniquify (list)
21118 "Remove duplicate elements from LIST."
21119 (let (res)
21120 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21121 res))
21123 (defun org-delete-all (elts list)
21124 "Remove all elements in ELTS from LIST."
21125 (while elts
21126 (setq list (delete (pop elts) list)))
21127 list)
21129 (defun org-count (cl-item cl-seq)
21130 "Count the number of occurrences of ITEM in SEQ.
21131 Taken from `count' in cl-seq.el with all keyword arguments removed."
21132 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21133 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21134 (while (< cl-start cl-end)
21135 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21136 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21137 (setq cl-start (1+ cl-start)))
21138 cl-count))
21140 (defun org-remove-if (predicate seq)
21141 "Remove everything from SEQ that fulfills PREDICATE."
21142 (let (res e)
21143 (while seq
21144 (setq e (pop seq))
21145 (if (not (funcall predicate e)) (push e res)))
21146 (nreverse res)))
21148 (defun org-remove-if-not (predicate seq)
21149 "Remove everything from SEQ that does not fulfill PREDICATE."
21150 (let (res e)
21151 (while seq
21152 (setq e (pop seq))
21153 (if (funcall predicate e) (push e res)))
21154 (nreverse res)))
21156 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21157 "Reduce two-argument FUNCTION across SEQ.
21158 Taken from `reduce' in cl-seq.el with all keyword arguments but
21159 \":initial-value\" removed."
21160 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21161 (cadr (memq :initial-value cl-keys)))
21162 (cl-seq (pop cl-seq))
21163 (t (funcall cl-func)))))
21164 (while cl-seq
21165 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21166 cl-accum))
21168 (defun org-back-over-empty-lines ()
21169 "Move backwards over whitespace, to the beginning of the first empty line.
21170 Returns the number of empty lines passed."
21171 (let ((pos (point)))
21172 (if (cdr (assoc 'heading org-blank-before-new-entry))
21173 (skip-chars-backward " \t\n\r")
21174 (unless (eobp)
21175 (forward-line -1)))
21176 (beginning-of-line 2)
21177 (goto-char (min (point) pos))
21178 (count-lines (point) pos)))
21180 (defun org-skip-whitespace ()
21181 (skip-chars-forward " \t\n\r"))
21183 (defun org-point-in-group (point group &optional context)
21184 "Check if POINT is in match-group GROUP.
21185 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21186 match. If the match group does not exist or point is not inside it,
21187 return nil."
21188 (and (match-beginning group)
21189 (>= point (match-beginning group))
21190 (<= point (match-end group))
21191 (if context
21192 (list context (match-beginning group) (match-end group))
21193 t)))
21195 (defun org-switch-to-buffer-other-window (&rest args)
21196 "Switch to buffer in a second window on the current frame.
21197 In particular, do not allow pop-up frames.
21198 Returns the newly created buffer."
21199 (org-no-popups
21200 (apply 'switch-to-buffer-other-window args)))
21202 (defun org-combine-plists (&rest plists)
21203 "Create a single property list from all plists in PLISTS.
21204 The process starts by copying the first list, and then setting properties
21205 from the other lists. Settings in the last list are the most significant
21206 ones and overrule settings in the other lists."
21207 (let ((rtn (copy-sequence (pop plists)))
21208 p v ls)
21209 (while plists
21210 (setq ls (pop plists))
21211 (while ls
21212 (setq p (pop ls) v (pop ls))
21213 (setq rtn (plist-put rtn p v))))
21214 rtn))
21216 (defun org-replace-escapes (string table)
21217 "Replace %-escapes in STRING with values in TABLE.
21218 TABLE is an association list with keys like \"%a\" and string values.
21219 The sequences in STRING may contain normal field width and padding information,
21220 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21221 so values can contain further %-escapes if they are define later in TABLE."
21222 (let ((tbl (copy-alist table))
21223 (case-fold-search nil)
21224 (pchg 0)
21225 e re rpl)
21226 (while (setq e (pop tbl))
21227 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21228 (when (and (cdr e) (string-match re (cdr e)))
21229 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21230 (safe "SREF"))
21231 (add-text-properties 0 3 (list 'sref sref) safe)
21232 (setcdr e (replace-match safe t t (cdr e)))))
21233 (while (string-match re string)
21234 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21235 (cdr e)))
21236 (setq string (replace-match rpl t t string))))
21237 (while (setq pchg (next-property-change pchg string))
21238 (let ((sref (get-text-property pchg 'sref string)))
21239 (when (and sref (string-match "SREF" string pchg))
21240 (setq string (replace-match sref t t string)))))
21241 string))
21243 (defun org-sublist (list start end)
21244 "Return a section of LIST, from START to END.
21245 Counting starts at 1."
21246 (let (rtn (c start))
21247 (setq list (nthcdr (1- start) list))
21248 (while (and list (<= c end))
21249 (push (pop list) rtn)
21250 (setq c (1+ c)))
21251 (nreverse rtn)))
21253 (defun org-find-base-buffer-visiting (file)
21254 "Like `find-buffer-visiting' but always return the base buffer and
21255 not an indirect buffer."
21256 (let ((buf (or (get-file-buffer file)
21257 (find-buffer-visiting file))))
21258 (if buf
21259 (or (buffer-base-buffer buf) buf)
21260 nil)))
21262 (defun org-image-file-name-regexp (&optional extensions)
21263 "Return regexp matching the file names of images.
21264 If EXTENSIONS is given, only match these."
21265 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21266 (image-file-name-regexp)
21267 (let ((image-file-name-extensions
21268 (or extensions
21269 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21270 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21271 (concat "\\."
21272 (regexp-opt (nconc (mapcar 'upcase
21273 image-file-name-extensions)
21274 image-file-name-extensions)
21276 "\\'"))))
21278 (defun org-file-image-p (file &optional extensions)
21279 "Return non-nil if FILE is an image."
21280 (save-match-data
21281 (string-match (org-image-file-name-regexp extensions) file)))
21283 (defun org-get-cursor-date (&optional with-time)
21284 "Return the date at cursor in as a time.
21285 This works in the calendar and in the agenda, anywhere else it just
21286 returns the current time.
21287 If WITH-TIME is non-nil, returns the time of the event at point (in
21288 the agenda) or the current time of the day."
21289 (let (date day defd tp tm hod mod)
21290 (when with-time
21291 (setq tp (get-text-property (point) 'time))
21292 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21293 (setq hod (string-to-number (match-string 1 tp))
21294 mod (string-to-number (match-string 2 tp))))
21295 (or tp (setq hod (nth 2 (decode-time (current-time)))
21296 mod (nth 1 (decode-time (current-time))))))
21297 (cond
21298 ((eq major-mode 'calendar-mode)
21299 (setq date (calendar-cursor-to-date)
21300 defd (encode-time 0 (or mod 0) (or hod 0)
21301 (nth 1 date) (nth 0 date) (nth 2 date))))
21302 ((eq major-mode 'org-agenda-mode)
21303 (setq day (get-text-property (point) 'day))
21304 (if day
21305 (setq date (calendar-gregorian-from-absolute day)
21306 defd (encode-time 0 (or mod 0) (or hod 0)
21307 (nth 1 date) (nth 0 date) (nth 2 date))))))
21308 (or defd (current-time))))
21310 (defun org-mark-subtree (&optional up)
21311 "Mark the current subtree.
21312 This puts point at the start of the current subtree, and mark at
21313 the end. If a numeric prefix UP is given, move up into the
21314 hierarchy of headlines by UP levels before marking the subtree."
21315 (interactive "P")
21316 (org-with-limited-levels
21317 (cond ((org-at-heading-p) (beginning-of-line))
21318 ((org-before-first-heading-p) (error "Not in a subtree"))
21319 (t (outline-previous-visible-heading 1))))
21320 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21321 (if (org-called-interactively-p 'any)
21322 (call-interactively 'org-mark-element)
21323 (org-mark-element)))
21326 ;;; Macros
21328 ;; Macros are expanded with `org-macro-replace-all', which relies
21329 ;; internally on `org-macro-expand'.
21331 ;; Default templates for expansion are stored in the buffer-local
21332 ;; variable `org-macro-templates'. This variable is updated by
21333 ;; `org-macro-initialize-templates'.
21335 ;; Along with macros defined through #+MACRO: keyword, default
21336 ;; templates include the following hard-coded macros:
21337 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21338 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21340 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21341 ;; {{{title}}} will also be provided.
21344 (defvar org-macro-templates nil
21345 "Alist containing all macro templates in current buffer.
21346 Associations are in the shape of (NAME . TEMPLATE) where NAME
21347 stands for macro's name and template for its replacement value,
21348 both as strings. This is an internal variable. Do not set it
21349 directly, use instead:
21351 #+MACRO: name template")
21352 (make-variable-buffer-local 'org-macro-templates)
21354 (defun org-macro-expand (macro templates)
21355 "Return expanded MACRO, as a string.
21356 MACRO is an object, obtained, for example, with
21357 `org-element-context'. TEMPLATES is an alist of templates used
21358 for expansion. See `org-macro-templates' for a buffer-local
21359 default value. Return nil if no template was found."
21360 (let ((template
21361 ;; Macro names are case-insensitive.
21362 (cdr (assoc-string (org-element-property :key macro) templates t))))
21363 (when template
21364 (let ((value (replace-regexp-in-string
21365 "\\$[0-9]+"
21366 (lambda (arg)
21367 (or (nth (1- (string-to-number (substring arg 1)))
21368 (org-element-property :args macro))
21369 ;; No argument provided: remove
21370 ;; place-holder.
21371 ""))
21372 template)))
21373 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21374 (when (string-match "\\`(eval\\>" value)
21375 (setq value (eval (read value))))
21376 ;; Return string.
21377 (format "%s" (or value ""))))))
21379 (defun org-macro-replace-all (templates)
21380 "Replace all macros in current buffer by their expansion.
21381 TEMPLATES is an alist of templates used for expansion. See
21382 `org-macro-templates' for a buffer-local default value."
21383 (save-excursion
21384 (goto-char (point-min))
21385 (let (record)
21386 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21387 (let ((object (org-element-context)))
21388 (when (eq (org-element-type object) 'macro)
21389 (let* ((value (org-macro-expand object templates))
21390 (begin (org-element-property :begin object))
21391 (signature (list begin
21392 object
21393 (org-element-property :args object))))
21394 ;; Avoid circular dependencies by checking if the same
21395 ;; macro with the same arguments is expanded at the same
21396 ;; position twice.
21397 (if (member signature record)
21398 (error "Circular macro expansion: %s"
21399 (org-element-property :key object))
21400 (when value
21401 (push signature record)
21402 (delete-region
21403 begin
21404 ;; Preserve white spaces after the macro.
21405 (progn (goto-char (org-element-property :end object))
21406 (skip-chars-backward " \t")
21407 (point)))
21408 ;; Leave point before replacement in case of recursive
21409 ;; expansions.
21410 (save-excursion (insert value)))))))))))
21412 (defun org-macro-initialize-templates ()
21413 "Collect macro templates defined in current buffer.
21414 Templates are stored in buffer-local variable
21415 `org-macro-templates'. In addition to buffer-defined macros, the
21416 function installs the following ones: \"property\",
21417 \"time\". and, if the buffer is associated to a file,
21418 \"input-file\" and \"modification-time\"."
21419 (let ((case-fold-search t)
21420 (set-template
21421 (lambda (cell)
21422 ;; Add CELL to `org-macro-templates' if there's no
21423 ;; association matching its name already. Otherwise,
21424 ;; replace old association with the new one in that
21425 ;; variable.
21426 (let ((old-template (assoc (car cell) org-macro-templates)))
21427 (if old-template (setcdr old-template (cdr cell))
21428 (push cell org-macro-templates))))))
21429 ;; Install buffer-local macros.
21430 (org-with-wide-buffer
21431 (goto-char (point-min))
21432 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21433 (let ((element (org-element-at-point)))
21434 (when (eq (org-element-type element) 'keyword)
21435 (let ((value (org-element-property :value element)))
21436 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21437 (funcall set-template
21438 (cons (match-string 1 value)
21439 (or (match-string 2 value) "")))))))))
21440 ;; Install hard-coded macros.
21441 (mapc (lambda (cell) (funcall set-template cell))
21442 (list
21443 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21444 (cons "time" "(eval (format-time-string \"$1\"))")))
21445 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21446 (when (and visited-file (file-exists-p visited-file))
21447 (mapc (lambda (cell) (funcall set-template cell))
21448 (list
21449 (cons "input-file" (file-name-nondirectory visited-file))
21450 (cons "modification-time"
21451 (format "(eval (format-time-string \"$1\" '%s))"
21452 (prin1-to-string
21453 (nth 5 (file-attributes visited-file)))))))))))
21456 ;;; Indentation
21458 (defun org-indent-line ()
21459 "Indent line depending on context."
21460 (interactive)
21461 (let* ((pos (point))
21462 (itemp (org-at-item-p))
21463 (case-fold-search t)
21464 (org-drawer-regexp (or org-drawer-regexp "\000"))
21465 (inline-task-p (and (featurep 'org-inlinetask)
21466 (org-inlinetask-in-task-p)))
21467 (inline-re (and inline-task-p
21468 (org-inlinetask-outline-regexp)))
21469 column)
21470 (if (and orgstruct-is-++ (eq pos (point)))
21471 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21472 (indent-according-to-mode))
21473 (beginning-of-line 1)
21474 (cond
21475 ;; Headings
21476 ((looking-at org-outline-regexp) (setq column 0))
21477 ;; Footnote definition
21478 ((looking-at org-footnote-definition-re) (setq column 0))
21479 ;; Literal examples
21480 ((looking-at "[ \t]*:\\( \\|$\\)")
21481 (setq column (org-get-indentation))) ; do nothing
21482 ;; Lists
21483 ((ignore-errors (goto-char (org-in-item-p)))
21484 (setq column (if itemp
21485 (org-get-indentation)
21486 (org-list-item-body-column (point))))
21487 (goto-char pos))
21488 ;; Drawers
21489 ((and (looking-at "[ \t]*:END:")
21490 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21491 (save-excursion
21492 (goto-char (1- (match-beginning 1)))
21493 (setq column (current-column))))
21494 ;; Special blocks
21495 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21496 (save-excursion
21497 (re-search-backward
21498 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21499 (setq column (org-get-indentation (match-string 0))))
21500 ((and (not (looking-at "[ \t]*#\\+begin_"))
21501 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21502 (save-excursion
21503 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21504 (setq column
21505 (cond ((equal (downcase (match-string 1)) "src")
21506 ;; src blocks: let `org-edit-src-exit' handle them
21507 (org-get-indentation))
21508 ((equal (downcase (match-string 1)) "example")
21509 (max (org-get-indentation)
21510 (org-get-indentation (match-string 0))))
21512 (org-get-indentation (match-string 0))))))
21513 ;; This line has nothing special, look at the previous relevant
21514 ;; line to compute indentation
21516 (beginning-of-line 0)
21517 (while (and (not (bobp))
21518 (not (looking-at org-table-line-regexp))
21519 (not (looking-at org-drawer-regexp))
21520 ;; When point started in an inline task, do not move
21521 ;; above task starting line.
21522 (not (and inline-task-p (looking-at inline-re)))
21523 ;; Skip drawers, blocks, empty lines, verbatim,
21524 ;; comments, tables, footnotes definitions, lists,
21525 ;; inline tasks.
21526 (or (and (looking-at "[ \t]*:END:")
21527 (re-search-backward org-drawer-regexp nil t))
21528 (and (looking-at "[ \t]*#\\+end_")
21529 (re-search-backward "[ \t]*#\\+begin_"nil t))
21530 (looking-at "[ \t]*[\n:#|]")
21531 (looking-at org-footnote-definition-re)
21532 (and (ignore-errors (goto-char (org-in-item-p)))
21533 (goto-char
21534 (org-list-get-top-point (org-list-struct))))
21535 (and (not inline-task-p)
21536 (featurep 'org-inlinetask)
21537 (org-inlinetask-in-task-p)
21538 (or (org-inlinetask-goto-beginning) t))))
21539 (beginning-of-line 0))
21540 (cond
21541 ;; There was an heading above.
21542 ((looking-at "\\*+[ \t]+")
21543 (if (not org-adapt-indentation)
21544 (setq column 0)
21545 (goto-char (match-end 0))
21546 (setq column (current-column))))
21547 ;; A drawer had started and is unfinished
21548 ((looking-at org-drawer-regexp)
21549 (goto-char (1- (match-beginning 1)))
21550 (setq column (current-column)))
21551 ;; Else, nothing noticeable found: get indentation and go on.
21552 (t (setq column (org-get-indentation))))))
21553 ;; Now apply indentation and move cursor accordingly
21554 (goto-char pos)
21555 (if (<= (current-column) (current-indentation))
21556 (org-indent-line-to column)
21557 (save-excursion (org-indent-line-to column)))
21558 ;; Special polishing for properties, see `org-property-format'
21559 (setq column (current-column))
21560 (beginning-of-line 1)
21561 (if (looking-at
21562 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21563 (replace-match (concat (match-string 1)
21564 (format org-property-format
21565 (match-string 2) (match-string 3)))
21566 t t))
21567 (org-move-to-column column))))
21569 (defun org-indent-drawer ()
21570 "Indent the drawer at point."
21571 (interactive)
21572 (let ((p (point))
21573 (e (and (save-excursion (re-search-forward ":END:" nil t))
21574 (match-end 0)))
21575 (folded
21576 (save-excursion
21577 (end-of-line)
21578 (when (overlays-at (point))
21579 (member 'invisible (overlay-properties
21580 (car (overlays-at (point)))))))))
21581 (when folded (org-cycle))
21582 (indent-for-tab-command)
21583 (while (and (move-beginning-of-line 2) (< (point) e))
21584 (indent-for-tab-command))
21585 (goto-char p)
21586 (when folded (org-cycle)))
21587 (message "Drawer at point indented"))
21589 (defun org-indent-block ()
21590 "Indent the block at point."
21591 (interactive)
21592 (let ((p (point))
21593 (case-fold-search t)
21594 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21595 (match-end 0)))
21596 (folded
21597 (save-excursion
21598 (end-of-line)
21599 (when (overlays-at (point))
21600 (member 'invisible (overlay-properties
21601 (car (overlays-at (point)))))))))
21602 (when folded (org-cycle))
21603 (indent-for-tab-command)
21604 (while (and (move-beginning-of-line 2) (< (point) e))
21605 (indent-for-tab-command))
21606 (goto-char p)
21607 (when folded (org-cycle)))
21608 (message "Block at point indented"))
21610 (defun org-indent-region (start end)
21611 "Indent region."
21612 (interactive "r")
21613 (save-excursion
21614 (let ((line-end (org-current-line end)))
21615 (goto-char start)
21616 (while (< (org-current-line) line-end)
21617 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21618 (t (call-interactively 'org-indent-line)))
21619 (move-beginning-of-line 2)))))
21622 ;;; Filling
21624 ;; We use our own fill-paragraph and auto-fill functions.
21626 ;; `org-fill-paragraph' relies on adaptive filling and context
21627 ;; checking. Appropriate `fill-prefix' is computed with
21628 ;; `org-adaptive-fill-function'.
21630 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21631 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21632 ;; `org-adaptive-fill-function' value. Internally,
21633 ;; `org-comment-line-break-function' breaks the line.
21635 ;; `org-setup-filling' installs filling and auto-filling related
21636 ;; variables during `org-mode' initialization.
21638 (defun org-setup-filling ()
21639 (interactive)
21640 ;; Prevent auto-fill from inserting unwanted new items.
21641 (when (boundp 'fill-nobreak-predicate)
21642 (org-set-local
21643 'fill-nobreak-predicate
21644 (org-uniquify
21645 (append fill-nobreak-predicate
21646 '(org-fill-paragraph-separate-nobreak-p
21647 org-fill-line-break-nobreak-p
21648 org-fill-paragraph-with-timestamp-nobreak-p)))))
21649 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21650 (org-set-local 'auto-fill-inhibit-regexp nil)
21651 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21652 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21653 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21655 (defvar org-element-paragraph-separate) ; org-element.el
21656 (defun org-fill-paragraph-separate-nobreak-p ()
21657 "Non-nil when a line break at point would insert a new item."
21658 (looking-at (substring org-element-paragraph-separate 1)))
21660 (defun org-fill-line-break-nobreak-p ()
21661 "Non-nil when a line break at point would create an Org line break."
21662 (save-excursion
21663 (skip-chars-backward "[ \t]")
21664 (skip-chars-backward "\\\\")
21665 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21667 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21668 "Non-nil when a line break at point would insert a new item."
21669 (and (org-at-timestamp-p t)
21670 (not (looking-at org-ts-regexp-both))))
21672 (declare-function message-in-body-p "message" ())
21673 (defvar orgtbl-line-start-regexp) ; From org-table.el
21674 (defun org-adaptive-fill-function ()
21675 "Compute a fill prefix for the current line.
21676 Return fill prefix, as a string, or nil if current line isn't
21677 meant to be filled."
21678 (let (prefix)
21679 (catch 'exit
21680 (when (derived-mode-p 'message-mode)
21681 (save-excursion
21682 (beginning-of-line)
21683 (cond ((or (not (message-in-body-p))
21684 (looking-at orgtbl-line-start-regexp))
21685 (throw 'exit nil))
21686 ((looking-at message-cite-prefix-regexp)
21687 (throw 'exit (match-string-no-properties 0)))
21688 ((looking-at org-outline-regexp)
21689 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21690 (org-with-wide-buffer
21691 (let* ((p (line-beginning-position))
21692 (element (save-excursion (beginning-of-line)
21693 (org-element-at-point)))
21694 (type (org-element-type element))
21695 (post-affiliated (org-element-property :post-affiliated element)))
21696 (unless (and post-affiliated (< p post-affiliated))
21697 (case type
21698 (comment (looking-at "[ \t]*# ?") (match-string 0))
21699 (footnote-definition "")
21700 ((item plain-list)
21701 (make-string (org-list-item-body-column
21702 (or post-affiliated
21703 (org-element-property :begin element)))
21704 ? ))
21705 (paragraph
21706 ;; Fill prefix is usually the same as the current line,
21707 ;; except if the paragraph is at the beginning of an item.
21708 (let ((parent (org-element-property :parent element)))
21709 (cond ((eq (org-element-type parent) 'item)
21710 (make-string (org-list-item-body-column
21711 (org-element-property :begin parent))
21712 ? ))
21713 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21714 (match-string 0))
21715 (t ""))))
21716 (comment-block
21717 ;; Only fill contents if P is within block boundaries.
21718 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21719 (forward-line)
21720 (point)))
21721 (cend (save-excursion
21722 (goto-char (org-element-property :end element))
21723 (skip-chars-backward " \r\t\n")
21724 (line-beginning-position))))
21725 (when (and (>= p cbeg) (< p cend))
21726 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21727 (match-string 0)
21728 "")))))))))))
21730 (declare-function message-goto-body "message" ())
21731 (defvar message-cite-prefix-regexp) ; From message.el
21732 (defvar org-element-all-objects) ; From org-element.el
21733 (defun org-fill-paragraph (&optional justify)
21734 "Fill element at point, when applicable.
21736 This function only applies to comment blocks, comments, example
21737 blocks and paragraphs. Also, as a special case, re-align table
21738 when point is at one.
21740 If JUSTIFY is non-nil (interactively, with prefix argument),
21741 justify as well. If `sentence-end-double-space' is non-nil, then
21742 period followed by one space does not end a sentence, so don't
21743 break a line there. The variable `fill-column' controls the
21744 width for filling.
21746 For convenience, when point is at a plain list, an item or
21747 a footnote definition, try to fill the first paragraph within."
21748 (interactive)
21749 (if (and (derived-mode-p 'message-mode)
21750 (or (not (message-in-body-p))
21751 (save-excursion (move-beginning-of-line 1)
21752 (looking-at message-cite-prefix-regexp))))
21753 ;; First ensure filling is correct in message-mode.
21754 (let ((fill-paragraph-function
21755 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21756 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21757 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21758 (paragraph-separate
21759 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21760 (fill-paragraph nil))
21761 (save-excursion
21762 ;; Move to end of line in order to get the first paragraph
21763 ;; within a plain list or a footnote definition.
21764 (end-of-line)
21765 (let ((element (org-element-at-point)))
21766 ;; First check if point is in a blank line at the beginning of
21767 ;; the buffer. In that case, ignore filling.
21768 (if (< (point) (org-element-property :begin element)) t
21769 (case (org-element-type element)
21770 ;; Use major mode filling function is src blocks.
21771 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21772 ;; Align Org tables, leave table.el tables as-is.
21773 (table-row (org-table-align) t)
21774 (table
21775 (when (eq (org-element-property :type element) 'org)
21776 (org-table-align))
21778 (paragraph
21779 ;; Paragraphs may contain `line-break' type objects.
21780 (let ((beg (max (point-min)
21781 (org-element-property :contents-begin element)))
21782 (end (min (point-max)
21783 (org-element-property :contents-end element))))
21784 ;; Do nothing if point is at an affiliated keyword.
21785 (if (< (point) beg) t
21786 (when (derived-mode-p 'message-mode)
21787 ;; In `message-mode', do not fill following
21788 ;; citation in current paragraph nor text before
21789 ;; message body.
21790 (let ((body-start (save-excursion (message-goto-body))))
21791 (when body-start (setq beg (max body-start beg))))
21792 (when (save-excursion
21793 (re-search-forward
21794 (concat "^" message-cite-prefix-regexp) end t))
21795 (setq end (match-beginning 0))))
21796 ;; Fill paragraph, taking line breaks into
21797 ;; consideration. For that, slice the paragraph
21798 ;; using line breaks as separators, and fill the
21799 ;; parts in reverse order to avoid messing with
21800 ;; markers.
21801 (save-excursion
21802 (goto-char end)
21803 (mapc
21804 (lambda (pos)
21805 (fill-region-as-paragraph pos (point) justify)
21806 (goto-char pos))
21807 ;; Find the list of ending positions for line
21808 ;; breaks in the current paragraph. Add paragraph
21809 ;; beginning to include first slice.
21810 (nreverse
21811 (cons
21813 (org-element-map
21814 (org-element--parse-objects
21815 beg end nil org-element-all-objects)
21816 'line-break
21817 (lambda (lb) (org-element-property :end lb)))))))
21818 t)))
21819 ;; Contents of `comment-block' type elements should be
21820 ;; filled as plain text, but only if point is within block
21821 ;; markers.
21822 (comment-block
21823 (let* ((case-fold-search t)
21824 (beg (save-excursion
21825 (goto-char (org-element-property :begin element))
21826 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21827 (forward-line)
21828 (point)))
21829 (end (save-excursion
21830 (goto-char (org-element-property :end element))
21831 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21832 (line-beginning-position))))
21833 (when (and (>= (point) beg) (< (point) end))
21834 (fill-region-as-paragraph
21835 (save-excursion
21836 (end-of-line)
21837 (re-search-backward "^[ \t]*$" beg 'move)
21838 (line-beginning-position))
21839 (save-excursion
21840 (beginning-of-line)
21841 (re-search-forward "^[ \t]*$" end 'move)
21842 (line-beginning-position))
21843 justify)))
21845 ;; Fill comments.
21846 (comment (fill-comment-paragraph justify))
21847 ;; Ignore every other element.
21848 (otherwise t)))))))
21850 (defun org-auto-fill-function ()
21851 "Auto-fill function."
21852 ;; Check if auto-filling is meaningful.
21853 (let ((fc (current-fill-column)))
21854 (when (and fc (> (current-column) fc))
21855 (let* ((fill-prefix (org-adaptive-fill-function))
21856 ;; Enforce empty fill prefix, if required. Otherwise, it
21857 ;; will be computed again.
21858 (adaptive-fill-mode (not (equal fill-prefix ""))))
21859 (when fill-prefix (do-auto-fill))))))
21861 (defun org-comment-line-break-function (&optional soft)
21862 "Break line at point and indent, continuing comment if within one.
21863 The inserted newline is marked hard if variable
21864 `use-hard-newlines' is true, unless optional argument SOFT is
21865 non-nil."
21866 (if soft (insert-and-inherit ?\n) (newline 1))
21867 (save-excursion (forward-char -1) (delete-horizontal-space))
21868 (delete-horizontal-space)
21869 (indent-to-left-margin)
21870 (insert-before-markers-and-inherit fill-prefix))
21873 ;;; Comments
21875 ;; Org comments syntax is quite complex. It requires the entire line
21876 ;; to be just a comment. Also, even with the right syntax at the
21877 ;; beginning of line, some some elements (i.e. verse-block or
21878 ;; example-block) don't accept comments. Usual Emacs comment commands
21879 ;; cannot cope with those requirements. Therefore, Org replaces them.
21881 ;; Org still relies on `comment-dwim', but cannot trust
21882 ;; `comment-only-p'. So, `comment-region-function' and
21883 ;; `uncomment-region-function' both point
21884 ;; to`org-comment-or-uncomment-region'. Eventually,
21885 ;; `org-insert-comment' takes care of insertion of comments at the
21886 ;; beginning of line.
21888 ;; `org-setup-comments-handling' install comments related variables
21889 ;; during `org-mode' initialization.
21891 (defun org-setup-comments-handling ()
21892 (interactive)
21893 (org-set-local 'comment-use-syntax nil)
21894 (org-set-local 'comment-start "# ")
21895 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21896 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21897 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21898 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21900 (defun org-insert-comment ()
21901 "Insert an empty comment above current line.
21902 If the line is empty, insert comment at its beginning."
21903 (beginning-of-line)
21904 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21905 (org-indent-line)
21906 (insert "# "))
21908 (defvar comment-empty-lines) ; From newcomment.el.
21909 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21910 "Comment or uncomment each non-blank line in the region.
21911 Uncomment each non-blank line between BEG and END if it only
21912 contains commented lines. Otherwise, comment them."
21913 (save-restriction
21914 ;; Restrict region
21915 (narrow-to-region (save-excursion (goto-char beg)
21916 (skip-chars-forward " \r\t\n" end)
21917 (line-beginning-position))
21918 (save-excursion (goto-char end)
21919 (skip-chars-backward " \r\t\n" beg)
21920 (line-end-position)))
21921 (let ((uncommentp
21922 ;; UNCOMMENTP is non-nil when every non blank line between
21923 ;; BEG and END is a comment.
21924 (save-excursion
21925 (goto-char (point-min))
21926 (while (and (not (eobp))
21927 (let ((element (org-element-at-point)))
21928 (and (eq (org-element-type element) 'comment)
21929 (goto-char (min (point-max)
21930 (org-element-property
21931 :end element)))))))
21932 (eobp))))
21933 (if uncommentp
21934 ;; Only blank lines and comments in region: uncomment it.
21935 (save-excursion
21936 (goto-char (point-min))
21937 (while (not (eobp))
21938 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21939 (replace-match "" nil nil nil 1))
21940 (forward-line)))
21941 ;; Comment each line in region.
21942 (let ((min-indent (point-max)))
21943 ;; First find the minimum indentation across all lines.
21944 (save-excursion
21945 (goto-char (point-min))
21946 (while (and (not (eobp)) (not (zerop min-indent)))
21947 (unless (looking-at "[ \t]*$")
21948 (setq min-indent (min min-indent (current-indentation))))
21949 (forward-line)))
21950 ;; Then loop over all lines.
21951 (save-excursion
21952 (goto-char (point-min))
21953 (while (not (eobp))
21954 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21955 (org-move-to-column min-indent t)
21956 (insert comment-start))
21957 (forward-line))))))))
21960 ;;; Planning
21962 ;; This section contains tools to operate on timestamp objects, as
21963 ;; returned by, e.g. `org-element-context'.
21965 (defun org-timestamp-has-time-p (timestamp)
21966 "Non-nil when TIMESTAMP has a time specified."
21967 (org-element-property :hour-start timestamp))
21969 (defun org-timestamp-format (timestamp format &optional end utc)
21970 "Format a TIMESTAMP element into a string.
21972 FORMAT is a format specifier to be passed to
21973 `format-time-string'.
21975 When optional argument END is non-nil, use end of date-range or
21976 time-range, if possible.
21978 When optional argument UTC is non-nil, time will be expressed as
21979 Universal Time."
21980 (format-time-string
21981 format
21982 (apply 'encode-time
21983 (cons 0
21984 (mapcar
21985 (lambda (prop) (or (org-element-property prop timestamp) 0))
21986 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21987 '(:minute-start :hour-start :day-start :month-start
21988 :year-start)))))
21989 utc))
21991 (defun org-timestamp-split-range (timestamp &optional end)
21992 "Extract a timestamp object from a date or time range.
21994 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21995 the end of the range. Otherwise, extract its start.
21997 Return a new timestamp object sharing the same parent as
21998 TIMESTAMP."
21999 (let ((type (org-element-property :type timestamp)))
22000 (if (memq type '(active inactive diary)) timestamp
22001 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22002 ;; Set new type.
22003 (org-element-put-property
22004 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22005 ;; Copy start properties over end properties if END is
22006 ;; non-nil. Otherwise, copy end properties over `start' ones.
22007 (let ((p-alist '((:minute-start . :minute-end)
22008 (:hour-start . :hour-end)
22009 (:day-start . :day-end)
22010 (:month-start . :month-end)
22011 (:year-start . :year-end))))
22012 (dolist (p-cell p-alist)
22013 (org-element-put-property
22014 split-ts
22015 (funcall (if end 'car 'cdr) p-cell)
22016 (org-element-property
22017 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22018 ;; Eventually refresh `:raw-value'.
22019 (org-element-put-property split-ts :raw-value nil)
22020 (org-element-put-property
22021 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22023 (defun org-timestamp-translate (timestamp &optional boundary)
22024 "Apply `org-translate-time' on a TIMESTAMP object.
22025 When optional argument BOUNDARY is non-nil, it is either the
22026 symbol `start' or `end'. In this case, only translate the
22027 starting or ending part of TIMESTAMP if it is a date or time
22028 range. Otherwise, translate both parts."
22029 (if (and (not boundary)
22030 (memq (org-element-property :type timestamp)
22031 '(active-range inactive-range)))
22032 (concat
22033 (org-translate-time
22034 (org-element-property :raw-value
22035 (org-timestamp-split-range timestamp)))
22036 "--"
22037 (org-translate-time
22038 (org-element-property :raw-value
22039 (org-timestamp-split-range timestamp t))))
22040 (org-translate-time
22041 (org-element-property
22042 :raw-value
22043 (if (not boundary) timestamp
22044 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22048 ;;; Other stuff.
22050 (defun org-toggle-fixed-width-section (arg)
22051 "Toggle the fixed-width export.
22052 If there is no active region, the QUOTE keyword at the current headline is
22053 inserted or removed. When present, it causes the text between this headline
22054 and the next to be exported as fixed-width text, and unmodified.
22055 If there is an active region, this command adds or removes a colon as the
22056 first character of this line. If the first character of a line is a colon,
22057 this line is also exported in fixed-width font."
22058 (interactive "P")
22059 (let* ((cc 0)
22060 (regionp (org-region-active-p))
22061 (beg (if regionp (region-beginning) (point)))
22062 (end (if regionp (region-end)))
22063 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22064 (case-fold-search nil)
22065 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22066 off)
22067 (if regionp
22068 (save-excursion
22069 (goto-char beg)
22070 (setq cc (current-column))
22071 (beginning-of-line 1)
22072 (setq off (looking-at re))
22073 (while (> nlines 0)
22074 (setq nlines (1- nlines))
22075 (beginning-of-line 1)
22076 (cond
22077 (arg
22078 (org-move-to-column cc t)
22079 (insert ": \n")
22080 (forward-line -1))
22081 ((and off (looking-at re))
22082 (replace-match "" t t nil 1))
22083 ((not off) (org-move-to-column cc t) (insert ": ")))
22084 (forward-line 1)))
22085 (save-excursion
22086 (org-back-to-heading)
22087 (cond
22088 ((looking-at (format org-heading-keyword-regexp-format
22089 org-quote-string))
22090 (goto-char (match-end 1))
22091 (looking-at (concat " +" org-quote-string))
22092 (replace-match "" t t)
22093 (when (eolp) (insert " ")))
22094 ((looking-at org-outline-regexp)
22095 (goto-char (match-end 0))
22096 (insert org-quote-string " ")))))))
22098 (defun org-reftex-citation ()
22099 "Use reftex-citation to insert a citation into the buffer.
22100 This looks for a line like
22102 #+BIBLIOGRAPHY: foo plain option:-d
22104 and derives from it that foo.bib is the bibliography file relevant
22105 for this document. It then installs the necessary environment for RefTeX
22106 to work in this buffer and calls `reftex-citation' to insert a citation
22107 into the buffer.
22109 Export of such citations to both LaTeX and HTML is handled by the contributed
22110 package org-exp-bibtex by Taru Karttunen."
22111 (interactive)
22112 (let ((reftex-docstruct-symbol 'rds)
22113 (reftex-cite-format "\\cite{%l}")
22114 rds bib)
22115 (save-excursion
22116 (save-restriction
22117 (widen)
22118 (let ((case-fold-search t)
22119 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22120 (if (not (save-excursion
22121 (or (re-search-forward re nil t)
22122 (re-search-backward re nil t))))
22123 (error "No bibliography defined in file")
22124 (setq bib (concat (match-string 1) ".bib")
22125 rds (list (list 'bib bib)))))))
22126 (call-interactively 'reftex-citation)))
22128 ;;;; Functions extending outline functionality
22130 (defun org-beginning-of-line (&optional arg)
22131 "Go to the beginning of the current line. If that is invisible, continue
22132 to a visible line beginning. This makes the function of C-a more intuitive.
22133 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22134 first attempt, and only move to after the tags when the cursor is already
22135 beyond the end of the headline."
22136 (interactive "P")
22137 (let ((pos (point))
22138 (special (if (consp org-special-ctrl-a/e)
22139 (car org-special-ctrl-a/e)
22140 org-special-ctrl-a/e))
22141 refpos)
22142 (if (org-bound-and-true-p visual-line-mode)
22143 (beginning-of-visual-line 1)
22144 (beginning-of-line 1))
22145 (if (and arg (fboundp 'move-beginning-of-line))
22146 (call-interactively 'move-beginning-of-line)
22147 (if (bobp)
22149 (backward-char 1)
22150 (if (org-truely-invisible-p)
22151 (while (and (not (bobp)) (org-truely-invisible-p))
22152 (backward-char 1)
22153 (beginning-of-line 1))
22154 (forward-char 1))))
22155 (when special
22156 (cond
22157 ((and (looking-at org-complex-heading-regexp)
22158 (= (char-after (match-end 1)) ?\ ))
22159 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22160 (point-at-eol)))
22161 (goto-char
22162 (if (eq special t)
22163 (cond ((> pos refpos) refpos)
22164 ((= pos (point)) refpos)
22165 (t (point)))
22166 (cond ((> pos (point)) (point))
22167 ((not (eq last-command this-command)) (point))
22168 (t refpos)))))
22169 ((org-at-item-p)
22170 ;; Being at an item and not looking at an the item means point
22171 ;; was previously moved to beginning of a visual line, which
22172 ;; doesn't contain the item. Therefore, do nothing special,
22173 ;; just stay here.
22174 (when (looking-at org-list-full-item-re)
22175 ;; Set special position at first white space character after
22176 ;; bullet, and check-box, if any.
22177 (let ((after-bullet
22178 (let ((box (match-end 3)))
22179 (if (not box) (match-end 1)
22180 (let ((after (char-after box)))
22181 (if (and after (= after ? )) (1+ box) box))))))
22182 ;; Special case: Move point to special position when
22183 ;; currently after it or at beginning of line.
22184 (if (eq special t)
22185 (when (or (> pos after-bullet) (= (point) pos))
22186 (goto-char after-bullet))
22187 ;; Reversed case: Move point to special position when
22188 ;; point was already at beginning of line and command is
22189 ;; repeated.
22190 (when (and (= (point) pos) (eq last-command this-command))
22191 (goto-char after-bullet))))))))
22192 (org-no-warnings
22193 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22195 (defun org-end-of-line (&optional arg)
22196 "Go to the end of the line.
22197 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22198 tags on the first attempt, and only move to after the tags when
22199 the cursor is already beyond the end of the headline."
22200 (interactive "P")
22201 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22202 org-special-ctrl-a/e))
22203 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22204 'end-of-visual-line)
22205 ((fboundp 'move-end-of-line) 'move-end-of-line)
22206 (t 'end-of-line))))
22207 (if (or (not special) arg) (call-interactively move-fun)
22208 (let* ((element (save-excursion (beginning-of-line)
22209 (org-element-at-point)))
22210 (type (org-element-type element)))
22211 (cond
22212 ((memq type '(headline inlinetask))
22213 (let ((pos (point)))
22214 (beginning-of-line 1)
22215 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22216 (if (eq special t)
22217 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22218 (goto-char (match-beginning 1))
22219 (goto-char (match-end 0)))
22220 (if (or (< pos (match-end 0))
22221 (not (eq this-command last-command)))
22222 (goto-char (match-end 0))
22223 (goto-char (match-beginning 1))))
22224 (call-interactively move-fun))))
22225 ((org-element-property :hiddenp element)
22226 ;; If element is hidden, `move-end-of-line' would put point
22227 ;; after it. Use `end-of-line' to stay on current line.
22228 (call-interactively 'end-of-line))
22229 (t (call-interactively move-fun)))))
22230 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22232 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22233 (define-key org-mode-map "\C-e" 'org-end-of-line)
22235 (defun org-backward-sentence (&optional arg)
22236 "Go to beginning of sentence, or beginning of table field.
22237 This will call `backward-sentence' or `org-table-beginning-of-field',
22238 depending on context."
22239 (interactive "P")
22240 (cond
22241 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22242 (t (call-interactively 'backward-sentence))))
22244 (defun org-forward-sentence (&optional arg)
22245 "Go to end of sentence, or end of table field.
22246 This will call `forward-sentence' or `org-table-end-of-field',
22247 depending on context."
22248 (interactive "P")
22249 (cond
22250 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22251 (t (call-interactively 'forward-sentence))))
22253 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22254 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22256 (defun org-kill-line (&optional arg)
22257 "Kill line, to tags or end of line."
22258 (interactive "P")
22259 (cond
22260 ((or (not org-special-ctrl-k)
22261 (bolp)
22262 (not (org-at-heading-p)))
22263 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22264 org-ctrl-k-protect-subtree)
22265 (if (or (eq org-ctrl-k-protect-subtree 'error)
22266 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22267 (error "C-k aborted - would kill hidden subtree")))
22268 (call-interactively
22269 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22270 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22271 (kill-region (point) (match-beginning 1))
22272 (org-set-tags nil t))
22273 (t (kill-region (point) (point-at-eol)))))
22275 (define-key org-mode-map "\C-k" 'org-kill-line)
22277 (defun org-yank (&optional arg)
22278 "Yank. If the kill is a subtree, treat it specially.
22279 This command will look at the current kill and check if is a single
22280 subtree, or a series of subtrees[1]. If it passes the test, and if the
22281 cursor is at the beginning of a line or after the stars of a currently
22282 empty headline, then the yank is handled specially. How exactly depends
22283 on the value of the following variables, both set by default.
22285 org-yank-folded-subtrees
22286 When set, the subtree(s) will be folded after insertion, but only
22287 if doing so would now swallow text after the yanked text.
22289 org-yank-adjusted-subtrees
22290 When set, the subtree will be promoted or demoted in order to
22291 fit into the local outline tree structure, which means that the level
22292 will be adjusted so that it becomes the smaller one of the two
22293 *visible* surrounding headings.
22295 Any prefix to this command will cause `yank' to be called directly with
22296 no special treatment. In particular, a simple \\[universal-argument] prefix \
22297 will just
22298 plainly yank the text as it is.
22300 \[1] The test checks if the first non-white line is a heading
22301 and if there are no other headings with fewer stars."
22302 (interactive "P")
22303 (org-yank-generic 'yank arg))
22305 (defun org-yank-generic (command arg)
22306 "Perform some yank-like command.
22308 This function implements the behavior described in the `org-yank'
22309 documentation. However, it has been generalized to work for any
22310 interactive command with similar behavior."
22312 ;; pretend to be command COMMAND
22313 (setq this-command command)
22315 (if arg
22316 (call-interactively command)
22318 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22319 (and (org-kill-is-subtree-p)
22320 (or (bolp)
22321 (and (looking-at "[ \t]*$")
22322 (string-match
22323 "\\`\\*+\\'"
22324 (buffer-substring (point-at-bol) (point)))))))
22325 swallowp)
22326 (cond
22327 ((and subtreep org-yank-folded-subtrees)
22328 (let ((beg (point))
22329 end)
22330 (if (and subtreep org-yank-adjusted-subtrees)
22331 (org-paste-subtree nil nil 'for-yank)
22332 (call-interactively command))
22334 (setq end (point))
22335 (goto-char beg)
22336 (when (and (bolp) subtreep
22337 (not (setq swallowp
22338 (org-yank-folding-would-swallow-text beg end))))
22339 (org-with-limited-levels
22340 (or (looking-at org-outline-regexp)
22341 (re-search-forward org-outline-regexp-bol end t))
22342 (while (and (< (point) end) (looking-at org-outline-regexp))
22343 (hide-subtree)
22344 (org-cycle-show-empty-lines 'folded)
22345 (condition-case nil
22346 (outline-forward-same-level 1)
22347 (error (goto-char end))))))
22348 (when swallowp
22349 (message
22350 "Inserted text not folded because that would swallow text"))
22352 (goto-char end)
22353 (skip-chars-forward " \t\n\r")
22354 (beginning-of-line 1)
22355 (push-mark beg 'nomsg)))
22356 ((and subtreep org-yank-adjusted-subtrees)
22357 (let ((beg (point-at-bol)))
22358 (org-paste-subtree nil nil 'for-yank)
22359 (push-mark beg 'nomsg)))
22361 (call-interactively command))))))
22363 (defun org-yank-folding-would-swallow-text (beg end)
22364 "Would hide-subtree at BEG swallow any text after END?"
22365 (let (level)
22366 (org-with-limited-levels
22367 (save-excursion
22368 (goto-char beg)
22369 (when (or (looking-at org-outline-regexp)
22370 (re-search-forward org-outline-regexp-bol end t))
22371 (setq level (org-outline-level)))
22372 (goto-char end)
22373 (skip-chars-forward " \t\r\n\v\f")
22374 (if (or (eobp)
22375 (and (bolp) (looking-at org-outline-regexp)
22376 (<= (org-outline-level) level)))
22377 nil ; Nothing would be swallowed
22378 t))))) ; something would swallow
22380 (define-key org-mode-map "\C-y" 'org-yank)
22382 (defun org-truely-invisible-p ()
22383 "Check if point is at a character currently not visible.
22384 This version does not only check the character property, but also
22385 `visible-mode'."
22386 ;; Early versions of noutline don't have `outline-invisible-p'.
22387 (if (org-bound-and-true-p visible-mode)
22389 (outline-invisible-p)))
22391 (defun org-invisible-p2 ()
22392 "Check if point is at a character currently not visible."
22393 (save-excursion
22394 (if (and (eolp) (not (bobp))) (backward-char 1))
22395 ;; Early versions of noutline don't have `outline-invisible-p'.
22396 (outline-invisible-p)))
22398 (defun org-back-to-heading (&optional invisible-ok)
22399 "Call `outline-back-to-heading', but provide a better error message."
22400 (condition-case nil
22401 (outline-back-to-heading invisible-ok)
22402 (error (error "Before first headline at position %d in buffer %s"
22403 (point) (current-buffer)))))
22405 (defun org-before-first-heading-p ()
22406 "Before first heading?"
22407 (save-excursion
22408 (end-of-line)
22409 (null (re-search-backward org-outline-regexp-bol nil t))))
22411 (defun org-at-heading-p (&optional ignored)
22412 (outline-on-heading-p t))
22413 ;; Compatibility alias with Org versions < 7.8.03
22414 (defalias 'org-on-heading-p 'org-at-heading-p)
22416 (defun org-at-comment-p nil
22417 "Is cursor in a line starting with a # character?"
22418 (save-excursion
22419 (beginning-of-line)
22420 (looking-at "^#")))
22422 (defun org-at-drawer-p nil
22423 "Is cursor at a drawer keyword?"
22424 (save-excursion
22425 (move-beginning-of-line 1)
22426 (looking-at org-drawer-regexp)))
22428 (defun org-at-block-p nil
22429 "Is cursor at a block keyword?"
22430 (save-excursion
22431 (move-beginning-of-line 1)
22432 (looking-at org-block-regexp)))
22434 (defun org-point-at-end-of-empty-headline ()
22435 "If point is at the end of an empty headline, return t, else nil.
22436 If the heading only contains a TODO keyword, it is still still considered
22437 empty."
22438 (and (looking-at "[ \t]*$")
22439 (when org-todo-line-regexp
22440 (save-excursion
22441 (beginning-of-line 1)
22442 (let ((case-fold-search nil))
22443 (looking-at org-todo-line-regexp)
22444 (string= (match-string 3) ""))))))
22446 (defun org-at-heading-or-item-p ()
22447 (or (org-at-heading-p) (org-at-item-p)))
22449 (defun org-at-target-p ()
22450 (or (org-in-regexp org-radio-target-regexp)
22451 (org-in-regexp org-target-regexp)))
22452 ;; Compatibility alias with Org versions < 7.8.03
22453 (defalias 'org-on-target-p 'org-at-target-p)
22455 (defun org-up-heading-all (arg)
22456 "Move to the heading line of which the present line is a subheading.
22457 This function considers both visible and invisible heading lines.
22458 With argument, move up ARG levels."
22459 (if (fboundp 'outline-up-heading-all)
22460 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22461 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22463 (defun org-up-heading-safe ()
22464 "Move to the heading line of which the present line is a subheading.
22465 This version will not throw an error. It will return the level of the
22466 headline found, or nil if no higher level is found.
22468 Also, this function will be a lot faster than `outline-up-heading',
22469 because it relies on stars being the outline starters. This can really
22470 make a significant difference in outlines with very many siblings."
22471 (let (start-level re)
22472 (org-back-to-heading t)
22473 (setq start-level (funcall outline-level))
22474 (if (equal start-level 1)
22476 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22477 (if (re-search-backward re nil t)
22478 (funcall outline-level)))))
22480 (defun org-first-sibling-p ()
22481 "Is this heading the first child of its parents?"
22482 (interactive)
22483 (let ((re org-outline-regexp-bol)
22484 level l)
22485 (unless (org-at-heading-p t)
22486 (error "Not at a heading"))
22487 (setq level (funcall outline-level))
22488 (save-excursion
22489 (if (not (re-search-backward re nil t))
22491 (setq l (funcall outline-level))
22492 (< l level)))))
22494 (defun org-goto-sibling (&optional previous)
22495 "Goto the next sibling, even if it is invisible.
22496 When PREVIOUS is set, go to the previous sibling instead. Returns t
22497 when a sibling was found. When none is found, return nil and don't
22498 move point."
22499 (let ((fun (if previous 're-search-backward 're-search-forward))
22500 (pos (point))
22501 (re org-outline-regexp-bol)
22502 level l)
22503 (when (condition-case nil (org-back-to-heading t) (error nil))
22504 (setq level (funcall outline-level))
22505 (catch 'exit
22506 (or previous (forward-char 1))
22507 (while (funcall fun re nil t)
22508 (setq l (funcall outline-level))
22509 (when (< l level) (goto-char pos) (throw 'exit nil))
22510 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22511 (goto-char pos)
22512 nil))))
22514 (defun org-show-siblings ()
22515 "Show all siblings of the current headline."
22516 (save-excursion
22517 (while (org-goto-sibling) (org-flag-heading nil)))
22518 (save-excursion
22519 (while (org-goto-sibling 'previous)
22520 (org-flag-heading nil))))
22522 (defun org-goto-first-child ()
22523 "Goto the first child, even if it is invisible.
22524 Return t when a child was found. Otherwise don't move point and
22525 return nil."
22526 (let (level (pos (point)) (re org-outline-regexp-bol))
22527 (when (condition-case nil (org-back-to-heading t) (error nil))
22528 (setq level (outline-level))
22529 (forward-char 1)
22530 (if (and (re-search-forward re nil t) (> (outline-level) level))
22531 (progn (goto-char (match-beginning 0)) t)
22532 (goto-char pos) nil))))
22534 (defun org-show-hidden-entry ()
22535 "Show an entry where even the heading is hidden."
22536 (save-excursion
22537 (org-show-entry)))
22539 (defun org-flag-heading (flag &optional entry)
22540 "Flag the current heading. FLAG non-nil means make invisible.
22541 When ENTRY is non-nil, show the entire entry."
22542 (save-excursion
22543 (org-back-to-heading t)
22544 ;; Check if we should show the entire entry
22545 (if entry
22546 (progn
22547 (org-show-entry)
22548 (save-excursion
22549 (and (outline-next-heading)
22550 (org-flag-heading nil))))
22551 (outline-flag-region (max (point-min) (1- (point)))
22552 (save-excursion (outline-end-of-heading) (point))
22553 flag))))
22555 (defun org-get-next-sibling ()
22556 "Move to next heading of the same level, and return point.
22557 If there is no such heading, return nil.
22558 This is like outline-next-sibling, but invisible headings are ok."
22559 (let ((level (funcall outline-level)))
22560 (outline-next-heading)
22561 (while (and (not (eobp)) (> (funcall outline-level) level))
22562 (outline-next-heading))
22563 (if (or (eobp) (< (funcall outline-level) level))
22565 (point))))
22567 (defun org-get-last-sibling ()
22568 "Move to previous heading of the same level, and return point.
22569 If there is no such heading, return nil."
22570 (let ((opoint (point))
22571 (level (funcall outline-level)))
22572 (outline-previous-heading)
22573 (when (and (/= (point) opoint) (outline-on-heading-p t))
22574 (while (and (> (funcall outline-level) level)
22575 (not (bobp)))
22576 (outline-previous-heading))
22577 (if (< (funcall outline-level) level)
22579 (point)))))
22581 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22582 "Goto to the end of a subtree."
22583 ;; This contains an exact copy of the original function, but it uses
22584 ;; `org-back-to-heading', to make it work also in invisible
22585 ;; trees. And is uses an invisible-ok argument.
22586 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22587 ;; Furthermore, when used inside Org, finding the end of a large subtree
22588 ;; with many children and grandchildren etc, this can be much faster
22589 ;; than the outline version.
22590 (org-back-to-heading invisible-ok)
22591 (let ((first t)
22592 (level (funcall outline-level)))
22593 (if (and (derived-mode-p 'org-mode) (< level 1000))
22594 ;; A true heading (not a plain list item), in Org-mode
22595 ;; This means we can easily find the end by looking
22596 ;; only for the right number of stars. Using a regexp to do
22597 ;; this is so much faster than using a Lisp loop.
22598 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22599 (forward-char 1)
22600 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22601 ;; something else, do it the slow way
22602 (while (and (not (eobp))
22603 (or first (> (funcall outline-level) level)))
22604 (setq first nil)
22605 (outline-next-heading)))
22606 (unless to-heading
22607 (if (memq (preceding-char) '(?\n ?\^M))
22608 (progn
22609 ;; Go to end of line before heading
22610 (forward-char -1)
22611 (if (memq (preceding-char) '(?\n ?\^M))
22612 ;; leave blank line before heading
22613 (forward-char -1))))))
22614 (point))
22616 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22617 "Use Org version in org-mode, for dramatic speed-up."
22618 (if (derived-mode-p 'org-mode)
22619 (progn
22620 (org-end-of-subtree nil t)
22621 (unless (eobp) (backward-char 1)))
22622 ad-do-it))
22624 (defun org-end-of-meta-data-and-drawers ()
22625 "Jump to the first text after meta data and drawers in the current entry.
22626 This will move over empty lines, lines with planning time stamps,
22627 clocking lines, and drawers."
22628 (org-back-to-heading t)
22629 (let ((end (save-excursion (outline-next-heading) (point)))
22630 (re (concat "\\(" org-drawer-regexp "\\)"
22631 "\\|" "[ \t]*" org-keyword-time-regexp)))
22632 (forward-line 1)
22633 (while (re-search-forward re end t)
22634 (if (not (match-end 1))
22635 ;; empty or planning line
22636 (forward-line 1)
22637 ;; a drawer, find the end
22638 (re-search-forward "^[ \t]*:END:" end 'move)
22639 (forward-line 1)))
22640 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22641 (point)))
22643 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22644 "Move forward to the ARG'th subheading at same level as this one.
22645 Stop at the first and last subheadings of a superior heading.
22646 Normally this only looks at visible headings, but when INVISIBLE-OK is
22647 non-nil it will also look at invisible ones."
22648 (interactive "p")
22649 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22650 (if (and arg (< arg 0))
22651 (goto-char (point-min))
22652 (outline-next-heading))
22653 (org-at-heading-p)
22654 (let ((level (- (match-end 0) (match-beginning 0) 1))
22655 (f (if (and arg (< arg 0))
22656 're-search-backward
22657 're-search-forward))
22658 (count (if arg (abs arg) 1))
22659 (result (point)))
22660 (forward-char (if (and arg (< arg 0)) -1 1))
22661 (while (and (> count 0)
22662 (funcall f org-outline-regexp-bol nil 'move))
22663 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22664 (cond ((< l level) (setq count 0))
22665 ((and (= l level)
22666 (or invisible-ok
22667 (progn
22668 (goto-char (line-beginning-position))
22669 (not (outline-invisible-p)))))
22670 (setq count (1- count))
22671 (when (eq l level)
22672 (setq result (point)))))))
22673 (goto-char result))
22674 (beginning-of-line 1)))
22676 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22677 "Move backward to the ARG'th subheading at same level as this one.
22678 Stop at the first and last subheadings of a superior heading."
22679 (interactive "p")
22680 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22682 (defun org-next-block (arg &optional backward block-regexp)
22683 "Jump to the next block.
22684 With a prefix argument ARG, jump forward ARG many source blocks.
22685 When BACKWARD is non-nil, jump to the previous block.
22686 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22687 (interactive "p")
22688 (let ((re (or block-regexp org-block-regexp))
22689 (re-search-fn (or (and backward 're-search-backward)
22690 're-search-forward)))
22691 (if (looking-at re) (forward-char 1))
22692 (condition-case nil
22693 (funcall re-search-fn re nil nil arg)
22694 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22695 (goto-char (match-beginning 0)) (org-show-context)))
22697 (defun org-previous-block (arg &optional block-regexp)
22698 "Jump to the previous block.
22699 With a prefix argument ARG, jump backward ARG many source blocks.
22700 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22701 (interactive "p")
22702 (org-next-block arg t block-regexp))
22704 (defun org-forward-element ()
22705 "Move forward by one element.
22706 Move to the next element at the same level, when possible."
22707 (interactive)
22708 (cond ((eobp) (error "Cannot move further down"))
22709 ((org-with-limited-levels (org-at-heading-p))
22710 (let ((origin (point)))
22711 (goto-char (org-end-of-subtree nil t))
22712 (unless (org-with-limited-levels (org-at-heading-p))
22713 (goto-char origin)
22714 (error "Cannot move further down"))))
22716 (let* ((elem (org-element-at-point))
22717 (end (org-element-property :end elem))
22718 (parent (org-element-property :parent elem)))
22719 (if (and parent (= (org-element-property :contents-end parent) end))
22720 (goto-char (org-element-property :end parent))
22721 (goto-char end))))))
22723 (defun org-backward-element ()
22724 "Move backward by one element.
22725 Move to the previous element at the same level, when possible."
22726 (interactive)
22727 (cond ((bobp) (error "Cannot move further up"))
22728 ((org-with-limited-levels (org-at-heading-p))
22729 ;; At an headline, move to the previous one, if any, or stay
22730 ;; here.
22731 (let ((origin (point)))
22732 (org-with-limited-levels (org-backward-heading-same-level 1))
22733 ;; When current headline has no sibling above, move to its
22734 ;; parent.
22735 (when (= (point) origin)
22736 (or (org-with-limited-levels (org-up-heading-safe))
22737 (progn (goto-char origin)
22738 (error "Cannot move further up"))))))
22740 (let* ((trail (org-element-at-point 'keep-trail))
22741 (elem (car trail))
22742 (prev-elem (nth 1 trail))
22743 (beg (org-element-property :begin elem)))
22744 (cond
22745 ;; Move to beginning of current element if point isn't
22746 ;; there already.
22747 ((/= (point) beg) (goto-char beg))
22748 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22749 ((org-before-first-heading-p) (goto-char (point-min)))
22750 (t (org-back-to-heading)))))))
22752 (defun org-up-element ()
22753 "Move to upper element."
22754 (interactive)
22755 (if (org-with-limited-levels (org-at-heading-p))
22756 (unless (org-up-heading-safe) (error "No surrounding element"))
22757 (let* ((elem (org-element-at-point))
22758 (parent (org-element-property :parent elem)))
22759 (if parent (goto-char (org-element-property :begin parent))
22760 (if (org-with-limited-levels (org-before-first-heading-p))
22761 (error "No surrounding element")
22762 (org-with-limited-levels (org-back-to-heading)))))))
22764 (defvar org-element-greater-elements)
22765 (defun org-down-element ()
22766 "Move to inner element."
22767 (interactive)
22768 (let ((element (org-element-at-point)))
22769 (cond
22770 ((memq (org-element-type element) '(plain-list table))
22771 (goto-char (org-element-property :contents-begin element))
22772 (forward-char))
22773 ((memq (org-element-type element) org-element-greater-elements)
22774 ;; If contents are hidden, first disclose them.
22775 (when (org-element-property :hiddenp element) (org-cycle))
22776 (goto-char (or (org-element-property :contents-begin element)
22777 (error "No content for this element"))))
22778 (t (error "No inner element")))))
22780 (defun org-drag-element-backward ()
22781 "Move backward element at point."
22782 (interactive)
22783 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22784 (let* ((trail (org-element-at-point 'keep-trail))
22785 (elem (car trail))
22786 (prev-elem (nth 1 trail)))
22787 ;; Error out if no previous element or previous element is
22788 ;; a parent of the current one.
22789 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22790 (error "Cannot drag element backward")
22791 (let ((pos (point)))
22792 (org-element-swap-A-B prev-elem elem)
22793 (goto-char (+ (org-element-property :begin prev-elem)
22794 (- pos (org-element-property :begin elem)))))))))
22796 (defun org-drag-element-forward ()
22797 "Move forward element at point."
22798 (interactive)
22799 (let* ((pos (point))
22800 (elem (org-element-at-point)))
22801 (when (= (point-max) (org-element-property :end elem))
22802 (error "Cannot drag element forward"))
22803 (goto-char (org-element-property :end elem))
22804 (let ((next-elem (org-element-at-point)))
22805 (when (or (org-element-nested-p elem next-elem)
22806 (and (eq (org-element-type next-elem) 'headline)
22807 (not (eq (org-element-type elem) 'headline))))
22808 (goto-char pos)
22809 (error "Cannot drag element forward"))
22810 ;; Compute new position of point: it's shifted by NEXT-ELEM
22811 ;; body's length (without final blanks) and by the length of
22812 ;; blanks between ELEM and NEXT-ELEM.
22813 (let ((size-next (- (save-excursion
22814 (goto-char (org-element-property :end next-elem))
22815 (skip-chars-backward " \r\t\n")
22816 (forward-line)
22817 ;; Small correction if buffer doesn't end
22818 ;; with a newline character.
22819 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22820 (org-element-property :begin next-elem)))
22821 (size-blank (- (org-element-property :end elem)
22822 (save-excursion
22823 (goto-char (org-element-property :end elem))
22824 (skip-chars-backward " \r\t\n")
22825 (forward-line)
22826 (point)))))
22827 (org-element-swap-A-B elem next-elem)
22828 (goto-char (+ pos size-next size-blank))))))
22830 (defun org-mark-element ()
22831 "Put point at beginning of this element, mark at end.
22833 Interactively, if this command is repeated or (in Transient Mark
22834 mode) if the mark is active, it marks the next element after the
22835 ones already marked."
22836 (interactive)
22837 (let (deactivate-mark)
22838 (if (and (org-called-interactively-p 'any)
22839 (or (and (eq last-command this-command) (mark t))
22840 (and transient-mark-mode mark-active)))
22841 (set-mark
22842 (save-excursion
22843 (goto-char (mark))
22844 (goto-char (org-element-property :end (org-element-at-point)))))
22845 (let ((element (org-element-at-point)))
22846 (end-of-line)
22847 (push-mark (org-element-property :end element) t t)
22848 (goto-char (org-element-property :begin element))))))
22850 (defun org-narrow-to-element ()
22851 "Narrow buffer to current element."
22852 (interactive)
22853 (let ((elem (org-element-at-point)))
22854 (cond
22855 ((eq (car elem) 'headline)
22856 (narrow-to-region
22857 (org-element-property :begin elem)
22858 (org-element-property :end elem)))
22859 ((memq (car elem) org-element-greater-elements)
22860 (narrow-to-region
22861 (org-element-property :contents-begin elem)
22862 (org-element-property :contents-end elem)))
22864 (narrow-to-region
22865 (org-element-property :begin elem)
22866 (org-element-property :end elem))))))
22868 (defun org-transpose-words ()
22869 "Transpose words, using `org-mode' syntax table."
22870 (interactive)
22871 (with-syntax-table org-syntax-table
22872 (call-interactively 'transpose-words)))
22873 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22875 (defun org-transpose-element ()
22876 "Transpose current and previous elements, keeping blank lines between.
22877 Point is moved after both elements."
22878 (interactive)
22879 (org-skip-whitespace)
22880 (let ((end (org-element-property :end (org-element-at-point))))
22881 (org-drag-element-backward)
22882 (goto-char end)))
22884 (defun org-unindent-buffer ()
22885 "Un-indent the visible part of the buffer.
22886 Relative indentation (between items, inside blocks, etc.) isn't
22887 modified."
22888 (interactive)
22889 (unless (eq major-mode 'org-mode)
22890 (error "Cannot un-indent a buffer not in Org mode"))
22891 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22892 unindent-tree ; For byte-compiler.
22893 (unindent-tree
22894 (function
22895 (lambda (contents)
22896 (mapc
22897 (lambda (element)
22898 (if (memq (org-element-type element) '(headline section))
22899 (funcall unindent-tree (org-element-contents element))
22900 (save-excursion
22901 (save-restriction
22902 (narrow-to-region
22903 (org-element-property :begin element)
22904 (org-element-property :end element))
22905 (org-do-remove-indentation)))))
22906 (reverse contents))))))
22907 (funcall unindent-tree (org-element-contents parse-tree))))
22909 (defun org-show-subtree ()
22910 "Show everything after this heading at deeper levels."
22911 (interactive)
22912 (outline-flag-region
22913 (point)
22914 (save-excursion
22915 (org-end-of-subtree t t))
22916 nil))
22918 (defun org-show-entry ()
22919 "Show the body directly following this heading.
22920 Show the heading too, if it is currently invisible."
22921 (interactive)
22922 (save-excursion
22923 (condition-case nil
22924 (progn
22925 (org-back-to-heading t)
22926 (outline-flag-region
22927 (max (point-min) (1- (point)))
22928 (save-excursion
22929 (if (re-search-forward
22930 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22931 (match-beginning 1)
22932 (point-max)))
22933 nil)
22934 (org-cycle-hide-drawers 'children))
22935 (error nil))))
22937 (defun org-make-options-regexp (kwds &optional extra)
22938 "Make a regular expression for keyword lines."
22939 (concat
22940 "^#\\+\\("
22941 (mapconcat 'regexp-quote kwds "\\|")
22942 (if extra (concat "\\|" extra))
22943 "\\):[ \t]*\\(.*\\)"))
22945 ;; Make isearch reveal the necessary context
22946 (defun org-isearch-end ()
22947 "Reveal context after isearch exits."
22948 (when isearch-success ; only if search was successful
22949 (if (featurep 'xemacs)
22950 ;; Under XEmacs, the hook is run in the correct place,
22951 ;; we directly show the context.
22952 (org-show-context 'isearch)
22953 ;; In Emacs the hook runs *before* restoring the overlays.
22954 ;; So we have to use a one-time post-command-hook to do this.
22955 ;; (Emacs 22 has a special variable, see function `org-mode')
22956 (unless (and (boundp 'isearch-mode-end-hook-quit)
22957 isearch-mode-end-hook-quit)
22958 ;; Only when the isearch was not quitted.
22959 (org-add-hook 'post-command-hook 'org-isearch-post-command
22960 'append 'local)))))
22962 (defun org-isearch-post-command ()
22963 "Remove self from hook, and show context."
22964 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22965 (org-show-context 'isearch))
22968 ;;;; Integration with and fixes for other packages
22970 ;;; Imenu support
22972 (defvar org-imenu-markers nil
22973 "All markers currently used by Imenu.")
22974 (make-variable-buffer-local 'org-imenu-markers)
22976 (defun org-imenu-new-marker (&optional pos)
22977 "Return a new marker for use by Imenu, and remember the marker."
22978 (let ((m (make-marker)))
22979 (move-marker m (or pos (point)))
22980 (push m org-imenu-markers)
22983 (defun org-imenu-get-tree ()
22984 "Produce the index for Imenu."
22985 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22986 (setq org-imenu-markers nil)
22987 (let* ((n org-imenu-depth)
22988 (re (concat "^" (org-get-limited-outline-regexp)))
22989 (subs (make-vector (1+ n) nil))
22990 (last-level 0)
22991 m level head)
22992 (save-excursion
22993 (save-restriction
22994 (widen)
22995 (goto-char (point-max))
22996 (while (re-search-backward re nil t)
22997 (setq level (org-reduced-level (funcall outline-level)))
22998 (when (and (<= level n)
22999 (looking-at org-complex-heading-regexp))
23000 (setq head (org-link-display-format
23001 (org-match-string-no-properties 4))
23002 m (org-imenu-new-marker))
23003 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23004 (if (>= level last-level)
23005 (push (cons head m) (aref subs level))
23006 (push (cons head (aref subs (1+ level))) (aref subs level))
23007 (loop for i from (1+ level) to n do (aset subs i nil)))
23008 (setq last-level level)))))
23009 (aref subs 1)))
23011 (eval-after-load "imenu"
23012 '(progn
23013 (add-hook 'imenu-after-jump-hook
23014 (lambda ()
23015 (if (derived-mode-p 'org-mode)
23016 (org-show-context 'org-goto))))))
23018 (defun org-link-display-format (link)
23019 "Replace a link with either the description, or the link target
23020 if no description is present"
23021 (save-match-data
23022 (if (string-match org-bracket-link-analytic-regexp link)
23023 (replace-match (if (match-end 5)
23024 (match-string 5 link)
23025 (concat (match-string 1 link)
23026 (match-string 3 link)))
23027 nil t link)
23028 link)))
23030 (defun org-toggle-link-display ()
23031 "Toggle the literal or descriptive display of links."
23032 (interactive)
23033 (if org-descriptive-links
23034 (progn (org-remove-from-invisibility-spec '(org-link))
23035 (org-restart-font-lock)
23036 (setq org-descriptive-links nil))
23037 (progn (add-to-invisibility-spec '(org-link))
23038 (org-restart-font-lock)
23039 (setq org-descriptive-links t))))
23041 ;; Speedbar support
23043 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23044 "Overlay marking the agenda restriction line in speedbar.")
23045 (overlay-put org-speedbar-restriction-lock-overlay
23046 'face 'org-agenda-restriction-lock)
23047 (overlay-put org-speedbar-restriction-lock-overlay
23048 'help-echo "Agendas are currently limited to this item.")
23049 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23051 (defun org-speedbar-set-agenda-restriction ()
23052 "Restrict future agenda commands to the location at point in speedbar.
23053 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23054 (interactive)
23055 (require 'org-agenda)
23056 (let (p m tp np dir txt)
23057 (cond
23058 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23059 'org-imenu t))
23060 (setq m (get-text-property p 'org-imenu-marker))
23061 (with-current-buffer (marker-buffer m)
23062 (goto-char m)
23063 (org-agenda-set-restriction-lock 'subtree)))
23064 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23065 'speedbar-function 'speedbar-find-file))
23066 (setq tp (previous-single-property-change
23067 (1+ p) 'speedbar-function)
23068 np (next-single-property-change
23069 tp 'speedbar-function)
23070 dir (speedbar-line-directory)
23071 txt (buffer-substring-no-properties (or tp (point-min))
23072 (or np (point-max))))
23073 (with-current-buffer (find-file-noselect
23074 (let ((default-directory dir))
23075 (expand-file-name txt)))
23076 (unless (derived-mode-p 'org-mode)
23077 (error "Cannot restrict to non-Org-mode file"))
23078 (org-agenda-set-restriction-lock 'file)))
23079 (t (error "Don't know how to restrict Org-mode's agenda")))
23080 (move-overlay org-speedbar-restriction-lock-overlay
23081 (point-at-bol) (point-at-eol))
23082 (setq current-prefix-arg nil)
23083 (org-agenda-maybe-redo)))
23085 (eval-after-load "speedbar"
23086 '(progn
23087 (speedbar-add-supported-extension ".org")
23088 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23089 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23090 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23091 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23092 (add-hook 'speedbar-visiting-tag-hook
23093 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23095 ;;; Fixes and Hacks for problems with other packages
23097 ;; Make flyspell not check words in links, to not mess up our keymap
23098 (defvar org-element-affiliated-keywords) ; From org-element.el
23099 (defvar org-element-block-name-alist) ; From org-element.el
23100 (defun org-mode-flyspell-verify ()
23101 "Don't let flyspell put overlays at active buttons, or on
23102 {todo,all-time,additional-option-like}-keywords."
23103 (let ((pos (max (1- (point)) (point-min)))
23104 (word (thing-at-point 'word)))
23105 (and (not (get-text-property pos 'keymap))
23106 (not (get-text-property pos 'org-no-flyspell))
23107 (not (member word org-todo-keywords-1))
23108 (not (member word org-all-time-keywords))
23109 (not (member word org-options-keywords))
23110 (not (member word (mapcar 'car org-startup-options)))
23111 (not (member-ignore-case word org-element-affiliated-keywords))
23112 (not (member-ignore-case word (org-get-export-keywords)))
23113 (not (member-ignore-case
23114 word (mapcar 'car org-element-block-name-alist)))
23115 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23117 (defun org-remove-flyspell-overlays-in (beg end)
23118 "Remove flyspell overlays in region."
23119 (and (org-bound-and-true-p flyspell-mode)
23120 (fboundp 'flyspell-delete-region-overlays)
23121 (flyspell-delete-region-overlays beg end))
23122 (add-text-properties beg end '(org-no-flyspell t)))
23124 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23125 (eval-after-load "bookmark"
23126 '(if (boundp 'bookmark-after-jump-hook)
23127 ;; We can use the hook
23128 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23129 ;; Hook not available, use advice
23130 (defadvice bookmark-jump (after org-make-visible activate)
23131 "Make the position visible."
23132 (org-bookmark-jump-unhide))))
23134 ;; Make sure saveplace shows the location if it was hidden
23135 (eval-after-load "saveplace"
23136 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23137 "Make the position visible."
23138 (org-bookmark-jump-unhide)))
23140 ;; Make sure ecb shows the location if it was hidden
23141 (eval-after-load "ecb"
23142 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23143 "Make hierarchy visible when jumping into location from ECB tree buffer."
23144 (if (derived-mode-p 'org-mode)
23145 (org-show-context))))
23147 (defun org-bookmark-jump-unhide ()
23148 "Unhide the current position, to show the bookmark location."
23149 (and (derived-mode-p 'org-mode)
23150 (or (outline-invisible-p)
23151 (save-excursion (goto-char (max (point-min) (1- (point))))
23152 (outline-invisible-p)))
23153 (org-show-context 'bookmark-jump)))
23155 ;; Make session.el ignore our circular variable
23156 (eval-after-load "session"
23157 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23159 ;;;; Experimental code
23161 (defun org-closed-in-range ()
23162 "Sparse tree of items closed in a certain time range.
23163 Still experimental, may disappear in the future."
23164 (interactive)
23165 ;; Get the time interval from the user.
23166 (let* ((time1 (org-float-time
23167 (org-read-date nil 'to-time nil "Starting date: ")))
23168 (time2 (org-float-time
23169 (org-read-date nil 'to-time nil "End date:")))
23170 ;; callback function
23171 (callback (lambda ()
23172 (let ((time
23173 (org-float-time
23174 (apply 'encode-time
23175 (org-parse-time-string
23176 (match-string 1))))))
23177 ;; check if time in interval
23178 (and (>= time time1) (<= time time2))))))
23179 ;; make tree, check each match with the callback
23180 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23182 ;;;; Finish up
23184 (provide 'org)
23186 (run-hooks 'org-load-hook)
23188 ;;; org.el ends here