org.el: Declare orgstruct-mode
[org-mode/org-tableheadings.git] / lisp / org.el
bloba1e223b9f34f9054bd3d22f86929a9817fdbc954
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 (defvar orgstruct-mode) ; defined below
7404 (defun org-heading-components ()
7405 "Return the components of the current heading.
7406 This is a list with the following elements:
7407 - the level as an integer
7408 - the reduced level, different if `org-odd-levels-only' is set.
7409 - the TODO keyword, or nil
7410 - the priority character, like ?A, or nil if no priority is given
7411 - the headline text itself, or the tags string if no headline text
7412 - the tags string, or nil."
7413 (save-excursion
7414 (org-back-to-heading t)
7415 (if (let (case-fold-search)
7416 (looking-at
7417 (if orgstruct-mode
7418 org-heading-regexp
7419 org-complex-heading-regexp)))
7420 (if orgstruct-mode
7421 (list (length (match-string 1))
7422 (org-reduced-level (length (match-string 1)))
7425 (match-string 2)
7426 nil)
7427 (list (length (match-string 1))
7428 (org-reduced-level (length (match-string 1)))
7429 (org-match-string-no-properties 2)
7430 (and (match-end 3) (aref (match-string 3) 2))
7431 (org-match-string-no-properties 4)
7432 (org-match-string-no-properties 5))))))
7434 (defun org-get-entry ()
7435 "Get the entry text, after heading, entire subtree."
7436 (save-excursion
7437 (org-back-to-heading t)
7438 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7440 (defun org-insert-heading-after-current ()
7441 "Insert a new heading with same level as current, after current subtree."
7442 (interactive)
7443 (org-back-to-heading)
7444 (org-insert-heading)
7445 (org-move-subtree-down)
7446 (end-of-line 1))
7448 (defun org-insert-heading-respect-content ()
7449 (interactive)
7450 (let ((org-insert-heading-respect-content t))
7451 (org-insert-heading t)))
7453 (defun org-insert-todo-heading-respect-content (&optional force-state)
7454 (interactive "P")
7455 (let ((org-insert-heading-respect-content t))
7456 (org-insert-todo-heading force-state t)))
7458 (defun org-insert-todo-heading (arg &optional force-heading)
7459 "Insert a new heading with the same level and TODO state as current heading.
7460 If the heading has no TODO state, or if the state is DONE, use the first
7461 state (TODO by default). Also one prefix arg, force first state. With two
7462 prefix args, force inserting at the end of the parent subtree."
7463 (interactive "P")
7464 (when (or force-heading (not (org-insert-item 'checkbox)))
7465 (org-insert-heading (or (and (equal arg '(16)) '(16))
7466 force-heading))
7467 (save-excursion
7468 (org-back-to-heading)
7469 (outline-previous-heading)
7470 (looking-at org-todo-line-regexp))
7471 (let*
7472 ((new-mark-x
7473 (if (or arg
7474 (not (match-beginning 2))
7475 (member (match-string 2) org-done-keywords))
7476 (car org-todo-keywords-1)
7477 (match-string 2)))
7478 (new-mark
7480 (run-hook-with-args-until-success
7481 'org-todo-get-default-hook new-mark-x nil)
7482 new-mark-x)))
7483 (beginning-of-line 1)
7484 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7485 (if org-treat-insert-todo-heading-as-state-change
7486 (org-todo new-mark)
7487 (insert new-mark " "))))
7488 (when org-provide-todo-statistics
7489 (org-update-parent-todo-statistics))))
7491 (defun org-insert-subheading (arg)
7492 "Insert a new subheading and demote it.
7493 Works for outline headings and for plain lists alike."
7494 (interactive "P")
7495 (org-insert-heading arg)
7496 (cond
7497 ((org-at-heading-p) (org-do-demote))
7498 ((org-at-item-p) (org-indent-item))))
7500 (defun org-insert-todo-subheading (arg)
7501 "Insert a new subheading with TODO keyword or checkbox and demote it.
7502 Works for outline headings and for plain lists alike."
7503 (interactive "P")
7504 (org-insert-todo-heading arg)
7505 (cond
7506 ((org-at-heading-p) (org-do-demote))
7507 ((org-at-item-p) (org-indent-item))))
7509 ;;; Promotion and Demotion
7511 (defvar org-after-demote-entry-hook nil
7512 "Hook run after an entry has been demoted.
7513 The cursor will be at the beginning of the entry.
7514 When a subtree is being demoted, the hook will be called for each node.")
7516 (defvar org-after-promote-entry-hook nil
7517 "Hook run after an entry has been promoted.
7518 The cursor will be at the beginning of the entry.
7519 When a subtree is being promoted, the hook will be called for each node.")
7521 (defun org-promote-subtree ()
7522 "Promote the entire subtree.
7523 See also `org-promote'."
7524 (interactive)
7525 (save-excursion
7526 (org-with-limited-levels (org-map-tree 'org-promote)))
7527 (org-fix-position-after-promote))
7529 (defun org-demote-subtree ()
7530 "Demote the entire subtree. See `org-demote'.
7531 See also `org-promote'."
7532 (interactive)
7533 (save-excursion
7534 (org-with-limited-levels (org-map-tree 'org-demote)))
7535 (org-fix-position-after-promote))
7538 (defun org-do-promote ()
7539 "Promote the current heading higher up the tree.
7540 If the region is active in `transient-mark-mode', promote all headings
7541 in the region."
7542 (interactive)
7543 (save-excursion
7544 (if (org-region-active-p)
7545 (org-map-region 'org-promote (region-beginning) (region-end))
7546 (org-promote)))
7547 (org-fix-position-after-promote))
7549 (defun org-do-demote ()
7550 "Demote the current heading lower down the tree.
7551 If the region is active in `transient-mark-mode', demote all headings
7552 in the region."
7553 (interactive)
7554 (save-excursion
7555 (if (org-region-active-p)
7556 (org-map-region 'org-demote (region-beginning) (region-end))
7557 (org-demote)))
7558 (org-fix-position-after-promote))
7560 (defun org-fix-position-after-promote ()
7561 "Make sure that after pro/demotion cursor position is right."
7562 (let ((pos (point)))
7563 (when (save-excursion
7564 (beginning-of-line 1)
7565 (looking-at org-todo-line-regexp)
7566 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7567 (cond ((eobp) (insert " "))
7568 ((eolp) (insert " "))
7569 ((equal (char-after) ?\ ) (forward-char 1))))))
7571 (defun org-current-level ()
7572 "Return the level of the current entry, or nil if before the first headline.
7573 The level is the number of stars at the beginning of the headline."
7574 (save-excursion
7575 (org-with-limited-levels
7576 (if (ignore-errors (org-back-to-heading t))
7577 (funcall outline-level)))))
7579 (defun org-get-previous-line-level ()
7580 "Return the outline depth of the last headline before the current line.
7581 Returns 0 for the first headline in the buffer, and nil if before the
7582 first headline."
7583 (let ((current-level (org-current-level))
7584 (prev-level (when (> (line-number-at-pos) 1)
7585 (save-excursion
7586 (beginning-of-line 0)
7587 (org-current-level)))))
7588 (cond ((null current-level) nil) ; Before first headline
7589 ((null prev-level) 0) ; At first headline
7590 (prev-level))))
7592 (defun org-reduced-level (l)
7593 "Compute the effective level of a heading.
7594 This takes into account the setting of `org-odd-levels-only'."
7595 (cond
7596 ((zerop l) 0)
7597 (org-odd-levels-only (1+ (floor (/ l 2))))
7598 (t l)))
7600 (defun org-level-increment ()
7601 "Return the number of stars that will be added or removed at a
7602 time to headlines when structure editing, based on the value of
7603 `org-odd-levels-only'."
7604 (if org-odd-levels-only 2 1))
7606 (defun org-get-valid-level (level &optional change)
7607 "Rectify a level change under the influence of `org-odd-levels-only'
7608 LEVEL is a current level, CHANGE is by how much the level should be
7609 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7610 even level numbers will become the next higher odd number."
7611 (if org-odd-levels-only
7612 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7613 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7614 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7615 (max 1 (+ level (or change 0)))))
7617 (if (boundp 'define-obsolete-function-alias)
7618 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7619 (define-obsolete-function-alias 'org-get-legal-level
7620 'org-get-valid-level)
7621 (define-obsolete-function-alias 'org-get-legal-level
7622 'org-get-valid-level "23.1")))
7624 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7625 ;; ̀org-with-limited-levels'
7626 (defun org-promote ()
7627 "Promote the current heading higher up the tree.
7628 If the region is active in `transient-mark-mode', promote all headings
7629 in the region."
7630 (org-back-to-heading t)
7631 (let* ((level (save-match-data (funcall outline-level)))
7632 (after-change-functions (remove 'flyspell-after-change-function
7633 after-change-functions))
7634 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7635 (diff (abs (- level (length up-head) -1))))
7636 (cond ((and (= level 1) org-called-with-limited-levels
7637 org-allow-promoting-top-level-subtree)
7638 (replace-match "# " nil t))
7639 ((= level 1)
7640 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7641 (t (replace-match up-head nil t)))
7642 ;; Fixup tag positioning
7643 (unless (= level 1)
7644 (and org-auto-align-tags (org-set-tags nil t))
7645 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7646 (run-hooks 'org-after-promote-entry-hook)))
7648 (defun org-demote ()
7649 "Demote the current heading lower down the tree.
7650 If the region is active in `transient-mark-mode', demote all headings
7651 in the region."
7652 (org-back-to-heading t)
7653 (let* ((level (save-match-data (funcall outline-level)))
7654 (after-change-functions (remove 'flyspell-after-change-function
7655 after-change-functions))
7656 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7657 (diff (abs (- level (length down-head) -1))))
7658 (replace-match down-head nil t)
7659 ;; Fixup tag positioning
7660 (and org-auto-align-tags (org-set-tags nil t))
7661 (if org-adapt-indentation (org-fixup-indentation diff))
7662 (run-hooks 'org-after-demote-entry-hook)))
7664 (defun org-cycle-level ()
7665 "Cycle the level of an empty headline through possible states.
7666 This goes first to child, then to parent, level, then up the hierarchy.
7667 After top level, it switches back to sibling level."
7668 (interactive)
7669 (let ((org-adapt-indentation nil))
7670 (when (org-point-at-end-of-empty-headline)
7671 (setq this-command 'org-cycle-level) ; Only needed for caching
7672 (let ((cur-level (org-current-level))
7673 (prev-level (org-get-previous-line-level)))
7674 (cond
7675 ;; If first headline in file, promote to top-level.
7676 ((= prev-level 0)
7677 (loop repeat (/ (- cur-level 1) (org-level-increment))
7678 do (org-do-promote)))
7679 ;; If same level as prev, demote one.
7680 ((= prev-level cur-level)
7681 (org-do-demote))
7682 ;; If parent is top-level, promote to top level if not already.
7683 ((= prev-level 1)
7684 (loop repeat (/ (- cur-level 1) (org-level-increment))
7685 do (org-do-promote)))
7686 ;; If top-level, return to prev-level.
7687 ((= cur-level 1)
7688 (loop repeat (/ (- prev-level 1) (org-level-increment))
7689 do (org-do-demote)))
7690 ;; If less than prev-level, promote one.
7691 ((< cur-level prev-level)
7692 (org-do-promote))
7693 ;; If deeper than prev-level, promote until higher than
7694 ;; prev-level.
7695 ((> cur-level prev-level)
7696 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7697 do (org-do-promote))))
7698 t))))
7700 (defun org-map-tree (fun)
7701 "Call FUN for every heading underneath the current one."
7702 (org-back-to-heading)
7703 (let ((level (funcall outline-level)))
7704 (save-excursion
7705 (funcall fun)
7706 (while (and (progn
7707 (outline-next-heading)
7708 (> (funcall outline-level) level))
7709 (not (eobp)))
7710 (funcall fun)))))
7712 (defun org-map-region (fun beg end)
7713 "Call FUN for every heading between BEG and END."
7714 (let ((org-ignore-region t))
7715 (save-excursion
7716 (setq end (copy-marker end))
7717 (goto-char beg)
7718 (if (and (re-search-forward org-outline-regexp-bol nil t)
7719 (< (point) end))
7720 (funcall fun))
7721 (while (and (progn
7722 (outline-next-heading)
7723 (< (point) end))
7724 (not (eobp)))
7725 (funcall fun)))))
7727 (defvar org-property-end-re) ; silence byte-compiler
7728 (defun org-fixup-indentation (diff)
7729 "Change the indentation in the current entry by DIFF.
7730 However, if any line in the current entry has no indentation, or if it
7731 would end up with no indentation after the change, nothing at all is done."
7732 (save-excursion
7733 (let ((end (save-excursion (outline-next-heading)
7734 (point-marker)))
7735 (prohibit (if (> diff 0)
7736 "^\\S-"
7737 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7738 col)
7739 (unless (save-excursion (end-of-line 1)
7740 (re-search-forward prohibit end t))
7741 (while (and (< (point) end)
7742 (re-search-forward "^[ \t]+" end t))
7743 (goto-char (match-end 0))
7744 (setq col (current-column))
7745 (if (< diff 0) (replace-match ""))
7746 (org-indent-to-column (+ diff col))))
7747 (move-marker end nil))))
7749 (defun org-convert-to-odd-levels ()
7750 "Convert an org-mode file with all levels allowed to one with odd levels.
7751 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7752 level 5 etc."
7753 (interactive)
7754 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7755 (let ((outline-level 'org-outline-level)
7756 (org-odd-levels-only nil) n)
7757 (save-excursion
7758 (goto-char (point-min))
7759 (while (re-search-forward "^\\*\\*+ " nil t)
7760 (setq n (- (length (match-string 0)) 2))
7761 (while (>= (setq n (1- n)) 0)
7762 (org-demote))
7763 (end-of-line 1))))))
7765 (defun org-convert-to-oddeven-levels ()
7766 "Convert an org-mode file with only odd levels to one with odd/even levels.
7767 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7768 file contains a section with an even level, conversion would
7769 destroy the structure of the file. An error is signaled in this
7770 case."
7771 (interactive)
7772 (goto-char (point-min))
7773 ;; First check if there are no even levels
7774 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7775 (org-show-context t)
7776 (error "Not all levels are odd in this file. Conversion not possible"))
7777 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7778 (let ((outline-regexp org-outline-regexp)
7779 (outline-level 'org-outline-level)
7780 (org-odd-levels-only nil) n)
7781 (save-excursion
7782 (goto-char (point-min))
7783 (while (re-search-forward "^\\*\\*+ " nil t)
7784 (setq n (/ (1- (length (match-string 0))) 2))
7785 (while (>= (setq n (1- n)) 0)
7786 (org-promote))
7787 (end-of-line 1))))))
7789 (defun org-tr-level (n)
7790 "Make N odd if required."
7791 (if org-odd-levels-only (1+ (/ n 2)) n))
7793 ;;; Vertical tree motion, cutting and pasting of subtrees
7795 (defun org-move-subtree-up (&optional arg)
7796 "Move the current subtree up past ARG headlines of the same level."
7797 (interactive "p")
7798 (org-move-subtree-down (- (prefix-numeric-value arg))))
7800 (defun org-move-subtree-down (&optional arg)
7801 "Move the current subtree down past ARG headlines of the same level."
7802 (interactive "p")
7803 (setq arg (prefix-numeric-value arg))
7804 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7805 'org-get-last-sibling))
7806 (ins-point (make-marker))
7807 (cnt (abs arg))
7808 (col (current-column))
7809 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7810 ;; Select the tree
7811 (org-back-to-heading)
7812 (setq beg0 (point))
7813 (save-excursion
7814 (setq ne-beg (org-back-over-empty-lines))
7815 (setq beg (point)))
7816 (save-match-data
7817 (save-excursion (outline-end-of-heading)
7818 (setq folded (outline-invisible-p)))
7819 (outline-end-of-subtree))
7820 (outline-next-heading)
7821 (setq ne-end (org-back-over-empty-lines))
7822 (setq end (point))
7823 (goto-char beg0)
7824 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7825 ;; include less whitespace
7826 (save-excursion
7827 (goto-char beg)
7828 (forward-line (- ne-beg ne-end))
7829 (setq beg (point))))
7830 ;; Find insertion point, with error handling
7831 (while (> cnt 0)
7832 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7833 (progn (goto-char beg0)
7834 (error "Cannot move past superior level or buffer limit")))
7835 (setq cnt (1- cnt)))
7836 (if (> arg 0)
7837 ;; Moving forward - still need to move over subtree
7838 (progn (org-end-of-subtree t t)
7839 (save-excursion
7840 (org-back-over-empty-lines)
7841 (or (bolp) (newline)))))
7842 (setq ne-ins (org-back-over-empty-lines))
7843 (move-marker ins-point (point))
7844 (setq txt (buffer-substring beg end))
7845 (org-save-markers-in-region beg end)
7846 (delete-region beg end)
7847 (org-remove-empty-overlays-at beg)
7848 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7849 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7850 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7851 (let ((bbb (point)))
7852 (insert-before-markers txt)
7853 (org-reinstall-markers-in-region bbb)
7854 (move-marker ins-point bbb))
7855 (or (bolp) (insert "\n"))
7856 (setq ins-end (point))
7857 (goto-char ins-point)
7858 (org-skip-whitespace)
7859 (when (and (< arg 0)
7860 (org-first-sibling-p)
7861 (> ne-ins ne-beg))
7862 ;; Move whitespace back to beginning
7863 (save-excursion
7864 (goto-char ins-end)
7865 (let ((kill-whole-line t))
7866 (kill-line (- ne-ins ne-beg)) (point)))
7867 (insert (make-string (- ne-ins ne-beg) ?\n)))
7868 (move-marker ins-point nil)
7869 (if folded
7870 (hide-subtree)
7871 (org-show-entry)
7872 (show-children)
7873 (org-cycle-hide-drawers 'children))
7874 (org-clean-visibility-after-subtree-move)
7875 ;; move back to the initial column we were at
7876 (move-to-column col)))
7878 (defvar org-subtree-clip ""
7879 "Clipboard for cut and paste of subtrees.
7880 This is actually only a copy of the kill, because we use the normal kill
7881 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7883 (defvar org-subtree-clip-folded nil
7884 "Was the last copied subtree folded?
7885 This is used to fold the tree back after pasting.")
7887 (defun org-cut-subtree (&optional n)
7888 "Cut the current subtree into the clipboard.
7889 With prefix arg N, cut this many sequential subtrees.
7890 This is a short-hand for marking the subtree and then cutting it."
7891 (interactive "p")
7892 (org-copy-subtree n 'cut))
7894 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7895 "Cut the current subtree into the clipboard.
7896 With prefix arg N, cut this many sequential subtrees.
7897 This is a short-hand for marking the subtree and then copying it.
7898 If CUT is non-nil, actually cut the subtree.
7899 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7900 of some markers in the region, even if CUT is non-nil. This is
7901 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7902 (interactive "p")
7903 (let (beg end folded (beg0 (point)))
7904 (if (org-called-interactively-p 'any)
7905 (org-back-to-heading nil) ; take what looks like a subtree
7906 (org-back-to-heading t)) ; take what is really there
7907 (setq beg (point))
7908 (skip-chars-forward " \t\r\n")
7909 (save-match-data
7910 (if nosubtrees
7911 (outline-next-heading)
7912 (save-excursion (outline-end-of-heading)
7913 (setq folded (outline-invisible-p)))
7914 (condition-case nil
7915 (org-forward-heading-same-level (1- n) t)
7916 (error nil))
7917 (org-end-of-subtree t t)))
7918 (setq end (point))
7919 (goto-char beg0)
7920 (when (> end beg)
7921 (setq org-subtree-clip-folded folded)
7922 (when (or cut force-store-markers)
7923 (org-save-markers-in-region beg end))
7924 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7925 (setq org-subtree-clip (current-kill 0))
7926 (message "%s: Subtree(s) with %d characters"
7927 (if cut "Cut" "Copied")
7928 (length org-subtree-clip)))))
7930 (defun org-paste-subtree (&optional level tree for-yank)
7931 "Paste the clipboard as a subtree, with modification of headline level.
7932 The entire subtree is promoted or demoted in order to match a new headline
7933 level.
7935 If the cursor is at the beginning of a headline, the same level as
7936 that headline is used to paste the tree.
7938 If not, the new level is derived from the *visible* headings
7939 before and after the insertion point, and taken to be the inferior headline
7940 level of the two. So if the previous visible heading is level 3 and the
7941 next is level 4 (or vice versa), level 4 will be used for insertion.
7942 This makes sure that the subtree remains an independent subtree and does
7943 not swallow low level entries.
7945 You can also force a different level, either by using a numeric prefix
7946 argument, or by inserting the heading marker by hand. For example, if the
7947 cursor is after \"*****\", then the tree will be shifted to level 5.
7949 If optional TREE is given, use this text instead of the kill ring.
7951 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7952 move back over whitespace before inserting, and move point to the end of
7953 the inserted text when done."
7954 (interactive "P")
7955 (setq tree (or tree (and kill-ring (current-kill 0))))
7956 (unless (org-kill-is-subtree-p tree)
7957 (error "%s"
7958 (substitute-command-keys
7959 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7960 (org-with-limited-levels
7961 (let* ((visp (not (outline-invisible-p)))
7962 (txt tree)
7963 (^re_ "\\(\\*+\\)[ \t]*")
7964 (old-level (if (string-match org-outline-regexp-bol txt)
7965 (- (match-end 0) (match-beginning 0) 1)
7966 -1))
7967 (force-level (cond (level (prefix-numeric-value level))
7968 ((and (looking-at "[ \t]*$")
7969 (string-match
7970 "^\\*+$" (buffer-substring
7971 (point-at-bol) (point))))
7972 (- (match-end 1) (match-beginning 1)))
7973 ((and (bolp)
7974 (looking-at org-outline-regexp))
7975 (- (match-end 0) (point) 1))))
7976 (previous-level (save-excursion
7977 (condition-case nil
7978 (progn
7979 (outline-previous-visible-heading 1)
7980 (if (looking-at ^re_)
7981 (- (match-end 0) (match-beginning 0) 1)
7983 (error 1))))
7984 (next-level (save-excursion
7985 (condition-case nil
7986 (progn
7987 (or (looking-at org-outline-regexp)
7988 (outline-next-visible-heading 1))
7989 (if (looking-at ^re_)
7990 (- (match-end 0) (match-beginning 0) 1)
7992 (error 1))))
7993 (new-level (or force-level (max previous-level next-level)))
7994 (shift (if (or (= old-level -1)
7995 (= new-level -1)
7996 (= old-level new-level))
7998 (- new-level old-level)))
7999 (delta (if (> shift 0) -1 1))
8000 (func (if (> shift 0) 'org-demote 'org-promote))
8001 (org-odd-levels-only nil)
8002 beg end newend)
8003 ;; Remove the forced level indicator
8004 (if force-level
8005 (delete-region (point-at-bol) (point)))
8006 ;; Paste
8007 (beginning-of-line (if (bolp) 1 2))
8008 (setq beg (point))
8009 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8010 (insert-before-markers txt)
8011 (unless (string-match "\n\\'" txt) (insert "\n"))
8012 (setq newend (point))
8013 (org-reinstall-markers-in-region beg)
8014 (setq end (point))
8015 (goto-char beg)
8016 (skip-chars-forward " \t\n\r")
8017 (setq beg (point))
8018 (if (and (outline-invisible-p) visp)
8019 (save-excursion (outline-show-heading)))
8020 ;; Shift if necessary
8021 (unless (= shift 0)
8022 (save-restriction
8023 (narrow-to-region beg end)
8024 (while (not (= shift 0))
8025 (org-map-region func (point-min) (point-max))
8026 (setq shift (+ delta shift)))
8027 (goto-char (point-min))
8028 (setq newend (point-max))))
8029 (when (or (org-called-interactively-p 'interactive) for-yank)
8030 (message "Clipboard pasted as level %d subtree" new-level))
8031 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8032 kill-ring
8033 (eq org-subtree-clip (current-kill 0))
8034 org-subtree-clip-folded)
8035 ;; The tree was folded before it was killed/copied
8036 (hide-subtree))
8037 (and for-yank (goto-char newend)))))
8039 (defun org-kill-is-subtree-p (&optional txt)
8040 "Check if the current kill is an outline subtree, or a set of trees.
8041 Returns nil if kill does not start with a headline, or if the first
8042 headline level is not the largest headline level in the tree.
8043 So this will actually accept several entries of equal levels as well,
8044 which is OK for `org-paste-subtree'.
8045 If optional TXT is given, check this string instead of the current kill."
8046 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8047 (re (org-get-limited-outline-regexp))
8048 (^re (concat "^" re))
8049 (start-level (and kill
8050 (string-match
8051 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8052 kill)
8053 (- (match-end 2) (match-beginning 2) 1)))
8054 (start (1+ (or (match-beginning 2) -1))))
8055 (if (not start-level)
8056 (progn
8057 nil) ;; does not even start with a heading
8058 (catch 'exit
8059 (while (setq start (string-match ^re kill (1+ start)))
8060 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8061 (throw 'exit nil)))
8062 t))))
8064 (defvar org-markers-to-move nil
8065 "Markers that should be moved with a cut-and-paste operation.
8066 Those markers are stored together with their positions relative to
8067 the start of the region.")
8069 (defun org-save-markers-in-region (beg end)
8070 "Check markers in region.
8071 If these markers are between BEG and END, record their position relative
8072 to BEG, so that after moving the block of text, we can put the markers back
8073 into place.
8074 This function gets called just before an entry or tree gets cut from the
8075 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8076 called immediately, to move the markers with the entries."
8077 (setq org-markers-to-move nil)
8078 (when (featurep 'org-clock)
8079 (org-clock-save-markers-for-cut-and-paste beg end))
8080 (when (featurep 'org-agenda)
8081 (org-agenda-save-markers-for-cut-and-paste beg end)))
8083 (defun org-check-and-save-marker (marker beg end)
8084 "Check if MARKER is between BEG and END.
8085 If yes, remember the marker and the distance to BEG."
8086 (when (and (marker-buffer marker)
8087 (equal (marker-buffer marker) (current-buffer)))
8088 (if (and (>= marker beg) (< marker end))
8089 (push (cons marker (- marker beg)) org-markers-to-move))))
8091 (defun org-reinstall-markers-in-region (beg)
8092 "Move all remembered markers to their position relative to BEG."
8093 (mapc (lambda (x)
8094 (move-marker (car x) (+ beg (cdr x))))
8095 org-markers-to-move)
8096 (setq org-markers-to-move nil))
8098 (defun org-narrow-to-subtree ()
8099 "Narrow buffer to the current subtree."
8100 (interactive)
8101 (save-excursion
8102 (save-match-data
8103 (org-with-limited-levels
8104 (narrow-to-region
8105 (progn (org-back-to-heading t) (point))
8106 (progn (org-end-of-subtree t t)
8107 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8108 (point)))))))
8110 (defun org-narrow-to-block ()
8111 "Narrow buffer to the current block."
8112 (interactive)
8113 (let* ((case-fold-search t)
8114 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8115 "^[ \t]*#\\+end_.*")))
8116 (if blockp
8117 (narrow-to-region (car blockp) (cdr blockp))
8118 (error "Not in a block"))))
8120 (eval-when-compile
8121 (defvar org-property-drawer-re))
8123 (defvar org-property-start-re) ;; defined below
8124 (defun org-clone-subtree-with-time-shift (n &optional shift)
8125 "Clone the task (subtree) at point N times.
8126 The clones will be inserted as siblings.
8128 In interactive use, the user will be prompted for the number of
8129 clones to be produced, and for a time SHIFT, which may be a
8130 repeater as used in time stamps, for example `+3d'.
8132 When a valid repeater is given and the entry contains any time
8133 stamps, the clones will become a sequence in time, with time
8134 stamps in the subtree shifted for each clone produced. If SHIFT
8135 is nil or the empty string, time stamps will be left alone. The
8136 ID property of the original subtree is removed.
8138 If the original subtree did contain time stamps with a repeater,
8139 the following will happen:
8140 - the repeater will be removed in each clone
8141 - an additional clone will be produced, with the current, unshifted
8142 date(s) in the entry.
8143 - the original entry will be placed *after* all the clones, with
8144 repeater intact.
8145 - the start days in the repeater in the original entry will be shifted
8146 to past the last clone.
8147 In this way you can spell out a number of instances of a repeating task,
8148 and still retain the repeater to cover future instances of the task."
8149 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8150 (let (beg end template task idprop
8151 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8152 (drawer-re org-drawer-regexp))
8153 (if (not (and (integerp n) (> n 0)))
8154 (error "Invalid number of replications %s" n))
8155 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8156 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8157 shift)))
8158 (error "Invalid shift specification %s" shift))
8159 (when doshift
8160 (setq shift-n (string-to-number (match-string 1 shift))
8161 shift-what (cdr (assoc (match-string 2 shift)
8162 '(("d" . day) ("w" . week)
8163 ("m" . month) ("y" . year))))))
8164 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8165 (setq nmin 1 nmax n)
8166 (org-back-to-heading t)
8167 (setq beg (point))
8168 (setq idprop (org-entry-get nil "ID"))
8169 (org-end-of-subtree t t)
8170 (or (bolp) (insert "\n"))
8171 (setq end (point))
8172 (setq template (buffer-substring beg end))
8173 (when (and doshift
8174 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8175 (delete-region beg end)
8176 (setq end beg)
8177 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8178 (goto-char end)
8179 (loop for n from nmin to nmax do
8180 ;; prepare clone
8181 (with-temp-buffer
8182 (insert template)
8183 (org-mode)
8184 (goto-char (point-min))
8185 (org-show-subtree)
8186 (and idprop (if org-clone-delete-id
8187 (org-entry-delete nil "ID")
8188 (org-id-get-create t)))
8189 (unless (= n 0)
8190 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8191 (kill-whole-line))
8192 (goto-char (point-min))
8193 (while (re-search-forward drawer-re nil t)
8194 (mapc (lambda (d)
8195 (org-remove-empty-drawer-at d (point))) org-drawers)))
8196 (goto-char (point-min))
8197 (when doshift
8198 (while (re-search-forward org-ts-regexp-both nil t)
8199 (org-timestamp-change (* n shift-n) shift-what))
8200 (unless (= n n-no-remove)
8201 (goto-char (point-min))
8202 (while (re-search-forward org-ts-regexp nil t)
8203 (save-excursion
8204 (goto-char (match-beginning 0))
8205 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8206 (delete-region (match-beginning 1) (match-end 1)))))))
8207 (setq task (buffer-string)))
8208 (insert task))
8209 (goto-char beg)))
8211 ;;; Outline Sorting
8213 (defun org-sort (with-case)
8214 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8215 Optional argument WITH-CASE means sort case-sensitively."
8216 (interactive "P")
8217 (cond
8218 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8219 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8221 (org-call-with-arg 'org-sort-entries with-case))))
8223 (defun org-sort-remove-invisible (s)
8224 (remove-text-properties 0 (length s) org-rm-props s)
8225 (while (string-match org-bracket-link-regexp s)
8226 (setq s (replace-match (if (match-end 2)
8227 (match-string 3 s)
8228 (match-string 1 s)) t t s)))
8231 (defvar org-priority-regexp) ; defined later in the file
8233 (defvar org-after-sorting-entries-or-items-hook nil
8234 "Hook that is run after a bunch of entries or items have been sorted.
8235 When children are sorted, the cursor is in the parent line when this
8236 hook gets called. When a region or a plain list is sorted, the cursor
8237 will be in the first entry of the sorted region/list.")
8239 (defun org-sort-entries
8240 (&optional with-case sorting-type getkey-func compare-func property)
8241 "Sort entries on a certain level of an outline tree.
8242 If there is an active region, the entries in the region are sorted.
8243 Else, if the cursor is before the first entry, sort the top-level items.
8244 Else, the children of the entry at point are sorted.
8246 Sorting can be alphabetically, numerically, by date/time as given by
8247 a time stamp, by a property or by priority.
8249 The command prompts for the sorting type unless it has been given to the
8250 function through the SORTING-TYPE argument, which needs to be a character,
8251 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8252 precise meaning of each character:
8254 n Numerically, by converting the beginning of the entry/item to a number.
8255 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8256 o By order of TODO keywords.
8257 t By date/time, either the first active time stamp in the entry, or, if
8258 none exist, by the first inactive one.
8259 s By the scheduled date/time.
8260 d By deadline date/time.
8261 c By creation time, which is assumed to be the first inactive time stamp
8262 at the beginning of a line.
8263 p By priority according to the cookie.
8264 r By the value of a property.
8266 Capital letters will reverse the sort order.
8268 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8269 called with point at the beginning of the record. It must return either
8270 a string or a number that should serve as the sorting key for that record.
8272 Comparing entries ignores case by default. However, with an optional argument
8273 WITH-CASE, the sorting considers case as well."
8274 (interactive "P")
8275 (let ((case-func (if with-case 'identity 'downcase))
8276 (cmstr
8277 ;; The clock marker is lost when using `sort-subr', let's
8278 ;; store the clocking string.
8279 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8280 (save-excursion
8281 (goto-char org-clock-marker)
8282 (looking-back "^.*") (match-string-no-properties 0))))
8283 start beg end stars re re2
8284 txt what tmp)
8285 ;; Find beginning and end of region to sort
8286 (cond
8287 ((org-region-active-p)
8288 ;; we will sort the region
8289 (setq end (region-end)
8290 what "region")
8291 (goto-char (region-beginning))
8292 (if (not (org-at-heading-p)) (outline-next-heading))
8293 (setq start (point)))
8294 ((or (org-at-heading-p)
8295 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8296 ;; we will sort the children of the current headline
8297 (org-back-to-heading)
8298 (setq start (point)
8299 end (progn (org-end-of-subtree t t)
8300 (or (bolp) (insert "\n"))
8301 (org-back-over-empty-lines)
8302 (point))
8303 what "children")
8304 (goto-char start)
8305 (show-subtree)
8306 (outline-next-heading))
8308 ;; we will sort the top-level entries in this file
8309 (goto-char (point-min))
8310 (or (org-at-heading-p) (outline-next-heading))
8311 (setq start (point))
8312 (goto-char (point-max))
8313 (beginning-of-line 1)
8314 (when (looking-at ".*?\\S-")
8315 ;; File ends in a non-white line
8316 (end-of-line 1)
8317 (insert "\n"))
8318 (setq end (point-max))
8319 (setq what "top-level")
8320 (goto-char start)
8321 (show-all)))
8323 (setq beg (point))
8324 (if (>= beg end) (error "Nothing to sort"))
8326 (looking-at "\\(\\*+\\)")
8327 (setq stars (match-string 1)
8328 re (concat "^" (regexp-quote stars) " +")
8329 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8330 txt (buffer-substring beg end))
8331 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8332 (if (and (not (equal stars "*")) (string-match re2 txt))
8333 (error "Region to sort contains a level above the first entry"))
8335 (unless sorting-type
8336 (message
8337 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8338 [t]ime [s]cheduled [d]eadline [c]reated
8339 A/N/P/R/O/F/T/S/D/C means reversed:"
8340 what)
8341 (setq sorting-type (read-char-exclusive))
8343 (unless getkey-func
8344 (and (= (downcase sorting-type) ?f)
8345 (setq getkey-func
8346 (org-icompleting-read "Sort using function: "
8347 obarray 'fboundp t nil nil))
8348 (setq getkey-func (intern getkey-func))))
8350 (and (= (downcase sorting-type) ?r)
8351 (not property)
8352 (setq property
8353 (org-icompleting-read "Property: "
8354 (mapcar 'list (org-buffer-property-keys t))
8355 nil t))))
8357 (message "Sorting entries...")
8359 (save-restriction
8360 (narrow-to-region start end)
8361 (let ((dcst (downcase sorting-type))
8362 (case-fold-search nil)
8363 (now (current-time)))
8364 (sort-subr
8365 (/= dcst sorting-type)
8366 ;; This function moves to the beginning character of the "record" to
8367 ;; be sorted.
8368 (lambda nil
8369 (if (re-search-forward re nil t)
8370 (goto-char (match-beginning 0))
8371 (goto-char (point-max))))
8372 ;; This function moves to the last character of the "record" being
8373 ;; sorted.
8374 (lambda nil
8375 (save-match-data
8376 (condition-case nil
8377 (outline-forward-same-level 1)
8378 (error
8379 (goto-char (point-max))))))
8380 ;; This function returns the value that gets sorted against.
8381 (lambda nil
8382 (cond
8383 ((= dcst ?n)
8384 (if (looking-at org-complex-heading-regexp)
8385 (string-to-number (match-string 4))
8386 nil))
8387 ((= dcst ?a)
8388 (if (looking-at org-complex-heading-regexp)
8389 (funcall case-func (match-string 4))
8390 nil))
8391 ((= dcst ?t)
8392 (let ((end (save-excursion (outline-next-heading) (point))))
8393 (if (or (re-search-forward org-ts-regexp end t)
8394 (re-search-forward org-ts-regexp-both end t))
8395 (org-time-string-to-seconds (match-string 0))
8396 (org-float-time now))))
8397 ((= dcst ?c)
8398 (let ((end (save-excursion (outline-next-heading) (point))))
8399 (if (re-search-forward
8400 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8401 end t)
8402 (org-time-string-to-seconds (match-string 0))
8403 (org-float-time now))))
8404 ((= dcst ?s)
8405 (let ((end (save-excursion (outline-next-heading) (point))))
8406 (if (re-search-forward org-scheduled-time-regexp end t)
8407 (org-time-string-to-seconds (match-string 1))
8408 (org-float-time now))))
8409 ((= dcst ?d)
8410 (let ((end (save-excursion (outline-next-heading) (point))))
8411 (if (re-search-forward org-deadline-time-regexp end t)
8412 (org-time-string-to-seconds (match-string 1))
8413 (org-float-time now))))
8414 ((= dcst ?p)
8415 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8416 (string-to-char (match-string 2))
8417 org-default-priority))
8418 ((= dcst ?r)
8419 (or (org-entry-get nil property) ""))
8420 ((= dcst ?o)
8421 (if (looking-at org-complex-heading-regexp)
8422 (- 9999 (length (member (match-string 2)
8423 org-todo-keywords-1)))))
8424 ((= dcst ?f)
8425 (if getkey-func
8426 (progn
8427 (setq tmp (funcall getkey-func))
8428 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8429 tmp)
8430 (error "Invalid key function `%s'" getkey-func)))
8431 (t (error "Invalid sorting type `%c'" sorting-type))))
8433 (cond
8434 ((= dcst ?a) 'string<)
8435 ((= dcst ?f) compare-func)
8436 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8437 (run-hooks 'org-after-sorting-entries-or-items-hook)
8438 ;; Reset the clock marker if needed
8439 (when cmstr
8440 (save-excursion
8441 (goto-char start)
8442 (search-forward cmstr nil t)
8443 (move-marker org-clock-marker (point))))
8444 (message "Sorting entries...done")))
8446 (defun org-do-sort (table what &optional with-case sorting-type)
8447 "Sort TABLE of WHAT according to SORTING-TYPE.
8448 The user will be prompted for the SORTING-TYPE if the call to this
8449 function does not specify it. WHAT is only for the prompt, to indicate
8450 what is being sorted. The sorting key will be extracted from
8451 the car of the elements of the table.
8452 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8453 (unless sorting-type
8454 (message
8455 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8456 what)
8457 (setq sorting-type (read-char-exclusive)))
8458 (let ((dcst (downcase sorting-type))
8459 extractfun comparefun)
8460 ;; Define the appropriate functions
8461 (cond
8462 ((= dcst ?n)
8463 (setq extractfun 'string-to-number
8464 comparefun (if (= dcst sorting-type) '< '>)))
8465 ((= dcst ?a)
8466 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8467 (lambda(x) (downcase (org-sort-remove-invisible x))))
8468 comparefun (if (= dcst sorting-type)
8469 'string<
8470 (lambda (a b) (and (not (string< a b))
8471 (not (string= a b)))))))
8472 ((= dcst ?t)
8473 (setq extractfun
8474 (lambda (x)
8475 (if (or (string-match org-ts-regexp x)
8476 (string-match org-ts-regexp-both x))
8477 (org-float-time
8478 (org-time-string-to-time (match-string 0 x)))
8480 comparefun (if (= dcst sorting-type) '< '>)))
8481 (t (error "Invalid sorting type `%c'" sorting-type)))
8483 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8484 table)
8485 (lambda (a b) (funcall comparefun (car a) (car b))))))
8488 ;;; The orgstruct minor mode
8490 ;; Define a minor mode which can be used in other modes in order to
8491 ;; integrate the org-mode structure editing commands.
8493 ;; This is really a hack, because the org-mode structure commands use
8494 ;; keys which normally belong to the major mode. Here is how it
8495 ;; works: The minor mode defines all the keys necessary to operate the
8496 ;; structure commands, but wraps the commands into a function which
8497 ;; tests if the cursor is currently at a headline or a plain list
8498 ;; item. If that is the case, the structure command is used,
8499 ;; temporarily setting many Org-mode variables like regular
8500 ;; expressions for filling etc. However, when any of those keys is
8501 ;; used at a different location, function uses `key-binding' to look
8502 ;; up if the key has an associated command in another currently active
8503 ;; keymap (minor modes, major mode, global), and executes that
8504 ;; command. There might be problems if any of the keys is otherwise
8505 ;; used as a prefix key.
8507 (defcustom orgstruct-heading-prefix-regexp ""
8508 "Regexp that matches the custom prefix of Org headlines in
8509 orgstruct(++)-mode."
8510 :group 'org
8511 :type 'string)
8512 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8514 (defcustom orgstruct-setup-hook nil
8515 "Hook run after orgstruct-mode-map is filled."
8516 :group 'org
8517 :type 'hook)
8519 (defvar orgstruct-initialized nil)
8521 (defvar org-local-vars nil
8522 "List of local variables, for use by `orgstruct-mode'.")
8524 ;;;###autoload
8525 (define-minor-mode orgstruct-mode
8526 "Toggle the minor mode `orgstruct-mode'.
8527 This mode is for using Org-mode structure commands in other
8528 modes. The following keys behave as if Org-mode were active, if
8529 the cursor is on a headline, or on a plain list item (both as
8530 defined by Org-mode)."
8531 nil " OrgStruct" (make-sparse-keymap)
8532 (when orgstruct-mode
8533 (org-load-modules-maybe)
8534 (unless orgstruct-initialized
8535 (orgstruct-setup)
8536 (setq orgstruct-initialized t))))
8538 ;;;###autoload
8539 (defun turn-on-orgstruct ()
8540 "Unconditionally turn on `orgstruct-mode'."
8541 (orgstruct-mode 1))
8543 (defvar org-fb-vars nil)
8544 (make-variable-buffer-local 'org-fb-vars)
8545 (defun orgstruct++-mode (&optional arg)
8546 "Toggle `orgstruct-mode', the enhanced version of it.
8547 In addition to setting orgstruct-mode, this also exports all
8548 indentation and autofilling variables from org-mode into the
8549 buffer. It will also recognize item context in multiline items."
8550 (interactive "P")
8551 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8552 (if (< arg 1)
8553 (progn (orgstruct-mode -1)
8554 (mapc (lambda(v)
8555 (org-set-local (car v)
8556 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8557 org-fb-vars))
8558 (orgstruct-mode 1)
8559 (setq org-fb-vars nil)
8560 (let (var val)
8561 (mapc
8562 (lambda (x)
8563 (when (string-match
8564 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8565 (symbol-name (car x)))
8566 (setq var (car x) val (nth 1 x))
8567 (push (list var `(quote ,(eval var))) org-fb-vars)
8568 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8569 org-local-vars)
8570 (org-set-local 'orgstruct-is-++ t))))
8572 (defvar orgstruct-is-++ nil
8573 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8574 (make-variable-buffer-local 'orgstruct-is-++)
8576 ;;;###autoload
8577 (defun turn-on-orgstruct++ ()
8578 "Unconditionally turn on `orgstruct++-mode'."
8579 (orgstruct++-mode 1))
8581 (defun orgstruct-error ()
8582 "Error when there is no default binding for a structure key."
8583 (interactive)
8584 (error "This key has no function outside structure elements"))
8586 (defun orgstruct-setup ()
8587 "Setup orgstruct keymap."
8588 (dolist (f
8589 '("org-meta"
8590 "org-shiftmeta"
8591 org-shifttab
8592 org-backward-element
8593 org-backward-heading-same-level
8594 org-ctrl-c-ret
8595 org-cycle
8596 org-forward-heading-same-level
8597 org-insert-heading
8598 org-insert-heading-respect-content
8599 org-kill-note-or-show-branches
8600 org-mark-subtree
8601 org-narrow-to-subtree
8602 org-promote-subtree
8603 org-reveal
8604 org-show-subtree
8605 org-sort
8606 org-up-element
8607 outline-demote
8608 outline-next-visible-heading
8609 outline-previous-visible-heading
8610 outline-promote
8611 outline-up-heading
8612 show-children))
8613 (dolist (f (if (stringp f)
8614 (let ((flist))
8615 (dolist (postfix
8616 '("-return" "tab" "left" "right" "up" "down")
8617 flist)
8618 (let ((f (intern (concat f postfix))))
8619 (when (fboundp f)
8620 (push f flist)))))
8621 (list f)))
8622 (dolist (binding (nconc (where-is-internal f org-mode-map)
8623 (where-is-internal f outline-mode-map)))
8624 ;; TODO use local-function-key-map
8625 (dolist (rep '(("<tab>" . "TAB")
8626 ("<ret>" . "RET")
8627 ("<esc>" . "ESC")
8628 ("<del>" . "DEL")))
8629 (setq binding (read-kbd-macro (replace-regexp-in-string
8630 (regexp-quote (car rep))
8631 (cdr rep)
8632 (key-description binding)))))
8633 (let ((key (lookup-key orgstruct-mode-map binding)))
8634 (when (or (not key) (numberp key))
8635 (org-defkey orgstruct-mode-map
8636 binding
8637 (orgstruct-make-binding f binding)))))))
8638 (run-hooks 'orgstruct-setup-hook))
8640 (defun orgstruct-make-binding (fun key)
8641 "Create a function for binding in the structure minor mode.
8642 FUN is the command to call inside a table. KEY is the key that
8643 should be checked in for a command to execute outside of tables."
8644 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8645 (let ((nname name)
8646 (i 0))
8647 (while (fboundp (intern nname))
8648 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8649 (setq name (intern nname)))
8650 (eval
8651 `(defun ,name (arg)
8652 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8653 "Outside of structure, run the binding of `"
8654 (key-description key) "'.")
8655 (interactive "p")
8656 (unless
8657 (let* ((org-heading-regexp
8658 (concat "^"
8659 orgstruct-heading-prefix-regexp
8660 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8661 (org-outline-regexp
8662 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8663 (org-outline-regexp-bol
8664 (concat "^" org-outline-regexp))
8665 (outline-regexp org-outline-regexp)
8666 (outline-heading-end-regexp "\n")
8667 (outline-level 'outline-level)
8668 (outline-heading-alist))
8669 (when (org-context-p 'headline 'item
8670 ,(when (memq fun '(org-insert-heading))
8671 '(when orgstruct-is-++
8672 'item-body)))
8673 (org-run-like-in-org-mode ',fun)
8675 (let ((binding (let ((orgstruct-mode)) (key-binding ,key))))
8676 (if (keymapp binding)
8677 (set-temporary-overlay-map binding)
8678 (call-interactively
8679 (or binding 'orgstruct-error)))))))
8680 name))
8682 (defun org-contextualize-keys (alist contexts)
8683 "Return valid elements in ALIST depending on CONTEXTS.
8685 `org-agenda-custom-commands' or `org-capture-templates' are the
8686 values used for ALIST, and `org-agenda-custom-commands-contexts'
8687 or `org-capture-templates-contexts' are the associated contexts
8688 definitions."
8689 (let ((contexts
8690 ;; normalize contexts
8691 (mapcar
8692 (lambda(c) (cond ((listp (cadr c))
8693 (list (car c) (car c) (cadr c)))
8694 ((string= "" (cadr c))
8695 (list (car c) (car c) (caddr c)))
8696 (t c))) contexts))
8697 (a alist) c r s)
8698 ;; loop over all commands or templates
8699 (while (setq c (pop a))
8700 (let (vrules repl)
8701 (cond
8702 ((not (assoc (car c) contexts))
8703 (push c r))
8704 ((and (assoc (car c) contexts)
8705 (setq vrules (org-contextualize-validate-key
8706 (car c) contexts)))
8707 (mapc (lambda (vr)
8708 (when (not (equal (car vr) (cadr vr)))
8709 (setq repl vr))) vrules)
8710 (if (not repl) (push c r)
8711 (push (cadr repl) s)
8712 (push
8713 (cons (car c)
8714 (cdr (or (assoc (cadr repl) alist)
8715 (error "Undefined key `%s' as contextual replacement for `%s'"
8716 (cadr repl) (car c)))))
8717 r))))))
8718 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8719 (delq
8721 (delete-dups
8722 (mapcar (lambda (x)
8723 (let ((tpl (car x)))
8724 (when (not (delq
8726 (mapcar (lambda(y)
8727 (equal y tpl)) s))) x)))
8728 (reverse r))))))
8730 (defun org-contextualize-validate-key (key contexts)
8731 "Check CONTEXTS for agenda or capture KEY."
8732 (let (r rr res)
8733 (while (setq r (pop contexts))
8734 (mapc
8735 (lambda (rr)
8736 (when
8737 (and (equal key (car r))
8738 (if (functionp rr) (funcall rr)
8739 (or (and (eq (car rr) 'in-file)
8740 (buffer-file-name)
8741 (string-match (cdr rr) (buffer-file-name)))
8742 (and (eq (car rr) 'in-mode)
8743 (string-match (cdr rr) (symbol-name major-mode)))
8744 (and (eq (car rr) 'in-buffer)
8745 (string-match (cdr rr) (buffer-name)))
8746 (when (and (eq (car rr) 'not-in-file)
8747 (buffer-file-name))
8748 (not (string-match (cdr rr) (buffer-file-name))))
8749 (when (eq (car rr) 'not-in-mode)
8750 (not (string-match (cdr rr) (symbol-name major-mode))))
8751 (when (eq (car rr) 'not-in-buffer)
8752 (not (string-match (cdr rr) (buffer-name)))))))
8753 (push r res)))
8754 (car (last r))))
8755 (delete-dups (delq nil res))))
8757 (defun org-context-p (&rest contexts)
8758 "Check if local context is any of CONTEXTS.
8759 Possible values in the list of contexts are `table', `headline', and `item'."
8760 (let ((pos (point)))
8761 (goto-char (point-at-bol))
8762 (prog1 (or (and (memq 'table contexts)
8763 (looking-at "[ \t]*|"))
8764 (and (memq 'headline contexts)
8765 (looking-at org-outline-regexp))
8766 (and (memq 'item contexts)
8767 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8768 (and (memq 'item-body contexts)
8769 (org-in-item-p)))
8770 (goto-char pos))))
8772 (defun org-get-local-variables ()
8773 "Return a list of all local variables in an Org mode buffer."
8774 (let (varlist)
8775 (with-current-buffer (get-buffer-create "*Org tmp*")
8776 (erase-buffer)
8777 (org-mode)
8778 (setq varlist (buffer-local-variables)))
8779 (kill-buffer "*Org tmp*")
8780 (delq nil
8781 (mapcar
8782 (lambda (x)
8783 (setq x
8784 (if (symbolp x)
8785 (list x)
8786 (list (car x) (cdr x))))
8787 (if (and (not (get (car x) 'org-state))
8788 (string-match
8789 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8790 (symbol-name (car x))))
8791 x nil))
8792 varlist))))
8794 (defun org-clone-local-variables (from-buffer &optional regexp)
8795 "Clone local variables from FROM-BUFFER.
8796 Optional argument REGEXP selects variables to clone."
8797 (mapc
8798 (lambda (pair)
8799 (and (symbolp (car pair))
8800 (or (null regexp)
8801 (string-match regexp (symbol-name (car pair))))
8802 (set (make-local-variable (car pair))
8803 (cdr pair))))
8804 (buffer-local-variables from-buffer)))
8806 ;;;###autoload
8807 (defun org-run-like-in-org-mode (cmd)
8808 "Run a command, pretending that the current buffer is in Org-mode.
8809 This will temporarily bind local variables that are typically bound in
8810 Org-mode to the values they have in Org-mode, and then interactively
8811 call CMD."
8812 (org-load-modules-maybe)
8813 (unless org-local-vars
8814 (setq org-local-vars (org-get-local-variables)))
8815 (let (symbols values)
8816 (dolist (var org-local-vars)
8817 (when (or (not (boundp (car var)))
8818 (eq (symbol-value (car var))
8819 (default-value (car var))))
8820 (push (car var) symbols)
8821 (push (cadr var) values)))
8822 (progv symbols values
8823 (call-interactively cmd))))
8825 ;;;; Archiving
8827 (defun org-get-category (&optional pos force-refresh)
8828 "Get the category applying to position POS."
8829 (save-match-data
8830 (if force-refresh (org-refresh-category-properties))
8831 (let ((pos (or pos (point))))
8832 (or (get-text-property pos 'org-category)
8833 (progn (org-refresh-category-properties)
8834 (get-text-property pos 'org-category))))))
8836 (defun org-refresh-category-properties ()
8837 "Refresh category text properties in the buffer."
8838 (let ((case-fold-search t)
8839 (inhibit-read-only t)
8840 (def-cat (cond
8841 ((null org-category)
8842 (if buffer-file-name
8843 (file-name-sans-extension
8844 (file-name-nondirectory buffer-file-name))
8845 "???"))
8846 ((symbolp org-category) (symbol-name org-category))
8847 (t org-category)))
8848 beg end cat pos optionp)
8849 (org-unmodified
8850 (save-excursion
8851 (save-restriction
8852 (widen)
8853 (goto-char (point-min))
8854 (put-text-property (point) (point-max) 'org-category def-cat)
8855 (while (re-search-forward
8856 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8857 (setq pos (match-end 0)
8858 optionp (equal (char-after (match-beginning 0)) ?#)
8859 cat (org-trim (match-string 2)))
8860 (if optionp
8861 (setq beg (point-at-bol) end (point-max))
8862 (org-back-to-heading t)
8863 (setq beg (point) end (org-end-of-subtree t t)))
8864 (put-text-property beg end 'org-category cat)
8865 (put-text-property beg end 'org-category-position beg)
8866 (goto-char pos)))))))
8868 (defun org-refresh-properties (dprop tprop)
8869 "Refresh buffer text properties.
8870 DPROP is the drawer property and TPROP is the corresponding text
8871 property to set."
8872 (let ((case-fold-search t)
8873 (inhibit-read-only t) p)
8874 (org-unmodified
8875 (save-excursion
8876 (save-restriction
8877 (widen)
8878 (goto-char (point-min))
8879 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8880 (setq p (org-match-string-no-properties 1))
8881 (save-excursion
8882 (org-back-to-heading t)
8883 (put-text-property
8884 (point-at-bol) (point-at-eol) tprop p))))))))
8887 ;;;; Link Stuff
8889 ;;; Link abbreviations
8891 (defun org-link-expand-abbrev (link)
8892 "Apply replacements as defined in `org-link-abbrev-alist'."
8893 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8894 (let* ((key (match-string 1 link))
8895 (as (or (assoc key org-link-abbrev-alist-local)
8896 (assoc key org-link-abbrev-alist)))
8897 (tag (and (match-end 2) (match-string 3 link)))
8898 rpl)
8899 (if (not as)
8900 link
8901 (setq rpl (cdr as))
8902 (cond
8903 ((symbolp rpl) (funcall rpl tag))
8904 ((string-match "%(\\([^)]+\\))" rpl)
8905 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8906 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8907 ((string-match "%h" rpl)
8908 (replace-match (url-hexify-string (or tag "")) t t rpl))
8909 (t (concat rpl tag)))))
8910 link))
8912 ;;; Storing and inserting links
8914 (defvar org-insert-link-history nil
8915 "Minibuffer history for links inserted with `org-insert-link'.")
8917 (defvar org-stored-links nil
8918 "Contains the links stored with `org-store-link'.")
8920 (defvar org-store-link-plist nil
8921 "Plist with info about the most recently link created with `org-store-link'.")
8923 (defvar org-link-protocols nil
8924 "Link protocols added to Org-mode using `org-add-link-type'.")
8926 (defvar org-store-link-functions nil
8927 "List of functions that are called to create and store a link.
8928 Each function will be called in turn until one returns a non-nil
8929 value. Each function should check if it is responsible for creating
8930 this link (for example by looking at the major mode).
8931 If not, it must exit and return nil.
8932 If yes, it should return a non-nil value after a calling
8933 `org-store-link-props' with a list of properties and values.
8934 Special properties are:
8936 :type The link prefix, like \"http\". This must be given.
8937 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8938 This is obligatory as well.
8939 :description Optional default description for the second pair
8940 of brackets in an Org-mode link. The user can still change
8941 this when inserting this link into an Org-mode buffer.
8943 In addition to these, any additional properties can be specified
8944 and then used in capture templates.")
8946 (defun org-add-link-type (type &optional follow export)
8947 "Add TYPE to the list of `org-link-types'.
8948 Re-compute all regular expressions depending on `org-link-types'
8950 FOLLOW and EXPORT are two functions.
8952 FOLLOW should take the link path as the single argument and do whatever
8953 is necessary to follow the link, for example find a file or display
8954 a mail message.
8956 EXPORT should format the link path for export to one of the export formats.
8957 It should be a function accepting three arguments:
8959 path the path of the link, the text after the prefix (like \"http:\")
8960 desc the description of the link, if any, or a description added by
8961 org-export-normalize-links if there is none
8962 format the export format, a symbol like `html' or `latex' or `ascii'..
8964 The function may use the FORMAT information to return different values
8965 depending on the format. The return value will be put literally into
8966 the exported file. If the return value is nil, this means Org should
8967 do what it normally does with links which do not have EXPORT defined.
8969 Org-mode has a built-in default for exporting links. If you are happy with
8970 this default, there is no need to define an export function for the link
8971 type. For a simple example of an export function, see `org-bbdb.el'."
8972 (add-to-list 'org-link-types type t)
8973 (org-make-link-regexps)
8974 (if (assoc type org-link-protocols)
8975 (setcdr (assoc type org-link-protocols) (list follow export))
8976 (push (list type follow export) org-link-protocols)))
8978 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8979 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8981 ;;;###autoload
8982 (defun org-store-link (arg)
8983 "\\<org-mode-map>Store an org-link to the current location.
8984 This link is added to `org-stored-links' and can later be inserted
8985 into an org-buffer with \\[org-insert-link].
8987 For some link types, a prefix arg is interpreted.
8988 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8989 For file links, arg negates `org-context-in-file-links'.
8991 A double prefix arg force skipping storing functions that are not
8992 part of Org's core."
8993 (interactive "P")
8994 (org-load-modules-maybe)
8995 (setq org-store-link-plist nil) ; reset
8996 (org-with-limited-levels
8997 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8998 (cond
8999 ((and (not (equal arg '(16)))
9000 (setq sfuns
9001 (delq
9002 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9003 org-store-link-functions))
9004 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9005 (or (and (cdr sfuns)
9006 (funcall (intern
9007 (completing-read "Which function for creating the link? "
9008 sfunsn t (car sfunsn)))))
9009 (funcall (caar sfuns)))
9010 (setq link (plist-get org-store-link-plist :link)
9011 desc (or (plist-get org-store-link-plist :description) link))))
9012 ((org-src-edit-buffer-p)
9013 (let (label gc)
9014 (while (or (not label)
9015 (save-excursion
9016 (save-restriction
9017 (widen)
9018 (goto-char (point-min))
9019 (re-search-forward
9020 (regexp-quote (format org-coderef-label-format label))
9021 nil t))))
9022 (when label (message "Label exists already") (sit-for 2))
9023 (setq label (read-string "Code line label: " label)))
9024 (end-of-line 1)
9025 (setq link (format org-coderef-label-format label))
9026 (setq gc (- 79 (length link)))
9027 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9028 (insert link)
9029 (setq link (concat "(" label ")") desc nil)))
9031 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9032 ;; We are in the agenda, link to referenced location
9033 (let ((m (or (get-text-property (point) 'org-hd-marker)
9034 (get-text-property (point) 'org-marker))))
9035 (when m
9036 (org-with-point-at m
9037 (setq agenda-link
9038 (if (org-called-interactively-p 'any)
9039 (call-interactively 'org-store-link)
9040 (org-store-link nil)))))))
9042 ((eq major-mode 'calendar-mode)
9043 (let ((cd (calendar-cursor-to-date)))
9044 (setq link
9045 (format-time-string
9046 (car org-time-stamp-formats)
9047 (apply 'encode-time
9048 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9049 nil nil nil))))
9050 (org-store-link-props :type "calendar" :date cd)))
9052 ((eq major-mode 'help-mode)
9053 (setq link (concat "help:" (save-excursion
9054 (goto-char (point-min))
9055 (looking-at "^[^ ]+")
9056 (match-string 0))))
9057 (org-store-link-props :type "help"))
9059 ((eq major-mode 'w3-mode)
9060 (setq cpltxt (if (and (buffer-name)
9061 (not (string-match "Untitled" (buffer-name))))
9062 (buffer-name)
9063 (url-view-url t))
9064 link (url-view-url t))
9065 (org-store-link-props :type "w3" :url (url-view-url t)))
9067 ((setq search (run-hook-with-args-until-success
9068 'org-create-file-search-functions))
9069 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9070 "::" search))
9071 (setq cpltxt (or description link)))
9073 ((eq major-mode 'image-mode)
9074 (setq cpltxt (concat "file:"
9075 (abbreviate-file-name buffer-file-name))
9076 link cpltxt)
9077 (org-store-link-props :type "image" :file buffer-file-name))
9079 ((eq major-mode 'dired-mode)
9080 ;; link to the file in the current line
9081 (let ((file (dired-get-filename nil t)))
9082 (setq file (if file
9083 (abbreviate-file-name
9084 (expand-file-name (dired-get-filename nil t)))
9085 ;; otherwise, no file so use current directory.
9086 default-directory))
9087 (setq cpltxt (concat "file:" file)
9088 link cpltxt)))
9090 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9091 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9092 (cond
9093 ((org-in-regexp "<<\\(.*?\\)>>")
9094 (setq cpltxt
9095 (concat "file:"
9096 (abbreviate-file-name
9097 (buffer-file-name (buffer-base-buffer)))
9098 "::" (match-string 1))
9099 link cpltxt))
9100 ((and (featurep 'org-id)
9101 (or (eq org-id-link-to-org-use-id t)
9102 (and (org-called-interactively-p 'any)
9103 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9104 (and (eq org-id-link-to-org-use-id
9105 'create-if-interactive-and-no-custom-id)
9106 (not custom-id))))
9107 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9108 ;; We can make a link using the ID.
9109 (setq link (condition-case nil
9110 (prog1 (org-id-store-link)
9111 (setq desc (plist-get org-store-link-plist :description)))
9112 (error
9113 ;; probably before first headline, link to file only
9114 (concat "file:"
9115 (abbreviate-file-name
9116 (buffer-file-name (buffer-base-buffer))))))))
9118 ;; Just link to current headline
9119 (setq cpltxt (concat "file:"
9120 (abbreviate-file-name
9121 (buffer-file-name (buffer-base-buffer)))))
9122 ;; Add a context search string
9123 (when (org-xor org-context-in-file-links arg)
9124 (let* ((ee (org-element-at-point))
9125 (et (org-element-type ee))
9126 (ev (plist-get (cadr ee) :value)))
9127 (setq txt (cond
9128 ((org-at-heading-p) nil)
9129 ((eq et 'keyword) ev)
9130 ((org-region-active-p)
9131 (buffer-substring (region-beginning) (region-end)))))
9132 (when (or (null txt) (string-match "\\S-" txt))
9133 (setq cpltxt
9134 (concat cpltxt "::"
9135 (condition-case nil
9136 (org-make-org-heading-search-string txt)
9137 (error "")))
9138 desc (or (and (eq et 'keyword) ev)
9139 (nth 4 (ignore-errors (org-heading-components)))
9140 "NONE")))))
9141 (if (string-match "::\\'" cpltxt)
9142 (setq cpltxt (substring cpltxt 0 -2)))
9143 (setq link cpltxt))))
9145 ((buffer-file-name (buffer-base-buffer))
9146 ;; Just link to this file here.
9147 (setq cpltxt (concat "file:"
9148 (abbreviate-file-name
9149 (buffer-file-name (buffer-base-buffer)))))
9150 ;; Add a context string
9151 (when (org-xor org-context-in-file-links arg)
9152 (setq txt (if (org-region-active-p)
9153 (buffer-substring (region-beginning) (region-end))
9154 (buffer-substring (point-at-bol) (point-at-eol))))
9155 ;; Only use search option if there is some text.
9156 (when (string-match "\\S-" txt)
9157 (setq cpltxt
9158 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9159 desc "NONE")))
9160 (setq link cpltxt))
9162 ((org-called-interactively-p 'interactive)
9163 (user-error "No method for storing a link from this buffer"))
9165 (t (setq link nil)))
9167 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9168 (setq link (or link cpltxt)
9169 desc (or desc cpltxt))
9170 (cond ((equal desc "NONE") (setq desc nil))
9171 ((string-match org-bracket-link-regexp desc)
9172 (setq desc (replace-regexp-in-string
9173 org-bracket-link-regexp
9174 (concat "\\3" (if (equal (length (match-string 0 desc))
9175 (length desc)) "*" "")) desc))))
9177 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9178 (progn
9179 (setq org-stored-links
9180 (cons (list link desc) org-stored-links))
9181 (message "Stored: %s" (or desc link))
9182 (when custom-id
9183 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9184 "::#" custom-id))
9185 (setq org-stored-links
9186 (cons (list link desc) org-stored-links))))
9187 (or agenda-link (and link (org-make-link-string link desc)))))))
9189 (defun org-store-link-props (&rest plist)
9190 "Store link properties, extract names and addresses."
9191 (let (x adr)
9192 (when (setq x (plist-get plist :from))
9193 (setq adr (mail-extract-address-components x))
9194 (setq plist (plist-put plist :fromname (car adr)))
9195 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9196 (when (setq x (plist-get plist :to))
9197 (setq adr (mail-extract-address-components x))
9198 (setq plist (plist-put plist :toname (car adr)))
9199 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9200 (let ((from (plist-get plist :from))
9201 (to (plist-get plist :to)))
9202 (when (and from to org-from-is-user-regexp)
9203 (setq plist
9204 (plist-put plist :fromto
9205 (if (string-match org-from-is-user-regexp from)
9206 (concat "to %t")
9207 (concat "from %f"))))))
9208 (setq org-store-link-plist plist))
9210 (defun org-add-link-props (&rest plist)
9211 "Add these properties to the link property list."
9212 (let (key value)
9213 (while plist
9214 (setq key (pop plist) value (pop plist))
9215 (setq org-store-link-plist
9216 (plist-put org-store-link-plist key value)))))
9218 (defun org-email-link-description (&optional fmt)
9219 "Return the description part of an email link.
9220 This takes information from `org-store-link-plist' and formats it
9221 according to FMT (default from `org-email-link-description-format')."
9222 (setq fmt (or fmt org-email-link-description-format))
9223 (let* ((p org-store-link-plist)
9224 (to (plist-get p :toaddress))
9225 (from (plist-get p :fromaddress))
9226 (table
9227 (list
9228 (cons "%c" (plist-get p :fromto))
9229 (cons "%F" (plist-get p :from))
9230 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9231 (cons "%T" (plist-get p :to))
9232 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9233 (cons "%s" (plist-get p :subject))
9234 (cons "%d" (plist-get p :date))
9235 (cons "%m" (plist-get p :message-id)))))
9236 (when (string-match "%c" fmt)
9237 ;; Check if the user wrote this message
9238 (if (and org-from-is-user-regexp from to
9239 (save-match-data (string-match org-from-is-user-regexp from)))
9240 (setq fmt (replace-match "to %t" t t fmt))
9241 (setq fmt (replace-match "from %f" t t fmt))))
9242 (org-replace-escapes fmt table)))
9244 (defun org-make-org-heading-search-string (&optional string)
9245 "Make search string for the current headline or STRING."
9246 (let ((s (or string
9247 (and (derived-mode-p 'org-mode)
9248 (save-excursion
9249 (org-back-to-heading t)
9250 (plist-get (cadr (org-element-at-point))
9251 :raw-value)))))
9252 (lines org-context-in-file-links))
9253 (or string (setq s (concat "*" s))) ; Add * for headlines
9254 (when (and string (integerp lines) (> lines 0))
9255 (let ((slines (org-split-string s "\n")))
9256 (when (< lines (length slines))
9257 (setq s (mapconcat
9258 'identity
9259 (reverse (nthcdr (- (length slines) lines)
9260 (reverse slines))) "\n")))))
9261 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9263 (defun org-make-link-string (link &optional description)
9264 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9265 (unless (string-match "\\S-" link)
9266 (error "Empty link"))
9267 (when (and description
9268 (stringp description)
9269 (not (string-match "\\S-" description)))
9270 (setq description nil))
9271 (when (stringp description)
9272 ;; Remove brackets from the description, they are fatal.
9273 (while (string-match "\\[" description)
9274 (setq description (replace-match "{" t t description)))
9275 (while (string-match "\\]" description)
9276 (setq description (replace-match "}" t t description))))
9277 (when (equal link description)
9278 ;; No description needed, it is identical
9279 (setq description nil))
9280 (when (and (not description)
9281 (not (string-match (org-image-file-name-regexp) link))
9282 (not (equal link (org-link-escape link))))
9283 (setq description (org-extract-attributes link)))
9284 (setq link
9285 (cond ((string-match (org-image-file-name-regexp) link) link)
9286 ((string-match org-link-types-re link)
9287 (concat (match-string 1 link)
9288 (org-link-escape (substring link (match-end 1)))))
9289 (t (org-link-escape link))))
9290 (concat "[[" link "]"
9291 (if description (concat "[" description "]") "")
9292 "]"))
9294 (defconst org-link-escape-chars
9295 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9296 "List of characters that should be escaped in link.
9297 This is the list that is used for internal purposes.")
9299 (defconst org-link-escape-chars-browser
9300 '(?\ )
9301 "List of escapes for characters that are problematic in links.
9302 This is the list that is used before handing over to the browser.")
9304 (defun org-link-escape (text &optional table merge)
9305 "Return percent escaped representation of TEXT.
9306 TEXT is a string with the text to escape.
9307 Optional argument TABLE is a list with characters that should be
9308 escaped. When nil, `org-link-escape-chars' is used.
9309 If optional argument MERGE is set, merge TABLE into
9310 `org-link-escape-chars'."
9311 (cond
9312 ((and table merge)
9313 (mapc (lambda (defchr)
9314 (unless (member defchr table)
9315 (setq table (cons defchr table)))) org-link-escape-chars))
9316 ((null table)
9317 (setq table org-link-escape-chars)))
9318 (mapconcat
9319 (lambda (char)
9320 (if (or (member char table)
9321 (and (or (< char 32) (= char 37) (> char 126))
9322 org-url-hexify-p))
9323 (mapconcat (lambda (sequence-element)
9324 (format "%%%.2X" sequence-element))
9325 (or (encode-coding-char char 'utf-8)
9326 (error "Unable to percent escape character: %s"
9327 (char-to-string char))) "")
9328 (char-to-string char))) text ""))
9330 (defun org-link-unescape (str)
9331 "Unhex hexified Unicode strings as returned from the JavaScript function
9332 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9333 (unless (and (null str) (string= "" str))
9334 (let ((pos 0) (case-fold-search t) unhexed)
9335 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9336 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9337 (setq str (replace-match unhexed t t str))
9338 (setq pos (+ pos (length unhexed))))))
9339 str)
9341 (defun org-link-unescape-compound (hex)
9342 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9343 Note: this function also decodes single byte encodings like
9344 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9345 (save-match-data
9346 (let* ((bytes (cdr (split-string hex "%")))
9347 (ret "")
9348 (eat 0)
9349 (sum 0))
9350 (while bytes
9351 (let* ((val (string-to-number (pop bytes) 16))
9352 (shift-xor
9353 (if (= 0 eat)
9354 (cond
9355 ((>= val 252) (cons 6 252))
9356 ((>= val 248) (cons 5 248))
9357 ((>= val 240) (cons 4 240))
9358 ((>= val 224) (cons 3 224))
9359 ((>= val 192) (cons 2 192))
9360 (t (cons 0 0)))
9361 (cons 6 128))))
9362 (if (>= val 192) (setq eat (car shift-xor)))
9363 (setq val (logxor val (cdr shift-xor)))
9364 (setq sum (+ (lsh sum (car shift-xor)) val))
9365 (if (> eat 0) (setq eat (- eat 1)))
9366 (cond
9367 ((= 0 eat) ;multi byte
9368 (setq ret (concat ret (org-char-to-string sum)))
9369 (setq sum 0))
9370 ((not bytes) ; single byte(s)
9371 (setq ret (org-link-unescape-single-byte-sequence hex))))
9372 )) ;; end (while bytes
9373 ret )))
9375 (defun org-link-unescape-single-byte-sequence (hex)
9376 "Unhexify hex-encoded single byte character sequences."
9377 (mapconcat (lambda (byte)
9378 (char-to-string (string-to-number byte 16)))
9379 (cdr (split-string hex "%")) ""))
9381 (defun org-xor (a b)
9382 "Exclusive or."
9383 (if a (not b) b))
9385 (defun org-fixup-message-id-for-http (s)
9386 "Replace special characters in a message id, so it can be used in an http query."
9387 (when (string-match "%" s)
9388 (setq s (mapconcat (lambda (c)
9389 (if (eq c ?%)
9390 "%25"
9391 (char-to-string c)))
9392 s "")))
9393 (while (string-match "<" s)
9394 (setq s (replace-match "%3C" t t s)))
9395 (while (string-match ">" s)
9396 (setq s (replace-match "%3E" t t s)))
9397 (while (string-match "@" s)
9398 (setq s (replace-match "%40" t t s)))
9401 (defun org-link-prettify (link)
9402 "Return a human-readable representation of LINK.
9403 The car of LINK must be a raw link the cdr of LINK must be either
9404 a link description or nil."
9405 (let ((desc (or (cadr link) "<no description>")))
9406 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9407 "<" (car link) ">")))
9409 ;;;###autoload
9410 (defun org-insert-link-global ()
9411 "Insert a link like Org-mode does.
9412 This command can be called in any mode to insert a link in Org-mode syntax."
9413 (interactive)
9414 (org-load-modules-maybe)
9415 (org-run-like-in-org-mode 'org-insert-link))
9417 (defun org-insert-all-links (&optional keep)
9418 "Insert all links in `org-stored-links'."
9419 (interactive "P")
9420 (let ((links (copy-sequence org-stored-links)) l)
9421 (while (setq l (if keep (pop links) (pop org-stored-links)))
9422 (insert "- ")
9423 (org-insert-link nil (car l) (cadr l))
9424 (insert "\n"))))
9426 (defun org-link-fontify-links-to-this-file ()
9427 "Fontify links to the current file in `org-stored-links'."
9428 (let ((f (buffer-file-name)) a b)
9429 (setq a (mapcar (lambda(l)
9430 (let ((ll (car l)))
9431 (when (and (string-match "^file:\\(.+\\)::" ll)
9432 (equal f (expand-file-name (match-string 1 ll))))
9433 ll)))
9434 org-stored-links))
9435 (when (featurep 'org-id)
9436 (setq b (mapcar (lambda(l)
9437 (let ((ll (car l)))
9438 (when (and (string-match "^id:\\(.+\\)$" ll)
9439 (equal f (expand-file-name
9440 (or (org-id-find-id-file
9441 (match-string 1 ll)) ""))))
9442 ll)))
9443 org-stored-links)))
9444 (mapcar (lambda(l)
9445 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9446 (delq nil (append a b)))))
9448 (defvar org-link-links-in-this-file nil)
9449 (defun org-insert-link (&optional complete-file link-location default-description)
9450 "Insert a link. At the prompt, enter the link.
9452 Completion can be used to insert any of the link protocol prefixes like
9453 http or ftp in use.
9455 The history can be used to select a link previously stored with
9456 `org-store-link'. When the empty string is entered (i.e. if you just
9457 press RET at the prompt), the link defaults to the most recently
9458 stored link. As SPC triggers completion in the minibuffer, you need to
9459 use M-SPC or C-q SPC to force the insertion of a space character.
9461 You will also be prompted for a description, and if one is given, it will
9462 be displayed in the buffer instead of the link.
9464 If there is already a link at point, this command will allow you to edit link
9465 and description parts.
9467 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9468 be selected using completion. The path to the file will be relative to the
9469 current directory if the file is in the current directory or a subdirectory.
9470 Otherwise, the link will be the absolute path as completed in the minibuffer
9471 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9472 option `org-link-file-path-type'.
9474 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9475 the current directory or below.
9477 With three \\[universal-argument] prefixes, negate the meaning of
9478 `org-keep-stored-link-after-insertion'.
9480 If `org-make-link-description-function' is non-nil, this function will be
9481 called with the link target, and the result will be the default
9482 link description.
9484 If the LINK-LOCATION parameter is non-nil, this value will be
9485 used as the link location instead of reading one interactively.
9487 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9488 be used as the default description."
9489 (interactive "P")
9490 (let* ((wcf (current-window-configuration))
9491 (origbuf (current-buffer))
9492 (region (if (org-region-active-p)
9493 (buffer-substring (region-beginning) (region-end))))
9494 (remove (and region (list (region-beginning) (region-end))))
9495 (desc region)
9496 tmphist ; byte-compile incorrectly complains about this
9497 (link link-location)
9498 (abbrevs org-link-abbrev-alist-local)
9499 entry file all-prefixes auto-desc)
9500 (cond
9501 (link-location) ; specified by arg, just use it.
9502 ((org-in-regexp org-bracket-link-regexp 1)
9503 ;; We do have a link at point, and we are going to edit it.
9504 (setq remove (list (match-beginning 0) (match-end 0)))
9505 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9506 (setq link (read-string "Link: "
9507 (org-link-unescape
9508 (org-match-string-no-properties 1)))))
9509 ((or (org-in-regexp org-angle-link-re)
9510 (org-in-regexp org-plain-link-re))
9511 ;; Convert to bracket link
9512 (setq remove (list (match-beginning 0) (match-end 0))
9513 link (read-string "Link: "
9514 (org-remove-angle-brackets (match-string 0)))))
9515 ((member complete-file '((4) (16)))
9516 ;; Completing read for file names.
9517 (setq link (org-file-complete-link complete-file)))
9519 ;; Read link, with completion for stored links.
9520 (org-link-fontify-links-to-this-file)
9521 (org-switch-to-buffer-other-window "*Org Links*")
9522 (with-current-buffer "*Org Links*"
9523 (erase-buffer)
9524 (insert "Insert a link.
9525 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9526 (when org-stored-links
9527 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9528 (insert (mapconcat 'org-link-prettify
9529 (reverse org-stored-links) "\n")))
9530 (goto-char (point-min)))
9531 (let ((cw (selected-window)))
9532 (select-window (get-buffer-window "*Org Links*" 'visible))
9533 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9534 (unless (pos-visible-in-window-p (point-max))
9535 (org-fit-window-to-buffer))
9536 (and (window-live-p cw) (select-window cw)))
9537 ;; Fake a link history, containing the stored links.
9538 (setq tmphist (append (mapcar 'car org-stored-links)
9539 org-insert-link-history))
9540 (setq all-prefixes (append (mapcar 'car abbrevs)
9541 (mapcar 'car org-link-abbrev-alist)
9542 org-link-types))
9543 (unwind-protect
9544 (progn
9545 (setq link
9546 (org-completing-read
9547 "Link: "
9548 (append
9549 (mapcar (lambda (x) (concat x ":"))
9550 all-prefixes)
9551 (mapcar 'car org-stored-links))
9552 nil nil nil
9553 'tmphist
9554 (caar org-stored-links)))
9555 (if (not (string-match "\\S-" link))
9556 (error "No link selected"))
9557 (mapc (lambda(l)
9558 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9559 org-stored-links)
9560 (if (or (member link all-prefixes)
9561 (and (equal ":" (substring link -1))
9562 (member (substring link 0 -1) all-prefixes)
9563 (setq link (substring link 0 -1))))
9564 (setq link (with-current-buffer origbuf
9565 (org-link-try-special-completion link)))))
9566 (set-window-configuration wcf)
9567 (kill-buffer "*Org Links*"))
9568 (setq entry (assoc link org-stored-links))
9569 (or entry (push link org-insert-link-history))
9570 (setq desc (or desc (nth 1 entry)))))
9572 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9573 (not org-keep-stored-link-after-insertion))
9574 (setq org-stored-links (delq (assoc link org-stored-links)
9575 org-stored-links)))
9577 (if (string-match org-plain-link-re link)
9578 ;; URL-like link, normalize the use of angular brackets.
9579 (setq link (org-remove-angle-brackets link)))
9581 ;; Check if we are linking to the current file with a search
9582 ;; option If yes, simplify the link by using only the search
9583 ;; option.
9584 (when (and buffer-file-name
9585 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9586 (let* ((path (match-string 1 link))
9587 (case-fold-search nil)
9588 (search (match-string 2 link)))
9589 (save-match-data
9590 (if (equal (file-truename buffer-file-name) (file-truename path))
9591 ;; We are linking to this same file, with a search option
9592 (setq link search)))))
9594 ;; Check if we can/should use a relative path. If yes, simplify the link
9595 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9596 (let* ((type (match-string 1 link))
9597 (path (match-string 2 link))
9598 (origpath path)
9599 (case-fold-search nil))
9600 (cond
9601 ((or (eq org-link-file-path-type 'absolute)
9602 (equal complete-file '(16)))
9603 (setq path (abbreviate-file-name (expand-file-name path))))
9604 ((eq org-link-file-path-type 'noabbrev)
9605 (setq path (expand-file-name path)))
9606 ((eq org-link-file-path-type 'relative)
9607 (setq path (file-relative-name path)))
9609 (save-match-data
9610 (if (string-match (concat "^" (regexp-quote
9611 (expand-file-name
9612 (file-name-as-directory
9613 default-directory))))
9614 (expand-file-name path))
9615 ;; We are linking a file with relative path name.
9616 (setq path (substring (expand-file-name path)
9617 (match-end 0)))
9618 (setq path (abbreviate-file-name (expand-file-name path)))))))
9619 (setq link (concat type path))
9620 (if (equal desc origpath)
9621 (setq desc path))))
9623 (if org-make-link-description-function
9624 (setq desc
9625 (or (condition-case nil
9626 (funcall org-make-link-description-function link desc)
9627 (error (progn (message "Can't get link description from `%s'"
9628 (symbol-name org-make-link-description-function))
9629 (sit-for 2) nil)))
9630 (read-string "Description: " default-description)))
9631 (if default-description (setq desc default-description)
9632 (setq desc (or (and auto-desc desc)
9633 (read-string "Description: " desc)))))
9635 (unless (string-match "\\S-" desc) (setq desc nil))
9636 (if remove (apply 'delete-region remove))
9637 (insert (org-make-link-string link desc))))
9639 (defun org-link-try-special-completion (type)
9640 "If there is completion support for link type TYPE, offer it."
9641 (let ((fun (intern (concat "org-" type "-complete-link"))))
9642 (if (functionp fun)
9643 (funcall fun)
9644 (read-string "Link (no completion support): " (concat type ":")))))
9646 (defun org-file-complete-link (&optional arg)
9647 "Create a file link using completion."
9648 (let (file link)
9649 (setq file (org-iread-file-name "File: "))
9650 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9651 (pwd1 (file-name-as-directory (abbreviate-file-name
9652 (expand-file-name ".")))))
9653 (cond
9654 ((equal arg '(16))
9655 (setq link (concat
9656 "file:"
9657 (abbreviate-file-name (expand-file-name file)))))
9658 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9659 (setq link (concat "file:" (match-string 1 file))))
9660 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9661 (expand-file-name file))
9662 (setq link (concat
9663 "file:" (match-string 1 (expand-file-name file)))))
9664 (t (setq link (concat "file:" file)))))
9665 link))
9667 (defun org-iread-file-name (&rest args)
9668 "Read-file-name using `ido-mode' speedup if available.
9669 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9670 See `read-file-name' for a description of parameters."
9671 (org-without-partial-completion
9672 (if (and org-completion-use-ido
9673 (fboundp 'ido-read-file-name)
9674 (boundp 'ido-mode) ido-mode
9675 (listp (second args)))
9676 (let ((ido-enter-matching-directory nil))
9677 (apply 'ido-read-file-name args))
9678 (apply 'read-file-name args))))
9680 (defun org-completing-read (&rest args)
9681 "Completing-read with SPACE being a normal character."
9682 (let ((enable-recursive-minibuffers t)
9683 (minibuffer-local-completion-map
9684 (copy-keymap minibuffer-local-completion-map)))
9685 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9686 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9687 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9688 (apply 'org-icompleting-read args)))
9690 (defun org-completing-read-no-i (&rest args)
9691 (let (org-completion-use-ido org-completion-use-iswitchb)
9692 (apply 'org-completing-read args)))
9694 (defun org-iswitchb-completing-read (prompt choices &rest args)
9695 "Use iswitch as a completing-read replacement to choose from choices.
9696 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9697 from."
9698 (let* ((iswitchb-use-virtual-buffers nil)
9699 (iswitchb-make-buflist-hook
9700 (lambda ()
9701 (setq iswitchb-temp-buflist choices))))
9702 (iswitchb-read-buffer prompt)))
9704 (defun org-icompleting-read (&rest args)
9705 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9706 (org-without-partial-completion
9707 (if (and org-completion-use-ido
9708 (fboundp 'ido-completing-read)
9709 (boundp 'ido-mode) ido-mode
9710 (listp (second args)))
9711 (let ((ido-enter-matching-directory nil))
9712 (apply 'ido-completing-read (concat (car args))
9713 (if (consp (car (nth 1 args)))
9714 (mapcar 'car (nth 1 args))
9715 (nth 1 args))
9716 (cddr args)))
9717 (if (and org-completion-use-iswitchb
9718 (boundp 'iswitchb-mode) iswitchb-mode
9719 (listp (second args)))
9720 (apply 'org-iswitchb-completing-read (concat (car args))
9721 (if (consp (car (nth 1 args)))
9722 (mapcar 'car (nth 1 args))
9723 (nth 1 args))
9724 (cddr args))
9725 (apply 'completing-read args)))))
9727 (defun org-extract-attributes (s)
9728 "Extract the attributes cookie from a string and set as text property."
9729 (let (a attr (start 0) key value)
9730 (save-match-data
9731 (when (string-match "{{\\([^}]+\\)}}$" s)
9732 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9733 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9734 (setq key (match-string 1 a) value (match-string 2 a)
9735 start (match-end 0)
9736 attr (plist-put attr (intern key) value))))
9737 (org-add-props s nil 'org-attr attr))
9740 (defun org-extract-attributes-from-string (tag)
9741 (let (key value attr)
9742 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9743 (setq key (match-string 1 tag) value (match-string 2 tag)
9744 tag (replace-match "" t t tag)
9745 attr (plist-put attr (intern key) value)))
9746 (cons tag attr)))
9748 (defun org-attributes-to-string (plist)
9749 "Format a property list into an HTML attribute list."
9750 (let ((s "") key value)
9751 (while plist
9752 (setq key (pop plist) value (pop plist))
9753 (and value
9754 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9757 ;;; Opening/following a link
9759 (defvar org-link-search-failed nil)
9761 (defvar org-open-link-functions nil
9762 "Hook for functions finding a plain text link.
9763 These functions must take a single argument, the link content.
9764 They will be called for links that look like [[link text][description]]
9765 when LINK TEXT does not have a protocol like \"http:\" and does not look
9766 like a filename (e.g. \"./blue.png\").
9768 These functions will be called *before* Org attempts to resolve the
9769 link by doing text searches in the current buffer - so if you want a
9770 link \"[[target]]\" to still find \"<<target>>\", your function should
9771 handle this as a special case.
9773 When the function does handle the link, it must return a non-nil value.
9774 If it decides that it is not responsible for this link, it must return
9775 nil to indicate that that Org-mode can continue with other options
9776 like exact and fuzzy text search.")
9778 (defun org-next-link ()
9779 "Move forward to the next link.
9780 If the link is in hidden text, expose it."
9781 (interactive)
9782 (when (and org-link-search-failed (eq this-command last-command))
9783 (goto-char (point-min))
9784 (message "Link search wrapped back to beginning of buffer"))
9785 (setq org-link-search-failed nil)
9786 (let* ((pos (point))
9787 (ct (org-context))
9788 (a (assoc :link ct)))
9789 (if a (goto-char (nth 2 a)))
9790 (if (re-search-forward org-any-link-re nil t)
9791 (progn
9792 (goto-char (match-beginning 0))
9793 (if (outline-invisible-p) (org-show-context)))
9794 (goto-char pos)
9795 (setq org-link-search-failed t)
9796 (error "No further link found"))))
9798 (defun org-previous-link ()
9799 "Move backward to the previous link.
9800 If the link is in hidden text, expose it."
9801 (interactive)
9802 (when (and org-link-search-failed (eq this-command last-command))
9803 (goto-char (point-max))
9804 (message "Link search wrapped back to end of buffer"))
9805 (setq org-link-search-failed nil)
9806 (let* ((pos (point))
9807 (ct (org-context))
9808 (a (assoc :link ct)))
9809 (if a (goto-char (nth 1 a)))
9810 (if (re-search-backward org-any-link-re nil t)
9811 (progn
9812 (goto-char (match-beginning 0))
9813 (if (outline-invisible-p) (org-show-context)))
9814 (goto-char pos)
9815 (setq org-link-search-failed t)
9816 (error "No further link found"))))
9818 (defun org-translate-link (s)
9819 "Translate a link string if a translation function has been defined."
9820 (if (and org-link-translation-function
9821 (fboundp org-link-translation-function)
9822 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9823 (progn
9824 (setq s (funcall org-link-translation-function
9825 (match-string 1 s) (match-string 2 s)))
9826 (concat (car s) ":" (cdr s)))
9829 (defun org-translate-link-from-planner (type path)
9830 "Translate a link from Emacs Planner syntax so that Org can follow it.
9831 This is still an experimental function, your mileage may vary."
9832 (cond
9833 ((member type '("http" "https" "news" "ftp"))
9834 ;; standard Internet links are the same.
9835 nil)
9836 ((and (equal type "irc") (string-match "^//" path))
9837 ;; Planner has two / at the beginning of an irc link, we have 1.
9838 ;; We should have zero, actually....
9839 (setq path (substring path 1)))
9840 ((and (equal type "lisp") (string-match "^/" path))
9841 ;; Planner has a slash, we do not.
9842 (setq type "elisp" path (substring path 1)))
9843 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9844 ;; A typical message link. Planner has the id after the final slash,
9845 ;; we separate it with a hash mark
9846 (setq path (concat (match-string 1 path) "#"
9847 (org-remove-angle-brackets (match-string 2 path)))))
9849 (cons type path))
9851 (defun org-find-file-at-mouse (ev)
9852 "Open file link or URL at mouse."
9853 (interactive "e")
9854 (mouse-set-point ev)
9855 (org-open-at-point 'in-emacs))
9857 (defun org-open-at-mouse (ev)
9858 "Open file link or URL at mouse.
9859 See the docstring of `org-open-file' for details."
9860 (interactive "e")
9861 (mouse-set-point ev)
9862 (if (eq major-mode 'org-agenda-mode)
9863 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9864 (org-open-at-point))
9866 (defvar org-window-config-before-follow-link nil
9867 "The window configuration before following a link.
9868 This is saved in case the need arises to restore it.")
9870 (defvar org-open-link-marker (make-marker)
9871 "Marker pointing to the location where `org-open-at-point; was called.")
9873 ;;;###autoload
9874 (defun org-open-at-point-global ()
9875 "Follow a link like Org-mode does.
9876 This command can be called in any mode to follow a link that has
9877 Org-mode syntax."
9878 (interactive)
9879 (org-run-like-in-org-mode 'org-open-at-point))
9881 ;;;###autoload
9882 (defun org-open-link-from-string (s &optional arg reference-buffer)
9883 "Open a link in the string S, as if it was in Org-mode."
9884 (interactive "sLink: \nP")
9885 (let ((reference-buffer (or reference-buffer (current-buffer))))
9886 (with-temp-buffer
9887 (let ((org-inhibit-startup (not reference-buffer)))
9888 (org-mode)
9889 (insert s)
9890 (goto-char (point-min))
9891 (when reference-buffer
9892 (setq org-link-abbrev-alist-local
9893 (with-current-buffer reference-buffer
9894 org-link-abbrev-alist-local)))
9895 (org-open-at-point arg reference-buffer)))))
9897 (defvar org-open-at-point-functions nil
9898 "Hook that is run when following a link at point.
9900 Functions in this hook must return t if they identify and follow
9901 a link at point. If they don't find anything interesting at point,
9902 they must return nil.")
9904 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9905 (defun org-open-at-point (&optional arg reference-buffer)
9906 "Open link at or after point.
9907 If there is no link at point, this function will search forward up to
9908 the end of the current line.
9909 Normally, files will be opened by an appropriate application. If the
9910 optional prefix argument ARG is non-nil, Emacs will visit the file.
9911 With a double prefix argument, try to open outside of Emacs, in the
9912 application the system uses for this file type."
9913 (interactive "P")
9914 ;; if in a code block, then open the block's results
9915 (unless (call-interactively #'org-babel-open-src-block-result)
9916 (org-load-modules-maybe)
9917 (move-marker org-open-link-marker (point))
9918 (setq org-window-config-before-follow-link (current-window-configuration))
9919 (org-remove-occur-highlights nil nil t)
9920 (cond
9921 ((and (org-at-heading-p)
9922 (not (org-at-timestamp-p t))
9923 (not (org-in-regexp
9924 (concat org-plain-link-re "\\|"
9925 org-bracket-link-regexp "\\|"
9926 org-angle-link-re "\\|"
9927 "[ \t]:[^ \t\n]+:[ \t]*$")))
9928 (not (get-text-property (point) 'org-linked-text)))
9929 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9930 (lk0 (car lkall))
9931 (lk (if (stringp lk0) (list lk0) lk0))
9932 (lkend (cdr lkall)))
9933 (mapcar (lambda(l)
9934 (search-forward l nil lkend)
9935 (goto-char (match-beginning 0))
9936 (org-open-at-point))
9937 lk))
9938 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9939 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9940 ((and (org-at-timestamp-p t)
9941 (not (org-in-regexp org-bracket-link-regexp)))
9942 (org-follow-timestamp-link))
9943 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9944 (not (org-in-regexp org-any-link-re)))
9945 (org-footnote-action))
9947 (let (type path link line search (pos (point)))
9948 (catch 'match
9949 (save-excursion
9950 (skip-chars-forward "^]\n\r")
9951 (when (org-in-regexp org-bracket-link-regexp 1)
9952 (setq link (org-extract-attributes
9953 (org-link-unescape (org-match-string-no-properties 1))))
9954 (while (string-match " *\n *" link)
9955 (setq link (replace-match " " t t link)))
9956 (setq link (org-link-expand-abbrev link))
9957 (cond
9958 ((or (file-name-absolute-p link)
9959 (string-match "^\\.\\.?/" link))
9960 (setq type "file" path link))
9961 ((string-match org-link-re-with-space3 link)
9962 (setq type (match-string 1 link) path (match-string 2 link)))
9963 ((string-match "^help:+\\(.+\\)" link)
9964 (setq type "help" path (match-string 1 link)))
9965 (t (setq type "thisfile" path link)))
9966 (throw 'match t)))
9968 (when (get-text-property (point) 'org-linked-text)
9969 (setq type "thisfile"
9970 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9971 (1+ (point)) (point))
9972 path (buffer-substring
9973 (or (previous-single-property-change pos 'org-linked-text)
9974 (point-min))
9975 (or (next-single-property-change pos 'org-linked-text)
9976 (point-max))))
9977 (throw 'match t))
9979 (save-excursion
9980 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9981 (when (or (org-in-regexp org-angle-link-re)
9982 (and plinkpos (goto-char (car plinkpos))
9983 (save-match-data (not (looking-back "\\[\\[")))))
9984 (setq type (match-string 1)
9985 path (org-link-unescape (match-string 2)))
9986 (throw 'match t))))
9987 (save-excursion
9988 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9989 (setq type "tags"
9990 path (match-string 1))
9991 (while (string-match ":" path)
9992 (setq path (replace-match "+" t t path)))
9993 (throw 'match t)))
9994 (when (org-in-regexp "<\\([^><\n]+\\)>")
9995 (setq type "tree-match"
9996 path (match-string 1))
9997 (throw 'match t)))
9998 (unless path
9999 (user-error "No link found"))
10001 ;; switch back to reference buffer
10002 ;; needed when if called in a temporary buffer through
10003 ;; org-open-link-from-string
10004 (with-current-buffer (or reference-buffer (current-buffer))
10006 ;; Remove any trailing spaces in path
10007 (if (string-match " +\\'" path)
10008 (setq path (replace-match "" t t path)))
10009 (if (and org-link-translation-function
10010 (fboundp org-link-translation-function))
10011 ;; Check if we need to translate the link
10012 (let ((tmp (funcall org-link-translation-function type path)))
10013 (setq type (car tmp) path (cdr tmp))))
10015 (cond
10017 ((assoc type org-link-protocols)
10018 (funcall (nth 1 (assoc type org-link-protocols)) path))
10020 ((equal type "help")
10021 (let ((f-or-v (intern path)))
10022 (cond ((fboundp f-or-v)
10023 (describe-function f-or-v))
10024 ((boundp f-or-v)
10025 (describe-variable f-or-v))
10026 (t (error "Not a known function or variable")))))
10028 ((equal type "mailto")
10029 (let ((cmd (car org-link-mailto-program))
10030 (args (cdr org-link-mailto-program)) args1
10031 (address path) (subject "") a)
10032 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10033 (setq address (match-string 1 path)
10034 subject (org-link-escape (match-string 2 path))))
10035 (while args
10036 (cond
10037 ((not (stringp (car args))) (push (pop args) args1))
10038 (t (setq a (pop args))
10039 (if (string-match "%a" a)
10040 (setq a (replace-match address t t a)))
10041 (if (string-match "%s" a)
10042 (setq a (replace-match subject t t a)))
10043 (push a args1))))
10044 (apply cmd (nreverse args1))))
10046 ((member type '("http" "https" "ftp" "news"))
10047 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10048 (org-link-escape
10049 path org-link-escape-chars-browser)
10050 path))))
10052 ((string= type "doi")
10053 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10054 (org-link-escape
10055 path org-link-escape-chars-browser)
10056 path))))
10058 ((member type '("message"))
10059 (browse-url (concat type ":" path)))
10061 ((string= type "tags")
10062 (org-tags-view arg path))
10064 ((string= type "tree-match")
10065 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10067 ((string= type "file")
10068 (if (string-match "::\\([0-9]+\\)\\'" path)
10069 (setq line (string-to-number (match-string 1 path))
10070 path (substring path 0 (match-beginning 0)))
10071 (if (string-match "::\\(.+\\)\\'" path)
10072 (setq search (match-string 1 path)
10073 path (substring path 0 (match-beginning 0)))))
10074 (if (string-match "[*?{]" (file-name-nondirectory path))
10075 (dired path)
10076 (org-open-file path arg line search)))
10078 ((string= type "shell")
10079 (let ((buf (generate-new-buffer "*Org Shell Output"))
10080 (cmd path))
10081 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10082 (string-match org-confirm-shell-link-not-regexp cmd))
10083 (not org-confirm-shell-link-function)
10084 (funcall org-confirm-shell-link-function
10085 (format "Execute \"%s\" in shell? "
10086 (org-add-props cmd nil
10087 'face 'org-warning))))
10088 (progn
10089 (message "Executing %s" cmd)
10090 (shell-command cmd buf)
10091 (if (featurep 'midnight)
10092 (setq clean-buffer-list-kill-buffer-names
10093 (cons buf clean-buffer-list-kill-buffer-names))))
10094 (error "Abort"))))
10096 ((string= type "elisp")
10097 (let ((cmd path))
10098 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10099 (string-match org-confirm-elisp-link-not-regexp cmd))
10100 (not org-confirm-elisp-link-function)
10101 (funcall org-confirm-elisp-link-function
10102 (format "Execute \"%s\" as elisp? "
10103 (org-add-props cmd nil
10104 'face 'org-warning))))
10105 (message "%s => %s" cmd
10106 (if (equal (string-to-char cmd) ?\()
10107 (eval (read cmd))
10108 (call-interactively (read cmd))))
10109 (error "Abort"))))
10111 ((and (string= type "thisfile")
10112 (run-hook-with-args-until-success
10113 'org-open-link-functions path)))
10115 ((string= type "thisfile")
10116 (if arg
10117 (switch-to-buffer-other-window
10118 (org-get-buffer-for-internal-link (current-buffer)))
10119 (org-mark-ring-push))
10120 (let ((cmd `(org-link-search
10121 ,path
10122 ,(cond ((equal arg '(4)) ''occur)
10123 ((equal arg '(16)) ''org-occur))
10124 ,pos)))
10125 (condition-case nil (let ((org-link-search-inhibit-query t))
10126 (eval cmd))
10127 (error (progn (widen) (eval cmd))))))
10129 (t (browse-url-at-point)))))))
10130 (move-marker org-open-link-marker nil)
10131 (run-hook-with-args 'org-follow-link-hook)))
10133 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10134 "Offer links in the current entry and return the selected link.
10135 If there is only one link, return it.
10136 If NTH is an integer, return the NTH link found.
10137 If ZERO is a string, check also this string for a link, and if
10138 there is one, return it."
10139 (with-current-buffer buffer
10140 (save-excursion
10141 (save-restriction
10142 (widen)
10143 (goto-char marker)
10144 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10145 "\\(" org-angle-link-re "\\)\\|"
10146 "\\(" org-plain-link-re "\\)"))
10147 (cnt ?0)
10148 (in-emacs (if (integerp nth) nil nth))
10149 have-zero end links link c)
10150 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10151 (push (match-string 0 zero) links)
10152 (setq cnt (1- cnt) have-zero t))
10153 (save-excursion
10154 (org-back-to-heading t)
10155 (setq end (save-excursion (outline-next-heading) (point)))
10156 (while (re-search-forward re end t)
10157 (push (match-string 0) links))
10158 (setq links (org-uniquify (reverse links))))
10159 (cond
10160 ((null links)
10161 (message "No links"))
10162 ((equal (length links) 1)
10163 (setq link (car links)))
10164 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10165 (setq link (nth (if have-zero nth (1- nth)) links)))
10166 (t ; we have to select a link
10167 (save-excursion
10168 (save-window-excursion
10169 (delete-other-windows)
10170 (with-output-to-temp-buffer "*Select Link*"
10171 (mapc (lambda (l)
10172 (if (not (string-match org-bracket-link-regexp l))
10173 (princ (format "[%c] %s\n" (incf cnt)
10174 (org-remove-angle-brackets l)))
10175 (if (match-end 3)
10176 (princ (format "[%c] %s (%s)\n" (incf cnt)
10177 (match-string 3 l) (match-string 1 l)))
10178 (princ (format "[%c] %s\n" (incf cnt)
10179 (match-string 1 l))))))
10180 links))
10181 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10182 (message "Select link to open, RET to open all:")
10183 (setq c (read-char-exclusive))
10184 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10185 (when (equal c ?q) (error "Abort"))
10186 (if (equal c ?\C-m)
10187 (setq link links)
10188 (setq nth (- c ?0))
10189 (if have-zero (setq nth (1+ nth)))
10190 (unless (and (integerp nth) (>= (length links) nth))
10191 (error "Invalid link selection"))
10192 (setq link (nth (1- nth) links)))))
10193 (cons link end))))))
10195 ;; Add special file links that specify the way of opening
10197 (org-add-link-type "file+sys" 'org-open-file-with-system)
10198 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10199 (defun org-open-file-with-system (path)
10200 "Open file at PATH using the system way of opening it."
10201 (org-open-file path 'system))
10202 (defun org-open-file-with-emacs (path)
10203 "Open file at PATH in Emacs."
10204 (org-open-file path 'emacs))
10207 ;;; File search
10209 (defvar org-create-file-search-functions nil
10210 "List of functions to construct the right search string for a file link.
10211 These functions are called in turn with point at the location to
10212 which the link should point.
10214 A function in the hook should first test if it would like to
10215 handle this file type, for example by checking the `major-mode'
10216 or the file extension. If it decides not to handle this file, it
10217 should just return nil to give other functions a chance. If it
10218 does handle the file, it must return the search string to be used
10219 when following the link. The search string will be part of the
10220 file link, given after a double colon, and `org-open-at-point'
10221 will automatically search for it. If special measures must be
10222 taken to make the search successful, another function should be
10223 added to the companion hook `org-execute-file-search-functions',
10224 which see.
10226 A function in this hook may also use `setq' to set the variable
10227 `description' to provide a suggestion for the descriptive text to
10228 be used for this link when it gets inserted into an Org-mode
10229 buffer with \\[org-insert-link].")
10231 (defvar org-execute-file-search-functions nil
10232 "List of functions to execute a file search triggered by a link.
10234 Functions added to this hook must accept a single argument, the
10235 search string that was part of the file link, the part after the
10236 double colon. The function must first check if it would like to
10237 handle this search, for example by checking the `major-mode' or
10238 the file extension. If it decides not to handle this search, it
10239 should just return nil to give other functions a chance. If it
10240 does handle the search, it must return a non-nil value to keep
10241 other functions from trying.
10243 Each function can access the current prefix argument through the
10244 variable `current-prefix-argument'. Note that a single prefix is
10245 used to force opening a link in Emacs, so it may be good to only
10246 use a numeric or double prefix to guide the search function.
10248 In case this is needed, a function in this hook can also restore
10249 the window configuration before `org-open-at-point' was called using:
10251 (set-window-configuration org-window-config-before-follow-link)")
10253 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10254 (defun org-link-search (s &optional type avoid-pos stealth)
10255 "Search for a link search option.
10256 If S is surrounded by forward slashes, it is interpreted as a
10257 regular expression. In org-mode files, this will create an `org-occur'
10258 sparse tree. In ordinary files, `occur' will be used to list matches.
10259 If the current buffer is in `dired-mode', grep will be used to search
10260 in all files. If AVOID-POS is given, ignore matches near that position.
10262 When optional argument STEALTH is non-nil, do not modify
10263 visibility around point, thus ignoring
10264 `org-show-hierarchy-above', `org-show-following-heading' and
10265 `org-show-siblings' variables."
10266 (let ((case-fold-search t)
10267 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10268 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10269 (append '(("") (" ") ("\t") ("\n"))
10270 org-emphasis-alist)
10271 "\\|") "\\)"))
10272 (pos (point))
10273 (pre nil) (post nil)
10274 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10275 (cond
10276 ;; First check if there are any special search functions
10277 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10278 ;; Now try the builtin stuff
10279 ((and (equal (string-to-char s0) ?#)
10280 (> (length s0) 1)
10281 (save-excursion
10282 (goto-char (point-min))
10283 (and
10284 (re-search-forward
10285 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10286 (setq type 'dedicated
10287 pos (match-beginning 0))))
10288 ;; There is an exact target for this
10289 (goto-char pos)
10290 (org-back-to-heading t)))
10291 ((save-excursion
10292 (goto-char (point-min))
10293 (and
10294 (re-search-forward
10295 (concat "<<" (regexp-quote s0) ">>") nil t)
10296 (setq type 'dedicated
10297 pos (match-beginning 0))))
10298 ;; There is an exact target for this
10299 (goto-char pos))
10300 ((save-excursion
10301 (goto-char (point-min))
10302 (and
10303 (re-search-forward
10304 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10305 (setq type 'dedicated pos (match-beginning 0))))
10306 ;; Found an invisible target.
10307 (goto-char pos))
10308 ((save-excursion
10309 (goto-char (point-min))
10310 (and
10311 (re-search-forward
10312 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10313 (setq type 'dedicated pos (match-beginning 0))))
10314 ;; Found an element with a matching #+name affiliated keyword.
10315 (goto-char pos))
10316 ((and (string-match "^(\\(.*\\))$" s0)
10317 (save-excursion
10318 (goto-char (point-min))
10319 (and
10320 (re-search-forward
10321 (concat "[^[]" (regexp-quote
10322 (format org-coderef-label-format
10323 (match-string 1 s0))))
10324 nil t)
10325 (setq type 'dedicated
10326 pos (1+ (match-beginning 0))))))
10327 ;; There is a coderef target for this
10328 (goto-char pos))
10329 ((string-match "^/\\(.*\\)/$" s)
10330 ;; A regular expression
10331 (cond
10332 ((derived-mode-p 'org-mode)
10333 (org-occur (match-string 1 s)))
10334 ;;((eq major-mode 'dired-mode)
10335 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10336 (t (org-do-occur (match-string 1 s)))))
10337 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10338 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10339 (goto-char (point-min))
10340 (cond
10341 ((let (case-fold-search)
10342 (re-search-forward (format org-complex-heading-regexp-format
10343 (regexp-quote s))
10344 nil t))
10345 ;; OK, found a match
10346 (setq type 'dedicated)
10347 (goto-char (match-beginning 0)))
10348 ((and (not org-link-search-inhibit-query)
10349 (eq org-link-search-must-match-exact-headline 'query-to-create)
10350 (y-or-n-p "No match - create this as a new heading? "))
10351 (goto-char (point-max))
10352 (or (bolp) (newline))
10353 (insert "* " s "\n")
10354 (beginning-of-line 0))
10356 (goto-char pos)
10357 (error "No match"))))
10359 ;; A normal search string
10360 (when (equal (string-to-char s) ?*)
10361 ;; Anchor on headlines, post may include tags.
10362 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10363 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10364 s (substring s 1)))
10365 (remove-text-properties
10366 0 (length s)
10367 '(face nil mouse-face nil keymap nil fontified nil) s)
10368 ;; Make a series of regular expressions to find a match
10369 (setq words (org-split-string s "[ \n\r\t]+")
10371 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10372 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10373 "\\)" markers)
10374 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10375 re2a (concat "[ \t\r\n]" re2a_)
10376 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10377 re4 (concat "[^a-zA-Z_]" re4_)
10379 re1 (concat pre re2 post)
10380 re3 (concat pre (if pre re4_ re4) post)
10381 re5 (concat pre ".*" re4)
10382 re2 (concat pre re2)
10383 re2a (concat pre (if pre re2a_ re2a))
10384 re4 (concat pre (if pre re4_ re4))
10385 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10386 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10387 re5 "\\)"
10389 (cond
10390 ((eq type 'org-occur) (org-occur reall))
10391 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10392 (t (goto-char (point-min))
10393 (setq type 'fuzzy)
10394 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10395 (org-search-not-self 1 re1 nil t)
10396 (org-search-not-self 1 re2 nil t)
10397 (org-search-not-self 1 re2a nil t)
10398 (org-search-not-self 1 re3 nil t)
10399 (org-search-not-self 1 re4 nil t)
10400 (org-search-not-self 1 re5 nil t)
10402 (goto-char (match-beginning 1))
10403 (goto-char pos)
10404 (error "No match"))))))
10405 (and (derived-mode-p 'org-mode)
10406 (not stealth)
10407 (org-show-context 'link-search))
10408 type))
10410 (defun org-search-not-self (group &rest args)
10411 "Execute `re-search-forward', but only accept matches that do not
10412 enclose the position of `org-open-link-marker'."
10413 (let ((m org-open-link-marker))
10414 (catch 'exit
10415 (while (apply 're-search-forward args)
10416 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10417 (goto-char (match-end group))
10418 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10419 (> (match-beginning 0) (marker-position m))
10420 (< (match-end 0) (marker-position m)))
10421 (save-match-data
10422 (or (not (org-in-regexp
10423 org-bracket-link-analytic-regexp 1))
10424 (not (match-end 4)) ; no description
10425 (and (<= (match-beginning 4) (point))
10426 (>= (match-end 4) (point))))))
10427 (throw 'exit (point))))))))
10429 (defun org-get-buffer-for-internal-link (buffer)
10430 "Return a buffer to be used for displaying the link target of internal links."
10431 (cond
10432 ((not org-display-internal-link-with-indirect-buffer)
10433 buffer)
10434 ((string-match "(Clone)$" (buffer-name buffer))
10435 (message "Buffer is already a clone, not making another one")
10436 ;; we also do not modify visibility in this case
10437 buffer)
10438 (t ; make a new indirect buffer for displaying the link
10439 (let* ((bn (buffer-name buffer))
10440 (ibn (concat bn "(Clone)"))
10441 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10442 (with-current-buffer ib (org-overview))
10443 ib))))
10445 (defun org-do-occur (regexp &optional cleanup)
10446 "Call the Emacs command `occur'.
10447 If CLEANUP is non-nil, remove the printout of the regular expression
10448 in the *Occur* buffer. This is useful if the regex is long and not useful
10449 to read."
10450 (occur regexp)
10451 (when cleanup
10452 (let ((cwin (selected-window)) win beg end)
10453 (when (setq win (get-buffer-window "*Occur*"))
10454 (select-window win))
10455 (goto-char (point-min))
10456 (when (re-search-forward "match[a-z]+" nil t)
10457 (setq beg (match-end 0))
10458 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10459 (setq end (1- (match-beginning 0)))))
10460 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10461 (goto-char (point-min))
10462 (select-window cwin))))
10464 ;;; The mark ring for links jumps
10466 (defvar org-mark-ring nil
10467 "Mark ring for positions before jumps in Org-mode.")
10468 (defvar org-mark-ring-last-goto nil
10469 "Last position in the mark ring used to go back.")
10470 ;; Fill and close the ring
10471 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10472 (loop for i from 1 to org-mark-ring-length do
10473 (push (make-marker) org-mark-ring))
10474 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10475 org-mark-ring)
10477 (defun org-mark-ring-push (&optional pos buffer)
10478 "Put the current position or POS into the mark ring and rotate it."
10479 (interactive)
10480 (setq pos (or pos (point)))
10481 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10482 (move-marker (car org-mark-ring)
10483 (or pos (point))
10484 (or buffer (current-buffer)))
10485 (message "%s"
10486 (substitute-command-keys
10487 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10489 (defun org-mark-ring-goto (&optional n)
10490 "Jump to the previous position in the mark ring.
10491 With prefix arg N, jump back that many stored positions. When
10492 called several times in succession, walk through the entire ring.
10493 Org-mode commands jumping to a different position in the current file,
10494 or to another Org-mode file, automatically push the old position
10495 onto the ring."
10496 (interactive "p")
10497 (let (p m)
10498 (if (eq last-command this-command)
10499 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10500 (setq p org-mark-ring))
10501 (setq org-mark-ring-last-goto p)
10502 (setq m (car p))
10503 (org-pop-to-buffer-same-window (marker-buffer m))
10504 (goto-char m)
10505 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10507 (defun org-remove-angle-brackets (s)
10508 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10509 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10511 (defun org-add-angle-brackets (s)
10512 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10513 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10515 (defun org-remove-double-quotes (s)
10516 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10517 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10520 ;;; Following specific links
10522 (defun org-follow-timestamp-link ()
10523 "Open an agenda view for the time-stamp date/range at point."
10524 (cond
10525 ((org-at-date-range-p t)
10526 (let ((org-agenda-start-on-weekday)
10527 (t1 (match-string 1))
10528 (t2 (match-string 2)) tt1 tt2)
10529 (setq tt1 (time-to-days (org-time-string-to-time t1))
10530 tt2 (time-to-days (org-time-string-to-time t2)))
10531 (let ((org-agenda-buffer-tmp-name
10532 (format "*Org Agenda(a:%s)"
10533 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10534 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10535 ((org-at-timestamp-p t)
10536 (let ((org-agenda-buffer-tmp-name
10537 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10538 (org-agenda-list nil (time-to-days (org-time-string-to-time
10539 (substring (match-string 1) 0 10)))
10540 1)))
10541 (t (error "This should not happen"))))
10544 ;;; Following file links
10545 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10546 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10547 (declare-function mailcap-mime-info
10548 "mailcap" (string &optional request no-decode))
10549 (defvar org-wait nil)
10550 (defun org-open-file (path &optional in-emacs line search)
10551 "Open the file at PATH.
10552 First, this expands any special file name abbreviations. Then the
10553 configuration variable `org-file-apps' is checked if it contains an
10554 entry for this file type, and if yes, the corresponding command is launched.
10556 If no application is found, Emacs simply visits the file.
10558 With optional prefix argument IN-EMACS, Emacs will visit the file.
10559 With a double \\[universal-argument] \\[universal-argument] \
10560 prefix arg, Org tries to avoid opening in Emacs
10561 and to use an external application to visit the file.
10563 Optional LINE specifies a line to go to, optional SEARCH a string
10564 to search for. If LINE or SEARCH is given, the file will be
10565 opened in Emacs, unless an entry from org-file-apps that makes
10566 use of groups in a regexp matches.
10568 If you want to change the way frames are used when following a
10569 link, please customize `org-link-frame-setup'.
10571 If the file does not exist, an error is thrown."
10572 (let* ((file (if (equal path "")
10573 buffer-file-name
10574 (substitute-in-file-name (expand-file-name path))))
10575 (file-apps (append org-file-apps (org-default-apps)))
10576 (apps (org-remove-if
10577 'org-file-apps-entry-match-against-dlink-p file-apps))
10578 (apps-dlink (org-remove-if-not
10579 'org-file-apps-entry-match-against-dlink-p file-apps))
10580 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10581 (dirp (if remp nil (file-directory-p file)))
10582 (file (if (and dirp org-open-directory-means-index-dot-org)
10583 (concat (file-name-as-directory file) "index.org")
10584 file))
10585 (a-m-a-p (assq 'auto-mode apps))
10586 (dfile (downcase file))
10587 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10588 (link (cond ((and (eq line nil)
10589 (eq search nil))
10590 file)
10591 (line
10592 (concat file "::" (number-to-string line)))
10593 (search
10594 (concat file "::" search))))
10595 (dlink (downcase link))
10596 (old-buffer (current-buffer))
10597 (old-pos (point))
10598 (old-mode major-mode)
10599 ext cmd link-match-data)
10600 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10601 (setq ext (match-string 1 dfile))
10602 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10603 (setq ext (match-string 1 dfile))))
10604 (cond
10605 ((member in-emacs '((16) system))
10606 (setq cmd (cdr (assoc 'system apps))))
10607 (in-emacs (setq cmd 'emacs))
10609 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10610 (and dirp (cdr (assoc 'directory apps)))
10611 ; first, try matching against apps-dlink
10612 ; if we get a match here, store the match data for later
10613 (let ((match (assoc-default dlink apps-dlink
10614 'string-match)))
10615 (if match
10616 (progn (setq link-match-data (match-data))
10617 match)
10618 (progn (setq in-emacs (or in-emacs line search))
10619 nil))) ; if we have no match in apps-dlink,
10620 ; always open the file in emacs if line or search
10621 ; is given (for backwards compatibility)
10622 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10623 'string-match)
10624 (cdr (assoc ext apps))
10625 (cdr (assoc t apps))))))
10626 (when (eq cmd 'system)
10627 (setq cmd (cdr (assoc 'system apps))))
10628 (when (eq cmd 'default)
10629 (setq cmd (cdr (assoc t apps))))
10630 (when (eq cmd 'mailcap)
10631 (require 'mailcap)
10632 (mailcap-parse-mailcaps)
10633 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10634 (command (mailcap-mime-info mime-type)))
10635 (if (stringp command)
10636 (setq cmd command)
10637 (setq cmd 'emacs))))
10638 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10639 (not (file-exists-p file))
10640 (not org-open-non-existing-files))
10641 (error "No such file: %s" file))
10642 (cond
10643 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10644 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10645 (while (string-match "['\"]%s['\"]" cmd)
10646 (setq cmd (replace-match "%s" t t cmd)))
10647 (while (string-match "%s" cmd)
10648 (setq cmd (replace-match
10649 (save-match-data
10650 (shell-quote-argument
10651 (convert-standard-filename file)))
10652 t t cmd)))
10654 ;; Replace "%1", "%2" etc. in command with group matches from regex
10655 (save-match-data
10656 (let ((match-index 1)
10657 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10658 (set-match-data link-match-data)
10659 (while (<= match-index number-of-groups)
10660 (let ((regex (concat "%" (number-to-string match-index)))
10661 (replace-with (match-string match-index dlink)))
10662 (while (string-match regex cmd)
10663 (setq cmd (replace-match replace-with t t cmd))))
10664 (setq match-index (+ match-index 1)))))
10666 (save-window-excursion
10667 (message "Running %s...done" cmd)
10668 (start-process-shell-command cmd nil cmd)
10669 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10670 ((or (stringp cmd)
10671 (eq cmd 'emacs))
10672 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10673 (widen)
10674 (if line (org-goto-line line)
10675 (if search (org-link-search search))))
10676 ((consp cmd)
10677 (let ((file (convert-standard-filename file)))
10678 (save-match-data
10679 (set-match-data link-match-data)
10680 (eval cmd))))
10681 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10682 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10683 (or (not (equal old-buffer (current-buffer)))
10684 (not (equal old-pos (point))))
10685 (org-mark-ring-push old-pos old-buffer))))
10687 (defun org-file-apps-entry-match-against-dlink-p (entry)
10688 "This function returns non-nil if `entry' uses a regular
10689 expression which should be matched against the whole link by
10690 org-open-file.
10692 It assumes that is the case when the entry uses a regular
10693 expression which has at least one grouping construct and the
10694 action is either a lisp form or a command string containing
10695 '%1', i.e. using at least one subexpression match as a
10696 parameter."
10697 (let ((selector (car entry))
10698 (action (cdr entry)))
10699 (if (stringp selector)
10700 (and (> (regexp-opt-depth selector) 0)
10701 (or (and (stringp action)
10702 (string-match "%[0-9]" action))
10703 (consp action)))
10704 nil)))
10706 (defun org-default-apps ()
10707 "Return the default applications for this operating system."
10708 (cond
10709 ((eq system-type 'darwin)
10710 org-file-apps-defaults-macosx)
10711 ((eq system-type 'windows-nt)
10712 org-file-apps-defaults-windowsnt)
10713 (t org-file-apps-defaults-gnu)))
10715 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10716 "Convert extensions to regular expressions in the cars of LIST.
10717 Also, weed out any non-string entries, because the return value is used
10718 only for regexp matching.
10719 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10720 point to the symbol `emacs', indicating that the file should
10721 be opened in Emacs."
10722 (append
10723 (delq nil
10724 (mapcar (lambda (x)
10725 (if (not (stringp (car x)))
10727 (if (string-match "\\W" (car x))
10729 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10730 list))
10731 (if add-auto-mode
10732 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10734 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10735 (defun org-file-remote-p (file)
10736 "Test whether FILE specifies a location on a remote system.
10737 Return non-nil if the location is indeed remote.
10739 For example, the filename \"/user@host:/foo\" specifies a location
10740 on the system \"/user@host:\"."
10741 (cond ((fboundp 'file-remote-p)
10742 (file-remote-p file))
10743 ((fboundp 'tramp-handle-file-remote-p)
10744 (tramp-handle-file-remote-p file))
10745 ((and (boundp 'ange-ftp-name-format)
10746 (string-match (car ange-ftp-name-format) file))
10747 t)))
10750 ;;;; Refiling
10752 (defun org-get-org-file ()
10753 "Read a filename, with default directory `org-directory'."
10754 (let ((default (or org-default-notes-file remember-data-file)))
10755 (read-file-name (format "File name [%s]: " default)
10756 (file-name-as-directory org-directory)
10757 default)))
10759 (defun org-notes-order-reversed-p ()
10760 "Check if the current file should receive notes in reversed order."
10761 (cond
10762 ((not org-reverse-note-order) nil)
10763 ((eq t org-reverse-note-order) t)
10764 ((not (listp org-reverse-note-order)) nil)
10765 (t (catch 'exit
10766 (let ((all org-reverse-note-order)
10767 entry)
10768 (while (setq entry (pop all))
10769 (if (string-match (car entry) buffer-file-name)
10770 (throw 'exit (cdr entry))))
10771 nil)))))
10773 (defvar org-refile-target-table nil
10774 "The list of refile targets, created by `org-refile'.")
10776 (defvar org-agenda-new-buffers nil
10777 "Buffers created to visit agenda files.")
10779 (defvar org-refile-cache nil
10780 "Cache for refile targets.")
10782 (defvar org-refile-markers nil
10783 "All the markers used for caching refile locations.")
10785 (defun org-refile-marker (pos)
10786 "Get a new refile marker, but only if caching is in use."
10787 (if (not org-refile-use-cache)
10789 (let ((m (make-marker)))
10790 (move-marker m pos)
10791 (push m org-refile-markers)
10792 m)))
10794 (defun org-refile-cache-clear ()
10795 "Clear the refile cache and disable all the markers."
10796 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10797 (setq org-refile-markers nil)
10798 (setq org-refile-cache nil)
10799 (message "Refile cache has been cleared"))
10801 (defun org-refile-cache-check-set (set)
10802 "Check if all the markers in the cache still have live buffers."
10803 (let (marker)
10804 (catch 'exit
10805 (while (and set (setq marker (nth 3 (pop set))))
10806 ;; if org-refile-use-outline-path is 'file, marker may be nil
10807 (when (and marker (null (marker-buffer marker)))
10808 (message "not found") (sit-for 3)
10809 (throw 'exit nil)))
10810 t)))
10812 (defun org-refile-cache-put (set &rest identifiers)
10813 "Push the refile targets SET into the cache, under IDENTIFIERS."
10814 (let* ((key (sha1 (prin1-to-string identifiers)))
10815 (entry (assoc key org-refile-cache)))
10816 (if entry
10817 (setcdr entry set)
10818 (push (cons key set) org-refile-cache))))
10820 (defun org-refile-cache-get (&rest identifiers)
10821 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10822 (cond
10823 ((not org-refile-cache) nil)
10824 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10826 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10827 org-refile-cache))))
10828 (and set (org-refile-cache-check-set set) set)))))
10830 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10831 "Produce a table with refile targets."
10832 (let ((case-fold-search nil)
10833 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10834 (entries (or org-refile-targets '((nil . (:level . 1)))))
10835 targets tgs txt re files f desc descre fast-path-p level pos0)
10836 (message "Getting targets...")
10837 (with-current-buffer (or default-buffer (current-buffer))
10838 (while (setq entry (pop entries))
10839 (setq files (car entry) desc (cdr entry))
10840 (setq fast-path-p nil)
10841 (cond
10842 ((null files) (setq files (list (current-buffer))))
10843 ((eq files 'org-agenda-files)
10844 (setq files (org-agenda-files 'unrestricted)))
10845 ((and (symbolp files) (fboundp files))
10846 (setq files (funcall files)))
10847 ((and (symbolp files) (boundp files))
10848 (setq files (symbol-value files))))
10849 (if (stringp files) (setq files (list files)))
10850 (cond
10851 ((eq (car desc) :tag)
10852 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10853 ((eq (car desc) :todo)
10854 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10855 ((eq (car desc) :regexp)
10856 (setq descre (cdr desc)))
10857 ((eq (car desc) :level)
10858 (setq descre (concat "^\\*\\{" (number-to-string
10859 (if org-odd-levels-only
10860 (1- (* 2 (cdr desc)))
10861 (cdr desc)))
10862 "\\}[ \t]")))
10863 ((eq (car desc) :maxlevel)
10864 (setq fast-path-p t)
10865 (setq descre (concat "^\\*\\{1," (number-to-string
10866 (if org-odd-levels-only
10867 (1- (* 2 (cdr desc)))
10868 (cdr desc)))
10869 "\\}[ \t]")))
10870 (t (error "Bad refiling target description %s" desc)))
10871 (while (setq f (pop files))
10872 (with-current-buffer
10873 (if (bufferp f) f (org-get-agenda-file-buffer f))
10875 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10876 (progn
10877 (if (bufferp f) (setq f (buffer-file-name
10878 (buffer-base-buffer f))))
10879 (setq f (and f (expand-file-name f)))
10880 (if (eq org-refile-use-outline-path 'file)
10881 (push (list (file-name-nondirectory f) f nil nil) tgs))
10882 (save-excursion
10883 (save-restriction
10884 (widen)
10885 (goto-char (point-min))
10886 (while (re-search-forward descre nil t)
10887 (goto-char (setq pos0 (point-at-bol)))
10888 (catch 'next
10889 (when org-refile-target-verify-function
10890 (save-match-data
10891 (or (funcall org-refile-target-verify-function)
10892 (throw 'next t))))
10893 (when (and (looking-at org-complex-heading-regexp)
10894 (not (member (match-string 4) excluded-entries))
10895 (match-string 4))
10896 (setq level (org-reduced-level
10897 (- (match-end 1) (match-beginning 1)))
10898 txt (org-link-display-format (match-string 4))
10899 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10900 re (format org-complex-heading-regexp-format
10901 (regexp-quote (match-string 4))))
10902 (when org-refile-use-outline-path
10903 (setq txt (mapconcat
10904 'org-protect-slash
10905 (append
10906 (if (eq org-refile-use-outline-path
10907 'file)
10908 (list (file-name-nondirectory
10909 (buffer-file-name
10910 (buffer-base-buffer))))
10911 (if (eq org-refile-use-outline-path
10912 'full-file-path)
10913 (list (buffer-file-name
10914 (buffer-base-buffer)))))
10915 (org-get-outline-path fast-path-p
10916 level txt)
10917 (list txt))
10918 "/")))
10919 (push (list txt f re (org-refile-marker (point)))
10920 tgs)))
10921 (when (= (point) pos0)
10922 ;; verification function has not moved point
10923 (goto-char (point-at-eol))))))))
10924 (when org-refile-use-cache
10925 (org-refile-cache-put tgs (buffer-file-name) descre))
10926 (setq targets (append tgs targets))
10927 ))))
10928 (message "Getting targets...done")
10929 (nreverse targets)))
10931 (defun org-protect-slash (s)
10932 (while (string-match "/" s)
10933 (setq s (replace-match "\\" t t s)))
10936 (defvar org-olpa (make-vector 20 nil))
10938 (defun org-get-outline-path (&optional fastp level heading)
10939 "Return the outline path to the current entry, as a list.
10941 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10942 routine which makes outline path derivations for an entire file,
10943 avoiding backtracing. Refile target collection makes use of that."
10944 (if fastp
10945 (progn
10946 (if (> level 19)
10947 (error "Outline path failure, more than 19 levels"))
10948 (loop for i from level upto 19 do
10949 (aset org-olpa i nil))
10950 (prog1
10951 (delq nil (append org-olpa nil))
10952 (aset org-olpa level heading)))
10953 (let (rtn case-fold-search)
10954 (save-excursion
10955 (save-restriction
10956 (widen)
10957 (while (org-up-heading-safe)
10958 (when (looking-at org-complex-heading-regexp)
10959 (push (org-match-string-no-properties 4) rtn)))
10960 rtn)))))
10962 (defun org-format-outline-path (path &optional width prefix separator)
10963 "Format the outline path PATH for display.
10964 WIDTH is the maximum number of characters that is available.
10965 PREFIX is a prefix to be included in the returned string,
10966 such as the file name.
10967 SEPARATOR is inserted between the different parts of the path,
10968 the default is \"/\"."
10969 (setq width (or width 79))
10970 (if prefix (setq width (- width (length prefix))))
10971 (if (not path)
10972 (or prefix "")
10973 (let* ((nsteps (length path))
10974 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10975 (maxwidth (if (<= total-width width)
10976 10000 ;; everything fits
10977 ;; we need to shorten the level headings
10978 (/ (- width nsteps) nsteps)))
10979 (org-odd-levels-only nil)
10980 (n 0)
10981 (total (1+ (length prefix))))
10982 (setq maxwidth (max maxwidth 10))
10983 (concat prefix
10984 (if prefix (or separator "/"))
10985 (mapconcat
10986 (lambda (h)
10987 (setq n (1+ n))
10988 (if (and (= n nsteps) (< maxwidth 10000))
10989 (setq maxwidth (- total-width total)))
10990 (if (< (length h) maxwidth)
10991 (progn (setq total (+ total (length h) 1)) h)
10992 (setq h (substring h 0 (- maxwidth 2))
10993 total (+ total maxwidth 1))
10994 (if (string-match "[ \t]+\\'" h)
10995 (setq h (substring h 0 (match-beginning 0))))
10996 (setq h (concat h "..")))
10997 (org-add-props h nil 'face
10998 (nth (% (1- n) org-n-level-faces)
10999 org-level-faces))
11001 path (or separator "/"))))))
11003 (defun org-display-outline-path (&optional file current separator just-return-string)
11004 "Display the current outline path in the echo area.
11006 If FILE is non-nil, prepend the output with the file name.
11007 If CURRENT is non-nil, append the current heading to the output.
11008 SEPARATOR is passed through to `org-format-outline-path'. It separates
11009 the different parts of the path and defaults to \"/\".
11010 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11011 (interactive "P")
11012 (let* (case-fold-search
11013 message-log-max ; Don't populate the *Messages* buffer
11014 (bfn (buffer-file-name (buffer-base-buffer)))
11015 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11016 res)
11017 (if current (setq path (append path
11018 (save-excursion
11019 (org-back-to-heading t)
11020 (if (looking-at org-complex-heading-regexp)
11021 (list (match-string 4)))))))
11022 (setq res
11023 (org-format-outline-path
11024 path
11025 (1- (frame-width))
11026 (and file bfn (concat (file-name-nondirectory bfn) separator))
11027 separator))
11028 (if just-return-string
11029 (org-no-properties res)
11030 (message "%s" res))))
11032 (defvar org-refile-history nil
11033 "History for refiling operations.")
11035 (defvar org-after-refile-insert-hook nil
11036 "Hook run after `org-refile' has inserted its stuff at the new location.
11037 Note that this is still *before* the stuff will be removed from
11038 the *old* location.")
11040 (defvar org-capture-last-stored-marker)
11041 (defvar org-refile-keep nil
11042 "Non-nil means `org-refile' will copy instead of refile.")
11044 (defun org-copy ()
11045 "Like `org-refile', but copy."
11046 (interactive)
11047 (let ((org-refile-keep t))
11048 (funcall 'org-refile nil nil nil "Copy")))
11050 (defun org-refile (&optional goto default-buffer rfloc msg)
11051 "Move the entry or entries at point to another heading.
11052 The list of target headings is compiled using the information in
11053 `org-refile-targets', which see.
11055 At the target location, the entry is filed as a subitem of the target
11056 heading. Depending on `org-reverse-note-order', the new subitem will
11057 either be the first or the last subitem.
11059 If there is an active region, all entries in that region will be moved.
11060 However, the region must fulfill the requirement that the first heading
11061 is the first one sets the top-level of the moved text - at most siblings
11062 below it are allowed.
11064 With prefix arg GOTO, the command will only visit the target location
11065 and not actually move anything.
11067 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11068 go to the location where the last refiling operation has put the subtree.
11069 With a prefix argument of `2', refile to the running clock.
11071 RFLOC can be a refile location obtained in a different way.
11073 MSG is a string to replace \"Refile\" in the default prompt with
11074 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11076 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11078 If you are using target caching (see `org-refile-use-cache'),
11079 you have to clear the target cache in order to find new targets.
11080 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11081 prefix argument (`C-u C-u C-u C-c C-w')."
11083 (interactive "P")
11084 (if (member goto '(0 (64)))
11085 (org-refile-cache-clear)
11086 (let* ((actionmsg (or msg "Refile"))
11087 (cbuf (current-buffer))
11088 (regionp (org-region-active-p))
11089 (region-start (and regionp (region-beginning)))
11090 (region-end (and regionp (region-end)))
11091 (region-length (and regionp (- region-end region-start)))
11092 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11093 pos it nbuf file re level reversed)
11094 (setq last-command nil)
11095 (when regionp
11096 (goto-char region-start)
11097 (or (bolp) (goto-char (point-at-bol)))
11098 (setq region-start (point))
11099 (unless (or (org-kill-is-subtree-p
11100 (buffer-substring region-start region-end))
11101 (prog1 org-refile-active-region-within-subtree
11102 (org-toggle-heading)))
11103 (error "The region is not a (sequence of) subtree(s)")))
11104 (if (equal goto '(16))
11105 (org-refile-goto-last-stored)
11106 (when (or
11107 (and (equal goto 2)
11108 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11109 (prog1
11110 (setq it (list (or org-clock-heading "running clock")
11111 (buffer-file-name
11112 (marker-buffer org-clock-hd-marker))
11114 (marker-position org-clock-hd-marker)))
11115 (setq goto nil)))
11116 (setq it (or rfloc
11117 (let (heading-text)
11118 (save-excursion
11119 (unless goto
11120 (org-back-to-heading t)
11121 (setq heading-text
11122 (nth 4 (org-heading-components))))
11124 (org-refile-get-location
11125 (cond (goto "Goto")
11126 (regionp (concat actionmsg " region to"))
11127 (t (concat actionmsg " subtree \""
11128 heading-text "\" to")))
11129 default-buffer
11130 (and (not (equal '(4) goto))
11131 org-refile-allow-creating-parent-nodes)
11132 goto))))))
11133 (setq file (nth 1 it)
11134 re (nth 2 it)
11135 pos (nth 3 it))
11136 (if (and (not goto)
11138 (equal (buffer-file-name) file)
11139 (if regionp
11140 (and (>= pos region-start)
11141 (<= pos region-end))
11142 (and (>= pos (point))
11143 (< pos (save-excursion
11144 (org-end-of-subtree t t))))))
11145 (error "Cannot refile to position inside the tree or region"))
11147 (setq nbuf (or (find-buffer-visiting file)
11148 (find-file-noselect file)))
11149 (if goto
11150 (progn
11151 (org-pop-to-buffer-same-window nbuf)
11152 (goto-char pos)
11153 (org-show-context 'org-goto))
11154 (if regionp
11155 (progn
11156 (org-kill-new (buffer-substring region-start region-end))
11157 (org-save-markers-in-region region-start region-end))
11158 (org-copy-subtree 1 nil t))
11159 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11160 (find-file-noselect file)))
11161 (setq reversed (org-notes-order-reversed-p))
11162 (save-excursion
11163 (save-restriction
11164 (widen)
11165 (if pos
11166 (progn
11167 (goto-char pos)
11168 (looking-at org-outline-regexp)
11169 (setq level (org-get-valid-level (funcall outline-level) 1))
11170 (goto-char
11171 (if reversed
11172 (or (outline-next-heading) (point-max))
11173 (or (save-excursion (org-get-next-sibling))
11174 (org-end-of-subtree t t)
11175 (point-max)))))
11176 (setq level 1)
11177 (if (not reversed)
11178 (goto-char (point-max))
11179 (goto-char (point-min))
11180 (or (outline-next-heading) (goto-char (point-max)))))
11181 (if (not (bolp)) (newline))
11182 (org-paste-subtree level)
11183 (when org-log-refile
11184 (org-add-log-setup 'refile nil nil 'findpos
11185 org-log-refile)
11186 (unless (eq org-log-refile 'note)
11187 (save-excursion (org-add-log-note))))
11188 (and org-auto-align-tags
11189 (let ((org-loop-over-headlines-in-active-region nil))
11190 (org-set-tags nil t)))
11191 (with-demoted-errors
11192 (bookmark-set "org-refile-last-stored"))
11193 ;; If we are refiling for capture, make sure that the
11194 ;; last-capture pointers point here
11195 (when (org-bound-and-true-p org-refile-for-capture)
11196 (with-demoted-errors
11197 (bookmark-set "org-capture-last-stored-marker"))
11198 (move-marker org-capture-last-stored-marker (point)))
11199 (if (fboundp 'deactivate-mark) (deactivate-mark))
11200 (run-hooks 'org-after-refile-insert-hook))))
11201 (unless org-refile-keep
11202 (if regionp
11203 (delete-region (point) (+ (point) region-length))
11204 (org-cut-subtree)))
11205 (when (featurep 'org-inlinetask)
11206 (org-inlinetask-remove-END-maybe))
11207 (setq org-markers-to-move nil)
11208 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11210 (defun org-refile-goto-last-stored ()
11211 "Go to the location where the last refile was stored."
11212 (interactive)
11213 (bookmark-jump "org-refile-last-stored")
11214 (message "This is the location of the last refile"))
11216 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11217 no-exclude)
11218 "Prompt the user for a refile location, using PROMPT.
11219 PROMPT should not be suffixed with a colon and a space, because
11220 this function appends the default value from
11221 `org-refile-history' automatically, if that is not empty.
11222 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11223 this is used for the GOTO interface."
11224 (let ((org-refile-targets org-refile-targets)
11225 (org-refile-use-outline-path org-refile-use-outline-path)
11226 excluded-entries)
11227 (when (and (derived-mode-p 'org-mode)
11228 (not org-refile-use-cache)
11229 (not no-exclude))
11230 (org-map-tree
11231 (lambda()
11232 (setq excluded-entries
11233 (append excluded-entries (list (org-get-heading t t)))))))
11234 (setq org-refile-target-table
11235 (org-refile-get-targets default-buffer excluded-entries)))
11236 (unless org-refile-target-table
11237 (error "No refile targets"))
11238 (let* ((cbuf (current-buffer))
11239 (partial-completion-mode nil)
11240 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11241 (cfunc (if (and org-refile-use-outline-path
11242 org-outline-path-complete-in-steps)
11243 'org-olpath-completing-read
11244 'org-icompleting-read))
11245 (extra (if org-refile-use-outline-path "/" ""))
11246 (cbnex (concat (buffer-name) extra))
11247 (filename (and cfn (expand-file-name cfn)))
11248 (tbl (mapcar
11249 (lambda (x)
11250 (if (and (not (member org-refile-use-outline-path
11251 '(file full-file-path)))
11252 (not (equal filename (nth 1 x))))
11253 (cons (concat (car x) extra " ("
11254 (file-name-nondirectory (nth 1 x)) ")")
11255 (cdr x))
11256 (cons (concat (car x) extra) (cdr x))))
11257 org-refile-target-table))
11258 (completion-ignore-case t)
11259 cdef
11260 (prompt (concat prompt
11261 (or (and (car org-refile-history)
11262 (concat " (default " (car org-refile-history) ")"))
11263 (and (assoc cbnex tbl) (setq cdef cbnex)
11264 (concat " (default " cbnex ")"))) ": "))
11265 pa answ parent-target child parent old-hist)
11266 (setq old-hist org-refile-history)
11267 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11268 nil 'org-refile-history (or cdef (car org-refile-history))))
11269 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11270 (org-refile-check-position pa)
11271 (if pa
11272 (progn
11273 (when (or (not org-refile-history)
11274 (not (eq old-hist org-refile-history))
11275 (not (equal (car pa) (car org-refile-history))))
11276 (setq org-refile-history
11277 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11278 org-refile-history
11279 (cdr org-refile-history))))
11280 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11281 (pop org-refile-history)))
11283 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11284 (progn
11285 (setq parent (match-string 1 answ)
11286 child (match-string 2 answ))
11287 (setq parent-target (or (assoc parent tbl)
11288 (assoc (concat parent "/") tbl)))
11289 (when (and parent-target
11290 (or (eq new-nodes t)
11291 (and (eq new-nodes 'confirm)
11292 (y-or-n-p (format "Create new node \"%s\"? "
11293 child)))))
11294 (org-refile-new-child parent-target child)))
11295 (error "Invalid target location")))))
11297 (declare-function org-string-nw-p "org-macs" (s))
11298 (defun org-refile-check-position (refile-pointer)
11299 "Check if the refile pointer matches the headline to which it points."
11300 (let* ((file (nth 1 refile-pointer))
11301 (re (nth 2 refile-pointer))
11302 (pos (nth 3 refile-pointer))
11303 buffer)
11304 (if (and (not (markerp pos)) (not file))
11305 (error "Please save the buffer to a file before refiling")
11306 (when (org-string-nw-p re)
11307 (setq buffer (if (markerp pos)
11308 (marker-buffer pos)
11309 (or (find-buffer-visiting file)
11310 (find-file-noselect file))))
11311 (with-current-buffer buffer
11312 (save-excursion
11313 (save-restriction
11314 (widen)
11315 (goto-char pos)
11316 (beginning-of-line 1)
11317 (unless (org-looking-at-p re)
11318 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11320 (defun org-refile-new-child (parent-target child)
11321 "Use refile target PARENT-TARGET to add new CHILD below it."
11322 (unless parent-target
11323 (error "Cannot find parent for new node"))
11324 (let ((file (nth 1 parent-target))
11325 (pos (nth 3 parent-target))
11326 level)
11327 (with-current-buffer (or (find-buffer-visiting file)
11328 (find-file-noselect file))
11329 (save-excursion
11330 (save-restriction
11331 (widen)
11332 (if pos
11333 (goto-char pos)
11334 (goto-char (point-max))
11335 (if (not (bolp)) (newline)))
11336 (when (looking-at org-outline-regexp)
11337 (setq level (funcall outline-level))
11338 (org-end-of-subtree t t))
11339 (org-back-over-empty-lines)
11340 (insert "\n" (make-string
11341 (if pos (org-get-valid-level level 1) 1) ?*)
11342 " " child "\n")
11343 (beginning-of-line 0)
11344 (list (concat (car parent-target) "/" child) file "" (point)))))))
11346 (defun org-olpath-completing-read (prompt collection &rest args)
11347 "Read an outline path like a file name."
11348 (let ((thetable collection)
11349 (org-completion-use-ido nil) ; does not work with ido.
11350 (org-completion-use-iswitchb nil)) ; or iswitchb
11351 (apply
11352 'org-icompleting-read prompt
11353 (lambda (string predicate &optional flag)
11354 (let (rtn r f (l (length string)))
11355 (cond
11356 ((eq flag nil)
11357 ;; try completion
11358 (try-completion string thetable))
11359 ((eq flag t)
11360 ;; all-completions
11361 (setq rtn (all-completions string thetable predicate))
11362 (mapcar
11363 (lambda (x)
11364 (setq r (substring x l))
11365 (if (string-match " ([^)]*)$" x)
11366 (setq f (match-string 0 x))
11367 (setq f ""))
11368 (if (string-match "/" r)
11369 (concat string (substring r 0 (match-end 0)) f)
11371 rtn))
11372 ((eq flag 'lambda)
11373 ;; exact match?
11374 (assoc string thetable)))))
11375 args)))
11377 ;;;; Dynamic blocks
11379 (defun org-find-dblock (name)
11380 "Find the first dynamic block with name NAME in the buffer.
11381 If not found, stay at current position and return nil."
11382 (let ((case-fold-search t) pos)
11383 (save-excursion
11384 (goto-char (point-min))
11385 (setq pos (and (re-search-forward
11386 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11387 (match-beginning 0))))
11388 (if pos (goto-char pos))
11389 pos))
11391 (defconst org-dblock-start-re
11392 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11393 "Matches the start line of a dynamic block, with parameters.")
11395 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11396 "Matches the end of a dynamic block.")
11398 (defun org-create-dblock (plist)
11399 "Create a dynamic block section, with parameters taken from PLIST.
11400 PLIST must contain a :name entry which is used as name of the block."
11401 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11402 (end-of-line 1)
11403 (newline))
11404 (let ((col (current-column))
11405 (name (plist-get plist :name)))
11406 (insert "#+BEGIN: " name)
11407 (while plist
11408 (if (eq (car plist) :name)
11409 (setq plist (cddr plist))
11410 (insert " " (prin1-to-string (pop plist)))))
11411 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11412 (beginning-of-line -2)))
11414 (defun org-prepare-dblock ()
11415 "Prepare dynamic block for refresh.
11416 This empties the block, puts the cursor at the insert position and returns
11417 the property list including an extra property :name with the block name."
11418 (unless (looking-at org-dblock-start-re)
11419 (error "Not at a dynamic block"))
11420 (let* ((begdel (1+ (match-end 0)))
11421 (name (org-no-properties (match-string 1)))
11422 (params (append (list :name name)
11423 (read (concat "(" (match-string 3) ")")))))
11424 (save-excursion
11425 (beginning-of-line 1)
11426 (skip-chars-forward " \t")
11427 (setq params (plist-put params :indentation-column (current-column))))
11428 (unless (re-search-forward org-dblock-end-re nil t)
11429 (error "Dynamic block not terminated"))
11430 (setq params
11431 (append params
11432 (list :content (buffer-substring
11433 begdel (match-beginning 0)))))
11434 (delete-region begdel (match-beginning 0))
11435 (goto-char begdel)
11436 (open-line 1)
11437 params))
11439 (defun org-map-dblocks (&optional command)
11440 "Apply COMMAND to all dynamic blocks in the current buffer.
11441 If COMMAND is not given, use `org-update-dblock'."
11442 (let ((cmd (or command 'org-update-dblock)))
11443 (save-excursion
11444 (goto-char (point-min))
11445 (while (re-search-forward org-dblock-start-re nil t)
11446 (goto-char (match-beginning 0))
11447 (save-excursion
11448 (condition-case nil
11449 (funcall cmd)
11450 (error (message "Error during update of dynamic block"))))
11451 (unless (re-search-forward org-dblock-end-re nil t)
11452 (error "Dynamic block not terminated"))))))
11454 (defun org-dblock-update (&optional arg)
11455 "User command for updating dynamic blocks.
11456 Update the dynamic block at point. With prefix ARG, update all dynamic
11457 blocks in the buffer."
11458 (interactive "P")
11459 (if arg
11460 (org-update-all-dblocks)
11461 (or (looking-at org-dblock-start-re)
11462 (org-beginning-of-dblock))
11463 (org-update-dblock)))
11465 (defun org-update-dblock ()
11466 "Update the dynamic block at point.
11467 This means to empty the block, parse for parameters and then call
11468 the correct writing function."
11469 (interactive)
11470 (save-window-excursion
11471 (let* ((pos (point))
11472 (line (org-current-line))
11473 (params (org-prepare-dblock))
11474 (name (plist-get params :name))
11475 (indent (plist-get params :indentation-column))
11476 (cmd (intern (concat "org-dblock-write:" name))))
11477 (message "Updating dynamic block `%s' at line %d..." name line)
11478 (funcall cmd params)
11479 (message "Updating dynamic block `%s' at line %d...done" name line)
11480 (goto-char pos)
11481 (when (and indent (> indent 0))
11482 (setq indent (make-string indent ?\ ))
11483 (save-excursion
11484 (org-beginning-of-dblock)
11485 (forward-line 1)
11486 (while (not (looking-at org-dblock-end-re))
11487 (insert indent)
11488 (beginning-of-line 2))
11489 (when (looking-at org-dblock-end-re)
11490 (and (looking-at "[ \t]+")
11491 (replace-match ""))
11492 (insert indent)))))))
11494 (defun org-beginning-of-dblock ()
11495 "Find the beginning of the dynamic block at point.
11496 Error if there is no such block at point."
11497 (let ((pos (point))
11498 beg)
11499 (end-of-line 1)
11500 (if (and (re-search-backward org-dblock-start-re nil t)
11501 (setq beg (match-beginning 0))
11502 (re-search-forward org-dblock-end-re nil t)
11503 (> (match-end 0) pos))
11504 (goto-char beg)
11505 (goto-char pos)
11506 (error "Not in a dynamic block"))))
11508 (defun org-update-all-dblocks ()
11509 "Update all dynamic blocks in the buffer.
11510 This function can be used in a hook."
11511 (interactive)
11512 (when (derived-mode-p 'org-mode)
11513 (org-map-dblocks 'org-update-dblock)))
11516 ;;;; Completion
11518 (defun org-get-export-keywords ()
11519 "Return a list of all currently understood export keywords.
11520 Export keywords include options, block names, attributes and
11521 keywords relative to each registered export back-end."
11522 (delq nil
11523 (let (keywords)
11524 (mapc
11525 (lambda (back-end)
11526 (let ((props (cdr back-end)))
11527 ;; Back-end name (for keywords, like #+LATEX:)
11528 (push (upcase (symbol-name (car back-end))) keywords)
11529 ;; Back-end options.
11530 (mapc (lambda (option) (push (cadr option) keywords))
11531 (plist-get (cdr back-end) :options-alist))))
11532 (org-bound-and-true-p org-export-registered-backends))
11533 keywords)))
11535 (defconst org-options-keywords
11536 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11537 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11538 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11539 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11540 "TITLE:" "TODO:" "TYP_TODO:"))
11542 (defcustom org-structure-template-alist
11543 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11544 "<src lang=\"?\">\n\n</src>")
11545 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11546 "<example>\n?\n</example>")
11547 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11548 "<quote>\n?\n</quote>")
11549 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11550 "<verse>\n?\n</verse>")
11551 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11552 "<verbatim>\n?\n</verbatim>")
11553 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11554 "<center>\n?\n</center>")
11555 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11556 "<literal style=\"latex\">\n?\n</literal>")
11557 ("L" "#+LaTeX: "
11558 "<literal style=\"latex\">?</literal>")
11559 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11560 "<literal style=\"html\">\n?\n</literal>")
11561 ("H" "#+HTML: "
11562 "<literal style=\"html\">?</literal>")
11563 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11564 ("A" "#+ASCII: ")
11565 ("i" "#+INDEX: ?"
11566 "#+INDEX: ?")
11567 ("I" "#+INCLUDE: %file ?"
11568 "<include file=%file markup=\"?\">"))
11569 "Structure completion elements.
11570 This is a list of abbreviation keys and values. The value gets inserted
11571 if you type `<' followed by the key and then press the completion key,
11572 usually `M-TAB'. %file will be replaced by a file name after prompting
11573 for the file using completion. The cursor will be placed at the position
11574 of the `?` in the template.
11575 There are two templates for each key, the first uses the original Org syntax,
11576 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11577 the default when the /org-mtags.el/ module has been loaded. See also the
11578 variable `org-mtags-prefer-muse-templates'."
11579 :group 'org-completion
11580 :type '(repeat
11581 (string :tag "Key")
11582 (string :tag "Template")
11583 (string :tag "Muse Template")))
11585 (defun org-try-structure-completion ()
11586 "Try to complete a structure template before point.
11587 This looks for strings like \"<e\" on an otherwise empty line and
11588 expands them."
11589 (let ((l (buffer-substring (point-at-bol) (point)))
11591 (when (and (looking-at "[ \t]*$")
11592 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11593 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11594 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11595 (match-beginning 1)) a)
11596 t)))
11598 (defun org-complete-expand-structure-template (start cell)
11599 "Expand a structure template."
11600 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11601 (rpl (nth (if musep 2 1) cell))
11602 (ind ""))
11603 (delete-region start (point))
11604 (when (string-match "\\`#\\+" rpl)
11605 (cond
11606 ((bolp))
11607 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11608 (setq ind (buffer-substring (point-at-bol) (point))))
11609 (t (newline))))
11610 (setq start (point))
11611 (if (string-match "%file" rpl)
11612 (setq rpl (replace-match
11613 (concat
11614 "\""
11615 (save-match-data
11616 (abbreviate-file-name (read-file-name "Include file: ")))
11617 "\"")
11618 t t rpl)))
11619 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11620 (concat "\n" ind)))
11621 (insert rpl)
11622 (if (re-search-backward "\\?" start t) (delete-char 1))))
11624 ;;;; TODO, DEADLINE, Comments
11626 (defun org-toggle-comment ()
11627 "Change the COMMENT state of an entry."
11628 (interactive)
11629 (save-excursion
11630 (org-back-to-heading)
11631 (let (case-fold-search)
11632 (cond
11633 ((looking-at (format org-heading-keyword-regexp-format
11634 org-comment-string))
11635 (goto-char (match-end 1))
11636 (looking-at (concat " +" org-comment-string))
11637 (replace-match "" t t)
11638 (when (eolp) (insert " ")))
11639 ((looking-at org-outline-regexp)
11640 (goto-char (match-end 0))
11641 (insert org-comment-string " "))))))
11643 (defvar org-last-todo-state-is-todo nil
11644 "This is non-nil when the last TODO state change led to a TODO state.
11645 If the last change removed the TODO tag or switched to DONE, then
11646 this is nil.")
11648 (defvar org-setting-tags nil) ; dynamically skipped
11650 (defvar org-todo-setup-filter-hook nil
11651 "Hook for functions that pre-filter todo specs.
11652 Each function takes a todo spec and returns either nil or the spec
11653 transformed into canonical form." )
11655 (defvar org-todo-get-default-hook nil
11656 "Hook for functions that get a default item for todo.
11657 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11658 nil or a string to be used for the todo mark." )
11660 (defvar org-agenda-headline-snapshot-before-repeat)
11662 (defun org-current-effective-time ()
11663 "Return current time adjusted for `org-extend-today-until' variable."
11664 (let* ((ct (org-current-time))
11665 (dct (decode-time ct))
11666 (ct1
11667 (cond
11668 (org-use-last-clock-out-time-as-effective-time
11669 (or (org-clock-get-last-clock-out-time) ct))
11670 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11671 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11672 (t ct))))
11673 ct1))
11675 (defun org-todo-yesterday (&optional arg)
11676 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11677 (interactive "P")
11678 (if (eq major-mode 'org-agenda-mode)
11679 (apply 'org-agenda-todo-yesterday arg)
11680 (let* ((hour (third (decode-time
11681 (org-current-time))))
11682 (org-extend-today-until (1+ hour)))
11683 (org-todo arg))))
11685 (defvar org-block-entry-blocking ""
11686 "First entry preventing the TODO state change.")
11688 (defun org-todo (&optional arg)
11689 "Change the TODO state of an item.
11690 The state of an item is given by a keyword at the start of the heading,
11691 like
11692 *** TODO Write paper
11693 *** DONE Call mom
11695 The different keywords are specified in the variable `org-todo-keywords'.
11696 By default the available states are \"TODO\" and \"DONE\".
11697 So for this example: when the item starts with TODO, it is changed to DONE.
11698 When it starts with DONE, the DONE is removed. And when neither TODO nor
11699 DONE are present, add TODO at the beginning of the heading.
11701 With \\[universal-argument] prefix arg, use completion to determine the new \
11702 state.
11703 With numeric prefix arg, switch to that state.
11704 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11705 keywords (nextset).
11706 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11707 With a numeric prefix arg of 0, inhibit note taking for the change.
11709 For calling through lisp, arg is also interpreted in the following way:
11710 'none -> empty state
11711 \"\"(empty string) -> switch to empty state
11712 'done -> switch to DONE
11713 'nextset -> switch to the next set of keywords
11714 'previousset -> switch to the previous set of keywords
11715 \"WAITING\" -> switch to the specified keyword, but only if it
11716 really is a member of `org-todo-keywords'."
11717 (interactive "P")
11718 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11719 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11720 'region-start-level 'region))
11721 org-loop-over-headlines-in-active-region)
11722 (org-map-entries
11723 `(org-todo ,arg)
11724 org-loop-over-headlines-in-active-region
11725 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11726 (if (equal arg '(16)) (setq arg 'nextset))
11727 (let ((org-blocker-hook org-blocker-hook)
11728 commentp
11729 case-fold-search)
11730 (when (equal arg '(64))
11731 (setq arg nil org-blocker-hook nil))
11732 (when (and org-blocker-hook
11733 (or org-inhibit-blocking
11734 (org-entry-get nil "NOBLOCKING")))
11735 (setq org-blocker-hook nil))
11736 (save-excursion
11737 (catch 'exit
11738 (org-back-to-heading t)
11739 (when (looking-at (concat "^\\*+ " org-comment-string))
11740 (org-toggle-comment)
11741 (setq commentp t))
11742 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11743 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11744 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11745 (let* ((match-data (match-data))
11746 (startpos (point-at-bol))
11747 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11748 (org-log-done org-log-done)
11749 (org-log-repeat org-log-repeat)
11750 (org-todo-log-states org-todo-log-states)
11751 (org-inhibit-logging
11752 (if (equal arg 0)
11753 (progn (setq arg nil) 'note) org-inhibit-logging))
11754 (this (match-string 1))
11755 (hl-pos (match-beginning 0))
11756 (head (org-get-todo-sequence-head this))
11757 (ass (assoc head org-todo-kwd-alist))
11758 (interpret (nth 1 ass))
11759 (done-word (nth 3 ass))
11760 (final-done-word (nth 4 ass))
11761 (org-last-state (or this ""))
11762 (completion-ignore-case t)
11763 (member (member this org-todo-keywords-1))
11764 (tail (cdr member))
11765 (org-state (cond
11766 ((and org-todo-key-trigger
11767 (or (and (equal arg '(4))
11768 (eq org-use-fast-todo-selection 'prefix))
11769 (and (not arg) org-use-fast-todo-selection
11770 (not (eq org-use-fast-todo-selection
11771 'prefix)))))
11772 ;; Use fast selection
11773 (org-fast-todo-selection))
11774 ((and (equal arg '(4))
11775 (or (not org-use-fast-todo-selection)
11776 (not org-todo-key-trigger)))
11777 ;; Read a state with completion
11778 (org-icompleting-read
11779 "State: " (mapcar (lambda(x) (list x))
11780 org-todo-keywords-1)
11781 nil t))
11782 ((eq arg 'right)
11783 (if this
11784 (if tail (car tail) nil)
11785 (car org-todo-keywords-1)))
11786 ((eq arg 'left)
11787 (if (equal member org-todo-keywords-1)
11789 (if this
11790 (nth (- (length org-todo-keywords-1)
11791 (length tail) 2)
11792 org-todo-keywords-1)
11793 (org-last org-todo-keywords-1))))
11794 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11795 (setq arg nil))) ; hack to fall back to cycling
11796 (arg
11797 ;; user or caller requests a specific state
11798 (cond
11799 ((equal arg "") nil)
11800 ((eq arg 'none) nil)
11801 ((eq arg 'done) (or done-word (car org-done-keywords)))
11802 ((eq arg 'nextset)
11803 (or (car (cdr (member head org-todo-heads)))
11804 (car org-todo-heads)))
11805 ((eq arg 'previousset)
11806 (let ((org-todo-heads (reverse org-todo-heads)))
11807 (or (car (cdr (member head org-todo-heads)))
11808 (car org-todo-heads))))
11809 ((car (member arg org-todo-keywords-1)))
11810 ((stringp arg)
11811 (error "State `%s' not valid in this file" arg))
11812 ((nth (1- (prefix-numeric-value arg))
11813 org-todo-keywords-1))))
11814 ((null member) (or head (car org-todo-keywords-1)))
11815 ((equal this final-done-word) nil) ;; -> make empty
11816 ((null tail) nil) ;; -> first entry
11817 ((memq interpret '(type priority))
11818 (if (eq this-command last-command)
11819 (car tail)
11820 (if (> (length tail) 0)
11821 (or done-word (car org-done-keywords))
11822 nil)))
11824 (car tail))))
11825 (org-state (or
11826 (run-hook-with-args-until-success
11827 'org-todo-get-default-hook org-state org-last-state)
11828 org-state))
11829 (next (if org-state (concat " " org-state " ") " "))
11830 (change-plist (list :type 'todo-state-change :from this :to org-state
11831 :position startpos))
11832 dolog now-done-p)
11833 (when org-blocker-hook
11834 (setq org-last-todo-state-is-todo
11835 (not (member this org-done-keywords)))
11836 (unless (save-excursion
11837 (save-match-data
11838 (org-with-wide-buffer
11839 (run-hook-with-args-until-failure
11840 'org-blocker-hook change-plist))))
11841 (if (org-called-interactively-p 'interactive)
11842 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11843 this org-state org-block-entry-blocking)
11844 ;; fail silently
11845 (message "TODO state change from %s to %s blocked (by \"%s\")"
11846 this org-state org-block-entry-blocking)
11847 (throw 'exit nil))))
11848 (store-match-data match-data)
11849 (replace-match next t t)
11850 (unless (pos-visible-in-window-p hl-pos)
11851 (message "TODO state changed to %s" (org-trim next)))
11852 (unless head
11853 (setq head (org-get-todo-sequence-head org-state)
11854 ass (assoc head org-todo-kwd-alist)
11855 interpret (nth 1 ass)
11856 done-word (nth 3 ass)
11857 final-done-word (nth 4 ass)))
11858 (when (memq arg '(nextset previousset))
11859 (message "Keyword-Set %d/%d: %s"
11860 (- (length org-todo-sets) -1
11861 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11862 (length org-todo-sets)
11863 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11864 (setq org-last-todo-state-is-todo
11865 (not (member org-state org-done-keywords)))
11866 (setq now-done-p (and (member org-state org-done-keywords)
11867 (not (member this org-done-keywords))))
11868 (and logging (org-local-logging logging))
11869 (when (and (or org-todo-log-states org-log-done)
11870 (not (eq org-inhibit-logging t))
11871 (not (memq arg '(nextset previousset))))
11872 ;; we need to look at recording a time and note
11873 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11874 (nth 2 (assoc this org-todo-log-states))))
11875 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11876 (setq dolog 'time))
11877 (when (and org-state
11878 (member org-state org-not-done-keywords)
11879 (not (member this org-not-done-keywords)))
11880 ;; This is now a todo state and was not one before
11881 ;; If there was a CLOSED time stamp, get rid of it.
11882 (org-add-planning-info nil nil 'closed))
11883 (when (and now-done-p org-log-done)
11884 ;; It is now done, and it was not done before
11885 (org-add-planning-info 'closed (org-current-effective-time))
11886 (if (and (not dolog) (eq 'note org-log-done))
11887 (org-add-log-setup 'done org-state this 'findpos 'note)))
11888 (when (and org-state dolog)
11889 ;; This is a non-nil state, and we need to log it
11890 (org-add-log-setup 'state org-state this 'findpos dolog)))
11891 ;; Fixup tag positioning
11892 (org-todo-trigger-tag-changes org-state)
11893 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11894 (when org-provide-todo-statistics
11895 (org-update-parent-todo-statistics))
11896 (run-hooks 'org-after-todo-state-change-hook)
11897 (if (and arg (not (member org-state org-done-keywords)))
11898 (setq head (org-get-todo-sequence-head org-state)))
11899 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11900 ;; Do we need to trigger a repeat?
11901 (when now-done-p
11902 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11903 ;; This is for the agenda, take a snapshot of the headline.
11904 (save-match-data
11905 (setq org-agenda-headline-snapshot-before-repeat
11906 (org-get-heading))))
11907 (org-auto-repeat-maybe org-state))
11908 ;; Fixup cursor location if close to the keyword
11909 (if (and (outline-on-heading-p)
11910 (not (bolp))
11911 (save-excursion (beginning-of-line 1)
11912 (looking-at org-todo-line-regexp))
11913 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11914 (progn
11915 (goto-char (or (match-end 2) (match-end 1)))
11916 (and (looking-at " ") (just-one-space))))
11917 (when org-trigger-hook
11918 (save-excursion
11919 (run-hook-with-args 'org-trigger-hook change-plist)))
11920 (when commentp (org-toggle-comment))))))))
11922 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11923 "Block turning an entry into a TODO, using the hierarchy.
11924 This checks whether the current task should be blocked from state
11925 changes. Such blocking occurs when:
11927 1. The task has children which are not all in a completed state.
11929 2. A task has a parent with the property :ORDERED:, and there
11930 are siblings prior to the current task with incomplete
11931 status.
11933 3. The parent of the task is blocked because it has siblings that should
11934 be done first, or is child of a block grandparent TODO entry."
11936 (if (not org-enforce-todo-dependencies)
11937 t ; if locally turned off don't block
11938 (catch 'dont-block
11939 ;; If this is not a todo state change, or if this entry is already DONE,
11940 ;; do not block
11941 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11942 (member (plist-get change-plist :from)
11943 (cons 'done org-done-keywords))
11944 (member (plist-get change-plist :to)
11945 (cons 'todo org-not-done-keywords))
11946 (not (plist-get change-plist :to)))
11947 (throw 'dont-block t))
11948 ;; If this task has children, and any are undone, it's blocked
11949 (save-excursion
11950 (org-back-to-heading t)
11951 (let ((this-level (funcall outline-level)))
11952 (outline-next-heading)
11953 (let ((child-level (funcall outline-level)))
11954 (while (and (not (eobp))
11955 (> child-level this-level))
11956 ;; this todo has children, check whether they are all
11957 ;; completed
11958 (if (and (not (org-entry-is-done-p))
11959 (org-entry-is-todo-p))
11960 (progn (setq org-block-entry-blocking (org-get-heading))
11961 (throw 'dont-block nil)))
11962 (outline-next-heading)
11963 (setq child-level (funcall outline-level))))))
11964 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11965 ;; any previous siblings are undone, it's blocked
11966 (save-excursion
11967 (org-back-to-heading t)
11968 (let* ((pos (point))
11969 (parent-pos (and (org-up-heading-safe) (point))))
11970 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11971 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11972 (forward-line 1)
11973 (re-search-forward org-not-done-heading-regexp pos t))
11974 (setq org-block-entry-blocking (match-string 0))
11975 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11976 ;; Search further up the hierarchy, to see if an ancestor is blocked
11977 (while t
11978 (goto-char parent-pos)
11979 (if (not (looking-at org-not-done-heading-regexp))
11980 (throw 'dont-block t)) ; do not block, parent is not a TODO
11981 (setq pos (point))
11982 (setq parent-pos (and (org-up-heading-safe) (point)))
11983 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11984 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11985 (forward-line 1)
11986 (re-search-forward org-not-done-heading-regexp pos t)
11987 (setq org-block-entry-blocking (org-get-heading)))
11988 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11990 (defcustom org-track-ordered-property-with-tag nil
11991 "Should the ORDERED property also be shown as a tag?
11992 The ORDERED property decides if an entry should require subtasks to be
11993 completed in sequence. Since a property is not very visible, setting
11994 this option means that toggling the ORDERED property with the command
11995 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11996 not relevant for the behavior, but it makes things more visible.
11998 Note that toggling the tag with tags commands will not change the property
11999 and therefore not influence behavior!
12001 This can be t, meaning the tag ORDERED should be used, It can also be a
12002 string to select a different tag for this task."
12003 :group 'org-todo
12004 :type '(choice
12005 (const :tag "No tracking" nil)
12006 (const :tag "Track with ORDERED tag" t)
12007 (string :tag "Use other tag")))
12009 (defun org-toggle-ordered-property ()
12010 "Toggle the ORDERED property of the current entry.
12011 For better visibility, you can track the value of this property with a tag.
12012 See variable `org-track-ordered-property-with-tag'."
12013 (interactive)
12014 (let* ((t1 org-track-ordered-property-with-tag)
12015 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12016 (save-excursion
12017 (org-back-to-heading)
12018 (if (org-entry-get nil "ORDERED")
12019 (progn
12020 (org-delete-property "ORDERED")
12021 (and tag (org-toggle-tag tag 'off))
12022 (message "Subtasks can be completed in arbitrary order"))
12023 (org-entry-put nil "ORDERED" "t")
12024 (and tag (org-toggle-tag tag 'on))
12025 (message "Subtasks must be completed in sequence")))))
12027 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12028 (defun org-block-todo-from-checkboxes (change-plist)
12029 "Block turning an entry into a TODO, using checkboxes.
12030 This checks whether the current task should be blocked from state
12031 changes because there are unchecked boxes in this entry."
12032 (if (not org-enforce-todo-checkbox-dependencies)
12033 t ; if locally turned off don't block
12034 (catch 'dont-block
12035 ;; If this is not a todo state change, or if this entry is already DONE,
12036 ;; do not block
12037 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12038 (member (plist-get change-plist :from)
12039 (cons 'done org-done-keywords))
12040 (member (plist-get change-plist :to)
12041 (cons 'todo org-not-done-keywords))
12042 (not (plist-get change-plist :to)))
12043 (throw 'dont-block t))
12044 ;; If this task has checkboxes that are not checked, it's blocked
12045 (save-excursion
12046 (org-back-to-heading t)
12047 (let ((beg (point)) end)
12048 (outline-next-heading)
12049 (setq end (point))
12050 (goto-char beg)
12051 (if (org-list-search-forward
12052 (concat (org-item-beginning-re)
12053 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12054 "\\[[- ]\\]")
12055 end t)
12056 (progn
12057 (if (boundp 'org-blocked-by-checkboxes)
12058 (setq org-blocked-by-checkboxes t))
12059 (throw 'dont-block nil)))))
12060 t))) ; do not block
12062 (defun org-entry-blocked-p ()
12063 "Is the current entry blocked?"
12064 (org-with-buffer-modified-unmodified
12065 (if (org-entry-get nil "NOBLOCKING")
12066 nil ;; Never block this entry
12067 (not
12068 (run-hook-with-args-until-failure
12069 'org-blocker-hook
12070 (list :type 'todo-state-change
12071 :position (point)
12072 :from 'todo
12073 :to 'done))))))
12075 (defun org-update-statistics-cookies (all)
12076 "Update the statistics cookie, either from TODO or from checkboxes.
12077 This should be called with the cursor in a line with a statistics cookie."
12078 (interactive "P")
12079 (if all
12080 (progn
12081 (org-update-checkbox-count 'all)
12082 (org-map-entries 'org-update-parent-todo-statistics))
12083 (if (not (org-at-heading-p))
12084 (org-update-checkbox-count)
12085 (let ((pos (point-marker))
12086 end l1 l2)
12087 (ignore-errors (org-back-to-heading t))
12088 (if (not (org-at-heading-p))
12089 (org-update-checkbox-count)
12090 (setq l1 (org-outline-level))
12091 (setq end (save-excursion
12092 (outline-next-heading)
12093 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12094 (point)))
12095 (if (and (save-excursion
12096 (re-search-forward
12097 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12098 (not (save-excursion (re-search-forward
12099 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12100 (org-update-checkbox-count)
12101 (if (and l2 (> l2 l1))
12102 (progn
12103 (goto-char end)
12104 (org-update-parent-todo-statistics))
12105 (goto-char pos)
12106 (beginning-of-line 1)
12107 (while (re-search-forward
12108 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12109 (point-at-eol) t)
12110 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12111 (goto-char pos)
12112 (move-marker pos nil)))))
12114 (defvar org-entry-property-inherited-from) ;; defined below
12115 (defun org-update-parent-todo-statistics ()
12116 "Update any statistics cookie in the parent of the current headline.
12117 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12118 the entire subtree and this will travel up the hierarchy and update
12119 statistics everywhere."
12120 (let* ((prop (save-excursion (org-up-heading-safe)
12121 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12122 (recursive (or (not org-hierarchical-todo-statistics)
12123 (and prop (string-match "\\<recursive\\>" prop))))
12124 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12126 (first t)
12127 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12128 level ltoggle l1 new ndel
12129 (cnt-all 0) (cnt-done 0) is-percent kwd
12130 checkbox-beg ov ovs ove cookie-present)
12131 (catch 'exit
12132 (save-excursion
12133 (beginning-of-line 1)
12134 (setq ltoggle (funcall outline-level))
12135 ;; Three situations are to consider:
12137 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12138 ;; to the top-level ancestor on the headline;
12140 ;; 2. If parent has "recursive" property, repeat up to the
12141 ;; headline setting that property, taking inheritance into
12142 ;; account;
12144 ;; 3. Else, move up to direct parent and proceed only once.
12145 (while (and (setq level (org-up-heading-safe))
12146 (or recursive first)
12147 (>= (point) lim))
12148 (setq first nil cookie-present nil)
12149 (unless (and level
12150 (not (string-match
12151 "\\<checkbox\\>"
12152 (downcase (or (org-entry-get nil "COOKIE_DATA")
12153 "")))))
12154 (throw 'exit nil))
12155 (while (re-search-forward box-re (point-at-eol) t)
12156 (setq cnt-all 0 cnt-done 0 cookie-present t)
12157 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12158 (save-match-data
12159 (unless (outline-next-heading) (throw 'exit nil))
12160 (while (and (looking-at org-complex-heading-regexp)
12161 (> (setq l1 (length (match-string 1))) level))
12162 (setq kwd (and (or recursive (= l1 ltoggle))
12163 (match-string 2)))
12164 (if (or (eq org-provide-todo-statistics 'all-headlines)
12165 (and (listp org-provide-todo-statistics)
12166 (or (member kwd org-provide-todo-statistics)
12167 (member kwd org-done-keywords))))
12168 (setq cnt-all (1+ cnt-all))
12169 (if (eq org-provide-todo-statistics t)
12170 (and kwd (setq cnt-all (1+ cnt-all)))))
12171 (and (member kwd org-done-keywords)
12172 (setq cnt-done (1+ cnt-done)))
12173 (outline-next-heading)))
12174 (setq new
12175 (if is-percent
12176 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12177 (format "[%d/%d]" cnt-done cnt-all))
12178 ndel (- (match-end 0) checkbox-beg))
12179 ;; handle overlays when updating cookie from column view
12180 (when (setq ov (car (overlays-at checkbox-beg)))
12181 (setq ovs (overlay-start ov) ove (overlay-end ov))
12182 (delete-overlay ov))
12183 (goto-char checkbox-beg)
12184 (insert new)
12185 (delete-region (point) (+ (point) ndel))
12186 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12187 (when ov (move-overlay ov ovs ove)))
12188 (when cookie-present
12189 (run-hook-with-args 'org-after-todo-statistics-hook
12190 cnt-done (- cnt-all cnt-done))))))
12191 (run-hooks 'org-todo-statistics-hook)))
12193 (defvar org-after-todo-statistics-hook nil
12194 "Hook that is called after a TODO statistics cookie has been updated.
12195 Each function is called with two arguments: the number of not-done entries
12196 and the number of done entries.
12198 For example, the following function, when added to this hook, will switch
12199 an entry to DONE when all children are done, and back to TODO when new
12200 entries are set to a TODO status. Note that this hook is only called
12201 when there is a statistics cookie in the headline!
12203 (defun org-summary-todo (n-done n-not-done)
12204 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12205 (let (org-log-done org-log-states) ; turn off logging
12206 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12209 (defvar org-todo-statistics-hook nil
12210 "Hook that is run whenever Org thinks TODO statistics should be updated.
12211 This hook runs even if there is no statistics cookie present, in which case
12212 `org-after-todo-statistics-hook' would not run.")
12214 (defun org-todo-trigger-tag-changes (state)
12215 "Apply the changes defined in `org-todo-state-tags-triggers'."
12216 (let ((l org-todo-state-tags-triggers)
12217 changes)
12218 (when (or (not state) (equal state ""))
12219 (setq changes (append changes (cdr (assoc "" l)))))
12220 (when (and (stringp state) (> (length state) 0))
12221 (setq changes (append changes (cdr (assoc state l)))))
12222 (when (member state org-not-done-keywords)
12223 (setq changes (append changes (cdr (assoc 'todo l)))))
12224 (when (member state org-done-keywords)
12225 (setq changes (append changes (cdr (assoc 'done l)))))
12226 (dolist (c changes)
12227 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12229 (defun org-local-logging (value)
12230 "Get logging settings from a property VALUE."
12231 (let* (words w a)
12232 ;; directly set the variables, they are already local.
12233 (setq org-log-done nil
12234 org-log-repeat nil
12235 org-todo-log-states nil)
12236 (setq words (org-split-string value))
12237 (while (setq w (pop words))
12238 (cond
12239 ((setq a (assoc w org-startup-options))
12240 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12241 (set (nth 1 a) (nth 2 a))))
12242 ((setq a (org-extract-log-state-settings w))
12243 (and (member (car a) org-todo-keywords-1)
12244 (push a org-todo-log-states)))))))
12246 (defun org-get-todo-sequence-head (kwd)
12247 "Return the head of the TODO sequence to which KWD belongs.
12248 If KWD is not set, check if there is a text property remembering the
12249 right sequence."
12250 (let (p)
12251 (cond
12252 ((not kwd)
12253 (or (get-text-property (point-at-bol) 'org-todo-head)
12254 (progn
12255 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12256 nil (point-at-eol)))
12257 (get-text-property p 'org-todo-head))))
12258 ((not (member kwd org-todo-keywords-1))
12259 (car org-todo-keywords-1))
12260 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12262 (defun org-fast-todo-selection ()
12263 "Fast TODO keyword selection with single keys.
12264 Returns the new TODO keyword, or nil if no state change should occur."
12265 (let* ((fulltable org-todo-key-alist)
12266 (done-keywords org-done-keywords) ;; needed for the faces.
12267 (maxlen (apply 'max (mapcar
12268 (lambda (x)
12269 (if (stringp (car x)) (string-width (car x)) 0))
12270 fulltable)))
12271 (expert nil)
12272 (fwidth (+ maxlen 3 1 3))
12273 (ncol (/ (- (window-width) 4) fwidth))
12274 tg cnt e c tbl
12275 groups ingroup)
12276 (save-excursion
12277 (save-window-excursion
12278 (if expert
12279 (set-buffer (get-buffer-create " *Org todo*"))
12280 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12281 (erase-buffer)
12282 (org-set-local 'org-done-keywords done-keywords)
12283 (setq tbl fulltable cnt 0)
12284 (while (setq e (pop tbl))
12285 (cond
12286 ((equal e '(:startgroup))
12287 (push '() groups) (setq ingroup t)
12288 (when (not (= cnt 0))
12289 (setq cnt 0)
12290 (insert "\n"))
12291 (insert "{ "))
12292 ((equal e '(:endgroup))
12293 (setq ingroup nil cnt 0)
12294 (insert "}\n"))
12295 ((equal e '(:newline))
12296 (when (not (= cnt 0))
12297 (setq cnt 0)
12298 (insert "\n")
12299 (setq e (car tbl))
12300 (while (equal (car tbl) '(:newline))
12301 (insert "\n")
12302 (setq tbl (cdr tbl)))))
12304 (setq tg (car e) c (cdr e))
12305 (if ingroup (push tg (car groups)))
12306 (setq tg (org-add-props tg nil 'face
12307 (org-get-todo-face tg)))
12308 (if (and (= cnt 0) (not ingroup)) (insert " "))
12309 (insert "[" c "] " tg (make-string
12310 (- fwidth 4 (length tg)) ?\ ))
12311 (when (= (setq cnt (1+ cnt)) ncol)
12312 (insert "\n")
12313 (if ingroup (insert " "))
12314 (setq cnt 0)))))
12315 (insert "\n")
12316 (goto-char (point-min))
12317 (if (not expert) (org-fit-window-to-buffer))
12318 (message "[a-z..]:Set [SPC]:clear")
12319 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12320 (cond
12321 ((or (= c ?\C-g)
12322 (and (= c ?q) (not (rassoc c fulltable))))
12323 (setq quit-flag t))
12324 ((= c ?\ ) nil)
12325 ((setq e (rassoc c fulltable) tg (car e))
12327 (t (setq quit-flag t)))))))
12329 (defun org-entry-is-todo-p ()
12330 (member (org-get-todo-state) org-not-done-keywords))
12332 (defun org-entry-is-done-p ()
12333 (member (org-get-todo-state) org-done-keywords))
12335 (defun org-get-todo-state ()
12336 (save-excursion
12337 (org-back-to-heading t)
12338 (and (looking-at org-todo-line-regexp)
12339 (match-end 2)
12340 (match-string 2))))
12342 (defun org-at-date-range-p (&optional inactive-ok)
12343 "Is the cursor inside a date range?"
12344 (interactive)
12345 (save-excursion
12346 (catch 'exit
12347 (let ((pos (point)))
12348 (skip-chars-backward "^[<\r\n")
12349 (skip-chars-backward "<[")
12350 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12351 (>= (match-end 0) pos)
12352 (throw 'exit t))
12353 (skip-chars-backward "^<[\r\n")
12354 (skip-chars-backward "<[")
12355 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12356 (>= (match-end 0) pos)
12357 (throw 'exit t)))
12358 nil)))
12360 (defun org-get-repeat (&optional tagline)
12361 "Check if there is a deadline/schedule with repeater in this entry."
12362 (save-match-data
12363 (save-excursion
12364 (org-back-to-heading t)
12365 (and (re-search-forward (if tagline
12366 (concat tagline "\\s-*" org-repeat-re)
12367 org-repeat-re)
12368 (org-entry-end-position) t)
12369 (match-string-no-properties 1)))))
12371 (defvar org-last-changed-timestamp)
12372 (defvar org-last-inserted-timestamp)
12373 (defvar org-log-post-message)
12374 (defvar org-log-note-purpose)
12375 (defvar org-log-note-how)
12376 (defvar org-log-note-extra)
12377 (defun org-auto-repeat-maybe (done-word)
12378 "Check if the current headline contains a repeated deadline/schedule.
12379 If yes, set TODO state back to what it was and change the base date
12380 of repeating deadline/scheduled time stamps to new date.
12381 This function is run automatically after each state change to a DONE state."
12382 ;; last-state is dynamically scoped into this function
12383 (let* ((repeat (org-get-repeat))
12384 (aa (assoc org-last-state org-todo-kwd-alist))
12385 (interpret (nth 1 aa))
12386 (head (nth 2 aa))
12387 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12388 (msg "Entry repeats: ")
12389 (org-log-done nil)
12390 (org-todo-log-states nil)
12391 re type n what ts time to-state)
12392 (when repeat
12393 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12394 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12395 org-todo-repeat-to-state))
12396 (unless (and to-state (member to-state org-todo-keywords-1))
12397 (setq to-state (if (eq interpret 'type) org-last-state head)))
12398 (org-todo to-state)
12399 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12400 (org-entry-put nil "LAST_REPEAT" (format-time-string
12401 (org-time-stamp-format t t))))
12402 (when org-log-repeat
12403 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12404 (memq 'org-add-log-note post-command-hook))
12405 ;; OK, we are already setup for some record
12406 (if (eq org-log-repeat 'note)
12407 ;; make sure we take a note, not only a time stamp
12408 (setq org-log-note-how 'note))
12409 ;; Set up for taking a record
12410 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12411 org-last-state
12412 'findpos org-log-repeat)))
12413 (org-back-to-heading t)
12414 (org-add-planning-info nil nil 'closed)
12415 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12416 org-deadline-time-regexp "\\)\\|\\("
12417 org-ts-regexp "\\)"))
12418 (while (re-search-forward
12419 re (save-excursion (outline-next-heading) (point)) t)
12420 (setq type (if (match-end 1) org-scheduled-string
12421 (if (match-end 3) org-deadline-string "Plain:"))
12422 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12423 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12424 (setq n (string-to-number (match-string 2 ts))
12425 what (match-string 3 ts))
12426 (if (equal what "w") (setq n (* n 7) what "d"))
12427 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12428 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12429 ;; Preparation, see if we need to modify the start date for the change
12430 (when (match-end 1)
12431 (setq time (save-match-data (org-time-string-to-time ts)))
12432 (cond
12433 ((equal (match-string 1 ts) ".")
12434 ;; Shift starting date to today
12435 (org-timestamp-change
12436 (- (org-today) (time-to-days time))
12437 'day))
12438 ((equal (match-string 1 ts) "+")
12439 (let ((nshiftmax 10) (nshift 0))
12440 (while (or (= nshift 0)
12441 (<= (time-to-days time)
12442 (time-to-days (current-time))))
12443 (when (= (incf nshift) nshiftmax)
12444 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12445 (error "Abort")))
12446 (org-timestamp-change n (cdr (assoc what whata)))
12447 (org-at-timestamp-p t)
12448 (setq ts (match-string 1))
12449 (setq time (save-match-data (org-time-string-to-time ts)))))
12450 (org-timestamp-change (- n) (cdr (assoc what whata)))
12451 ;; rematch, so that we have everything in place for the real shift
12452 (org-at-timestamp-p t)
12453 (setq ts (match-string 1))
12454 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12455 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12456 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12457 (setq org-log-post-message msg)
12458 (message "%s" msg))))
12460 (defun org-show-todo-tree (arg)
12461 "Make a compact tree which shows all headlines marked with TODO.
12462 The tree will show the lines where the regexp matches, and all higher
12463 headlines above the match.
12464 With a \\[universal-argument] prefix, prompt for a regexp to match.
12465 With a numeric prefix N, construct a sparse tree for the Nth element
12466 of `org-todo-keywords-1'."
12467 (interactive "P")
12468 (let ((case-fold-search nil)
12469 (kwd-re
12470 (cond ((null arg) org-not-done-regexp)
12471 ((equal arg '(4))
12472 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12473 (mapcar 'list org-todo-keywords-1))))
12474 (concat "\\("
12475 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12476 "\\)\\>")))
12477 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12478 (regexp-quote (nth (1- (prefix-numeric-value arg))
12479 org-todo-keywords-1)))
12480 (t (error "Invalid prefix argument: %s" arg)))))
12481 (message "%d TODO entries found"
12482 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12484 (defun org-deadline (&optional arg time)
12485 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12486 With one universal prefix argument, remove any deadline from the item.
12487 With two universal prefix arguments, prompt for a warning delay.
12488 With argument TIME, set the deadline at the corresponding date. TIME
12489 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12490 (interactive "P")
12491 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12492 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12493 'region-start-level 'region))
12494 org-loop-over-headlines-in-active-region)
12495 (org-map-entries
12496 `(org-deadline ',arg ,time)
12497 org-loop-over-headlines-in-active-region
12498 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12499 (let* ((old-date (org-entry-get nil "DEADLINE"))
12500 (repeater (and old-date
12501 (string-match
12502 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12503 old-date)
12504 (match-string 1 old-date))))
12505 (cond
12506 ((equal arg '(4))
12507 (when (and old-date org-log-redeadline)
12508 (org-add-log-setup 'deldeadline nil old-date 'findpos
12509 org-log-redeadline))
12510 (org-remove-timestamp-with-keyword org-deadline-string)
12511 (message "Item no longer has a deadline."))
12512 ((equal arg '(16))
12513 (save-excursion
12514 (if (re-search-forward
12515 org-deadline-time-regexp
12516 (save-excursion (outline-next-heading) (point)) t)
12517 (let* ((rpl0 (match-string 1))
12518 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12519 (replace-match
12520 (concat org-deadline-string
12521 " <" rpl
12522 (format " -%dd" (abs
12523 (- (time-to-days
12524 (save-match-data
12525 (org-read-date nil t nil "Warn starting from")))
12526 (time-to-days nil))))
12527 ">") t t))
12528 (user-error "No deadline information to update"))))
12530 (org-add-planning-info 'deadline time 'closed)
12531 (when (and old-date org-log-redeadline
12532 (not (equal old-date
12533 (substring org-last-inserted-timestamp 1 -1))))
12534 (org-add-log-setup 'redeadline nil old-date 'findpos
12535 org-log-redeadline))
12536 (when repeater
12537 (save-excursion
12538 (org-back-to-heading t)
12539 (when (re-search-forward (concat org-deadline-string " "
12540 org-last-inserted-timestamp)
12541 (save-excursion
12542 (outline-next-heading) (point)) t)
12543 (goto-char (1- (match-end 0)))
12544 (insert " " repeater)
12545 (setq org-last-inserted-timestamp
12546 (concat (substring org-last-inserted-timestamp 0 -1)
12547 " " repeater
12548 (substring org-last-inserted-timestamp -1))))))
12549 (message "Deadline on %s" org-last-inserted-timestamp))))))
12551 (defun org-schedule (&optional arg time)
12552 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12553 With one universal prefix argument, remove any scheduling date from the item.
12554 With two universal prefix arguments, prompt for a delay cookie.
12555 With argument TIME, scheduled at the corresponding date. TIME can
12556 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12557 (interactive "P")
12558 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12559 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12560 'region-start-level 'region))
12561 org-loop-over-headlines-in-active-region)
12562 (org-map-entries
12563 `(org-schedule ',arg ,time)
12564 org-loop-over-headlines-in-active-region
12565 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12566 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12567 (repeater (and old-date
12568 (string-match
12569 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12570 old-date)
12571 (match-string 1 old-date))))
12572 (cond
12573 ((equal arg '(4))
12574 (progn
12575 (when (and old-date org-log-reschedule)
12576 (org-add-log-setup 'delschedule nil old-date 'findpos
12577 org-log-reschedule))
12578 (org-remove-timestamp-with-keyword org-scheduled-string)
12579 (message "Item is no longer scheduled.")))
12580 ((equal arg '(16))
12581 (save-excursion
12582 (if (re-search-forward
12583 org-scheduled-time-regexp
12584 (save-excursion (outline-next-heading) (point)) t)
12585 (let* ((rpl0 (match-string 1))
12586 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12587 (replace-match
12588 (concat org-scheduled-string
12589 " <" rpl
12590 (format " -%dd" (abs
12591 (- (time-to-days
12592 (save-match-data
12593 (org-read-date nil t nil "Delay until")))
12594 (time-to-days nil))))
12595 ">") t t))
12596 (user-error "No scheduled information to update"))))
12598 (org-add-planning-info 'scheduled time 'closed)
12599 (when (and old-date org-log-reschedule
12600 (not (equal old-date
12601 (substring org-last-inserted-timestamp 1 -1))))
12602 (org-add-log-setup 'reschedule nil old-date 'findpos
12603 org-log-reschedule))
12604 (when repeater
12605 (save-excursion
12606 (org-back-to-heading t)
12607 (when (re-search-forward (concat org-scheduled-string " "
12608 org-last-inserted-timestamp)
12609 (save-excursion
12610 (outline-next-heading) (point)) t)
12611 (goto-char (1- (match-end 0)))
12612 (insert " " repeater)
12613 (setq org-last-inserted-timestamp
12614 (concat (substring org-last-inserted-timestamp 0 -1)
12615 " " repeater
12616 (substring org-last-inserted-timestamp -1))))))
12617 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12619 (defun org-get-scheduled-time (pom &optional inherit)
12620 "Get the scheduled time as a time tuple, of a format suitable
12621 for calling org-schedule with, or if there is no scheduling,
12622 returns nil."
12623 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12624 (when time
12625 (apply 'encode-time (org-parse-time-string time)))))
12627 (defun org-get-deadline-time (pom &optional inherit)
12628 "Get the deadline as a time tuple, of a format suitable for
12629 calling org-deadline with, or if there is no scheduling, returns
12630 nil."
12631 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12632 (when time
12633 (apply 'encode-time (org-parse-time-string time)))))
12635 (defun org-remove-timestamp-with-keyword (keyword)
12636 "Remove all time stamps with KEYWORD in the current entry."
12637 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12638 beg)
12639 (save-excursion
12640 (org-back-to-heading t)
12641 (setq beg (point))
12642 (outline-next-heading)
12643 (while (re-search-backward re beg t)
12644 (replace-match "")
12645 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12646 (equal (char-before) ?\ ))
12647 (backward-delete-char 1)
12648 (if (string-match "^[ \t]*$" (buffer-substring
12649 (point-at-bol) (point-at-eol)))
12650 (delete-region (point-at-bol)
12651 (min (point-max) (1+ (point-at-eol))))))))))
12653 (defun org-add-planning-info (what &optional time &rest remove)
12654 "Insert new timestamp with keyword in the line directly after the headline.
12655 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12656 If non is given, the user is prompted for a date.
12657 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12658 be removed."
12659 (interactive)
12660 (let (org-time-was-given org-end-time-was-given ts
12661 end default-time default-input)
12663 (catch 'exit
12664 (when (and (memq what '(scheduled deadline))
12665 (or (not time)
12666 (and (stringp time)
12667 (string-match "^[-+]+[0-9]" time))))
12668 ;; Try to get a default date/time from existing timestamp
12669 (save-excursion
12670 (org-back-to-heading t)
12671 (setq end (save-excursion (outline-next-heading) (point)))
12672 (when (re-search-forward (if (eq what 'scheduled)
12673 org-scheduled-time-regexp
12674 org-deadline-time-regexp)
12675 end t)
12676 (setq ts (match-string 1)
12677 default-time
12678 (apply 'encode-time (org-parse-time-string ts))
12679 default-input (and ts (org-get-compact-tod ts))))))
12680 (when what
12681 (setq time
12682 (if (stringp time)
12683 ;; This is a string (relative or absolute), set proper date
12684 (apply 'encode-time
12685 (org-read-date-analyze
12686 time default-time (decode-time default-time)))
12687 ;; If necessary, get the time from the user
12688 (or time (org-read-date nil 'to-time nil nil
12689 default-time default-input)))))
12691 (when (and org-insert-labeled-timestamps-at-point
12692 (member what '(scheduled deadline)))
12693 (insert
12694 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12695 (org-insert-time-stamp time org-time-was-given
12696 nil nil nil (list org-end-time-was-given))
12697 (setq what nil))
12698 (save-excursion
12699 (save-restriction
12700 (let (col list elt ts buffer-invisibility-spec)
12701 (org-back-to-heading t)
12702 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12703 (goto-char (match-end 1))
12704 (setq col (current-column))
12705 (goto-char (match-end 0))
12706 (if (eobp) (insert "\n") (forward-char 1))
12707 (when (and (not what)
12708 (not (looking-at
12709 (concat "[ \t]*"
12710 org-keyword-time-not-clock-regexp))))
12711 ;; Nothing to add, nothing to remove...... :-)
12712 (throw 'exit nil))
12713 (if (and (not (looking-at org-outline-regexp))
12714 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12715 "[^\r\n]*"))
12716 (not (equal (match-string 1) org-clock-string)))
12717 (narrow-to-region (match-beginning 0) (match-end 0))
12718 (insert-before-markers "\n")
12719 (backward-char 1)
12720 (narrow-to-region (point) (point))
12721 (and org-adapt-indentation (org-indent-to-column col)))
12722 ;; Check if we have to remove something.
12723 (setq list (cons what remove))
12724 (while list
12725 (setq elt (pop list))
12726 (when (or (and (eq elt 'scheduled)
12727 (re-search-forward org-scheduled-time-regexp nil t))
12728 (and (eq elt 'deadline)
12729 (re-search-forward org-deadline-time-regexp nil t))
12730 (and (eq elt 'closed)
12731 (re-search-forward org-closed-time-regexp nil t)))
12732 (replace-match "")
12733 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12734 (and (looking-at "[ \t]+") (replace-match ""))
12735 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12736 (when what
12737 (insert
12738 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12739 (cond ((eq what 'scheduled) org-scheduled-string)
12740 ((eq what 'deadline) org-deadline-string)
12741 ((eq what 'closed) org-closed-string))
12742 " ")
12743 (setq ts (org-insert-time-stamp
12744 time
12745 (or org-time-was-given
12746 (and (eq what 'closed) org-log-done-with-time))
12747 (eq what 'closed)
12748 nil nil (list org-end-time-was-given)))
12749 (insert
12750 (if (not (or (bolp) (eq (char-before) ?\ )
12751 (memq (char-after) '(32 10))
12752 (eobp))) " " ""))
12753 (end-of-line 1))
12754 (goto-char (point-min))
12755 (widen)
12756 (if (and (looking-at "[ \t]*\n")
12757 (equal (char-before) ?\n))
12758 (delete-region (1- (point)) (point-at-eol)))
12759 ts))))))
12761 (defvar org-log-note-marker (make-marker))
12762 (defvar org-log-note-purpose nil)
12763 (defvar org-log-note-state nil)
12764 (defvar org-log-note-previous-state nil)
12765 (defvar org-log-note-how nil)
12766 (defvar org-log-note-extra nil)
12767 (defvar org-log-note-window-configuration nil)
12768 (defvar org-log-note-return-to (make-marker))
12769 (defvar org-log-note-effective-time nil
12770 "Remembered current time so that dynamically scoped
12771 `org-extend-today-until' affects tha timestamps in state change
12772 log")
12774 (defvar org-log-post-message nil
12775 "Message to be displayed after a log note has been stored.
12776 The auto-repeater uses this.")
12778 (defun org-add-note ()
12779 "Add a note to the current entry.
12780 This is done in the same way as adding a state change note."
12781 (interactive)
12782 (org-add-log-setup 'note nil nil 'findpos nil))
12784 (defvar org-property-end-re)
12785 (defun org-add-log-setup (&optional purpose state prev-state
12786 findpos how extra)
12787 "Set up the post command hook to take a note.
12788 If this is about to TODO state change, the new state is expected in STATE.
12789 When FINDPOS is non-nil, find the correct position for the note in
12790 the current entry. If not, assume that it can be inserted at point.
12791 HOW is an indicator what kind of note should be created.
12792 EXTRA is additional text that will be inserted into the notes buffer."
12793 (let* ((org-log-into-drawer (org-log-into-drawer))
12794 (drawer (cond ((stringp org-log-into-drawer)
12795 org-log-into-drawer)
12796 (org-log-into-drawer "LOGBOOK"))))
12797 (save-restriction
12798 (save-excursion
12799 (when findpos
12800 (org-back-to-heading t)
12801 (narrow-to-region (point) (save-excursion
12802 (outline-next-heading) (point)))
12803 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12804 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12805 "[^\r\n]*\\)?"))
12806 (goto-char (match-end 0))
12807 (cond
12808 (drawer
12809 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12810 nil t)
12811 (progn
12812 (goto-char (match-end 0))
12813 (or org-log-states-order-reversed
12814 (and (re-search-forward org-property-end-re nil t)
12815 (goto-char (1- (match-beginning 0))))))
12816 (insert "\n:" drawer ":\n:END:")
12817 (beginning-of-line 0)
12818 (org-indent-line)
12819 (beginning-of-line 2)
12820 (org-indent-line)
12821 (end-of-line 0)))
12822 ((and org-log-state-notes-insert-after-drawers
12823 (save-excursion
12824 (forward-line) (looking-at org-drawer-regexp)))
12825 (forward-line)
12826 (while (looking-at org-drawer-regexp)
12827 (goto-char (match-end 0))
12828 (re-search-forward org-property-end-re (point-max) t)
12829 (forward-line))
12830 (forward-line -1)))
12831 (unless org-log-states-order-reversed
12832 (and (= (char-after) ?\n) (forward-char 1))
12833 (org-skip-over-state-notes)
12834 (skip-chars-backward " \t\n\r")))
12835 (move-marker org-log-note-marker (point))
12836 (setq org-log-note-purpose purpose
12837 org-log-note-state state
12838 org-log-note-previous-state prev-state
12839 org-log-note-how how
12840 org-log-note-extra extra
12841 org-log-note-effective-time (org-current-effective-time))
12842 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12844 (defun org-skip-over-state-notes ()
12845 "Skip past the list of State notes in an entry."
12846 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12847 (when (ignore-errors (goto-char (org-in-item-p)))
12848 (let* ((struct (org-list-struct))
12849 (prevs (org-list-prevs-alist struct)))
12850 (while (looking-at "[ \t]*- State")
12851 (goto-char (or (org-list-get-next-item (point) struct prevs)
12852 (org-list-get-item-end (point) struct)))))))
12854 (defun org-add-log-note (&optional purpose)
12855 "Pop up a window for taking a note, and add this note later at point."
12856 (remove-hook 'post-command-hook 'org-add-log-note)
12857 (setq org-log-note-window-configuration (current-window-configuration))
12858 (delete-other-windows)
12859 (move-marker org-log-note-return-to (point))
12860 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12861 (goto-char org-log-note-marker)
12862 (org-switch-to-buffer-other-window "*Org Note*")
12863 (erase-buffer)
12864 (if (memq org-log-note-how '(time state))
12865 (let (current-prefix-arg) (org-store-log-note))
12866 (let ((org-inhibit-startup t)) (org-mode))
12867 (insert (format "# Insert note for %s.
12868 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12869 (cond
12870 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12871 ((eq org-log-note-purpose 'done) "closed todo item")
12872 ((eq org-log-note-purpose 'state)
12873 (format "state change from \"%s\" to \"%s\""
12874 (or org-log-note-previous-state "")
12875 (or org-log-note-state "")))
12876 ((eq org-log-note-purpose 'reschedule)
12877 "rescheduling")
12878 ((eq org-log-note-purpose 'delschedule)
12879 "no longer scheduled")
12880 ((eq org-log-note-purpose 'redeadline)
12881 "changing deadline")
12882 ((eq org-log-note-purpose 'deldeadline)
12883 "removing deadline")
12884 ((eq org-log-note-purpose 'refile)
12885 "refiling")
12886 ((eq org-log-note-purpose 'note)
12887 "this entry")
12888 (t (error "This should not happen")))))
12889 (if org-log-note-extra (insert org-log-note-extra))
12890 (org-set-local 'org-finish-function 'org-store-log-note)
12891 (run-hooks 'org-log-buffer-setup-hook)))
12893 (defvar org-note-abort nil) ; dynamically scoped
12894 (defun org-store-log-note ()
12895 "Finish taking a log note, and insert it to where it belongs."
12896 (let ((txt (buffer-string)))
12897 (kill-buffer (current-buffer))
12898 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12899 lines ind bul)
12900 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12901 (setq txt (replace-match "" t t txt)))
12902 (if (string-match "\\s-+\\'" txt)
12903 (setq txt (replace-match "" t t txt)))
12904 (setq lines (org-split-string txt "\n"))
12905 (when (and note (string-match "\\S-" note))
12906 (setq note
12907 (org-replace-escapes
12908 note
12909 (list (cons "%u" (user-login-name))
12910 (cons "%U" user-full-name)
12911 (cons "%t" (format-time-string
12912 (org-time-stamp-format 'long 'inactive)
12913 org-log-note-effective-time))
12914 (cons "%T" (format-time-string
12915 (org-time-stamp-format 'long nil)
12916 org-log-note-effective-time))
12917 (cons "%d" (format-time-string
12918 (org-time-stamp-format nil 'inactive)
12919 org-log-note-effective-time))
12920 (cons "%D" (format-time-string
12921 (org-time-stamp-format nil nil)
12922 org-log-note-effective-time))
12923 (cons "%s" (if org-log-note-state
12924 (concat "\"" org-log-note-state "\"")
12925 ""))
12926 (cons "%S" (if org-log-note-previous-state
12927 (concat "\"" org-log-note-previous-state "\"")
12928 "\"\"")))))
12929 (if lines (setq note (concat note " \\\\")))
12930 (push note lines))
12931 (when (or current-prefix-arg org-note-abort)
12932 (when org-log-into-drawer
12933 (org-remove-empty-drawer-at
12934 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12935 org-log-note-marker))
12936 (setq lines nil))
12937 (when lines
12938 (with-current-buffer (marker-buffer org-log-note-marker)
12939 (save-excursion
12940 (goto-char org-log-note-marker)
12941 (move-marker org-log-note-marker nil)
12942 (end-of-line 1)
12943 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12944 (setq ind (save-excursion
12945 (if (ignore-errors (goto-char (org-in-item-p)))
12946 (let ((struct (org-list-struct)))
12947 (org-list-get-ind
12948 (org-list-get-top-point struct) struct))
12949 (skip-chars-backward " \r\t\n")
12950 (cond
12951 ((and (org-at-heading-p)
12952 org-adapt-indentation)
12953 (1+ (org-current-level)))
12954 ((org-at-heading-p) 0)
12955 (t (org-get-indentation))))))
12956 (setq bul (org-list-bullet-string "-"))
12957 (org-indent-line-to ind)
12958 (insert bul (pop lines))
12959 (let ((ind-body (+ (length bul) ind)))
12960 (while lines
12961 (insert "\n")
12962 (org-indent-line-to ind-body)
12963 (insert (pop lines))))
12964 (message "Note stored")
12965 (org-back-to-heading t)
12966 (org-cycle-hide-drawers 'children))))))
12967 (set-window-configuration org-log-note-window-configuration)
12968 (with-current-buffer (marker-buffer org-log-note-return-to)
12969 (goto-char org-log-note-return-to))
12970 (move-marker org-log-note-return-to nil)
12971 (and org-log-post-message (message "%s" org-log-post-message)))
12973 (defun org-remove-empty-drawer-at (drawer pos)
12974 "Remove an empty drawer DRAWER at position POS.
12975 POS may also be a marker."
12976 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12977 (save-excursion
12978 (save-restriction
12979 (widen)
12980 (goto-char pos)
12981 (if (org-in-regexp
12982 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12983 (replace-match ""))))))
12985 (defvar org-ts-type nil)
12986 (defun org-sparse-tree (&optional arg type)
12987 "Create a sparse tree, prompt for the details.
12988 This command can create sparse trees. You first need to select the type
12989 of match used to create the tree:
12991 t Show all TODO entries.
12992 T Show entries with a specific TODO keyword.
12993 m Show entries selected by a tags/property match.
12994 p Enter a property name and its value (both with completion on existing
12995 names/values) and show entries with that property.
12996 r Show entries matching a regular expression (`/' can be used as well).
12997 b Show deadlines and scheduled items before a date.
12998 a Show deadlines and scheduled items after a date.
12999 d Show deadlines due within `org-deadline-warning-days'.
13000 D Show deadlines and scheduled items between a date range."
13001 (interactive "P")
13002 (let (ans kwd value ts-type)
13003 (setq type (or type org-sparse-tree-default-date-type))
13004 (setq org-ts-type type)
13005 (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"
13006 (cond ((eq type 'all) "all timestamps")
13007 ((eq type 'scheduled) "only scheduled")
13008 ((eq type 'deadline) "only deadline")
13009 ((eq type 'active) "only active timestamps")
13010 ((eq type 'inactive) "only inactive timestamps")
13011 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13012 (t "scheduled/deadline")))
13013 (setq ans (read-char-exclusive))
13014 (cond
13015 ((equal ans ?c)
13016 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13017 ((equal ans ?d)
13018 (call-interactively 'org-check-deadlines))
13019 ((equal ans ?b)
13020 (call-interactively 'org-check-before-date))
13021 ((equal ans ?a)
13022 (call-interactively 'org-check-after-date))
13023 ((equal ans ?D)
13024 (call-interactively 'org-check-dates-range))
13025 ((equal ans ?t)
13026 (call-interactively 'org-show-todo-tree))
13027 ((equal ans ?T)
13028 (org-show-todo-tree '(4)))
13029 ((member ans '(?T ?m))
13030 (call-interactively 'org-match-sparse-tree))
13031 ((member ans '(?p ?P))
13032 (setq kwd (org-icompleting-read "Property: "
13033 (mapcar 'list (org-buffer-property-keys))))
13034 (setq value (org-icompleting-read "Value: "
13035 (mapcar 'list (org-property-values kwd))))
13036 (unless (string-match "\\`{.*}\\'" value)
13037 (setq value (concat "\"" value "\"")))
13038 (org-match-sparse-tree arg (concat kwd "=" value)))
13039 ((member ans '(?r ?R ?/))
13040 (call-interactively 'org-occur))
13041 (t (error "No such sparse tree command \"%c\"" ans)))))
13043 (defvar org-occur-highlights nil
13044 "List of overlays used for occur matches.")
13045 (make-variable-buffer-local 'org-occur-highlights)
13046 (defvar org-occur-parameters nil
13047 "Parameters of the active org-occur calls.
13048 This is a list, each call to org-occur pushes as cons cell,
13049 containing the regular expression and the callback, onto the list.
13050 The list can contain several entries if `org-occur' has been called
13051 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13052 will only contain one set of parameters. When the highlights are
13053 removed (for example with `C-c C-c', or with the next edit (depending
13054 on `org-remove-highlights-with-change'), this variable is emptied
13055 as well.")
13056 (make-variable-buffer-local 'org-occur-parameters)
13058 (defun org-occur (regexp &optional keep-previous callback)
13059 "Make a compact tree which shows all matches of REGEXP.
13060 The tree will show the lines where the regexp matches, and all higher
13061 headlines above the match. It will also show the heading after the match,
13062 to make sure editing the matching entry is easy.
13063 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13064 call to `org-occur' will be kept, to allow stacking of calls to this
13065 command.
13066 If CALLBACK is non-nil, it is a function which is called to confirm
13067 that the match should indeed be shown."
13068 (interactive "sRegexp: \nP")
13069 (when (equal regexp "")
13070 (error "Regexp cannot be empty"))
13071 (unless keep-previous
13072 (org-remove-occur-highlights nil nil t))
13073 (push (cons regexp callback) org-occur-parameters)
13074 (let ((cnt 0))
13075 (save-excursion
13076 (goto-char (point-min))
13077 (if (or (not keep-previous) ; do not want to keep
13078 (not org-occur-highlights)) ; no previous matches
13079 ;; hide everything
13080 (org-overview))
13081 (while (re-search-forward regexp nil t)
13082 (when (or (not callback)
13083 (save-match-data (funcall callback)))
13084 (setq cnt (1+ cnt))
13085 (when org-highlight-sparse-tree-matches
13086 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13087 (org-show-context 'occur-tree))))
13088 (when org-remove-highlights-with-change
13089 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13090 nil 'local))
13091 (unless org-sparse-tree-open-archived-trees
13092 (org-hide-archived-subtrees (point-min) (point-max)))
13093 (run-hooks 'org-occur-hook)
13094 (if (org-called-interactively-p 'interactive)
13095 (message "%d match(es) for regexp %s" cnt regexp))
13096 cnt))
13098 (defun org-occur-next-match (&optional n reset)
13099 "Function for `next-error-function' to find sparse tree matches.
13100 N is the number of matches to move, when negative move backwards.
13101 RESET is entirely ignored - this function always goes back to the
13102 starting point when no match is found."
13103 (let* ((limit (if (< n 0) (point-min) (point-max)))
13104 (search-func (if (< n 0)
13105 'previous-single-char-property-change
13106 'next-single-char-property-change))
13107 (n (abs n))
13108 (pos (point))
13110 (catch 'exit
13111 (while (setq p1 (funcall search-func (point) 'org-type))
13112 (when (equal p1 limit)
13113 (goto-char pos)
13114 (error "No more matches"))
13115 (when (equal (get-char-property p1 'org-type) 'org-occur)
13116 (setq n (1- n))
13117 (when (= n 0)
13118 (goto-char p1)
13119 (throw 'exit (point))))
13120 (goto-char p1))
13121 (goto-char p1)
13122 (error "No more matches"))))
13124 (defun org-show-context (&optional key)
13125 "Make sure point and context are visible.
13126 How much context is shown depends upon the variables
13127 `org-show-hierarchy-above', `org-show-following-heading',
13128 `org-show-entry-below' and `org-show-siblings'."
13129 (let ((heading-p (org-at-heading-p t))
13130 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13131 (following-p (org-get-alist-option org-show-following-heading key))
13132 (entry-p (org-get-alist-option org-show-entry-below key))
13133 (siblings-p (org-get-alist-option org-show-siblings key)))
13134 (catch 'exit
13135 ;; Show heading or entry text
13136 (if (and heading-p (not entry-p))
13137 (org-flag-heading nil) ; only show the heading
13138 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13139 (org-show-hidden-entry))) ; show entire entry
13140 (when following-p
13141 ;; Show next sibling, or heading below text
13142 (save-excursion
13143 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13144 (org-flag-heading nil))))
13145 (when siblings-p (org-show-siblings))
13146 (when hierarchy-p
13147 ;; show all higher headings, possibly with siblings
13148 (save-excursion
13149 (while (and (condition-case nil
13150 (progn (org-up-heading-all 1) t)
13151 (error nil))
13152 (not (bobp)))
13153 (org-flag-heading nil)
13154 (when siblings-p (org-show-siblings))))))))
13156 (defvar org-reveal-start-hook nil
13157 "Hook run before revealing a location.")
13159 (defun org-reveal (&optional siblings)
13160 "Show current entry, hierarchy above it, and the following headline.
13161 This can be used to show a consistent set of context around locations
13162 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13163 not t for the search context.
13165 With optional argument SIBLINGS, on each level of the hierarchy all
13166 siblings are shown. This repairs the tree structure to what it would
13167 look like when opened with hierarchical calls to `org-cycle'.
13168 With double optional argument \\[universal-argument] \\[universal-argument], \
13169 go to the parent and show the
13170 entire tree."
13171 (interactive "P")
13172 (run-hooks 'org-reveal-start-hook)
13173 (let ((org-show-hierarchy-above t)
13174 (org-show-following-heading t)
13175 (org-show-siblings (if siblings t org-show-siblings)))
13176 (org-show-context nil))
13177 (when (equal siblings '(16))
13178 (save-excursion
13179 (when (org-up-heading-safe)
13180 (org-show-subtree)
13181 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13183 (defun org-highlight-new-match (beg end)
13184 "Highlight from BEG to END and mark the highlight is an occur headline."
13185 (let ((ov (make-overlay beg end)))
13186 (overlay-put ov 'face 'secondary-selection)
13187 (overlay-put ov 'org-type 'org-occur)
13188 (push ov org-occur-highlights)))
13190 (defun org-remove-occur-highlights (&optional beg end noremove)
13191 "Remove the occur highlights from the buffer.
13192 BEG and END are ignored. If NOREMOVE is nil, remove this function
13193 from the `before-change-functions' in the current buffer."
13194 (interactive)
13195 (unless org-inhibit-highlight-removal
13196 (mapc 'delete-overlay org-occur-highlights)
13197 (setq org-occur-highlights nil)
13198 (setq org-occur-parameters nil)
13199 (unless noremove
13200 (remove-hook 'before-change-functions
13201 'org-remove-occur-highlights 'local))))
13203 ;;;; Priorities
13205 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13206 "Regular expression matching the priority indicator.")
13208 (defvar org-remove-priority-next-time nil)
13210 (defun org-priority-up ()
13211 "Increase the priority of the current item."
13212 (interactive)
13213 (org-priority 'up))
13215 (defun org-priority-down ()
13216 "Decrease the priority of the current item."
13217 (interactive)
13218 (org-priority 'down))
13220 (defun org-priority (&optional action show)
13221 "Change the priority of an item.
13222 ACTION can be `set', `up', `down', or a character."
13223 (interactive "P")
13224 (if (equal action '(4))
13225 (org-show-priority)
13226 (unless org-enable-priority-commands
13227 (error "Priority commands are disabled"))
13228 (setq action (or action 'set))
13229 (let (current new news have remove)
13230 (save-excursion
13231 (org-back-to-heading t)
13232 (if (looking-at org-priority-regexp)
13233 (setq current (string-to-char (match-string 2))
13234 have t))
13235 (cond
13236 ((eq action 'remove)
13237 (setq remove t new ?\ ))
13238 ((or (eq action 'set)
13239 (if (featurep 'xemacs) (characterp action) (integerp action)))
13240 (if (not (eq action 'set))
13241 (setq new action)
13242 (message "Priority %c-%c, SPC to remove: "
13243 org-highest-priority org-lowest-priority)
13244 (save-match-data
13245 (setq new (read-char-exclusive))))
13246 (if (and (= (upcase org-highest-priority) org-highest-priority)
13247 (= (upcase org-lowest-priority) org-lowest-priority))
13248 (setq new (upcase new)))
13249 (cond ((equal new ?\ ) (setq remove t))
13250 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13251 (error "Priority must be between `%c' and `%c'"
13252 org-highest-priority org-lowest-priority))))
13253 ((eq action 'up)
13254 (setq new (if have
13255 (1- current) ; normal cycling
13256 ;; last priority was empty
13257 (if (eq last-command this-command)
13258 org-lowest-priority ; wrap around empty to lowest
13259 ;; default
13260 (if org-priority-start-cycle-with-default
13261 org-default-priority
13262 (1- org-default-priority))))))
13263 ((eq action 'down)
13264 (setq new (if have
13265 (1+ current) ; normal cycling
13266 ;; last priority was empty
13267 (if (eq last-command this-command)
13268 org-highest-priority ; wrap around empty to highest
13269 ;; default
13270 (if org-priority-start-cycle-with-default
13271 org-default-priority
13272 (1+ org-default-priority))))))
13273 (t (error "Invalid action")))
13274 (if (or (< (upcase new) org-highest-priority)
13275 (> (upcase new) org-lowest-priority))
13276 (if (and (memq action '(up down))
13277 (not have) (not (eq last-command this-command)))
13278 ;; `new' is from default priority
13279 (error
13280 "The default can not be set, see `org-default-priority' why")
13281 ;; normal cycling: `new' is beyond highest/lowest priority
13282 ;; and is wrapped around to the empty priority
13283 (setq remove t)))
13284 (setq news (format "%c" new))
13285 (if have
13286 (if remove
13287 (replace-match "" t t nil 1)
13288 (replace-match news t t nil 2))
13289 (if remove
13290 (error "No priority cookie found in line")
13291 (let ((case-fold-search nil))
13292 (looking-at org-todo-line-regexp))
13293 (if (match-end 2)
13294 (progn
13295 (goto-char (match-end 2))
13296 (insert " [#" news "]"))
13297 (goto-char (match-beginning 3))
13298 (insert "[#" news "] "))))
13299 (org-preserve-lc (org-set-tags nil 'align)))
13300 (if remove
13301 (message "Priority removed")
13302 (message "Priority of current item set to %s" news)))))
13304 (defun org-show-priority ()
13305 "Show the priority of the current item.
13306 This priority is composed of the main priority given with the [#A] cookies,
13307 and by additional input from the age of a schedules or deadline entry."
13308 (interactive)
13309 (let ((pri (if (eq major-mode 'org-agenda-mode)
13310 (org-get-at-bol 'priority)
13311 (save-excursion
13312 (save-match-data
13313 (beginning-of-line)
13314 (and (looking-at org-heading-regexp)
13315 (org-get-priority (match-string 0))))))))
13316 (message "Priority is %d" (if pri pri -1000))))
13318 (defun org-get-priority (s)
13319 "Find priority cookie and return priority."
13320 (save-match-data
13321 (if (functionp org-get-priority-function)
13322 (funcall org-get-priority-function)
13323 (if (not (string-match org-priority-regexp s))
13324 (* 1000 (- org-lowest-priority org-default-priority))
13325 (* 1000 (- org-lowest-priority
13326 (string-to-char (match-string 2 s))))))))
13328 ;;;; Tags
13330 (defvar org-agenda-archives-mode)
13331 (defvar org-map-continue-from nil
13332 "Position from where mapping should continue.
13333 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13335 (defvar org-scanner-tags nil
13336 "The current tag list while the tags scanner is running.")
13337 (defvar org-trust-scanner-tags nil
13338 "Should `org-get-tags-at' use the tags for the scanner.
13339 This is for internal dynamical scoping only.
13340 When this is non-nil, the function `org-get-tags-at' will return the value
13341 of `org-scanner-tags' instead of building the list by itself. This
13342 can lead to large speed-ups when the tags scanner is used in a file with
13343 many entries, and when the list of tags is retrieved, for example to
13344 obtain a list of properties. Building the tags list for each entry in such
13345 a file becomes an N^2 operation - but with this variable set, it scales
13346 as N.")
13348 (defun org-scan-tags (action matcher todo-only &optional start-level)
13349 "Scan headline tags with inheritance and produce output ACTION.
13351 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13352 or `agenda' to produce an entry list for an agenda view. It can also be
13353 a Lisp form or a function that should be called at each matched headline, in
13354 this case the return value is a list of all return values from these calls.
13356 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13357 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13358 only lines with a not-done TODO keyword are included in the output.
13359 This should be the same variable that was scoped into
13360 and set by `org-make-tags-matcher' when it constructed MATCHER.
13362 START-LEVEL can be a string with asterisks, reducing the scope to
13363 headlines matching this string."
13364 (require 'org-agenda)
13365 (let* ((re (concat "^"
13366 (if start-level
13367 ;; Get the correct level to match
13368 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13369 org-outline-regexp)
13370 " *\\(\\<\\("
13371 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13372 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13373 (props (list 'face 'default
13374 'done-face 'org-agenda-done
13375 'undone-face 'default
13376 'mouse-face 'highlight
13377 'org-not-done-regexp org-not-done-regexp
13378 'org-todo-regexp org-todo-regexp
13379 'org-complex-heading-regexp org-complex-heading-regexp
13380 'help-echo
13381 (format "mouse-2 or RET jump to org file %s"
13382 (abbreviate-file-name
13383 (or (buffer-file-name (buffer-base-buffer))
13384 (buffer-name (buffer-base-buffer)))))))
13385 (case-fold-search nil)
13386 (org-map-continue-from nil)
13387 lspos tags tags-list
13388 (tags-alist (list (cons 0 org-file-tags)))
13389 (llast 0) rtn rtn1 level category i txt
13390 todo marker entry priority)
13391 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13392 (setq action (list 'lambda nil action)))
13393 (save-excursion
13394 (goto-char (point-min))
13395 (when (eq action 'sparse-tree)
13396 (org-overview)
13397 (org-remove-occur-highlights))
13398 (while (re-search-forward re nil t)
13399 (setq org-map-continue-from nil)
13400 (catch :skip
13401 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13402 tags (if (match-end 4) (org-match-string-no-properties 4)))
13403 (goto-char (setq lspos (match-beginning 0)))
13404 (setq level (org-reduced-level (org-outline-level))
13405 category (org-get-category))
13406 (setq i llast llast level)
13407 ;; remove tag lists from same and sublevels
13408 (while (>= i level)
13409 (when (setq entry (assoc i tags-alist))
13410 (setq tags-alist (delete entry tags-alist)))
13411 (setq i (1- i)))
13412 ;; add the next tags
13413 (when tags
13414 (setq tags (org-split-string tags ":")
13415 tags-alist
13416 (cons (cons level tags) tags-alist)))
13417 ;; compile tags for current headline
13418 (setq tags-list
13419 (if org-use-tag-inheritance
13420 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13421 tags)
13422 org-scanner-tags tags-list)
13423 (when org-use-tag-inheritance
13424 (setcdr (car tags-alist)
13425 (mapcar (lambda (x)
13426 (setq x (copy-sequence x))
13427 (org-add-prop-inherited x))
13428 (cdar tags-alist))))
13429 (when (and tags org-use-tag-inheritance
13430 (or (not (eq t org-use-tag-inheritance))
13431 org-tags-exclude-from-inheritance))
13432 ;; selective inheritance, remove uninherited ones
13433 (setcdr (car tags-alist)
13434 (org-remove-uninherited-tags (cdar tags-alist))))
13435 (when (and
13437 ;; eval matcher only when the todo condition is OK
13438 (and (or (not todo-only) (member todo org-not-done-keywords))
13439 (let ((case-fold-search t) (org-trust-scanner-tags t))
13440 (eval matcher)))
13442 ;; Call the skipper, but return t if it does not skip,
13443 ;; so that the `and' form continues evaluating
13444 (progn
13445 (unless (eq action 'sparse-tree) (org-agenda-skip))
13448 ;; Check if timestamps are deselecting this entry
13449 (or (not todo-only)
13450 (and (member todo org-not-done-keywords)
13451 (or (not org-agenda-tags-todo-honor-ignore-options)
13452 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13454 ;; select this headline
13455 (cond
13456 ((eq action 'sparse-tree)
13457 (and org-highlight-sparse-tree-matches
13458 (org-get-heading) (match-end 0)
13459 (org-highlight-new-match
13460 (match-beginning 1) (match-end 1)))
13461 (org-show-context 'tags-tree))
13462 ((eq action 'agenda)
13463 (setq txt (org-agenda-format-item
13465 (concat
13466 (if (eq org-tags-match-list-sublevels 'indented)
13467 (make-string (1- level) ?.) "")
13468 (org-get-heading))
13469 level category
13470 tags-list)
13471 priority (org-get-priority txt))
13472 (goto-char lspos)
13473 (setq marker (org-agenda-new-marker))
13474 (org-add-props txt props
13475 'org-marker marker 'org-hd-marker marker 'org-category category
13476 'todo-state todo
13477 'priority priority 'type "tagsmatch")
13478 (push txt rtn))
13479 ((functionp action)
13480 (setq org-map-continue-from nil)
13481 (save-excursion
13482 (setq rtn1 (funcall action))
13483 (push rtn1 rtn)))
13484 (t (error "Invalid action")))
13486 ;; if we are to skip sublevels, jump to end of subtree
13487 (unless org-tags-match-list-sublevels
13488 (org-end-of-subtree t)
13489 (backward-char 1))))
13490 ;; Get the correct position from where to continue
13491 (if org-map-continue-from
13492 (goto-char org-map-continue-from)
13493 (and (= (point) lspos) (end-of-line 1)))))
13494 (when (and (eq action 'sparse-tree)
13495 (not org-sparse-tree-open-archived-trees))
13496 (org-hide-archived-subtrees (point-min) (point-max)))
13497 (nreverse rtn)))
13499 (defun org-remove-uninherited-tags (tags)
13500 "Remove all tags that are not inherited from the list TAGS."
13501 (cond
13502 ((eq org-use-tag-inheritance t)
13503 (if org-tags-exclude-from-inheritance
13504 (org-delete-all org-tags-exclude-from-inheritance tags)
13505 tags))
13506 ((not org-use-tag-inheritance) nil)
13507 ((stringp org-use-tag-inheritance)
13508 (delq nil (mapcar
13509 (lambda (x)
13510 (if (and (string-match org-use-tag-inheritance x)
13511 (not (member x org-tags-exclude-from-inheritance)))
13512 x nil))
13513 tags)))
13514 ((listp org-use-tag-inheritance)
13515 (delq nil (mapcar
13516 (lambda (x)
13517 (if (member x org-use-tag-inheritance) x nil))
13518 tags)))))
13520 (defun org-match-sparse-tree (&optional todo-only match)
13521 "Create a sparse tree according to tags string MATCH.
13522 MATCH can contain positive and negative selection of tags, like
13523 \"+WORK+URGENT-WITHBOSS\".
13524 If optional argument TODO-ONLY is non-nil, only select lines that are
13525 also TODO lines."
13526 (interactive "P")
13527 (org-agenda-prepare-buffers (list (current-buffer)))
13528 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13530 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13532 (defvar org-cached-props nil)
13533 (defun org-cached-entry-get (pom property)
13534 (if (or (eq t org-use-property-inheritance)
13535 (and (stringp org-use-property-inheritance)
13536 (string-match org-use-property-inheritance property))
13537 (and (listp org-use-property-inheritance)
13538 (member property org-use-property-inheritance)))
13539 ;; Caching is not possible, check it directly
13540 (org-entry-get pom property 'inherit)
13541 ;; Get all properties, so that we can do complicated checks easily
13542 (cdr (assoc property (or org-cached-props
13543 (setq org-cached-props
13544 (org-entry-properties pom)))))))
13546 (defun org-global-tags-completion-table (&optional files)
13547 "Return the list of all tags in all agenda buffer/files.
13548 Optional FILES argument is a list of files which can be used
13549 instead of the agenda files."
13550 (save-excursion
13551 (org-uniquify
13552 (delq nil
13553 (apply 'append
13554 (mapcar
13555 (lambda (file)
13556 (set-buffer (find-file-noselect file))
13557 (append (org-get-buffer-tags)
13558 (mapcar (lambda (x) (if (stringp (car-safe x))
13559 (list (car-safe x)) nil))
13560 org-tag-alist)))
13561 (if (and files (car files))
13562 files
13563 (org-agenda-files))))))))
13565 (defun org-make-tags-matcher (match)
13566 "Create the TAGS/TODO matcher form for the selection string MATCH.
13568 The variable `todo-only' is scoped dynamically into this function.
13569 It will be set to t if the matcher restricts matching to TODO entries,
13570 otherwise will not be touched.
13572 Returns a cons of the selection string MATCH and the constructed
13573 lisp form implementing the matcher. The matcher is to be evaluated
13574 at an Org entry, with point on the headline, and returns t if the
13575 entry matches the selection string MATCH. The returned lisp form
13576 references two variables with information about the entry, which
13577 must be bound around the form's evaluation: todo, the TODO keyword
13578 at the entry (or nil of none); and tags-list, the list of all tags
13579 at the entry including inherited ones. Additionally, the category
13580 of the entry (if any) must be specified as the text property
13581 'org-category on the headline.
13583 See also `org-scan-tags'.
13585 (declare (special todo-only))
13586 (unless (boundp 'todo-only)
13587 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13588 (unless match
13589 ;; Get a new match request, with completion
13590 (let ((org-last-tags-completion-table
13591 (org-global-tags-completion-table)))
13592 (setq match (org-completing-read-no-i
13593 "Match: " 'org-tags-completion-function nil nil nil
13594 'org-tags-history))))
13596 ;; Parse the string and create a lisp form
13597 (let ((match0 match)
13598 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13599 minus tag mm
13600 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13601 orterms term orlist re-p str-p level-p level-op time-p
13602 prop-p pn pv po gv rest)
13603 (if (string-match "/+" match)
13604 ;; match contains also a todo-matching request
13605 (progn
13606 (setq tagsmatch (substring match 0 (match-beginning 0))
13607 todomatch (substring match (match-end 0)))
13608 (if (string-match "^!" todomatch)
13609 (setq todo-only t todomatch (substring todomatch 1)))
13610 (if (string-match "^\\s-*$" todomatch)
13611 (setq todomatch nil)))
13612 ;; only matching tags
13613 (setq tagsmatch match todomatch nil))
13615 ;; Make the tags matcher
13616 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13617 (setq tagsmatcher t)
13618 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13619 (while (setq term (pop orterms))
13620 (while (and (equal (substring term -1) "\\") orterms)
13621 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13622 (while (string-match re term)
13623 (setq rest (substring term (match-end 0))
13624 minus (and (match-end 1)
13625 (equal (match-string 1 term) "-"))
13626 tag (save-match-data (replace-regexp-in-string
13627 "\\\\-" "-"
13628 (match-string 2 term)))
13629 re-p (equal (string-to-char tag) ?{)
13630 level-p (match-end 4)
13631 prop-p (match-end 5)
13632 mm (cond
13633 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13634 (level-p
13635 (setq level-op (org-op-to-function (match-string 3 term)))
13636 `(,level-op level ,(string-to-number
13637 (match-string 4 term))))
13638 (prop-p
13639 (setq pn (match-string 5 term)
13640 po (match-string 6 term)
13641 pv (match-string 7 term)
13642 re-p (equal (string-to-char pv) ?{)
13643 str-p (equal (string-to-char pv) ?\")
13644 time-p (save-match-data
13645 (string-match "^\"[[<].*[]>]\"$" pv))
13646 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13647 (if time-p (setq pv (org-matcher-time pv)))
13648 (setq po (org-op-to-function po (if time-p 'time str-p)))
13649 (cond
13650 ((equal pn "CATEGORY")
13651 (setq gv '(get-text-property (point) 'org-category)))
13652 ((equal pn "TODO")
13653 (setq gv 'todo))
13655 (setq gv `(org-cached-entry-get nil ,pn))))
13656 (if re-p
13657 (if (eq po 'org<>)
13658 `(not (string-match ,pv (or ,gv "")))
13659 `(string-match ,pv (or ,gv "")))
13660 (if str-p
13661 `(,po (or ,gv "") ,pv)
13662 `(,po (string-to-number (or ,gv ""))
13663 ,(string-to-number pv) ))))
13664 (t `(member ,tag tags-list)))
13665 mm (if minus (list 'not mm) mm)
13666 term rest)
13667 (push mm tagsmatcher))
13668 (push (if (> (length tagsmatcher) 1)
13669 (cons 'and tagsmatcher)
13670 (car tagsmatcher))
13671 orlist)
13672 (setq tagsmatcher nil))
13673 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13674 (setq tagsmatcher
13675 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13676 ;; Make the todo matcher
13677 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13678 (setq todomatcher t)
13679 (setq orterms (org-split-string todomatch "|") orlist nil)
13680 (while (setq term (pop orterms))
13681 (while (string-match re term)
13682 (setq minus (and (match-end 1)
13683 (equal (match-string 1 term) "-"))
13684 kwd (match-string 2 term)
13685 re-p (equal (string-to-char kwd) ?{)
13686 term (substring term (match-end 0))
13687 mm (if re-p
13688 `(string-match ,(substring kwd 1 -1) todo)
13689 (list 'equal 'todo kwd))
13690 mm (if minus (list 'not mm) mm))
13691 (push mm todomatcher))
13692 (push (if (> (length todomatcher) 1)
13693 (cons 'and todomatcher)
13694 (car todomatcher))
13695 orlist)
13696 (setq todomatcher nil))
13697 (setq todomatcher (if (> (length orlist) 1)
13698 (cons 'or orlist) (car orlist))))
13700 ;; Return the string and lisp forms of the matcher
13701 (setq matcher (if todomatcher
13702 (list 'and tagsmatcher todomatcher)
13703 tagsmatcher))
13704 (when todo-only
13705 (setq matcher (list 'and '(member todo org-not-done-keywords)
13706 matcher)))
13707 (cons match0 matcher)))
13709 (defun org-op-to-function (op &optional stringp)
13710 "Turn an operator into the appropriate function."
13711 (setq op
13712 (cond
13713 ((equal op "<" ) '(< string< org-time<))
13714 ((equal op ">" ) '(> org-string> org-time>))
13715 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13716 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13717 ((member op '("=" "==")) '(= string= org-time=))
13718 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13719 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13721 (defun org<> (a b) (not (= a b)))
13722 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13723 (defun org-string>= (a b) (not (string< a b)))
13724 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13725 (defun org-string<> (a b) (not (string= 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) (> a b)))
13730 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13731 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13732 (defun org-2ft (s)
13733 "Convert S to a floating point time.
13734 If S is already a number, just return it. If it is a string, parse
13735 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13736 (cond
13737 ((numberp s) s)
13738 ((stringp s)
13739 (condition-case nil
13740 (float-time (apply 'encode-time (org-parse-time-string s)))
13741 (error 0.)))
13742 (t 0.)))
13744 (defun org-time-today ()
13745 "Time in seconds today at 0:00.
13746 Returns the float number of seconds since the beginning of the
13747 epoch to the beginning of today (00:00)."
13748 (float-time (apply 'encode-time
13749 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13751 (defun org-matcher-time (s)
13752 "Interpret a time comparison value."
13753 (save-match-data
13754 (cond
13755 ((string= s "<now>") (float-time))
13756 ((string= s "<today>") (org-time-today))
13757 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13758 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13759 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13760 (+ (org-time-today)
13761 (* (string-to-number (match-string 1 s))
13762 (cdr (assoc (match-string 2 s)
13763 '(("d" . 86400.0) ("w" . 604800.0)
13764 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13765 (t (org-2ft s)))))
13767 (defun org-match-any-p (re list)
13768 "Does re match any element of list?"
13769 (setq list (mapcar (lambda (x) (string-match re x)) list))
13770 (delq nil list))
13772 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13773 (defvar org-tags-overlay (make-overlay 1 1))
13774 (org-detach-overlay org-tags-overlay)
13776 (defun org-get-local-tags-at (&optional pos)
13777 "Get a list of tags defined in the current headline."
13778 (org-get-tags-at pos 'local))
13780 (defun org-get-local-tags ()
13781 "Get a list of tags defined in the current headline."
13782 (org-get-tags-at nil 'local))
13784 (defun org-get-tags-at (&optional pos local)
13785 "Get a list of all headline tags applicable at POS.
13786 POS defaults to point. If tags are inherited, the list contains
13787 the targets in the same sequence as the headlines appear, i.e.
13788 the tags of the current headline come last.
13789 When LOCAL is non-nil, only return tags from the current headline,
13790 ignore inherited ones."
13791 (interactive)
13792 (if (and org-trust-scanner-tags
13793 (or (not pos) (equal pos (point)))
13794 (not local))
13795 org-scanner-tags
13796 (let (tags ltags lastpos parent)
13797 (save-excursion
13798 (save-restriction
13799 (widen)
13800 (goto-char (or pos (point)))
13801 (save-match-data
13802 (catch 'done
13803 (condition-case nil
13804 (progn
13805 (org-back-to-heading t)
13806 (while (not (equal lastpos (point)))
13807 (setq lastpos (point))
13808 (when (looking-at
13809 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13810 (setq ltags (org-split-string
13811 (org-match-string-no-properties 1) ":"))
13812 (when parent
13813 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13814 (setq tags (append
13815 (if parent
13816 (org-remove-uninherited-tags ltags)
13817 ltags)
13818 tags)))
13819 (or org-use-tag-inheritance (throw 'done t))
13820 (if local (throw 'done t))
13821 (or (org-up-heading-safe) (error nil))
13822 (setq parent t)))
13823 (error nil)))))
13824 (if local
13825 tags
13826 (reverse (delete-dups
13827 (reverse (append
13828 (org-remove-uninherited-tags
13829 org-file-tags) tags)))))))))
13831 (defun org-add-prop-inherited (s)
13832 (add-text-properties 0 (length s) '(inherited t) s)
13835 (defun org-toggle-tag (tag &optional onoff)
13836 "Toggle the tag TAG for the current line.
13837 If ONOFF is `on' or `off', don't toggle but set to this state."
13838 (let (res current)
13839 (save-excursion
13840 (org-back-to-heading t)
13841 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13842 (point-at-eol) t)
13843 (progn
13844 (setq current (match-string 1))
13845 (replace-match ""))
13846 (setq current ""))
13847 (setq current (nreverse (org-split-string current ":")))
13848 (cond
13849 ((eq onoff 'on)
13850 (setq res t)
13851 (or (member tag current) (push tag current)))
13852 ((eq onoff 'off)
13853 (or (not (member tag current)) (setq current (delete tag current))))
13854 (t (if (member tag current)
13855 (setq current (delete tag current))
13856 (setq res t)
13857 (push tag current))))
13858 (end-of-line 1)
13859 (if current
13860 (progn
13861 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13862 (org-set-tags nil t))
13863 (delete-horizontal-space))
13864 (run-hooks 'org-after-tags-change-hook))
13865 res))
13867 (defun org-align-tags-here (to-col)
13868 ;; Assumes that this is a headline
13869 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13870 (beginning-of-line 1)
13871 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13872 (< pos (match-beginning 2)))
13873 (progn
13874 (setq tags-l (- (match-end 2) (match-beginning 2)))
13875 (goto-char (match-beginning 1))
13876 (insert " ")
13877 (delete-region (point) (1+ (match-beginning 2)))
13878 (setq ncol (max (current-column)
13879 (1+ col)
13880 (if (> to-col 0)
13881 to-col
13882 (- (abs to-col) tags-l))))
13883 (setq p (point))
13884 (insert (make-string (- ncol (current-column)) ?\ ))
13885 (setq ncol (current-column))
13886 (when indent-tabs-mode (tabify p (point-at-eol)))
13887 (org-move-to-column (min ncol col) t))
13888 (goto-char pos))))
13890 (defun org-set-tags-command (&optional arg just-align)
13891 "Call the set-tags command for the current entry."
13892 (interactive "P")
13893 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13894 (org-set-tags arg just-align)
13895 (save-excursion
13896 (org-back-to-heading t)
13897 (org-set-tags arg just-align))))
13899 (defun org-set-tags-to (data)
13900 "Set the tags of the current entry to DATA, replacing the current tags.
13901 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13902 If DATA is nil or the empty string, any tags will be removed."
13903 (interactive "sTags: ")
13904 (setq data
13905 (cond
13906 ((eq data nil) "")
13907 ((equal data "") "")
13908 ((stringp data)
13909 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13910 ":"))
13911 ((listp data)
13912 (concat ":" (mapconcat 'identity data ":") ":"))))
13913 (when data
13914 (save-excursion
13915 (org-back-to-heading t)
13916 (when (looking-at org-complex-heading-regexp)
13917 (if (match-end 5)
13918 (progn
13919 (goto-char (match-beginning 5))
13920 (insert data)
13921 (delete-region (point) (point-at-eol))
13922 (org-set-tags nil 'align))
13923 (goto-char (point-at-eol))
13924 (insert " " data)
13925 (org-set-tags nil 'align)))
13926 (beginning-of-line 1)
13927 (if (looking-at ".*?\\([ \t]+\\)$")
13928 (delete-region (match-beginning 1) (match-end 1))))))
13930 (defun org-align-all-tags ()
13931 "Align the tags i all headings."
13932 (interactive)
13933 (save-excursion
13934 (or (ignore-errors (org-back-to-heading t))
13935 (outline-next-heading))
13936 (if (org-at-heading-p)
13937 (org-set-tags t)
13938 (message "No headings"))))
13940 (defvar org-indent-indentation-per-level)
13941 (defun org-set-tags (&optional arg just-align)
13942 "Set the tags for the current headline.
13943 With prefix ARG, realign all tags in headings in the current buffer."
13944 (interactive "P")
13945 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13946 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13947 'region-start-level 'region))
13948 org-loop-over-headlines-in-active-region)
13949 (org-map-entries
13950 ;; We don't use ARG and JUST-ALIGN here these args are not
13951 ;; useful when looping over headlines
13952 `(org-set-tags)
13953 org-loop-over-headlines-in-active-region
13954 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13955 (let* ((re org-outline-regexp-bol)
13956 (current (unless arg (org-get-tags-string)))
13957 (col (current-column))
13958 (org-setting-tags t)
13959 table current-tags inherited-tags ; computed below when needed
13960 tags p0 c0 c1 rpl di tc level)
13961 (if arg
13962 (save-excursion
13963 (goto-char (point-min))
13964 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13965 (while (re-search-forward re nil t)
13966 (org-set-tags nil t)
13967 (end-of-line 1)))
13968 (message "All tags realigned to column %d" org-tags-column))
13969 (if just-align
13970 (setq tags current)
13971 ;; Get a new set of tags from the user
13972 (save-excursion
13973 (setq table (append org-tag-persistent-alist
13974 (or org-tag-alist (org-get-buffer-tags))
13975 (and
13976 org-complete-tags-always-offer-all-agenda-tags
13977 (org-global-tags-completion-table
13978 (org-agenda-files))))
13979 org-last-tags-completion-table table
13980 current-tags (org-split-string current ":")
13981 inherited-tags (nreverse
13982 (nthcdr (length current-tags)
13983 (nreverse (org-get-tags-at))))
13984 tags
13985 (if (or (eq t org-use-fast-tag-selection)
13986 (and org-use-fast-tag-selection
13987 (delq nil (mapcar 'cdr table))))
13988 (org-fast-tag-selection
13989 current-tags inherited-tags table
13990 (if org-fast-tag-selection-include-todo
13991 org-todo-key-alist))
13992 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13993 (org-trim
13994 (org-icompleting-read "Tags: "
13995 'org-tags-completion-function
13996 nil nil current 'org-tags-history))))))
13997 (while (string-match "[-+&]+" tags)
13998 ;; No boolean logic, just a list
13999 (setq tags (replace-match ":" t t tags))))
14001 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14003 (if org-tags-sort-function
14004 (setq tags (mapconcat 'identity
14005 (sort (org-split-string
14006 tags (org-re "[^[:alnum:]_@#%]+"))
14007 org-tags-sort-function) ":")))
14009 (if (string-match "\\`[\t ]*\\'" tags)
14010 (setq tags "")
14011 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14012 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14014 ;; Insert new tags at the correct column
14015 (beginning-of-line 1)
14016 (setq level (or (and (looking-at org-outline-regexp)
14017 (- (match-end 0) (point) 1))
14019 (cond
14020 ((and (equal current "") (equal tags "")))
14021 ((re-search-forward
14022 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14023 (point-at-eol) t)
14024 (if (equal tags "")
14025 (setq rpl "")
14026 (goto-char (match-beginning 0))
14027 (setq c0 (current-column)
14028 ;; compute offset for the case of org-indent-mode active
14029 di (if org-indent-mode
14030 (* (1- org-indent-indentation-per-level) (1- level))
14032 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14033 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14034 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14035 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14036 (replace-match rpl t t)
14037 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14038 tags)
14039 (t (error "Tags alignment failed")))
14040 (org-move-to-column col)
14041 (unless just-align
14042 (run-hooks 'org-after-tags-change-hook))))))
14044 (defun org-change-tag-in-region (beg end tag off)
14045 "Add or remove TAG for each entry in the region.
14046 This works in the agenda, and also in an org-mode buffer."
14047 (interactive
14048 (list (region-beginning) (region-end)
14049 (let ((org-last-tags-completion-table
14050 (if (derived-mode-p 'org-mode)
14051 (org-get-buffer-tags)
14052 (org-global-tags-completion-table))))
14053 (org-icompleting-read
14054 "Tag: " 'org-tags-completion-function nil nil nil
14055 'org-tags-history))
14056 (progn
14057 (message "[s]et or [r]emove? ")
14058 (equal (read-char-exclusive) ?r))))
14059 (if (fboundp 'deactivate-mark) (deactivate-mark))
14060 (let ((agendap (equal major-mode 'org-agenda-mode))
14061 l1 l2 m buf pos newhead (cnt 0))
14062 (goto-char end)
14063 (setq l2 (1- (org-current-line)))
14064 (goto-char beg)
14065 (setq l1 (org-current-line))
14066 (loop for l from l1 to l2 do
14067 (org-goto-line l)
14068 (setq m (get-text-property (point) 'org-hd-marker))
14069 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14070 (and agendap m))
14071 (setq buf (if agendap (marker-buffer m) (current-buffer))
14072 pos (if agendap m (point)))
14073 (with-current-buffer buf
14074 (save-excursion
14075 (save-restriction
14076 (goto-char pos)
14077 (setq cnt (1+ cnt))
14078 (org-toggle-tag tag (if off 'off 'on))
14079 (setq newhead (org-get-heading)))))
14080 (and agendap (org-agenda-change-all-lines newhead m))))
14081 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14083 (defun org-tags-completion-function (string predicate &optional flag)
14084 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14085 (confirm (lambda (x) (stringp (car x)))))
14086 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14087 (setq s1 (match-string 1 string)
14088 s2 (match-string 2 string))
14089 (setq s1 "" s2 string))
14090 (cond
14091 ((eq flag nil)
14092 ;; try completion
14093 (setq rtn (try-completion s2 ctable confirm))
14094 (if (stringp rtn)
14095 (setq rtn
14096 (concat s1 s2 (substring rtn (length s2))
14097 (if (and org-add-colon-after-tag-completion
14098 (assoc rtn ctable))
14099 ":" ""))))
14100 rtn)
14101 ((eq flag t)
14102 ;; all-completions
14103 (all-completions s2 ctable confirm)
14105 ((eq flag 'lambda)
14106 ;; exact match?
14107 (assoc s2 ctable)))
14110 (defun org-fast-tag-insert (kwd tags face &optional end)
14111 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14112 (insert (format "%-12s" (concat kwd ":"))
14113 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14114 (or end "")))
14116 (defun org-fast-tag-show-exit (flag)
14117 (save-excursion
14118 (org-goto-line 3)
14119 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14120 (replace-match ""))
14121 (when flag
14122 (end-of-line 1)
14123 (org-move-to-column (- (window-width) 19) t)
14124 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14126 (defun org-set-current-tags-overlay (current prefix)
14127 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14128 (if (featurep 'xemacs)
14129 (org-overlay-display org-tags-overlay (concat prefix s)
14130 'secondary-selection)
14131 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14132 (org-overlay-display org-tags-overlay (concat prefix s)))))
14134 (defvar org-last-tag-selection-key nil)
14135 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14136 "Fast tag selection with single keys.
14137 CURRENT is the current list of tags in the headline, INHERITED is the
14138 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14139 possibly with grouping information. TODO-TABLE is a similar table with
14140 TODO keywords, should these have keys assigned to them.
14141 If the keys are nil, a-z are automatically assigned.
14142 Returns the new tags string, or nil to not change the current settings."
14143 (let* ((fulltable (append table todo-table))
14144 (maxlen (apply 'max (mapcar
14145 (lambda (x)
14146 (if (stringp (car x)) (string-width (car x)) 0))
14147 fulltable)))
14148 (buf (current-buffer))
14149 (expert (eq org-fast-tag-selection-single-key 'expert))
14150 (buffer-tags nil)
14151 (fwidth (+ maxlen 3 1 3))
14152 (ncol (/ (- (window-width) 4) fwidth))
14153 (i-face 'org-done)
14154 (c-face 'org-todo)
14155 tg cnt e c char c1 c2 ntable tbl rtn
14156 ov-start ov-end ov-prefix
14157 (exit-after-next org-fast-tag-selection-single-key)
14158 (done-keywords org-done-keywords)
14159 groups ingroup)
14160 (save-excursion
14161 (beginning-of-line 1)
14162 (if (looking-at
14163 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14164 (setq ov-start (match-beginning 1)
14165 ov-end (match-end 1)
14166 ov-prefix "")
14167 (setq ov-start (1- (point-at-eol))
14168 ov-end (1+ ov-start))
14169 (skip-chars-forward "^\n\r")
14170 (setq ov-prefix
14171 (concat
14172 (buffer-substring (1- (point)) (point))
14173 (if (> (current-column) org-tags-column)
14175 (make-string (- org-tags-column (current-column)) ?\ ))))))
14176 (move-overlay org-tags-overlay ov-start ov-end)
14177 (save-window-excursion
14178 (if expert
14179 (set-buffer (get-buffer-create " *Org tags*"))
14180 (delete-other-windows)
14181 (split-window-vertically)
14182 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14183 (erase-buffer)
14184 (org-set-local 'org-done-keywords done-keywords)
14185 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14186 (org-fast-tag-insert "Current" current c-face "\n\n")
14187 (org-fast-tag-show-exit exit-after-next)
14188 (org-set-current-tags-overlay current ov-prefix)
14189 (setq tbl fulltable char ?a cnt 0)
14190 (while (setq e (pop tbl))
14191 (cond
14192 ((equal (car e) :startgroup)
14193 (push '() groups) (setq ingroup t)
14194 (when (not (= cnt 0))
14195 (setq cnt 0)
14196 (insert "\n"))
14197 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14198 ((equal (car e) :endgroup)
14199 (setq ingroup nil cnt 0)
14200 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14201 ((equal e '(:newline))
14202 (when (not (= cnt 0))
14203 (setq cnt 0)
14204 (insert "\n")
14205 (setq e (car tbl))
14206 (while (equal (car tbl) '(:newline))
14207 (insert "\n")
14208 (setq tbl (cdr tbl)))))
14210 (setq tg (copy-sequence (car e)) c2 nil)
14211 (if (cdr e)
14212 (setq c (cdr e))
14213 ;; automatically assign a character.
14214 (setq c1 (string-to-char
14215 (downcase (substring
14216 tg (if (= (string-to-char tg) ?@) 1 0)))))
14217 (if (or (rassoc c1 ntable) (rassoc c1 table))
14218 (while (or (rassoc char ntable) (rassoc char table))
14219 (setq char (1+ char)))
14220 (setq c2 c1))
14221 (setq c (or c2 char)))
14222 (if ingroup (push tg (car groups)))
14223 (setq tg (org-add-props tg nil 'face
14224 (cond
14225 ((not (assoc tg table))
14226 (org-get-todo-face tg))
14227 ((member tg current) c-face)
14228 ((member tg inherited) i-face))))
14229 (if (and (= cnt 0) (not ingroup)) (insert " "))
14230 (insert "[" c "] " tg (make-string
14231 (- fwidth 4 (length tg)) ?\ ))
14232 (push (cons tg c) ntable)
14233 (when (= (setq cnt (1+ cnt)) ncol)
14234 (insert "\n")
14235 (if ingroup (insert " "))
14236 (setq cnt 0)))))
14237 (setq ntable (nreverse ntable))
14238 (insert "\n")
14239 (goto-char (point-min))
14240 (if (not expert) (org-fit-window-to-buffer))
14241 (setq rtn
14242 (catch 'exit
14243 (while t
14244 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14245 (if (not groups) "no " "")
14246 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14247 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14248 (setq org-last-tag-selection-key c)
14249 (cond
14250 ((= c ?\r) (throw 'exit t))
14251 ((= c ?!)
14252 (setq groups (not groups))
14253 (goto-char (point-min))
14254 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14255 ((= c ?\C-c)
14256 (if (not expert)
14257 (org-fast-tag-show-exit
14258 (setq exit-after-next (not exit-after-next)))
14259 (setq expert nil)
14260 (delete-other-windows)
14261 (set-window-buffer (split-window-vertically) " *Org tags*")
14262 (org-switch-to-buffer-other-window " *Org tags*")
14263 (org-fit-window-to-buffer)))
14264 ((or (= c ?\C-g)
14265 (and (= c ?q) (not (rassoc c ntable))))
14266 (org-detach-overlay org-tags-overlay)
14267 (setq quit-flag t))
14268 ((= c ?\ )
14269 (setq current nil)
14270 (if exit-after-next (setq exit-after-next 'now)))
14271 ((= c ?\t)
14272 (condition-case nil
14273 (setq tg (org-icompleting-read
14274 "Tag: "
14275 (or buffer-tags
14276 (with-current-buffer buf
14277 (org-get-buffer-tags)))))
14278 (quit (setq tg "")))
14279 (when (string-match "\\S-" tg)
14280 (add-to-list 'buffer-tags (list tg))
14281 (if (member tg current)
14282 (setq current (delete tg current))
14283 (push tg current)))
14284 (if exit-after-next (setq exit-after-next 'now)))
14285 ((setq e (rassoc c todo-table) tg (car e))
14286 (with-current-buffer buf
14287 (save-excursion (org-todo tg)))
14288 (if exit-after-next (setq exit-after-next 'now)))
14289 ((setq e (rassoc c ntable) tg (car e))
14290 (if (member tg current)
14291 (setq current (delete tg current))
14292 (loop for g in groups do
14293 (if (member tg g)
14294 (mapc (lambda (x)
14295 (setq current (delete x current)))
14296 g)))
14297 (push tg current))
14298 (if exit-after-next (setq exit-after-next 'now))))
14300 ;; Create a sorted list
14301 (setq current
14302 (sort current
14303 (lambda (a b)
14304 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14305 (if (eq exit-after-next 'now) (throw 'exit t))
14306 (goto-char (point-min))
14307 (beginning-of-line 2)
14308 (delete-region (point) (point-at-eol))
14309 (org-fast-tag-insert "Current" current c-face)
14310 (org-set-current-tags-overlay current ov-prefix)
14311 (while (re-search-forward
14312 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14313 (setq tg (match-string 1))
14314 (add-text-properties
14315 (match-beginning 1) (match-end 1)
14316 (list 'face
14317 (cond
14318 ((member tg current) c-face)
14319 ((member tg inherited) i-face)
14320 (t (get-text-property (match-beginning 1) 'face))))))
14321 (goto-char (point-min)))))
14322 (org-detach-overlay org-tags-overlay)
14323 (if rtn
14324 (mapconcat 'identity current ":")
14325 nil))))
14327 (defun org-get-tags-string ()
14328 "Get the TAGS string in the current headline."
14329 (unless (org-at-heading-p t)
14330 (error "Not on a heading"))
14331 (save-excursion
14332 (beginning-of-line 1)
14333 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14334 (org-match-string-no-properties 1)
14335 "")))
14337 (defun org-get-tags ()
14338 "Get the list of tags specified in the current headline."
14339 (org-split-string (org-get-tags-string) ":"))
14341 (defun org-get-buffer-tags ()
14342 "Get a table of all tags used in the buffer, for completion."
14343 (let (tags)
14344 (save-excursion
14345 (goto-char (point-min))
14346 (while (re-search-forward
14347 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14348 (when (equal (char-after (point-at-bol 0)) ?*)
14349 (mapc (lambda (x) (add-to-list 'tags x))
14350 (org-split-string (org-match-string-no-properties 1) ":")))))
14351 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14352 (mapcar 'list tags)))
14354 ;;;; The mapping API
14356 (defun org-map-entries (func &optional match scope &rest skip)
14357 "Call FUNC at each headline selected by MATCH in SCOPE.
14359 FUNC is a function or a lisp form. The function will be called without
14360 arguments, with the cursor positioned at the beginning of the headline.
14361 The return values of all calls to the function will be collected and
14362 returned as a list.
14364 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14365 does not need to preserve point. After evaluation, the cursor will be
14366 moved to the end of the line (presumably of the headline of the
14367 processed entry) and search continues from there. Under some
14368 circumstances, this may not produce the wanted results. For example,
14369 if you have removed (e.g. archived) the current (sub)tree it could
14370 mean that the next entry will be skipped entirely. In such cases, you
14371 can specify the position from where search should continue by making
14372 FUNC set the variable `org-map-continue-from' to the desired buffer
14373 position.
14375 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14376 Only headlines that are matched by this query will be considered during
14377 the iteration. When MATCH is nil or t, all headlines will be
14378 visited by the iteration.
14380 SCOPE determines the scope of this command. It can be any of:
14382 nil The current buffer, respecting the restriction if any
14383 tree The subtree started with the entry at point
14384 region The entries within the active region, if any
14385 region-start-level
14386 The entries within the active region, but only those at
14387 the same level than the first one.
14388 file The current buffer, without restriction
14389 file-with-archives
14390 The current buffer, and any archives associated with it
14391 agenda All agenda files
14392 agenda-with-archives
14393 All agenda files with any archive files associated with them
14394 \(file1 file2 ...)
14395 If this is a list, all files in the list will be scanned
14397 The remaining args are treated as settings for the skipping facilities of
14398 the scanner. The following items can be given here:
14400 archive skip trees with the archive tag.
14401 comment skip trees with the COMMENT keyword
14402 function or Emacs Lisp form:
14403 will be used as value for `org-agenda-skip-function', so whenever
14404 the function returns t, FUNC will not be called for that
14405 entry and search will continue from the point where the
14406 function leaves it.
14408 If your function needs to retrieve the tags including inherited tags
14409 at the *current* entry, you can use the value of the variable
14410 `org-scanner-tags' which will be much faster than getting the value
14411 with `org-get-tags-at'. If your function gets properties with
14412 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14413 to t around the call to `org-entry-properties' to get the same speedup.
14414 Note that if your function moves around to retrieve tags and properties at
14415 a *different* entry, you cannot use these techniques."
14416 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14417 (not (org-region-active-p)))
14418 (let* ((org-agenda-archives-mode nil) ; just to make sure
14419 (org-agenda-skip-archived-trees (memq 'archive skip))
14420 (org-agenda-skip-comment-trees (memq 'comment skip))
14421 (org-agenda-skip-function
14422 (car (org-delete-all '(comment archive) skip)))
14423 (org-tags-match-list-sublevels t)
14424 (start-level (eq scope 'region-start-level))
14425 matcher file res
14426 org-todo-keywords-for-agenda
14427 org-done-keywords-for-agenda
14428 org-todo-keyword-alist-for-agenda
14429 org-drawers-for-agenda
14430 org-tag-alist-for-agenda
14431 todo-only)
14433 (cond
14434 ((eq match t) (setq matcher t))
14435 ((eq match nil) (setq matcher t))
14436 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14438 (save-excursion
14439 (save-restriction
14440 (cond ((eq scope 'tree)
14441 (org-back-to-heading t)
14442 (org-narrow-to-subtree)
14443 (setq scope nil))
14444 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14445 (org-region-active-p))
14446 ;; If needed, set start-level to a string like "2"
14447 (when start-level
14448 (save-excursion
14449 (goto-char (region-beginning))
14450 (unless (org-at-heading-p) (outline-next-heading))
14451 (setq start-level (org-current-level))))
14452 (narrow-to-region (region-beginning)
14453 (save-excursion
14454 (goto-char (region-end))
14455 (unless (and (bolp) (org-at-heading-p))
14456 (outline-next-heading))
14457 (point)))
14458 (setq scope nil)))
14460 (if (not scope)
14461 (progn
14462 (org-agenda-prepare-buffers
14463 (list (buffer-file-name (current-buffer))))
14464 (setq res (org-scan-tags func matcher todo-only start-level)))
14465 ;; Get the right scope
14466 (cond
14467 ((and scope (listp scope) (symbolp (car scope)))
14468 (setq scope (eval scope)))
14469 ((eq scope 'agenda)
14470 (setq scope (org-agenda-files t)))
14471 ((eq scope 'agenda-with-archives)
14472 (setq scope (org-agenda-files t))
14473 (setq scope (org-add-archive-files scope)))
14474 ((eq scope 'file)
14475 (setq scope (list (buffer-file-name))))
14476 ((eq scope 'file-with-archives)
14477 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14478 (org-agenda-prepare-buffers scope)
14479 (while (setq file (pop scope))
14480 (with-current-buffer (org-find-base-buffer-visiting file)
14481 (save-excursion
14482 (save-restriction
14483 (widen)
14484 (goto-char (point-min))
14485 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14486 res)))
14488 ;;;; Properties
14490 ;;; Setting and retrieving properties
14492 (defconst org-special-properties
14493 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14494 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14495 "The special properties valid in Org-mode.
14497 These are properties that are not defined in the property drawer,
14498 but in some other way.")
14500 (defconst org-default-properties
14501 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14502 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14503 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14504 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14505 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14506 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14507 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14508 "Some properties that are used by Org-mode for various purposes.
14509 Being in this list makes sure that they are offered for completion.")
14511 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14512 "Regular expression matching the first line of a property drawer.")
14514 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14515 "Regular expression matching the last line of a property drawer.")
14517 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14518 "Regular expression matching the first line of a property drawer.")
14520 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14521 "Regular expression matching the first line of a property drawer.")
14523 (defconst org-property-drawer-re
14524 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14525 org-property-end-re "\\)\n?")
14526 "Matches an entire property drawer.")
14528 (defconst org-clock-drawer-re
14529 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14530 org-property-end-re "\\)\n?")
14531 "Matches an entire clock drawer.")
14533 (defsubst org-re-property (property)
14534 "Return a regexp matching a PROPERTY line.
14535 Match group 1 will be set to the value."
14536 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14538 (defsubst org-re-property-keyword (property)
14539 "Return a regexp matching a PROPERTY line, possibly with no
14540 value for the property."
14541 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14543 (defun org-property-action ()
14544 "Do an action on properties."
14545 (interactive)
14546 (let (c)
14547 (org-at-property-p)
14548 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14549 (setq c (read-char-exclusive))
14550 (cond
14551 ((equal c ?s)
14552 (call-interactively 'org-set-property))
14553 ((equal c ?d)
14554 (call-interactively 'org-delete-property))
14555 ((equal c ?D)
14556 (call-interactively 'org-delete-property-globally))
14557 ((equal c ?c)
14558 (call-interactively 'org-compute-property-at-point))
14559 (t (error "No such property action %c" c)))))
14561 (defun org-inc-effort ()
14562 "Increment the value of the effort property in the current entry."
14563 (interactive)
14564 (org-set-effort nil t))
14566 (defun org-set-effort (&optional value increment)
14567 "Set the effort property of the current entry.
14568 With numerical prefix arg, use the nth allowed value, 0 stands for the
14569 10th allowed value.
14571 When INCREMENT is non-nil, set the property to the next allowed value."
14572 (interactive "P")
14573 (if (equal value 0) (setq value 10))
14574 (let* ((completion-ignore-case t)
14575 (prop org-effort-property)
14576 (cur (org-entry-get nil prop))
14577 (allowed (org-property-get-allowed-values nil prop 'table))
14578 (existing (mapcar 'list (org-property-values prop)))
14580 (val (cond
14581 ((stringp value) value)
14582 ((and allowed (integerp value))
14583 (or (car (nth (1- value) allowed))
14584 (car (org-last allowed))))
14585 ((and allowed increment)
14586 (or (caadr (member (list cur) allowed))
14587 (error "Allowed effort values are not set")))
14588 (allowed
14589 (message "Select 1-9,0, [RET%s]: %s"
14590 (if cur (concat "=" cur) "")
14591 (mapconcat 'car allowed " "))
14592 (setq rpl (read-char-exclusive))
14593 (if (equal rpl ?\r)
14595 (setq rpl (- rpl ?0))
14596 (if (equal rpl 0) (setq rpl 10))
14597 (if (and (> rpl 0) (<= rpl (length allowed)))
14598 (car (nth (1- rpl) allowed))
14599 (org-completing-read "Effort: " allowed nil))))
14601 (let (org-completion-use-ido org-completion-use-iswitchb)
14602 (org-completing-read
14603 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14604 (concat "[" cur "]") "")
14605 ": ")
14606 existing nil nil "" nil cur))))))
14607 (unless (equal (org-entry-get nil prop) val)
14608 (org-entry-put nil prop val))
14609 (save-excursion
14610 (org-back-to-heading t)
14611 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14612 (message "%s is now %s" prop val)))
14614 (defun org-at-property-p ()
14615 "Is cursor inside a property drawer?"
14616 (save-excursion
14617 (beginning-of-line 1)
14618 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14619 (save-match-data ;; Used by calling procedures
14620 (let ((p (point))
14621 (range (unless (org-before-first-heading-p)
14622 (org-get-property-block))))
14623 (and range (<= (car range) p) (< p (cdr range))))))))
14625 (defun org-get-property-block (&optional beg end force)
14626 "Return the (beg . end) range of the body of the property drawer.
14627 BEG and END are the beginning and end of the current subtree, or of
14628 the part before the first headline. If they are not given, they will
14629 be found. If the drawer does not exist and FORCE is non-nil, create
14630 the drawer."
14631 (catch 'exit
14632 (save-excursion
14633 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14634 (progn (org-back-to-heading t) (point))))
14635 (end (or end (and (not (outline-next-heading)) (point-max))
14636 (point))))
14637 (goto-char beg)
14638 (if (re-search-forward org-property-start-re end t)
14639 (setq beg (1+ (match-end 0)))
14640 (if force
14641 (save-excursion
14642 (org-insert-property-drawer)
14643 (setq end (progn (outline-next-heading) (point))))
14644 (throw 'exit nil))
14645 (goto-char beg)
14646 (if (re-search-forward org-property-start-re end t)
14647 (setq beg (1+ (match-end 0)))))
14648 (if (re-search-forward org-property-end-re end t)
14649 (setq end (match-beginning 0))
14650 (or force (throw 'exit nil))
14651 (goto-char beg)
14652 (setq end beg)
14653 (org-indent-line)
14654 (insert ":END:\n"))
14655 (cons beg end)))))
14657 (defun org-entry-properties (&optional pom which specific)
14658 "Get all properties of the entry at point-or-marker POM.
14659 This includes the TODO keyword, the tags, time strings for deadline,
14660 scheduled, and clocking, and any additional properties defined in the
14661 entry. The return value is an alist, keys may occur multiple times
14662 if the property key was used several times.
14663 POM may also be nil, in which case the current entry is used.
14664 If WHICH is nil or `all', get all properties. If WHICH is
14665 `special' or `standard', only get that subclass. If WHICH
14666 is a string only get exactly this property. SPECIFIC can be a string, the
14667 specific property we are interested in. Specifying it can speed
14668 things up because then unnecessary parsing is avoided."
14669 (setq which (or which 'all))
14670 (org-with-point-at pom
14671 (let ((clockstr (substring org-clock-string 0 -1))
14672 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14673 (case-fold-search nil)
14674 beg end range props sum-props key key1 value string clocksum clocksumt)
14675 (save-excursion
14676 (when (condition-case nil
14677 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14678 (error nil))
14679 (setq beg (point))
14680 (setq sum-props (get-text-property (point) 'org-summaries))
14681 (setq clocksum (get-text-property (point) :org-clock-minutes)
14682 clocksumt (get-text-property (point) :org-clock-minutes-today))
14683 (outline-next-heading)
14684 (setq end (point))
14685 (when (memq which '(all special))
14686 ;; Get the special properties, like TODO and tags
14687 (goto-char beg)
14688 (when (and (or (not specific) (string= specific "TODO"))
14689 (looking-at org-todo-line-regexp) (match-end 2))
14690 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14691 (when (and (or (not specific) (string= specific "PRIORITY"))
14692 (looking-at org-priority-regexp))
14693 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14694 (when (or (not specific) (string= specific "FILE"))
14695 (push (cons "FILE" buffer-file-name) props))
14696 (when (and (or (not specific) (string= specific "TAGS"))
14697 (setq value (org-get-tags-string))
14698 (string-match "\\S-" value))
14699 (push (cons "TAGS" value) props))
14700 (when (and (or (not specific) (string= specific "ALLTAGS"))
14701 (setq value (org-get-tags-at)))
14702 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14703 ":"))
14704 props))
14705 (when (or (not specific) (string= specific "BLOCKED"))
14706 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14707 (when (or (not specific)
14708 (member specific
14709 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14710 "TIMESTAMP" "TIMESTAMP_IA")))
14711 (catch 'match
14712 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14713 (setq key (if (match-end 1)
14714 (substring (org-match-string-no-properties 1)
14715 0 -1))
14716 string (if (equal key clockstr)
14717 (org-trim
14718 (buffer-substring-no-properties
14719 (match-beginning 3) (goto-char
14720 (point-at-eol))))
14721 (substring (org-match-string-no-properties 3)
14722 1 -1)))
14723 ;; Get the correct property name from the key. This is
14724 ;; necessary if the user has configured time keywords.
14725 (setq key1 (concat key ":"))
14726 (cond
14727 ((not key)
14728 (setq key
14729 (if (= (char-after (match-beginning 3)) ?\[)
14730 "TIMESTAMP_IA" "TIMESTAMP")))
14731 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14732 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14733 ((equal key1 org-closed-string) (setq key "CLOSED"))
14734 ((equal key1 org-clock-string) (setq key "CLOCK")))
14735 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14736 (progn
14737 (push (cons key string) props)
14738 ;; no need to search further if match is found
14739 (throw 'match t))
14740 (when (or (equal key "CLOCK") (not (assoc key props)))
14741 (push (cons key string) props)))))))
14743 (when (memq which '(all standard))
14744 ;; Get the standard properties, like :PROP: ...
14745 (setq range (org-get-property-block beg end))
14746 (when range
14747 (goto-char (car range))
14748 (while (re-search-forward
14749 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14750 (cdr range) t)
14751 (setq key (org-match-string-no-properties 1)
14752 value (org-trim (or (org-match-string-no-properties 2) "")))
14753 (unless (member key excluded)
14754 (push (cons key (or value "")) props)))))
14755 (if clocksum
14756 (push (cons "CLOCKSUM"
14757 (org-columns-number-to-string (/ (float clocksum) 60.)
14758 'add_times))
14759 props))
14760 (if clocksumt
14761 (push (cons "CLOCKSUM_T"
14762 (org-columns-number-to-string (/ (float clocksumt) 60.)
14763 'add_times))
14764 props))
14765 (unless (assoc "CATEGORY" props)
14766 (push (cons "CATEGORY" (org-get-category)) props))
14767 (append sum-props (nreverse props)))))))
14769 (defun org-entry-get (pom property &optional inherit literal-nil)
14770 "Get value of PROPERTY for entry or content at point-or-marker POM.
14771 If INHERIT is non-nil and the entry does not have the property,
14772 then also check higher levels of the hierarchy.
14773 If INHERIT is the symbol `selective', use inheritance only if the setting
14774 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14775 If the property is present but empty, the return value is the empty string.
14776 If the property is not present at all, nil is returned.
14778 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14779 do not interpret it as the list atom nil. This is used for inheritance
14780 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14781 (org-with-point-at pom
14782 (if (and inherit (if (eq inherit 'selective)
14783 (org-property-inherit-p property)
14785 (org-entry-get-with-inheritance property literal-nil)
14786 (if (member property org-special-properties)
14787 ;; We need a special property. Use `org-entry-properties' to
14788 ;; retrieve it, but specify the wanted property
14789 (cdr (assoc property (org-entry-properties nil 'special property)))
14790 (let ((range (org-get-property-block)))
14791 (when (and range (not (eq (car range) (cdr range))))
14792 (let* ((props (list (or (assoc property org-file-properties)
14793 (assoc property org-global-properties)
14794 (assoc property org-global-properties-fixed))))
14795 (ap (lambda (key)
14796 (when (re-search-forward
14797 (org-re-property key) (cdr range) t)
14798 (setq props
14799 (org-update-property-plist
14801 (if (match-end 1)
14802 (org-match-string-no-properties 1) "")
14803 props)))))
14804 val)
14805 (goto-char (car range))
14806 (funcall ap property)
14807 (goto-char (car range))
14808 (while (funcall ap (concat property "+")))
14809 (setq val (cdr (assoc property props)))
14810 (when val (if literal-nil val (org-not-nil val))))))))))
14812 (defun org-property-or-variable-value (var &optional inherit)
14813 "Check if there is a property fixing the value of VAR.
14814 If yes, return this value. If not, return the current value of the variable."
14815 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14816 (if (and prop (stringp prop) (string-match "\\S-" prop))
14817 (read prop)
14818 (symbol-value var))))
14820 (defun org-entry-delete (pom property)
14821 "Delete the property PROPERTY from entry at point-or-marker POM."
14822 (org-with-point-at pom
14823 (if (member property org-special-properties)
14824 nil ; cannot delete these properties.
14825 (let ((range (org-get-property-block)))
14826 (if (and range
14827 (goto-char (car range))
14828 (re-search-forward
14829 (org-re-property property)
14830 (cdr range) t))
14831 (progn
14832 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14834 nil)))))
14836 ;; Multi-values properties are properties that contain multiple values
14837 ;; These values are assumed to be single words, separated by whitespace.
14838 (defun org-entry-add-to-multivalued-property (pom property value)
14839 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14840 (let* ((old (org-entry-get pom property))
14841 (values (and old (org-split-string old "[ \t]"))))
14842 (setq value (org-entry-protect-space value))
14843 (unless (member value values)
14844 (setq values (cons value values))
14845 (org-entry-put pom property
14846 (mapconcat 'identity values " ")))))
14848 (defun org-entry-remove-from-multivalued-property (pom property value)
14849 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14850 (let* ((old (org-entry-get pom property))
14851 (values (and old (org-split-string old "[ \t]"))))
14852 (setq value (org-entry-protect-space value))
14853 (when (member value values)
14854 (setq values (delete value values))
14855 (org-entry-put pom property
14856 (mapconcat 'identity values " ")))))
14858 (defun org-entry-member-in-multivalued-property (pom property value)
14859 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14860 (let* ((old (org-entry-get pom property))
14861 (values (and old (org-split-string old "[ \t]"))))
14862 (setq value (org-entry-protect-space value))
14863 (member value values)))
14865 (defun org-entry-get-multivalued-property (pom property)
14866 "Return a list of values in a multivalued property."
14867 (let* ((value (org-entry-get pom property))
14868 (values (and value (org-split-string value "[ \t]"))))
14869 (mapcar 'org-entry-restore-space values)))
14871 (defun org-entry-put-multivalued-property (pom property &rest values)
14872 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14873 VALUES should be a list of strings. Spaces will be protected."
14874 (org-entry-put pom property
14875 (mapconcat 'org-entry-protect-space values " "))
14876 (let* ((value (org-entry-get pom property))
14877 (values (and value (org-split-string value "[ \t]"))))
14878 (mapcar 'org-entry-restore-space values)))
14880 (defun org-entry-protect-space (s)
14881 "Protect spaces and newline in string S."
14882 (while (string-match " " s)
14883 (setq s (replace-match "%20" t t s)))
14884 (while (string-match "\n" s)
14885 (setq s (replace-match "%0A" t t s)))
14888 (defun org-entry-restore-space (s)
14889 "Restore spaces and newline in string S."
14890 (while (string-match "%20" s)
14891 (setq s (replace-match " " t t s)))
14892 (while (string-match "%0A" s)
14893 (setq s (replace-match "\n" t t s)))
14896 (defvar org-entry-property-inherited-from (make-marker)
14897 "Marker pointing to the entry from where a property was inherited.
14898 Each call to `org-entry-get-with-inheritance' will set this marker to the
14899 location of the entry where the inheritance search matched. If there was
14900 no match, the marker will point nowhere.
14901 Note that also `org-entry-get' calls this function, if the INHERIT flag
14902 is set.")
14904 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14905 "Get PROPERTY of entry or content at point, search higher levels if needed.
14906 The search will stop at the first ancestor which has the property defined.
14907 If the value found is \"nil\", return nil to show that the property
14908 should be considered as undefined (this is the meaning of nil here).
14909 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14910 (move-marker org-entry-property-inherited-from nil)
14911 (let (tmp)
14912 (save-excursion
14913 (save-restriction
14914 (widen)
14915 (catch 'ex
14916 (while t
14917 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14918 (or (ignore-errors (org-back-to-heading t))
14919 (goto-char (point-min)))
14920 (move-marker org-entry-property-inherited-from (point))
14921 (throw 'ex tmp))
14922 (or (ignore-errors (org-up-heading-safe))
14923 (throw 'ex nil))))))
14924 (setq tmp (or tmp
14925 (cdr (assoc property org-file-properties))
14926 (cdr (assoc property org-global-properties))
14927 (cdr (assoc property org-global-properties-fixed))))
14928 (if literal-nil tmp (org-not-nil tmp))))
14930 (defvar org-property-changed-functions nil
14931 "Hook called when the value of a property has changed.
14932 Each hook function should accept two arguments, the name of the property
14933 and the new value.")
14935 (defun org-entry-put (pom property value)
14936 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14937 (org-with-point-at pom
14938 (org-back-to-heading t)
14939 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14940 range)
14941 (cond
14942 ((equal property "TODO")
14943 (when (and (stringp value) (string-match "\\S-" value)
14944 (not (member value org-todo-keywords-1)))
14945 (error "\"%s\" is not a valid TODO state" value))
14946 (if (or (not value)
14947 (not (string-match "\\S-" value)))
14948 (setq value 'none))
14949 (org-todo value)
14950 (org-set-tags nil 'align))
14951 ((equal property "PRIORITY")
14952 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14953 (string-to-char value) ?\ ))
14954 (org-set-tags nil 'align))
14955 ((equal property "CLOCKSUM")
14956 (if (not (re-search-forward
14957 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14958 (error "Cannot find a clock log")
14959 (goto-char (- (match-end 1) 2))
14960 (cond
14961 ((eq value 'earlier) (org-timestamp-down))
14962 ((eq value 'later) (org-timestamp-up)))
14963 (org-clock-sum-current-item)))
14964 ((equal property "SCHEDULED")
14965 (if (re-search-forward org-scheduled-time-regexp end t)
14966 (cond
14967 ((eq value 'earlier) (org-timestamp-change -1 'day))
14968 ((eq value 'later) (org-timestamp-change 1 'day))
14969 (t (call-interactively 'org-schedule)))
14970 (call-interactively 'org-schedule)))
14971 ((equal property "DEADLINE")
14972 (if (re-search-forward org-deadline-time-regexp end t)
14973 (cond
14974 ((eq value 'earlier) (org-timestamp-change -1 'day))
14975 ((eq value 'later) (org-timestamp-change 1 'day))
14976 (t (call-interactively 'org-deadline)))
14977 (call-interactively 'org-deadline)))
14978 ((member property org-special-properties)
14979 (error "The %s property can not yet be set with `org-entry-put'"
14980 property))
14981 (t ; a non-special property
14982 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14983 (setq range (org-get-property-block beg end 'force))
14984 (goto-char (car range))
14985 (if (re-search-forward
14986 (org-re-property-keyword property) (cdr range) t)
14987 (progn
14988 (delete-region (match-beginning 0) (match-end 0))
14989 (goto-char (match-beginning 0)))
14990 (goto-char (cdr range))
14991 (insert "\n")
14992 (backward-char 1)
14993 (org-indent-line))
14994 (insert ":" property ":")
14995 (and value (insert " " value))
14996 (org-indent-line)))))
14997 (run-hook-with-args 'org-property-changed-functions property value)))
14999 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15000 "Get all property keys in the current buffer.
15001 With INCLUDE-SPECIALS, also list the special properties that reflect things
15002 like tags and TODO state.
15003 With INCLUDE-DEFAULTS, also include properties that has special meaning
15004 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15005 and others.
15006 With INCLUDE-COLUMNS, also include property names given in COLUMN
15007 formats in the current buffer."
15008 (let (rtn range cfmt s p)
15009 (save-excursion
15010 (save-restriction
15011 (widen)
15012 (goto-char (point-min))
15013 (while (re-search-forward org-property-start-re nil t)
15014 (setq range (org-get-property-block))
15015 (goto-char (car range))
15016 (while (re-search-forward
15017 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15018 (cdr range) t)
15019 (add-to-list 'rtn (org-match-string-no-properties 1)))
15020 (outline-next-heading))))
15022 (when include-specials
15023 (setq rtn (append org-special-properties rtn)))
15025 (when include-defaults
15026 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15027 (add-to-list 'rtn org-effort-property))
15029 (when include-columns
15030 (save-excursion
15031 (save-restriction
15032 (widen)
15033 (goto-char (point-min))
15034 (while (re-search-forward
15035 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15036 nil t)
15037 (setq cfmt (match-string 2) s 0)
15038 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15039 cfmt s)
15040 (setq s (match-end 0)
15041 p (match-string 1 cfmt))
15042 (unless (or (equal p "ITEM")
15043 (member p org-special-properties))
15044 (add-to-list 'rtn (match-string 1 cfmt))))))))
15046 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15048 (defun org-property-values (key)
15049 "Return a list of all values of property KEY in the current buffer."
15050 (save-excursion
15051 (save-restriction
15052 (widen)
15053 (goto-char (point-min))
15054 (let ((re (org-re-property key))
15055 values)
15056 (while (re-search-forward re nil t)
15057 (add-to-list 'values (org-trim (match-string 1))))
15058 (delete "" values)))))
15060 (defun org-insert-property-drawer ()
15061 "Insert a property drawer into the current entry."
15062 (org-back-to-heading t)
15063 (looking-at org-outline-regexp)
15064 (let ((indent (if org-adapt-indentation
15065 (- (match-end 0) (match-beginning 0))
15067 (beg (point))
15068 (re (concat "^[ \t]*" org-keyword-time-regexp))
15069 end hiddenp)
15070 (outline-next-heading)
15071 (setq end (point))
15072 (goto-char beg)
15073 (while (re-search-forward re end t))
15074 (setq hiddenp (outline-invisible-p))
15075 (end-of-line 1)
15076 (and (equal (char-after) ?\n) (forward-char 1))
15077 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15078 (if (member (match-string 1) '("CLOCK:" ":END:"))
15079 ;; just skip this line
15080 (beginning-of-line 2)
15081 ;; Drawer start, find the end
15082 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15083 (beginning-of-line 1)))
15084 (org-skip-over-state-notes)
15085 (skip-chars-backward " \t\n\r")
15086 (if (eq (char-before) ?*) (forward-char 1))
15087 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15088 (beginning-of-line 0)
15089 (org-indent-to-column indent)
15090 (beginning-of-line 2)
15091 (org-indent-to-column indent)
15092 (beginning-of-line 0)
15093 (if hiddenp
15094 (save-excursion
15095 (org-back-to-heading t)
15096 (hide-entry))
15097 (org-flag-drawer t))))
15099 (defun org-insert-drawer (&optional arg drawer)
15100 "Insert a drawer at point.
15102 Optional argument DRAWER, when non-nil, is a string representing
15103 drawer's name. Otherwise, the user is prompted for a name.
15105 If a region is active, insert the drawer around that region
15106 instead.
15108 Point is left between drawer's boundaries."
15109 (interactive "P")
15110 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15111 "LOGBOOK"))
15112 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15113 ;; internally by Org. They are meant to be inserted
15114 ;; automatically.
15115 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15116 ;; Remove system drawers from list. Note: For some reason,
15117 ;; `org-completing-read' ignores the predicate while
15118 ;; `completing-read' handles it fine.
15119 (drawer (if arg "PROPERTIES"
15120 (or drawer
15121 (completing-read
15122 "Drawer: " org-drawers
15123 (lambda (d) (not (member d system-drawers))))))))
15124 (cond
15125 ;; With C-u, fall back on `org-insert-property-drawer'
15126 (arg (org-insert-property-drawer))
15127 ;; With an active region, insert a drawer at point.
15128 ((not (org-region-active-p))
15129 (progn
15130 (unless (bolp) (insert "\n"))
15131 (insert (format ":%s:\n\n:END:\n" drawer))
15132 (forward-line -2)))
15133 ;; Otherwise, insert the drawer at point
15135 (let ((rbeg (region-beginning))
15136 (rend (copy-marker (region-end))))
15137 (unwind-protect
15138 (progn
15139 (goto-char rbeg)
15140 (beginning-of-line)
15141 (when (save-excursion
15142 (re-search-forward org-outline-regexp-bol rend t))
15143 (error "Drawers cannot contain headlines"))
15144 ;; Position point at the beginning of the first
15145 ;; non-blank line in region. Insert drawer's opening
15146 ;; there, then indent it.
15147 (org-skip-whitespace)
15148 (beginning-of-line)
15149 (insert ":" drawer ":\n")
15150 (forward-line -1)
15151 (indent-for-tab-command)
15152 ;; Move point to the beginning of the first blank line
15153 ;; after the last non-blank line in region. Insert
15154 ;; drawer's closing, then indent it.
15155 (goto-char rend)
15156 (skip-chars-backward " \r\t\n")
15157 (insert "\n:END:")
15158 (deactivate-mark t)
15159 (indent-for-tab-command)
15160 (unless (eolp) (insert "\n")))
15161 ;; Clear marker, whatever the outcome of insertion is.
15162 (set-marker rend nil)))))))
15164 (defvar org-property-set-functions-alist nil
15165 "Property set function alist.
15166 Each entry should have the following format:
15168 (PROPERTY . READ-FUNCTION)
15170 The read function will be called with the same argument as
15171 `org-completing-read'.")
15173 (defun org-set-property-function (property)
15174 "Get the function that should be used to set PROPERTY.
15175 This is computed according to `org-property-set-functions-alist'."
15176 (or (cdr (assoc property org-property-set-functions-alist))
15177 'org-completing-read))
15179 (defun org-read-property-value (property)
15180 "Read PROPERTY value from user."
15181 (let* ((completion-ignore-case t)
15182 (allowed (org-property-get-allowed-values nil property 'table))
15183 (cur (org-entry-get nil property))
15184 (prompt (concat property " value"
15185 (if (and cur (string-match "\\S-" cur))
15186 (concat " [" cur "]") "") ": "))
15187 (set-function (org-set-property-function property))
15188 (val (if allowed
15189 (funcall set-function prompt allowed nil
15190 (not (get-text-property 0 'org-unrestricted
15191 (caar allowed))))
15192 (let (org-completion-use-ido org-completion-use-iswitchb)
15193 (funcall set-function prompt
15194 (mapcar 'list (org-property-values property))
15195 nil nil "" nil cur)))))
15196 (if (equal val "")
15198 val)))
15200 (defvar org-last-set-property nil)
15201 (defvar org-last-set-property-value nil)
15202 (defun org-read-property-name ()
15203 "Read a property name."
15204 (let* ((completion-ignore-case t)
15205 (keys (org-buffer-property-keys nil t t))
15206 (default-prop (or (save-excursion
15207 (save-match-data
15208 (beginning-of-line)
15209 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15210 (null (string= (match-string 1) "END"))
15211 (match-string 1))))
15212 org-last-set-property))
15213 (property (org-icompleting-read
15214 (concat "Property"
15215 (if default-prop (concat " [" default-prop "]") "")
15216 ": ")
15217 (mapcar 'list keys)
15218 nil nil nil nil
15219 default-prop)))
15220 (if (member property keys)
15221 property
15222 (or (cdr (assoc (downcase property)
15223 (mapcar (lambda (x) (cons (downcase x) x))
15224 keys)))
15225 property))))
15227 (defun org-set-property-and-value (use-last)
15228 "Allow to set [PROPERTY]: [value] direction from prompt.
15229 When use-default, don't even ask, just use the last
15230 \"[PROPERTY]: [value]\" string from the history."
15231 (interactive "P")
15232 (let* ((completion-ignore-case t)
15233 (pv (or (and use-last org-last-set-property-value)
15234 (org-completing-read
15235 "Enter a \"[Property]: [value]\" pair: "
15236 nil nil nil nil nil
15237 org-last-set-property-value)))
15238 prop val)
15239 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15240 (setq prop (match-string 1 pv)
15241 val (match-string 2 pv))
15242 (org-set-property prop val))))
15244 (defun org-set-property (property value)
15245 "In the current entry, set PROPERTY to VALUE.
15246 When called interactively, this will prompt for a property name, offering
15247 completion on existing and default properties. And then it will prompt
15248 for a value, offering completion either on allowed values (via an inherited
15249 xxx_ALL property) or on existing values in other instances of this property
15250 in the current file."
15251 (interactive (list nil nil))
15252 (let* ((property (or property (org-read-property-name)))
15253 (value (or value (org-read-property-value property)))
15254 (fn (cdr (assoc property org-properties-postprocess-alist))))
15255 (setq org-last-set-property property)
15256 (setq org-last-set-property-value (concat property ": " value))
15257 ;; Possibly postprocess the inserted value:
15258 (when fn (setq value (funcall fn value)))
15259 (unless (equal (org-entry-get nil property) value)
15260 (org-entry-put nil property value))))
15262 (defun org-delete-property (property)
15263 "In the current entry, delete PROPERTY."
15264 (interactive
15265 (let* ((completion-ignore-case t)
15266 (prop (org-icompleting-read "Property: "
15267 (org-entry-properties nil 'standard))))
15268 (list prop)))
15269 (message "Property %s %s" property
15270 (if (org-entry-delete nil property)
15271 "deleted"
15272 "was not present in the entry")))
15274 (defun org-delete-property-globally (property)
15275 "Remove PROPERTY globally, from all entries."
15276 (interactive
15277 (let* ((completion-ignore-case t)
15278 (prop (org-icompleting-read
15279 "Globally remove property: "
15280 (mapcar 'list (org-buffer-property-keys)))))
15281 (list prop)))
15282 (save-excursion
15283 (save-restriction
15284 (widen)
15285 (goto-char (point-min))
15286 (let ((cnt 0))
15287 (while (re-search-forward
15288 (org-re-property property)
15289 nil t)
15290 (setq cnt (1+ cnt))
15291 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15292 (message "Property \"%s\" removed from %d entries" property cnt)))))
15294 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15296 (defun org-compute-property-at-point ()
15297 "Compute the property at point.
15298 This looks for an enclosing column format, extracts the operator and
15299 then applies it to the property in the column format's scope."
15300 (interactive)
15301 (unless (org-at-property-p)
15302 (error "Not at a property"))
15303 (let ((prop (org-match-string-no-properties 2)))
15304 (org-columns-get-format-and-top-level)
15305 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15306 (error "No operator defined for property %s" prop))
15307 (org-columns-compute prop)))
15309 (defvar org-property-allowed-value-functions nil
15310 "Hook for functions supplying allowed values for a specific property.
15311 The functions must take a single argument, the name of the property, and
15312 return a flat list of allowed values. If \":ETC\" is one of
15313 the values, this means that these values are intended as defaults for
15314 completion, but that other values should be allowed too.
15315 The functions must return nil if they are not responsible for this
15316 property.")
15318 (defun org-property-get-allowed-values (pom property &optional table)
15319 "Get allowed values for the property PROPERTY.
15320 When TABLE is non-nil, return an alist that can directly be used for
15321 completion."
15322 (let (vals)
15323 (cond
15324 ((equal property "TODO")
15325 (setq vals (org-with-point-at pom
15326 (append org-todo-keywords-1 '("")))))
15327 ((equal property "PRIORITY")
15328 (let ((n org-lowest-priority))
15329 (while (>= n org-highest-priority)
15330 (push (char-to-string n) vals)
15331 (setq n (1- n)))))
15332 ((member property org-special-properties))
15333 ((setq vals (run-hook-with-args-until-success
15334 'org-property-allowed-value-functions property)))
15336 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15337 (when (and vals (string-match "\\S-" vals))
15338 (setq vals (car (read-from-string (concat "(" vals ")"))))
15339 (setq vals (mapcar (lambda (x)
15340 (cond ((stringp x) x)
15341 ((numberp x) (number-to-string x))
15342 ((symbolp x) (symbol-name x))
15343 (t "???")))
15344 vals)))))
15345 (when (member ":ETC" vals)
15346 (setq vals (remove ":ETC" vals))
15347 (org-add-props (car vals) '(org-unrestricted t)))
15348 (if table (mapcar 'list vals) vals)))
15350 (defun org-property-previous-allowed-value (&optional previous)
15351 "Switch to the next allowed value for this property."
15352 (interactive)
15353 (org-property-next-allowed-value t))
15355 (defun org-property-next-allowed-value (&optional previous)
15356 "Switch to the next allowed value for this property."
15357 (interactive)
15358 (unless (org-at-property-p)
15359 (error "Not at a property"))
15360 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15361 (key (match-string 2))
15362 (value (match-string 3))
15363 (allowed (or (org-property-get-allowed-values (point) key)
15364 (and (member value '("[ ]" "[-]" "[X]"))
15365 '("[ ]" "[X]"))))
15366 nval)
15367 (unless allowed
15368 (error "Allowed values for this property have not been defined"))
15369 (if previous (setq allowed (reverse allowed)))
15370 (if (member value allowed)
15371 (setq nval (car (cdr (member value allowed)))))
15372 (setq nval (or nval (car allowed)))
15373 (if (equal nval value)
15374 (error "Only one allowed value for this property"))
15375 (org-at-property-p)
15376 (replace-match (concat " :" key ": " nval) t t)
15377 (org-indent-line)
15378 (beginning-of-line 1)
15379 (skip-chars-forward " \t")
15380 (when (equal prop org-effort-property)
15381 (save-excursion
15382 (org-back-to-heading t)
15383 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15384 (run-hook-with-args 'org-property-changed-functions key nval)))
15386 (defun org-find-olp (path &optional this-buffer)
15387 "Return a marker pointing to the entry at outline path OLP.
15388 If anything goes wrong, throw an error.
15389 You can wrap this call to catch the error like this:
15391 (condition-case msg
15392 (org-mobile-locate-entry (match-string 4))
15393 (error (nth 1 msg)))
15395 The return value will then be either a string with the error message,
15396 or a marker if everything is OK.
15398 If THIS-BUFFER is set, the outline path does not contain a file,
15399 only headings."
15400 (let* ((file (if this-buffer buffer-file-name (pop path)))
15401 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15402 (level 1)
15403 (lmin 1)
15404 (lmax 1)
15405 limit re end found pos heading cnt flevel)
15406 (unless buffer (error "File not found :%s" file))
15407 (with-current-buffer buffer
15408 (save-excursion
15409 (save-restriction
15410 (widen)
15411 (setq limit (point-max))
15412 (goto-char (point-min))
15413 (while (setq heading (pop path))
15414 (setq re (format org-complex-heading-regexp-format
15415 (regexp-quote heading)))
15416 (setq cnt 0 pos (point))
15417 (while (re-search-forward re end t)
15418 (setq level (- (match-end 1) (match-beginning 1)))
15419 (if (and (>= level lmin) (<= level lmax))
15420 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15421 (when (= cnt 0) (error "Heading not found on level %d: %s"
15422 lmax heading))
15423 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15424 lmax heading))
15425 (goto-char found)
15426 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15427 (setq end (save-excursion (org-end-of-subtree t t))))
15428 (when (org-at-heading-p)
15429 (point-marker)))))))
15431 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15432 "Find node HEADING in BUFFER.
15433 Return a marker to the heading if it was found, or nil if not.
15434 If POS-ONLY is set, return just the position instead of a marker.
15436 The heading text must match exact, but it may have a TODO keyword,
15437 a priority cookie and tags in the standard locations."
15438 (with-current-buffer (or buffer (current-buffer))
15439 (save-excursion
15440 (save-restriction
15441 (widen)
15442 (goto-char (point-min))
15443 (let (case-fold-search)
15444 (if (re-search-forward
15445 (format org-complex-heading-regexp-format
15446 (regexp-quote heading)) nil t)
15447 (if pos-only
15448 (match-beginning 0)
15449 (move-marker (make-marker) (match-beginning 0)))))))))
15451 (defun org-find-exact-heading-in-directory (heading &optional dir)
15452 "Find Org node headline HEADING in all .org files in directory DIR.
15453 When the target headline is found, return a marker to this location."
15454 (let ((files (directory-files (or dir default-directory)
15455 nil "\\`[^.#].*\\.org\\'"))
15456 file visiting m buffer)
15457 (catch 'found
15458 (while (setq file (pop files))
15459 (message "trying %s" file)
15460 (setq visiting (org-find-base-buffer-visiting file))
15461 (setq buffer (or visiting (find-file-noselect file)))
15462 (setq m (org-find-exact-headline-in-buffer
15463 heading buffer))
15464 (when (and (not m) (not visiting)) (kill-buffer buffer))
15465 (and m (throw 'found m))))))
15467 (defun org-find-entry-with-id (ident)
15468 "Locate the entry that contains the ID property with exact value IDENT.
15469 IDENT can be a string, a symbol or a number, this function will search for
15470 the string representation of it.
15471 Return the position where this entry starts, or nil if there is no such entry."
15472 (interactive "sID: ")
15473 (let ((id (cond
15474 ((stringp ident) ident)
15475 ((symbol-name ident) (symbol-name ident))
15476 ((numberp ident) (number-to-string ident))
15477 (t (error "IDENT %s must be a string, symbol or number" ident))))
15478 (case-fold-search nil))
15479 (save-excursion
15480 (save-restriction
15481 (widen)
15482 (goto-char (point-min))
15483 (when (re-search-forward
15484 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15485 nil t)
15486 (org-back-to-heading t)
15487 (point))))))
15489 ;;;; Timestamps
15491 (defvar org-last-changed-timestamp nil)
15492 (defvar org-last-inserted-timestamp nil
15493 "The last time stamp inserted with `org-insert-time-stamp'.")
15494 (defvar org-time-was-given) ; dynamically scoped parameter
15495 (defvar org-end-time-was-given) ; dynamically scoped parameter
15496 (defvar org-ts-what) ; dynamically scoped parameter
15498 (defun org-time-stamp (arg &optional inactive)
15499 "Prompt for a date/time and insert a time stamp.
15500 If the user specifies a time like HH:MM or if this command is
15501 called with at least one prefix argument, the time stamp contains
15502 the date and the time. Otherwise, only the date is be included.
15504 All parts of a date not specified by the user is filled in from
15505 the current date/time. So if you just press return without
15506 typing anything, the time stamp will represent the current
15507 date/time.
15509 If there is already a timestamp at the cursor, it will be
15510 modified.
15512 With two universal prefix arguments, insert an active timestamp
15513 with the current time without prompting the user."
15514 (interactive "P")
15515 (let* ((ts nil)
15516 (default-time
15517 ;; Default time is either today, or, when entering a range,
15518 ;; the range start.
15519 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15520 (save-excursion
15521 (re-search-backward
15522 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15523 (- (point) 20) t)))
15524 (apply 'encode-time (org-parse-time-string (match-string 1)))
15525 (current-time)))
15526 (default-input (and ts (org-get-compact-tod ts)))
15527 (repeater (save-excursion
15528 (save-match-data
15529 (beginning-of-line)
15530 (when (re-search-forward
15531 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15532 (save-excursion (progn (end-of-line) (point))) t)
15533 (match-string 0)))))
15534 org-time-was-given org-end-time-was-given time)
15535 (cond
15536 ((and (org-at-timestamp-p t)
15537 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15538 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15539 (insert "--")
15540 (setq time (let ((this-command this-command))
15541 (org-read-date arg 'totime nil nil
15542 default-time default-input inactive)))
15543 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15544 ((org-at-timestamp-p t)
15545 (setq time (let ((this-command this-command))
15546 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15547 (when (org-at-timestamp-p t) ; just to get the match data
15548 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15549 (replace-match "")
15550 (setq org-last-changed-timestamp
15551 (org-insert-time-stamp
15552 time (or org-time-was-given arg)
15553 inactive nil nil (list org-end-time-was-given)))
15554 (when repeater (goto-char (1- (point))) (insert " " repeater)
15555 (setq org-last-changed-timestamp
15556 (concat (substring org-last-inserted-timestamp 0 -1)
15557 " " repeater ">"))))
15558 (message "Timestamp updated"))
15559 ((equal arg '(16))
15560 (org-insert-time-stamp (current-time) t))
15562 (setq time (let ((this-command this-command))
15563 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15564 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15565 nil nil (list org-end-time-was-given))))))
15567 ;; FIXME: can we use this for something else, like computing time differences?
15568 (defun org-get-compact-tod (s)
15569 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15570 (let* ((t1 (match-string 1 s))
15571 (h1 (string-to-number (match-string 2 s)))
15572 (m1 (string-to-number (match-string 3 s)))
15573 (t2 (and (match-end 4) (match-string 5 s)))
15574 (h2 (and t2 (string-to-number (match-string 6 s))))
15575 (m2 (and t2 (string-to-number (match-string 7 s))))
15576 dh dm)
15577 (if (not t2)
15579 (setq dh (- h2 h1) dm (- m2 m1))
15580 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15581 (concat t1 "+" (number-to-string dh)
15582 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15584 (defun org-time-stamp-inactive (&optional arg)
15585 "Insert an inactive time stamp.
15586 An inactive time stamp is enclosed in square brackets instead of angle
15587 brackets. It is inactive in the sense that it does not trigger agenda entries,
15588 does not link to the calendar and cannot be changed with the S-cursor keys.
15589 So these are more for recording a certain time/date."
15590 (interactive "P")
15591 (org-time-stamp arg 'inactive))
15593 (defvar org-date-ovl (make-overlay 1 1))
15594 (overlay-put org-date-ovl 'face 'org-date-selected)
15595 (org-detach-overlay org-date-ovl)
15597 (defvar org-ans1) ; dynamically scoped parameter
15598 (defvar org-ans2) ; dynamically scoped parameter
15600 (defvar org-plain-time-of-day-regexp) ; defined below
15602 (defvar org-overriding-default-time nil) ; dynamically scoped
15603 (defvar org-read-date-overlay nil)
15604 (defvar org-dcst nil) ; dynamically scoped
15605 (defvar org-read-date-history nil)
15606 (defvar org-read-date-final-answer nil)
15607 (defvar org-read-date-analyze-futurep nil)
15608 (defvar org-read-date-analyze-forced-year nil)
15609 (defvar org-read-date-inactive)
15611 (defvar org-read-date-minibuffer-local-map
15612 (let ((map (make-sparse-keymap)))
15613 (set-keymap-parent map minibuffer-local-map)
15614 (org-defkey map (kbd ".")
15615 (lambda () (interactive)
15616 (org-eval-in-calendar '(calendar-goto-today))))
15617 (org-defkey map [(meta shift left)]
15618 (lambda () (interactive)
15619 (org-eval-in-calendar '(calendar-backward-month 1))))
15620 (org-defkey map [(meta shift right)]
15621 (lambda () (interactive)
15622 (org-eval-in-calendar '(calendar-forward-month 1))))
15623 (org-defkey map [(meta shift up)]
15624 (lambda () (interactive)
15625 (org-eval-in-calendar '(calendar-backward-year 1))))
15626 (org-defkey map [(meta shift down)]
15627 (lambda () (interactive)
15628 (org-eval-in-calendar '(calendar-forward-year 1))))
15629 (org-defkey map [?\e (shift left)]
15630 (lambda () (interactive)
15631 (org-eval-in-calendar '(calendar-backward-month 1))))
15632 (org-defkey map [?\e (shift right)]
15633 (lambda () (interactive)
15634 (org-eval-in-calendar '(calendar-forward-month 1))))
15635 (org-defkey map [?\e (shift up)]
15636 (lambda () (interactive)
15637 (org-eval-in-calendar '(calendar-backward-year 1))))
15638 (org-defkey map [?\e (shift down)]
15639 (lambda () (interactive)
15640 (org-eval-in-calendar '(calendar-forward-year 1))))
15641 (org-defkey map [(shift up)]
15642 (lambda () (interactive)
15643 (org-eval-in-calendar '(calendar-backward-week 1))))
15644 (org-defkey map [(shift down)]
15645 (lambda () (interactive)
15646 (org-eval-in-calendar '(calendar-forward-week 1))))
15647 (org-defkey map [(shift left)]
15648 (lambda () (interactive)
15649 (org-eval-in-calendar '(calendar-backward-day 1))))
15650 (org-defkey map [(shift right)]
15651 (lambda () (interactive)
15652 (org-eval-in-calendar '(calendar-forward-day 1))))
15653 (org-defkey map "!"
15654 (lambda () (interactive)
15655 (org-eval-in-calendar '(diary-view-entries))
15656 (message "")))
15657 (org-defkey map ">"
15658 (lambda () (interactive)
15659 (org-eval-in-calendar '(scroll-calendar-left 1))))
15660 (org-defkey map "<"
15661 (lambda () (interactive)
15662 (org-eval-in-calendar '(scroll-calendar-right 1))))
15663 (org-defkey map "\C-v"
15664 (lambda () (interactive)
15665 (org-eval-in-calendar
15666 '(calendar-scroll-left-three-months 1))))
15667 (org-defkey map "\M-v"
15668 (lambda () (interactive)
15669 (org-eval-in-calendar
15670 '(calendar-scroll-right-three-months 1))))
15671 map)
15672 "Keymap for minibuffer commands when using `org-read-date'.")
15674 (defun org-read-date (&optional org-with-time to-time from-string prompt
15675 default-time default-input inactive)
15676 "Read a date, possibly a time, and make things smooth for the user.
15677 The prompt will suggest to enter an ISO date, but you can also enter anything
15678 which will at least partially be understood by `parse-time-string'.
15679 Unrecognized parts of the date will default to the current day, month, year,
15680 hour and minute. If this command is called to replace a timestamp at point,
15681 or to enter the second timestamp of a range, the default time is taken
15682 from the existing stamp. Furthermore, the command prefers the future,
15683 so if you are giving a date where the year is not given, and the day-month
15684 combination is already past in the current year, it will assume you
15685 mean next year. For details, see the manual. A few examples:
15687 3-2-5 --> 2003-02-05
15688 feb 15 --> currentyear-02-15
15689 2/15 --> currentyear-02-15
15690 sep 12 9 --> 2009-09-12
15691 12:45 --> today 12:45
15692 22 sept 0:34 --> currentyear-09-22 0:34
15693 12 --> currentyear-currentmonth-12
15694 Fri --> nearest Friday (today or later)
15695 etc.
15697 Furthermore you can specify a relative date by giving, as the *first* thing
15698 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15699 change in days weeks, months, years.
15700 With a single plus or minus, the date is relative to today. With a double
15701 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15702 +4d --> four days from today
15703 +4 --> same as above
15704 +2w --> two weeks from today
15705 ++5 --> five days from default date
15707 The function understands only English month and weekday abbreviations.
15709 While prompting, a calendar is popped up - you can also select the
15710 date with the mouse (button 1). The calendar shows a period of three
15711 months. To scroll it to other months, use the keys `>' and `<'.
15712 If you don't like the calendar, turn it off with
15713 \(setq org-read-date-popup-calendar nil)
15715 With optional argument TO-TIME, the date will immediately be converted
15716 to an internal time.
15717 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15718 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15719 still enter a time, and this function will inform the calling routine
15720 about this change. The calling routine may then choose to change the
15721 format used to insert the time stamp into the buffer to include the time.
15722 With optional argument FROM-STRING, read from this string instead from
15723 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15724 the time/date that is used for everything that is not specified by the
15725 user."
15726 (require 'parse-time)
15727 (let* ((org-time-stamp-rounding-minutes
15728 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15729 (org-dcst org-display-custom-times)
15730 (ct (org-current-time))
15731 (org-def (or org-overriding-default-time default-time ct))
15732 (org-defdecode (decode-time org-def))
15733 (dummy (progn
15734 (when (< (nth 2 org-defdecode) org-extend-today-until)
15735 (setcar (nthcdr 2 org-defdecode) -1)
15736 (setcar (nthcdr 1 org-defdecode) 59)
15737 (setq org-def (apply 'encode-time org-defdecode)
15738 org-defdecode (decode-time org-def)))))
15739 (mouse-autoselect-window nil) ; Don't let the mouse jump
15740 (calendar-frame-setup nil)
15741 (calendar-setup nil)
15742 (calendar-move-hook nil)
15743 (calendar-view-diary-initially-flag nil)
15744 (calendar-view-holidays-initially-flag nil)
15745 (timestr (format-time-string
15746 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15747 (prompt (concat (if prompt (concat prompt " ") "")
15748 (format "Date+time [%s]: " timestr)))
15749 ans (org-ans0 "") org-ans1 org-ans2 final)
15751 (cond
15752 (from-string (setq ans from-string))
15753 (org-read-date-popup-calendar
15754 (save-excursion
15755 (save-window-excursion
15756 (calendar)
15757 (org-eval-in-calendar '(setq cursor-type nil) t)
15758 (unwind-protect
15759 (progn
15760 (calendar-forward-day (- (time-to-days org-def)
15761 (calendar-absolute-from-gregorian
15762 (calendar-current-date))))
15763 (org-eval-in-calendar nil t)
15764 (let* ((old-map (current-local-map))
15765 (map (copy-keymap calendar-mode-map))
15766 (minibuffer-local-map
15767 (copy-keymap org-read-date-minibuffer-local-map)))
15768 (org-defkey map (kbd "RET") 'org-calendar-select)
15769 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15770 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15771 (unwind-protect
15772 (progn
15773 (use-local-map map)
15774 (setq org-read-date-inactive inactive)
15775 (add-hook 'post-command-hook 'org-read-date-display)
15776 (setq org-ans0 (read-string prompt default-input
15777 'org-read-date-history nil))
15778 ;; org-ans0: from prompt
15779 ;; org-ans1: from mouse click
15780 ;; org-ans2: from calendar motion
15781 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15782 (remove-hook 'post-command-hook 'org-read-date-display)
15783 (use-local-map old-map)
15784 (when org-read-date-overlay
15785 (delete-overlay org-read-date-overlay)
15786 (setq org-read-date-overlay nil)))))
15787 (bury-buffer "*Calendar*")))))
15789 (t ; Naked prompt only
15790 (unwind-protect
15791 (setq ans (read-string prompt default-input
15792 'org-read-date-history timestr))
15793 (when org-read-date-overlay
15794 (delete-overlay org-read-date-overlay)
15795 (setq org-read-date-overlay nil)))))
15797 (setq final (org-read-date-analyze ans org-def org-defdecode))
15799 (when org-read-date-analyze-forced-year
15800 (message "Year was forced into %s"
15801 (if org-read-date-force-compatible-dates
15802 "compatible range (1970-2037)"
15803 "range representable on this machine"))
15804 (ding))
15806 ;; One round trip to get rid of 34th of August and stuff like that....
15807 (setq final (decode-time (apply 'encode-time final)))
15809 (setq org-read-date-final-answer ans)
15811 (if to-time
15812 (apply 'encode-time final)
15813 (if (and (boundp 'org-time-was-given) org-time-was-given)
15814 (format "%04d-%02d-%02d %02d:%02d"
15815 (nth 5 final) (nth 4 final) (nth 3 final)
15816 (nth 2 final) (nth 1 final))
15817 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15819 (defvar org-def)
15820 (defvar org-defdecode)
15821 (defvar org-with-time)
15822 (defun org-read-date-display ()
15823 "Display the current date prompt interpretation in the minibuffer."
15824 (when org-read-date-display-live
15825 (when org-read-date-overlay
15826 (delete-overlay org-read-date-overlay))
15827 (when (minibufferp (current-buffer))
15828 (save-excursion
15829 (end-of-line 1)
15830 (while (not (equal (buffer-substring
15831 (max (point-min) (- (point) 4)) (point))
15832 " "))
15833 (insert " ")))
15834 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15835 " " (or org-ans1 org-ans2)))
15836 (org-end-time-was-given nil)
15837 (f (org-read-date-analyze ans org-def org-defdecode))
15838 (fmts (if org-dcst
15839 org-time-stamp-custom-formats
15840 org-time-stamp-formats))
15841 (fmt (if (or org-with-time
15842 (and (boundp 'org-time-was-given) org-time-was-given))
15843 (cdr fmts)
15844 (car fmts)))
15845 (txt (format-time-string fmt (apply 'encode-time f)))
15846 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15847 (txt (concat "=> " txt)))
15848 (when (and org-end-time-was-given
15849 (string-match org-plain-time-of-day-regexp txt))
15850 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15851 org-end-time-was-given
15852 (substring txt (match-end 0)))))
15853 (when org-read-date-analyze-futurep
15854 (setq txt (concat txt " (=>F)")))
15855 (setq org-read-date-overlay
15856 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15857 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15859 (defun org-read-date-analyze (ans org-def org-defdecode)
15860 "Analyze the combined answer of the date prompt."
15861 ;; FIXME: cleanup and comment
15862 (let ((nowdecode (decode-time (current-time)))
15863 delta deltan deltaw deltadef year month day
15864 hour minute second wday pm h2 m2 tl wday1
15865 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15866 (setq org-read-date-analyze-futurep nil
15867 org-read-date-analyze-forced-year nil)
15868 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15869 (setq ans "+0"))
15871 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15872 (setq ans (replace-match "" t t ans)
15873 deltan (car delta)
15874 deltaw (nth 1 delta)
15875 deltadef (nth 2 delta)))
15877 ;; Check if there is an iso week date in there. If yes, store the
15878 ;; info and postpone interpreting it until the rest of the parsing
15879 ;; is done.
15880 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15881 (setq iso-year (if (match-end 1)
15882 (org-small-year-to-year
15883 (string-to-number (match-string 1 ans))))
15884 iso-weekday (if (match-end 3)
15885 (string-to-number (match-string 3 ans)))
15886 iso-week (string-to-number (match-string 2 ans)))
15887 (setq ans (replace-match "" t t ans)))
15889 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15890 (when (string-match
15891 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15892 (setq year (if (match-end 2)
15893 (string-to-number (match-string 2 ans))
15894 (progn (setq kill-year t)
15895 (string-to-number (format-time-string "%Y"))))
15896 month (string-to-number (match-string 3 ans))
15897 day (string-to-number (match-string 4 ans)))
15898 (if (< year 100) (setq year (+ 2000 year)))
15899 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15900 t nil ans)))
15902 ;; Help matching dotted european dates
15903 (when (string-match
15904 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15905 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15906 (setq kill-year t)
15907 (string-to-number (format-time-string "%Y")))
15908 day (string-to-number (match-string 1 ans))
15909 month (string-to-number (match-string 2 ans))
15910 ans (replace-match (format "%04d-%02d-%02d" year month day)
15911 t nil ans)))
15913 ;; Help matching american dates, like 5/30 or 5/30/7
15914 (when (string-match
15915 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15916 (setq year (if (match-end 4)
15917 (string-to-number (match-string 4 ans))
15918 (progn (setq kill-year t)
15919 (string-to-number (format-time-string "%Y"))))
15920 month (string-to-number (match-string 1 ans))
15921 day (string-to-number (match-string 2 ans)))
15922 (if (< year 100) (setq year (+ 2000 year)))
15923 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15924 t nil ans)))
15925 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15926 ;; If there is a time with am/pm, and *no* time without it, we convert
15927 ;; so that matching will be successful.
15928 (loop for i from 1 to 2 do ; twice, for end time as well
15929 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15930 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15931 (setq hour (string-to-number (match-string 1 ans))
15932 minute (if (match-end 3)
15933 (string-to-number (match-string 3 ans))
15935 pm (equal ?p
15936 (string-to-char (downcase (match-string 4 ans)))))
15937 (if (and (= hour 12) (not pm))
15938 (setq hour 0)
15939 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15940 (setq ans (replace-match (format "%02d:%02d" hour minute)
15941 t t ans))))
15943 ;; Check if a time range is given as a duration
15944 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15945 (setq hour (string-to-number (match-string 1 ans))
15946 h2 (+ hour (string-to-number (match-string 3 ans)))
15947 minute (string-to-number (match-string 2 ans))
15948 m2 (+ minute (if (match-end 5) (string-to-number
15949 (match-string 5 ans))0)))
15950 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15951 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15952 t t ans)))
15954 ;; Check if there is a time range
15955 (when (boundp 'org-end-time-was-given)
15956 (setq org-time-was-given nil)
15957 (when (and (string-match org-plain-time-of-day-regexp ans)
15958 (match-end 8))
15959 (setq org-end-time-was-given (match-string 8 ans))
15960 (setq ans (concat (substring ans 0 (match-beginning 7))
15961 (substring ans (match-end 7))))))
15963 (setq tl (parse-time-string ans)
15964 day (or (nth 3 tl) (nth 3 org-defdecode))
15965 month (or (nth 4 tl)
15966 (if (and org-read-date-prefer-future
15967 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15968 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15969 (nth 4 org-defdecode)))
15970 year (or (and (not kill-year) (nth 5 tl))
15971 (if (and org-read-date-prefer-future
15972 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15973 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15974 (nth 5 org-defdecode)))
15975 hour (or (nth 2 tl) (nth 2 org-defdecode))
15976 minute (or (nth 1 tl) (nth 1 org-defdecode))
15977 second (or (nth 0 tl) 0)
15978 wday (nth 6 tl))
15980 (when (and (eq org-read-date-prefer-future 'time)
15981 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15982 (equal day (nth 3 nowdecode))
15983 (equal month (nth 4 nowdecode))
15984 (equal year (nth 5 nowdecode))
15985 (nth 2 tl)
15986 (or (< (nth 2 tl) (nth 2 nowdecode))
15987 (and (= (nth 2 tl) (nth 2 nowdecode))
15988 (nth 1 tl)
15989 (< (nth 1 tl) (nth 1 nowdecode)))))
15990 (setq day (1+ day)
15991 futurep t))
15993 ;; Special date definitions below
15994 (cond
15995 (iso-week
15996 ;; There was an iso week
15997 (require 'cal-iso)
15998 (setq futurep nil)
15999 (setq year (or iso-year year)
16000 day (or iso-weekday wday 1)
16001 wday nil ; to make sure that the trigger below does not match
16002 iso-date (calendar-gregorian-from-absolute
16003 (calendar-absolute-from-iso
16004 (list iso-week day year))))
16005 ; FIXME: Should we also push ISO weeks into the future?
16006 ; (when (and org-read-date-prefer-future
16007 ; (not iso-year)
16008 ; (< (calendar-absolute-from-gregorian iso-date)
16009 ; (time-to-days (current-time))))
16010 ; (setq year (1+ year)
16011 ; iso-date (calendar-gregorian-from-absolute
16012 ; (calendar-absolute-from-iso
16013 ; (list iso-week day year)))))
16014 (setq month (car iso-date)
16015 year (nth 2 iso-date)
16016 day (nth 1 iso-date)))
16017 (deltan
16018 (setq futurep nil)
16019 (unless deltadef
16020 (let ((now (decode-time (current-time))))
16021 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16022 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16023 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16024 ((equal deltaw "m") (setq month (+ month deltan)))
16025 ((equal deltaw "y") (setq year (+ year deltan)))))
16026 ((and wday (not (nth 3 tl)))
16027 ;; Weekday was given, but no day, so pick that day in the week
16028 ;; on or after the derived date.
16029 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16030 (unless (equal wday wday1)
16031 (setq day (+ day (% (- wday wday1 -7) 7))))))
16032 (if (and (boundp 'org-time-was-given)
16033 (nth 2 tl))
16034 (setq org-time-was-given t))
16035 (if (< year 100) (setq year (+ 2000 year)))
16036 ;; Check of the date is representable
16037 (if org-read-date-force-compatible-dates
16038 (progn
16039 (if (< year 1970)
16040 (setq year 1970 org-read-date-analyze-forced-year t))
16041 (if (> year 2037)
16042 (setq year 2037 org-read-date-analyze-forced-year t)))
16043 (condition-case nil
16044 (ignore (encode-time second minute hour day month year))
16045 (error
16046 (setq year (nth 5 org-defdecode))
16047 (setq org-read-date-analyze-forced-year t))))
16048 (setq org-read-date-analyze-futurep futurep)
16049 (list second minute hour day month year)))
16051 (defvar parse-time-weekdays)
16052 (defun org-read-date-get-relative (s today default)
16053 "Check string S for special relative date string.
16054 TODAY and DEFAULT are internal times, for today and for a default.
16055 Return shift list (N what def-flag)
16056 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16057 N is the number of WHATs to shift.
16058 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16059 the DEFAULT date rather than TODAY."
16060 (require 'parse-time)
16061 (when (and
16062 (string-match
16063 (concat
16064 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16065 "\\([0-9]+\\)?"
16066 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16067 "\\([ \t]\\|$\\)") s)
16068 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16069 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16070 (string-to-char (substring (match-string 1 s) -1))
16071 ?+))
16072 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16073 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16074 (what (if (match-end 3) (match-string 3 s) "d"))
16075 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16076 (date (if rel default today))
16077 (wday (nth 6 (decode-time date)))
16078 delta)
16079 (if wday1
16080 (progn
16081 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16082 (if (= dir ?-) (setq delta (- delta 7)))
16083 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16084 (list delta "d" rel))
16085 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16087 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16088 "Turn a user-specified date into the internal representation.
16089 The internal representation needed by the calendar is (month day year).
16090 This is a wrapper to handle the brain-dead convention in calendar that
16091 user function argument order change dependent on argument order."
16092 (if (boundp 'calendar-date-style)
16093 (cond
16094 ((eq calendar-date-style 'american)
16095 (list arg1 arg2 arg3))
16096 ((eq calendar-date-style 'european)
16097 (list arg2 arg1 arg3))
16098 ((eq calendar-date-style 'iso)
16099 (list arg2 arg3 arg1)))
16100 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16101 (if (org-bound-and-true-p european-calendar-style)
16102 (list arg2 arg1 arg3)
16103 (list arg1 arg2 arg3)))))
16105 (defun org-eval-in-calendar (form &optional keepdate)
16106 "Eval FORM in the calendar window and return to current window.
16107 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16108 otherwise stick to the current value of `org-ans2'."
16109 (let ((sf (selected-frame))
16110 (sw (selected-window)))
16111 (select-window (get-buffer-window "*Calendar*" t))
16112 (eval form)
16113 (when (and (not keepdate) (calendar-cursor-to-date))
16114 (let* ((date (calendar-cursor-to-date))
16115 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16116 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16117 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16118 (select-window sw)
16119 (org-select-frame-set-input-focus sf)))
16121 (defun org-calendar-select ()
16122 "Return to `org-read-date' with the date currently selected.
16123 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16124 (interactive)
16125 (when (calendar-cursor-to-date)
16126 (let* ((date (calendar-cursor-to-date))
16127 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16128 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16129 (if (active-minibuffer-window) (exit-minibuffer))))
16131 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16132 "Insert a date stamp for the date given by the internal TIME.
16133 WITH-HM means use the stamp format that includes the time of the day.
16134 INACTIVE means use square brackets instead of angular ones, so that the
16135 stamp will not contribute to the agenda.
16136 PRE and POST are optional strings to be inserted before and after the
16137 stamp.
16138 The command returns the inserted time stamp."
16139 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16140 stamp)
16141 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16142 (insert-before-markers (or pre ""))
16143 (when (listp extra)
16144 (setq extra (car extra))
16145 (if (and (stringp extra)
16146 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16147 (setq extra (format "-%02d:%02d"
16148 (string-to-number (match-string 1 extra))
16149 (string-to-number (match-string 2 extra))))
16150 (setq extra nil)))
16151 (when extra
16152 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16153 (insert-before-markers (setq stamp (format-time-string fmt time)))
16154 (insert-before-markers (or post ""))
16155 (setq org-last-inserted-timestamp stamp)))
16157 (defun org-toggle-time-stamp-overlays ()
16158 "Toggle the use of custom time stamp formats."
16159 (interactive)
16160 (setq org-display-custom-times (not org-display-custom-times))
16161 (unless org-display-custom-times
16162 (let ((p (point-min)) (bmp (buffer-modified-p)))
16163 (while (setq p (next-single-property-change p 'display))
16164 (if (and (get-text-property p 'display)
16165 (eq (get-text-property p 'face) 'org-date))
16166 (remove-text-properties
16167 p (setq p (next-single-property-change p 'display))
16168 '(display t))))
16169 (set-buffer-modified-p bmp)))
16170 (if (featurep 'xemacs)
16171 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16172 (org-restart-font-lock)
16173 (setq org-table-may-need-update t)
16174 (if org-display-custom-times
16175 (message "Time stamps are overlaid with custom format")
16176 (message "Time stamp overlays removed")))
16178 (defun org-display-custom-time (beg end)
16179 "Overlay modified time stamp format over timestamp between BEG and END."
16180 (let* ((ts (buffer-substring beg end))
16181 t1 w1 with-hm tf time str w2 (off 0))
16182 (save-match-data
16183 (setq t1 (org-parse-time-string ts t))
16184 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16185 (setq off (- (match-end 0) (match-beginning 0)))))
16186 (setq end (- end off))
16187 (setq w1 (- end beg)
16188 with-hm (and (nth 1 t1) (nth 2 t1))
16189 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16190 time (org-fix-decoded-time t1)
16191 str (org-add-props
16192 (format-time-string
16193 (substring tf 1 -1) (apply 'encode-time time))
16194 nil 'mouse-face 'highlight)
16195 w2 (length str))
16196 (if (not (= w2 w1))
16197 (add-text-properties (1+ beg) (+ 2 beg)
16198 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16199 (if (featurep 'xemacs)
16200 (progn
16201 (put-text-property beg end 'invisible t)
16202 (put-text-property beg end 'end-glyph (make-glyph str)))
16203 (put-text-property beg end 'display str))))
16205 (defun org-translate-time (string)
16206 "Translate all timestamps in STRING to custom format.
16207 But do this only if the variable `org-display-custom-times' is set."
16208 (when org-display-custom-times
16209 (save-match-data
16210 (let* ((start 0)
16211 (re org-ts-regexp-both)
16212 t1 with-hm inactive tf time str beg end)
16213 (while (setq start (string-match re string start))
16214 (setq beg (match-beginning 0)
16215 end (match-end 0)
16216 t1 (save-match-data
16217 (org-parse-time-string (substring string beg end) t))
16218 with-hm (and (nth 1 t1) (nth 2 t1))
16219 inactive (equal (substring string beg (1+ beg)) "[")
16220 tf (funcall (if with-hm 'cdr 'car)
16221 org-time-stamp-custom-formats)
16222 time (org-fix-decoded-time t1)
16223 str (format-time-string
16224 (concat
16225 (if inactive "[" "<") (substring tf 1 -1)
16226 (if inactive "]" ">"))
16227 (apply 'encode-time time))
16228 string (replace-match str t t string)
16229 start (+ start (length str)))))))
16230 string)
16232 (defun org-fix-decoded-time (time)
16233 "Set 0 instead of nil for the first 6 elements of time.
16234 Don't touch the rest."
16235 (let ((n 0))
16236 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16238 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16240 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16241 "Difference between TIMESTAMP-STRING and now in days.
16242 If SECONDS is non-nil, return the difference in seconds."
16243 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16244 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16245 (funcall fdiff (current-time)))))
16247 (defun org-deadline-close (timestamp-string &optional ndays)
16248 "Is the time in TIMESTAMP-STRING close to the current date?"
16249 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16250 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16251 (not (org-entry-is-done-p))))
16253 (defun org-get-wdays (ts &optional delay zero-delay)
16254 "Get the deadline lead time appropriate for timestring TS.
16255 When DELAY is non-nil, get the delay time for scheduled items
16256 instead of the deadline lead time. When ZERO-DELAY is non-nil
16257 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16258 don't try to find the delay cookie in the scheduled timestamp."
16259 (let ((tv (if delay org-scheduled-delay-days
16260 org-deadline-warning-days)))
16261 (cond
16262 ((or (and delay (< tv 0))
16263 (and delay zero-delay (<= tv 0))
16264 (and (not delay) (<= tv 0)))
16265 ;; Enforce this value no matter what
16266 (- tv))
16267 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16268 ;; lead time is specified.
16269 (floor (* (string-to-number (match-string 1 ts))
16270 (cdr (assoc (match-string 2 ts)
16271 '(("d" . 1) ("w" . 7)
16272 ("m" . 30.4) ("y" . 365.25)
16273 ("h" . 0.041667)))))))
16274 ;; go for the default.
16275 (t tv))))
16277 (defun org-calendar-select-mouse (ev)
16278 "Return to `org-read-date' with the date currently selected.
16279 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16280 (interactive "e")
16281 (mouse-set-point ev)
16282 (when (calendar-cursor-to-date)
16283 (let* ((date (calendar-cursor-to-date))
16284 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16285 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16286 (if (active-minibuffer-window) (exit-minibuffer))))
16288 (defun org-check-deadlines (ndays)
16289 "Check if there are any deadlines due or past due.
16290 A deadline is considered due if it happens within `org-deadline-warning-days'
16291 days from today's date. If the deadline appears in an entry marked DONE,
16292 it is not shown. The prefix arg NDAYS can be used to test that many
16293 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16294 (interactive "P")
16295 (let* ((org-warn-days
16296 (cond
16297 ((equal ndays '(4)) 100000)
16298 (ndays (prefix-numeric-value ndays))
16299 (t (abs org-deadline-warning-days))))
16300 (case-fold-search nil)
16301 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16302 (callback
16303 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16305 (message "%d deadlines past-due or due within %d days"
16306 (org-occur regexp nil callback)
16307 org-warn-days)))
16309 (defsubst org-re-timestamp (type)
16310 "Return a regexp for timestamp TYPE.
16311 Allowed values for TYPE are:
16313 all: all timestamps
16314 active: only active timestamps (<...>)
16315 inactive: only inactive timestamps ([...])
16316 scheduled: only scheduled timestamps
16317 deadline: only deadline timestamps
16319 When TYPE is nil, fall back on returning a regexp that matches
16320 both scheduled and deadline timestamps."
16321 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16322 ((eq type 'active) org-ts-regexp)
16323 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16324 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16325 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16326 ((eq type 'scheduled-or-deadline)
16327 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16329 (defun org-check-before-date (date)
16330 "Check if there are deadlines or scheduled entries before DATE."
16331 (interactive (list (org-read-date)))
16332 (let ((case-fold-search nil)
16333 (regexp (org-re-timestamp org-ts-type))
16334 (callback
16335 (lambda () (time-less-p
16336 (org-time-string-to-time (match-string 1))
16337 (org-time-string-to-time date)))))
16338 (message "%d entries before %s"
16339 (org-occur regexp nil callback) date)))
16341 (defun org-check-after-date (date)
16342 "Check if there are deadlines or scheduled entries after DATE."
16343 (interactive (list (org-read-date)))
16344 (let ((case-fold-search nil)
16345 (regexp (org-re-timestamp org-ts-type))
16346 (callback
16347 (lambda () (not
16348 (time-less-p
16349 (org-time-string-to-time (match-string 1))
16350 (org-time-string-to-time date))))))
16351 (message "%d entries after %s"
16352 (org-occur regexp nil callback) date)))
16354 (defun org-check-dates-range (start-date end-date)
16355 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16356 (interactive (list (org-read-date nil nil nil "Range starts")
16357 (org-read-date nil nil nil "Range end")))
16358 (let ((case-fold-search nil)
16359 (regexp (org-re-timestamp org-ts-type))
16360 (callback
16361 (lambda ()
16362 (let ((match (match-string 1)))
16363 (and
16364 (not (time-less-p
16365 (org-time-string-to-time match)
16366 (org-time-string-to-time start-date)))
16367 (time-less-p
16368 (org-time-string-to-time match)
16369 (org-time-string-to-time end-date)))))))
16370 (message "%d entries between %s and %s"
16371 (org-occur regexp nil callback) start-date end-date)))
16373 (defun org-evaluate-time-range (&optional to-buffer)
16374 "Evaluate a time range by computing the difference between start and end.
16375 Normally the result is just printed in the echo area, but with prefix arg
16376 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16377 If the time range is actually in a table, the result is inserted into the
16378 next column.
16379 For time difference computation, a year is assumed to be exactly 365
16380 days in order to avoid rounding problems."
16381 (interactive "P")
16383 (org-clock-update-time-maybe)
16384 (save-excursion
16385 (unless (org-at-date-range-p t)
16386 (goto-char (point-at-bol))
16387 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16388 (if (not (org-at-date-range-p t))
16389 (error "Not at a time-stamp range, and none found in current line")))
16390 (let* ((ts1 (match-string 1))
16391 (ts2 (match-string 2))
16392 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16393 (match-end (match-end 0))
16394 (time1 (org-time-string-to-time ts1))
16395 (time2 (org-time-string-to-time ts2))
16396 (t1 (org-float-time time1))
16397 (t2 (org-float-time time2))
16398 (diff (abs (- t2 t1)))
16399 (negative (< (- t2 t1) 0))
16400 ;; (ys (floor (* 365 24 60 60)))
16401 (ds (* 24 60 60))
16402 (hs (* 60 60))
16403 (fy "%dy %dd %02d:%02d")
16404 (fy1 "%dy %dd")
16405 (fd "%dd %02d:%02d")
16406 (fd1 "%dd")
16407 (fh "%02d:%02d")
16408 y d h m align)
16409 (if havetime
16410 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16412 d (floor (/ diff ds)) diff (mod diff ds)
16413 h (floor (/ diff hs)) diff (mod diff hs)
16414 m (floor (/ diff 60)))
16415 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16417 d (floor (+ (/ diff ds) 0.5))
16418 h 0 m 0))
16419 (if (not to-buffer)
16420 (message "%s" (org-make-tdiff-string y d h m))
16421 (if (org-at-table-p)
16422 (progn
16423 (goto-char match-end)
16424 (setq align t)
16425 (and (looking-at " *|") (goto-char (match-end 0))))
16426 (goto-char match-end))
16427 (if (looking-at
16428 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16429 (replace-match ""))
16430 (if negative (insert " -"))
16431 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16432 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16433 (insert " " (format fh h m))))
16434 (if align (org-table-align))
16435 (message "Time difference inserted")))))
16437 (defun org-make-tdiff-string (y d h m)
16438 (let ((fmt "")
16439 (l nil))
16440 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16441 l (push y l)))
16442 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16443 l (push d l)))
16444 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16445 l (push h l)))
16446 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16447 l (push m l)))
16448 (apply 'format fmt (nreverse l))))
16450 (defun org-time-string-to-time (s &optional buffer pos)
16451 "Convert a timestamp string into internal time."
16452 (condition-case errdata
16453 (apply 'encode-time (org-parse-time-string s))
16454 (error (error "Bad timestamp `%s'%s\nError was: %s"
16455 s (if (not (and buffer pos))
16457 (format " at %d in buffer `%s'" pos buffer))
16458 (cdr errdata)))))
16460 (defun org-time-string-to-seconds (s)
16461 "Convert a timestamp string to a number of seconds."
16462 (org-float-time (org-time-string-to-time s)))
16464 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16465 "Convert a time stamp to an absolute day number.
16466 If there is a specifier for a cyclic time stamp, get the closest
16467 date to DAYNR.
16468 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16469 The variable date is bound by the calendar when this is called."
16470 (cond
16471 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16472 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16473 daynr
16474 (+ daynr 1000)))
16475 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16476 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16477 (time-to-days (current-time))) (match-string 0 s)
16478 prefer show-all))
16479 (t (time-to-days
16480 (condition-case errdata
16481 (apply 'encode-time (org-parse-time-string s))
16482 (error (error "Bad timestamp `%s'%s\nError was: %s"
16483 s (if (not (and buffer pos))
16485 (format " at %d in buffer `%s'" pos buffer))
16486 (cdr errdata))))))))
16488 (defun org-days-to-iso-week (days)
16489 "Return the iso week number."
16490 (require 'cal-iso)
16491 (car (calendar-iso-from-absolute days)))
16493 (defun org-small-year-to-year (year)
16494 "Convert 2-digit years into 4-digit years.
16495 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16496 The year 2000 cannot be abbreviated. Any year larger than 99
16497 is returned unchanged."
16498 (if (< year 38)
16499 (setq year (+ 2000 year))
16500 (if (< year 100)
16501 (setq year (+ 1900 year))))
16502 year)
16504 (defun org-time-from-absolute (d)
16505 "Return the time corresponding to date D.
16506 D may be an absolute day number, or a calendar-type list (month day year)."
16507 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16508 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16510 (defun org-calendar-holiday ()
16511 "List of holidays, for Diary display in Org-mode."
16512 (require 'holidays)
16513 (let ((hl (funcall
16514 (if (fboundp 'calendar-check-holidays)
16515 'calendar-check-holidays 'check-calendar-holidays) date)))
16516 (if hl (mapconcat 'identity hl "; "))))
16518 (defun org-diary-sexp-entry (sexp entry date)
16519 "Process a SEXP diary ENTRY for DATE."
16520 (require 'diary-lib)
16521 (let ((result (if calendar-debug-sexp
16522 (let ((stack-trace-on-error t))
16523 (eval (car (read-from-string sexp))))
16524 (condition-case nil
16525 (eval (car (read-from-string sexp)))
16526 (error
16527 (beep)
16528 (message "Bad sexp at line %d in %s: %s"
16529 (org-current-line)
16530 (buffer-file-name) sexp)
16531 (sleep-for 2))))))
16532 (cond ((stringp result) (split-string result "; "))
16533 ((and (consp result)
16534 (not (consp (cdr result)))
16535 (stringp (cdr result))) (cdr result))
16536 ((and (consp result)
16537 (stringp (car result))) result)
16538 (result entry))))
16540 (defun org-diary-to-ical-string (frombuf)
16541 "Get iCalendar entries from diary entries in buffer FROMBUF.
16542 This uses the icalendar.el library."
16543 (let* ((tmpdir (if (featurep 'xemacs)
16544 (temp-directory)
16545 temporary-file-directory))
16546 (tmpfile (make-temp-name
16547 (expand-file-name "orgics" tmpdir)))
16548 buf rtn b e)
16549 (with-current-buffer frombuf
16550 (icalendar-export-region (point-min) (point-max) tmpfile)
16551 (setq buf (find-buffer-visiting tmpfile))
16552 (set-buffer buf)
16553 (goto-char (point-min))
16554 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16555 (setq b (match-beginning 0)))
16556 (goto-char (point-max))
16557 (if (re-search-backward "^END:VEVENT" nil t)
16558 (setq e (match-end 0)))
16559 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16560 (kill-buffer buf)
16561 (delete-file tmpfile)
16562 rtn))
16564 (defun org-closest-date (start current change prefer show-all)
16565 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16566 When PREFER is `past', return a date that is either CURRENT or past.
16567 When PREFER is `future', return a date that is either CURRENT or future.
16568 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16569 ;; Make the proper lists from the dates
16570 (catch 'exit
16571 (let ((a1 '(("h" . hour)
16572 ("d" . day)
16573 ("w" . week)
16574 ("m" . month)
16575 ("y" . year)))
16576 (shour (nth 2 (org-parse-time-string start)))
16577 dn dw sday cday n1 n2 n0
16578 d m y y1 y2 date1 date2 nmonths nm ny m2)
16580 (setq start (org-date-to-gregorian start)
16581 current (org-date-to-gregorian
16582 (if show-all
16583 current
16584 (time-to-days (current-time))))
16585 sday (calendar-absolute-from-gregorian start)
16586 cday (calendar-absolute-from-gregorian current))
16588 (if (<= cday sday) (throw 'exit sday))
16590 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16591 (setq dn (string-to-number (match-string 1 change))
16592 dw (cdr (assoc (match-string 2 change) a1)))
16593 (error "Invalid change specifier: %s" change))
16594 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16595 (cond
16596 ((eq dw 'hour)
16597 (let ((missing-hours
16598 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16599 dn)))
16600 (setq n1 (if (zerop missing-hours) cday
16601 (- cday (1+ (floor (/ missing-hours 24)))))
16602 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16603 ((eq dw 'day)
16604 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16605 n2 (+ n1 dn)))
16606 ((eq dw 'year)
16607 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16608 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16609 (setq date1 (list m d y1)
16610 n1 (calendar-absolute-from-gregorian date1)
16611 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16612 n2 (calendar-absolute-from-gregorian date2)))
16613 ((eq dw 'month)
16614 ;; approx number of month between the two dates
16615 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16616 ;; How often does dn fit in there?
16617 (setq d (nth 1 start) m (car start) y (nth 2 start)
16618 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16619 m (+ m nm)
16620 ny (floor (/ m 12))
16621 y (+ y ny)
16622 m (- m (* ny 12)))
16623 (while (> m 12) (setq m (- m 12) y (1+ y)))
16624 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16625 (setq m2 (+ m dn) y2 y)
16626 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16627 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16628 (while (<= n2 cday)
16629 (setq n1 n2 m m2 y y2)
16630 (setq m2 (+ m dn) y2 y)
16631 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16632 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16633 ;; Make sure n1 is the earlier date
16634 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16635 (if show-all
16636 (cond
16637 ((eq prefer 'past) (if (= cday n2) n2 n1))
16638 ((eq prefer 'future) (if (= cday n1) n1 n2))
16639 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16640 (cond
16641 ((eq prefer 'past) (if (= cday n2) n2 n1))
16642 ((eq prefer 'future) (if (= cday n1) n1 n2))
16643 (t (if (= cday n1) n1 n2)))))))
16645 (defun org-date-to-gregorian (date)
16646 "Turn any specification of DATE into a Gregorian date for the calendar."
16647 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16648 ((and (listp date) (= (length date) 3)) date)
16649 ((stringp date)
16650 (setq date (org-parse-time-string date))
16651 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16652 ((listp date)
16653 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16655 (defun org-parse-time-string (s &optional nodefault)
16656 "Parse the standard Org-mode time string.
16657 This should be a lot faster than the normal `parse-time-string'.
16658 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16659 hour and minute fields will be nil if not given."
16660 (cond ((string-match org-ts-regexp0 s)
16661 (list 0
16662 (if (or (match-beginning 8) (not nodefault))
16663 (string-to-number (or (match-string 8 s) "0")))
16664 (if (or (match-beginning 7) (not nodefault))
16665 (string-to-number (or (match-string 7 s) "0")))
16666 (string-to-number (match-string 4 s))
16667 (string-to-number (match-string 3 s))
16668 (string-to-number (match-string 2 s))
16669 nil nil nil))
16670 ((string-match "^<[^>]+>$" s)
16671 (decode-time (seconds-to-time (org-matcher-time s))))
16672 (t (error "Not a standard Org-mode time string: %s" s))))
16674 (defun org-timestamp-up (&optional arg)
16675 "Increase the date item at the cursor by one.
16676 If the cursor is on the year, change the year. If it is on the month,
16677 the day or the time, change that.
16678 With prefix ARG, change by that many units."
16679 (interactive "p")
16680 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16682 (defun org-timestamp-down (&optional arg)
16683 "Decrease the date item at the cursor by one.
16684 If the cursor is on the year, change the year. If it is on the month,
16685 the day or the time, change that.
16686 With prefix ARG, change by that many units."
16687 (interactive "p")
16688 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16690 (defun org-timestamp-up-day (&optional arg)
16691 "Increase the date in the time stamp by one day.
16692 With prefix ARG, change that many days."
16693 (interactive "p")
16694 (if (and (not (org-at-timestamp-p t))
16695 (org-at-heading-p))
16696 (org-todo 'up)
16697 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16699 (defun org-timestamp-down-day (&optional arg)
16700 "Decrease the date in the time stamp by one day.
16701 With prefix ARG, change that many days."
16702 (interactive "p")
16703 (if (and (not (org-at-timestamp-p t))
16704 (org-at-heading-p))
16705 (org-todo 'down)
16706 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16708 (defun org-at-timestamp-p (&optional inactive-ok)
16709 "Determine if the cursor is in or at a timestamp."
16710 (interactive)
16711 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16712 (pos (point))
16713 (ans (or (looking-at tsr)
16714 (save-excursion
16715 (skip-chars-backward "^[<\n\r\t")
16716 (if (> (point) (point-min)) (backward-char 1))
16717 (and (looking-at tsr)
16718 (> (- (match-end 0) pos) -1))))))
16719 (and ans
16720 (boundp 'org-ts-what)
16721 (setq org-ts-what
16722 (cond
16723 ((= pos (match-beginning 0)) 'bracket)
16724 ;; Point is considered to be "on the bracket" whether
16725 ;; it's really on it or right after it.
16726 ((= pos (1- (match-end 0))) 'bracket)
16727 ((= pos (match-end 0)) 'after)
16728 ((org-pos-in-match-range pos 2) 'year)
16729 ((org-pos-in-match-range pos 3) 'month)
16730 ((org-pos-in-match-range pos 7) 'hour)
16731 ((org-pos-in-match-range pos 8) 'minute)
16732 ((or (org-pos-in-match-range pos 4)
16733 (org-pos-in-match-range pos 5)) 'day)
16734 ((and (> pos (or (match-end 8) (match-end 5)))
16735 (< pos (match-end 0)))
16736 (- pos (or (match-end 8) (match-end 5))))
16737 (t 'day))))
16738 ans))
16740 (defun org-toggle-timestamp-type ()
16741 "Toggle the type (<active> or [inactive]) of a time stamp."
16742 (interactive)
16743 (when (org-at-timestamp-p t)
16744 (let ((beg (match-beginning 0)) (end (match-end 0))
16745 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16746 (save-excursion
16747 (goto-char beg)
16748 (while (re-search-forward "[][<>]" end t)
16749 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16750 t t)))
16751 (message "Timestamp is now %sactive"
16752 (if (equal (char-after beg) ?<) "" "in")))))
16754 (defvar org-clock-history) ; defined in org-clock.el
16755 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16756 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16757 "Change the date in the time stamp at point.
16758 The date will be changed by N times WHAT. WHAT can be `day', `month',
16759 `year', `minute', `second'. If WHAT is not given, the cursor position
16760 in the timestamp determines what will be changed.
16761 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16762 (let ((origin (point)) origin-cat
16763 with-hm inactive
16764 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16765 org-ts-what
16766 extra rem
16767 ts time time0 fixnext clrgx)
16768 (if (not (org-at-timestamp-p t))
16769 (error "Not at a timestamp"))
16770 (if (and (not what) (eq org-ts-what 'bracket))
16771 (org-toggle-timestamp-type)
16772 ;; Point isn't on brackets. Remember the part of the time-stamp
16773 ;; the point was in. Indeed, size of time-stamps may change,
16774 ;; but point must be kept in the same category nonetheless.
16775 (setq origin-cat org-ts-what)
16776 (if (and (not what) (not (eq org-ts-what 'day))
16777 org-display-custom-times
16778 (get-text-property (point) 'display)
16779 (not (get-text-property (1- (point)) 'display)))
16780 (setq org-ts-what 'day))
16781 (setq org-ts-what (or what org-ts-what)
16782 inactive (= (char-after (match-beginning 0)) ?\[)
16783 ts (match-string 0))
16784 (replace-match "")
16785 (when (string-match
16786 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16788 (setq extra (match-string 1 ts))
16789 (if suppress-tmp-delay
16790 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16791 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16792 (setq with-hm t))
16793 (setq time0 (org-parse-time-string ts))
16794 (when (and updown
16795 (eq org-ts-what 'minute)
16796 (not current-prefix-arg))
16797 ;; This looks like s-up and s-down. Change by one rounding step.
16798 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16799 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16800 (setcar (cdr time0) (+ (nth 1 time0)
16801 (if (> n 0) (- rem) (- dm rem))))))
16802 (setq time
16803 (encode-time (or (car time0) 0)
16804 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16805 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16806 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16807 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16808 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16809 (nthcdr 6 time0)))
16810 (when (and (member org-ts-what '(hour minute))
16811 extra
16812 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16813 (setq extra (org-modify-ts-extra
16814 extra
16815 (if (eq org-ts-what 'hour) 2 5)
16816 n dm)))
16817 (when (integerp org-ts-what)
16818 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16819 (if (eq what 'calendar)
16820 (let ((cal-date (org-get-date-from-calendar)))
16821 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16822 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16823 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16824 (setcar time0 (or (car time0) 0))
16825 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16826 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16827 (setq time (apply 'encode-time time0))))
16828 ;; Insert the new time-stamp, and ensure point stays in the same
16829 ;; category as before (i.e. not after the last position in that
16830 ;; category).
16831 (let ((pos (point)))
16832 ;; Stay before inserted string. `save-excursion' is of no use.
16833 (setq org-last-changed-timestamp
16834 (org-insert-time-stamp time with-hm inactive nil nil extra))
16835 (goto-char pos))
16836 (save-match-data
16837 (looking-at org-ts-regexp3)
16838 (goto-char (cond
16839 ;; `day' category ends before `hour' if any, or at
16840 ;; the end of the day name.
16841 ((eq origin-cat 'day)
16842 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16843 ((eq origin-cat 'hour) (min (match-end 7) origin))
16844 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16845 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16846 ;; `year' and `month' have both fixed size: point
16847 ;; couldn't have moved into another part.
16848 (t origin))))
16849 ;; Update clock if on a CLOCK line.
16850 (org-clock-update-time-maybe)
16851 ;; Maybe adjust the closest clock in `org-clock-history'
16852 (when org-clock-adjust-closest
16853 (if (not (and (org-at-clock-log-p)
16854 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16855 org-clock-history))))))
16856 (message "No clock to adjust")
16857 (cond ((save-excursion ; fix previous clock?
16858 (re-search-backward org-ts-regexp0 nil t)
16859 (org-looking-back (concat org-clock-string " \\[")))
16860 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16861 ((save-excursion ; fix next clock?
16862 (re-search-backward org-ts-regexp0 nil t)
16863 (looking-at (concat org-ts-regexp0 "\\] =>")))
16864 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16865 (save-window-excursion
16866 ;; Find closest clock to point, adjust the previous/next one in history
16867 (let* ((p (save-excursion (org-back-to-heading t)))
16868 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16869 (clfixnth
16870 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16871 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16872 (if (not clfixpos)
16873 (message "No clock to adjust")
16874 (save-excursion
16875 (org-goto-marker-or-bmk clfixpos)
16876 (org-show-subtree)
16877 (when (re-search-forward clrgx nil t)
16878 (goto-char (match-beginning 1))
16879 (let (org-clock-adjust-closest)
16880 (org-timestamp-change n org-ts-what updown))
16881 (message "Clock adjusted in %s for heading: %s"
16882 (file-name-nondirectory (buffer-file-name))
16883 (org-get-heading t t)))))))))
16884 ;; Try to recenter the calendar window, if any.
16885 (if (and org-calendar-follow-timestamp-change
16886 (get-buffer-window "*Calendar*" t)
16887 (memq org-ts-what '(day month year)))
16888 (org-recenter-calendar (time-to-days time))))))
16890 (defun org-modify-ts-extra (s pos n dm)
16891 "Change the different parts of the lead-time and repeat fields in timestamp."
16892 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16893 ng h m new rem)
16894 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16895 (cond
16896 ((or (org-pos-in-match-range pos 2)
16897 (org-pos-in-match-range pos 3))
16898 (setq m (string-to-number (match-string 3 s))
16899 h (string-to-number (match-string 2 s)))
16900 (if (org-pos-in-match-range pos 2)
16901 (setq h (+ h n))
16902 (setq n (* dm (org-no-warnings (signum n))))
16903 (when (not (= 0 (setq rem (% m dm))))
16904 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16905 (setq m (+ m n)))
16906 (if (< m 0) (setq m (+ m 60) h (1- h)))
16907 (if (> m 59) (setq m (- m 60) h (1+ h)))
16908 (setq h (min 24 (max 0 h)))
16909 (setq ng 1 new (format "-%02d:%02d" h m)))
16910 ((org-pos-in-match-range pos 6)
16911 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16912 ((org-pos-in-match-range pos 5)
16913 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16915 ((org-pos-in-match-range pos 9)
16916 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16917 ((org-pos-in-match-range pos 8)
16918 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16920 (when ng
16921 (setq s (concat
16922 (substring s 0 (match-beginning ng))
16924 (substring s (match-end ng))))))
16927 (defun org-recenter-calendar (date)
16928 "If the calendar is visible, recenter it to DATE."
16929 (let ((cwin (get-buffer-window "*Calendar*" t)))
16930 (when cwin
16931 (let ((calendar-move-hook nil))
16932 (with-selected-window cwin
16933 (calendar-goto-date (if (listp date) date
16934 (calendar-gregorian-from-absolute date))))))))
16936 (defun org-goto-calendar (&optional arg)
16937 "Go to the Emacs calendar at the current date.
16938 If there is a time stamp in the current line, go to that date.
16939 A prefix ARG can be used to force the current date."
16940 (interactive "P")
16941 (let ((tsr org-ts-regexp) diff
16942 (calendar-move-hook nil)
16943 (calendar-view-holidays-initially-flag nil)
16944 (calendar-view-diary-initially-flag nil))
16945 (if (or (org-at-timestamp-p)
16946 (save-excursion
16947 (beginning-of-line 1)
16948 (looking-at (concat ".*" tsr))))
16949 (let ((d1 (time-to-days (current-time)))
16950 (d2 (time-to-days
16951 (org-time-string-to-time (match-string 1)))))
16952 (setq diff (- d2 d1))))
16953 (calendar)
16954 (calendar-goto-today)
16955 (if (and diff (not arg)) (calendar-forward-day diff))))
16957 (defun org-get-date-from-calendar ()
16958 "Return a list (month day year) of date at point in calendar."
16959 (with-current-buffer "*Calendar*"
16960 (save-match-data
16961 (calendar-cursor-to-date))))
16963 (defun org-date-from-calendar ()
16964 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16965 If there is already a time stamp at the cursor position, update it."
16966 (interactive)
16967 (if (org-at-timestamp-p t)
16968 (org-timestamp-change 0 'calendar)
16969 (let ((cal-date (org-get-date-from-calendar)))
16970 (org-insert-time-stamp
16971 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16973 (defcustom org-effort-durations
16974 `(("h" . 60)
16975 ("d" . ,(* 60 8))
16976 ("w" . ,(* 60 8 5))
16977 ("m" . ,(* 60 8 5 4))
16978 ("y" . ,(* 60 8 5 40)))
16979 "Conversion factor to minutes for an effort modifier.
16981 Each entry has the form (MODIFIER . MINUTES).
16983 In an effort string, a number followed by MODIFIER is multiplied
16984 by the specified number of MINUTES to obtain an effort in
16985 minutes.
16987 For example, if the value of this variable is ((\"hours\" . 60)), then an
16988 effort string \"2hours\" is equivalent to 120 minutes."
16989 :group 'org-agenda
16990 :version "24.1"
16991 :type '(alist :key-type (string :tag "Modifier")
16992 :value-type (number :tag "Minutes")))
16994 (defun org-minutes-to-clocksum-string (m)
16995 "Format number of minutes as a clocksum string.
16996 The format is determined by `org-time-clocksum-format',
16997 `org-time-clocksum-use-fractional' and
16998 `org-time-clocksum-fractional-format' and
16999 `org-time-clocksum-use-effort-durations'."
17000 (let ((clocksum "") h d w mo y fmt n)
17001 (setq h (if org-time-clocksum-use-effort-durations
17002 (cdr (assoc "h" org-effort-durations)) 60)
17003 d (if org-time-clocksum-use-effort-durations
17004 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17005 w (if org-time-clocksum-use-effort-durations
17006 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17007 mo (if org-time-clocksum-use-effort-durations
17008 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17009 y (if org-time-clocksum-use-effort-durations
17010 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17011 ;; fractional format
17012 (if org-time-clocksum-use-fractional
17013 (cond
17014 ;; single format string
17015 ((stringp org-time-clocksum-fractional-format)
17016 (format org-time-clocksum-fractional-format (/ m (float h))))
17017 ;; choice of fractional formats for different time units
17018 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17019 (> (/ (truncate m) (* y d h)) 0))
17020 (format fmt (/ m (* y d (float h)))))
17021 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17022 (> (/ (truncate m) (* mo d h)) 0))
17023 (format fmt (/ m (* mo d (float h)))))
17024 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17025 (> (/ (truncate m) (* w d h)) 0))
17026 (format fmt (/ m (* w d (float h)))))
17027 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17028 (> (/ (truncate m) (* d h)) 0))
17029 (format fmt (/ m (* d (float h)))))
17030 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17031 (> (/ (truncate m) h) 0))
17032 (format fmt (/ m (float h))))
17033 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17034 (format fmt m))
17035 ;; fall back to smallest time unit with a format
17036 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17037 (format fmt (/ m (float h))))
17038 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17039 (format fmt (/ m (* d (float h)))))
17040 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17041 (format fmt (/ m (* w d (float h)))))
17042 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17043 (format fmt (/ m (* mo d (float h)))))
17044 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17045 (format fmt (/ m (* y d (float h))))))
17046 ;; standard (non-fractional) format, with single format string
17047 (if (stringp org-time-clocksum-format)
17048 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17049 ;; separate formats components
17050 (and (setq fmt (plist-get org-time-clocksum-format :years))
17051 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17052 (plist-get org-time-clocksum-format :require-years))
17053 (setq clocksum (concat clocksum (format fmt n))
17054 m (- m (* n y d h))))
17055 (and (setq fmt (plist-get org-time-clocksum-format :months))
17056 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17057 (plist-get org-time-clocksum-format :require-months))
17058 (setq clocksum (concat clocksum (format fmt n))
17059 m (- m (* n mo d h))))
17060 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17061 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17062 (plist-get org-time-clocksum-format :require-weeks))
17063 (setq clocksum (concat clocksum (format fmt n))
17064 m (- m (* n w d h))))
17065 (and (setq fmt (plist-get org-time-clocksum-format :days))
17066 (or (> (setq n (/ (truncate m) (* d h))) 0)
17067 (plist-get org-time-clocksum-format :require-days))
17068 (setq clocksum (concat clocksum (format fmt n))
17069 m (- m (* n d h))))
17070 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17071 (or (> (setq n (/ (truncate m) h)) 0)
17072 (plist-get org-time-clocksum-format :require-hours))
17073 (setq clocksum (concat clocksum (format fmt n))
17074 m (- m (* n h))))
17075 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17076 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17077 (setq clocksum (concat clocksum (format fmt m))))
17078 ;; return formatted time duration
17079 clocksum))))
17081 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17082 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17083 "Org mode version 8.0")
17085 (defun org-hours-to-clocksum-string (n)
17086 (org-minutes-to-clocksum-string (* n 60)))
17088 (defun org-hh:mm-string-to-minutes (s)
17089 "Convert a string H:MM to a number of minutes.
17090 If the string is just a number, interpret it as minutes.
17091 In fact, the first hh:mm or number in the string will be taken,
17092 there can be extra stuff in the string.
17093 If no number is found, the return value is 0."
17094 (cond
17095 ((integerp s) s)
17096 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17097 (+ (* (string-to-number (match-string 1 s)) 60)
17098 (string-to-number (match-string 2 s))))
17099 ((string-match "\\([0-9]+\\)" s)
17100 (string-to-number (match-string 1 s)))
17101 (t 0)))
17103 (defcustom org-image-actual-width t
17104 "Should we use the actual width of images when inlining them?
17106 When set to `t', always use the image width.
17108 When set to a number, use imagemagick (when available) to set
17109 the image's width to this value.
17111 When set to a number in a list, try to get the width from the
17112 #+ATTR.* keyword if it matches a width specification like
17113 width=\"[0-9]+\", and fall back on that number if none is found.
17115 When set to nil, try to get the width from an #+ATTR.* keyword
17116 and fall back on the original width if none is found.
17118 This requires Emacs >= 24.1, build with imagemagick support."
17119 :group 'org-appearance
17120 :version "24.3"
17121 :type '(choice
17122 (const :tag "Use the image width" t)
17123 (integer :tag "Use a number of pixels")
17124 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17125 (const :tag "Use #+ATTR* or don't resize" nil)))
17127 (defcustom org-agenda-inhibit-startup t
17128 "Inhibit startup when preparing agenda buffers.
17129 When this variable is `t' (the default), the initialization of
17130 the Org agenda buffers is inhibited: e.g. the visibility state
17131 is not set, the tables are not re-aligned, etc."
17132 :type 'boolean
17133 :version "24.3"
17134 :group 'org-agenda)
17136 (defun org-duration-string-to-minutes (s &optional output-to-string)
17137 "Convert a duration string S to minutes.
17139 A bare number is interpreted as minutes, modifiers can be set by
17140 customizing `org-effort-durations' (which see).
17142 Entries containing a colon are interpreted as H:MM by
17143 `org-hh:mm-string-to-minutes'."
17144 (let ((result 0)
17145 (re (concat "\\([0-9.]+\\) *\\("
17146 (regexp-opt (mapcar 'car org-effort-durations))
17147 "\\)")))
17148 (while (string-match re s)
17149 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17150 (string-to-number (match-string 1 s))))
17151 (setq s (replace-match "" nil t s)))
17152 (setq result (floor result))
17153 (incf result (org-hh:mm-string-to-minutes s))
17154 (if output-to-string (number-to-string result) result)))
17156 ;;;; Files
17158 (defun org-save-all-org-buffers ()
17159 "Save all Org-mode buffers without user confirmation."
17160 (interactive)
17161 (message "Saving all Org-mode buffers...")
17162 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17163 (when (featurep 'org-id) (org-id-locations-save))
17164 (message "Saving all Org-mode buffers... done"))
17166 (defun org-revert-all-org-buffers ()
17167 "Revert all Org-mode buffers.
17168 Prompt for confirmation when there are unsaved changes.
17169 Be sure you know what you are doing before letting this function
17170 overwrite your changes.
17172 This function is useful in a setup where one tracks org files
17173 with a version control system, to revert on one machine after pulling
17174 changes from another. I believe the procedure must be like this:
17176 1. M-x org-save-all-org-buffers
17177 2. Pull changes from the other machine, resolve conflicts
17178 3. M-x org-revert-all-org-buffers"
17179 (interactive)
17180 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17181 (error "Abort"))
17182 (save-excursion
17183 (save-window-excursion
17184 (mapc
17185 (lambda (b)
17186 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17187 (with-current-buffer b buffer-file-name))
17188 (org-pop-to-buffer-same-window b)
17189 (revert-buffer t 'no-confirm)))
17190 (buffer-list))
17191 (when (and (featurep 'org-id) org-id-track-globally)
17192 (org-id-locations-load)))))
17194 ;;;; Agenda files
17196 ;;;###autoload
17197 (defun org-switchb (&optional arg)
17198 "Switch between Org buffers.
17199 With one prefix argument, restrict available buffers to files.
17200 With two prefix arguments, restrict available buffers to agenda files.
17202 Defaults to `iswitchb' for buffer name completion.
17203 Set `org-completion-use-ido' to make it use ido instead."
17204 (interactive "P")
17205 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17206 ((equal arg '(16)) (org-buffer-list 'agenda))
17207 (t (org-buffer-list))))
17208 (org-completion-use-iswitchb org-completion-use-iswitchb)
17209 (org-completion-use-ido org-completion-use-ido))
17210 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17211 (setq org-completion-use-iswitchb t))
17212 (org-pop-to-buffer-same-window
17213 (org-icompleting-read "Org buffer: "
17214 (mapcar 'list (mapcar 'buffer-name blist))
17215 nil t))))
17217 ;;; Define some older names previously used for this functionality
17218 ;;;###autoload
17219 (defalias 'org-ido-switchb 'org-switchb)
17220 ;;;###autoload
17221 (defalias 'org-iswitchb 'org-switchb)
17223 (defun org-buffer-list (&optional predicate exclude-tmp)
17224 "Return a list of Org buffers.
17225 PREDICATE can be `export', `files' or `agenda'.
17227 export restrict the list to Export buffers.
17228 files restrict the list to buffers visiting Org files.
17229 agenda restrict the list to buffers visiting agenda files.
17231 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17232 (let* ((bfn nil)
17233 (agenda-files (and (eq predicate 'agenda)
17234 (mapcar 'file-truename (org-agenda-files t))))
17235 (filter
17236 (cond
17237 ((eq predicate 'files)
17238 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17239 ((eq predicate 'export)
17240 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17241 ((eq predicate 'agenda)
17242 (lambda (b)
17243 (with-current-buffer b
17244 (and (derived-mode-p 'org-mode)
17245 (setq bfn (buffer-file-name b))
17246 (member (file-truename bfn) agenda-files)))))
17247 (t (lambda (b) (with-current-buffer b
17248 (or (derived-mode-p 'org-mode)
17249 (string-match "\*Org .*Export"
17250 (buffer-name b)))))))))
17251 (delq nil
17252 (mapcar
17253 (lambda(b)
17254 (if (and (funcall filter b)
17255 (or (not exclude-tmp)
17256 (not (string-match "tmp" (buffer-name b)))))
17258 nil))
17259 (buffer-list)))))
17261 (defun org-agenda-files (&optional unrestricted archives)
17262 "Get the list of agenda files.
17263 Optional UNRESTRICTED means return the full list even if a restriction
17264 is currently in place.
17265 When ARCHIVES is t, include all archive files that are really being
17266 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17267 `org-agenda-archives-mode' is t."
17268 (let ((files
17269 (cond
17270 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17271 ((stringp org-agenda-files) (org-read-agenda-file-list))
17272 ((listp org-agenda-files) org-agenda-files)
17273 (t (error "Invalid value of `org-agenda-files'")))))
17274 (setq files (apply 'append
17275 (mapcar (lambda (f)
17276 (if (file-directory-p f)
17277 (directory-files
17278 f t org-agenda-file-regexp)
17279 (list f)))
17280 files)))
17281 (when org-agenda-skip-unavailable-files
17282 (setq files (delq nil
17283 (mapcar (function
17284 (lambda (file)
17285 (and (file-readable-p file) file)))
17286 files))))
17287 (when (or (eq archives t)
17288 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17289 (setq files (org-add-archive-files files)))
17290 files))
17292 (defun org-agenda-file-p (&optional file)
17293 "Return non-nil, if FILE is an agenda file.
17294 If FILE is omitted, use the file associated with the current
17295 buffer."
17296 (member (or file (buffer-file-name))
17297 (org-agenda-files t)))
17299 (defun org-edit-agenda-file-list ()
17300 "Edit the list of agenda files.
17301 Depending on setup, this either uses customize to edit the variable
17302 `org-agenda-files', or it visits the file that is holding the list. In the
17303 latter case, the buffer is set up in a way that saving it automatically kills
17304 the buffer and restores the previous window configuration."
17305 (interactive)
17306 (if (stringp org-agenda-files)
17307 (let ((cw (current-window-configuration)))
17308 (find-file org-agenda-files)
17309 (org-set-local 'org-window-configuration cw)
17310 (org-add-hook 'after-save-hook
17311 (lambda ()
17312 (set-window-configuration
17313 (prog1 org-window-configuration
17314 (kill-buffer (current-buffer))))
17315 (org-install-agenda-files-menu)
17316 (message "New agenda file list installed"))
17317 nil 'local)
17318 (message "%s" (substitute-command-keys
17319 "Edit list and finish with \\[save-buffer]")))
17320 (customize-variable 'org-agenda-files)))
17322 (defun org-store-new-agenda-file-list (list)
17323 "Set new value for the agenda file list and save it correctly."
17324 (if (stringp org-agenda-files)
17325 (let ((fe (org-read-agenda-file-list t)) b u)
17326 (while (setq b (find-buffer-visiting org-agenda-files))
17327 (kill-buffer b))
17328 (with-temp-file org-agenda-files
17329 (insert
17330 (mapconcat
17331 (lambda (f) ;; Keep un-expanded entries.
17332 (if (setq u (assoc f fe))
17333 (cdr u)
17335 list "\n")
17336 "\n")))
17337 (let ((org-mode-hook nil) (org-inhibit-startup t)
17338 (org-insert-mode-line-in-empty-file nil))
17339 (setq org-agenda-files list)
17340 (customize-save-variable 'org-agenda-files org-agenda-files))))
17342 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17343 "Read the list of agenda files from a file.
17344 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17345 filenames, used by `org-store-new-agenda-file-list' to write back
17346 un-expanded file names."
17347 (when (file-directory-p org-agenda-files)
17348 (error "`org-agenda-files' cannot be a single directory"))
17349 (when (stringp org-agenda-files)
17350 (with-temp-buffer
17351 (insert-file-contents org-agenda-files)
17352 (mapcar
17353 (lambda (f)
17354 (let ((e (expand-file-name (substitute-in-file-name f)
17355 org-directory)))
17356 (if pair-with-expansion
17357 (cons e f)
17358 e)))
17359 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17361 ;;;###autoload
17362 (defun org-cycle-agenda-files ()
17363 "Cycle through the files in `org-agenda-files'.
17364 If the current buffer visits an agenda file, find the next one in the list.
17365 If the current buffer does not, find the first agenda file."
17366 (interactive)
17367 (let* ((fs (org-agenda-files t))
17368 (files (append fs (list (car fs))))
17369 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17370 file)
17371 (unless files (error "No agenda files"))
17372 (catch 'exit
17373 (while (setq file (pop files))
17374 (if (equal (file-truename file) tcf)
17375 (when (car files)
17376 (find-file (car files))
17377 (throw 'exit t))))
17378 (find-file (car fs)))
17379 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17381 (defun org-agenda-file-to-front (&optional to-end)
17382 "Move/add the current file to the top of the agenda file list.
17383 If the file is not present in the list, it is added to the front. If it is
17384 present, it is moved there. With optional argument TO-END, add/move to the
17385 end of the list."
17386 (interactive "P")
17387 (let ((org-agenda-skip-unavailable-files nil)
17388 (file-alist (mapcar (lambda (x)
17389 (cons (file-truename x) x))
17390 (org-agenda-files t)))
17391 (ctf (file-truename
17392 (or buffer-file-name
17393 (error "Please save the current buffer to a file"))))
17394 x had)
17395 (setq x (assoc ctf file-alist) had x)
17397 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17398 (if to-end
17399 (setq file-alist (append (delq x file-alist) (list x)))
17400 (setq file-alist (cons x (delq x file-alist))))
17401 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17402 (org-install-agenda-files-menu)
17403 (message "File %s to %s of agenda file list"
17404 (if had "moved" "added") (if to-end "end" "front"))))
17406 (defun org-remove-file (&optional file)
17407 "Remove current file from the list of files in variable `org-agenda-files'.
17408 These are the files which are being checked for agenda entries.
17409 Optional argument FILE means use this file instead of the current."
17410 (interactive)
17411 (let* ((org-agenda-skip-unavailable-files nil)
17412 (file (or file buffer-file-name
17413 (error "Current buffer does not visit a file")))
17414 (true-file (file-truename file))
17415 (afile (abbreviate-file-name file))
17416 (files (delq nil (mapcar
17417 (lambda (x)
17418 (if (equal true-file
17419 (file-truename x))
17420 nil x))
17421 (org-agenda-files t)))))
17422 (if (not (= (length files) (length (org-agenda-files t))))
17423 (progn
17424 (org-store-new-agenda-file-list files)
17425 (org-install-agenda-files-menu)
17426 (message "Removed file: %s" afile))
17427 (message "File was not in list: %s (not removed)" afile))))
17429 (defun org-file-menu-entry (file)
17430 (vector file (list 'find-file file) t))
17432 (defun org-check-agenda-file (file)
17433 "Make sure FILE exists. If not, ask user what to do."
17434 (when (not (file-exists-p file))
17435 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17436 (abbreviate-file-name file))
17437 (let ((r (downcase (read-char-exclusive))))
17438 (cond
17439 ((equal r ?r)
17440 (org-remove-file file)
17441 (throw 'nextfile t))
17442 (t (error "Abort"))))))
17444 (defun org-get-agenda-file-buffer (file)
17445 "Get a buffer visiting FILE. If the buffer needs to be created, add
17446 it to the list of buffers which might be released later."
17447 (let ((buf (org-find-base-buffer-visiting file)))
17448 (if buf
17449 buf ; just return it
17450 ;; Make a new buffer and remember it
17451 (setq buf (find-file-noselect file))
17452 (if buf (push buf org-agenda-new-buffers))
17453 buf)))
17455 (defun org-release-buffers (blist)
17456 "Release all buffers in list, asking the user for confirmation when needed.
17457 When a buffer is unmodified, it is just killed. When modified, it is saved
17458 \(if the user agrees) and then killed."
17459 (let (buf file)
17460 (while (setq buf (pop blist))
17461 (setq file (buffer-file-name buf))
17462 (when (and (buffer-modified-p buf)
17463 file
17464 (y-or-n-p (format "Save file %s? " file)))
17465 (with-current-buffer buf (save-buffer)))
17466 (kill-buffer buf))))
17468 (defun org-agenda-prepare-buffers (files)
17469 "Create buffers for all agenda files, protect archived trees and comments."
17470 (interactive)
17471 (let ((pa '(:org-archived t))
17472 (pc '(:org-comment t))
17473 (pall '(:org-archived t :org-comment t))
17474 (inhibit-read-only t)
17475 (org-inhibit-startup org-agenda-inhibit-startup)
17476 (rea (concat ":" org-archive-tag ":"))
17477 file re)
17478 (save-excursion
17479 (save-restriction
17480 (while (setq file (pop files))
17481 (catch 'nextfile
17482 (if (bufferp file)
17483 (set-buffer file)
17484 (org-check-agenda-file file)
17485 (set-buffer (org-get-agenda-file-buffer file)))
17486 (widen)
17487 (org-unmodified
17488 (org-refresh-category-properties)
17489 (org-refresh-properties org-effort-property 'org-effort)
17490 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17491 (setq org-todo-keywords-for-agenda
17492 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17493 (setq org-done-keywords-for-agenda
17494 (append org-done-keywords-for-agenda org-done-keywords))
17495 (setq org-todo-keyword-alist-for-agenda
17496 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17497 (setq org-drawers-for-agenda
17498 (append org-drawers-for-agenda org-drawers))
17499 (setq org-tag-alist-for-agenda
17500 (append org-tag-alist-for-agenda org-tag-alist))
17502 (save-excursion
17503 (remove-text-properties (point-min) (point-max) pall)
17504 (when org-agenda-skip-archived-trees
17505 (goto-char (point-min))
17506 (while (re-search-forward rea nil t)
17507 (if (org-at-heading-p t)
17508 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17509 (goto-char (point-min))
17510 (setq re (format org-heading-keyword-regexp-format
17511 org-comment-string))
17512 (while (re-search-forward re nil t)
17513 (add-text-properties
17514 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17515 (setq org-todo-keywords-for-agenda
17516 (org-uniquify org-todo-keywords-for-agenda))
17517 (setq org-todo-keyword-alist-for-agenda
17518 (org-uniquify org-todo-keyword-alist-for-agenda)
17519 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17523 ;;;; CDLaTeX minor mode
17525 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17526 "Keymap for the minor `org-cdlatex-mode'.")
17528 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17529 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17530 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17531 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17532 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17534 (defvar org-cdlatex-texmathp-advice-is-done nil
17535 "Flag remembering if we have applied the advice to texmathp already.")
17537 (define-minor-mode org-cdlatex-mode
17538 "Toggle the minor `org-cdlatex-mode'.
17539 This mode supports entering LaTeX environment and math in LaTeX fragments
17540 in Org-mode.
17541 \\{org-cdlatex-mode-map}"
17542 nil " OCDL" nil
17543 (when org-cdlatex-mode
17544 (require 'cdlatex)
17545 (run-hooks 'cdlatex-mode-hook)
17546 (cdlatex-compute-tables))
17547 (unless org-cdlatex-texmathp-advice-is-done
17548 (setq org-cdlatex-texmathp-advice-is-done t)
17549 (defadvice texmathp (around org-math-always-on activate)
17550 "Always return t in org-mode buffers.
17551 This is because we want to insert math symbols without dollars even outside
17552 the LaTeX math segments. If Orgmode thinks that point is actually inside
17553 an embedded LaTeX fragment, let texmathp do its job.
17554 \\[org-cdlatex-mode-map]"
17555 (interactive)
17556 (let (p)
17557 (cond
17558 ((not (derived-mode-p 'org-mode)) ad-do-it)
17559 ((eq this-command 'cdlatex-math-symbol)
17560 (setq ad-return-value t
17561 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17563 (let ((p (org-inside-LaTeX-fragment-p)))
17564 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17565 (setq ad-return-value t
17566 texmathp-why '("Org-mode embedded math" . 0))
17567 (if p ad-do-it)))))))))
17569 (defun turn-on-org-cdlatex ()
17570 "Unconditionally turn on `org-cdlatex-mode'."
17571 (org-cdlatex-mode 1))
17573 (defun org-try-cdlatex-tab ()
17574 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17575 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17576 - inside a LaTeX fragment, or
17577 - after the first word in a line, where an abbreviation expansion could
17578 insert a LaTeX environment."
17579 (when org-cdlatex-mode
17580 (cond
17581 ;; Before any word on the line: No expansion possible.
17582 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17583 ;; Just after first word on the line: Expand it. Make sure it
17584 ;; cannot happen on headlines, though.
17585 ((save-excursion
17586 (skip-chars-backward "a-zA-Z0-9*")
17587 (skip-chars-backward " \t")
17588 (and (bolp) (not (org-at-heading-p))))
17589 (cdlatex-tab) t)
17590 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17592 (defun org-cdlatex-underscore-caret (&optional arg)
17593 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17594 Revert to the normal definition outside of these fragments."
17595 (interactive "P")
17596 (if (org-inside-LaTeX-fragment-p)
17597 (call-interactively 'cdlatex-sub-superscript)
17598 (let (org-cdlatex-mode)
17599 (call-interactively (key-binding (vector last-input-event))))))
17601 (defun org-cdlatex-math-modify (&optional arg)
17602 "Execute `cdlatex-math-modify' in LaTeX fragments.
17603 Revert to the normal definition outside of these fragments."
17604 (interactive "P")
17605 (if (org-inside-LaTeX-fragment-p)
17606 (call-interactively 'cdlatex-math-modify)
17607 (let (org-cdlatex-mode)
17608 (call-interactively (key-binding (vector last-input-event))))))
17612 ;;;; LaTeX fragments
17614 (defvar org-latex-regexps
17615 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17616 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17617 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17618 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17619 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17620 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17621 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17622 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17623 "Regular expressions for matching embedded LaTeX.")
17625 (defun org-inside-LaTeX-fragment-p ()
17626 "Test if point is inside a LaTeX fragment.
17627 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17628 sequence appearing also before point.
17629 Even though the matchers for math are configurable, this function assumes
17630 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17631 delimiters are skipped when they have been removed by customization.
17632 The return value is nil, or a cons cell with the delimiter and the
17633 position of this delimiter.
17635 This function does a reasonably good job, but can locally be fooled by
17636 for example currency specifications. For example it will assume being in
17637 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17638 fragments that are properly closed, but during editing, we have to live
17639 with the uncertainty caused by missing closing delimiters. This function
17640 looks only before point, not after."
17641 (catch 'exit
17642 (let ((pos (point))
17643 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17644 (lim (progn
17645 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17646 (point)))
17647 dd-on str (start 0) m re)
17648 (goto-char pos)
17649 (when dodollar
17650 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17651 re (nth 1 (assoc "$" org-latex-regexps)))
17652 (while (string-match re str start)
17653 (cond
17654 ((= (match-end 0) (length str))
17655 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17656 ((= (match-end 0) (- (length str) 5))
17657 (throw 'exit nil))
17658 (t (setq start (match-end 0))))))
17659 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17660 (goto-char pos)
17661 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17662 (and (match-beginning 2) (throw 'exit nil))
17663 ;; count $$
17664 (while (re-search-backward "\\$\\$" lim t)
17665 (setq dd-on (not dd-on)))
17666 (goto-char pos)
17667 (if dd-on (cons "$$" m))))))
17669 (defun org-inside-latex-macro-p ()
17670 "Is point inside a LaTeX macro or its arguments?"
17671 (save-match-data
17672 (org-in-regexp
17673 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17675 (defvar org-latex-fragment-image-overlays nil
17676 "List of overlays carrying the images of latex fragments.")
17677 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17679 (defun org-remove-latex-fragment-image-overlays ()
17680 "Remove all overlays with LaTeX fragment images in current buffer."
17681 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17682 (setq org-latex-fragment-image-overlays nil))
17684 (defun org-preview-latex-fragment (&optional subtree)
17685 "Preview the LaTeX fragment at point, or all locally or globally.
17686 If the cursor is in a LaTeX fragment, create the image and overlay
17687 it over the source code. If there is no fragment at point, display
17688 all fragments in the current text, from one headline to the next. With
17689 prefix SUBTREE, display all fragments in the current subtree. With a
17690 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17691 the cursor is before the first headline,
17692 display all fragments in the buffer.
17693 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17694 (interactive "P")
17695 (unless buffer-file-name
17696 (error "Can't preview LaTeX fragment in a non-file buffer"))
17697 (org-remove-latex-fragment-image-overlays)
17698 (save-excursion
17699 (save-restriction
17700 (let (beg end at msg)
17701 (cond
17702 ((or (equal subtree '(16))
17703 (not (save-excursion
17704 (re-search-backward org-outline-regexp-bol nil t))))
17705 (setq beg (point-min) end (point-max)
17706 msg "Creating images for buffer...%s"))
17707 ((equal subtree '(4))
17708 (org-back-to-heading)
17709 (setq beg (point) end (org-end-of-subtree t)
17710 msg "Creating images for subtree...%s"))
17712 (if (setq at (org-inside-LaTeX-fragment-p))
17713 (goto-char (max (point-min) (- (cdr at) 2)))
17714 (org-back-to-heading))
17715 (setq beg (point) end (progn (outline-next-heading) (point))
17716 msg (if at "Creating image...%s"
17717 "Creating images for entry...%s"))))
17718 (message msg "")
17719 (narrow-to-region beg end)
17720 (goto-char beg)
17721 (org-format-latex
17722 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17723 (file-name-nondirectory
17724 buffer-file-name)))
17725 default-directory 'overlays msg at 'forbuffer
17726 org-latex-create-formula-image-program)
17727 (message msg "done. Use `C-c C-c' to remove images.")))))
17729 (defun org-format-latex (prefix &optional dir overlays msg at
17730 forbuffer processing-type)
17731 "Replace LaTeX fragments with links to an image, and produce images.
17732 Some of the options can be changed using the variable
17733 `org-format-latex-options'."
17734 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17735 (let* ((prefixnodir (file-name-nondirectory prefix))
17736 (absprefix (expand-file-name prefix dir))
17737 (todir (file-name-directory absprefix))
17738 (opt org-format-latex-options)
17739 (optnew org-format-latex-options)
17740 (matchers (plist-get opt :matchers))
17741 (re-list org-latex-regexps)
17742 (cnt 0) txt hash link beg end re e checkdir
17743 string
17744 m n block-type block linkfile movefile ov)
17745 ;; Check the different regular expressions
17746 (while (setq e (pop re-list))
17747 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17748 block (if block-type "\n\n" ""))
17749 (when (member m matchers)
17750 (goto-char (point-min))
17751 (while (re-search-forward re nil t)
17752 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17753 (or (not overlays)
17754 (not (eq (get-char-property (match-beginning n)
17755 'org-overlay-type)
17756 'org-latex-overlay))))
17757 (cond
17758 ((eq processing-type 'verbatim))
17759 ((eq processing-type 'mathjax)
17760 ;; Prepare for MathJax processing.
17761 (setq string (match-string n))
17762 (when (member m '("$" "$1"))
17763 (save-excursion
17764 (delete-region (match-beginning n) (match-end n))
17765 (goto-char (match-beginning n))
17766 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17767 ((or (eq processing-type 'dvipng)
17768 (eq processing-type 'imagemagick))
17769 ;; Process to an image.
17770 (setq txt (match-string n)
17771 beg (match-beginning n) end (match-end n)
17772 cnt (1+ cnt))
17773 (let ((face (face-at-point))
17774 (fg (plist-get opt :foreground))
17775 (bg (plist-get opt :background))
17776 ;; Ensure full list is printed.
17777 print-length print-level)
17778 (when forbuffer
17779 ;; Get the colors from the face at point.
17780 (goto-char beg)
17781 (when (eq fg 'auto)
17782 (setq fg (face-attribute face :foreground nil 'default)))
17783 (when (eq bg 'auto)
17784 (setq bg (face-attribute face :background nil 'default)))
17785 (setq optnew (copy-sequence opt))
17786 (plist-put optnew :foreground fg)
17787 (plist-put optnew :background bg))
17788 (setq hash (sha1 (prin1-to-string
17789 (list org-format-latex-header
17790 org-latex-default-packages-alist
17791 org-latex-packages-alist
17792 org-format-latex-options
17793 forbuffer txt fg bg)))
17794 linkfile (format "%s_%s.png" prefix hash)
17795 movefile (format "%s_%s.png" absprefix hash)))
17796 (setq link (concat block "[[file:" linkfile "]]" block))
17797 (if msg (message msg cnt))
17798 (goto-char beg)
17799 (unless checkdir ; Ensure the directory exists.
17800 (setq checkdir t)
17801 (or (file-directory-p todir) (make-directory todir t)))
17802 (unless (file-exists-p movefile)
17803 (org-create-formula-image
17804 txt movefile optnew forbuffer processing-type))
17805 (if overlays
17806 (progn
17807 (mapc (lambda (o)
17808 (if (eq (overlay-get o 'org-overlay-type)
17809 'org-latex-overlay)
17810 (delete-overlay o)))
17811 (overlays-in beg end))
17812 (setq ov (make-overlay beg end))
17813 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17814 (if (featurep 'xemacs)
17815 (progn
17816 (overlay-put ov 'invisible t)
17817 (overlay-put
17818 ov 'end-glyph
17819 (make-glyph (vector 'png :file movefile))))
17820 (overlay-put
17821 ov 'display
17822 (list 'image :type 'png :file movefile :ascent 'center)))
17823 (push ov org-latex-fragment-image-overlays)
17824 (goto-char end))
17825 (delete-region beg end)
17826 (insert (org-add-props link
17827 (list 'org-latex-src
17828 (replace-regexp-in-string
17829 "\"" "" txt)
17830 'org-latex-src-embed-type
17831 (if block-type 'paragraph 'character))))))
17832 ((eq processing-type 'mathml)
17833 ;; Process to MathML
17834 (unless (save-match-data (org-format-latex-mathml-available-p))
17835 (error "LaTeX to MathML converter not configured"))
17836 (setq txt (match-string n)
17837 beg (match-beginning n) end (match-end n)
17838 cnt (1+ cnt))
17839 (if msg (message msg cnt))
17840 (goto-char beg)
17841 (delete-region beg end)
17842 (insert (org-format-latex-as-mathml
17843 txt block-type prefix dir)))
17845 (error "Unknown conversion type %s for latex fragments"
17846 processing-type)))))))))
17848 (defun org-create-math-formula (latex-frag &optional mathml-file)
17849 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17850 Use `org-latex-to-mathml-convert-command'. If the conversion is
17851 sucessful, return the portion between \"<math...> </math>\"
17852 elements otherwise return nil. When MATHML-FILE is specified,
17853 write the results in to that file. When invoked as an
17854 interactive command, prompt for LATEX-FRAG, with initial value
17855 set to the current active region and echo the results for user
17856 inspection."
17857 (interactive (list (let ((frag (when (org-region-active-p)
17858 (buffer-substring-no-properties
17859 (region-beginning) (region-end)))))
17860 (read-string "LaTeX Fragment: " frag nil frag))))
17861 (unless latex-frag (error "Invalid latex-frag"))
17862 (let* ((tmp-in-file (file-relative-name
17863 (make-temp-name (expand-file-name "ltxmathml-in"))))
17864 (ignore (write-region latex-frag nil tmp-in-file))
17865 (tmp-out-file (file-relative-name
17866 (make-temp-name (expand-file-name "ltxmathml-out"))))
17867 (cmd (format-spec
17868 org-latex-to-mathml-convert-command
17869 `((?j . ,(shell-quote-argument
17870 (expand-file-name org-latex-to-mathml-jar-file)))
17871 (?I . ,(shell-quote-argument tmp-in-file))
17872 (?o . ,(shell-quote-argument tmp-out-file)))))
17873 mathml shell-command-output)
17874 (when (org-called-interactively-p 'any)
17875 (unless (org-format-latex-mathml-available-p)
17876 (error "LaTeX to MathML converter not configured")))
17877 (message "Running %s" cmd)
17878 (setq shell-command-output (shell-command-to-string cmd))
17879 (setq mathml
17880 (when (file-readable-p tmp-out-file)
17881 (with-current-buffer (find-file-noselect tmp-out-file t)
17882 (goto-char (point-min))
17883 (when (re-search-forward
17884 (concat
17885 (regexp-quote
17886 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17887 "\\(.\\|\n\\)*"
17888 (regexp-quote "</math>")) nil t)
17889 (prog1 (match-string 0) (kill-buffer))))))
17890 (cond
17891 (mathml
17892 (setq mathml
17893 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17894 (when mathml-file
17895 (write-region mathml nil mathml-file))
17896 (when (org-called-interactively-p 'any)
17897 (message mathml)))
17898 ((message "LaTeX to MathML conversion failed")
17899 (message shell-command-output)))
17900 (delete-file tmp-in-file)
17901 (when (file-exists-p tmp-out-file)
17902 (delete-file tmp-out-file))
17903 mathml))
17905 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17906 prefix &optional dir)
17907 "Use `org-create-math-formula' but check local cache first."
17908 (let* ((absprefix (expand-file-name prefix dir))
17909 (print-length nil) (print-level nil)
17910 (formula-id (concat
17911 "formula-"
17912 (sha1
17913 (prin1-to-string
17914 (list latex-frag
17915 org-latex-to-mathml-convert-command)))))
17916 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17917 (formula-cache-dir (file-name-directory formula-cache)))
17919 (unless (file-directory-p formula-cache-dir)
17920 (make-directory formula-cache-dir t))
17922 (unless (file-exists-p formula-cache)
17923 (org-create-math-formula latex-frag formula-cache))
17925 (if (file-exists-p formula-cache)
17926 ;; Successful conversion. Return the link to MathML file.
17927 (org-add-props
17928 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17929 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17930 'org-latex-src-embed-type (if latex-frag-type
17931 'paragraph 'character)))
17932 ;; Failed conversion. Return the LaTeX fragment verbatim
17933 latex-frag)))
17935 (defun org-create-formula-image (string tofile options buffer &optional type)
17936 "Create an image from LaTeX source using dvipng or convert.
17937 This function calls either `org-create-formula-image-with-dvipng'
17938 or `org-create-formula-image-with-imagemagick' depending on the
17939 value of `org-latex-create-formula-image-program' or on the value
17940 of the optional TYPE variable.
17942 Note: ultimately these two function should be combined as they
17943 share a good deal of logic."
17944 (org-check-external-command
17945 "latex" "needed to convert LaTeX fragments to images")
17946 (funcall
17947 (case (or type org-latex-create-formula-image-program)
17948 ('dvipng
17949 (org-check-external-command
17950 "dvipng" "needed to convert LaTeX fragments to images")
17951 #'org-create-formula-image-with-dvipng)
17952 ('imagemagick
17953 (org-check-external-command
17954 "convert" "you need to install imagemagick")
17955 #'org-create-formula-image-with-imagemagick)
17956 (t (error
17957 "invalid value of `org-latex-create-formula-image-program'")))
17958 string tofile options buffer))
17960 ;; This function borrows from Ganesh Swami's latex2png.el
17961 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17962 "This calls dvipng."
17963 (let* ((tmpdir (if (featurep 'xemacs)
17964 (temp-directory)
17965 temporary-file-directory))
17966 (texfilebase (make-temp-name
17967 (expand-file-name "orgtex" tmpdir)))
17968 (texfile (concat texfilebase ".tex"))
17969 (dvifile (concat texfilebase ".dvi"))
17970 (pngfile (concat texfilebase ".png"))
17971 (fnh (if (featurep 'xemacs)
17972 (font-height (face-font 'default))
17973 (face-attribute 'default :height nil)))
17974 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17975 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17976 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17977 "Black"))
17978 (bg (or (plist-get options (if buffer :background :html-background))
17979 "Transparent")))
17980 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17981 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17982 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17983 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17984 (with-temp-file texfile
17985 (require 'ox-latex)
17986 (insert (org-latex-guess-inputenc
17987 (org-splice-latex-header
17988 org-format-latex-header
17989 org-latex-default-packages-alist
17990 org-latex-packages-alist t)))
17991 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17992 (let ((dir default-directory))
17993 (condition-case nil
17994 (progn
17995 (cd tmpdir)
17996 (call-process "latex" nil nil nil texfile))
17997 (error nil))
17998 (cd dir))
17999 (if (not (file-exists-p dvifile))
18000 (progn (message "Failed to create dvi file from %s" texfile) nil)
18001 (condition-case nil
18002 (if (featurep 'xemacs)
18003 (call-process "dvipng" nil nil nil
18004 "-fg" fg "-bg" bg
18005 "-T" "tight"
18006 "-o" pngfile
18007 dvifile)
18008 (call-process "dvipng" nil nil nil
18009 "-fg" fg "-bg" bg
18010 "-D" dpi
18011 ;;"-x" scale "-y" scale
18012 "-T" "tight"
18013 "-o" pngfile
18014 dvifile))
18015 (error nil))
18016 (if (not (file-exists-p pngfile))
18017 (if org-format-latex-signal-error
18018 (error "Failed to create png file from %s" texfile)
18019 (message "Failed to create png file from %s" texfile)
18020 nil)
18021 ;; Use the requested file name and clean up
18022 (copy-file pngfile tofile 'replace)
18023 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18024 (if (file-exists-p (concat texfilebase e))
18025 (delete-file (concat texfilebase e))))
18026 pngfile))))
18028 (defvar org-latex-pdf-process) ; From ox-latex.el
18029 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18030 "This calls convert, which is included into imagemagick."
18031 (let* ((tmpdir (if (featurep 'xemacs)
18032 (temp-directory)
18033 temporary-file-directory))
18034 (texfilebase (make-temp-name
18035 (expand-file-name "orgtex" tmpdir)))
18036 (texfile (concat texfilebase ".tex"))
18037 (pdffile (concat texfilebase ".pdf"))
18038 (pngfile (concat texfilebase ".png"))
18039 (fnh (if (featurep 'xemacs)
18040 (font-height (face-font 'default))
18041 (face-attribute 'default :height nil)))
18042 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18043 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18044 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18045 "black"))
18046 (bg (or (plist-get options (if buffer :background :html-background))
18047 "white")))
18048 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18049 (setq fg (org-latex-color-format fg)))
18050 (if (eq bg 'default) (setq bg (org-latex-color :background))
18051 (setq bg (org-latex-color-format
18052 (if (string= bg "Transparent") "white" bg))))
18053 (with-temp-file texfile
18054 (require 'ox-latex)
18055 (insert (org-latex-guess-inputenc
18056 (org-splice-latex-header
18057 org-format-latex-header
18058 org-latex-default-packages-alist
18059 org-latex-packages-alist t)))
18060 (insert "\n\\begin{document}\n"
18061 "\\definecolor{fg}{rgb}{" fg "}\n"
18062 "\\definecolor{bg}{rgb}{" bg "}\n"
18063 "\n\\pagecolor{bg}\n"
18064 "\n{\\color{fg}\n"
18065 string
18066 "\n}\n"
18067 "\n\\end{document}\n"))
18068 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18069 (condition-case nil
18070 (progn
18071 (cd tmpdir)
18072 (setq cmds org-latex-pdf-process)
18073 (while cmds
18074 (setq latex-frags-cmds (pop cmds))
18075 (if (listp latex-frags-cmds)
18076 (setq cmds nil)
18077 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18078 (while latex-frags-cmds
18079 (setq cmd (pop latex-frags-cmds))
18080 (while (string-match "%b" cmd)
18081 (setq cmd (replace-match
18082 (save-match-data
18083 (shell-quote-argument texfile))
18084 t t cmd)))
18085 (while (string-match "%f" cmd)
18086 (setq cmd (replace-match
18087 (save-match-data
18088 (shell-quote-argument
18089 (file-name-nondirectory texfile)))
18090 t t cmd)))
18091 (while (string-match "%o" cmd)
18092 (setq cmd (replace-match
18093 (save-match-data
18094 (shell-quote-argument
18095 (file-name-directory texfile)))
18096 t t cmd)))
18097 (setq cmd (split-string cmd))
18098 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18099 (error nil))
18100 (cd dir))
18101 (if (not (file-exists-p pdffile))
18102 (progn (message "Failed to create pdf file from %s" texfile) nil)
18103 (condition-case nil
18104 (if (featurep 'xemacs)
18105 (call-process "convert" nil nil nil
18106 "-density" "96"
18107 "-trim"
18108 "-antialias"
18109 pdffile
18110 "-quality" "100"
18111 ;; "-sharpen" "0x1.0"
18112 pngfile)
18113 (call-process "convert" nil nil nil
18114 "-density" dpi
18115 "-trim"
18116 "-antialias"
18117 pdffile
18118 "-quality" "100"
18119 ;; "-sharpen" "0x1.0"
18120 pngfile))
18121 (error nil))
18122 (if (not (file-exists-p pngfile))
18123 (if org-format-latex-signal-error
18124 (error "Failed to create png file from %s" texfile)
18125 (message "Failed to create png file from %s" texfile)
18126 nil)
18127 ;; Use the requested file name and clean up
18128 (copy-file pngfile tofile 'replace)
18129 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18130 (if (file-exists-p (concat texfilebase e))
18131 (delete-file (concat texfilebase e))))
18132 pngfile))))
18134 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18135 "Fill a LaTeX header template TPL.
18136 In the template, the following place holders will be recognized:
18138 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18139 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18140 [PACKAGES] \\usepackage statements for PKG
18141 [NO-PACKAGES] do not include PKG
18142 [EXTRA] the string EXTRA
18143 [NO-EXTRA] do not include EXTRA
18145 For backward compatibility, if both the positive and the negative place
18146 holder is missing, the positive one (without the \"NO-\") will be
18147 assumed to be present at the end of the template.
18148 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18149 EXTRA is a string.
18150 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18151 (let (rpl (end ""))
18152 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18153 (setq rpl (if (or (match-end 1) (not def-pkg))
18154 "" (org-latex-packages-to-string def-pkg snippets-p t))
18155 tpl (replace-match rpl t t tpl))
18156 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18158 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18159 (setq rpl (if (or (match-end 1) (not pkg))
18160 "" (org-latex-packages-to-string pkg snippets-p t))
18161 tpl (replace-match rpl t t tpl))
18162 (if pkg (setq end
18163 (concat end "\n"
18164 (org-latex-packages-to-string pkg snippets-p)))))
18166 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18167 (setq rpl (if (or (match-end 1) (not extra))
18168 "" (concat extra "\n"))
18169 tpl (replace-match rpl t t tpl))
18170 (if (and extra (string-match "\\S-" extra))
18171 (setq end (concat end "\n" extra))))
18173 (if (string-match "\\S-" end)
18174 (concat tpl "\n" end)
18175 tpl)))
18177 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18178 "Turn an alist of packages into a string with the \\usepackage macros."
18179 (setq pkg (mapconcat (lambda(p)
18180 (cond
18181 ((stringp p) p)
18182 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18183 (format "%% Package %s omitted" (cadr p)))
18184 ((equal "" (car p))
18185 (format "\\usepackage{%s}" (cadr p)))
18187 (format "\\usepackage[%s]{%s}"
18188 (car p) (cadr p)))))
18190 "\n"))
18191 (if newline (concat pkg "\n") pkg))
18193 (defun org-dvipng-color (attr)
18194 "Return a RGB color specification for dvipng."
18195 (apply 'format "rgb %s %s %s"
18196 (mapcar 'org-normalize-color
18197 (if (featurep 'xemacs)
18198 (color-rgb-components
18199 (face-property 'default
18200 (cond ((eq attr :foreground) 'foreground)
18201 ((eq attr :background) 'background))))
18202 (color-values (face-attribute 'default attr nil))))))
18204 (defun org-dvipng-color-format (color-name)
18205 "Convert COLOR-NAME to a RGB color value for dvipng."
18206 (apply 'format "rgb %s %s %s"
18207 (mapcar 'org-normalize-color
18208 (color-values color-name))))
18210 (defun org-latex-color (attr)
18211 "Return a RGB color for the LaTeX color package."
18212 (apply 'format "%s,%s,%s"
18213 (mapcar 'org-normalize-color
18214 (if (featurep 'xemacs)
18215 (color-rgb-components
18216 (face-property 'default
18217 (cond ((eq attr :foreground) 'foreground)
18218 ((eq attr :background) 'background))))
18219 (color-values (face-attribute 'default attr nil))))))
18221 (defun org-latex-color-format (color-name)
18222 "Convert COLOR-NAME to a RGB color value."
18223 (apply 'format "%s,%s,%s"
18224 (mapcar 'org-normalize-color
18225 (color-values color-name))))
18227 (defun org-normalize-color (value)
18228 "Return string to be used as color value for an RGB component."
18229 (format "%g" (/ value 65535.0)))
18233 ;; Image display
18235 (defvar org-inline-image-overlays nil)
18236 (make-variable-buffer-local 'org-inline-image-overlays)
18238 (defun org-toggle-inline-images (&optional include-linked)
18239 "Toggle the display of inline images.
18240 INCLUDE-LINKED is passed to `org-display-inline-images'."
18241 (interactive "P")
18242 (if org-inline-image-overlays
18243 (progn
18244 (org-remove-inline-images)
18245 (message "Inline image display turned off"))
18246 (org-display-inline-images include-linked)
18247 (if (and (org-called-interactively-p)
18248 org-inline-image-overlays)
18249 (message "%d images displayed inline"
18250 (length org-inline-image-overlays))
18251 (message "No images to display inline"))))
18253 (defun org-redisplay-inline-images ()
18254 "Refresh the display of inline images."
18255 (interactive)
18256 (if (not org-inline-image-overlays)
18257 (org-toggle-inline-images)
18258 (org-toggle-inline-images)
18259 (org-toggle-inline-images)))
18261 (defun org-display-inline-images (&optional include-linked refresh beg end)
18262 "Display inline images.
18263 Normally only links without a description part are inlined, because this
18264 is how it will work for export. When INCLUDE-LINKED is set, also links
18265 with a description part will be inlined. This can be nice for a quick
18266 look at those images, but it does not reflect what exported files will look
18267 like.
18268 When REFRESH is set, refresh existing images between BEG and END.
18269 This will create new image displays only if necessary.
18270 BEG and END default to the buffer boundaries."
18271 (interactive "P")
18272 (unless refresh
18273 (org-remove-inline-images)
18274 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18275 (save-excursion
18276 (save-restriction
18277 (widen)
18278 (setq beg (or beg (point-min)) end (or end (point-max)))
18279 (goto-char beg)
18280 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18281 (substring (org-image-file-name-regexp) 0 -2)
18282 "\\)\\]" (if include-linked "" "\\]")))
18283 old file ov img type attrwidth width)
18284 (while (re-search-forward re end t)
18285 (setq old (get-char-property-and-overlay (match-beginning 1)
18286 'org-image-overlay)
18287 file (expand-file-name
18288 (concat (or (match-string 3) "") (match-string 4))))
18289 (when (image-type-available-p 'imagemagick)
18290 (setq attrwidth (if (or (listp org-image-actual-width)
18291 (null org-image-actual-width))
18292 (save-excursion
18293 (save-match-data
18294 (when (re-search-backward
18295 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18296 (save-excursion
18297 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18298 (string-to-number (match-string 1))))))
18299 width (cond ((eq org-image-actual-width t) nil)
18300 ((null org-image-actual-width) attrwidth)
18301 ((numberp org-image-actual-width)
18302 org-image-actual-width)
18303 ((listp org-image-actual-width)
18304 (or attrwidth (car org-image-actual-width))))
18305 type (if width 'imagemagick)))
18306 (when (file-exists-p file)
18307 (if (and (car-safe old) refresh)
18308 (image-refresh (overlay-get (cdr old) 'display))
18309 (setq img (save-match-data (create-image file type nil :width width)))
18310 (when img
18311 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18312 (overlay-put ov 'display img)
18313 (overlay-put ov 'face 'default)
18314 (overlay-put ov 'org-image-overlay t)
18315 (overlay-put ov 'modification-hooks
18316 (list 'org-display-inline-remove-overlay))
18317 (push ov org-inline-image-overlays)))))))))
18319 (define-obsolete-function-alias
18320 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18322 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18323 "Remove inline-display overlay if a corresponding region is modified."
18324 (let ((inhibit-modification-hooks t))
18325 (when (and ov after)
18326 (delete ov org-inline-image-overlays)
18327 (delete-overlay ov))))
18329 (defun org-remove-inline-images ()
18330 "Remove inline display of images."
18331 (interactive)
18332 (mapc 'delete-overlay org-inline-image-overlays)
18333 (setq org-inline-image-overlays nil))
18335 ;;;; Key bindings
18337 ;; Outline functions from `outline-mode-prefix-map'
18338 ;; that can be remapped in Org:
18339 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18340 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18341 (define-key org-mode-map [remap outline-forward-same-level]
18342 'org-forward-heading-same-level)
18343 (define-key org-mode-map [remap outline-backward-same-level]
18344 'org-backward-heading-same-level)
18345 (define-key org-mode-map [remap show-branches]
18346 'org-kill-note-or-show-branches)
18347 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18348 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18349 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18351 ;; Outline functions from `outline-mode-prefix-map' that can not
18352 ;; be remapped in Org:
18354 ;; - the column "key binding" shows whether the Outline function is still
18355 ;; available in Org mode on the same key that it has been bound to in
18356 ;; Outline mode:
18357 ;; - "overridden": key used for a different functionality in Org mode
18358 ;; - else: key still bound to the same Outline function in Org mode
18360 ;; | Outline function | key binding | Org replacement |
18361 ;; |------------------------------------+-------------+-----------------------|
18362 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18363 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18364 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18365 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18366 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18367 ;; | `show-entry' | overridden | no replacement |
18368 ;; | `show-children' | `C-c C-i' | visibility cycling |
18369 ;; | `show-branches' | `C-c C-k' | still same function |
18370 ;; | `show-subtree' | overridden | visibility cycling |
18371 ;; | `show-all' | overridden | no replacement |
18372 ;; | `hide-subtree' | overridden | visibility cycling |
18373 ;; | `hide-body' | overridden | no replacement |
18374 ;; | `hide-entry' | overridden | visibility cycling |
18375 ;; | `hide-leaves' | overridden | no replacement |
18376 ;; | `hide-sublevels' | overridden | no replacement |
18377 ;; | `hide-other' | overridden | no replacement |
18379 ;; Make `C-c C-x' a prefix key
18380 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18382 ;; TAB key with modifiers
18383 (org-defkey org-mode-map "\C-i" 'org-cycle)
18384 (org-defkey org-mode-map [(tab)] 'org-cycle)
18385 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18386 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18387 ;; The following line is necessary under Suse GNU/Linux
18388 (unless (featurep 'xemacs)
18389 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18390 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18391 (define-key org-mode-map [backtab] 'org-shifttab)
18393 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18394 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18395 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18397 ;; Cursor keys with modifiers
18398 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18399 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18400 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18401 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18403 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18404 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18405 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18406 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18408 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18409 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18410 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18411 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18413 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18414 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18415 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18416 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18418 ;; Babel keys
18419 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18420 (mapc (lambda (pair)
18421 (define-key org-babel-map (car pair) (cdr pair)))
18422 org-babel-key-bindings)
18424 ;;; Extra keys for tty access.
18425 ;; We only set them when really needed because otherwise the
18426 ;; menus don't show the simple keys
18428 (when (or org-use-extra-keys
18429 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18430 (not window-system))
18431 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18432 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18433 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18434 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18435 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18436 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18437 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18438 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18439 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18440 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18441 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18442 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18443 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18444 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18445 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18446 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18447 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18448 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18449 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18450 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18451 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18452 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18453 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18454 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18455 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18456 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18457 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18458 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18460 ;; All the other keys
18462 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18463 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18464 (if (boundp 'narrow-map)
18465 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18466 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18467 (if (boundp 'narrow-map)
18468 (org-defkey narrow-map "b" 'org-narrow-to-block)
18469 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18470 (if (boundp 'narrow-map)
18471 (org-defkey narrow-map "e" 'org-narrow-to-element)
18472 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18473 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18474 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18475 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18476 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18477 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18478 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18479 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18480 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18481 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18482 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18483 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18484 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18485 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18486 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18487 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18488 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18489 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18490 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18491 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18492 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18493 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18494 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18495 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18496 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18497 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18498 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18499 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18500 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18501 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18502 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18503 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18504 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18505 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18506 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18507 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18508 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18509 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18510 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18511 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18512 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18513 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18514 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18515 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18516 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18517 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18518 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18519 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18520 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18521 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18522 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18523 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18524 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18525 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18526 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18527 (org-defkey org-mode-map "\C-c^" 'org-sort)
18528 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18529 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18530 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18531 (org-defkey org-mode-map "\C-m" 'org-return)
18532 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18533 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18534 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18535 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18536 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18537 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18538 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18539 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18540 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18541 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18542 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18543 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18544 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18545 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18546 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18547 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18548 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18549 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18550 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18551 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18552 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18553 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18554 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18556 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18557 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18558 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18560 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18561 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18562 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18563 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18564 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18565 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18566 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18567 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18568 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18569 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18570 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18571 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18572 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18573 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18574 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18575 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18576 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18577 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18578 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18579 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18580 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18581 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18582 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18584 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18585 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18586 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18587 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18588 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18590 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18592 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18594 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18595 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18597 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18600 (when (featurep 'xemacs)
18601 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18604 (defconst org-speed-commands-default
18606 ("Outline Navigation")
18607 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18608 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18609 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18610 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18611 ("F" . org-next-block)
18612 ("B" . org-previous-block)
18613 ("u" . (org-speed-move-safe 'outline-up-heading))
18614 ("j" . org-goto)
18615 ("g" . (org-refile t))
18616 ("Outline Visibility")
18617 ("c" . org-cycle)
18618 ("C" . org-shifttab)
18619 (" " . org-display-outline-path)
18620 ("=" . org-columns)
18621 ("Outline Structure Editing")
18622 ("U" . org-shiftmetaup)
18623 ("D" . org-shiftmetadown)
18624 ("r" . org-metaright)
18625 ("l" . org-metaleft)
18626 ("R" . org-shiftmetaright)
18627 ("L" . org-shiftmetaleft)
18628 ("i" . (progn (forward-char 1) (call-interactively
18629 'org-insert-heading-respect-content)))
18630 ("^" . org-sort)
18631 ("w" . org-refile)
18632 ("a" . org-archive-subtree-default-with-confirmation)
18633 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18634 ("#" . org-toggle-comment)
18635 ("Clock Commands")
18636 ("I" . org-clock-in)
18637 ("O" . org-clock-out)
18638 ("Meta Data Editing")
18639 ("t" . org-todo)
18640 ("," . (org-priority))
18641 ("0" . (org-priority ?\ ))
18642 ("1" . (org-priority ?A))
18643 ("2" . (org-priority ?B))
18644 ("3" . (org-priority ?C))
18645 (":" . org-set-tags-command)
18646 ("e" . org-set-effort)
18647 ("E" . org-inc-effort)
18648 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18649 (org-entry-put (point) "APPT_WARNTIME" m)))
18650 ("Agenda Views etc")
18651 ("v" . org-agenda)
18652 ("/" . org-sparse-tree)
18653 ("Misc")
18654 ("o" . org-open-at-point)
18655 ("?" . org-speed-command-help)
18656 ("<" . (org-agenda-set-restriction-lock 'subtree))
18657 (">" . (org-agenda-remove-restriction-lock))
18659 "The default speed commands.")
18661 (defun org-print-speed-command (e)
18662 (if (> (length (car e)) 1)
18663 (progn
18664 (princ "\n")
18665 (princ (car e))
18666 (princ "\n")
18667 (princ (make-string (length (car e)) ?-))
18668 (princ "\n"))
18669 (princ (car e))
18670 (princ " ")
18671 (if (symbolp (cdr e))
18672 (princ (symbol-name (cdr e)))
18673 (prin1 (cdr e)))
18674 (princ "\n")))
18676 (defun org-speed-command-help ()
18677 "Show the available speed commands."
18678 (interactive)
18679 (if (not org-use-speed-commands)
18680 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18681 (with-output-to-temp-buffer "*Help*"
18682 (princ "User-defined Speed commands\n===========================\n")
18683 (mapc 'org-print-speed-command org-speed-commands-user)
18684 (princ "\n")
18685 (princ "Built-in Speed commands\n=======================\n")
18686 (mapc 'org-print-speed-command org-speed-commands-default))
18687 (with-current-buffer "*Help*"
18688 (setq truncate-lines t))))
18690 (defun org-speed-move-safe (cmd)
18691 "Execute CMD, but make sure that the cursor always ends up in a headline.
18692 If not, return to the original position and throw an error."
18693 (interactive)
18694 (let ((pos (point)))
18695 (call-interactively cmd)
18696 (unless (and (bolp) (org-at-heading-p))
18697 (goto-char pos)
18698 (error "Boundary reached while executing %s" cmd))))
18700 (defvar org-self-insert-command-undo-counter 0)
18702 (defvar org-table-auto-blank-field) ; defined in org-table.el
18703 (defvar org-speed-command nil)
18705 (define-obsolete-function-alias
18706 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18708 (defun org-speed-command-activate (keys)
18709 "Hook for activating single-letter speed commands.
18710 `org-speed-commands-default' specifies a minimal command set.
18711 Use `org-speed-commands-user' for further customization."
18712 (when (or (and (bolp) (looking-at org-outline-regexp))
18713 (and (functionp org-use-speed-commands)
18714 (funcall org-use-speed-commands)))
18715 (cdr (assoc keys (append org-speed-commands-user
18716 org-speed-commands-default)))))
18718 (define-obsolete-function-alias
18719 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18721 (defun org-babel-speed-command-activate (keys)
18722 "Hook for activating single-letter code block commands."
18723 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18724 (cdr (assoc keys org-babel-key-bindings))))
18726 (defcustom org-speed-command-hook
18727 '(org-speed-command-default-hook org-babel-speed-command-hook)
18728 "Hook for activating speed commands at strategic locations.
18729 Hook functions are called in sequence until a valid handler is
18730 found.
18732 Each hook takes a single argument, a user-pressed command key
18733 which is also a `self-insert-command' from the global map.
18735 Within the hook, examine the cursor position and the command key
18736 and return nil or a valid handler as appropriate. Handler could
18737 be one of an interactive command, a function, or a form.
18739 Set `org-use-speed-commands' to non-nil value to enable this
18740 hook. The default setting is `org-speed-command-activate'."
18741 :group 'org-structure
18742 :version "24.1"
18743 :type 'hook)
18745 (defun org-self-insert-command (N)
18746 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18747 If the cursor is in a table looking at whitespace, the whitespace is
18748 overwritten, and the table is not marked as requiring realignment."
18749 (interactive "p")
18750 (org-check-before-invisible-edit 'insert)
18751 (cond
18752 ((and org-use-speed-commands
18753 (setq org-speed-command
18754 (run-hook-with-args-until-success
18755 'org-speed-command-hook (this-command-keys))))
18756 (cond
18757 ((commandp org-speed-command)
18758 (setq this-command org-speed-command)
18759 (call-interactively org-speed-command))
18760 ((functionp org-speed-command)
18761 (funcall org-speed-command))
18762 ((and org-speed-command (listp org-speed-command))
18763 (eval org-speed-command))
18764 (t (let (org-use-speed-commands)
18765 (call-interactively 'org-self-insert-command)))))
18766 ((and
18767 (org-table-p)
18768 (progn
18769 ;; check if we blank the field, and if that triggers align
18770 (and (featurep 'org-table) org-table-auto-blank-field
18771 (member last-command
18772 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18773 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18774 ;; got extra space, this field does not determine column width
18775 (let (org-table-may-need-update) (org-table-blank-field))
18776 ;; no extra space, this field may determine column width
18777 (org-table-blank-field)))
18779 (eq N 1)
18780 (looking-at "[^|\n]* |"))
18781 (let (org-table-may-need-update)
18782 (goto-char (1- (match-end 0)))
18783 (backward-delete-char 1)
18784 (goto-char (match-beginning 0))
18785 (self-insert-command N)))
18787 (setq org-table-may-need-update t)
18788 (self-insert-command N)
18789 (org-fix-tags-on-the-fly)
18790 (if org-self-insert-cluster-for-undo
18791 (if (not (eq last-command 'org-self-insert-command))
18792 (setq org-self-insert-command-undo-counter 1)
18793 (if (>= org-self-insert-command-undo-counter 20)
18794 (setq org-self-insert-command-undo-counter 1)
18795 (and (> org-self-insert-command-undo-counter 0)
18796 buffer-undo-list (listp buffer-undo-list)
18797 (not (cadr buffer-undo-list)) ; remove nil entry
18798 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18799 (setq org-self-insert-command-undo-counter
18800 (1+ org-self-insert-command-undo-counter))))))))
18802 (defun org-check-before-invisible-edit (kind)
18803 "Check is editing if kind KIND would be dangerous with invisible text around.
18804 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18805 ;; First, try to get out of here as quickly as possible, to reduce overhead
18806 (if (and org-catch-invisible-edits
18807 (or (not (boundp 'visible-mode)) (not visible-mode))
18808 (or (get-char-property (point) 'invisible)
18809 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18810 ;; OK, we need to take a closer look
18811 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18812 (invisible-before-point (if (bobp) nil (get-char-property
18813 (1- (point)) 'invisible)))
18814 (border-and-ok-direction
18816 ;; Check if we are acting predictably before invisible text
18817 (and invisible-at-point (not invisible-before-point)
18818 (memq kind '(insert delete-backward)))
18819 ;; Check if we are acting predictably after invisible text
18820 ;; This works not well, and I have turned it off. It seems
18821 ;; better to always show and stop after invisible text.
18822 ;; (and (not invisible-at-point) invisible-before-point
18823 ;; (memq kind '(insert delete)))
18825 (when (or (memq invisible-at-point '(outline org-hide-block t))
18826 (memq invisible-before-point '(outline org-hide-block t)))
18827 (if (eq org-catch-invisible-edits 'error)
18828 (error "Editing in invisible areas is prohibited - make visible first"))
18829 (if (and org-custom-properties-overlays
18830 (y-or-n-p "Display invisible properties in this buffer? "))
18831 (org-toggle-custom-properties-visibility)
18832 ;; Make the area visible
18833 (save-excursion
18834 (if invisible-before-point
18835 (goto-char (previous-single-char-property-change
18836 (point) 'invisible)))
18837 (org-cycle))
18838 (cond
18839 ((eq org-catch-invisible-edits 'show)
18840 ;; That's it, we do the edit after showing
18841 (message
18842 "Unfolding invisible region around point before editing")
18843 (sit-for 1))
18844 ((and (eq org-catch-invisible-edits 'smart)
18845 border-and-ok-direction)
18846 (message "Unfolding invisible region around point before editing"))
18848 ;; Don't do the edit, make the user repeat it in full visibility
18849 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18851 (defun org-fix-tags-on-the-fly ()
18852 (when (and (equal (char-after (point-at-bol)) ?*)
18853 (org-at-heading-p))
18854 (org-align-tags-here org-tags-column)))
18856 (defun org-delete-backward-char (N)
18857 "Like `delete-backward-char', insert whitespace at field end in tables.
18858 When deleting backwards, in tables this function will insert whitespace in
18859 front of the next \"|\" separator, to keep the table aligned. The table will
18860 still be marked for re-alignment if the field did fill the entire column,
18861 because, in this case the deletion might narrow the column."
18862 (interactive "p")
18863 (save-match-data
18864 (org-check-before-invisible-edit 'delete-backward)
18865 (if (and (org-table-p)
18866 (eq N 1)
18867 (string-match "|" (buffer-substring (point-at-bol) (point)))
18868 (looking-at ".*?|"))
18869 (let ((pos (point))
18870 (noalign (looking-at "[^|\n\r]* |"))
18871 (c org-table-may-need-update))
18872 (backward-delete-char N)
18873 (if (not overwrite-mode)
18874 (progn
18875 (skip-chars-forward "^|")
18876 (insert " ")
18877 (goto-char (1- pos))))
18878 ;; noalign: if there were two spaces at the end, this field
18879 ;; does not determine the width of the column.
18880 (if noalign (setq org-table-may-need-update c)))
18881 (backward-delete-char N)
18882 (org-fix-tags-on-the-fly))))
18884 (defun org-delete-char (N)
18885 "Like `delete-char', but insert whitespace at field end in tables.
18886 When deleting characters, in tables this function will insert whitespace in
18887 front of the next \"|\" separator, to keep the table aligned. The table will
18888 still be marked for re-alignment if the field did fill the entire column,
18889 because, in this case the deletion might narrow the column."
18890 (interactive "p")
18891 (save-match-data
18892 (org-check-before-invisible-edit 'delete)
18893 (if (and (org-table-p)
18894 (not (bolp))
18895 (not (= (char-after) ?|))
18896 (eq N 1))
18897 (if (looking-at ".*?|")
18898 (let ((pos (point))
18899 (noalign (looking-at "[^|\n\r]* |"))
18900 (c org-table-may-need-update))
18901 (replace-match (concat
18902 (substring (match-string 0) 1 -1)
18903 " |"))
18904 (goto-char pos)
18905 ;; noalign: if there were two spaces at the end, this field
18906 ;; does not determine the width of the column.
18907 (if noalign (setq org-table-may-need-update c)))
18908 (delete-char N))
18909 (delete-char N)
18910 (org-fix-tags-on-the-fly))))
18912 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18913 (put 'org-self-insert-command 'delete-selection t)
18914 (put 'orgtbl-self-insert-command 'delete-selection t)
18915 (put 'org-delete-char 'delete-selection 'supersede)
18916 (put 'org-delete-backward-char 'delete-selection 'supersede)
18917 (put 'org-yank 'delete-selection 'yank)
18919 ;; Make `flyspell-mode' delay after some commands
18920 (put 'org-self-insert-command 'flyspell-delayed t)
18921 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18922 (put 'org-delete-char 'flyspell-delayed t)
18923 (put 'org-delete-backward-char 'flyspell-delayed t)
18925 ;; Make pabbrev-mode expand after org-mode commands
18926 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18927 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18929 ;; How to do this: Measure non-white length of current string
18930 ;; If equal to column width, we should realign.
18932 (defun org-remap (map &rest commands)
18933 "In MAP, remap the functions given in COMMANDS.
18934 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18935 (let (new old)
18936 (while commands
18937 (setq old (pop commands) new (pop commands))
18938 (if (fboundp 'command-remapping)
18939 (org-defkey map (vector 'remap old) new)
18940 (substitute-key-definition old new map global-map)))))
18942 (when (eq org-enable-table-editor 'optimized)
18943 ;; If the user wants maximum table support, we need to hijack
18944 ;; some standard editing functions
18945 (org-remap org-mode-map
18946 'self-insert-command 'org-self-insert-command
18947 'delete-char 'org-delete-char
18948 'delete-backward-char 'org-delete-backward-char)
18949 (org-defkey org-mode-map "|" 'org-force-self-insert))
18951 (defvar org-ctrl-c-ctrl-c-hook nil
18952 "Hook for functions attaching themselves to `C-c C-c'.
18954 This can be used to add additional functionality to the C-c C-c
18955 key which executes context-dependent commands. This hook is run
18956 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18957 run after the last test.
18959 Each function will be called with no arguments. The function
18960 must check if the context is appropriate for it to act. If yes,
18961 it should do its thing and then return a non-nil value. If the
18962 context is wrong, just do nothing and return nil.")
18964 (defvar org-ctrl-c-ctrl-c-final-hook nil
18965 "Hook for functions attaching themselves to `C-c C-c'.
18967 This can be used to add additional functionality to the C-c C-c
18968 key which executes context-dependent commands. This hook is run
18969 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18970 before the first test.
18972 Each function will be called with no arguments. The function
18973 must check if the context is appropriate for it to act. If yes,
18974 it should do its thing and then return a non-nil value. If the
18975 context is wrong, just do nothing and return nil.")
18977 (defvar org-tab-first-hook nil
18978 "Hook for functions to attach themselves to TAB.
18979 See `org-ctrl-c-ctrl-c-hook' for more information.
18980 This hook runs as the first action when TAB is pressed, even before
18981 `org-cycle' messes around with the `outline-regexp' to cater for
18982 inline tasks and plain list item folding.
18983 If any function in this hook returns t, any other actions that
18984 would have been caused by TAB (such as table field motion or visibility
18985 cycling) will not occur.")
18987 (defvar org-tab-after-check-for-table-hook nil
18988 "Hook for functions to attach themselves to TAB.
18989 See `org-ctrl-c-ctrl-c-hook' for more information.
18990 This hook runs after it has been established that the cursor is not in a
18991 table, but before checking if the cursor is in a headline or if global cycling
18992 should be done.
18993 If any function in this hook returns t, not other actions like visibility
18994 cycling will be done.")
18996 (defvar org-tab-after-check-for-cycling-hook nil
18997 "Hook for functions to attach themselves to TAB.
18998 See `org-ctrl-c-ctrl-c-hook' for more information.
18999 This hook runs after it has been established that not table field motion and
19000 not visibility should be done because of current context. This is probably
19001 the place where a package like yasnippets can hook in.")
19003 (defvar org-tab-before-tab-emulation-hook nil
19004 "Hook for functions to attach themselves to TAB.
19005 See `org-ctrl-c-ctrl-c-hook' for more information.
19006 This hook runs after every other options for TAB have been exhausted, but
19007 before indentation and \t insertion takes place.")
19009 (defvar org-metaleft-hook nil
19010 "Hook for functions attaching themselves to `M-left'.
19011 See `org-ctrl-c-ctrl-c-hook' for more information.")
19012 (defvar org-metaright-hook nil
19013 "Hook for functions attaching themselves to `M-right'.
19014 See `org-ctrl-c-ctrl-c-hook' for more information.")
19015 (defvar org-metaup-hook nil
19016 "Hook for functions attaching themselves to `M-up'.
19017 See `org-ctrl-c-ctrl-c-hook' for more information.")
19018 (defvar org-metadown-hook nil
19019 "Hook for functions attaching themselves to `M-down'.
19020 See `org-ctrl-c-ctrl-c-hook' for more information.")
19021 (defvar org-shiftmetaleft-hook nil
19022 "Hook for functions attaching themselves to `M-S-left'.
19023 See `org-ctrl-c-ctrl-c-hook' for more information.")
19024 (defvar org-shiftmetaright-hook nil
19025 "Hook for functions attaching themselves to `M-S-right'.
19026 See `org-ctrl-c-ctrl-c-hook' for more information.")
19027 (defvar org-shiftmetaup-hook nil
19028 "Hook for functions attaching themselves to `M-S-up'.
19029 See `org-ctrl-c-ctrl-c-hook' for more information.")
19030 (defvar org-shiftmetadown-hook nil
19031 "Hook for functions attaching themselves to `M-S-down'.
19032 See `org-ctrl-c-ctrl-c-hook' for more information.")
19033 (defvar org-metareturn-hook nil
19034 "Hook for functions attaching themselves to `M-RET'.
19035 See `org-ctrl-c-ctrl-c-hook' for more information.")
19036 (defvar org-shiftup-hook nil
19037 "Hook for functions attaching themselves to `S-up'.
19038 See `org-ctrl-c-ctrl-c-hook' for more information.")
19039 (defvar org-shiftup-final-hook nil
19040 "Hook for functions attaching themselves to `S-up'.
19041 This one runs after all other options except shift-select have been excluded.
19042 See `org-ctrl-c-ctrl-c-hook' for more information.")
19043 (defvar org-shiftdown-hook nil
19044 "Hook for functions attaching themselves to `S-down'.
19045 See `org-ctrl-c-ctrl-c-hook' for more information.")
19046 (defvar org-shiftdown-final-hook nil
19047 "Hook for functions attaching themselves to `S-down'.
19048 This one runs after all other options except shift-select have been excluded.
19049 See `org-ctrl-c-ctrl-c-hook' for more information.")
19050 (defvar org-shiftleft-hook nil
19051 "Hook for functions attaching themselves to `S-left'.
19052 See `org-ctrl-c-ctrl-c-hook' for more information.")
19053 (defvar org-shiftleft-final-hook nil
19054 "Hook for functions attaching themselves to `S-left'.
19055 This one runs after all other options except shift-select have been excluded.
19056 See `org-ctrl-c-ctrl-c-hook' for more information.")
19057 (defvar org-shiftright-hook nil
19058 "Hook for functions attaching themselves to `S-right'.
19059 See `org-ctrl-c-ctrl-c-hook' for more information.")
19060 (defvar org-shiftright-final-hook nil
19061 "Hook for functions attaching themselves to `S-right'.
19062 This one runs after all other options except shift-select have been excluded.
19063 See `org-ctrl-c-ctrl-c-hook' for more information.")
19065 (defun org-modifier-cursor-error ()
19066 "Throw an error, a modified cursor command was applied in wrong context."
19067 (error "This command is active in special context like tables, headlines or items"))
19069 (defun org-shiftselect-error ()
19070 "Throw an error because Shift-Cursor command was applied in wrong context."
19071 (if (and (boundp 'shift-select-mode) shift-select-mode)
19072 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19073 (error "This command works only in special context like headlines or timestamps")))
19075 (defun org-call-for-shift-select (cmd)
19076 (let ((this-command-keys-shift-translated t))
19077 (call-interactively cmd)))
19079 (defun org-shifttab (&optional arg)
19080 "Global visibility cycling or move to previous table field.
19081 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19082 on context.
19083 See the individual commands for more information."
19084 (interactive "P")
19085 (cond
19086 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19087 ((integerp arg)
19088 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19089 (message "Content view to level: %d" arg)
19090 (org-content (prefix-numeric-value arg2))
19091 (setq org-cycle-global-status 'overview)))
19092 (t (call-interactively 'org-global-cycle))))
19094 (defun org-shiftmetaleft ()
19095 "Promote subtree or delete table column.
19096 Calls `org-promote-subtree', `org-outdent-item-tree', or
19097 `org-table-delete-column', depending on context. See the
19098 individual commands for more information."
19099 (interactive)
19100 (cond
19101 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19102 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19103 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19104 ((if (not (org-region-active-p)) (org-at-item-p)
19105 (save-excursion (goto-char (region-beginning))
19106 (org-at-item-p)))
19107 (call-interactively 'org-outdent-item-tree))
19108 (t (org-modifier-cursor-error))))
19110 (defun org-shiftmetaright ()
19111 "Demote subtree or insert table column.
19112 Calls `org-demote-subtree', `org-indent-item-tree', or
19113 `org-table-insert-column', depending on context. See the
19114 individual commands for more information."
19115 (interactive)
19116 (cond
19117 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19118 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19119 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19120 ((if (not (org-region-active-p)) (org-at-item-p)
19121 (save-excursion (goto-char (region-beginning))
19122 (org-at-item-p)))
19123 (call-interactively 'org-indent-item-tree))
19124 (t (org-modifier-cursor-error))))
19126 (defun org-shiftmetaup (&optional arg)
19127 "Move subtree up or kill table row.
19128 Calls `org-move-subtree-up' or `org-table-kill-row' or
19129 `org-move-item-up' or `org-timestamp-up', depending on context.
19130 See the individual commands for more information."
19131 (interactive "P")
19132 (cond
19133 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19134 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19135 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19136 ((org-at-item-p) (call-interactively 'org-move-item-up))
19137 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19138 (call-interactively 'org-timestamp-up)))
19139 (t (org-modifier-cursor-error))))
19141 (defun org-shiftmetadown (&optional arg)
19142 "Move subtree down or insert table row.
19143 Calls `org-move-subtree-down' or `org-table-insert-row' or
19144 `org-move-item-down' or `org-timestamp-up', depending on context.
19145 See the individual commands for more information."
19146 (interactive "P")
19147 (cond
19148 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19149 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19150 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19151 ((org-at-item-p) (call-interactively 'org-move-item-down))
19152 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19153 (call-interactively 'org-timestamp-down)))
19154 (t (org-modifier-cursor-error))))
19156 (defsubst org-hidden-tree-error ()
19157 (error
19158 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19160 (defun org-metaleft (&optional arg)
19161 "Promote heading or move table column to left.
19162 Calls `org-do-promote' or `org-table-move-column', depending on context.
19163 With no specific context, calls the Emacs default `backward-word'.
19164 See the individual commands for more information."
19165 (interactive "P")
19166 (cond
19167 ((run-hook-with-args-until-success 'org-metaleft-hook))
19168 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19169 ((org-with-limited-levels
19170 (or (org-at-heading-p)
19171 (and (org-region-active-p)
19172 (save-excursion
19173 (goto-char (region-beginning))
19174 (org-at-heading-p)))))
19175 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19176 (call-interactively 'org-do-promote))
19177 ;; At an inline task.
19178 ((org-at-heading-p)
19179 (call-interactively 'org-inlinetask-promote))
19180 ((or (org-at-item-p)
19181 (and (org-region-active-p)
19182 (save-excursion
19183 (goto-char (region-beginning))
19184 (org-at-item-p))))
19185 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19186 (call-interactively 'org-outdent-item))
19187 (t (call-interactively 'backward-word))))
19189 (defun org-metaright (&optional arg)
19190 "Demote a subtree, a list item or move table column to right.
19191 In front of a drawer or a block keyword, indent it correctly.
19192 With no specific context, calls the Emacs default `forward-word'.
19193 See the individual commands for more information."
19194 (interactive "P")
19195 (cond
19196 ((run-hook-with-args-until-success 'org-metaright-hook))
19197 ((org-at-table-p) (call-interactively 'org-table-move-column))
19198 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19199 ((org-at-block-p) (call-interactively 'org-indent-block))
19200 ((org-with-limited-levels
19201 (or (org-at-heading-p)
19202 (and (org-region-active-p)
19203 (save-excursion
19204 (goto-char (region-beginning))
19205 (org-at-heading-p)))))
19206 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19207 (call-interactively 'org-do-demote))
19208 ;; At an inline task.
19209 ((org-at-heading-p)
19210 (call-interactively 'org-inlinetask-demote))
19211 ((or (org-at-item-p)
19212 (and (org-region-active-p)
19213 (save-excursion
19214 (goto-char (region-beginning))
19215 (org-at-item-p))))
19216 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19217 (call-interactively 'org-indent-item))
19218 (t (call-interactively 'forward-word))))
19220 (defun org-check-for-hidden (what)
19221 "Check if there are hidden headlines/items in the current visual line.
19222 WHAT can be either `headlines' or `items'. If the current line is
19223 an outline or item heading and it has a folded subtree below it,
19224 this function returns t, nil otherwise."
19225 (let ((re (cond
19226 ((eq what 'headlines) org-outline-regexp-bol)
19227 ((eq what 'items) (org-item-beginning-re))
19228 (t (error "This should not happen"))))
19229 beg end)
19230 (save-excursion
19231 (catch 'exit
19232 (unless (org-region-active-p)
19233 (setq beg (point-at-bol))
19234 (beginning-of-line 2)
19235 (while (and (not (eobp)) ;; this is like `next-line'
19236 (get-char-property (1- (point)) 'invisible))
19237 (beginning-of-line 2))
19238 (setq end (point))
19239 (goto-char beg)
19240 (goto-char (point-at-eol))
19241 (setq end (max end (point)))
19242 (while (re-search-forward re end t)
19243 (if (get-char-property (match-beginning 0) 'invisible)
19244 (throw 'exit t))))
19245 nil))))
19247 (defun org-metaup (&optional arg)
19248 "Move subtree up or move table row up.
19249 Calls `org-move-subtree-up' or `org-table-move-row' or
19250 `org-move-item-up', depending on context. See the individual commands
19251 for more information."
19252 (interactive "P")
19253 (cond
19254 ((run-hook-with-args-until-success 'org-metaup-hook))
19255 ((org-region-active-p)
19256 (let* ((a (min (region-beginning) (region-end)))
19257 (b (1- (max (region-beginning) (region-end))))
19258 (c (save-excursion (goto-char a)
19259 (move-beginning-of-line 0)))
19260 (d (save-excursion (goto-char a)
19261 (move-end-of-line 0) (point))))
19262 (transpose-regions a b c d)
19263 (goto-char c)))
19264 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19265 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19266 ((org-at-item-p) (call-interactively 'org-move-item-up))
19267 (t (org-drag-element-backward))))
19269 (defun org-metadown (&optional arg)
19270 "Move subtree down or move table row down.
19271 Calls `org-move-subtree-down' or `org-table-move-row' or
19272 `org-move-item-down', depending on context. See the individual
19273 commands for more information."
19274 (interactive "P")
19275 (cond
19276 ((run-hook-with-args-until-success 'org-metadown-hook))
19277 ((org-region-active-p)
19278 (let* ((a (min (region-beginning) (region-end)))
19279 (b (max (region-beginning) (region-end)))
19280 (c (save-excursion (goto-char b)
19281 (move-beginning-of-line 1)))
19282 (d (save-excursion (goto-char b)
19283 (move-end-of-line 1) (1+ (point)))))
19284 (transpose-regions a b c d)
19285 (goto-char d)))
19286 ((org-at-table-p) (call-interactively 'org-table-move-row))
19287 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19288 ((org-at-item-p) (call-interactively 'org-move-item-down))
19289 (t (org-drag-element-forward))))
19291 (defun org-shiftup (&optional arg)
19292 "Increase item in timestamp or increase priority of current headline.
19293 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19294 depending on context. See the individual commands for more information."
19295 (interactive "P")
19296 (cond
19297 ((run-hook-with-args-until-success 'org-shiftup-hook))
19298 ((and org-support-shift-select (org-region-active-p))
19299 (org-call-for-shift-select 'previous-line))
19300 ((org-at-timestamp-p t)
19301 (call-interactively (if org-edit-timestamp-down-means-later
19302 'org-timestamp-down 'org-timestamp-up)))
19303 ((and (not (eq org-support-shift-select 'always))
19304 org-enable-priority-commands
19305 (org-at-heading-p))
19306 (call-interactively 'org-priority-up))
19307 ((and (not org-support-shift-select) (org-at-item-p))
19308 (call-interactively 'org-previous-item))
19309 ((org-clocktable-try-shift 'up arg))
19310 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19311 (org-support-shift-select
19312 (org-call-for-shift-select 'previous-line))
19313 (t (org-shiftselect-error))))
19315 (defun org-shiftdown (&optional arg)
19316 "Decrease item in timestamp or decrease priority of current headline.
19317 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19318 depending on context. See the individual commands for more information."
19319 (interactive "P")
19320 (cond
19321 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19322 ((and org-support-shift-select (org-region-active-p))
19323 (org-call-for-shift-select 'next-line))
19324 ((org-at-timestamp-p t)
19325 (call-interactively (if org-edit-timestamp-down-means-later
19326 'org-timestamp-up 'org-timestamp-down)))
19327 ((and (not (eq org-support-shift-select 'always))
19328 org-enable-priority-commands
19329 (org-at-heading-p))
19330 (call-interactively 'org-priority-down))
19331 ((and (not org-support-shift-select) (org-at-item-p))
19332 (call-interactively 'org-next-item))
19333 ((org-clocktable-try-shift 'down arg))
19334 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19335 (org-support-shift-select
19336 (org-call-for-shift-select 'next-line))
19337 (t (org-shiftselect-error))))
19339 (defun org-shiftright (&optional arg)
19340 "Cycle the thing at point or in the current line, depending on context.
19341 Depending on context, this does one of the following:
19343 - switch a timestamp at point one day into the future
19344 - on a headline, switch to the next TODO keyword.
19345 - on an item, switch entire list to the next bullet type
19346 - on a property line, switch to the next allowed value
19347 - on a clocktable definition line, move time block into the future"
19348 (interactive "P")
19349 (cond
19350 ((run-hook-with-args-until-success 'org-shiftright-hook))
19351 ((and org-support-shift-select (org-region-active-p))
19352 (org-call-for-shift-select 'forward-char))
19353 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19354 ((and (not (eq org-support-shift-select 'always))
19355 (org-at-heading-p))
19356 (let ((org-inhibit-logging
19357 (not org-treat-S-cursor-todo-selection-as-state-change))
19358 (org-inhibit-blocking
19359 (not org-treat-S-cursor-todo-selection-as-state-change)))
19360 (org-call-with-arg 'org-todo 'right)))
19361 ((or (and org-support-shift-select
19362 (not (eq org-support-shift-select 'always))
19363 (org-at-item-bullet-p))
19364 (and (not org-support-shift-select) (org-at-item-p)))
19365 (org-call-with-arg 'org-cycle-list-bullet nil))
19366 ((and (not (eq org-support-shift-select 'always))
19367 (org-at-property-p))
19368 (call-interactively 'org-property-next-allowed-value))
19369 ((org-clocktable-try-shift 'right arg))
19370 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19371 (org-support-shift-select
19372 (org-call-for-shift-select 'forward-char))
19373 (t (org-shiftselect-error))))
19375 (defun org-shiftleft (&optional arg)
19376 "Cycle the thing at point or in the current line, depending on context.
19377 Depending on context, this does one of the following:
19379 - switch a timestamp at point one day into the past
19380 - on a headline, switch to the previous TODO keyword.
19381 - on an item, switch entire list to the previous bullet type
19382 - on a property line, switch to the previous allowed value
19383 - on a clocktable definition line, move time block into the past"
19384 (interactive "P")
19385 (cond
19386 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19387 ((and org-support-shift-select (org-region-active-p))
19388 (org-call-for-shift-select 'backward-char))
19389 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19390 ((and (not (eq org-support-shift-select 'always))
19391 (org-at-heading-p))
19392 (let ((org-inhibit-logging
19393 (not org-treat-S-cursor-todo-selection-as-state-change))
19394 (org-inhibit-blocking
19395 (not org-treat-S-cursor-todo-selection-as-state-change)))
19396 (org-call-with-arg 'org-todo 'left)))
19397 ((or (and org-support-shift-select
19398 (not (eq org-support-shift-select 'always))
19399 (org-at-item-bullet-p))
19400 (and (not org-support-shift-select) (org-at-item-p)))
19401 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19402 ((and (not (eq org-support-shift-select 'always))
19403 (org-at-property-p))
19404 (call-interactively 'org-property-previous-allowed-value))
19405 ((org-clocktable-try-shift 'left arg))
19406 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19407 (org-support-shift-select
19408 (org-call-for-shift-select 'backward-char))
19409 (t (org-shiftselect-error))))
19411 (defun org-shiftcontrolright ()
19412 "Switch to next TODO set."
19413 (interactive)
19414 (cond
19415 ((and org-support-shift-select (org-region-active-p))
19416 (org-call-for-shift-select 'forward-word))
19417 ((and (not (eq org-support-shift-select 'always))
19418 (org-at-heading-p))
19419 (org-call-with-arg 'org-todo 'nextset))
19420 (org-support-shift-select
19421 (org-call-for-shift-select 'forward-word))
19422 (t (org-shiftselect-error))))
19424 (defun org-shiftcontrolleft ()
19425 "Switch to previous TODO set."
19426 (interactive)
19427 (cond
19428 ((and org-support-shift-select (org-region-active-p))
19429 (org-call-for-shift-select 'backward-word))
19430 ((and (not (eq org-support-shift-select 'always))
19431 (org-at-heading-p))
19432 (org-call-with-arg 'org-todo 'previousset))
19433 (org-support-shift-select
19434 (org-call-for-shift-select 'backward-word))
19435 (t (org-shiftselect-error))))
19437 (defun org-shiftcontrolup (&optional n)
19438 "Change timestamps synchronously up in CLOCK log lines.
19439 Optional argument N tells to change by that many units."
19440 (interactive "P")
19441 (cond ((and (not org-support-shift-select)
19442 (org-at-clock-log-p)
19443 (org-at-timestamp-p t))
19444 (org-clock-timestamps-up n))
19445 (t (org-shiftselect-error))))
19447 (defun org-shiftcontroldown (&optional n)
19448 "Change timestamps synchronously down in CLOCK log lines.
19449 Optional argument N tells to change by that many units."
19450 (interactive "P")
19451 (cond ((and (not org-support-shift-select)
19452 (org-at-clock-log-p)
19453 (org-at-timestamp-p t))
19454 (org-clock-timestamps-down n))
19455 (t (org-shiftselect-error))))
19457 (defun org-ctrl-c-ret ()
19458 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19459 (interactive)
19460 (cond
19461 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19462 (t (call-interactively 'org-insert-heading))))
19464 (defun org-find-visible ()
19465 (let ((s (point)))
19466 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19467 (get-char-property s 'invisible)))
19469 (defun org-find-invisible ()
19470 (let ((s (point)))
19471 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19472 (not (get-char-property s 'invisible))))
19475 (defun org-copy-visible (beg end)
19476 "Copy the visible parts of the region."
19477 (interactive "r")
19478 (let (snippets s)
19479 (save-excursion
19480 (save-restriction
19481 (narrow-to-region beg end)
19482 (setq s (goto-char (point-min)))
19483 (while (not (= (point) (point-max)))
19484 (goto-char (org-find-invisible))
19485 (push (buffer-substring s (point)) snippets)
19486 (setq s (goto-char (org-find-visible))))))
19487 (kill-new (apply 'concat (nreverse snippets)))))
19489 (defun org-copy-special ()
19490 "Copy region in table or copy current subtree.
19491 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19492 See the individual commands for more information."
19493 (interactive)
19494 (call-interactively
19495 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19497 (defun org-cut-special ()
19498 "Cut region in table or cut current subtree.
19499 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19500 See the individual commands for more information."
19501 (interactive)
19502 (call-interactively
19503 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19505 (defun org-paste-special (arg)
19506 "Paste rectangular region into table, or past subtree relative to level.
19507 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19508 See the individual commands for more information."
19509 (interactive "P")
19510 (if (org-at-table-p)
19511 (org-table-paste-rectangle)
19512 (org-paste-subtree arg)))
19514 (defsubst org-in-fixed-width-region-p ()
19515 "Is point in a fixed-width region?"
19516 (save-match-data
19517 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19519 (defun org-edit-special (&optional arg)
19520 "Call a special editor for the element at point.
19521 When at a table, call the formula editor with `org-table-edit-formulas'.
19522 When in a source code block, call `org-edit-src-code'.
19523 When in a fixed-width region, call `org-edit-fixed-width-region'.
19524 When at an #+INCLUDE keyword, visit the included file.
19525 On a link, call `ffap' to visit the link at point.
19526 Otherwise, return a user error."
19527 (interactive)
19528 (let ((element (org-element-at-point)))
19529 (assert (not buffer-read-only) nil
19530 "Buffer is read-only: %s" (buffer-name))
19531 (case (org-element-type element)
19532 (src-block
19533 (if (not arg) (org-edit-src-code)
19534 (let* ((info (org-babel-get-src-block-info))
19535 (lang (nth 0 info))
19536 (params (nth 2 info))
19537 (session (cdr (assq :session params))))
19538 (if (not session) (org-edit-src-code)
19539 ;; At a src-block with a session and function called with
19540 ;; an ARG: switch to the buffer related to the inferior
19541 ;; process.
19542 (funcall (intern (concat "org-babel-prep-session:" lang))
19543 session params)))))
19544 (keyword
19545 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19546 (find-file
19547 (org-remove-double-quotes
19548 (car (org-split-string (org-element-property :value element)))))
19549 (user-error "No special environment to edit here")))
19550 (table
19551 (if (eq (org-element-property :type element) 'table.el)
19552 (org-edit-src-code)
19553 (call-interactively 'org-table-edit-formulas)))
19554 ;; Only Org tables contain `table-row' type elements.
19555 (table-row (call-interactively 'org-table-edit-formulas))
19556 ((example-block export-block) (org-edit-src-code))
19557 (fixed-width (org-edit-fixed-width-region))
19558 (otherwise
19559 ;; No notable element at point. Though, we may be at a link,
19560 ;; which is an object. Thus, scan deeper.
19561 (if (eq (org-element-type (org-element-context element)) 'link)
19562 (call-interactively 'ffap)
19563 (user-error "No special environment to edit here"))))))
19565 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19566 (defun org-ctrl-c-ctrl-c (&optional arg)
19567 "Set tags in headline, or update according to changed information at point.
19569 This command does many different things, depending on context:
19571 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19572 this is what we do.
19574 - If the cursor is on a statistics cookie, update it.
19576 - If the cursor is in a headline, prompt for tags and insert them
19577 into the current line, aligned to `org-tags-column'. When called
19578 with prefix arg, realign all tags in the current buffer.
19580 - If the cursor is in one of the special #+KEYWORD lines, this
19581 triggers scanning the buffer for these lines and updating the
19582 information.
19584 - If the cursor is inside a table, realign the table. This command
19585 works even if the automatic table editor has been turned off.
19587 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19588 the entire table.
19590 - If the cursor is at a footnote reference or definition, jump to
19591 the corresponding definition or references, respectively.
19593 - If the cursor is a the beginning of a dynamic block, update it.
19595 - If the current buffer is a capture buffer, close note and file it.
19597 - If the cursor is on a <<<target>>>, update radio targets and
19598 corresponding links in this buffer.
19600 - If the cursor is on a numbered item in a plain list, renumber the
19601 ordered list.
19603 - If the cursor is on a checkbox, toggle it.
19605 - If the cursor is on a code block, evaluate it. The variable
19606 `org-confirm-babel-evaluate' can be used to control prompting
19607 before code block evaluation, by default every code block
19608 evaluation requires confirmation. Code block evaluation can be
19609 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19610 (interactive "P")
19611 (cond
19612 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19613 org-occur-highlights
19614 org-latex-fragment-image-overlays)
19615 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19616 (org-remove-occur-highlights)
19617 (org-remove-latex-fragment-image-overlays)
19618 (message "Temporary highlights/overlays removed from current buffer"))
19619 ((and (local-variable-p 'org-finish-function (current-buffer))
19620 (fboundp org-finish-function))
19621 (funcall org-finish-function))
19622 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19624 (let* ((context (org-element-context)) (type (org-element-type context)))
19625 ;; Test if point is within blanks at the end of an element.
19626 (if (save-excursion
19627 (or (not context)
19628 (beginning-of-line)
19629 (and (looking-at "[ \t]*$")
19630 (skip-chars-forward " \r\t\n")
19631 (>= (point) (org-element-property :end context)))))
19632 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19633 (user-error "C-c C-c can do nothing useful at this location"))
19634 ;; For convenience: at the first line of a paragraph on the
19635 ;; same line as an item, apply function on that item instead.
19636 (when (eq type 'paragraph)
19637 (let ((parent (org-element-property :parent context)))
19638 (when (and (eq (org-element-type parent) 'item)
19639 (= (point-at-bol) (org-element-property :begin parent)))
19640 (setq context parent type 'item))))
19641 ;; Act according to type of element or object at point.
19642 (case type
19643 (clock (org-clock-update-time-maybe))
19644 (dynamic-block
19645 (save-excursion
19646 (goto-char (org-element-property :post-affiliated context))
19647 (org-update-dblock)))
19648 (footnote-definition
19649 (goto-char (org-element-property :post-affiliated context))
19650 (call-interactively 'org-footnote-action))
19651 (footnote-reference (call-interactively 'org-footnote-action))
19652 ((headline inlinetask)
19653 (save-excursion (goto-char (org-element-property :begin context))
19654 (call-interactively 'org-set-tags)))
19655 (item
19656 ;; At an item: a double C-u set checkbox to "[-]"
19657 ;; unconditionally, whereas a single one will toggle its
19658 ;; presence. Without an universal argument, if the item
19659 ;; has a checkbox, toggle it. Otherwise repair the list.
19660 (let* ((box (org-element-property :checkbox context))
19661 (struct (org-element-property :structure context))
19662 (old-struct (copy-tree struct))
19663 (parents (org-list-parents-alist struct))
19664 (prevs (org-list-prevs-alist struct))
19665 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19666 (org-list-set-checkbox
19667 (org-element-property :begin context) struct
19668 (cond ((equal arg '(16)) "[-]")
19669 ((and (not box) (equal arg '(4))) "[ ]")
19670 ((or (not box) (equal arg '(4))) nil)
19671 ((eq box 'on) "[ ]")
19672 (t "[X]")))
19673 ;; Mimic `org-list-write-struct' but with grabbing
19674 ;; a return value from `org-list-struct-fix-box'.
19675 (org-list-struct-fix-ind struct parents 2)
19676 (org-list-struct-fix-item-end struct)
19677 (org-list-struct-fix-bul struct prevs)
19678 (org-list-struct-fix-ind struct parents)
19679 (let ((block-item
19680 (org-list-struct-fix-box struct parents prevs orderedp)))
19681 (if (and box (equal struct old-struct))
19682 (if (equal arg '(16))
19683 (message "Checkboxes already reset")
19684 (user-error "Cannot toggle this checkbox: %s"
19685 (if (eq box 'on)
19686 "all subitems checked"
19687 "unchecked subitems")))
19688 (org-list-struct-apply-struct struct old-struct)
19689 (org-update-checkbox-count-maybe))
19690 (when block-item
19691 (message "Checkboxes were removed due to empty box at line %d"
19692 (org-current-line block-item))))))
19693 (keyword
19694 (let ((org-inhibit-startup-visibility-stuff t)
19695 (org-startup-align-all-tables nil))
19696 (when (boundp 'org-table-coordinate-overlays)
19697 (mapc 'delete-overlay org-table-coordinate-overlays)
19698 (setq org-table-coordinate-overlays nil))
19699 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19700 (message "Local setup has been refreshed"))
19701 (plain-list
19702 ;; At a plain list, with a double C-u argument, set
19703 ;; checkboxes of each item to "[-]", whereas a single one
19704 ;; will toggle their presence according to the state of the
19705 ;; first item in the list. Without an argument, repair the
19706 ;; list.
19707 (let* ((begin (org-element-property :contents-begin context))
19708 (struct (org-element-property :structure context))
19709 (old-struct (copy-tree struct))
19710 (first-box (save-excursion
19711 (goto-char begin)
19712 (looking-at org-list-full-item-re)
19713 (match-string-no-properties 3)))
19714 (new-box (cond ((equal arg '(16)) "[-]")
19715 ((equal arg '(4)) (unless first-box "[ ]"))
19716 ((equal first-box "[X]") "[ ]")
19717 (t "[X]"))))
19718 (cond
19719 (arg
19720 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19721 (org-list-get-all-items
19722 begin struct (org-list-prevs-alist struct))))
19723 ((and first-box (eq (point) begin))
19724 ;; For convenience, when point is at bol on the first
19725 ;; item of the list and no argument is provided, simply
19726 ;; toggle checkbox of that item, if any.
19727 (org-list-set-checkbox begin struct new-box)))
19728 (org-list-write-struct
19729 struct (org-list-parents-alist struct) old-struct)
19730 (org-update-checkbox-count-maybe)
19731 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19732 ((property-drawer node-property)
19733 (call-interactively 'org-property-action))
19734 ((radio-target target)
19735 (call-interactively 'org-update-radio-target-regexp))
19736 (statistics-cookie
19737 (call-interactively 'org-update-statistics-cookies))
19738 ((table table-cell table-row)
19739 ;; At a table, recalculate every field and align it. Also
19740 ;; send the table if necessary. If the table has
19741 ;; a `table.el' type, just give up. At a table row or
19742 ;; cell, maybe recalculate line but always align table.
19743 (if (eq (org-element-property :type context) 'table.el)
19744 (message "Use C-c ' to edit table.el tables")
19745 (let ((org-enable-table-editor t))
19746 (if (or (eq type 'table)
19747 ;; Check if point is at a TBLFM line.
19748 (and (eq type 'table-row)
19749 (= (point) (org-element-property :end context))))
19750 (save-excursion
19751 (goto-char (org-element-property :contents-begin context))
19752 (org-call-with-arg 'org-table-recalculate (or arg t))
19753 (orgtbl-send-table 'maybe))
19754 (org-table-maybe-eval-formula)
19755 (cond (arg (call-interactively 'org-table-recalculate))
19756 ((org-table-maybe-recalculate-line))
19757 (t (org-table-align)))))))
19758 (timestamp (org-timestamp-change 0 'day))
19759 (otherwise
19760 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19761 (user-error
19762 "C-c C-c can do nothing useful at this location")))))))))
19764 (defun org-mode-restart ()
19765 "Restart Org-mode, to scan again for special lines.
19766 Also updates the keyword regular expressions."
19767 (interactive)
19768 (org-mode)
19769 (message "Org-mode restarted"))
19771 (defun org-kill-note-or-show-branches ()
19772 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19773 (interactive)
19774 (if (not org-finish-function)
19775 (progn
19776 (hide-subtree)
19777 (call-interactively 'show-branches))
19778 (let ((org-note-abort t))
19779 (funcall org-finish-function))))
19781 (defun org-return (&optional indent)
19782 "Goto next table row or insert a newline.
19783 Calls `org-table-next-row' or `newline', depending on context.
19784 See the individual commands for more information."
19785 (interactive)
19786 (let (org-ts-what)
19787 (cond
19788 ((or (bobp) (org-in-src-block-p))
19789 (if indent (newline-and-indent) (newline)))
19790 ((org-at-table-p)
19791 (org-table-justify-field-maybe)
19792 (call-interactively 'org-table-next-row))
19793 ;; when `newline-and-indent' is called within a list, make sure
19794 ;; text moved stays inside the item.
19795 ((and (org-in-item-p) indent)
19796 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19797 (progn
19798 (save-match-data (newline))
19799 (org-indent-line-to (length (match-string 0))))
19800 (let ((ind (org-get-indentation)))
19801 (newline)
19802 (if (org-looking-back org-list-end-re)
19803 (org-indent-line)
19804 (org-indent-line-to ind)))))
19805 ((and org-return-follows-link
19806 (org-at-timestamp-p t)
19807 (not (eq org-ts-what 'after)))
19808 (org-follow-timestamp-link))
19809 ((and org-return-follows-link
19810 (let ((tprop (get-text-property (point) 'face)))
19811 (or (eq tprop 'org-link)
19812 (and (listp tprop) (memq 'org-link tprop)))))
19813 (call-interactively 'org-open-at-point))
19814 ((and (org-at-heading-p)
19815 (looking-at
19816 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19817 (org-show-entry)
19818 (end-of-line 1)
19819 (newline))
19820 (t (if indent (newline-and-indent) (newline))))))
19822 (defun org-return-indent ()
19823 "Goto next table row or insert a newline and indent.
19824 Calls `org-table-next-row' or `newline-and-indent', depending on
19825 context. See the individual commands for more information."
19826 (interactive)
19827 (org-return t))
19829 (defun org-ctrl-c-star ()
19830 "Compute table, or change heading status of lines.
19831 Calls `org-table-recalculate' or `org-toggle-heading',
19832 depending on context."
19833 (interactive)
19834 (cond
19835 ((org-at-table-p)
19836 (call-interactively 'org-table-recalculate))
19838 ;; Convert all lines in region to list items
19839 (call-interactively 'org-toggle-heading))))
19841 (defun org-ctrl-c-minus ()
19842 "Insert separator line in table or modify bullet status of line.
19843 Also turns a plain line or a region of lines into list items.
19844 Calls `org-table-insert-hline', `org-toggle-item', or
19845 `org-cycle-list-bullet', depending on context."
19846 (interactive)
19847 (cond
19848 ((org-at-table-p)
19849 (call-interactively 'org-table-insert-hline))
19850 ((org-region-active-p)
19851 (call-interactively 'org-toggle-item))
19852 ((org-in-item-p)
19853 (call-interactively 'org-cycle-list-bullet))
19855 (call-interactively 'org-toggle-item))))
19857 (defun org-toggle-item (arg)
19858 "Convert headings or normal lines to items, items to normal lines.
19859 If there is no active region, only the current line is considered.
19861 If the first non blank line in the region is an headline, convert
19862 all headlines to items, shifting text accordingly.
19864 If it is an item, convert all items to normal lines.
19866 If it is normal text, change region into an item. With a prefix
19867 argument ARG, change each line in region into an item."
19868 (interactive "P")
19869 (let ((shift-text
19870 (function
19871 ;; Shift text in current section to IND, from point to END.
19872 ;; The function leaves point to END line.
19873 (lambda (ind end)
19874 (let ((min-i 1000) (end (copy-marker end)))
19875 ;; First determine the minimum indentation (MIN-I) of
19876 ;; the text.
19877 (save-excursion
19878 (catch 'exit
19879 (while (< (point) end)
19880 (let ((i (org-get-indentation)))
19881 (cond
19882 ;; Skip blank lines and inline tasks.
19883 ((looking-at "^[ \t]*$"))
19884 ((looking-at org-outline-regexp-bol))
19885 ;; We can't find less than 0 indentation.
19886 ((zerop i) (throw 'exit (setq min-i 0)))
19887 ((< i min-i) (setq min-i i))))
19888 (forward-line))))
19889 ;; Then indent each line so that a line indented to
19890 ;; MIN-I becomes indented to IND. Ignore blank lines
19891 ;; and inline tasks in the process.
19892 (let ((delta (- ind min-i)))
19893 (while (< (point) end)
19894 (unless (or (looking-at "^[ \t]*$")
19895 (looking-at org-outline-regexp-bol))
19896 (org-indent-line-to (+ (org-get-indentation) delta)))
19897 (forward-line)))))))
19898 (skip-blanks
19899 (function
19900 ;; Return beginning of first non-blank line, starting from
19901 ;; line at POS.
19902 (lambda (pos)
19903 (save-excursion
19904 (goto-char pos)
19905 (skip-chars-forward " \r\t\n")
19906 (point-at-bol)))))
19907 beg end)
19908 ;; Determine boundaries of changes.
19909 (if (org-region-active-p)
19910 (setq beg (funcall skip-blanks (region-beginning))
19911 end (copy-marker (region-end)))
19912 (setq beg (funcall skip-blanks (point-at-bol))
19913 end (copy-marker (point-at-eol))))
19914 ;; Depending on the starting line, choose an action on the text
19915 ;; between BEG and END.
19916 (org-with-limited-levels
19917 (save-excursion
19918 (goto-char beg)
19919 (cond
19920 ;; Case 1. Start at an item: de-itemize. Note that it only
19921 ;; happens when a region is active: `org-ctrl-c-minus'
19922 ;; would call `org-cycle-list-bullet' otherwise.
19923 ((org-at-item-p)
19924 (while (< (point) end)
19925 (when (org-at-item-p)
19926 (skip-chars-forward " \t")
19927 (delete-region (point) (match-end 0)))
19928 (forward-line)))
19929 ;; Case 2. Start at an heading: convert to items.
19930 ((org-at-heading-p)
19931 (let* ((bul (org-list-bullet-string "-"))
19932 (bul-len (length bul))
19933 ;; Indentation of the first heading. It should be
19934 ;; relative to the indentation of its parent, if any.
19935 (start-ind (save-excursion
19936 (cond
19937 ((not org-adapt-indentation) 0)
19938 ((not (outline-previous-heading)) 0)
19939 (t (length (match-string 0))))))
19940 ;; Level of first heading. Further headings will be
19941 ;; compared to it to determine hierarchy in the list.
19942 (ref-level (org-reduced-level (org-outline-level))))
19943 (while (< (point) end)
19944 (let* ((level (org-reduced-level (org-outline-level)))
19945 (delta (max 0 (- level ref-level))))
19946 ;; If current headline is less indented than the first
19947 ;; one, set it as reference, in order to preserve
19948 ;; subtrees.
19949 (when (< level ref-level) (setq ref-level level))
19950 (replace-match bul t t)
19951 (org-indent-line-to (+ start-ind (* delta bul-len)))
19952 ;; Ensure all text down to END (or SECTION-END) belongs
19953 ;; to the newly created item.
19954 (let ((section-end (save-excursion
19955 (or (outline-next-heading) (point)))))
19956 (forward-line)
19957 (funcall shift-text
19958 (+ start-ind (* (1+ delta) bul-len))
19959 (min end section-end)))))))
19960 ;; Case 3. Normal line with ARG: turn each non-item line into
19961 ;; an item.
19962 (arg
19963 (while (< (point) end)
19964 (unless (or (org-at-heading-p) (org-at-item-p))
19965 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19966 (replace-match
19967 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19968 (forward-line)))
19969 ;; Case 4. Normal line without ARG: make the first line of
19970 ;; region an item, and shift indentation of others
19971 ;; lines to set them as item's body.
19972 (t (let* ((bul (org-list-bullet-string "-"))
19973 (bul-len (length bul))
19974 (ref-ind (org-get-indentation)))
19975 (skip-chars-forward " \t")
19976 (insert bul)
19977 (forward-line)
19978 (while (< (point) end)
19979 ;; Ensure that lines less indented than first one
19980 ;; still get included in item body.
19981 (funcall shift-text
19982 (+ ref-ind bul-len)
19983 (min end (save-excursion (or (outline-next-heading)
19984 (point)))))
19985 (forward-line)))))))))
19987 (defun org-toggle-heading (&optional nstars)
19988 "Convert headings to normal text, or items or text to headings.
19989 If there is no active region, only the current line is considered.
19991 With a \\[universal-argument] prefix, convert the whole list at
19992 point into heading.
19994 In a region:
19996 - If the first non blank line is an headline, remove the stars
19997 from all headlines in the region.
19999 - If it is a normal line turn each and every normal line (i.e. not an
20000 heading or an item) in the region into a heading.
20002 - If it is a plain list item, turn all plain list items into headings.
20004 When converting a line into a heading, the number of stars is chosen
20005 such that the lines become children of the current entry. However,
20006 when a prefix argument is given, its value determines the number of
20007 stars to add."
20008 (interactive "P")
20009 (let ((skip-blanks
20010 (function
20011 ;; Return beginning of first non-blank line, starting from
20012 ;; line at POS.
20013 (lambda (pos)
20014 (save-excursion
20015 (goto-char pos)
20016 (while (org-at-comment-p) (forward-line))
20017 (skip-chars-forward " \r\t\n")
20018 (point-at-bol)))))
20019 beg end toggled)
20020 ;; Determine boundaries of changes. If a universal prefix has
20021 ;; been given, put the list in a region. If region ends at a bol,
20022 ;; do not consider the last line to be in the region.
20024 (when (and current-prefix-arg (org-at-item-p))
20025 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20026 (org-mark-element))
20028 (if (org-region-active-p)
20029 (setq beg (funcall skip-blanks (region-beginning))
20030 end (copy-marker (save-excursion
20031 (goto-char (region-end))
20032 (if (bolp) (point) (point-at-eol)))))
20033 (setq beg (funcall skip-blanks (point-at-bol))
20034 end (copy-marker (point-at-eol))))
20035 ;; Ensure inline tasks don't count as headings.
20036 (org-with-limited-levels
20037 (save-excursion
20038 (goto-char beg)
20039 (cond
20040 ;; Case 1. Started at an heading: de-star headings.
20041 ((org-at-heading-p)
20042 (while (< (point) end)
20043 (when (org-at-heading-p t)
20044 (looking-at org-outline-regexp) (replace-match "")
20045 (setq toggled t))
20046 (forward-line)))
20047 ;; Case 2. Started at an item: change items into headlines.
20048 ;; One star will be added by `org-list-to-subtree'.
20049 ((org-at-item-p)
20050 (let* ((stars (make-string
20051 (if nstars
20052 ;; subtract the star that will be added again by
20053 ;; `org-list-to-subtree'
20054 (1- (prefix-numeric-value current-prefix-arg))
20055 (or (org-current-level) 0))
20056 ?*))
20057 (add-stars
20058 (cond (nstars "") ; stars from prefix only
20059 ((equal stars "") "") ; before first heading
20060 (org-odd-levels-only "*") ; inside heading, odd
20061 (t "")))) ; inside heading, oddeven
20062 (while (< (point) end)
20063 (when (org-at-item-p)
20064 ;; Pay attention to cases when region ends before list.
20065 (let* ((struct (org-list-struct))
20066 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20067 (save-restriction
20068 (narrow-to-region (point) list-end)
20069 (insert
20070 (org-list-to-subtree
20071 (org-list-parse-list t)
20072 '(:istart (concat stars add-stars (funcall get-stars depth))
20073 :icount (concat stars add-stars (funcall get-stars depth)))))))
20074 (setq toggled t))
20075 (forward-line))))
20076 ;; Case 3. Started at normal text: make every line an heading,
20077 ;; skipping headlines and items.
20078 (t (let* ((stars (make-string
20079 (if nstars
20080 (prefix-numeric-value current-prefix-arg)
20081 (or (org-current-level) 0))
20082 ?*))
20083 (add-stars
20084 (cond (nstars "") ; stars from prefix only
20085 ((equal stars "") "*") ; before first heading
20086 (org-odd-levels-only "**") ; inside heading, odd
20087 (t "*"))) ; inside heading, oddeven
20088 (rpl (concat stars add-stars " ")))
20089 (while (< (point) end)
20090 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20091 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20092 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20093 (forward-line)))))))
20094 (unless toggled (message "Cannot toggle heading from here"))))
20096 (defun org-meta-return (&optional arg)
20097 "Insert a new heading or wrap a region in a table.
20098 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20099 See the individual commands for more information."
20100 (interactive "P")
20101 (cond
20102 ((run-hook-with-args-until-success 'org-metareturn-hook))
20103 ((or (org-at-drawer-p) (org-at-property-p))
20104 (newline-and-indent))
20105 ((org-at-table-p)
20106 (call-interactively 'org-table-wrap-region))
20107 (t (call-interactively 'org-insert-heading))))
20109 ;;; Menu entries
20111 (defsubst org-in-subtree-not-table-p ()
20112 "Are we in a subtree and not in a table?"
20113 (and (not (org-before-first-heading-p))
20114 (not (org-at-table-p))))
20116 ;; Define the Org-mode menus
20117 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20118 '("Tbl"
20119 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20120 ["Next Field" org-cycle (org-at-table-p)]
20121 ["Previous Field" org-shifttab (org-at-table-p)]
20122 ["Next Row" org-return (org-at-table-p)]
20123 "--"
20124 ["Blank Field" org-table-blank-field (org-at-table-p)]
20125 ["Edit Field" org-table-edit-field (org-at-table-p)]
20126 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20127 "--"
20128 ("Column"
20129 ["Move Column Left" org-metaleft (org-at-table-p)]
20130 ["Move Column Right" org-metaright (org-at-table-p)]
20131 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20132 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20133 ("Row"
20134 ["Move Row Up" org-metaup (org-at-table-p)]
20135 ["Move Row Down" org-metadown (org-at-table-p)]
20136 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20137 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20138 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20139 "--"
20140 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20141 ("Rectangle"
20142 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20143 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20144 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20145 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20146 "--"
20147 ("Calculate"
20148 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20149 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20150 ["Edit Formulas" org-edit-special (org-at-table-p)]
20151 "--"
20152 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20153 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20154 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20155 "--"
20156 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20157 "--"
20158 ["Sum Column/Rectangle" org-table-sum
20159 (or (org-at-table-p) (org-region-active-p))]
20160 ["Which Column?" org-table-current-column (org-at-table-p)])
20161 ["Debug Formulas"
20162 org-table-toggle-formula-debugger
20163 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20164 ["Show Col/Row Numbers"
20165 org-table-toggle-coordinate-overlays
20166 :style toggle
20167 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20168 "--"
20169 ["Create" org-table-create (and (not (org-at-table-p))
20170 org-enable-table-editor)]
20171 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20172 ["Import from File" org-table-import (not (org-at-table-p))]
20173 ["Export to File" org-table-export (org-at-table-p)]
20174 "--"
20175 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20177 (easy-menu-define org-org-menu org-mode-map "Org menu"
20178 '("Org"
20179 ("Show/Hide"
20180 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20181 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20182 ["Sparse Tree..." org-sparse-tree t]
20183 ["Reveal Context" org-reveal t]
20184 ["Show All" show-all t]
20185 "--"
20186 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20187 "--"
20188 ["New Heading" org-insert-heading t]
20189 ("Navigate Headings"
20190 ["Up" outline-up-heading t]
20191 ["Next" outline-next-visible-heading t]
20192 ["Previous" outline-previous-visible-heading t]
20193 ["Next Same Level" outline-forward-same-level t]
20194 ["Previous Same Level" outline-backward-same-level t]
20195 "--"
20196 ["Jump" org-goto t])
20197 ("Edit Structure"
20198 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20199 "--"
20200 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20201 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20202 "--"
20203 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20204 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20205 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20206 "--"
20207 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20208 "--"
20209 ["Copy visible text" org-copy-visible t]
20210 "--"
20211 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20212 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20213 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20214 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20215 "--"
20216 ["Sort Region/Children" org-sort t]
20217 "--"
20218 ["Convert to odd levels" org-convert-to-odd-levels t]
20219 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20220 ("Editing"
20221 ["Emphasis..." org-emphasize t]
20222 ["Edit Source Example" org-edit-special t]
20223 "--"
20224 ["Footnote new/jump" org-footnote-action t]
20225 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20226 ("Archive"
20227 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20228 "--"
20229 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20230 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20231 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20233 "--"
20234 ("Hyperlinks"
20235 ["Store Link (Global)" org-store-link t]
20236 ["Find existing link to here" org-occur-link-in-agenda-files t]
20237 ["Insert Link" org-insert-link t]
20238 ["Follow Link" org-open-at-point t]
20239 "--"
20240 ["Next link" org-next-link t]
20241 ["Previous link" org-previous-link t]
20242 "--"
20243 ["Descriptive Links"
20244 org-toggle-link-display
20245 :style radio
20246 :selected org-descriptive-links
20248 ["Literal Links"
20249 org-toggle-link-display
20250 :style radio
20251 :selected (not org-descriptive-links)])
20252 "--"
20253 ("TODO Lists"
20254 ["TODO/DONE/-" org-todo t]
20255 ("Select keyword"
20256 ["Next keyword" org-shiftright (org-at-heading-p)]
20257 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20258 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20259 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20260 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20261 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20262 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20263 "--"
20264 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20265 :selected org-enforce-todo-dependencies :style toggle :active t]
20266 "Settings for tree at point"
20267 ["Do Children sequentially" org-toggle-ordered-property :style radio
20268 :selected (org-entry-get nil "ORDERED")
20269 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20270 ["Do Children parallel" org-toggle-ordered-property :style radio
20271 :selected (not (org-entry-get nil "ORDERED"))
20272 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20273 "--"
20274 ["Set Priority" org-priority t]
20275 ["Priority Up" org-shiftup t]
20276 ["Priority Down" org-shiftdown t]
20277 "--"
20278 ["Get news from all feeds" org-feed-update-all t]
20279 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20280 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20281 ("TAGS and Properties"
20282 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20283 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20284 "--"
20285 ["Set property" org-set-property (not (org-before-first-heading-p))]
20286 ["Column view of properties" org-columns t]
20287 ["Insert Column View DBlock" org-insert-columns-dblock t])
20288 ("Dates and Scheduling"
20289 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20290 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20291 ("Change Date"
20292 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20293 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20294 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20295 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20296 ["Compute Time Range" org-evaluate-time-range t]
20297 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20298 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20299 "--"
20300 ["Custom time format" org-toggle-time-stamp-overlays
20301 :style radio :selected org-display-custom-times]
20302 "--"
20303 ["Goto Calendar" org-goto-calendar t]
20304 ["Date from Calendar" org-date-from-calendar t]
20305 "--"
20306 ["Start/Restart Timer" org-timer-start t]
20307 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20308 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20309 ["Insert Timer String" org-timer t]
20310 ["Insert Timer Item" org-timer-item t])
20311 ("Logging work"
20312 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20313 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20314 ["Clock out" org-clock-out t]
20315 ["Clock cancel" org-clock-cancel t]
20316 "--"
20317 ["Mark as default task" org-clock-mark-default-task t]
20318 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20319 ["Goto running clock" org-clock-goto t]
20320 "--"
20321 ["Display times" org-clock-display t]
20322 ["Create clock table" org-clock-report t]
20323 "--"
20324 ["Record DONE time"
20325 (progn (setq org-log-done (not org-log-done))
20326 (message "Switching to %s will %s record a timestamp"
20327 (car org-done-keywords)
20328 (if org-log-done "automatically" "not")))
20329 :style toggle :selected org-log-done])
20330 "--"
20331 ["Agenda Command..." org-agenda t]
20332 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20333 ("File List for Agenda")
20334 ("Special views current file"
20335 ["TODO Tree" org-show-todo-tree t]
20336 ["Check Deadlines" org-check-deadlines t]
20337 ["Timeline" org-timeline t]
20338 ["Tags/Property tree" org-match-sparse-tree t])
20339 "--"
20340 ["Export/Publish..." org-export-dispatch t]
20341 ("LaTeX"
20342 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20343 :selected org-cdlatex-mode]
20344 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20345 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20346 ["Modify math symbol" org-cdlatex-math-modify
20347 (org-inside-LaTeX-fragment-p)]
20348 ["Insert citation" org-reftex-citation t]
20349 "--"
20350 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20351 "--"
20352 ("MobileOrg"
20353 ["Push Files and Views" org-mobile-push t]
20354 ["Get Captured and Flagged" org-mobile-pull t]
20355 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20356 "--"
20357 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20358 "--"
20359 ("Documentation"
20360 ["Show Version" org-version t]
20361 ["Info Documentation" org-info t])
20362 ("Customize"
20363 ["Browse Org Group" org-customize t]
20364 "--"
20365 ["Expand This Menu" org-create-customize-menu
20366 (fboundp 'customize-menu-create)])
20367 ["Send bug report" org-submit-bug-report t]
20368 "--"
20369 ("Refresh/Reload"
20370 ["Refresh setup current buffer" org-mode-restart t]
20371 ["Reload Org (after update)" org-reload t]
20372 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20375 (defun org-info (&optional node)
20376 "Read documentation for Org-mode in the info system.
20377 With optional NODE, go directly to that node."
20378 (interactive)
20379 (info (format "(org)%s" (or node ""))))
20381 ;;;###autoload
20382 (defun org-submit-bug-report ()
20383 "Submit a bug report on Org-mode via mail.
20385 Don't hesitate to report any problems or inaccurate documentation.
20387 If you don't have setup sending mail from (X)Emacs, please copy the
20388 output buffer into your mail program, as it gives us important
20389 information about your Org-mode version and configuration."
20390 (interactive)
20391 (require 'reporter)
20392 (org-load-modules-maybe)
20393 (org-require-autoloaded-modules)
20394 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20395 (reporter-submit-bug-report
20396 "emacs-orgmode@gnu.org"
20397 (org-version nil 'full)
20398 (let (list)
20399 (save-window-excursion
20400 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20401 (delete-other-windows)
20402 (erase-buffer)
20403 (insert "You are about to submit a bug report to the Org-mode mailing list.
20405 We would like to add your full Org-mode and Outline configuration to the
20406 bug report. This greatly simplifies the work of the maintainer and
20407 other experts on the mailing list.
20409 HOWEVER, some variables you have customized may contain private
20410 information. The names of customers, colleagues, or friends, might
20411 appear in the form of file names, tags, todo states, or search strings.
20412 If you answer yes to the prompt, you might want to check and remove
20413 such private information before sending the email.")
20414 (add-text-properties (point-min) (point-max) '(face org-warning))
20415 (when (yes-or-no-p "Include your Org-mode configuration ")
20416 (mapatoms
20417 (lambda (v)
20418 (and (boundp v)
20419 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20420 (or (and (symbol-value v)
20421 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20422 (and
20423 (get v 'custom-type) (get v 'standard-value)
20424 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20425 (push v list)))))
20426 (kill-buffer (get-buffer "*Warn about privacy*"))
20427 list))
20428 nil nil
20429 "Remember to cover the basics, that is, what you expected to happen and
20430 what in fact did happen. You don't know how to make a good report? See
20432 http://orgmode.org/manual/Feedback.html#Feedback
20434 Your bug report will be posted to the Org-mode mailing list.
20435 ------------------------------------------------------------------------")
20436 (save-excursion
20437 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20438 (replace-match "\\1Bug: \\3 [\\2]")))))
20441 (defun org-install-agenda-files-menu ()
20442 (let ((bl (buffer-list)))
20443 (save-excursion
20444 (while bl
20445 (set-buffer (pop bl))
20446 (if (derived-mode-p 'org-mode) (setq bl nil)))
20447 (when (derived-mode-p 'org-mode)
20448 (easy-menu-change
20449 '("Org") "File List for Agenda"
20450 (append
20451 (list
20452 ["Edit File List" (org-edit-agenda-file-list) t]
20453 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20454 ["Remove Current File from List" org-remove-file t]
20455 ["Cycle through agenda files" org-cycle-agenda-files t]
20456 ["Occur in all agenda files" org-occur-in-agenda-files t]
20457 "--")
20458 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20460 ;;;; Documentation
20462 (defun org-require-autoloaded-modules ()
20463 (interactive)
20464 (mapc 'require
20465 '(org-agenda org-archive org-attach org-clock org-colview org-id
20466 org-remember org-table org-timer)))
20468 ;;;###autoload
20469 (defun org-reload (&optional uncompiled)
20470 "Reload all org lisp files.
20471 With prefix arg UNCOMPILED, load the uncompiled versions."
20472 (interactive "P")
20473 (require 'loadhist)
20474 (let* ((org-dir (org-find-library-dir "org"))
20475 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20476 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20477 (remove-re (mapconcat 'identity
20478 (mapcar (lambda (f) (concat "^" f "$"))
20479 (list (if (featurep 'xemacs)
20480 "org-colview"
20481 "org-colview-xemacs")
20482 "org" "org-loaddefs" "org-version"))
20483 "\\|"))
20484 (feats (delete-dups
20485 (mapcar 'file-name-sans-extension
20486 (mapcar 'file-name-nondirectory
20487 (delq nil
20488 (mapcar 'feature-file
20489 features))))))
20490 (lfeat (append
20491 (sort
20492 (setq feats
20493 (delq nil (mapcar
20494 (lambda (f)
20495 (if (and (string-match feature-re f)
20496 (not (string-match remove-re f)))
20497 f nil))
20498 feats)))
20499 'string-lessp)
20500 (list "org-version" "org")))
20501 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20502 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20503 load-uncore load-misses)
20504 (setq load-misses
20505 (delq 't
20506 (mapcar (lambda (f)
20507 (or (org-load-noerror-mustsuffix (concat org-dir f))
20508 (and (string= org-dir contrib-dir)
20509 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20510 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20511 (add-to-list 'load-uncore f 'append)
20514 lfeat)))
20515 (if load-uncore
20516 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20517 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20518 (if load-misses
20519 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20520 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20521 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20523 ;;;###autoload
20524 (defun org-customize ()
20525 "Call the customize function with org as argument."
20526 (interactive)
20527 (org-load-modules-maybe)
20528 (org-require-autoloaded-modules)
20529 (customize-browse 'org))
20531 (defun org-create-customize-menu ()
20532 "Create a full customization menu for Org-mode, insert it into the menu."
20533 (interactive)
20534 (org-load-modules-maybe)
20535 (org-require-autoloaded-modules)
20536 (if (fboundp 'customize-menu-create)
20537 (progn
20538 (easy-menu-change
20539 '("Org") "Customize"
20540 `(["Browse Org group" org-customize t]
20541 "--"
20542 ,(customize-menu-create 'org)
20543 ["Set" Custom-set t]
20544 ["Save" Custom-save t]
20545 ["Reset to Current" Custom-reset-current t]
20546 ["Reset to Saved" Custom-reset-saved t]
20547 ["Reset to Standard Settings" Custom-reset-standard t]))
20548 (message "\"Org\"-menu now contains full customization menu"))
20549 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20551 ;;;; Miscellaneous stuff
20553 ;;; Generally useful functions
20555 (defun org-get-at-bol (property)
20556 "Get text property PROPERTY at beginning of line."
20557 (get-text-property (point-at-bol) property))
20559 (defun org-find-text-property-in-string (prop s)
20560 "Return the first non-nil value of property PROP in string S."
20561 (or (get-text-property 0 prop s)
20562 (get-text-property (or (next-single-property-change 0 prop s) 0)
20563 prop s)))
20565 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20566 "Display the given MESSAGE as a warning."
20567 (if (fboundp 'display-warning)
20568 (display-warning 'org message
20569 (if (featurep 'xemacs) 'warning :warning))
20570 (let ((buf (get-buffer-create "*Org warnings*")))
20571 (with-current-buffer buf
20572 (goto-char (point-max))
20573 (insert "Warning (Org): " message)
20574 (unless (bolp)
20575 (newline)))
20576 (display-buffer buf)
20577 (sit-for 0))))
20579 (defun org-eval (form)
20580 "Eval FORM and return result."
20581 (condition-case error
20582 (eval form)
20583 (error (format "%%![Error: %s]" error))))
20585 (defun org-in-clocktable-p ()
20586 "Check if the cursor is in a clocktable."
20587 (let ((pos (point)) start)
20588 (save-excursion
20589 (end-of-line 1)
20590 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20591 (setq start (match-beginning 0))
20592 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20593 (>= (match-end 0) pos)
20594 start))))
20596 (defun org-in-commented-line ()
20597 "Is point in a line starting with `#'?"
20598 (equal (char-after (point-at-bol)) ?#))
20600 (defun org-in-indented-comment-line ()
20601 "Is point in a line starting with `#' after some white space?"
20602 (save-excursion
20603 (save-match-data
20604 (goto-char (point-at-bol))
20605 (looking-at "[ \t]*#"))))
20607 (defun org-in-verbatim-emphasis ()
20608 (save-match-data
20609 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20611 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20612 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20613 (if (and marker (marker-buffer marker)
20614 (buffer-live-p (marker-buffer marker)))
20615 (progn
20616 (org-pop-to-buffer-same-window (marker-buffer marker))
20617 (if (or (> marker (point-max)) (< marker (point-min)))
20618 (widen))
20619 (goto-char marker)
20620 (org-show-context 'org-goto))
20621 (if bookmark
20622 (bookmark-jump bookmark)
20623 (error "Cannot find location"))))
20625 (defun org-quote-csv-field (s)
20626 "Quote field for inclusion in CSV material."
20627 (if (string-match "[\",]" s)
20628 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20631 (defun org-force-self-insert (N)
20632 "Needed to enforce self-insert under remapping."
20633 (interactive "p")
20634 (self-insert-command N))
20636 (defun org-string-width (s)
20637 "Compute width of string, ignoring invisible characters.
20638 This ignores character with invisibility property `org-link', and also
20639 characters with property `org-cwidth', because these will become invisible
20640 upon the next fontification round."
20641 (let (b l)
20642 (when (or (eq t buffer-invisibility-spec)
20643 (assq 'org-link buffer-invisibility-spec))
20644 (while (setq b (text-property-any 0 (length s)
20645 'invisible 'org-link s))
20646 (setq s (concat (substring s 0 b)
20647 (substring s (or (next-single-property-change
20648 b 'invisible s) (length s)))))))
20649 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20650 (setq s (concat (substring s 0 b)
20651 (substring s (or (next-single-property-change
20652 b 'org-cwidth s) (length s))))))
20653 (setq l (string-width s) b -1)
20654 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20655 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20658 (defun org-shorten-string (s maxlength)
20659 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20660 If the string is shorter or has length MAXLENGTH, just return the
20661 original string. If it is longer, the functions finds a space in the
20662 string, breaks this string off at that locations and adds three dots
20663 as ellipsis. Including the ellipsis, the string will not be longer
20664 than MAXLENGTH. If finding a good breaking point in the string does
20665 not work, the string is just chopped off in the middle of a word
20666 if necessary."
20667 (if (<= (length s) maxlength)
20669 (let* ((n (max (- maxlength 4) 1))
20670 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20671 (if (string-match re s)
20672 (concat (match-string 1 s) "...")
20673 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20675 (defun org-get-indentation (&optional line)
20676 "Get the indentation of the current line, interpreting tabs.
20677 When LINE is given, assume it represents a line and compute its indentation."
20678 (if line
20679 (if (string-match "^ *" (org-remove-tabs line))
20680 (match-end 0))
20681 (save-excursion
20682 (beginning-of-line 1)
20683 (skip-chars-forward " \t")
20684 (current-column))))
20686 (defun org-get-string-indentation (s)
20687 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20688 (let ((n -1) (i 0) (w tab-width) c)
20689 (catch 'exit
20690 (while (< (setq n (1+ n)) (length s))
20691 (setq c (aref s n))
20692 (cond ((= c ?\ ) (setq i (1+ i)))
20693 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20694 (t (throw 'exit t)))))
20697 (defun org-remove-tabs (s &optional width)
20698 "Replace tabulators in S with spaces.
20699 Assumes that s is a single line, starting in column 0."
20700 (setq width (or width tab-width))
20701 (while (string-match "\t" s)
20702 (setq s (replace-match
20703 (make-string
20704 (- (* width (/ (+ (match-beginning 0) width) width))
20705 (match-beginning 0)) ?\ )
20706 t t s)))
20709 (defun org-fix-indentation (line ind)
20710 "Fix indentation in LINE.
20711 IND is a cons cell with target and minimum indentation.
20712 If the current indentation in LINE is smaller than the minimum,
20713 leave it alone. If it is larger than ind, set it to the target."
20714 (let* ((l (org-remove-tabs line))
20715 (i (org-get-indentation l))
20716 (i1 (car ind)) (i2 (cdr ind)))
20717 (if (>= i i2) (setq l (substring line i2)))
20718 (if (> i1 0)
20719 (concat (make-string i1 ?\ ) l)
20720 l)))
20722 (defun org-remove-indentation (code &optional n)
20723 "Remove the maximum common indentation from the lines in CODE.
20724 N may optionally be the number of spaces to remove."
20725 (with-temp-buffer
20726 (insert code)
20727 (org-do-remove-indentation n)
20728 (buffer-string)))
20730 (defun org-do-remove-indentation (&optional n)
20731 "Remove the maximum common indentation from the buffer."
20732 (untabify (point-min) (point-max))
20733 (let ((min 10000) re)
20734 (if n
20735 (setq min n)
20736 (goto-char (point-min))
20737 (while (re-search-forward "^ *[^ \n]" nil t)
20738 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20739 (unless (or (= min 0) (= min 10000))
20740 (setq re (format "^ \\{%d\\}" min))
20741 (goto-char (point-min))
20742 (while (re-search-forward re nil t)
20743 (replace-match "")
20744 (end-of-line 1))
20745 min)))
20747 (defun org-fill-template (template alist)
20748 "Find each %key of ALIST in TEMPLATE and replace it."
20749 (let ((case-fold-search nil)
20750 entry key value)
20751 (setq alist (sort (copy-sequence alist)
20752 (lambda (a b) (< (length (car a)) (length (car b))))))
20753 (while (setq entry (pop alist))
20754 (setq template
20755 (replace-regexp-in-string
20756 (concat "%" (regexp-quote (car entry)))
20757 (or (cdr entry) "") template t t)))
20758 template))
20760 (defun org-base-buffer (buffer)
20761 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20762 (if (not buffer)
20763 buffer
20764 (or (buffer-base-buffer buffer)
20765 buffer)))
20767 (defun org-trim (s)
20768 "Remove whitespace at beginning and end of string."
20769 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20770 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20773 (defun org-wrap (string &optional width lines)
20774 "Wrap string to either a number of lines, or a width in characters.
20775 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20776 that costs. If there is a word longer than WIDTH, the text is actually
20777 wrapped to the length of that word.
20778 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20779 many lines, whatever width that takes.
20780 The return value is a list of lines, without newlines at the end."
20781 (let* ((words (org-split-string string "[ \t\n]+"))
20782 (maxword (apply 'max (mapcar 'org-string-width words)))
20783 w ll)
20784 (cond (width
20785 (org-do-wrap words (max maxword width)))
20786 (lines
20787 (setq w maxword)
20788 (setq ll (org-do-wrap words maxword))
20789 (if (<= (length ll) lines)
20791 (setq ll words)
20792 (while (> (length ll) lines)
20793 (setq w (1+ w))
20794 (setq ll (org-do-wrap words w)))
20795 ll))
20796 (t (error "Cannot wrap this")))))
20798 (defun org-do-wrap (words width)
20799 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20800 (let (lines line)
20801 (while words
20802 (setq line (pop words))
20803 (while (and words (< (+ (length line) (length (car words))) width))
20804 (setq line (concat line " " (pop words))))
20805 (setq lines (push line lines)))
20806 (nreverse lines)))
20808 (defun org-split-string (string &optional separators)
20809 "Splits STRING into substrings at SEPARATORS.
20810 No empty strings are returned if there are matches at the beginning
20811 and end of string."
20812 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20813 (start 0)
20814 notfirst
20815 (list nil))
20816 (while (and (string-match rexp string
20817 (if (and notfirst
20818 (= start (match-beginning 0))
20819 (< start (length string)))
20820 (1+ start) start))
20821 (< (match-beginning 0) (length string)))
20822 (setq notfirst t)
20823 (or (eq (match-beginning 0) 0)
20824 (and (eq (match-beginning 0) (match-end 0))
20825 (eq (match-beginning 0) start))
20826 (setq list
20827 (cons (substring string start (match-beginning 0))
20828 list)))
20829 (setq start (match-end 0)))
20830 (or (eq start (length string))
20831 (setq list
20832 (cons (substring string start)
20833 list)))
20834 (nreverse list)))
20836 (defun org-quote-vert (s)
20837 "Replace \"|\" with \"\\vert\"."
20838 (while (string-match "|" s)
20839 (setq s (replace-match "\\vert" t t s)))
20842 (defun org-uuidgen-p (s)
20843 "Is S an ID created by UUIDGEN?"
20844 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20846 (defun org-in-src-block-p (&optional inside)
20847 "Whether point is in a code source block.
20848 When INSIDE is non-nil, don't consider we are within a src block
20849 when point is at #+BEGIN_SRC or #+END_SRC."
20850 (let ((case-fold-search t) ov)
20851 (or (and (setq ov (overlays-at (point)))
20852 (memq 'org-block-background
20853 (overlay-properties (car ov))))
20854 (and (not inside)
20855 (save-match-data
20856 (save-excursion
20857 (beginning-of-line)
20858 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20860 (defun org-context ()
20861 "Return a list of contexts of the current cursor position.
20862 If several contexts apply, all are returned.
20863 Each context entry is a list with a symbol naming the context, and
20864 two positions indicating start and end of the context. Possible
20865 contexts are:
20867 :headline anywhere in a headline
20868 :headline-stars on the leading stars in a headline
20869 :todo-keyword on a TODO keyword (including DONE) in a headline
20870 :tags on the TAGS in a headline
20871 :priority on the priority cookie in a headline
20872 :item on the first line of a plain list item
20873 :item-bullet on the bullet/number of a plain list item
20874 :checkbox on the checkbox in a plain list item
20875 :table in an org-mode table
20876 :table-special on a special filed in a table
20877 :table-table in a table.el table
20878 :clocktable in a clocktable
20879 :src-block in a source block
20880 :link on a hyperlink
20881 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20882 :target on a <<target>>
20883 :radio-target on a <<<radio-target>>>
20884 :latex-fragment on a LaTeX fragment
20885 :latex-preview on a LaTeX fragment with overlaid preview image
20887 This function expects the position to be visible because it uses font-lock
20888 faces as a help to recognize the following contexts: :table-special, :link,
20889 and :keyword."
20890 (let* ((f (get-text-property (point) 'face))
20891 (faces (if (listp f) f (list f)))
20892 (case-fold-search t)
20893 (p (point)) clist o)
20894 ;; First the large context
20895 (cond
20896 ((org-at-heading-p t)
20897 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20898 (when (progn
20899 (beginning-of-line 1)
20900 (looking-at org-todo-line-tags-regexp))
20901 (push (org-point-in-group p 1 :headline-stars) clist)
20902 (push (org-point-in-group p 2 :todo-keyword) clist)
20903 (push (org-point-in-group p 4 :tags) clist))
20904 (goto-char p)
20905 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20906 (if (looking-at "\\[#[A-Z0-9]\\]")
20907 (push (org-point-in-group p 0 :priority) clist)))
20909 ((org-at-item-p)
20910 (push (org-point-in-group p 2 :item-bullet) clist)
20911 (push (list :item (point-at-bol)
20912 (save-excursion (org-end-of-item) (point)))
20913 clist)
20914 (and (org-at-item-checkbox-p)
20915 (push (org-point-in-group p 0 :checkbox) clist)))
20917 ((org-at-table-p)
20918 (push (list :table (org-table-begin) (org-table-end)) clist)
20919 (if (memq 'org-formula faces)
20920 (push (list :table-special
20921 (previous-single-property-change p 'face)
20922 (next-single-property-change p 'face)) clist)))
20923 ((org-at-table-p 'any)
20924 (push (list :table-table) clist)))
20925 (goto-char p)
20927 (let ((case-fold-search t))
20928 ;; New the "medium" contexts: clocktables, source blocks
20929 (cond ((org-in-clocktable-p)
20930 (push (list :clocktable
20931 (and (or (looking-at "#\\+BEGIN: clocktable")
20932 (search-backward "#+BEGIN: clocktable" nil t))
20933 (match-beginning 0))
20934 (and (re-search-forward "#\\+END:?" nil t)
20935 (match-end 0))) clist))
20936 ((org-in-src-block-p)
20937 (push (list :src-block
20938 (and (or (looking-at "#\\+BEGIN_SRC")
20939 (search-backward "#+BEGIN_SRC" nil t))
20940 (match-beginning 0))
20941 (and (search-forward "#+END_SRC" nil t)
20942 (match-beginning 0))) clist))))
20943 (goto-char p)
20945 ;; Now the small context
20946 (cond
20947 ((org-at-timestamp-p)
20948 (push (org-point-in-group p 0 :timestamp) clist))
20949 ((memq 'org-link faces)
20950 (push (list :link
20951 (previous-single-property-change p 'face)
20952 (next-single-property-change p 'face)) clist))
20953 ((memq 'org-special-keyword faces)
20954 (push (list :keyword
20955 (previous-single-property-change p 'face)
20956 (next-single-property-change p 'face)) clist))
20957 ((org-at-target-p)
20958 (push (org-point-in-group p 0 :target) clist)
20959 (goto-char (1- (match-beginning 0)))
20960 (if (looking-at org-radio-target-regexp)
20961 (push (org-point-in-group p 0 :radio-target) clist))
20962 (goto-char p))
20963 ((setq o (car (delq nil
20964 (mapcar
20965 (lambda (x)
20966 (if (memq x org-latex-fragment-image-overlays) x))
20967 (overlays-at (point))))))
20968 (push (list :latex-fragment
20969 (overlay-start o) (overlay-end o)) clist)
20970 (push (list :latex-preview
20971 (overlay-start o) (overlay-end o)) clist))
20972 ((org-inside-LaTeX-fragment-p)
20973 ;; FIXME: positions wrong.
20974 (push (list :latex-fragment (point) (point)) clist)))
20976 (setq clist (nreverse (delq nil clist)))
20977 clist))
20979 ;; FIXME: Compare with at-regexp-p Do we need both?
20980 (defun org-in-regexp (re &optional nlines visually)
20981 "Check if point is inside a match of regexp.
20982 Normally only the current line is checked, but you can include NLINES extra
20983 lines both before and after point into the search.
20984 If VISUALLY is set, require that the cursor is not after the match but
20985 really on, so that the block visually is on the match."
20986 (catch 'exit
20987 (let ((pos (point))
20988 (eol (point-at-eol (+ 1 (or nlines 0))))
20989 (inc (if visually 1 0)))
20990 (save-excursion
20991 (beginning-of-line (- 1 (or nlines 0)))
20992 (while (re-search-forward re eol t)
20993 (if (and (<= (match-beginning 0) pos)
20994 (>= (+ inc (match-end 0)) pos))
20995 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20997 (defun org-at-regexp-p (regexp)
20998 "Is point inside a match of REGEXP in the current line?"
20999 (catch 'exit
21000 (save-excursion
21001 (let ((pos (point)) (end (point-at-eol)))
21002 (beginning-of-line 1)
21003 (while (re-search-forward regexp end t)
21004 (if (and (<= (match-beginning 0) pos)
21005 (>= (match-end 0) pos))
21006 (throw 'exit t)))
21007 nil))))
21009 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21010 "Non-nil when point is between matches of START-RE and END-RE.
21012 Also return a non-nil value when point is on one of the matches.
21014 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21015 buffer positions. Default values are the positions of headlines
21016 surrounding the point.
21018 The functions returns a cons cell whose car (resp. cdr) is the
21019 position before START-RE (resp. after END-RE)."
21020 (save-match-data
21021 (let ((pos (point))
21022 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21023 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21024 beg end)
21025 (save-excursion
21026 ;; Point is on a block when on START-RE or if START-RE can be
21027 ;; found before it...
21028 (and (or (org-at-regexp-p start-re)
21029 (re-search-backward start-re limit-up t))
21030 (setq beg (match-beginning 0))
21031 ;; ... and END-RE after it...
21032 (goto-char (match-end 0))
21033 (re-search-forward end-re limit-down t)
21034 (> (setq end (match-end 0)) pos)
21035 ;; ... without another START-RE in-between.
21036 (goto-char (match-beginning 0))
21037 (not (re-search-backward start-re (1+ beg) t))
21038 ;; Return value.
21039 (cons beg end))))))
21041 (defun org-in-block-p (names)
21042 "Non-nil when point belongs to a block whose name belongs to NAMES.
21044 NAMES is a list of strings containing names of blocks.
21046 Return first block name matched, or nil. Beware that in case of
21047 nested blocks, the returned name may not belong to the closest
21048 block from point."
21049 (save-match-data
21050 (catch 'exit
21051 (let ((case-fold-search t)
21052 (lim-up (save-excursion (outline-previous-heading)))
21053 (lim-down (save-excursion (outline-next-heading))))
21054 (mapc (lambda (name)
21055 (let ((n (regexp-quote name)))
21056 (when (org-between-regexps-p
21057 (concat "^[ \t]*#\\+begin_" n)
21058 (concat "^[ \t]*#\\+end_" n)
21059 lim-up lim-down)
21060 (throw 'exit n))))
21061 names))
21062 nil)))
21064 (defun org-occur-in-agenda-files (regexp &optional nlines)
21065 "Call `multi-occur' with buffers for all agenda files."
21066 (interactive "sOrg-files matching: \np")
21067 (let* ((files (org-agenda-files))
21068 (tnames (mapcar 'file-truename files))
21069 (extra org-agenda-text-search-extra-files)
21071 (when (eq (car extra) 'agenda-archives)
21072 (setq extra (cdr extra))
21073 (setq files (org-add-archive-files files)))
21074 (while (setq f (pop extra))
21075 (unless (member (file-truename f) tnames)
21076 (add-to-list 'files f 'append)
21077 (add-to-list 'tnames (file-truename f) 'append)))
21078 (multi-occur
21079 (mapcar (lambda (x)
21080 (with-current-buffer
21081 (or (get-file-buffer x) (find-file-noselect x))
21082 (widen)
21083 (current-buffer)))
21084 files)
21085 regexp)))
21087 (if (boundp 'occur-mode-find-occurrence-hook)
21088 ;; Emacs 23
21089 (add-hook 'occur-mode-find-occurrence-hook
21090 (lambda ()
21091 (when (derived-mode-p 'org-mode)
21092 (org-reveal))))
21093 ;; Emacs 22
21094 (defadvice occur-mode-goto-occurrence
21095 (after org-occur-reveal activate)
21096 (and (derived-mode-p 'org-mode) (org-reveal)))
21097 (defadvice occur-mode-goto-occurrence-other-window
21098 (after org-occur-reveal activate)
21099 (and (derived-mode-p 'org-mode) (org-reveal)))
21100 (defadvice occur-mode-display-occurrence
21101 (after org-occur-reveal activate)
21102 (when (derived-mode-p 'org-mode)
21103 (let ((pos (occur-mode-find-occurrence)))
21104 (with-current-buffer (marker-buffer pos)
21105 (save-excursion
21106 (goto-char pos)
21107 (org-reveal)))))))
21109 (defun org-occur-link-in-agenda-files ()
21110 "Create a link and search for it in the agendas.
21111 The link is not stored in `org-stored-links', it is just created
21112 for the search purpose."
21113 (interactive)
21114 (let ((link (condition-case nil
21115 (org-store-link nil)
21116 (error "Unable to create a link to here"))))
21117 (org-occur-in-agenda-files (regexp-quote link))))
21119 (defun org-uniquify (list)
21120 "Remove duplicate elements from LIST."
21121 (let (res)
21122 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21123 res))
21125 (defun org-delete-all (elts list)
21126 "Remove all elements in ELTS from LIST."
21127 (while elts
21128 (setq list (delete (pop elts) list)))
21129 list)
21131 (defun org-count (cl-item cl-seq)
21132 "Count the number of occurrences of ITEM in SEQ.
21133 Taken from `count' in cl-seq.el with all keyword arguments removed."
21134 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21135 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21136 (while (< cl-start cl-end)
21137 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21138 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21139 (setq cl-start (1+ cl-start)))
21140 cl-count))
21142 (defun org-remove-if (predicate seq)
21143 "Remove everything from SEQ that fulfills PREDICATE."
21144 (let (res e)
21145 (while seq
21146 (setq e (pop seq))
21147 (if (not (funcall predicate e)) (push e res)))
21148 (nreverse res)))
21150 (defun org-remove-if-not (predicate seq)
21151 "Remove everything from SEQ that does not fulfill PREDICATE."
21152 (let (res e)
21153 (while seq
21154 (setq e (pop seq))
21155 (if (funcall predicate e) (push e res)))
21156 (nreverse res)))
21158 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21159 "Reduce two-argument FUNCTION across SEQ.
21160 Taken from `reduce' in cl-seq.el with all keyword arguments but
21161 \":initial-value\" removed."
21162 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21163 (cadr (memq :initial-value cl-keys)))
21164 (cl-seq (pop cl-seq))
21165 (t (funcall cl-func)))))
21166 (while cl-seq
21167 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21168 cl-accum))
21170 (defun org-back-over-empty-lines ()
21171 "Move backwards over whitespace, to the beginning of the first empty line.
21172 Returns the number of empty lines passed."
21173 (let ((pos (point)))
21174 (if (cdr (assoc 'heading org-blank-before-new-entry))
21175 (skip-chars-backward " \t\n\r")
21176 (unless (eobp)
21177 (forward-line -1)))
21178 (beginning-of-line 2)
21179 (goto-char (min (point) pos))
21180 (count-lines (point) pos)))
21182 (defun org-skip-whitespace ()
21183 (skip-chars-forward " \t\n\r"))
21185 (defun org-point-in-group (point group &optional context)
21186 "Check if POINT is in match-group GROUP.
21187 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21188 match. If the match group does not exist or point is not inside it,
21189 return nil."
21190 (and (match-beginning group)
21191 (>= point (match-beginning group))
21192 (<= point (match-end group))
21193 (if context
21194 (list context (match-beginning group) (match-end group))
21195 t)))
21197 (defun org-switch-to-buffer-other-window (&rest args)
21198 "Switch to buffer in a second window on the current frame.
21199 In particular, do not allow pop-up frames.
21200 Returns the newly created buffer."
21201 (org-no-popups
21202 (apply 'switch-to-buffer-other-window args)))
21204 (defun org-combine-plists (&rest plists)
21205 "Create a single property list from all plists in PLISTS.
21206 The process starts by copying the first list, and then setting properties
21207 from the other lists. Settings in the last list are the most significant
21208 ones and overrule settings in the other lists."
21209 (let ((rtn (copy-sequence (pop plists)))
21210 p v ls)
21211 (while plists
21212 (setq ls (pop plists))
21213 (while ls
21214 (setq p (pop ls) v (pop ls))
21215 (setq rtn (plist-put rtn p v))))
21216 rtn))
21218 (defun org-replace-escapes (string table)
21219 "Replace %-escapes in STRING with values in TABLE.
21220 TABLE is an association list with keys like \"%a\" and string values.
21221 The sequences in STRING may contain normal field width and padding information,
21222 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21223 so values can contain further %-escapes if they are define later in TABLE."
21224 (let ((tbl (copy-alist table))
21225 (case-fold-search nil)
21226 (pchg 0)
21227 e re rpl)
21228 (while (setq e (pop tbl))
21229 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21230 (when (and (cdr e) (string-match re (cdr e)))
21231 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21232 (safe "SREF"))
21233 (add-text-properties 0 3 (list 'sref sref) safe)
21234 (setcdr e (replace-match safe t t (cdr e)))))
21235 (while (string-match re string)
21236 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21237 (cdr e)))
21238 (setq string (replace-match rpl t t string))))
21239 (while (setq pchg (next-property-change pchg string))
21240 (let ((sref (get-text-property pchg 'sref string)))
21241 (when (and sref (string-match "SREF" string pchg))
21242 (setq string (replace-match sref t t string)))))
21243 string))
21245 (defun org-sublist (list start end)
21246 "Return a section of LIST, from START to END.
21247 Counting starts at 1."
21248 (let (rtn (c start))
21249 (setq list (nthcdr (1- start) list))
21250 (while (and list (<= c end))
21251 (push (pop list) rtn)
21252 (setq c (1+ c)))
21253 (nreverse rtn)))
21255 (defun org-find-base-buffer-visiting (file)
21256 "Like `find-buffer-visiting' but always return the base buffer and
21257 not an indirect buffer."
21258 (let ((buf (or (get-file-buffer file)
21259 (find-buffer-visiting file))))
21260 (if buf
21261 (or (buffer-base-buffer buf) buf)
21262 nil)))
21264 (defun org-image-file-name-regexp (&optional extensions)
21265 "Return regexp matching the file names of images.
21266 If EXTENSIONS is given, only match these."
21267 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21268 (image-file-name-regexp)
21269 (let ((image-file-name-extensions
21270 (or extensions
21271 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21272 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21273 (concat "\\."
21274 (regexp-opt (nconc (mapcar 'upcase
21275 image-file-name-extensions)
21276 image-file-name-extensions)
21278 "\\'"))))
21280 (defun org-file-image-p (file &optional extensions)
21281 "Return non-nil if FILE is an image."
21282 (save-match-data
21283 (string-match (org-image-file-name-regexp extensions) file)))
21285 (defun org-get-cursor-date (&optional with-time)
21286 "Return the date at cursor in as a time.
21287 This works in the calendar and in the agenda, anywhere else it just
21288 returns the current time.
21289 If WITH-TIME is non-nil, returns the time of the event at point (in
21290 the agenda) or the current time of the day."
21291 (let (date day defd tp tm hod mod)
21292 (when with-time
21293 (setq tp (get-text-property (point) 'time))
21294 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21295 (setq hod (string-to-number (match-string 1 tp))
21296 mod (string-to-number (match-string 2 tp))))
21297 (or tp (setq hod (nth 2 (decode-time (current-time)))
21298 mod (nth 1 (decode-time (current-time))))))
21299 (cond
21300 ((eq major-mode 'calendar-mode)
21301 (setq date (calendar-cursor-to-date)
21302 defd (encode-time 0 (or mod 0) (or hod 0)
21303 (nth 1 date) (nth 0 date) (nth 2 date))))
21304 ((eq major-mode 'org-agenda-mode)
21305 (setq day (get-text-property (point) 'day))
21306 (if day
21307 (setq date (calendar-gregorian-from-absolute day)
21308 defd (encode-time 0 (or mod 0) (or hod 0)
21309 (nth 1 date) (nth 0 date) (nth 2 date))))))
21310 (or defd (current-time))))
21312 (defun org-mark-subtree (&optional up)
21313 "Mark the current subtree.
21314 This puts point at the start of the current subtree, and mark at
21315 the end. If a numeric prefix UP is given, move up into the
21316 hierarchy of headlines by UP levels before marking the subtree."
21317 (interactive "P")
21318 (org-with-limited-levels
21319 (cond ((org-at-heading-p) (beginning-of-line))
21320 ((org-before-first-heading-p) (error "Not in a subtree"))
21321 (t (outline-previous-visible-heading 1))))
21322 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21323 (if (org-called-interactively-p 'any)
21324 (call-interactively 'org-mark-element)
21325 (org-mark-element)))
21328 ;;; Macros
21330 ;; Macros are expanded with `org-macro-replace-all', which relies
21331 ;; internally on `org-macro-expand'.
21333 ;; Default templates for expansion are stored in the buffer-local
21334 ;; variable `org-macro-templates'. This variable is updated by
21335 ;; `org-macro-initialize-templates'.
21337 ;; Along with macros defined through #+MACRO: keyword, default
21338 ;; templates include the following hard-coded macros:
21339 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21340 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21342 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21343 ;; {{{title}}} will also be provided.
21346 (defvar org-macro-templates nil
21347 "Alist containing all macro templates in current buffer.
21348 Associations are in the shape of (NAME . TEMPLATE) where NAME
21349 stands for macro's name and template for its replacement value,
21350 both as strings. This is an internal variable. Do not set it
21351 directly, use instead:
21353 #+MACRO: name template")
21354 (make-variable-buffer-local 'org-macro-templates)
21356 (defun org-macro-expand (macro templates)
21357 "Return expanded MACRO, as a string.
21358 MACRO is an object, obtained, for example, with
21359 `org-element-context'. TEMPLATES is an alist of templates used
21360 for expansion. See `org-macro-templates' for a buffer-local
21361 default value. Return nil if no template was found."
21362 (let ((template
21363 ;; Macro names are case-insensitive.
21364 (cdr (assoc-string (org-element-property :key macro) templates t))))
21365 (when template
21366 (let ((value (replace-regexp-in-string
21367 "\\$[0-9]+"
21368 (lambda (arg)
21369 (or (nth (1- (string-to-number (substring arg 1)))
21370 (org-element-property :args macro))
21371 ;; No argument provided: remove
21372 ;; place-holder.
21373 ""))
21374 template)))
21375 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21376 (when (string-match "\\`(eval\\>" value)
21377 (setq value (eval (read value))))
21378 ;; Return string.
21379 (format "%s" (or value ""))))))
21381 (defun org-macro-replace-all (templates)
21382 "Replace all macros in current buffer by their expansion.
21383 TEMPLATES is an alist of templates used for expansion. See
21384 `org-macro-templates' for a buffer-local default value."
21385 (save-excursion
21386 (goto-char (point-min))
21387 (let (record)
21388 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21389 (let ((object (org-element-context)))
21390 (when (eq (org-element-type object) 'macro)
21391 (let* ((value (org-macro-expand object templates))
21392 (begin (org-element-property :begin object))
21393 (signature (list begin
21394 object
21395 (org-element-property :args object))))
21396 ;; Avoid circular dependencies by checking if the same
21397 ;; macro with the same arguments is expanded at the same
21398 ;; position twice.
21399 (if (member signature record)
21400 (error "Circular macro expansion: %s"
21401 (org-element-property :key object))
21402 (when value
21403 (push signature record)
21404 (delete-region
21405 begin
21406 ;; Preserve white spaces after the macro.
21407 (progn (goto-char (org-element-property :end object))
21408 (skip-chars-backward " \t")
21409 (point)))
21410 ;; Leave point before replacement in case of recursive
21411 ;; expansions.
21412 (save-excursion (insert value)))))))))))
21414 (defun org-macro-initialize-templates ()
21415 "Collect macro templates defined in current buffer.
21416 Templates are stored in buffer-local variable
21417 `org-macro-templates'. In addition to buffer-defined macros, the
21418 function installs the following ones: \"property\",
21419 \"time\". and, if the buffer is associated to a file,
21420 \"input-file\" and \"modification-time\"."
21421 (let ((case-fold-search t)
21422 (set-template
21423 (lambda (cell)
21424 ;; Add CELL to `org-macro-templates' if there's no
21425 ;; association matching its name already. Otherwise,
21426 ;; replace old association with the new one in that
21427 ;; variable.
21428 (let ((old-template (assoc (car cell) org-macro-templates)))
21429 (if old-template (setcdr old-template (cdr cell))
21430 (push cell org-macro-templates))))))
21431 ;; Install buffer-local macros.
21432 (org-with-wide-buffer
21433 (goto-char (point-min))
21434 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21435 (let ((element (org-element-at-point)))
21436 (when (eq (org-element-type element) 'keyword)
21437 (let ((value (org-element-property :value element)))
21438 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21439 (funcall set-template
21440 (cons (match-string 1 value)
21441 (or (match-string 2 value) "")))))))))
21442 ;; Install hard-coded macros.
21443 (mapc (lambda (cell) (funcall set-template cell))
21444 (list
21445 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21446 (cons "time" "(eval (format-time-string \"$1\"))")))
21447 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21448 (when (and visited-file (file-exists-p visited-file))
21449 (mapc (lambda (cell) (funcall set-template cell))
21450 (list
21451 (cons "input-file" (file-name-nondirectory visited-file))
21452 (cons "modification-time"
21453 (format "(eval (format-time-string \"$1\" '%s))"
21454 (prin1-to-string
21455 (nth 5 (file-attributes visited-file)))))))))))
21458 ;;; Indentation
21460 (defun org-indent-line ()
21461 "Indent line depending on context."
21462 (interactive)
21463 (let* ((pos (point))
21464 (itemp (org-at-item-p))
21465 (case-fold-search t)
21466 (org-drawer-regexp (or org-drawer-regexp "\000"))
21467 (inline-task-p (and (featurep 'org-inlinetask)
21468 (org-inlinetask-in-task-p)))
21469 (inline-re (and inline-task-p
21470 (org-inlinetask-outline-regexp)))
21471 column)
21472 (if (and orgstruct-is-++ (eq pos (point)))
21473 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21474 (indent-according-to-mode))
21475 (beginning-of-line 1)
21476 (cond
21477 ;; Headings
21478 ((looking-at org-outline-regexp) (setq column 0))
21479 ;; Footnote definition
21480 ((looking-at org-footnote-definition-re) (setq column 0))
21481 ;; Literal examples
21482 ((looking-at "[ \t]*:\\( \\|$\\)")
21483 (setq column (org-get-indentation))) ; do nothing
21484 ;; Lists
21485 ((ignore-errors (goto-char (org-in-item-p)))
21486 (setq column (if itemp
21487 (org-get-indentation)
21488 (org-list-item-body-column (point))))
21489 (goto-char pos))
21490 ;; Drawers
21491 ((and (looking-at "[ \t]*:END:")
21492 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21493 (save-excursion
21494 (goto-char (1- (match-beginning 1)))
21495 (setq column (current-column))))
21496 ;; Special blocks
21497 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21498 (save-excursion
21499 (re-search-backward
21500 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21501 (setq column (org-get-indentation (match-string 0))))
21502 ((and (not (looking-at "[ \t]*#\\+begin_"))
21503 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21504 (save-excursion
21505 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21506 (setq column
21507 (cond ((equal (downcase (match-string 1)) "src")
21508 ;; src blocks: let `org-edit-src-exit' handle them
21509 (org-get-indentation))
21510 ((equal (downcase (match-string 1)) "example")
21511 (max (org-get-indentation)
21512 (org-get-indentation (match-string 0))))
21514 (org-get-indentation (match-string 0))))))
21515 ;; This line has nothing special, look at the previous relevant
21516 ;; line to compute indentation
21518 (beginning-of-line 0)
21519 (while (and (not (bobp))
21520 (not (looking-at org-table-line-regexp))
21521 (not (looking-at org-drawer-regexp))
21522 ;; When point started in an inline task, do not move
21523 ;; above task starting line.
21524 (not (and inline-task-p (looking-at inline-re)))
21525 ;; Skip drawers, blocks, empty lines, verbatim,
21526 ;; comments, tables, footnotes definitions, lists,
21527 ;; inline tasks.
21528 (or (and (looking-at "[ \t]*:END:")
21529 (re-search-backward org-drawer-regexp nil t))
21530 (and (looking-at "[ \t]*#\\+end_")
21531 (re-search-backward "[ \t]*#\\+begin_"nil t))
21532 (looking-at "[ \t]*[\n:#|]")
21533 (looking-at org-footnote-definition-re)
21534 (and (ignore-errors (goto-char (org-in-item-p)))
21535 (goto-char
21536 (org-list-get-top-point (org-list-struct))))
21537 (and (not inline-task-p)
21538 (featurep 'org-inlinetask)
21539 (org-inlinetask-in-task-p)
21540 (or (org-inlinetask-goto-beginning) t))))
21541 (beginning-of-line 0))
21542 (cond
21543 ;; There was an heading above.
21544 ((looking-at "\\*+[ \t]+")
21545 (if (not org-adapt-indentation)
21546 (setq column 0)
21547 (goto-char (match-end 0))
21548 (setq column (current-column))))
21549 ;; A drawer had started and is unfinished
21550 ((looking-at org-drawer-regexp)
21551 (goto-char (1- (match-beginning 1)))
21552 (setq column (current-column)))
21553 ;; Else, nothing noticeable found: get indentation and go on.
21554 (t (setq column (org-get-indentation))))))
21555 ;; Now apply indentation and move cursor accordingly
21556 (goto-char pos)
21557 (if (<= (current-column) (current-indentation))
21558 (org-indent-line-to column)
21559 (save-excursion (org-indent-line-to column)))
21560 ;; Special polishing for properties, see `org-property-format'
21561 (setq column (current-column))
21562 (beginning-of-line 1)
21563 (if (looking-at
21564 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21565 (replace-match (concat (match-string 1)
21566 (format org-property-format
21567 (match-string 2) (match-string 3)))
21568 t t))
21569 (org-move-to-column column))))
21571 (defun org-indent-drawer ()
21572 "Indent the drawer at point."
21573 (interactive)
21574 (let ((p (point))
21575 (e (and (save-excursion (re-search-forward ":END:" nil t))
21576 (match-end 0)))
21577 (folded
21578 (save-excursion
21579 (end-of-line)
21580 (when (overlays-at (point))
21581 (member 'invisible (overlay-properties
21582 (car (overlays-at (point)))))))))
21583 (when folded (org-cycle))
21584 (indent-for-tab-command)
21585 (while (and (move-beginning-of-line 2) (< (point) e))
21586 (indent-for-tab-command))
21587 (goto-char p)
21588 (when folded (org-cycle)))
21589 (message "Drawer at point indented"))
21591 (defun org-indent-block ()
21592 "Indent the block at point."
21593 (interactive)
21594 (let ((p (point))
21595 (case-fold-search t)
21596 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21597 (match-end 0)))
21598 (folded
21599 (save-excursion
21600 (end-of-line)
21601 (when (overlays-at (point))
21602 (member 'invisible (overlay-properties
21603 (car (overlays-at (point)))))))))
21604 (when folded (org-cycle))
21605 (indent-for-tab-command)
21606 (while (and (move-beginning-of-line 2) (< (point) e))
21607 (indent-for-tab-command))
21608 (goto-char p)
21609 (when folded (org-cycle)))
21610 (message "Block at point indented"))
21612 (defun org-indent-region (start end)
21613 "Indent region."
21614 (interactive "r")
21615 (save-excursion
21616 (let ((line-end (org-current-line end)))
21617 (goto-char start)
21618 (while (< (org-current-line) line-end)
21619 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21620 (t (call-interactively 'org-indent-line)))
21621 (move-beginning-of-line 2)))))
21624 ;;; Filling
21626 ;; We use our own fill-paragraph and auto-fill functions.
21628 ;; `org-fill-paragraph' relies on adaptive filling and context
21629 ;; checking. Appropriate `fill-prefix' is computed with
21630 ;; `org-adaptive-fill-function'.
21632 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21633 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21634 ;; `org-adaptive-fill-function' value. Internally,
21635 ;; `org-comment-line-break-function' breaks the line.
21637 ;; `org-setup-filling' installs filling and auto-filling related
21638 ;; variables during `org-mode' initialization.
21640 (defun org-setup-filling ()
21641 (interactive)
21642 ;; Prevent auto-fill from inserting unwanted new items.
21643 (when (boundp 'fill-nobreak-predicate)
21644 (org-set-local
21645 'fill-nobreak-predicate
21646 (org-uniquify
21647 (append fill-nobreak-predicate
21648 '(org-fill-paragraph-separate-nobreak-p
21649 org-fill-line-break-nobreak-p
21650 org-fill-paragraph-with-timestamp-nobreak-p)))))
21651 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21652 (org-set-local 'auto-fill-inhibit-regexp nil)
21653 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21654 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21655 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21657 (defvar org-element-paragraph-separate) ; org-element.el
21658 (defun org-fill-paragraph-separate-nobreak-p ()
21659 "Non-nil when a line break at point would insert a new item."
21660 (looking-at (substring org-element-paragraph-separate 1)))
21662 (defun org-fill-line-break-nobreak-p ()
21663 "Non-nil when a line break at point would create an Org line break."
21664 (save-excursion
21665 (skip-chars-backward "[ \t]")
21666 (skip-chars-backward "\\\\")
21667 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21669 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21670 "Non-nil when a line break at point would insert a new item."
21671 (and (org-at-timestamp-p t)
21672 (not (looking-at org-ts-regexp-both))))
21674 (declare-function message-in-body-p "message" ())
21675 (defvar orgtbl-line-start-regexp) ; From org-table.el
21676 (defun org-adaptive-fill-function ()
21677 "Compute a fill prefix for the current line.
21678 Return fill prefix, as a string, or nil if current line isn't
21679 meant to be filled."
21680 (let (prefix)
21681 (catch 'exit
21682 (when (derived-mode-p 'message-mode)
21683 (save-excursion
21684 (beginning-of-line)
21685 (cond ((or (not (message-in-body-p))
21686 (looking-at orgtbl-line-start-regexp))
21687 (throw 'exit nil))
21688 ((looking-at message-cite-prefix-regexp)
21689 (throw 'exit (match-string-no-properties 0)))
21690 ((looking-at org-outline-regexp)
21691 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21692 (org-with-wide-buffer
21693 (let* ((p (line-beginning-position))
21694 (element (save-excursion (beginning-of-line)
21695 (org-element-at-point)))
21696 (type (org-element-type element))
21697 (post-affiliated (org-element-property :post-affiliated element)))
21698 (unless (and post-affiliated (< p post-affiliated))
21699 (case type
21700 (comment (looking-at "[ \t]*# ?") (match-string 0))
21701 (footnote-definition "")
21702 ((item plain-list)
21703 (make-string (org-list-item-body-column
21704 (or post-affiliated
21705 (org-element-property :begin element)))
21706 ? ))
21707 (paragraph
21708 ;; Fill prefix is usually the same as the current line,
21709 ;; except if the paragraph is at the beginning of an item.
21710 (let ((parent (org-element-property :parent element)))
21711 (cond ((eq (org-element-type parent) 'item)
21712 (make-string (org-list-item-body-column
21713 (org-element-property :begin parent))
21714 ? ))
21715 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21716 (match-string 0))
21717 (t ""))))
21718 (comment-block
21719 ;; Only fill contents if P is within block boundaries.
21720 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21721 (forward-line)
21722 (point)))
21723 (cend (save-excursion
21724 (goto-char (org-element-property :end element))
21725 (skip-chars-backward " \r\t\n")
21726 (line-beginning-position))))
21727 (when (and (>= p cbeg) (< p cend))
21728 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21729 (match-string 0)
21730 "")))))))))))
21732 (declare-function message-goto-body "message" ())
21733 (defvar message-cite-prefix-regexp) ; From message.el
21734 (defvar org-element-all-objects) ; From org-element.el
21735 (defun org-fill-paragraph (&optional justify)
21736 "Fill element at point, when applicable.
21738 This function only applies to comment blocks, comments, example
21739 blocks and paragraphs. Also, as a special case, re-align table
21740 when point is at one.
21742 If JUSTIFY is non-nil (interactively, with prefix argument),
21743 justify as well. If `sentence-end-double-space' is non-nil, then
21744 period followed by one space does not end a sentence, so don't
21745 break a line there. The variable `fill-column' controls the
21746 width for filling.
21748 For convenience, when point is at a plain list, an item or
21749 a footnote definition, try to fill the first paragraph within."
21750 (interactive)
21751 (if (and (derived-mode-p 'message-mode)
21752 (or (not (message-in-body-p))
21753 (save-excursion (move-beginning-of-line 1)
21754 (looking-at message-cite-prefix-regexp))))
21755 ;; First ensure filling is correct in message-mode.
21756 (let ((fill-paragraph-function
21757 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21758 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21759 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21760 (paragraph-separate
21761 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21762 (fill-paragraph nil))
21763 (save-excursion
21764 ;; Move to end of line in order to get the first paragraph
21765 ;; within a plain list or a footnote definition.
21766 (end-of-line)
21767 (let ((element (org-element-at-point)))
21768 ;; First check if point is in a blank line at the beginning of
21769 ;; the buffer. In that case, ignore filling.
21770 (if (< (point) (org-element-property :begin element)) t
21771 (case (org-element-type element)
21772 ;; Use major mode filling function is src blocks.
21773 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21774 ;; Align Org tables, leave table.el tables as-is.
21775 (table-row (org-table-align) t)
21776 (table
21777 (when (eq (org-element-property :type element) 'org)
21778 (org-table-align))
21780 (paragraph
21781 ;; Paragraphs may contain `line-break' type objects.
21782 (let ((beg (max (point-min)
21783 (org-element-property :contents-begin element)))
21784 (end (min (point-max)
21785 (org-element-property :contents-end element))))
21786 ;; Do nothing if point is at an affiliated keyword.
21787 (if (< (point) beg) t
21788 (when (derived-mode-p 'message-mode)
21789 ;; In `message-mode', do not fill following
21790 ;; citation in current paragraph nor text before
21791 ;; message body.
21792 (let ((body-start (save-excursion (message-goto-body))))
21793 (when body-start (setq beg (max body-start beg))))
21794 (when (save-excursion
21795 (re-search-forward
21796 (concat "^" message-cite-prefix-regexp) end t))
21797 (setq end (match-beginning 0))))
21798 ;; Fill paragraph, taking line breaks into
21799 ;; consideration. For that, slice the paragraph
21800 ;; using line breaks as separators, and fill the
21801 ;; parts in reverse order to avoid messing with
21802 ;; markers.
21803 (save-excursion
21804 (goto-char end)
21805 (mapc
21806 (lambda (pos)
21807 (fill-region-as-paragraph pos (point) justify)
21808 (goto-char pos))
21809 ;; Find the list of ending positions for line
21810 ;; breaks in the current paragraph. Add paragraph
21811 ;; beginning to include first slice.
21812 (nreverse
21813 (cons
21815 (org-element-map
21816 (org-element--parse-objects
21817 beg end nil org-element-all-objects)
21818 'line-break
21819 (lambda (lb) (org-element-property :end lb)))))))
21820 t)))
21821 ;; Contents of `comment-block' type elements should be
21822 ;; filled as plain text, but only if point is within block
21823 ;; markers.
21824 (comment-block
21825 (let* ((case-fold-search t)
21826 (beg (save-excursion
21827 (goto-char (org-element-property :begin element))
21828 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21829 (forward-line)
21830 (point)))
21831 (end (save-excursion
21832 (goto-char (org-element-property :end element))
21833 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21834 (line-beginning-position))))
21835 (when (and (>= (point) beg) (< (point) end))
21836 (fill-region-as-paragraph
21837 (save-excursion
21838 (end-of-line)
21839 (re-search-backward "^[ \t]*$" beg 'move)
21840 (line-beginning-position))
21841 (save-excursion
21842 (beginning-of-line)
21843 (re-search-forward "^[ \t]*$" end 'move)
21844 (line-beginning-position))
21845 justify)))
21847 ;; Fill comments.
21848 (comment (fill-comment-paragraph justify))
21849 ;; Ignore every other element.
21850 (otherwise t)))))))
21852 (defun org-auto-fill-function ()
21853 "Auto-fill function."
21854 ;; Check if auto-filling is meaningful.
21855 (let ((fc (current-fill-column)))
21856 (when (and fc (> (current-column) fc))
21857 (let* ((fill-prefix (org-adaptive-fill-function))
21858 ;; Enforce empty fill prefix, if required. Otherwise, it
21859 ;; will be computed again.
21860 (adaptive-fill-mode (not (equal fill-prefix ""))))
21861 (when fill-prefix (do-auto-fill))))))
21863 (defun org-comment-line-break-function (&optional soft)
21864 "Break line at point and indent, continuing comment if within one.
21865 The inserted newline is marked hard if variable
21866 `use-hard-newlines' is true, unless optional argument SOFT is
21867 non-nil."
21868 (if soft (insert-and-inherit ?\n) (newline 1))
21869 (save-excursion (forward-char -1) (delete-horizontal-space))
21870 (delete-horizontal-space)
21871 (indent-to-left-margin)
21872 (insert-before-markers-and-inherit fill-prefix))
21875 ;;; Comments
21877 ;; Org comments syntax is quite complex. It requires the entire line
21878 ;; to be just a comment. Also, even with the right syntax at the
21879 ;; beginning of line, some some elements (i.e. verse-block or
21880 ;; example-block) don't accept comments. Usual Emacs comment commands
21881 ;; cannot cope with those requirements. Therefore, Org replaces them.
21883 ;; Org still relies on `comment-dwim', but cannot trust
21884 ;; `comment-only-p'. So, `comment-region-function' and
21885 ;; `uncomment-region-function' both point
21886 ;; to`org-comment-or-uncomment-region'. Eventually,
21887 ;; `org-insert-comment' takes care of insertion of comments at the
21888 ;; beginning of line.
21890 ;; `org-setup-comments-handling' install comments related variables
21891 ;; during `org-mode' initialization.
21893 (defun org-setup-comments-handling ()
21894 (interactive)
21895 (org-set-local 'comment-use-syntax nil)
21896 (org-set-local 'comment-start "# ")
21897 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21898 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21899 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21900 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21902 (defun org-insert-comment ()
21903 "Insert an empty comment above current line.
21904 If the line is empty, insert comment at its beginning."
21905 (beginning-of-line)
21906 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21907 (org-indent-line)
21908 (insert "# "))
21910 (defvar comment-empty-lines) ; From newcomment.el.
21911 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21912 "Comment or uncomment each non-blank line in the region.
21913 Uncomment each non-blank line between BEG and END if it only
21914 contains commented lines. Otherwise, comment them."
21915 (save-restriction
21916 ;; Restrict region
21917 (narrow-to-region (save-excursion (goto-char beg)
21918 (skip-chars-forward " \r\t\n" end)
21919 (line-beginning-position))
21920 (save-excursion (goto-char end)
21921 (skip-chars-backward " \r\t\n" beg)
21922 (line-end-position)))
21923 (let ((uncommentp
21924 ;; UNCOMMENTP is non-nil when every non blank line between
21925 ;; BEG and END is a comment.
21926 (save-excursion
21927 (goto-char (point-min))
21928 (while (and (not (eobp))
21929 (let ((element (org-element-at-point)))
21930 (and (eq (org-element-type element) 'comment)
21931 (goto-char (min (point-max)
21932 (org-element-property
21933 :end element)))))))
21934 (eobp))))
21935 (if uncommentp
21936 ;; Only blank lines and comments in region: uncomment it.
21937 (save-excursion
21938 (goto-char (point-min))
21939 (while (not (eobp))
21940 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21941 (replace-match "" nil nil nil 1))
21942 (forward-line)))
21943 ;; Comment each line in region.
21944 (let ((min-indent (point-max)))
21945 ;; First find the minimum indentation across all lines.
21946 (save-excursion
21947 (goto-char (point-min))
21948 (while (and (not (eobp)) (not (zerop min-indent)))
21949 (unless (looking-at "[ \t]*$")
21950 (setq min-indent (min min-indent (current-indentation))))
21951 (forward-line)))
21952 ;; Then loop over all lines.
21953 (save-excursion
21954 (goto-char (point-min))
21955 (while (not (eobp))
21956 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21957 (org-move-to-column min-indent t)
21958 (insert comment-start))
21959 (forward-line))))))))
21962 ;;; Planning
21964 ;; This section contains tools to operate on timestamp objects, as
21965 ;; returned by, e.g. `org-element-context'.
21967 (defun org-timestamp-has-time-p (timestamp)
21968 "Non-nil when TIMESTAMP has a time specified."
21969 (org-element-property :hour-start timestamp))
21971 (defun org-timestamp-format (timestamp format &optional end utc)
21972 "Format a TIMESTAMP element into a string.
21974 FORMAT is a format specifier to be passed to
21975 `format-time-string'.
21977 When optional argument END is non-nil, use end of date-range or
21978 time-range, if possible.
21980 When optional argument UTC is non-nil, time will be expressed as
21981 Universal Time."
21982 (format-time-string
21983 format
21984 (apply 'encode-time
21985 (cons 0
21986 (mapcar
21987 (lambda (prop) (or (org-element-property prop timestamp) 0))
21988 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21989 '(:minute-start :hour-start :day-start :month-start
21990 :year-start)))))
21991 utc))
21993 (defun org-timestamp-split-range (timestamp &optional end)
21994 "Extract a timestamp object from a date or time range.
21996 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21997 the end of the range. Otherwise, extract its start.
21999 Return a new timestamp object sharing the same parent as
22000 TIMESTAMP."
22001 (let ((type (org-element-property :type timestamp)))
22002 (if (memq type '(active inactive diary)) timestamp
22003 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22004 ;; Set new type.
22005 (org-element-put-property
22006 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22007 ;; Copy start properties over end properties if END is
22008 ;; non-nil. Otherwise, copy end properties over `start' ones.
22009 (let ((p-alist '((:minute-start . :minute-end)
22010 (:hour-start . :hour-end)
22011 (:day-start . :day-end)
22012 (:month-start . :month-end)
22013 (:year-start . :year-end))))
22014 (dolist (p-cell p-alist)
22015 (org-element-put-property
22016 split-ts
22017 (funcall (if end 'car 'cdr) p-cell)
22018 (org-element-property
22019 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22020 ;; Eventually refresh `:raw-value'.
22021 (org-element-put-property split-ts :raw-value nil)
22022 (org-element-put-property
22023 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22025 (defun org-timestamp-translate (timestamp &optional boundary)
22026 "Apply `org-translate-time' on a TIMESTAMP object.
22027 When optional argument BOUNDARY is non-nil, it is either the
22028 symbol `start' or `end'. In this case, only translate the
22029 starting or ending part of TIMESTAMP if it is a date or time
22030 range. Otherwise, translate both parts."
22031 (if (and (not boundary)
22032 (memq (org-element-property :type timestamp)
22033 '(active-range inactive-range)))
22034 (concat
22035 (org-translate-time
22036 (org-element-property :raw-value
22037 (org-timestamp-split-range timestamp)))
22038 "--"
22039 (org-translate-time
22040 (org-element-property :raw-value
22041 (org-timestamp-split-range timestamp t))))
22042 (org-translate-time
22043 (org-element-property
22044 :raw-value
22045 (if (not boundary) timestamp
22046 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22050 ;;; Other stuff.
22052 (defun org-toggle-fixed-width-section (arg)
22053 "Toggle the fixed-width export.
22054 If there is no active region, the QUOTE keyword at the current headline is
22055 inserted or removed. When present, it causes the text between this headline
22056 and the next to be exported as fixed-width text, and unmodified.
22057 If there is an active region, this command adds or removes a colon as the
22058 first character of this line. If the first character of a line is a colon,
22059 this line is also exported in fixed-width font."
22060 (interactive "P")
22061 (let* ((cc 0)
22062 (regionp (org-region-active-p))
22063 (beg (if regionp (region-beginning) (point)))
22064 (end (if regionp (region-end)))
22065 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22066 (case-fold-search nil)
22067 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22068 off)
22069 (if regionp
22070 (save-excursion
22071 (goto-char beg)
22072 (setq cc (current-column))
22073 (beginning-of-line 1)
22074 (setq off (looking-at re))
22075 (while (> nlines 0)
22076 (setq nlines (1- nlines))
22077 (beginning-of-line 1)
22078 (cond
22079 (arg
22080 (org-move-to-column cc t)
22081 (insert ": \n")
22082 (forward-line -1))
22083 ((and off (looking-at re))
22084 (replace-match "" t t nil 1))
22085 ((not off) (org-move-to-column cc t) (insert ": ")))
22086 (forward-line 1)))
22087 (save-excursion
22088 (org-back-to-heading)
22089 (cond
22090 ((looking-at (format org-heading-keyword-regexp-format
22091 org-quote-string))
22092 (goto-char (match-end 1))
22093 (looking-at (concat " +" org-quote-string))
22094 (replace-match "" t t)
22095 (when (eolp) (insert " ")))
22096 ((looking-at org-outline-regexp)
22097 (goto-char (match-end 0))
22098 (insert org-quote-string " ")))))))
22100 (defun org-reftex-citation ()
22101 "Use reftex-citation to insert a citation into the buffer.
22102 This looks for a line like
22104 #+BIBLIOGRAPHY: foo plain option:-d
22106 and derives from it that foo.bib is the bibliography file relevant
22107 for this document. It then installs the necessary environment for RefTeX
22108 to work in this buffer and calls `reftex-citation' to insert a citation
22109 into the buffer.
22111 Export of such citations to both LaTeX and HTML is handled by the contributed
22112 package org-exp-bibtex by Taru Karttunen."
22113 (interactive)
22114 (let ((reftex-docstruct-symbol 'rds)
22115 (reftex-cite-format "\\cite{%l}")
22116 rds bib)
22117 (save-excursion
22118 (save-restriction
22119 (widen)
22120 (let ((case-fold-search t)
22121 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22122 (if (not (save-excursion
22123 (or (re-search-forward re nil t)
22124 (re-search-backward re nil t))))
22125 (error "No bibliography defined in file")
22126 (setq bib (concat (match-string 1) ".bib")
22127 rds (list (list 'bib bib)))))))
22128 (call-interactively 'reftex-citation)))
22130 ;;;; Functions extending outline functionality
22132 (defun org-beginning-of-line (&optional arg)
22133 "Go to the beginning of the current line. If that is invisible, continue
22134 to a visible line beginning. This makes the function of C-a more intuitive.
22135 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22136 first attempt, and only move to after the tags when the cursor is already
22137 beyond the end of the headline."
22138 (interactive "P")
22139 (let ((pos (point))
22140 (special (if (consp org-special-ctrl-a/e)
22141 (car org-special-ctrl-a/e)
22142 org-special-ctrl-a/e))
22143 refpos)
22144 (if (org-bound-and-true-p visual-line-mode)
22145 (beginning-of-visual-line 1)
22146 (beginning-of-line 1))
22147 (if (and arg (fboundp 'move-beginning-of-line))
22148 (call-interactively 'move-beginning-of-line)
22149 (if (bobp)
22151 (backward-char 1)
22152 (if (org-truely-invisible-p)
22153 (while (and (not (bobp)) (org-truely-invisible-p))
22154 (backward-char 1)
22155 (beginning-of-line 1))
22156 (forward-char 1))))
22157 (when special
22158 (cond
22159 ((and (looking-at org-complex-heading-regexp)
22160 (= (char-after (match-end 1)) ?\ ))
22161 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22162 (point-at-eol)))
22163 (goto-char
22164 (if (eq special t)
22165 (cond ((> pos refpos) refpos)
22166 ((= pos (point)) refpos)
22167 (t (point)))
22168 (cond ((> pos (point)) (point))
22169 ((not (eq last-command this-command)) (point))
22170 (t refpos)))))
22171 ((org-at-item-p)
22172 ;; Being at an item and not looking at an the item means point
22173 ;; was previously moved to beginning of a visual line, which
22174 ;; doesn't contain the item. Therefore, do nothing special,
22175 ;; just stay here.
22176 (when (looking-at org-list-full-item-re)
22177 ;; Set special position at first white space character after
22178 ;; bullet, and check-box, if any.
22179 (let ((after-bullet
22180 (let ((box (match-end 3)))
22181 (if (not box) (match-end 1)
22182 (let ((after (char-after box)))
22183 (if (and after (= after ? )) (1+ box) box))))))
22184 ;; Special case: Move point to special position when
22185 ;; currently after it or at beginning of line.
22186 (if (eq special t)
22187 (when (or (> pos after-bullet) (= (point) pos))
22188 (goto-char after-bullet))
22189 ;; Reversed case: Move point to special position when
22190 ;; point was already at beginning of line and command is
22191 ;; repeated.
22192 (when (and (= (point) pos) (eq last-command this-command))
22193 (goto-char after-bullet))))))))
22194 (org-no-warnings
22195 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22197 (defun org-end-of-line (&optional arg)
22198 "Go to the end of the line.
22199 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22200 tags on the first attempt, and only move to after the tags when
22201 the cursor is already beyond the end of the headline."
22202 (interactive "P")
22203 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22204 org-special-ctrl-a/e))
22205 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22206 'end-of-visual-line)
22207 ((fboundp 'move-end-of-line) 'move-end-of-line)
22208 (t 'end-of-line))))
22209 (if (or (not special) arg) (call-interactively move-fun)
22210 (let* ((element (save-excursion (beginning-of-line)
22211 (org-element-at-point)))
22212 (type (org-element-type element)))
22213 (cond
22214 ((memq type '(headline inlinetask))
22215 (let ((pos (point)))
22216 (beginning-of-line 1)
22217 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22218 (if (eq special t)
22219 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22220 (goto-char (match-beginning 1))
22221 (goto-char (match-end 0)))
22222 (if (or (< pos (match-end 0))
22223 (not (eq this-command last-command)))
22224 (goto-char (match-end 0))
22225 (goto-char (match-beginning 1))))
22226 (call-interactively move-fun))))
22227 ((org-element-property :hiddenp element)
22228 ;; If element is hidden, `move-end-of-line' would put point
22229 ;; after it. Use `end-of-line' to stay on current line.
22230 (call-interactively 'end-of-line))
22231 (t (call-interactively move-fun)))))
22232 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22234 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22235 (define-key org-mode-map "\C-e" 'org-end-of-line)
22237 (defun org-backward-sentence (&optional arg)
22238 "Go to beginning of sentence, or beginning of table field.
22239 This will call `backward-sentence' or `org-table-beginning-of-field',
22240 depending on context."
22241 (interactive "P")
22242 (cond
22243 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22244 (t (call-interactively 'backward-sentence))))
22246 (defun org-forward-sentence (&optional arg)
22247 "Go to end of sentence, or end of table field.
22248 This will call `forward-sentence' or `org-table-end-of-field',
22249 depending on context."
22250 (interactive "P")
22251 (cond
22252 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22253 (t (call-interactively 'forward-sentence))))
22255 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22256 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22258 (defun org-kill-line (&optional arg)
22259 "Kill line, to tags or end of line."
22260 (interactive "P")
22261 (cond
22262 ((or (not org-special-ctrl-k)
22263 (bolp)
22264 (not (org-at-heading-p)))
22265 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22266 org-ctrl-k-protect-subtree)
22267 (if (or (eq org-ctrl-k-protect-subtree 'error)
22268 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22269 (error "C-k aborted - would kill hidden subtree")))
22270 (call-interactively
22271 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22272 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22273 (kill-region (point) (match-beginning 1))
22274 (org-set-tags nil t))
22275 (t (kill-region (point) (point-at-eol)))))
22277 (define-key org-mode-map "\C-k" 'org-kill-line)
22279 (defun org-yank (&optional arg)
22280 "Yank. If the kill is a subtree, treat it specially.
22281 This command will look at the current kill and check if is a single
22282 subtree, or a series of subtrees[1]. If it passes the test, and if the
22283 cursor is at the beginning of a line or after the stars of a currently
22284 empty headline, then the yank is handled specially. How exactly depends
22285 on the value of the following variables, both set by default.
22287 org-yank-folded-subtrees
22288 When set, the subtree(s) will be folded after insertion, but only
22289 if doing so would now swallow text after the yanked text.
22291 org-yank-adjusted-subtrees
22292 When set, the subtree will be promoted or demoted in order to
22293 fit into the local outline tree structure, which means that the level
22294 will be adjusted so that it becomes the smaller one of the two
22295 *visible* surrounding headings.
22297 Any prefix to this command will cause `yank' to be called directly with
22298 no special treatment. In particular, a simple \\[universal-argument] prefix \
22299 will just
22300 plainly yank the text as it is.
22302 \[1] The test checks if the first non-white line is a heading
22303 and if there are no other headings with fewer stars."
22304 (interactive "P")
22305 (org-yank-generic 'yank arg))
22307 (defun org-yank-generic (command arg)
22308 "Perform some yank-like command.
22310 This function implements the behavior described in the `org-yank'
22311 documentation. However, it has been generalized to work for any
22312 interactive command with similar behavior."
22314 ;; pretend to be command COMMAND
22315 (setq this-command command)
22317 (if arg
22318 (call-interactively command)
22320 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22321 (and (org-kill-is-subtree-p)
22322 (or (bolp)
22323 (and (looking-at "[ \t]*$")
22324 (string-match
22325 "\\`\\*+\\'"
22326 (buffer-substring (point-at-bol) (point)))))))
22327 swallowp)
22328 (cond
22329 ((and subtreep org-yank-folded-subtrees)
22330 (let ((beg (point))
22331 end)
22332 (if (and subtreep org-yank-adjusted-subtrees)
22333 (org-paste-subtree nil nil 'for-yank)
22334 (call-interactively command))
22336 (setq end (point))
22337 (goto-char beg)
22338 (when (and (bolp) subtreep
22339 (not (setq swallowp
22340 (org-yank-folding-would-swallow-text beg end))))
22341 (org-with-limited-levels
22342 (or (looking-at org-outline-regexp)
22343 (re-search-forward org-outline-regexp-bol end t))
22344 (while (and (< (point) end) (looking-at org-outline-regexp))
22345 (hide-subtree)
22346 (org-cycle-show-empty-lines 'folded)
22347 (condition-case nil
22348 (outline-forward-same-level 1)
22349 (error (goto-char end))))))
22350 (when swallowp
22351 (message
22352 "Inserted text not folded because that would swallow text"))
22354 (goto-char end)
22355 (skip-chars-forward " \t\n\r")
22356 (beginning-of-line 1)
22357 (push-mark beg 'nomsg)))
22358 ((and subtreep org-yank-adjusted-subtrees)
22359 (let ((beg (point-at-bol)))
22360 (org-paste-subtree nil nil 'for-yank)
22361 (push-mark beg 'nomsg)))
22363 (call-interactively command))))))
22365 (defun org-yank-folding-would-swallow-text (beg end)
22366 "Would hide-subtree at BEG swallow any text after END?"
22367 (let (level)
22368 (org-with-limited-levels
22369 (save-excursion
22370 (goto-char beg)
22371 (when (or (looking-at org-outline-regexp)
22372 (re-search-forward org-outline-regexp-bol end t))
22373 (setq level (org-outline-level)))
22374 (goto-char end)
22375 (skip-chars-forward " \t\r\n\v\f")
22376 (if (or (eobp)
22377 (and (bolp) (looking-at org-outline-regexp)
22378 (<= (org-outline-level) level)))
22379 nil ; Nothing would be swallowed
22380 t))))) ; something would swallow
22382 (define-key org-mode-map "\C-y" 'org-yank)
22384 (defun org-truely-invisible-p ()
22385 "Check if point is at a character currently not visible.
22386 This version does not only check the character property, but also
22387 `visible-mode'."
22388 ;; Early versions of noutline don't have `outline-invisible-p'.
22389 (if (org-bound-and-true-p visible-mode)
22391 (outline-invisible-p)))
22393 (defun org-invisible-p2 ()
22394 "Check if point is at a character currently not visible."
22395 (save-excursion
22396 (if (and (eolp) (not (bobp))) (backward-char 1))
22397 ;; Early versions of noutline don't have `outline-invisible-p'.
22398 (outline-invisible-p)))
22400 (defun org-back-to-heading (&optional invisible-ok)
22401 "Call `outline-back-to-heading', but provide a better error message."
22402 (condition-case nil
22403 (outline-back-to-heading invisible-ok)
22404 (error (error "Before first headline at position %d in buffer %s"
22405 (point) (current-buffer)))))
22407 (defun org-before-first-heading-p ()
22408 "Before first heading?"
22409 (save-excursion
22410 (end-of-line)
22411 (null (re-search-backward org-outline-regexp-bol nil t))))
22413 (defun org-at-heading-p (&optional ignored)
22414 (outline-on-heading-p t))
22415 ;; Compatibility alias with Org versions < 7.8.03
22416 (defalias 'org-on-heading-p 'org-at-heading-p)
22418 (defun org-at-comment-p nil
22419 "Is cursor in a line starting with a # character?"
22420 (save-excursion
22421 (beginning-of-line)
22422 (looking-at "^#")))
22424 (defun org-at-drawer-p nil
22425 "Is cursor at a drawer keyword?"
22426 (save-excursion
22427 (move-beginning-of-line 1)
22428 (looking-at org-drawer-regexp)))
22430 (defun org-at-block-p nil
22431 "Is cursor at a block keyword?"
22432 (save-excursion
22433 (move-beginning-of-line 1)
22434 (looking-at org-block-regexp)))
22436 (defun org-point-at-end-of-empty-headline ()
22437 "If point is at the end of an empty headline, return t, else nil.
22438 If the heading only contains a TODO keyword, it is still still considered
22439 empty."
22440 (and (looking-at "[ \t]*$")
22441 (when org-todo-line-regexp
22442 (save-excursion
22443 (beginning-of-line 1)
22444 (let ((case-fold-search nil))
22445 (looking-at org-todo-line-regexp)
22446 (string= (match-string 3) ""))))))
22448 (defun org-at-heading-or-item-p ()
22449 (or (org-at-heading-p) (org-at-item-p)))
22451 (defun org-at-target-p ()
22452 (or (org-in-regexp org-radio-target-regexp)
22453 (org-in-regexp org-target-regexp)))
22454 ;; Compatibility alias with Org versions < 7.8.03
22455 (defalias 'org-on-target-p 'org-at-target-p)
22457 (defun org-up-heading-all (arg)
22458 "Move to the heading line of which the present line is a subheading.
22459 This function considers both visible and invisible heading lines.
22460 With argument, move up ARG levels."
22461 (if (fboundp 'outline-up-heading-all)
22462 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22463 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22465 (defun org-up-heading-safe ()
22466 "Move to the heading line of which the present line is a subheading.
22467 This version will not throw an error. It will return the level of the
22468 headline found, or nil if no higher level is found.
22470 Also, this function will be a lot faster than `outline-up-heading',
22471 because it relies on stars being the outline starters. This can really
22472 make a significant difference in outlines with very many siblings."
22473 (let (start-level re)
22474 (org-back-to-heading t)
22475 (setq start-level (funcall outline-level))
22476 (if (equal start-level 1)
22478 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22479 (if (re-search-backward re nil t)
22480 (funcall outline-level)))))
22482 (defun org-first-sibling-p ()
22483 "Is this heading the first child of its parents?"
22484 (interactive)
22485 (let ((re org-outline-regexp-bol)
22486 level l)
22487 (unless (org-at-heading-p t)
22488 (error "Not at a heading"))
22489 (setq level (funcall outline-level))
22490 (save-excursion
22491 (if (not (re-search-backward re nil t))
22493 (setq l (funcall outline-level))
22494 (< l level)))))
22496 (defun org-goto-sibling (&optional previous)
22497 "Goto the next sibling, even if it is invisible.
22498 When PREVIOUS is set, go to the previous sibling instead. Returns t
22499 when a sibling was found. When none is found, return nil and don't
22500 move point."
22501 (let ((fun (if previous 're-search-backward 're-search-forward))
22502 (pos (point))
22503 (re org-outline-regexp-bol)
22504 level l)
22505 (when (condition-case nil (org-back-to-heading t) (error nil))
22506 (setq level (funcall outline-level))
22507 (catch 'exit
22508 (or previous (forward-char 1))
22509 (while (funcall fun re nil t)
22510 (setq l (funcall outline-level))
22511 (when (< l level) (goto-char pos) (throw 'exit nil))
22512 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22513 (goto-char pos)
22514 nil))))
22516 (defun org-show-siblings ()
22517 "Show all siblings of the current headline."
22518 (save-excursion
22519 (while (org-goto-sibling) (org-flag-heading nil)))
22520 (save-excursion
22521 (while (org-goto-sibling 'previous)
22522 (org-flag-heading nil))))
22524 (defun org-goto-first-child ()
22525 "Goto the first child, even if it is invisible.
22526 Return t when a child was found. Otherwise don't move point and
22527 return nil."
22528 (let (level (pos (point)) (re org-outline-regexp-bol))
22529 (when (condition-case nil (org-back-to-heading t) (error nil))
22530 (setq level (outline-level))
22531 (forward-char 1)
22532 (if (and (re-search-forward re nil t) (> (outline-level) level))
22533 (progn (goto-char (match-beginning 0)) t)
22534 (goto-char pos) nil))))
22536 (defun org-show-hidden-entry ()
22537 "Show an entry where even the heading is hidden."
22538 (save-excursion
22539 (org-show-entry)))
22541 (defun org-flag-heading (flag &optional entry)
22542 "Flag the current heading. FLAG non-nil means make invisible.
22543 When ENTRY is non-nil, show the entire entry."
22544 (save-excursion
22545 (org-back-to-heading t)
22546 ;; Check if we should show the entire entry
22547 (if entry
22548 (progn
22549 (org-show-entry)
22550 (save-excursion
22551 (and (outline-next-heading)
22552 (org-flag-heading nil))))
22553 (outline-flag-region (max (point-min) (1- (point)))
22554 (save-excursion (outline-end-of-heading) (point))
22555 flag))))
22557 (defun org-get-next-sibling ()
22558 "Move to next heading of the same level, and return point.
22559 If there is no such heading, return nil.
22560 This is like outline-next-sibling, but invisible headings are ok."
22561 (let ((level (funcall outline-level)))
22562 (outline-next-heading)
22563 (while (and (not (eobp)) (> (funcall outline-level) level))
22564 (outline-next-heading))
22565 (if (or (eobp) (< (funcall outline-level) level))
22567 (point))))
22569 (defun org-get-last-sibling ()
22570 "Move to previous heading of the same level, and return point.
22571 If there is no such heading, return nil."
22572 (let ((opoint (point))
22573 (level (funcall outline-level)))
22574 (outline-previous-heading)
22575 (when (and (/= (point) opoint) (outline-on-heading-p t))
22576 (while (and (> (funcall outline-level) level)
22577 (not (bobp)))
22578 (outline-previous-heading))
22579 (if (< (funcall outline-level) level)
22581 (point)))))
22583 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22584 "Goto to the end of a subtree."
22585 ;; This contains an exact copy of the original function, but it uses
22586 ;; `org-back-to-heading', to make it work also in invisible
22587 ;; trees. And is uses an invisible-ok argument.
22588 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22589 ;; Furthermore, when used inside Org, finding the end of a large subtree
22590 ;; with many children and grandchildren etc, this can be much faster
22591 ;; than the outline version.
22592 (org-back-to-heading invisible-ok)
22593 (let ((first t)
22594 (level (funcall outline-level)))
22595 (if (and (derived-mode-p 'org-mode) (< level 1000))
22596 ;; A true heading (not a plain list item), in Org-mode
22597 ;; This means we can easily find the end by looking
22598 ;; only for the right number of stars. Using a regexp to do
22599 ;; this is so much faster than using a Lisp loop.
22600 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22601 (forward-char 1)
22602 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22603 ;; something else, do it the slow way
22604 (while (and (not (eobp))
22605 (or first (> (funcall outline-level) level)))
22606 (setq first nil)
22607 (outline-next-heading)))
22608 (unless to-heading
22609 (if (memq (preceding-char) '(?\n ?\^M))
22610 (progn
22611 ;; Go to end of line before heading
22612 (forward-char -1)
22613 (if (memq (preceding-char) '(?\n ?\^M))
22614 ;; leave blank line before heading
22615 (forward-char -1))))))
22616 (point))
22618 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22619 "Use Org version in org-mode, for dramatic speed-up."
22620 (if (derived-mode-p 'org-mode)
22621 (progn
22622 (org-end-of-subtree nil t)
22623 (unless (eobp) (backward-char 1)))
22624 ad-do-it))
22626 (defun org-end-of-meta-data-and-drawers ()
22627 "Jump to the first text after meta data and drawers in the current entry.
22628 This will move over empty lines, lines with planning time stamps,
22629 clocking lines, and drawers."
22630 (org-back-to-heading t)
22631 (let ((end (save-excursion (outline-next-heading) (point)))
22632 (re (concat "\\(" org-drawer-regexp "\\)"
22633 "\\|" "[ \t]*" org-keyword-time-regexp)))
22634 (forward-line 1)
22635 (while (re-search-forward re end t)
22636 (if (not (match-end 1))
22637 ;; empty or planning line
22638 (forward-line 1)
22639 ;; a drawer, find the end
22640 (re-search-forward "^[ \t]*:END:" end 'move)
22641 (forward-line 1)))
22642 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22643 (point)))
22645 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22646 "Move forward to the ARG'th subheading at same level as this one.
22647 Stop at the first and last subheadings of a superior heading.
22648 Normally this only looks at visible headings, but when INVISIBLE-OK is
22649 non-nil it will also look at invisible ones."
22650 (interactive "p")
22651 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22652 (if (and arg (< arg 0))
22653 (goto-char (point-min))
22654 (outline-next-heading))
22655 (org-at-heading-p)
22656 (let ((level (- (match-end 0) (match-beginning 0) 1))
22657 (f (if (and arg (< arg 0))
22658 're-search-backward
22659 're-search-forward))
22660 (count (if arg (abs arg) 1))
22661 (result (point)))
22662 (forward-char (if (and arg (< arg 0)) -1 1))
22663 (while (and (> count 0)
22664 (funcall f org-outline-regexp-bol nil 'move))
22665 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22666 (cond ((< l level) (setq count 0))
22667 ((and (= l level)
22668 (or invisible-ok
22669 (progn
22670 (goto-char (line-beginning-position))
22671 (not (outline-invisible-p)))))
22672 (setq count (1- count))
22673 (when (eq l level)
22674 (setq result (point)))))))
22675 (goto-char result))
22676 (beginning-of-line 1)))
22678 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22679 "Move backward to the ARG'th subheading at same level as this one.
22680 Stop at the first and last subheadings of a superior heading."
22681 (interactive "p")
22682 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22684 (defun org-next-block (arg &optional backward block-regexp)
22685 "Jump to the next block.
22686 With a prefix argument ARG, jump forward ARG many source blocks.
22687 When BACKWARD is non-nil, jump to the previous block.
22688 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22689 (interactive "p")
22690 (let ((re (or block-regexp org-block-regexp))
22691 (re-search-fn (or (and backward 're-search-backward)
22692 're-search-forward)))
22693 (if (looking-at re) (forward-char 1))
22694 (condition-case nil
22695 (funcall re-search-fn re nil nil arg)
22696 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22697 (goto-char (match-beginning 0)) (org-show-context)))
22699 (defun org-previous-block (arg &optional block-regexp)
22700 "Jump to the previous block.
22701 With a prefix argument ARG, jump backward ARG many source blocks.
22702 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22703 (interactive "p")
22704 (org-next-block arg t block-regexp))
22706 (defun org-forward-element ()
22707 "Move forward by one element.
22708 Move to the next element at the same level, when possible."
22709 (interactive)
22710 (cond ((eobp) (error "Cannot move further down"))
22711 ((org-with-limited-levels (org-at-heading-p))
22712 (let ((origin (point)))
22713 (goto-char (org-end-of-subtree nil t))
22714 (unless (org-with-limited-levels (org-at-heading-p))
22715 (goto-char origin)
22716 (error "Cannot move further down"))))
22718 (let* ((elem (org-element-at-point))
22719 (end (org-element-property :end elem))
22720 (parent (org-element-property :parent elem)))
22721 (if (and parent (= (org-element-property :contents-end parent) end))
22722 (goto-char (org-element-property :end parent))
22723 (goto-char end))))))
22725 (defun org-backward-element ()
22726 "Move backward by one element.
22727 Move to the previous element at the same level, when possible."
22728 (interactive)
22729 (cond ((bobp) (error "Cannot move further up"))
22730 ((org-with-limited-levels (org-at-heading-p))
22731 ;; At an headline, move to the previous one, if any, or stay
22732 ;; here.
22733 (let ((origin (point)))
22734 (org-with-limited-levels (org-backward-heading-same-level 1))
22735 ;; When current headline has no sibling above, move to its
22736 ;; parent.
22737 (when (= (point) origin)
22738 (or (org-with-limited-levels (org-up-heading-safe))
22739 (progn (goto-char origin)
22740 (error "Cannot move further up"))))))
22742 (let* ((trail (org-element-at-point 'keep-trail))
22743 (elem (car trail))
22744 (prev-elem (nth 1 trail))
22745 (beg (org-element-property :begin elem)))
22746 (cond
22747 ;; Move to beginning of current element if point isn't
22748 ;; there already.
22749 ((/= (point) beg) (goto-char beg))
22750 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22751 ((org-before-first-heading-p) (goto-char (point-min)))
22752 (t (org-back-to-heading)))))))
22754 (defun org-up-element ()
22755 "Move to upper element."
22756 (interactive)
22757 (if (org-with-limited-levels (org-at-heading-p))
22758 (unless (org-up-heading-safe) (error "No surrounding element"))
22759 (let* ((elem (org-element-at-point))
22760 (parent (org-element-property :parent elem)))
22761 (if parent (goto-char (org-element-property :begin parent))
22762 (if (org-with-limited-levels (org-before-first-heading-p))
22763 (error "No surrounding element")
22764 (org-with-limited-levels (org-back-to-heading)))))))
22766 (defvar org-element-greater-elements)
22767 (defun org-down-element ()
22768 "Move to inner element."
22769 (interactive)
22770 (let ((element (org-element-at-point)))
22771 (cond
22772 ((memq (org-element-type element) '(plain-list table))
22773 (goto-char (org-element-property :contents-begin element))
22774 (forward-char))
22775 ((memq (org-element-type element) org-element-greater-elements)
22776 ;; If contents are hidden, first disclose them.
22777 (when (org-element-property :hiddenp element) (org-cycle))
22778 (goto-char (or (org-element-property :contents-begin element)
22779 (error "No content for this element"))))
22780 (t (error "No inner element")))))
22782 (defun org-drag-element-backward ()
22783 "Move backward element at point."
22784 (interactive)
22785 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22786 (let* ((trail (org-element-at-point 'keep-trail))
22787 (elem (car trail))
22788 (prev-elem (nth 1 trail)))
22789 ;; Error out if no previous element or previous element is
22790 ;; a parent of the current one.
22791 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22792 (error "Cannot drag element backward")
22793 (let ((pos (point)))
22794 (org-element-swap-A-B prev-elem elem)
22795 (goto-char (+ (org-element-property :begin prev-elem)
22796 (- pos (org-element-property :begin elem)))))))))
22798 (defun org-drag-element-forward ()
22799 "Move forward element at point."
22800 (interactive)
22801 (let* ((pos (point))
22802 (elem (org-element-at-point)))
22803 (when (= (point-max) (org-element-property :end elem))
22804 (error "Cannot drag element forward"))
22805 (goto-char (org-element-property :end elem))
22806 (let ((next-elem (org-element-at-point)))
22807 (when (or (org-element-nested-p elem next-elem)
22808 (and (eq (org-element-type next-elem) 'headline)
22809 (not (eq (org-element-type elem) 'headline))))
22810 (goto-char pos)
22811 (error "Cannot drag element forward"))
22812 ;; Compute new position of point: it's shifted by NEXT-ELEM
22813 ;; body's length (without final blanks) and by the length of
22814 ;; blanks between ELEM and NEXT-ELEM.
22815 (let ((size-next (- (save-excursion
22816 (goto-char (org-element-property :end next-elem))
22817 (skip-chars-backward " \r\t\n")
22818 (forward-line)
22819 ;; Small correction if buffer doesn't end
22820 ;; with a newline character.
22821 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22822 (org-element-property :begin next-elem)))
22823 (size-blank (- (org-element-property :end elem)
22824 (save-excursion
22825 (goto-char (org-element-property :end elem))
22826 (skip-chars-backward " \r\t\n")
22827 (forward-line)
22828 (point)))))
22829 (org-element-swap-A-B elem next-elem)
22830 (goto-char (+ pos size-next size-blank))))))
22832 (defun org-mark-element ()
22833 "Put point at beginning of this element, mark at end.
22835 Interactively, if this command is repeated or (in Transient Mark
22836 mode) if the mark is active, it marks the next element after the
22837 ones already marked."
22838 (interactive)
22839 (let (deactivate-mark)
22840 (if (and (org-called-interactively-p 'any)
22841 (or (and (eq last-command this-command) (mark t))
22842 (and transient-mark-mode mark-active)))
22843 (set-mark
22844 (save-excursion
22845 (goto-char (mark))
22846 (goto-char (org-element-property :end (org-element-at-point)))))
22847 (let ((element (org-element-at-point)))
22848 (end-of-line)
22849 (push-mark (org-element-property :end element) t t)
22850 (goto-char (org-element-property :begin element))))))
22852 (defun org-narrow-to-element ()
22853 "Narrow buffer to current element."
22854 (interactive)
22855 (let ((elem (org-element-at-point)))
22856 (cond
22857 ((eq (car elem) 'headline)
22858 (narrow-to-region
22859 (org-element-property :begin elem)
22860 (org-element-property :end elem)))
22861 ((memq (car elem) org-element-greater-elements)
22862 (narrow-to-region
22863 (org-element-property :contents-begin elem)
22864 (org-element-property :contents-end elem)))
22866 (narrow-to-region
22867 (org-element-property :begin elem)
22868 (org-element-property :end elem))))))
22870 (defun org-transpose-words ()
22871 "Transpose words, using `org-mode' syntax table."
22872 (interactive)
22873 (with-syntax-table org-syntax-table
22874 (call-interactively 'transpose-words)))
22875 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22877 (defun org-transpose-element ()
22878 "Transpose current and previous elements, keeping blank lines between.
22879 Point is moved after both elements."
22880 (interactive)
22881 (org-skip-whitespace)
22882 (let ((end (org-element-property :end (org-element-at-point))))
22883 (org-drag-element-backward)
22884 (goto-char end)))
22886 (defun org-unindent-buffer ()
22887 "Un-indent the visible part of the buffer.
22888 Relative indentation (between items, inside blocks, etc.) isn't
22889 modified."
22890 (interactive)
22891 (unless (eq major-mode 'org-mode)
22892 (error "Cannot un-indent a buffer not in Org mode"))
22893 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22894 unindent-tree ; For byte-compiler.
22895 (unindent-tree
22896 (function
22897 (lambda (contents)
22898 (mapc
22899 (lambda (element)
22900 (if (memq (org-element-type element) '(headline section))
22901 (funcall unindent-tree (org-element-contents element))
22902 (save-excursion
22903 (save-restriction
22904 (narrow-to-region
22905 (org-element-property :begin element)
22906 (org-element-property :end element))
22907 (org-do-remove-indentation)))))
22908 (reverse contents))))))
22909 (funcall unindent-tree (org-element-contents parse-tree))))
22911 (defun org-show-subtree ()
22912 "Show everything after this heading at deeper levels."
22913 (interactive)
22914 (outline-flag-region
22915 (point)
22916 (save-excursion
22917 (org-end-of-subtree t t))
22918 nil))
22920 (defun org-show-entry ()
22921 "Show the body directly following this heading.
22922 Show the heading too, if it is currently invisible."
22923 (interactive)
22924 (save-excursion
22925 (condition-case nil
22926 (progn
22927 (org-back-to-heading t)
22928 (outline-flag-region
22929 (max (point-min) (1- (point)))
22930 (save-excursion
22931 (if (re-search-forward
22932 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22933 (match-beginning 1)
22934 (point-max)))
22935 nil)
22936 (org-cycle-hide-drawers 'children))
22937 (error nil))))
22939 (defun org-make-options-regexp (kwds &optional extra)
22940 "Make a regular expression for keyword lines."
22941 (concat
22942 "^#\\+\\("
22943 (mapconcat 'regexp-quote kwds "\\|")
22944 (if extra (concat "\\|" extra))
22945 "\\):[ \t]*\\(.*\\)"))
22947 ;; Make isearch reveal the necessary context
22948 (defun org-isearch-end ()
22949 "Reveal context after isearch exits."
22950 (when isearch-success ; only if search was successful
22951 (if (featurep 'xemacs)
22952 ;; Under XEmacs, the hook is run in the correct place,
22953 ;; we directly show the context.
22954 (org-show-context 'isearch)
22955 ;; In Emacs the hook runs *before* restoring the overlays.
22956 ;; So we have to use a one-time post-command-hook to do this.
22957 ;; (Emacs 22 has a special variable, see function `org-mode')
22958 (unless (and (boundp 'isearch-mode-end-hook-quit)
22959 isearch-mode-end-hook-quit)
22960 ;; Only when the isearch was not quitted.
22961 (org-add-hook 'post-command-hook 'org-isearch-post-command
22962 'append 'local)))))
22964 (defun org-isearch-post-command ()
22965 "Remove self from hook, and show context."
22966 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22967 (org-show-context 'isearch))
22970 ;;;; Integration with and fixes for other packages
22972 ;;; Imenu support
22974 (defvar org-imenu-markers nil
22975 "All markers currently used by Imenu.")
22976 (make-variable-buffer-local 'org-imenu-markers)
22978 (defun org-imenu-new-marker (&optional pos)
22979 "Return a new marker for use by Imenu, and remember the marker."
22980 (let ((m (make-marker)))
22981 (move-marker m (or pos (point)))
22982 (push m org-imenu-markers)
22985 (defun org-imenu-get-tree ()
22986 "Produce the index for Imenu."
22987 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22988 (setq org-imenu-markers nil)
22989 (let* ((n org-imenu-depth)
22990 (re (concat "^" (org-get-limited-outline-regexp)))
22991 (subs (make-vector (1+ n) nil))
22992 (last-level 0)
22993 m level head)
22994 (save-excursion
22995 (save-restriction
22996 (widen)
22997 (goto-char (point-max))
22998 (while (re-search-backward re nil t)
22999 (setq level (org-reduced-level (funcall outline-level)))
23000 (when (and (<= level n)
23001 (looking-at org-complex-heading-regexp))
23002 (setq head (org-link-display-format
23003 (org-match-string-no-properties 4))
23004 m (org-imenu-new-marker))
23005 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23006 (if (>= level last-level)
23007 (push (cons head m) (aref subs level))
23008 (push (cons head (aref subs (1+ level))) (aref subs level))
23009 (loop for i from (1+ level) to n do (aset subs i nil)))
23010 (setq last-level level)))))
23011 (aref subs 1)))
23013 (eval-after-load "imenu"
23014 '(progn
23015 (add-hook 'imenu-after-jump-hook
23016 (lambda ()
23017 (if (derived-mode-p 'org-mode)
23018 (org-show-context 'org-goto))))))
23020 (defun org-link-display-format (link)
23021 "Replace a link with either the description, or the link target
23022 if no description is present"
23023 (save-match-data
23024 (if (string-match org-bracket-link-analytic-regexp link)
23025 (replace-match (if (match-end 5)
23026 (match-string 5 link)
23027 (concat (match-string 1 link)
23028 (match-string 3 link)))
23029 nil t link)
23030 link)))
23032 (defun org-toggle-link-display ()
23033 "Toggle the literal or descriptive display of links."
23034 (interactive)
23035 (if org-descriptive-links
23036 (progn (org-remove-from-invisibility-spec '(org-link))
23037 (org-restart-font-lock)
23038 (setq org-descriptive-links nil))
23039 (progn (add-to-invisibility-spec '(org-link))
23040 (org-restart-font-lock)
23041 (setq org-descriptive-links t))))
23043 ;; Speedbar support
23045 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23046 "Overlay marking the agenda restriction line in speedbar.")
23047 (overlay-put org-speedbar-restriction-lock-overlay
23048 'face 'org-agenda-restriction-lock)
23049 (overlay-put org-speedbar-restriction-lock-overlay
23050 'help-echo "Agendas are currently limited to this item.")
23051 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23053 (defun org-speedbar-set-agenda-restriction ()
23054 "Restrict future agenda commands to the location at point in speedbar.
23055 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23056 (interactive)
23057 (require 'org-agenda)
23058 (let (p m tp np dir txt)
23059 (cond
23060 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23061 'org-imenu t))
23062 (setq m (get-text-property p 'org-imenu-marker))
23063 (with-current-buffer (marker-buffer m)
23064 (goto-char m)
23065 (org-agenda-set-restriction-lock 'subtree)))
23066 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23067 'speedbar-function 'speedbar-find-file))
23068 (setq tp (previous-single-property-change
23069 (1+ p) 'speedbar-function)
23070 np (next-single-property-change
23071 tp 'speedbar-function)
23072 dir (speedbar-line-directory)
23073 txt (buffer-substring-no-properties (or tp (point-min))
23074 (or np (point-max))))
23075 (with-current-buffer (find-file-noselect
23076 (let ((default-directory dir))
23077 (expand-file-name txt)))
23078 (unless (derived-mode-p 'org-mode)
23079 (error "Cannot restrict to non-Org-mode file"))
23080 (org-agenda-set-restriction-lock 'file)))
23081 (t (error "Don't know how to restrict Org-mode's agenda")))
23082 (move-overlay org-speedbar-restriction-lock-overlay
23083 (point-at-bol) (point-at-eol))
23084 (setq current-prefix-arg nil)
23085 (org-agenda-maybe-redo)))
23087 (eval-after-load "speedbar"
23088 '(progn
23089 (speedbar-add-supported-extension ".org")
23090 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23091 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23092 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23093 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23094 (add-hook 'speedbar-visiting-tag-hook
23095 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23097 ;;; Fixes and Hacks for problems with other packages
23099 ;; Make flyspell not check words in links, to not mess up our keymap
23100 (defvar org-element-affiliated-keywords) ; From org-element.el
23101 (defvar org-element-block-name-alist) ; From org-element.el
23102 (defun org-mode-flyspell-verify ()
23103 "Don't let flyspell put overlays at active buttons, or on
23104 {todo,all-time,additional-option-like}-keywords."
23105 (let ((pos (max (1- (point)) (point-min)))
23106 (word (thing-at-point 'word)))
23107 (and (not (get-text-property pos 'keymap))
23108 (not (get-text-property pos 'org-no-flyspell))
23109 (not (member word org-todo-keywords-1))
23110 (not (member word org-all-time-keywords))
23111 (not (member word org-options-keywords))
23112 (not (member word (mapcar 'car org-startup-options)))
23113 (not (member-ignore-case word org-element-affiliated-keywords))
23114 (not (member-ignore-case word (org-get-export-keywords)))
23115 (not (member-ignore-case
23116 word (mapcar 'car org-element-block-name-alist)))
23117 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23119 (defun org-remove-flyspell-overlays-in (beg end)
23120 "Remove flyspell overlays in region."
23121 (and (org-bound-and-true-p flyspell-mode)
23122 (fboundp 'flyspell-delete-region-overlays)
23123 (flyspell-delete-region-overlays beg end))
23124 (add-text-properties beg end '(org-no-flyspell t)))
23126 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23127 (eval-after-load "bookmark"
23128 '(if (boundp 'bookmark-after-jump-hook)
23129 ;; We can use the hook
23130 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23131 ;; Hook not available, use advice
23132 (defadvice bookmark-jump (after org-make-visible activate)
23133 "Make the position visible."
23134 (org-bookmark-jump-unhide))))
23136 ;; Make sure saveplace shows the location if it was hidden
23137 (eval-after-load "saveplace"
23138 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23139 "Make the position visible."
23140 (org-bookmark-jump-unhide)))
23142 ;; Make sure ecb shows the location if it was hidden
23143 (eval-after-load "ecb"
23144 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23145 "Make hierarchy visible when jumping into location from ECB tree buffer."
23146 (if (derived-mode-p 'org-mode)
23147 (org-show-context))))
23149 (defun org-bookmark-jump-unhide ()
23150 "Unhide the current position, to show the bookmark location."
23151 (and (derived-mode-p 'org-mode)
23152 (or (outline-invisible-p)
23153 (save-excursion (goto-char (max (point-min) (1- (point))))
23154 (outline-invisible-p)))
23155 (org-show-context 'bookmark-jump)))
23157 ;; Make session.el ignore our circular variable
23158 (eval-after-load "session"
23159 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23161 ;;;; Experimental code
23163 (defun org-closed-in-range ()
23164 "Sparse tree of items closed in a certain time range.
23165 Still experimental, may disappear in the future."
23166 (interactive)
23167 ;; Get the time interval from the user.
23168 (let* ((time1 (org-float-time
23169 (org-read-date nil 'to-time nil "Starting date: ")))
23170 (time2 (org-float-time
23171 (org-read-date nil 'to-time nil "End date:")))
23172 ;; callback function
23173 (callback (lambda ()
23174 (let ((time
23175 (org-float-time
23176 (apply 'encode-time
23177 (org-parse-time-string
23178 (match-string 1))))))
23179 ;; check if time in interval
23180 (and (>= time time1) (<= time time2))))))
23181 ;; make tree, check each match with the callback
23182 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23184 ;;;; Finish up
23186 (provide 'org)
23188 (run-hooks 'org-load-hook)
23190 ;;; org.el ends here