ox: Docstring fix
[org-mode.git] / lisp / org.el
blobffecf98bdf9b0811c1b05da551eaf6307b51b2ca
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything
591 By default, this option is ignored when Org opens agenda files
592 for the first time. If you want the agenda to honor the startup
593 option, set `org-agenda-inhibit-startup' to nil."
594 :group 'org-startup
595 :type '(choice
596 (const :tag "nofold: show all" nil)
597 (const :tag "fold: overview" t)
598 (const :tag "content: all headlines" content)
599 (const :tag "show everything, even drawers" showeverything)))
601 (defcustom org-startup-truncated t
602 "Non-nil means entering Org-mode will set `truncate-lines'.
603 This is useful since some lines containing links can be very long and
604 uninteresting. Also tables look terrible when wrapped."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-startup-indented nil
609 "Non-nil means turn on `org-indent-mode' on startup.
610 This can also be configured on a per-file basis by adding one of
611 the following lines anywhere in the buffer:
613 #+STARTUP: indent
614 #+STARTUP: noindent"
615 :group 'org-structure
616 :type '(choice
617 (const :tag "Not" nil)
618 (const :tag "Globally (slow on startup in large files)" t)))
620 (defcustom org-use-sub-superscripts t
621 "Non-nil means interpret \"_\" and \"^\" for display.
622 When this option is turned on, you can use TeX-like syntax for sub- and
623 superscripts. Several characters after \"_\" or \"^\" will be
624 considered as a single item - so grouping with {} is normally not
625 needed. For example, the following things will be parsed as single
626 sub- or superscripts.
628 10^24 or 10^tau several digits will be considered 1 item.
629 10^-12 or 10^-tau a leading sign with digits or a word
630 x^2-y^3 will be read as x^2 - y^3, because items are
631 terminated by almost any nonword/nondigit char.
632 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
634 Still, ambiguity is possible - so when in doubt use {} to enclose
635 the sub/superscript. If you set this variable to the symbol
636 `{}', the braces are *required* in order to trigger
637 interpretations as sub/superscript. This can be helpful in
638 documents that need \"_\" frequently in plain text."
639 :group 'org-startup
640 :version "24.1"
641 :type '(choice
642 (const :tag "Always interpret" t)
643 (const :tag "Only with braces" {})
644 (const :tag "Never interpret" nil)))
646 (defcustom org-startup-with-beamer-mode nil
647 "Non-nil means turn on `org-beamer-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: beamer"
652 :group 'org-startup
653 :version "24.1"
654 :type 'boolean)
656 (defcustom org-startup-align-all-tables nil
657 "Non-nil means align all tables when visiting a file.
658 This is useful when the column width in tables is forced with <N> cookies
659 in table fields. Such tables will look correct only after the first re-align.
660 This can also be configured on a per-file basis by adding one of
661 the following lines anywhere in the buffer:
662 #+STARTUP: align
663 #+STARTUP: noalign"
664 :group 'org-startup
665 :type 'boolean)
667 (defcustom org-startup-with-inline-images nil
668 "Non-nil means show inline images when loading a new Org file.
669 This can also be configured on a per-file basis by adding one of
670 the following lines anywhere in the buffer:
671 #+STARTUP: inlineimages
672 #+STARTUP: noinlineimages"
673 :group 'org-startup
674 :version "24.1"
675 :type 'boolean)
677 (defcustom org-startup-with-latex-preview nil
678 "Non-nil means preview LaTeX fragments when loading a new Org file.
680 This can also be configured on a per-file basis by adding one of
681 the followinglines anywhere in the buffer:
682 #+STARTUP: latexpreview
683 #+STARTUP: nolatexpreview"
684 :group 'org-startup
685 :version "24.3"
686 :type 'boolean)
688 (defcustom org-insert-mode-line-in-empty-file nil
689 "Non-nil means insert the first line setting Org-mode in empty files.
690 When the function `org-mode' is called interactively in an empty file, this
691 normally means that the file name does not automatically trigger Org-mode.
692 To ensure that the file will always be in Org-mode in the future, a
693 line enforcing Org-mode will be inserted into the buffer, if this option
694 has been set."
695 :group 'org-startup
696 :type 'boolean)
698 (defcustom org-replace-disputed-keys nil
699 "Non-nil means use alternative key bindings for some keys.
700 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
701 These keys are also used by other packages like shift-selection-mode'
702 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
703 If you want to use Org-mode together with one of these other modes,
704 or more generally if you would like to move some Org-mode commands to
705 other keys, set this variable and configure the keys with the variable
706 `org-disputed-keys'.
708 This option is only relevant at load-time of Org-mode, and must be set
709 *before* org.el is loaded. Changing it requires a restart of Emacs to
710 become effective."
711 :group 'org-startup
712 :type 'boolean)
714 (defcustom org-use-extra-keys nil
715 "Non-nil means use extra key sequence definitions for certain commands.
716 This happens automatically if you run XEmacs or if `window-system'
717 is nil. This variable lets you do the same manually. You must
718 set it before loading org.
720 Example: on Carbon Emacs 22 running graphically, with an external
721 keyboard on a Powerbook, the default way of setting M-left might
722 not work for either Alt or ESC. Setting this variable will make
723 it work for ESC."
724 :group 'org-startup
725 :type 'boolean)
727 (if (fboundp 'defvaralias)
728 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
730 (defcustom org-disputed-keys
731 '(([(shift up)] . [(meta p)])
732 ([(shift down)] . [(meta n)])
733 ([(shift left)] . [(meta -)])
734 ([(shift right)] . [(meta +)])
735 ([(control shift right)] . [(meta shift +)])
736 ([(control shift left)] . [(meta shift -)]))
737 "Keys for which Org-mode and other modes compete.
738 This is an alist, cars are the default keys, second element specifies
739 the alternative to use when `org-replace-disputed-keys' is t.
741 Keys can be specified in any syntax supported by `define-key'.
742 The value of this option takes effect only at Org-mode's startup,
743 therefore you'll have to restart Emacs to apply it after changing."
744 :group 'org-startup
745 :type 'alist)
747 (defun org-key (key)
748 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
749 Or return the original if not disputed.
750 Also apply the translations defined in `org-xemacs-key-equivalents'."
751 (when org-replace-disputed-keys
752 (let* ((nkey (key-description key))
753 (x (org-find-if (lambda (x)
754 (equal (key-description (car x)) nkey))
755 org-disputed-keys)))
756 (setq key (if x (cdr x) key))))
757 (when (featurep 'xemacs)
758 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
759 key)
761 (defun org-find-if (predicate seq)
762 (catch 'exit
763 (while seq
764 (if (funcall predicate (car seq))
765 (throw 'exit (car seq))
766 (pop seq)))))
768 (defun org-defkey (keymap key def)
769 "Define a key, possibly translated, as returned by `org-key'."
770 (define-key keymap (org-key key) def))
772 (defcustom org-ellipsis nil
773 "The ellipsis to use in the Org-mode outline.
774 When nil, just use the standard three dots. When a string, use that instead,
775 When a face, use the standard 3 dots, but with the specified face.
776 The change affects only Org-mode (which will then use its own display table).
777 Changing this requires executing `M-x org-mode' in a buffer to become
778 effective."
779 :group 'org-startup
780 :type '(choice (const :tag "Default" nil)
781 (face :tag "Face" :value org-warning)
782 (string :tag "String" :value "...#")))
784 (defvar org-display-table nil
785 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
787 (defgroup org-keywords nil
788 "Keywords in Org-mode."
789 :tag "Org Keywords"
790 :group 'org)
792 (defcustom org-deadline-string "DEADLINE:"
793 "String to mark deadline entries.
794 A deadline is this string, followed by a time stamp. Should be a word,
795 terminated by a colon. You can insert a schedule keyword and
796 a timestamp with \\[org-deadline].
797 Changes become only effective after restarting Emacs."
798 :group 'org-keywords
799 :type 'string)
801 (defcustom org-scheduled-string "SCHEDULED:"
802 "String to mark scheduled TODO entries.
803 A schedule is this string, followed by a time stamp. Should be a word,
804 terminated by a colon. You can insert a schedule keyword and
805 a timestamp with \\[org-schedule].
806 Changes become only effective after restarting Emacs."
807 :group 'org-keywords
808 :type 'string)
810 (defcustom org-closed-string "CLOSED:"
811 "String used as the prefix for timestamps logging closing a TODO entry."
812 :group 'org-keywords
813 :type 'string)
815 (defcustom org-clock-string "CLOCK:"
816 "String used as prefix for timestamps clocking work hours on an item."
817 :group 'org-keywords
818 :type 'string)
820 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
821 org-scheduled-string "\\|"
822 org-deadline-string "\\|"
823 org-closed-string "\\|"
824 org-clock-string "\\)")
825 "Matches a line with planning or clock info.")
827 (defcustom org-comment-string "COMMENT"
828 "Entries starting with this keyword will never be exported.
829 An entry can be toggled between COMMENT and normal with
830 \\[org-toggle-comment].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-quote-string "QUOTE"
836 "Entries starting with this keyword will be exported in fixed-width font.
837 Quoting applies only to the text in the entry following the headline, and does
838 not extend beyond the next headline, even if that is lower level.
839 An entry can be toggled between QUOTE and normal with
840 \\[org-toggle-fixed-width-section]."
841 :group 'org-keywords
842 :type 'string)
844 (defconst org-repeat-re
845 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
846 "Regular expression for specifying repeated events.
847 After a match, group 1 contains the repeat expression.")
849 (defgroup org-structure nil
850 "Options concerning the general structure of Org-mode files."
851 :tag "Org Structure"
852 :group 'org)
854 (defgroup org-reveal-location nil
855 "Options about how to make context of a location visible."
856 :tag "Org Reveal Location"
857 :group 'org-structure)
859 (defconst org-context-choice
860 '(choice
861 (const :tag "Always" t)
862 (const :tag "Never" nil)
863 (repeat :greedy t :tag "Individual contexts"
864 (cons
865 (choice :tag "Context"
866 (const agenda)
867 (const org-goto)
868 (const occur-tree)
869 (const tags-tree)
870 (const link-search)
871 (const mark-goto)
872 (const bookmark-jump)
873 (const isearch)
874 (const default))
875 (boolean))))
876 "Contexts for the reveal options.")
878 (defcustom org-show-hierarchy-above '((default . t))
879 "Non-nil means show full hierarchy when revealing a location.
880 Org-mode often shows locations in an org-mode file which might have
881 been invisible before. When this is set, the hierarchy of headings
882 above the exposed location is shown.
883 Turning this off for example for sparse trees makes them very compact.
884 Instead of t, this can also be an alist specifying this option for different
885 contexts. Valid contexts are
886 agenda when exposing an entry from the agenda
887 org-goto when using the command `org-goto' on key C-c C-j
888 occur-tree when using the command `org-occur' on key C-c /
889 tags-tree when constructing a sparse tree based on tags matches
890 link-search when exposing search matches associated with a link
891 mark-goto when exposing the jump goal of a mark
892 bookmark-jump when exposing a bookmark location
893 isearch when exiting from an incremental search
894 default default for all contexts not set explicitly"
895 :group 'org-reveal-location
896 :type org-context-choice)
898 (defcustom org-show-following-heading '((default . nil))
899 "Non-nil means show following heading when revealing a location.
900 Org-mode often shows locations in an org-mode file which might have
901 been invisible before. When this is set, the heading following the
902 match is shown.
903 Turning this off for example for sparse trees makes them very compact,
904 but makes it harder to edit the location of the match. In such a case,
905 use the command \\[org-reveal] to show more context.
906 Instead of t, this can also be an alist specifying this option for different
907 contexts. See `org-show-hierarchy-above' for valid contexts."
908 :group 'org-reveal-location
909 :type org-context-choice)
911 (defcustom org-show-siblings '((default . nil) (isearch t))
912 "Non-nil means show all sibling heading when revealing a location.
913 Org-mode often shows locations in an org-mode file which might have
914 been invisible before. When this is set, the sibling of the current entry
915 heading are all made visible. If `org-show-hierarchy-above' is t,
916 the same happens on each level of the hierarchy above the current entry.
918 By default this is on for the isearch context, off for all other contexts.
919 Turning this off for example for sparse trees makes them very compact,
920 but makes it harder to edit the location of the match. In such a case,
921 use the command \\[org-reveal] to show more context.
922 Instead of t, this can also be an alist specifying this option for different
923 contexts. See `org-show-hierarchy-above' for valid contexts."
924 :group 'org-reveal-location
925 :type org-context-choice)
927 (defcustom org-show-entry-below '((default . nil))
928 "Non-nil means show the entry below a headline when revealing a location.
929 Org-mode often shows locations in an org-mode file which might have
930 been invisible before. When this is set, the text below the headline that is
931 exposed is also shown.
933 By default this is off for all contexts.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. See `org-show-hierarchy-above' for valid contexts."
936 :group 'org-reveal-location
937 :type org-context-choice)
939 (defcustom org-indirect-buffer-display 'other-window
940 "How should indirect tree buffers be displayed?
941 This applies to indirect buffers created with the commands
942 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
943 Valid values are:
944 current-window Display in the current window
945 other-window Just display in another window.
946 dedicated-frame Create one new frame, and re-use it each time.
947 new-frame Make a new frame each time. Note that in this case
948 previously-made indirect buffers are kept, and you need to
949 kill these buffers yourself."
950 :group 'org-structure
951 :group 'org-agenda-windows
952 :type '(choice
953 (const :tag "In current window" current-window)
954 (const :tag "In current frame, other window" other-window)
955 (const :tag "Each time a new frame" new-frame)
956 (const :tag "One dedicated frame" dedicated-frame)))
958 (defcustom org-use-speed-commands nil
959 "Non-nil means activate single letter commands at beginning of a headline.
960 This may also be a function to test for appropriate locations where speed
961 commands should be active."
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Never" nil)
965 (const :tag "At beginning of headline stars" t)
966 (function)))
968 (defcustom org-speed-commands-user nil
969 "Alist of additional speed commands.
970 This list will be checked before `org-speed-commands-default'
971 when the variable `org-use-speed-commands' is non-nil
972 and when the cursor is at the beginning of a headline.
973 The car if each entry is a string with a single letter, which must
974 be assigned to `self-insert-command' in the global map.
975 The cdr is either a command to be called interactively, a function
976 to be called, or a form to be evaluated.
977 An entry that is just a list with a single string will be interpreted
978 as a descriptive headline that will be added when listing the speed
979 commands in the Help buffer using the `?' speed command."
980 :group 'org-structure
981 :type '(repeat :value ("k" . ignore)
982 (choice :value ("k" . ignore)
983 (list :tag "Descriptive Headline" (string :tag "Headline"))
984 (cons :tag "Letter and Command"
985 (string :tag "Command letter")
986 (choice
987 (function)
988 (sexp))))))
990 (defgroup org-cycle nil
991 "Options concerning visibility cycling in Org-mode."
992 :tag "Org Cycle"
993 :group 'org-structure)
995 (defcustom org-cycle-skip-children-state-if-no-children t
996 "Non-nil means skip CHILDREN state in entries that don't have any."
997 :group 'org-cycle
998 :type 'boolean)
1000 (defcustom org-cycle-max-level nil
1001 "Maximum level which should still be subject to visibility cycling.
1002 Levels higher than this will, for cycling, be treated as text, not a headline.
1003 When `org-odd-levels-only' is set, a value of N in this variable actually
1004 means 2N-1 stars as the limiting headline.
1005 When nil, cycle all levels.
1006 Note that the limiting level of cycling is also influenced by
1007 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1008 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1009 than its value."
1010 :group 'org-cycle
1011 :type '(choice
1012 (const :tag "No limit" nil)
1013 (integer :tag "Maximum level")))
1015 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1016 "Names of drawers. Drawers are not opened by cycling on the headline above.
1017 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1018 this:
1019 :DRAWERNAME:
1020 .....
1021 :END:
1022 The drawer \"PROPERTIES\" is special for capturing properties through
1023 the property API.
1025 Drawers can be defined on the per-file basis with a line like:
1027 #+DRAWERS: HIDDEN STATE PROPERTIES"
1028 :group 'org-structure
1029 :group 'org-cycle
1030 :type '(repeat (string :tag "Drawer Name")))
1032 (defcustom org-hide-block-startup nil
1033 "Non-nil means entering Org-mode will fold all blocks.
1034 This can also be set in on a per-file basis with
1036 #+STARTUP: hideblocks
1037 #+STARTUP: showblocks"
1038 :group 'org-startup
1039 :group 'org-cycle
1040 :type 'boolean)
1042 (defcustom org-cycle-global-at-bob nil
1043 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1044 This makes it possible to do global cycling without having to use S-TAB or
1045 \\[universal-argument] TAB. For this special case to work, the first line
1046 of the buffer must not be a headline -- it may be empty or some other text.
1047 When used in this way, `org-cycle-hook' is disabled temporarily to make
1048 sure the cursor stays at the beginning of the buffer. When this option is
1049 nil, don't do anything special at the beginning of the buffer."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-level-after-item/entry-creation t
1054 "Non-nil means cycle entry level or item indentation in new empty entries.
1056 When the cursor is at the end of an empty headline, i.e., with only stars
1057 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1058 and then all possible ancestor states, before returning to the original state.
1059 This makes data entry extremely fast: M-RET to create a new headline,
1060 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1062 When the cursor is at the end of an empty plain list item, one TAB will
1063 make it a subitem, two or more tabs will back up to make this an item
1064 higher up in the item hierarchy."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-emulate-tab t
1069 "Where should `org-cycle' emulate TAB.
1070 nil Never
1071 white Only in completely white lines
1072 whitestart Only at the beginning of lines, before the first non-white char
1073 t Everywhere except in headlines
1074 exc-hl-bol Everywhere except at the start of a headline
1075 If TAB is used in a place where it does not emulate TAB, the current subtree
1076 visibility is cycled."
1077 :group 'org-cycle
1078 :type '(choice (const :tag "Never" nil)
1079 (const :tag "Only in completely white lines" white)
1080 (const :tag "Before first char in a line" whitestart)
1081 (const :tag "Everywhere except in headlines" t)
1082 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1085 (defcustom org-cycle-separator-lines 2
1086 "Number of empty lines needed to keep an empty line between collapsed trees.
1087 If you leave an empty line between the end of a subtree and the following
1088 headline, this empty line is hidden when the subtree is folded.
1089 Org-mode will leave (exactly) one empty line visible if the number of
1090 empty lines is equal or larger to the number given in this variable.
1091 So the default 2 means at least 2 empty lines after the end of a subtree
1092 are needed to produce free space between a collapsed subtree and the
1093 following headline.
1095 If the number is negative, and the number of empty lines is at least -N,
1096 all empty lines are shown.
1098 Special case: when 0, never leave empty lines in collapsed view."
1099 :group 'org-cycle
1100 :type 'integer)
1101 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1103 (defcustom org-pre-cycle-hook nil
1104 "Hook that is run before visibility cycling is happening.
1105 The function(s) in this hook must accept a single argument which indicates
1106 the new state that will be set right after running this hook. The
1107 argument is a symbol. Before a global state change, it can have the values
1108 `overview', `content', or `all'. Before a local state change, it can have
1109 the values `folded', `children', or `subtree'."
1110 :group 'org-cycle
1111 :type 'hook)
1113 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1114 org-cycle-hide-drawers
1115 org-cycle-hide-inline-tasks
1116 org-cycle-show-empty-lines
1117 org-optimize-window-after-visibility-change)
1118 "Hook that is run after `org-cycle' has changed the buffer visibility.
1119 The function(s) in this hook must accept a single argument which indicates
1120 the new state that was set by the most recent `org-cycle' command. The
1121 argument is a symbol. After a global state change, it can have the values
1122 `overview', `contents', or `all'. After a local state change, it can have
1123 the values `folded', `children', or `subtree'."
1124 :group 'org-cycle
1125 :type 'hook)
1127 (defgroup org-edit-structure nil
1128 "Options concerning structure editing in Org-mode."
1129 :tag "Org Edit Structure"
1130 :group 'org-structure)
1132 (defcustom org-odd-levels-only nil
1133 "Non-nil means skip even levels and only use odd levels for the outline.
1134 This has the effect that two stars are being added/taken away in
1135 promotion/demotion commands. It also influences how levels are
1136 handled by the exporters.
1137 Changing it requires restart of `font-lock-mode' to become effective
1138 for fontification also in regions already fontified.
1139 You may also set this on a per-file basis by adding one of the following
1140 lines to the buffer:
1142 #+STARTUP: odd
1143 #+STARTUP: oddeven"
1144 :group 'org-edit-structure
1145 :group 'org-appearance
1146 :type 'boolean)
1148 (defcustom org-adapt-indentation t
1149 "Non-nil means adapt indentation to outline node level.
1151 When this variable is set, Org assumes that you write outlines by
1152 indenting text in each node to align with the headline (after the stars).
1153 The following issues are influenced by this variable:
1155 - When this is set and the *entire* text in an entry is indented, the
1156 indentation is increased by one space in a demotion command, and
1157 decreased by one in a promotion command. If any line in the entry
1158 body starts with text at column 0, indentation is not changed at all.
1160 - Property drawers and planning information is inserted indented when
1161 this variable s set. When nil, they will not be indented.
1163 - TAB indents a line relative to context. The lines below a headline
1164 will be indented when this variable is set.
1166 Note that this is all about true indentation, by adding and removing
1167 space characters. See also `org-indent.el' which does level-dependent
1168 indentation in a virtual way, i.e. at display time in Emacs."
1169 :group 'org-edit-structure
1170 :type 'boolean)
1172 (defcustom org-special-ctrl-a/e nil
1173 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1175 When t, `C-a' will bring back the cursor to the beginning of the
1176 headline text, i.e. after the stars and after a possible TODO
1177 keyword. In an item, this will be the position after bullet and
1178 check-box, if any. When the cursor is already at that position,
1179 another `C-a' will bring it to the beginning of the line.
1181 `C-e' will jump to the end of the headline, ignoring the presence
1182 of tags in the headline. A second `C-e' will then jump to the
1183 true end of the line, after any tags. This also means that, when
1184 this variable is non-nil, `C-e' also will never jump beyond the
1185 end of the heading of a folded section, i.e. not after the
1186 ellipses.
1188 When set to the symbol `reversed', the first `C-a' or `C-e' works
1189 normally, going to the true line boundary first. Only a directly
1190 following, identical keypress will bring the cursor to the
1191 special positions.
1193 This may also be a cons cell where the behavior for `C-a' and
1194 `C-e' is set separately."
1195 :group 'org-edit-structure
1196 :type '(choice
1197 (const :tag "off" nil)
1198 (const :tag "on: after stars/bullet and before tags first" t)
1199 (const :tag "reversed: true line boundary first" reversed)
1200 (cons :tag "Set C-a and C-e separately"
1201 (choice :tag "Special C-a"
1202 (const :tag "off" nil)
1203 (const :tag "on: after stars/bullet first" t)
1204 (const :tag "reversed: before stars/bullet first" reversed))
1205 (choice :tag "Special C-e"
1206 (const :tag "off" nil)
1207 (const :tag "on: before tags first" t)
1208 (const :tag "reversed: after tags first" reversed)))))
1209 (if (fboundp 'defvaralias)
1210 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1212 (defcustom org-special-ctrl-k nil
1213 "Non-nil means `C-k' will behave specially in headlines.
1214 When nil, `C-k' will call the default `kill-line' command.
1215 When t, the following will happen while the cursor is in the headline:
1217 - When the cursor is at the beginning of a headline, kill the entire
1218 line and possible the folded subtree below the line.
1219 - When in the middle of the headline text, kill the headline up to the tags.
1220 - When after the headline text, kill the tags."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-ctrl-k-protect-subtree nil
1225 "Non-nil means, do not delete a hidden subtree with C-k.
1226 When set to the symbol `error', simply throw an error when C-k is
1227 used to kill (part-of) a headline that has hidden text behind it.
1228 Any other non-nil value will result in a query to the user, if it is
1229 OK to kill that hidden subtree. When nil, kill without remorse."
1230 :group 'org-edit-structure
1231 :version "24.1"
1232 :type '(choice
1233 (const :tag "Do not protect hidden subtrees" nil)
1234 (const :tag "Protect hidden subtrees with a security query" t)
1235 (const :tag "Never kill a hidden subtree with C-k" error)))
1237 (defcustom org-catch-invisible-edits nil
1238 "Check if in invisible region before inserting or deleting a character.
1239 Valid values are:
1241 nil Do not check, so just do invisible edits.
1242 error Throw an error and do nothing.
1243 show Make point visible, and do the requested edit.
1244 show-and-error Make point visible, then throw an error and abort the edit.
1245 smart Make point visible, and do insertion/deletion if it is
1246 adjacent to visible text and the change feels predictable.
1247 Never delete a previously invisible character or add in the
1248 middle or right after an invisible region. Basically, this
1249 allows insertion and backward-delete right before ellipses.
1250 FIXME: maybe in this case we should not even show?"
1251 :group 'org-edit-structure
1252 :version "24.1"
1253 :type '(choice
1254 (const :tag "Do not check" nil)
1255 (const :tag "Throw error when trying to edit" error)
1256 (const :tag "Unhide, but do not do the edit" show-and-error)
1257 (const :tag "Show invisible part and do the edit" show)
1258 (const :tag "Be smart and do the right thing" smart)))
1260 (defcustom org-yank-folded-subtrees t
1261 "Non-nil means when yanking subtrees, fold them.
1262 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1263 it starts with a heading and all other headings in it are either children
1264 or siblings, then fold all the subtrees. However, do this only if no
1265 text after the yank would be swallowed into a folded tree by this action."
1266 :group 'org-edit-structure
1267 :type 'boolean)
1269 (defcustom org-yank-adjusted-subtrees nil
1270 "Non-nil means when yanking subtrees, adjust the level.
1271 With this setting, `org-paste-subtree' is used to insert the subtree, see
1272 this function for details."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-M-RET-may-split-line '((default . t))
1277 "Non-nil means M-RET will split the line at the cursor position.
1278 When nil, it will go to the end of the line before making a
1279 new line.
1280 You may also set this option in a different way for different
1281 contexts. Valid contexts are:
1283 headline when creating a new headline
1284 item when creating a new item
1285 table in a table field
1286 default the value to be used for all contexts not explicitly
1287 customized"
1288 :group 'org-structure
1289 :group 'org-table
1290 :type '(choice
1291 (const :tag "Always" t)
1292 (const :tag "Never" nil)
1293 (repeat :greedy t :tag "Individual contexts"
1294 (cons
1295 (choice :tag "Context"
1296 (const headline)
1297 (const item)
1298 (const table)
1299 (const default))
1300 (boolean)))))
1303 (defcustom org-insert-heading-respect-content nil
1304 "Non-nil means insert new headings after the current subtree.
1305 When nil, the new heading is created directly after the current line.
1306 The commands \\[org-insert-heading-respect-content] and
1307 \\[org-insert-todo-heading-respect-content] turn this variable on
1308 for the duration of the command."
1309 :group 'org-structure
1310 :type 'boolean)
1312 (defcustom org-blank-before-new-entry '((heading . auto)
1313 (plain-list-item . auto))
1314 "Should `org-insert-heading' leave a blank line before new heading/item?
1315 The value is an alist, with `heading' and `plain-list-item' as CAR,
1316 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1317 which case Org will look at the surrounding headings/items and try to
1318 make an intelligent decision whether to insert a blank line or not.
1320 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1321 set, the setting here is ignored and no empty line is inserted, to avoid
1322 breaking the list structure."
1323 :group 'org-edit-structure
1324 :type '(list
1325 (cons (const heading)
1326 (choice (const :tag "Never" nil)
1327 (const :tag "Always" t)
1328 (const :tag "Auto" auto)))
1329 (cons (const plain-list-item)
1330 (choice (const :tag "Never" nil)
1331 (const :tag "Always" t)
1332 (const :tag "Auto" auto)))))
1334 (defcustom org-insert-heading-hook nil
1335 "Hook being run after inserting a new heading."
1336 :group 'org-edit-structure
1337 :type 'hook)
1339 (defcustom org-enable-fixed-width-editor t
1340 "Non-nil means lines starting with \":\" are treated as fixed-width.
1341 This currently only means they are never auto-wrapped.
1342 When nil, such lines will be treated like ordinary lines.
1343 See also the QUOTE keyword."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-goto-auto-isearch t
1348 "Non-nil means typing characters in `org-goto' starts incremental search.
1349 When nil, you can use these keybindings to navigate the buffer:
1351 q Quit the org-goto interface
1352 n Go to the next visible heading
1353 p Go to the previous visible heading
1354 f Go one heading forward on same level
1355 b Go one heading backward on same level
1356 u Go one heading up"
1357 :group 'org-edit-structure
1358 :type 'boolean)
1360 (defgroup org-sparse-trees nil
1361 "Options concerning sparse trees in Org-mode."
1362 :tag "Org Sparse Trees"
1363 :group 'org-structure)
1365 (defcustom org-highlight-sparse-tree-matches t
1366 "Non-nil means highlight all matches that define a sparse tree.
1367 The highlights will automatically disappear the next time the buffer is
1368 changed by an edit command."
1369 :group 'org-sparse-trees
1370 :type 'boolean)
1372 (defcustom org-remove-highlights-with-change t
1373 "Non-nil means any change to the buffer will remove temporary highlights.
1374 Such highlights are created by `org-occur' and `org-clock-display'.
1375 When nil, `C-c C-c needs to be used to get rid of the highlights.
1376 The highlights created by `org-preview-latex-fragment' always need
1377 `C-c C-c' to be removed."
1378 :group 'org-sparse-trees
1379 :group 'org-time
1380 :type 'boolean)
1383 (defcustom org-occur-hook '(org-first-headline-recenter)
1384 "Hook that is run after `org-occur' has constructed a sparse tree.
1385 This can be used to recenter the window to show as much of the structure
1386 as possible."
1387 :group 'org-sparse-trees
1388 :type 'hook)
1390 (defgroup org-imenu-and-speedbar nil
1391 "Options concerning imenu and speedbar in Org-mode."
1392 :tag "Org Imenu and Speedbar"
1393 :group 'org-structure)
1395 (defcustom org-imenu-depth 2
1396 "The maximum level for Imenu access to Org-mode headlines.
1397 This also applied for speedbar access."
1398 :group 'org-imenu-and-speedbar
1399 :type 'integer)
1401 (defgroup org-table nil
1402 "Options concerning tables in Org-mode."
1403 :tag "Org Table"
1404 :group 'org)
1406 (defcustom org-enable-table-editor 'optimized
1407 "Non-nil means lines starting with \"|\" are handled by the table editor.
1408 When nil, such lines will be treated like ordinary lines.
1410 When equal to the symbol `optimized', the table editor will be optimized to
1411 do the following:
1412 - Automatic overwrite mode in front of whitespace in table fields.
1413 This makes the structure of the table stay in tact as long as the edited
1414 field does not exceed the column width.
1415 - Minimize the number of realigns. Normally, the table is aligned each time
1416 TAB or RET are pressed to move to another field. With optimization this
1417 happens only if changes to a field might have changed the column width.
1418 Optimization requires replacing the functions `self-insert-command',
1419 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1420 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1421 very good at guessing when a re-align will be necessary, but you can always
1422 force one with \\[org-ctrl-c-ctrl-c].
1424 If you would like to use the optimized version in Org-mode, but the
1425 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1427 This variable can be used to turn on and off the table editor during a session,
1428 but in order to toggle optimization, a restart is required.
1430 See also the variable `org-table-auto-blank-field'."
1431 :group 'org-table
1432 :type '(choice
1433 (const :tag "off" nil)
1434 (const :tag "on" t)
1435 (const :tag "on, optimized" optimized)))
1437 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1438 (version<= emacs-version "24.1"))
1439 "Non-nil means cluster self-insert commands for undo when possible.
1440 If this is set, then, like in the Emacs command loop, 20 consecutive
1441 characters will be undone together.
1442 This is configurable, because there is some impact on typing performance."
1443 :group 'org-table
1444 :type 'boolean)
1446 (defcustom org-table-tab-recognizes-table.el t
1447 "Non-nil means TAB will automatically notice a table.el table.
1448 When it sees such a table, it moves point into it and - if necessary -
1449 calls `table-recognize-table'."
1450 :group 'org-table-editing
1451 :type 'boolean)
1453 (defgroup org-link nil
1454 "Options concerning links in Org-mode."
1455 :tag "Org Link"
1456 :group 'org)
1458 (defvar org-link-abbrev-alist-local nil
1459 "Buffer-local version of `org-link-abbrev-alist', which see.
1460 The value of this is taken from the #+LINK lines.")
1461 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1463 (defcustom org-link-abbrev-alist nil
1464 "Alist of link abbreviations.
1465 The car of each element is a string, to be replaced at the start of a link.
1466 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1467 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1469 [[linkkey:tag][description]]
1471 The 'linkkey' must be a word word, starting with a letter, followed
1472 by letters, numbers, '-' or '_'.
1474 If REPLACE is a string, the tag will simply be appended to create the link.
1475 If the string contains \"%s\", the tag will be inserted there. If the string
1476 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1477 at that point (see the function `url-hexify-string'). If the string contains
1478 the specifier \"%(my-function)\", then the custom function `my-function' will
1479 be invoked: this function takes the tag as its only argument and must return
1480 a string.
1482 REPLACE may also be a function that will be called with the tag as the
1483 only argument to create the link, which should be returned as a string.
1485 See the manual for examples."
1486 :group 'org-link
1487 :type '(repeat
1488 (cons
1489 (string :tag "Protocol")
1490 (choice
1491 (string :tag "Format")
1492 (function)))))
1494 (defcustom org-descriptive-links t
1495 "Non-nil means Org will display descriptive links.
1496 E.g. [[http://orgmode.org][Org website]] will be displayed as
1497 \"Org Website\", hiding the link itself and just displaying its
1498 description. When set to `nil', Org will display the full links
1499 literally.
1501 You can interactively set the value of this variable by calling
1502 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1503 :group 'org-link
1504 :type 'boolean)
1506 (defcustom org-link-file-path-type 'adaptive
1507 "How the path name in file links should be stored.
1508 Valid values are:
1510 relative Relative to the current directory, i.e. the directory of the file
1511 into which the link is being inserted.
1512 absolute Absolute path, if possible with ~ for home directory.
1513 noabbrev Absolute path, no abbreviation of home directory.
1514 adaptive Use relative path for files in the current directory and sub-
1515 directories of it. For other files, use an absolute path."
1516 :group 'org-link
1517 :type '(choice
1518 (const relative)
1519 (const absolute)
1520 (const noabbrev)
1521 (const adaptive)))
1523 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1524 "Types of links that should be activated in Org-mode files.
1525 This is a list of symbols, each leading to the activation of a certain link
1526 type. In principle, it does not hurt to turn on most link types - there may
1527 be a small gain when turning off unused link types. The types are:
1529 bracket The recommended [[link][description]] or [[link]] links with hiding.
1530 angle Links in angular brackets that may contain whitespace like
1531 <bbdb:Carsten Dominik>.
1532 plain Plain links in normal text, no whitespace, like http://google.com.
1533 radio Text that is matched by a radio target, see manual for details.
1534 tag Tag settings in a headline (link to tag search).
1535 date Time stamps (link to calendar).
1536 footnote Footnote labels.
1538 Changing this variable requires a restart of Emacs to become effective."
1539 :group 'org-link
1540 :type '(set :greedy t
1541 (const :tag "Double bracket links" bracket)
1542 (const :tag "Angular bracket links" angle)
1543 (const :tag "Plain text links" plain)
1544 (const :tag "Radio target matches" radio)
1545 (const :tag "Tags" tag)
1546 (const :tag "Timestamps" date)
1547 (const :tag "Footnotes" footnote)))
1549 (defcustom org-make-link-description-function nil
1550 "Function to use for generating link descriptions from links.
1551 When nil, the link location will be used. This function must take
1552 two parameters: the first one is the link, the second one is the
1553 description generated by `org-insert-link'. The function should
1554 return the description to use."
1555 :group 'org-link
1556 :type 'function)
1558 (defgroup org-link-store nil
1559 "Options concerning storing links in Org-mode."
1560 :tag "Org Store Link"
1561 :group 'org-link)
1563 (defcustom org-url-hexify-p t
1564 "When non-nil, hexify URL when creating a link."
1565 :type 'boolean
1566 :version "24.3"
1567 :group 'org-link-store)
1569 (defcustom org-email-link-description-format "Email %c: %.30s"
1570 "Format of the description part of a link to an email or usenet message.
1571 The following %-escapes will be replaced by corresponding information:
1573 %F full \"From\" field
1574 %f name, taken from \"From\" field, address if no name
1575 %T full \"To\" field
1576 %t first name in \"To\" field, address if no name
1577 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1578 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1579 %s subject
1580 %d date
1581 %m message-id.
1583 You may use normal field width specification between the % and the letter.
1584 This is for example useful to limit the length of the subject.
1586 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1587 :group 'org-link-store
1588 :type 'string)
1590 (defcustom org-from-is-user-regexp
1591 (let (r1 r2)
1592 (when (and user-mail-address (not (string= user-mail-address "")))
1593 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1594 (when (and user-full-name (not (string= user-full-name "")))
1595 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1596 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1597 "Regexp matched against the \"From:\" header of an email or usenet message.
1598 It should match if the message is from the user him/herself."
1599 :group 'org-link-store
1600 :type 'regexp)
1602 (defcustom org-context-in-file-links t
1603 "Non-nil means file links from `org-store-link' contain context.
1604 A search string will be added to the file name with :: as separator and
1605 used to find the context when the link is activated by the command
1606 `org-open-at-point'. When this option is t, the entire active region
1607 will be placed in the search string of the file link. If set to a
1608 positive integer, only the first n lines of context will be stored.
1610 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1611 negates this setting for the duration of the command."
1612 :group 'org-link-store
1613 :type '(choice boolean integer))
1615 (defcustom org-keep-stored-link-after-insertion nil
1616 "Non-nil means keep link in list for entire session.
1618 The command `org-store-link' adds a link pointing to the current
1619 location to an internal list. These links accumulate during a session.
1620 The command `org-insert-link' can be used to insert links into any
1621 Org-mode file (offering completion for all stored links). When this
1622 option is nil, every link which has been inserted once using \\[org-insert-link]
1623 will be removed from the list, to make completing the unused links
1624 more efficient."
1625 :group 'org-link-store
1626 :type 'boolean)
1628 (defgroup org-link-follow nil
1629 "Options concerning following links in Org-mode."
1630 :tag "Org Follow Link"
1631 :group 'org-link)
1633 (defcustom org-link-translation-function nil
1634 "Function to translate links with different syntax to Org syntax.
1635 This can be used to translate links created for example by the Planner
1636 or emacs-wiki packages to Org syntax.
1637 The function must accept two parameters, a TYPE containing the link
1638 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1639 which is everything after the link protocol. It should return a cons
1640 with possibly modified values of type and path.
1641 Org contains a function for this, so if you set this variable to
1642 `org-translate-link-from-planner', you should be able follow many
1643 links created by planner."
1644 :group 'org-link-follow
1645 :type 'function)
1647 (defcustom org-follow-link-hook nil
1648 "Hook that is run after a link has been followed."
1649 :group 'org-link-follow
1650 :type 'hook)
1652 (defcustom org-tab-follows-link nil
1653 "Non-nil means on links TAB will follow the link.
1654 Needs to be set before org.el is loaded.
1655 This really should not be used, it does not make sense, and the
1656 implementation is bad."
1657 :group 'org-link-follow
1658 :type 'boolean)
1660 (defcustom org-return-follows-link nil
1661 "Non-nil means on links RET will follow the link."
1662 :group 'org-link-follow
1663 :type 'boolean)
1665 (defcustom org-mouse-1-follows-link
1666 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1667 "Non-nil means mouse-1 on a link will follow the link.
1668 A longer mouse click will still set point. Does not work on XEmacs.
1669 Needs to be set before org.el is loaded."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mark-ring-length 4
1674 "Number of different positions to be recorded in the ring.
1675 Changing this requires a restart of Emacs to work correctly."
1676 :group 'org-link-follow
1677 :type 'integer)
1679 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1680 "Non-nil means internal links in Org files must exactly match a headline.
1681 When nil, the link search tries to match a phrase with all words
1682 in the search text."
1683 :group 'org-link-follow
1684 :version "24.1"
1685 :type '(choice
1686 (const :tag "Use fuzzy text search" nil)
1687 (const :tag "Match only exact headline" t)
1688 (const :tag "Match exact headline or query to create it"
1689 query-to-create)))
1691 (defcustom org-link-frame-setup
1692 '((vm . vm-visit-folder-other-frame)
1693 (vm-imap . vm-visit-imap-folder-other-frame)
1694 (gnus . org-gnus-no-new-news)
1695 (file . find-file-other-window)
1696 (wl . wl-other-frame))
1697 "Setup the frame configuration for following links.
1698 When following a link with Emacs, it may often be useful to display
1699 this link in another window or frame. This variable can be used to
1700 set this up for the different types of links.
1701 For VM, use any of
1702 `vm-visit-folder'
1703 `vm-visit-folder-other-window'
1704 `vm-visit-folder-other-frame'
1705 For Gnus, use any of
1706 `gnus'
1707 `gnus-other-frame'
1708 `org-gnus-no-new-news'
1709 For FILE, use any of
1710 `find-file'
1711 `find-file-other-window'
1712 `find-file-other-frame'
1713 For Wanderlust use any of
1714 `wl'
1715 `wl-other-frame'
1716 For the calendar, use the variable `calendar-setup'.
1717 For BBDB, it is currently only possible to display the matches in
1718 another window."
1719 :group 'org-link-follow
1720 :type '(list
1721 (cons (const vm)
1722 (choice
1723 (const vm-visit-folder)
1724 (const vm-visit-folder-other-window)
1725 (const vm-visit-folder-other-frame)))
1726 (cons (const gnus)
1727 (choice
1728 (const gnus)
1729 (const gnus-other-frame)
1730 (const org-gnus-no-new-news)))
1731 (cons (const file)
1732 (choice
1733 (const find-file)
1734 (const find-file-other-window)
1735 (const find-file-other-frame)))
1736 (cons (const wl)
1737 (choice
1738 (const wl)
1739 (const wl-other-frame)))))
1741 (defcustom org-display-internal-link-with-indirect-buffer nil
1742 "Non-nil means use indirect buffer to display infile links.
1743 Activating internal links (from one location in a file to another location
1744 in the same file) normally just jumps to the location. When the link is
1745 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1746 is displayed in
1747 another window. When this option is set, the other window actually displays
1748 an indirect buffer clone of the current buffer, to avoid any visibility
1749 changes to the current buffer."
1750 :group 'org-link-follow
1751 :type 'boolean)
1753 (defcustom org-open-non-existing-files nil
1754 "Non-nil means `org-open-file' will open non-existing files.
1755 When nil, an error will be generated.
1756 This variable applies only to external applications because they
1757 might choke on non-existing files. If the link is to a file that
1758 will be opened in Emacs, the variable is ignored."
1759 :group 'org-link-follow
1760 :type 'boolean)
1762 (defcustom org-open-directory-means-index-dot-org nil
1763 "Non-nil means a link to a directory really means to index.org.
1764 When nil, following a directory link will run dired or open a finder/explorer
1765 window on that directory."
1766 :group 'org-link-follow
1767 :type 'boolean)
1769 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1770 "Function and arguments to call for following mailto links.
1771 This is a list with the first element being a Lisp function, and the
1772 remaining elements being arguments to the function. In string arguments,
1773 %a will be replaced by the address, and %s will be replaced by the subject
1774 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1775 :group 'org-link-follow
1776 :type '(choice
1777 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1778 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1779 (const :tag "message-mail" (message-mail "%a" "%s"))
1780 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1782 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1783 "Non-nil means ask for confirmation before executing shell links.
1784 Shell links can be dangerous: just think about a link
1786 [[shell:rm -rf ~/*][Google Search]]
1788 This link would show up in your Org-mode document as \"Google Search\",
1789 but really it would remove your entire home directory.
1790 Therefore we advise against setting this variable to nil.
1791 Just change it to `y-or-n-p' if you want to confirm with a
1792 single keystroke rather than having to type \"yes\"."
1793 :group 'org-link-follow
1794 :type '(choice
1795 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1796 (const :tag "with y-or-n (faster)" y-or-n-p)
1797 (const :tag "no confirmation (dangerous)" nil)))
1798 (put 'org-confirm-shell-link-function
1799 'safe-local-variable
1800 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1802 (defcustom org-confirm-shell-link-not-regexp ""
1803 "A regexp to skip confirmation for shell links."
1804 :group 'org-link-follow
1805 :version "24.1"
1806 :type 'regexp)
1808 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1809 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1810 Elisp links can be dangerous: just think about a link
1812 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1814 This link would show up in your Org-mode document as \"Google Search\",
1815 but really it would remove your entire home directory.
1816 Therefore we advise against setting this variable to nil.
1817 Just change it to `y-or-n-p' if you want to confirm with a
1818 single keystroke rather than having to type \"yes\"."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1822 (const :tag "with y-or-n (faster)" y-or-n-p)
1823 (const :tag "no confirmation (dangerous)" nil)))
1824 (put 'org-confirm-shell-link-function
1825 'safe-local-variable
1826 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1828 (defcustom org-confirm-elisp-link-not-regexp ""
1829 "A regexp to skip confirmation for Elisp links."
1830 :group 'org-link-follow
1831 :version "24.1"
1832 :type 'regexp)
1834 (defconst org-file-apps-defaults-gnu
1835 '((remote . emacs)
1836 (system . mailcap)
1837 (t . mailcap))
1838 "Default file applications on a UNIX or GNU/Linux system.
1839 See `org-file-apps'.")
1841 (defconst org-file-apps-defaults-macosx
1842 '((remote . emacs)
1843 (t . "open %s")
1844 (system . "open %s")
1845 ("ps.gz" . "gv %s")
1846 ("eps.gz" . "gv %s")
1847 ("dvi" . "xdvi %s")
1848 ("fig" . "xfig %s"))
1849 "Default file applications on a MacOS X system.
1850 The system \"open\" is known as a default, but we use X11 applications
1851 for some files for which the OS does not have a good default.
1852 See `org-file-apps'.")
1854 (defconst org-file-apps-defaults-windowsnt
1855 (list
1856 '(remote . emacs)
1857 (cons t
1858 (list (if (featurep 'xemacs)
1859 'mswindows-shell-execute
1860 'w32-shell-execute)
1861 "open" 'file))
1862 (cons 'system
1863 (list (if (featurep 'xemacs)
1864 'mswindows-shell-execute
1865 'w32-shell-execute)
1866 "open" 'file)))
1867 "Default file applications on a Windows NT system.
1868 The system \"open\" is used for most files.
1869 See `org-file-apps'.")
1871 (defcustom org-file-apps
1873 (auto-mode . emacs)
1874 ("\\.mm\\'" . default)
1875 ("\\.x?html?\\'" . default)
1876 ("\\.pdf\\'" . default)
1878 "External applications for opening `file:path' items in a document.
1879 Org-mode uses system defaults for different file types, but
1880 you can use this variable to set the application for a given file
1881 extension. The entries in this list are cons cells where the car identifies
1882 files and the cdr the corresponding command. Possible values for the
1883 file identifier are
1884 \"string\" A string as a file identifier can be interpreted in different
1885 ways, depending on its contents:
1887 - Alphanumeric characters only:
1888 Match links with this file extension.
1889 Example: (\"pdf\" . \"evince %s\")
1890 to open PDFs with evince.
1892 - Regular expression: Match links where the
1893 filename matches the regexp. If you want to
1894 use groups here, use shy groups.
1896 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1897 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1898 to open *.html and *.xhtml with firefox.
1900 - Regular expression which contains (non-shy) groups:
1901 Match links where the whole link, including \"::\", and
1902 anything after that, matches the regexp.
1903 In a custom command string, %1, %2, etc. are replaced with
1904 the parts of the link that were matched by the groups.
1905 For backwards compatibility, if a command string is given
1906 that does not use any of the group matches, this case is
1907 handled identically to the second one (i.e. match against
1908 file name only).
1909 In a custom lisp form, you can access the group matches with
1910 (match-string n link).
1912 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1913 to open [[file:document.pdf::5]] with evince at page 5.
1915 `directory' Matches a directory
1916 `remote' Matches a remote file, accessible through tramp or efs.
1917 Remote files most likely should be visited through Emacs
1918 because external applications cannot handle such paths.
1919 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1920 so all files Emacs knows how to handle. Using this with
1921 command `emacs' will open most files in Emacs. Beware that this
1922 will also open html files inside Emacs, unless you add
1923 (\"html\" . default) to the list as well.
1924 t Default for files not matched by any of the other options.
1925 `system' The system command to open files, like `open' on Windows
1926 and Mac OS X, and mailcap under GNU/Linux. This is the command
1927 that will be selected if you call `C-c C-o' with a double
1928 \\[universal-argument] \\[universal-argument] prefix.
1930 Possible values for the command are:
1931 `emacs' The file will be visited by the current Emacs process.
1932 `default' Use the default application for this file type, which is the
1933 association for t in the list, most likely in the system-specific
1934 part.
1935 This can be used to overrule an unwanted setting in the
1936 system-specific variable.
1937 `system' Use the system command for opening files, like \"open\".
1938 This command is specified by the entry whose car is `system'.
1939 Most likely, the system-specific version of this variable
1940 does define this command, but you can overrule/replace it
1941 here.
1942 string A command to be executed by a shell; %s will be replaced
1943 by the path to the file.
1944 sexp A Lisp form which will be evaluated. The file path will
1945 be available in the Lisp variable `file'.
1946 For more examples, see the system specific constants
1947 `org-file-apps-defaults-macosx'
1948 `org-file-apps-defaults-windowsnt'
1949 `org-file-apps-defaults-gnu'."
1950 :group 'org-link-follow
1951 :type '(repeat
1952 (cons (choice :value ""
1953 (string :tag "Extension")
1954 (const :tag "System command to open files" system)
1955 (const :tag "Default for unrecognized files" t)
1956 (const :tag "Remote file" remote)
1957 (const :tag "Links to a directory" directory)
1958 (const :tag "Any files that have Emacs modes"
1959 auto-mode))
1960 (choice :value ""
1961 (const :tag "Visit with Emacs" emacs)
1962 (const :tag "Use default" default)
1963 (const :tag "Use the system command" system)
1964 (string :tag "Command")
1965 (sexp :tag "Lisp form")))))
1967 (defcustom org-doi-server-url "http://dx.doi.org/"
1968 "The URL of the DOI server."
1969 :type 'string
1970 :version "24.3"
1971 :group 'org-link-follow)
1973 (defgroup org-refile nil
1974 "Options concerning refiling entries in Org-mode."
1975 :tag "Org Refile"
1976 :group 'org)
1978 (defcustom org-directory "~/org"
1979 "Directory with org files.
1980 This is just a default location to look for Org files. There is no need
1981 at all to put your files into this directory. It is only used in the
1982 following situations:
1984 1. When a capture template specifies a target file that is not an
1985 absolute path. The path will then be interpreted relative to
1986 `org-directory'
1987 2. When a capture note is filed away in an interactive way (when exiting the
1988 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1989 with `org-directory' as the default path."
1990 :group 'org-refile
1991 :group 'org-remember
1992 :group 'org-capture
1993 :type 'directory)
1995 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1996 "Default target for storing notes.
1997 Used as a fall back file for org-remember.el and org-capture.el, for
1998 templates that do not specify a target file."
1999 :group 'org-refile
2000 :group 'org-remember
2001 :group 'org-capture
2002 :type '(choice
2003 (const :tag "Default from remember-data-file" nil)
2004 file))
2006 (defcustom org-goto-interface 'outline
2007 "The default interface to be used for `org-goto'.
2008 Allowed values are:
2009 outline The interface shows an outline of the relevant file
2010 and the correct heading is found by moving through
2011 the outline or by searching with incremental search.
2012 outline-path-completion Headlines in the current buffer are offered via
2013 completion. This is the interface also used by
2014 the refile command."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Outline" outline)
2018 (const :tag "Outline-path-completion" outline-path-completion)))
2020 (defcustom org-goto-max-level 5
2021 "Maximum target level when running `org-goto' with refile interface."
2022 :group 'org-refile
2023 :type 'integer)
2025 (defcustom org-reverse-note-order nil
2026 "Non-nil means store new notes at the beginning of a file or entry.
2027 When nil, new notes will be filed to the end of a file or entry.
2028 This can also be a list with cons cells of regular expressions that
2029 are matched against file names, and values."
2030 :group 'org-remember
2031 :group 'org-capture
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Reverse always" t)
2035 (const :tag "Reverse never" nil)
2036 (repeat :tag "By file name regexp"
2037 (cons regexp boolean))))
2039 (defcustom org-log-refile nil
2040 "Information to record when a task is refiled.
2042 Possible values are:
2044 nil Don't add anything
2045 time Add a time stamp to the task
2046 note Prompt for a note and add it with template `org-log-note-headings'
2048 This option can also be set with on a per-file-basis with
2050 #+STARTUP: nologrefile
2051 #+STARTUP: logrefile
2052 #+STARTUP: lognoterefile
2054 You can have local logging settings for a subtree by setting the LOGGING
2055 property to one or more of these keywords.
2057 When bulk-refiling from the agenda, the value `note' is forbidden and
2058 will temporarily be changed to `time'."
2059 :group 'org-refile
2060 :group 'org-progress
2061 :version "24.1"
2062 :type '(choice
2063 (const :tag "No logging" nil)
2064 (const :tag "Record timestamp" time)
2065 (const :tag "Record timestamp with note." note)))
2067 (defcustom org-refile-targets nil
2068 "Targets for refiling entries with \\[org-refile].
2069 This is a list of cons cells. Each cell contains:
2070 - a specification of the files to be considered, either a list of files,
2071 or a symbol whose function or variable value will be used to retrieve
2072 a file name or a list of file names. If you use `org-agenda-files' for
2073 that, all agenda files will be scanned for targets. Nil means consider
2074 headings in the current buffer.
2075 - A specification of how to find candidate refile targets. This may be
2076 any of:
2077 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2078 This tag has to be present in all target headlines, inheritance will
2079 not be considered.
2080 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2081 todo keyword.
2082 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2083 headlines that are refiling targets.
2084 - a cons cell (:level . N). Any headline of level N is considered a target.
2085 Note that, when `org-odd-levels-only' is set, level corresponds to
2086 order in hierarchy, not to the number of stars.
2087 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2088 Note that, when `org-odd-levels-only' is set, level corresponds to
2089 order in hierarchy, not to the number of stars.
2091 Each element of this list generates a set of possible targets.
2092 The union of these sets is presented (with completion) to
2093 the user by `org-refile'.
2095 You can set the variable `org-refile-target-verify-function' to a function
2096 to verify each headline found by the simple criteria above.
2098 When this variable is nil, all top-level headlines in the current buffer
2099 are used, equivalent to the value `((nil . (:level . 1))'."
2100 :group 'org-refile
2101 :type '(repeat
2102 (cons
2103 (choice :value org-agenda-files
2104 (const :tag "All agenda files" org-agenda-files)
2105 (const :tag "Current buffer" nil)
2106 (function) (variable) (file))
2107 (choice :tag "Identify target headline by"
2108 (cons :tag "Specific tag" (const :value :tag) (string))
2109 (cons :tag "TODO keyword" (const :value :todo) (string))
2110 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2111 (cons :tag "Level number" (const :value :level) (integer))
2112 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2114 (defcustom org-refile-target-verify-function nil
2115 "Function to verify if the headline at point should be a refile target.
2116 The function will be called without arguments, with point at the
2117 beginning of the headline. It should return t and leave point
2118 where it is if the headline is a valid target for refiling.
2120 If the target should not be selected, the function must return nil.
2121 In addition to this, it may move point to a place from where the search
2122 should be continued. For example, the function may decide that the entire
2123 subtree of the current entry should be excluded and move point to the end
2124 of the subtree."
2125 :group 'org-refile
2126 :type 'function)
2128 (defcustom org-refile-use-cache nil
2129 "Non-nil means cache refile targets to speed up the process.
2130 The cache for a particular file will be updated automatically when
2131 the buffer has been killed, or when any of the marker used for flagging
2132 refile targets no longer points at a live buffer.
2133 If you have added new entries to a buffer that might themselves be targets,
2134 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2135 find that easier, `C-u C-u C-u C-c C-w'."
2136 :group 'org-refile
2137 :version "24.1"
2138 :type 'boolean)
2140 (defcustom org-refile-use-outline-path nil
2141 "Non-nil means provide refile targets as paths.
2142 So a level 3 headline will be available as level1/level2/level3.
2144 When the value is `file', also include the file name (without directory)
2145 into the path. In this case, you can also stop the completion after
2146 the file name, to get entries inserted as top level in the file.
2148 When `full-file-path', include the full file path."
2149 :group 'org-refile
2150 :type '(choice
2151 (const :tag "Not" nil)
2152 (const :tag "Yes" t)
2153 (const :tag "Start with file name" file)
2154 (const :tag "Start with full file path" full-file-path)))
2156 (defcustom org-outline-path-complete-in-steps t
2157 "Non-nil means complete the outline path in hierarchical steps.
2158 When Org-mode uses the refile interface to select an outline path
2159 \(see variable `org-refile-use-outline-path'), the completion of
2160 the path can be done is a single go, or if can be done in steps down
2161 the headline hierarchy. Going in steps is probably the best if you
2162 do not use a special completion package like `ido' or `icicles'.
2163 However, when using these packages, going in one step can be very
2164 fast, while still showing the whole path to the entry."
2165 :group 'org-refile
2166 :type 'boolean)
2168 (defcustom org-refile-allow-creating-parent-nodes nil
2169 "Non-nil means allow to create new nodes as refile targets.
2170 New nodes are then created by adding \"/new node name\" to the completion
2171 of an existing node. When the value of this variable is `confirm',
2172 new node creation must be confirmed by the user (recommended)
2173 When nil, the completion must match an existing entry.
2175 Note that, if the new heading is not seen by the criteria
2176 listed in `org-refile-targets', multiple instances of the same
2177 heading would be created by trying again to file under the new
2178 heading."
2179 :group 'org-refile
2180 :type '(choice
2181 (const :tag "Never" nil)
2182 (const :tag "Always" t)
2183 (const :tag "Prompt for confirmation" confirm)))
2185 (defcustom org-refile-active-region-within-subtree nil
2186 "Non-nil means also refile active region within a subtree.
2188 By default `org-refile' doesn't allow refiling regions if they
2189 don't contain a set of subtrees, but it might be convenient to
2190 do so sometimes: in that case, the first line of the region is
2191 converted to a headline before refiling."
2192 :group 'org-refile
2193 :version "24.1"
2194 :type 'boolean)
2196 (defgroup org-todo nil
2197 "Options concerning TODO items in Org-mode."
2198 :tag "Org TODO"
2199 :group 'org)
2201 (defgroup org-progress nil
2202 "Options concerning Progress logging in Org-mode."
2203 :tag "Org Progress"
2204 :group 'org-time)
2206 (defvar org-todo-interpretation-widgets
2207 '((:tag "Sequence (cycling hits every state)" sequence)
2208 (:tag "Type (cycling directly to DONE)" type))
2209 "The available interpretation symbols for customizing `org-todo-keywords'.
2210 Interested libraries should add to this list.")
2212 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2213 "List of TODO entry keyword sequences and their interpretation.
2214 \\<org-mode-map>This is a list of sequences.
2216 Each sequence starts with a symbol, either `sequence' or `type',
2217 indicating if the keywords should be interpreted as a sequence of
2218 action steps, or as different types of TODO items. The first
2219 keywords are states requiring action - these states will select a headline
2220 for inclusion into the global TODO list Org-mode produces. If one of
2221 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2222 signify that no further action is necessary. If \"|\" is not found,
2223 the last keyword is treated as the only DONE state of the sequence.
2225 The command \\[org-todo] cycles an entry through these states, and one
2226 additional state where no keyword is present. For details about this
2227 cycling, see the manual.
2229 TODO keywords and interpretation can also be set on a per-file basis with
2230 the special #+SEQ_TODO and #+TYP_TODO lines.
2232 Each keyword can optionally specify a character for fast state selection
2233 \(in combination with the variable `org-use-fast-todo-selection')
2234 and specifiers for state change logging, using the same syntax that
2235 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2236 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2237 indicates to record a time stamp each time this state is selected.
2239 Each keyword may also specify if a timestamp or a note should be
2240 recorded when entering or leaving the state, by adding additional
2241 characters in the parenthesis after the keyword. This looks like this:
2242 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2243 record only the time of the state change. With X and Y being either
2244 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2245 Y when leaving the state if and only if the *target* state does not
2246 define X. You may omit any of the fast-selection key or X or /Y,
2247 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2249 For backward compatibility, this variable may also be just a list
2250 of keywords. In this case the interpretation (sequence or type) will be
2251 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2252 :group 'org-todo
2253 :group 'org-keywords
2254 :type '(choice
2255 (repeat :tag "Old syntax, just keywords"
2256 (string :tag "Keyword"))
2257 (repeat :tag "New syntax"
2258 (cons
2259 (choice
2260 :tag "Interpretation"
2261 ;;Quick and dirty way to see
2262 ;;`org-todo-interpretations'. This takes the
2263 ;;place of item arguments
2264 :convert-widget
2265 (lambda (widget)
2266 (widget-put widget
2267 :args (mapcar
2268 #'(lambda (x)
2269 (widget-convert
2270 (cons 'const x)))
2271 org-todo-interpretation-widgets))
2272 widget))
2273 (repeat
2274 (string :tag "Keyword"))))))
2276 (defvar org-todo-keywords-1 nil
2277 "All TODO and DONE keywords active in a buffer.")
2278 (make-variable-buffer-local 'org-todo-keywords-1)
2279 (defvar org-todo-keywords-for-agenda nil)
2280 (defvar org-done-keywords-for-agenda nil)
2281 (defvar org-drawers-for-agenda nil)
2282 (defvar org-todo-keyword-alist-for-agenda nil)
2283 (defvar org-tag-alist-for-agenda nil)
2284 (defvar org-agenda-contributing-files nil)
2285 (defvar org-not-done-keywords nil)
2286 (make-variable-buffer-local 'org-not-done-keywords)
2287 (defvar org-done-keywords nil)
2288 (make-variable-buffer-local 'org-done-keywords)
2289 (defvar org-todo-heads nil)
2290 (make-variable-buffer-local 'org-todo-heads)
2291 (defvar org-todo-sets nil)
2292 (make-variable-buffer-local 'org-todo-sets)
2293 (defvar org-todo-log-states nil)
2294 (make-variable-buffer-local 'org-todo-log-states)
2295 (defvar org-todo-kwd-alist nil)
2296 (make-variable-buffer-local 'org-todo-kwd-alist)
2297 (defvar org-todo-key-alist nil)
2298 (make-variable-buffer-local 'org-todo-key-alist)
2299 (defvar org-todo-key-trigger nil)
2300 (make-variable-buffer-local 'org-todo-key-trigger)
2302 (defcustom org-todo-interpretation 'sequence
2303 "Controls how TODO keywords are interpreted.
2304 This variable is in principle obsolete and is only used for
2305 backward compatibility, if the interpretation of todo keywords is
2306 not given already in `org-todo-keywords'. See that variable for
2307 more information."
2308 :group 'org-todo
2309 :group 'org-keywords
2310 :type '(choice (const sequence)
2311 (const type)))
2313 (defcustom org-use-fast-todo-selection t
2314 "Non-nil means use the fast todo selection scheme with C-c C-t.
2315 This variable describes if and under what circumstances the cycling
2316 mechanism for TODO keywords will be replaced by a single-key, direct
2317 selection scheme.
2319 When nil, fast selection is never used.
2321 When the symbol `prefix', it will be used when `org-todo' is called
2322 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2323 `C-u t' in an agenda buffer.
2325 When t, fast selection is used by default. In this case, the prefix
2326 argument forces cycling instead.
2328 In all cases, the special interface is only used if access keys have
2329 actually been assigned by the user, i.e. if keywords in the configuration
2330 are followed by a letter in parenthesis, like TODO(t)."
2331 :group 'org-todo
2332 :type '(choice
2333 (const :tag "Never" nil)
2334 (const :tag "By default" t)
2335 (const :tag "Only with C-u C-c C-t" prefix)))
2337 (defcustom org-provide-todo-statistics t
2338 "Non-nil means update todo statistics after insert and toggle.
2339 ALL-HEADLINES means update todo statistics by including headlines
2340 with no TODO keyword as well, counting them as not done.
2341 A list of TODO keywords means the same, but skip keywords that are
2342 not in this list.
2344 When this is set, todo statistics is updated in the parent of the
2345 current entry each time a todo state is changed."
2346 :group 'org-todo
2347 :type '(choice
2348 (const :tag "Yes, only for TODO entries" t)
2349 (const :tag "Yes, including all entries" 'all-headlines)
2350 (repeat :tag "Yes, for TODOs in this list"
2351 (string :tag "TODO keyword"))
2352 (other :tag "No TODO statistics" nil)))
2354 (defcustom org-hierarchical-todo-statistics t
2355 "Non-nil means TODO statistics covers just direct children.
2356 When nil, all entries in the subtree are considered.
2357 This has only an effect if `org-provide-todo-statistics' is set.
2358 To set this to nil for only a single subtree, use a COOKIE_DATA
2359 property and include the word \"recursive\" into the value."
2360 :group 'org-todo
2361 :type 'boolean)
2363 (defcustom org-after-todo-state-change-hook nil
2364 "Hook which is run after the state of a TODO item was changed.
2365 The new state (a string with a TODO keyword, or nil) is available in the
2366 Lisp variable `org-state'."
2367 :group 'org-todo
2368 :type 'hook)
2370 (defvar org-blocker-hook nil
2371 "Hook for functions that are allowed to block a state change.
2373 Functions in this hook should not modify the buffer.
2374 Each function gets as its single argument a property list,
2375 see `org-trigger-hook' for more information about this list.
2377 If any of the functions in this hook returns nil, the state change
2378 is blocked.")
2380 (defvar org-trigger-hook nil
2381 "Hook for functions that are triggered by a state change.
2383 Each function gets as its single argument a property list with at
2384 least the following elements:
2386 (:type type-of-change :position pos-at-entry-start
2387 :from old-state :to new-state)
2389 Depending on the type, more properties may be present.
2391 This mechanism is currently implemented for:
2393 TODO state changes
2394 ------------------
2395 :type todo-state-change
2396 :from previous state (keyword as a string), or nil, or a symbol
2397 'todo' or 'done', to indicate the general type of state.
2398 :to new state, like in :from")
2400 (defcustom org-enforce-todo-dependencies nil
2401 "Non-nil means undone TODO entries will block switching the parent to DONE.
2402 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2403 be blocked if any prior sibling is not yet done.
2404 Finally, if the parent is blocked because of ordered siblings of its own,
2405 the child will also be blocked."
2406 :set (lambda (var val)
2407 (set var val)
2408 (if val
2409 (add-hook 'org-blocker-hook
2410 'org-block-todo-from-children-or-siblings-or-parent)
2411 (remove-hook 'org-blocker-hook
2412 'org-block-todo-from-children-or-siblings-or-parent)))
2413 :group 'org-todo
2414 :type 'boolean)
2416 (defcustom org-enforce-todo-checkbox-dependencies nil
2417 "Non-nil means unchecked boxes will block switching the parent to DONE.
2418 When this is nil, checkboxes have no influence on switching TODO states.
2419 When non-nil, you first need to check off all check boxes before the TODO
2420 entry can be switched to DONE.
2421 This variable needs to be set before org.el is loaded, and you need to
2422 restart Emacs after a change to make the change effective. The only way
2423 to change is while Emacs is running is through the customize interface."
2424 :set (lambda (var val)
2425 (set var val)
2426 (if val
2427 (add-hook 'org-blocker-hook
2428 'org-block-todo-from-checkboxes)
2429 (remove-hook 'org-blocker-hook
2430 'org-block-todo-from-checkboxes)))
2431 :group 'org-todo
2432 :type 'boolean)
2434 (defcustom org-treat-insert-todo-heading-as-state-change nil
2435 "Non-nil means inserting a TODO heading is treated as state change.
2436 So when the command \\[org-insert-todo-heading] is used, state change
2437 logging will apply if appropriate. When nil, the new TODO item will
2438 be inserted directly, and no logging will take place."
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2443 "Non-nil means switching TODO states with S-cursor counts as state change.
2444 This is the default behavior. However, setting this to nil allows a
2445 convenient way to select a TODO state and bypass any logging associated
2446 with that."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-todo-state-tags-triggers nil
2451 "Tag changes that should be triggered by TODO state changes.
2452 This is a list. Each entry is
2454 (state-change (tag . flag) .......)
2456 State-change can be a string with a state, and empty string to indicate the
2457 state that has no TODO keyword, or it can be one of the symbols `todo'
2458 or `done', meaning any not-done or done state, respectively."
2459 :group 'org-todo
2460 :group 'org-tags
2461 :type '(repeat
2462 (cons (choice :tag "When changing to"
2463 (const :tag "Not-done state" todo)
2464 (const :tag "Done state" done)
2465 (string :tag "State"))
2466 (repeat
2467 (cons :tag "Tag action"
2468 (string :tag "Tag")
2469 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2471 (defcustom org-log-done nil
2472 "Information to record when a task moves to the DONE state.
2474 Possible values are:
2476 nil Don't add anything, just change the keyword
2477 time Add a time stamp to the task
2478 note Prompt for a note and add it with template `org-log-note-headings'
2480 This option can also be set with on a per-file-basis with
2482 #+STARTUP: nologdone
2483 #+STARTUP: logdone
2484 #+STARTUP: lognotedone
2486 You can have local logging settings for a subtree by setting the LOGGING
2487 property to one or more of these keywords."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "No logging" nil)
2492 (const :tag "Record CLOSED timestamp" time)
2493 (const :tag "Record CLOSED timestamp with note." note)))
2495 ;; Normalize old uses of org-log-done.
2496 (cond
2497 ((eq org-log-done t) (setq org-log-done 'time))
2498 ((and (listp org-log-done) (memq 'done org-log-done))
2499 (setq org-log-done 'note)))
2501 (defcustom org-log-reschedule nil
2502 "Information to record when the scheduling date of a tasks is modified.
2504 Possible values are:
2506 nil Don't add anything, just change the date
2507 time Add a time stamp to the task
2508 note Prompt for a note and add it with template `org-log-note-headings'
2510 This option can also be set with on a per-file-basis with
2512 #+STARTUP: nologreschedule
2513 #+STARTUP: logreschedule
2514 #+STARTUP: lognotereschedule"
2515 :group 'org-todo
2516 :group 'org-progress
2517 :type '(choice
2518 (const :tag "No logging" nil)
2519 (const :tag "Record timestamp" time)
2520 (const :tag "Record timestamp with note." note)))
2522 (defcustom org-log-redeadline nil
2523 "Information to record when the deadline date of a tasks is modified.
2525 Possible values are:
2527 nil Don't add anything, just change the date
2528 time Add a time stamp to the task
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologredeadline
2534 #+STARTUP: logredeadline
2535 #+STARTUP: lognoteredeadline
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "No logging" nil)
2543 (const :tag "Record timestamp" time)
2544 (const :tag "Record timestamp with note." note)))
2546 (defcustom org-log-note-clock-out nil
2547 "Non-nil means record a note when clocking out of an item.
2548 This can also be configured on a per-file basis by adding one of
2549 the following lines anywhere in the buffer:
2551 #+STARTUP: lognoteclock-out
2552 #+STARTUP: nolognoteclock-out"
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type 'boolean)
2557 (defcustom org-log-done-with-time t
2558 "Non-nil means the CLOSED time stamp will contain date and time.
2559 When nil, only the date will be recorded."
2560 :group 'org-progress
2561 :type 'boolean)
2563 (defcustom org-log-note-headings
2564 '((done . "CLOSING NOTE %t")
2565 (state . "State %-12s from %-12S %t")
2566 (note . "Note taken on %t")
2567 (reschedule . "Rescheduled from %S on %t")
2568 (delschedule . "Not scheduled, was %S on %t")
2569 (redeadline . "New deadline from %S on %t")
2570 (deldeadline . "Removed deadline, was %S on %t")
2571 (refile . "Refiled on %t")
2572 (clock-out . ""))
2573 "Headings for notes added to entries.
2574 The value is an alist, with the car being a symbol indicating the note
2575 context, and the cdr is the heading to be used. The heading may also be the
2576 empty string.
2577 %t in the heading will be replaced by a time stamp.
2578 %T will be an active time stamp instead the default inactive one
2579 %d will be replaced by a short-format time stamp.
2580 %D will be replaced by an active short-format time stamp.
2581 %s will be replaced by the new TODO state, in double quotes.
2582 %S will be replaced by the old TODO state, in double quotes.
2583 %u will be replaced by the user name.
2584 %U will be replaced by the full user name.
2586 In fact, it is not a good idea to change the `state' entry, because
2587 agenda log mode depends on the format of these entries."
2588 :group 'org-todo
2589 :group 'org-progress
2590 :type '(list :greedy t
2591 (cons (const :tag "Heading when closing an item" done) string)
2592 (cons (const :tag
2593 "Heading when changing todo state (todo sequence only)"
2594 state) string)
2595 (cons (const :tag "Heading when just taking a note" note) string)
2596 (cons (const :tag "Heading when clocking out" clock-out) string)
2597 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2598 (cons (const :tag "Heading when rescheduling" reschedule) string)
2599 (cons (const :tag "Heading when changing deadline" redeadline) string)
2600 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2601 (cons (const :tag "Heading when refiling" refile) string)))
2603 (unless (assq 'note org-log-note-headings)
2604 (push '(note . "%t") org-log-note-headings))
2606 (defcustom org-log-into-drawer nil
2607 "Non-nil means insert state change notes and time stamps into a drawer.
2608 When nil, state changes notes will be inserted after the headline and
2609 any scheduling and clock lines, but not inside a drawer.
2611 The value of this variable should be the name of the drawer to use.
2612 LOGBOOK is proposed as the default drawer for this purpose, you can
2613 also set this to a string to define the drawer of your choice.
2615 A value of t is also allowed, representing \"LOGBOOK\".
2617 A value of t or nil can also be set with on a per-file-basis with
2619 #+STARTUP: logdrawer
2620 #+STARTUP: nologdrawer
2622 If this variable is set, `org-log-state-notes-insert-after-drawers'
2623 will be ignored.
2625 You can set the property LOG_INTO_DRAWER to overrule this setting for
2626 a subtree."
2627 :group 'org-todo
2628 :group 'org-progress
2629 :type '(choice
2630 (const :tag "Not into a drawer" nil)
2631 (const :tag "LOGBOOK" t)
2632 (string :tag "Other")))
2634 (if (fboundp 'defvaralias)
2635 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2637 (defun org-log-into-drawer ()
2638 "Return the value of `org-log-into-drawer', but let properties overrule.
2639 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2640 used instead of the default value."
2641 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2642 (cond
2643 ((not p) org-log-into-drawer)
2644 ((equal p "nil") nil)
2645 ((equal p "t") "LOGBOOK")
2646 (t p))))
2648 (defcustom org-log-state-notes-insert-after-drawers nil
2649 "Non-nil means insert state change notes after any drawers in entry.
2650 Only the drawers that *immediately* follow the headline and the
2651 deadline/scheduled line are skipped.
2652 When nil, insert notes right after the heading and perhaps the line
2653 with deadline/scheduling if present.
2655 This variable will have no effect if `org-log-into-drawer' is
2656 set."
2657 :group 'org-todo
2658 :group 'org-progress
2659 :type 'boolean)
2661 (defcustom org-log-states-order-reversed t
2662 "Non-nil means the latest state note will be directly after heading.
2663 When nil, the state change notes will be ordered according to time.
2665 This option can also be set with on a per-file-basis with
2667 #+STARTUP: logstatesreversed
2668 #+STARTUP: nologstatesreversed"
2669 :group 'org-todo
2670 :group 'org-progress
2671 :type 'boolean)
2673 (defcustom org-todo-repeat-to-state nil
2674 "The TODO state to which a repeater should return the repeating task.
2675 By default this is the first task in a TODO sequence, or the previous state
2676 in a TODO_TYP set. But you can specify another task here.
2677 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2678 :group 'org-todo
2679 :version "24.1"
2680 :type '(choice (const :tag "Head of sequence" nil)
2681 (string :tag "Specific state")))
2683 (defcustom org-log-repeat 'time
2684 "Non-nil means record moving through the DONE state when triggering repeat.
2685 An auto-repeating task is immediately switched back to TODO when
2686 marked DONE. If you are not logging state changes (by adding \"@\"
2687 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2688 record a closing note, there will be no record of the task moving
2689 through DONE. This variable forces taking a note anyway.
2691 nil Don't force a record
2692 time Record a time stamp
2693 note Prompt for a note and add it with template `org-log-note-headings'
2695 This option can also be set with on a per-file-basis with
2697 #+STARTUP: nologrepeat
2698 #+STARTUP: logrepeat
2699 #+STARTUP: lognoterepeat
2701 You can have local logging settings for a subtree by setting the LOGGING
2702 property to one or more of these keywords."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type '(choice
2706 (const :tag "Don't force a record" nil)
2707 (const :tag "Force recording the DONE state" time)
2708 (const :tag "Force recording a note with the DONE state" note)))
2711 (defgroup org-priorities nil
2712 "Priorities in Org-mode."
2713 :tag "Org Priorities"
2714 :group 'org-todo)
2716 (defcustom org-enable-priority-commands t
2717 "Non-nil means priority commands are active.
2718 When nil, these commands will be disabled, so that you never accidentally
2719 set a priority."
2720 :group 'org-priorities
2721 :type 'boolean)
2723 (defcustom org-highest-priority ?A
2724 "The highest priority of TODO items. A character like ?A, ?B etc.
2725 Must have a smaller ASCII number than `org-lowest-priority'."
2726 :group 'org-priorities
2727 :type 'character)
2729 (defcustom org-lowest-priority ?C
2730 "The lowest priority of TODO items. A character like ?A, ?B etc.
2731 Must have a larger ASCII number than `org-highest-priority'."
2732 :group 'org-priorities
2733 :type 'character)
2735 (defcustom org-default-priority ?B
2736 "The default priority of TODO items.
2737 This is the priority an item gets if no explicit priority is given.
2738 When starting to cycle on an empty priority the first step in the cycle
2739 depends on `org-priority-start-cycle-with-default'. The resulting first
2740 step priority must not exceed the range from `org-highest-priority' to
2741 `org-lowest-priority' which means that `org-default-priority' has to be
2742 in this range exclusive or inclusive the range boundaries. Else the
2743 first step refuses to set the default and the second will fall back
2744 to (depending on the command used) the highest or lowest priority."
2745 :group 'org-priorities
2746 :type 'character)
2748 (defcustom org-priority-start-cycle-with-default t
2749 "Non-nil means start with default priority when starting to cycle.
2750 When this is nil, the first step in the cycle will be (depending on the
2751 command used) one higher or lower than the default priority.
2752 See also `org-default-priority'."
2753 :group 'org-priorities
2754 :type 'boolean)
2756 (defcustom org-get-priority-function nil
2757 "Function to extract the priority from a string.
2758 The string is normally the headline. If this is nil Org computes the
2759 priority from the priority cookie like [#A] in the headline. It returns
2760 an integer, increasing by 1000 for each priority level.
2761 The user can set a different function here, which should take a string
2762 as an argument and return the numeric priority."
2763 :group 'org-priorities
2764 :version "24.1"
2765 :type 'function)
2767 (defgroup org-time nil
2768 "Options concerning time stamps and deadlines in Org-mode."
2769 :tag "Org Time"
2770 :group 'org)
2772 (defcustom org-insert-labeled-timestamps-at-point nil
2773 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2774 When nil, these labeled time stamps are forces into the second line of an
2775 entry, just after the headline. When scheduling from the global TODO list,
2776 the time stamp will always be forced into the second line."
2777 :group 'org-time
2778 :type 'boolean)
2780 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2781 "Formats for `format-time-string' which are used for time stamps.
2782 It is not recommended to change this constant.")
2784 (defcustom org-time-stamp-rounding-minutes '(0 5)
2785 "Number of minutes to round time stamps to.
2786 These are two values, the first applies when first creating a time stamp.
2787 The second applies when changing it with the commands `S-up' and `S-down'.
2788 When changing the time stamp, this means that it will change in steps
2789 of N minutes, as given by the second value.
2791 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2792 numbers should be factors of 60, so for example 5, 10, 15.
2794 When this is larger than 1, you can still force an exact time stamp by using
2795 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2796 and by using a prefix arg to `S-up/down' to specify the exact number
2797 of minutes to shift."
2798 :group 'org-time
2799 :get #'(lambda (var) ; Make sure both elements are there
2800 (if (integerp (default-value var))
2801 (list (default-value var) 5)
2802 (default-value var)))
2803 :type '(list
2804 (integer :tag "when inserting times")
2805 (integer :tag "when modifying times")))
2807 ;; Normalize old customizations of this variable.
2808 (when (integerp org-time-stamp-rounding-minutes)
2809 (setq org-time-stamp-rounding-minutes
2810 (list org-time-stamp-rounding-minutes
2811 org-time-stamp-rounding-minutes)))
2813 (defcustom org-display-custom-times nil
2814 "Non-nil means overlay custom formats over all time stamps.
2815 The formats are defined through the variable `org-time-stamp-custom-formats'.
2816 To turn this on on a per-file basis, insert anywhere in the file:
2817 #+STARTUP: customtime"
2818 :group 'org-time
2819 :set 'set-default
2820 :type 'sexp)
2821 (make-variable-buffer-local 'org-display-custom-times)
2823 (defcustom org-time-stamp-custom-formats
2824 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2825 "Custom formats for time stamps. See `format-time-string' for the syntax.
2826 These are overlaid over the default ISO format if the variable
2827 `org-display-custom-times' is set. Time like %H:%M should be at the
2828 end of the second format. The custom formats are also honored by export
2829 commands, if custom time display is turned on at the time of export."
2830 :group 'org-time
2831 :type 'sexp)
2833 (defun org-time-stamp-format (&optional long inactive)
2834 "Get the right format for a time string."
2835 (let ((f (if long (cdr org-time-stamp-formats)
2836 (car org-time-stamp-formats))))
2837 (if inactive
2838 (concat "[" (substring f 1 -1) "]")
2839 f)))
2841 (defcustom org-time-clocksum-format
2842 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2843 "The format string used when creating CLOCKSUM lines.
2844 This is also used when Org mode generates a time duration.
2846 The value can be a single format string containing two
2847 %-sequences, which will be filled with the number of hours and
2848 minutes in that order.
2850 Alternatively, the value can be a plist associating any of the
2851 keys :years, :months, :weeks, :days, :hours or :minutes with
2852 format strings. The time duration is formatted using only the
2853 time components that are needed and concatenating the results.
2854 If a time unit in absent, it falls back to the next smallest
2855 unit.
2857 The keys :require-years, :require-months, :require-days,
2858 :require-weeks, :require-hours, :require-minutes are also
2859 meaningful. A non-nil value for these keys indicates that the
2860 corresponding time component should always be included, even if
2861 its value is 0.
2864 For example,
2866 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2867 :require-minutes t)
2869 means durations longer than a day will be expressed in days,
2870 hours and minutes, and durations less than a day will always be
2871 expressed in hours and minutes (even for durations less than an
2872 hour).
2874 The value
2876 \(:days \"%dd\" :minutes \"%dm\")
2878 means durations longer than a day will be expressed in days and
2879 minutes, and durations less than a day will be expressed entirely
2880 in minutes (even for durations longer than an hour)."
2881 :group 'org-time
2882 :group 'org-clock
2883 :version "24.3"
2884 :type '(choice (string :tag "Format string")
2885 (set :tag "Plist"
2886 (group :inline t (const :tag "Years" :years)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show years" :require-years)
2890 (const t))
2891 (group :inline t (const :tag "Months" :months)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show months" :require-months)
2895 (const t))
2896 (group :inline t (const :tag "Weeks" :weeks)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show weeks" :require-weeks)
2900 (const t))
2901 (group :inline t (const :tag "Days" :days)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show days" :require-days)
2905 (const t))
2906 (group :inline t (const :tag "Hours" :hours)
2907 (string :tag "Format string"))
2908 (group :inline t
2909 (const :tag "Always show hours" :require-hours)
2910 (const t))
2911 (group :inline t (const :tag "Minutes" :minutes)
2912 (string :tag "Format string"))
2913 (group :inline t
2914 (const :tag "Always show minutes" :require-minutes)
2915 (const t)))))
2917 (defcustom org-time-clocksum-use-fractional nil
2918 "When non-nil, \\[org-clock-display] uses fractional times.
2919 See `org-time-clocksum-format' for more on time clock formats."
2920 :group 'org-time
2921 :group 'org-clock
2922 :version "24.3"
2923 :type 'boolean)
2925 (defcustom org-time-clocksum-use-effort-durations t
2926 "When non-nil, \\[org-clock-display] uses effort durations.
2927 E.g. by default, one day is considered to be a 8 hours effort,
2928 so a task that has been clocked for 16 hours will be displayed
2929 as during 2 days in the clock display or in the clocktable.
2931 See `org-effort-durations' on how to set effort durations
2932 and `org-time-clocksum-format' for more on time clock formats."
2933 :group 'org-time
2934 :group 'org-clock
2935 :version "24.3"
2936 :type 'boolean)
2938 (defcustom org-time-clocksum-fractional-format "%.2f"
2939 "The format string used when creating CLOCKSUM lines,
2940 or when Org mode generates a time duration, if
2941 `org-time-clocksum-use-fractional' is enabled.
2943 The value can be a single format string containing one
2944 %-sequence, which will be filled with the number of hours as
2945 a float.
2947 Alternatively, the value can be a plist associating any of the
2948 keys :years, :months, :weeks, :days, :hours or :minutes with
2949 a format string. The time duration is formatted using the
2950 largest time unit which gives a non-zero integer part. If all
2951 specified formats have zero integer part, the smallest time unit
2952 is used."
2953 :group 'org-time
2954 :type '(choice (string :tag "Format string")
2955 (set (group :inline t (const :tag "Years" :years)
2956 (string :tag "Format string"))
2957 (group :inline t (const :tag "Months" :months)
2958 (string :tag "Format string"))
2959 (group :inline t (const :tag "Weeks" :weeks)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Days" :days)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Hours" :hours)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Minutes" :minutes)
2966 (string :tag "Format string")))))
2968 (defcustom org-deadline-warning-days 14
2969 "Number of days before expiration during which a deadline becomes active.
2970 This variable governs the display in sparse trees and in the agenda.
2971 When 0 or negative, it means use this number (the absolute value of it)
2972 even if a deadline has a different individual lead time specified.
2974 Custom commands can set this variable in the options section."
2975 :group 'org-time
2976 :group 'org-agenda-daily/weekly
2977 :type 'integer)
2979 (defcustom org-scheduled-delay-days 0
2980 "Number of days before a scheduled item becomes active.
2981 This variable governs the display in sparse trees and in the agenda.
2982 The default value (i.e. 0) means: don't delay scheduled item.
2983 When negative, it means use this number (the absolute value of it)
2984 even if a scheduled item has a different individual delay time
2985 specified.
2987 Custom commands can set this variable in the options section."
2988 :group 'org-time
2989 :group 'org-agenda-daily/weekly
2990 :version "24.3"
2991 :type 'integer)
2993 (defcustom org-read-date-prefer-future t
2994 "Non-nil means assume future for incomplete date input from user.
2995 This affects the following situations:
2996 1. The user gives a month but not a year.
2997 For example, if it is April and you enter \"feb 2\", this will be read
2998 as Feb 2, *next* year. \"May 5\", however, will be this year.
2999 2. The user gives a day, but no month.
3000 For example, if today is the 15th, and you enter \"3\", Org-mode will
3001 read this as the third of *next* month. However, if you enter \"17\",
3002 it will be considered as *this* month.
3004 If you set this variable to the symbol `time', then also the following
3005 will work:
3007 3. If the user gives a time.
3008 If the time is before now, it will be interpreted as tomorrow.
3010 Currently none of this works for ISO week specifications.
3012 When this option is nil, the current day, month and year will always be
3013 used as defaults.
3015 See also `org-agenda-jump-prefer-future'."
3016 :group 'org-time
3017 :type '(choice
3018 (const :tag "Never" nil)
3019 (const :tag "Check month and day" t)
3020 (const :tag "Check month, day, and time" time)))
3022 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3023 "Should the agenda jump command prefer the future for incomplete dates?
3024 The default is to do the same as configured in `org-read-date-prefer-future'.
3025 But you can also set a deviating value here.
3026 This may t or nil, or the symbol `org-read-date-prefer-future'."
3027 :group 'org-agenda
3028 :group 'org-time
3029 :version "24.1"
3030 :type '(choice
3031 (const :tag "Use org-read-date-prefer-future"
3032 org-read-date-prefer-future)
3033 (const :tag "Never" nil)
3034 (const :tag "Always" t)))
3036 (defcustom org-read-date-force-compatible-dates t
3037 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3039 Depending on the system Emacs is running on, certain dates cannot
3040 be represented with the type used internally to represent time.
3041 Dates between 1970-1-1 and 2038-1-1 can always be represented
3042 correctly. Some systems allow for earlier dates, some for later,
3043 some for both. One way to find out it to insert any date into an
3044 Org buffer, putting the cursor on the year and hitting S-up and
3045 S-down to test the range.
3047 When this variable is set to t, the date/time prompt will not let
3048 you specify dates outside the 1970-2037 range, so it is certain that
3049 these dates will work in whatever version of Emacs you are
3050 running, and also that you can move a file from one Emacs implementation
3051 to another. WHenever Org is forcing the year for you, it will display
3052 a message and beep.
3054 When this variable is nil, Org will check if the date is
3055 representable in the specific Emacs implementation you are using.
3056 If not, it will force a year, usually the current year, and beep
3057 to remind you. Currently this setting is not recommended because
3058 the likelihood that you will open your Org files in an Emacs that
3059 has limited date range is not negligible.
3061 A workaround for this problem is to use diary sexp dates for time
3062 stamps outside of this range."
3063 :group 'org-time
3064 :version "24.1"
3065 :type 'boolean)
3067 (defcustom org-read-date-display-live t
3068 "Non-nil means display current interpretation of date prompt live.
3069 This display will be in an overlay, in the minibuffer."
3070 :group 'org-time
3071 :type 'boolean)
3073 (defcustom org-read-date-popup-calendar t
3074 "Non-nil means pop up a calendar when prompting for a date.
3075 In the calendar, the date can be selected with mouse-1. However, the
3076 minibuffer will also be active, and you can simply enter the date as well.
3077 When nil, only the minibuffer will be available."
3078 :group 'org-time
3079 :type 'boolean)
3080 (if (fboundp 'defvaralias)
3081 (defvaralias 'org-popup-calendar-for-date-prompt
3082 'org-read-date-popup-calendar))
3084 (make-obsolete-variable
3085 'org-read-date-minibuffer-setup-hook
3086 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3087 (defcustom org-read-date-minibuffer-setup-hook nil
3088 "Hook to be used to set up keys for the date/time interface.
3089 Add key definitions to `minibuffer-local-map', which will be a
3090 temporary copy.
3092 WARNING: This option is obsolete, you should use
3093 `org-read-date-minibuffer-local-map' to set up keys."
3094 :group 'org-time
3095 :type 'hook)
3097 (defcustom org-extend-today-until 0
3098 "The hour when your day really ends. Must be an integer.
3099 This has influence for the following applications:
3100 - When switching the agenda to \"today\". It it is still earlier than
3101 the time given here, the day recognized as TODAY is actually yesterday.
3102 - When a date is read from the user and it is still before the time given
3103 here, the current date and time will be assumed to be yesterday, 23:59.
3104 Also, timestamps inserted in capture templates follow this rule.
3106 IMPORTANT: This is a feature whose implementation is and likely will
3107 remain incomplete. Really, it is only here because past midnight seems to
3108 be the favorite working time of John Wiegley :-)"
3109 :group 'org-time
3110 :type 'integer)
3112 (defcustom org-use-effective-time nil
3113 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3114 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3115 \"effective time\" of any timestamps between midnight and 8am will be
3116 23:59 of the previous day."
3117 :group 'org-time
3118 :version "24.1"
3119 :type 'boolean)
3121 (defcustom org-use-last-clock-out-time-as-effective-time nil
3122 "When non-nil, use the last clock out time for `org-todo'.
3123 Note that this option has precedence over the combined use of
3124 `org-use-effective-time' and `org-extend-today-until'."
3125 :group 'org-time
3126 ;; :version "24.3"
3127 :type 'boolean)
3129 (defcustom org-edit-timestamp-down-means-later nil
3130 "Non-nil means S-down will increase the time in a time stamp.
3131 When nil, S-up will increase."
3132 :group 'org-time
3133 :type 'boolean)
3135 (defcustom org-calendar-follow-timestamp-change t
3136 "Non-nil means make the calendar window follow timestamp changes.
3137 When a timestamp is modified and the calendar window is visible, it will be
3138 moved to the new date."
3139 :group 'org-time
3140 :type 'boolean)
3142 (defgroup org-tags nil
3143 "Options concerning tags in Org-mode."
3144 :tag "Org Tags"
3145 :group 'org)
3147 (defcustom org-tag-alist nil
3148 "List of tags allowed in Org-mode files.
3149 When this list is nil, Org-mode will base TAG input on what is already in the
3150 buffer.
3151 The value of this variable is an alist, the car of each entry must be a
3152 keyword as a string, the cdr may be a character that is used to select
3153 that tag through the fast-tag-selection interface.
3154 See the manual for details."
3155 :group 'org-tags
3156 :type '(repeat
3157 (choice
3158 (cons (string :tag "Tag name")
3159 (character :tag "Access char"))
3160 (list :tag "Start radio group"
3161 (const :startgroup)
3162 (option (string :tag "Group description")))
3163 (list :tag "End radio group"
3164 (const :endgroup)
3165 (option (string :tag "Group description")))
3166 (const :tag "New line" (:newline)))))
3168 (defcustom org-tag-persistent-alist nil
3169 "List of tags that will always appear in all Org-mode files.
3170 This is in addition to any in buffer settings or customizations
3171 of `org-tag-alist'.
3172 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3173 The value of this variable is an alist, the car of each entry must be a
3174 keyword as a string, the cdr may be a character that is used to select
3175 that tag through the fast-tag-selection interface.
3176 See the manual for details.
3177 To disable these tags on a per-file basis, insert anywhere in the file:
3178 #+STARTUP: noptag"
3179 :group 'org-tags
3180 :type '(repeat
3181 (choice
3182 (cons (string :tag "Tag name")
3183 (character :tag "Access char"))
3184 (const :tag "Start radio group" (:startgroup))
3185 (const :tag "End radio group" (:endgroup))
3186 (const :tag "New line" (:newline)))))
3188 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3189 "If non-nil, always offer completion for all tags of all agenda files.
3190 Instead of customizing this variable directly, you might want to
3191 set it locally for capture buffers, because there no list of
3192 tags in that file can be created dynamically (there are none).
3194 (add-hook 'org-capture-mode-hook
3195 (lambda ()
3196 (set (make-local-variable
3197 'org-complete-tags-always-offer-all-agenda-tags)
3198 t)))"
3199 :group 'org-tags
3200 :version "24.1"
3201 :type 'boolean)
3203 (defvar org-file-tags nil
3204 "List of tags that can be inherited by all entries in the file.
3205 The tags will be inherited if the variable `org-use-tag-inheritance'
3206 says they should be.
3207 This variable is populated from #+FILETAGS lines.")
3209 (defcustom org-use-fast-tag-selection 'auto
3210 "Non-nil means use fast tag selection scheme.
3211 This is a special interface to select and deselect tags with single keys.
3212 When nil, fast selection is never used.
3213 When the symbol `auto', fast selection is used if and only if selection
3214 characters for tags have been configured, either through the variable
3215 `org-tag-alist' or through a #+TAGS line in the buffer.
3216 When t, fast selection is always used and selection keys are assigned
3217 automatically if necessary."
3218 :group 'org-tags
3219 :type '(choice
3220 (const :tag "Always" t)
3221 (const :tag "Never" nil)
3222 (const :tag "When selection characters are configured" 'auto)))
3224 (defcustom org-fast-tag-selection-single-key nil
3225 "Non-nil means fast tag selection exits after first change.
3226 When nil, you have to press RET to exit it.
3227 During fast tag selection, you can toggle this flag with `C-c'.
3228 This variable can also have the value `expert'. In this case, the window
3229 displaying the tags menu is not even shown, until you press C-c again."
3230 :group 'org-tags
3231 :type '(choice
3232 (const :tag "No" nil)
3233 (const :tag "Yes" t)
3234 (const :tag "Expert" expert)))
3236 (defvar org-fast-tag-selection-include-todo nil
3237 "Non-nil means fast tags selection interface will also offer TODO states.
3238 This is an undocumented feature, you should not rely on it.")
3240 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3241 "The column to which tags should be indented in a headline.
3242 If this number is positive, it specifies the column. If it is negative,
3243 it means that the tags should be flushright to that column. For example,
3244 -80 works well for a normal 80 character screen.
3245 When 0, place tags directly after headline text, with only one space in
3246 between."
3247 :group 'org-tags
3248 :type 'integer)
3250 (defcustom org-auto-align-tags t
3251 "Non-nil keeps tags aligned when modifying headlines.
3252 Some operations (i.e. demoting) change the length of a headline and
3253 therefore shift the tags around. With this option turned on, after
3254 each such operation the tags are again aligned to `org-tags-column'."
3255 :group 'org-tags
3256 :type 'boolean)
3258 (defcustom org-use-tag-inheritance t
3259 "Non-nil means tags in levels apply also for sublevels.
3260 When nil, only the tags directly given in a specific line apply there.
3261 This may also be a list of tags that should be inherited, or a regexp that
3262 matches tags that should be inherited. Additional control is possible
3263 with the variable `org-tags-exclude-from-inheritance' which gives an
3264 explicit list of tags to be excluded from inheritance, even if the value of
3265 `org-use-tag-inheritance' would select it for inheritance.
3267 If this option is t, a match early-on in a tree can lead to a large
3268 number of matches in the subtree when constructing the agenda or creating
3269 a sparse tree. If you only want to see the first match in a tree during
3270 a search, check out the variable `org-tags-match-list-sublevels'."
3271 :group 'org-tags
3272 :type '(choice
3273 (const :tag "Not" nil)
3274 (const :tag "Always" t)
3275 (repeat :tag "Specific tags" (string :tag "Tag"))
3276 (regexp :tag "Tags matched by regexp")))
3278 (defcustom org-tags-exclude-from-inheritance nil
3279 "List of tags that should never be inherited.
3280 This is a way to exclude a few tags from inheritance. For way to do
3281 the opposite, to actively allow inheritance for selected tags,
3282 see the variable `org-use-tag-inheritance'."
3283 :group 'org-tags
3284 :type '(repeat (string :tag "Tag")))
3286 (defun org-tag-inherit-p (tag)
3287 "Check if TAG is one that should be inherited."
3288 (cond
3289 ((member tag org-tags-exclude-from-inheritance) nil)
3290 ((eq org-use-tag-inheritance t) t)
3291 ((not org-use-tag-inheritance) nil)
3292 ((stringp org-use-tag-inheritance)
3293 (string-match org-use-tag-inheritance tag))
3294 ((listp org-use-tag-inheritance)
3295 (member tag org-use-tag-inheritance))
3296 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3298 (defcustom org-tags-match-list-sublevels t
3299 "Non-nil means list also sublevels of headlines matching a search.
3300 This variable applies to tags/property searches, and also to stuck
3301 projects because this search is based on a tags match as well.
3303 When set to the symbol `indented', sublevels are indented with
3304 leading dots.
3306 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3307 the sublevels of a headline matching a tag search often also match
3308 the same search. Listing all of them can create very long lists.
3309 Setting this variable to nil causes subtrees of a match to be skipped.
3311 This variable is semi-obsolete and probably should always be true. It
3312 is better to limit inheritance to certain tags using the variables
3313 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3314 :group 'org-tags
3315 :type '(choice
3316 (const :tag "No, don't list them" nil)
3317 (const :tag "Yes, do list them" t)
3318 (const :tag "List them, indented with leading dots" indented)))
3320 (defcustom org-tags-sort-function nil
3321 "When set, tags are sorted using this function as a comparator."
3322 :group 'org-tags
3323 :type '(choice
3324 (const :tag "No sorting" nil)
3325 (const :tag "Alphabetical" string<)
3326 (const :tag "Reverse alphabetical" string>)
3327 (function :tag "Custom function" nil)))
3329 (defvar org-tags-history nil
3330 "History of minibuffer reads for tags.")
3331 (defvar org-last-tags-completion-table nil
3332 "The last used completion table for tags.")
3333 (defvar org-after-tags-change-hook nil
3334 "Hook that is run after the tags in a line have changed.")
3336 (defgroup org-properties nil
3337 "Options concerning properties in Org-mode."
3338 :tag "Org Properties"
3339 :group 'org)
3341 (defcustom org-property-format "%-10s %s"
3342 "How property key/value pairs should be formatted by `indent-line'.
3343 When `indent-line' hits a property definition, it will format the line
3344 according to this format, mainly to make sure that the values are
3345 lined-up with respect to each other."
3346 :group 'org-properties
3347 :type 'string)
3349 (defcustom org-properties-postprocess-alist nil
3350 "Alist of properties and functions to adjust inserted values.
3351 Elements of this alist must be of the form
3353 ([string] [function])
3355 where [string] must be a property name and [function] must be a
3356 lambda expression: this lambda expression must take one argument,
3357 the value to adjust, and return the new value as a string.
3359 For example, this element will allow the property \"Remaining\"
3360 to be updated wrt the relation between the \"Effort\" property
3361 and the clock summary:
3363 ((\"Remaining\" (lambda(value)
3364 (let ((clocksum (org-clock-sum-current-item))
3365 (effort (org-duration-string-to-minutes
3366 (org-entry-get (point) \"Effort\"))))
3367 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3368 :group 'org-properties
3369 :version "24.1"
3370 :type '(alist :key-type (string :tag "Property")
3371 :value-type (function :tag "Function")))
3373 (defcustom org-use-property-inheritance nil
3374 "Non-nil means properties apply also for sublevels.
3376 This setting is chiefly used during property searches. Turning it on can
3377 cause significant overhead when doing a search, which is why it is not
3378 on by default.
3380 When nil, only the properties directly given in the current entry count.
3381 When t, every property is inherited. The value may also be a list of
3382 properties that should have inheritance, or a regular expression matching
3383 properties that should be inherited.
3385 However, note that some special properties use inheritance under special
3386 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3387 and the properties ending in \"_ALL\" when they are used as descriptor
3388 for valid values of a property.
3390 Note for programmers:
3391 When querying an entry with `org-entry-get', you can control if inheritance
3392 should be used. By default, `org-entry-get' looks only at the local
3393 properties. You can request inheritance by setting the inherit argument
3394 to t (to force inheritance) or to `selective' (to respect the setting
3395 in this variable)."
3396 :group 'org-properties
3397 :type '(choice
3398 (const :tag "Not" nil)
3399 (const :tag "Always" t)
3400 (repeat :tag "Specific properties" (string :tag "Property"))
3401 (regexp :tag "Properties matched by regexp")))
3403 (defun org-property-inherit-p (property)
3404 "Check if PROPERTY is one that should be inherited."
3405 (cond
3406 ((eq org-use-property-inheritance t) t)
3407 ((not org-use-property-inheritance) nil)
3408 ((stringp org-use-property-inheritance)
3409 (string-match org-use-property-inheritance property))
3410 ((listp org-use-property-inheritance)
3411 (member property org-use-property-inheritance))
3412 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3414 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3415 "The default column format, if no other format has been defined.
3416 This variable can be set on the per-file basis by inserting a line
3418 #+COLUMNS: %25ITEM ....."
3419 :group 'org-properties
3420 :type 'string)
3422 (defcustom org-columns-ellipses ".."
3423 "The ellipses to be used when a field in column view is truncated.
3424 When this is the empty string, as many characters as possible are shown,
3425 but then there will be no visual indication that the field has been truncated.
3426 When this is a string of length N, the last N characters of a truncated
3427 field are replaced by this string. If the column is narrower than the
3428 ellipses string, only part of the ellipses string will be shown."
3429 :group 'org-properties
3430 :type 'string)
3432 (defcustom org-columns-modify-value-for-display-function nil
3433 "Function that modifies values for display in column view.
3434 For example, it can be used to cut out a certain part from a time stamp.
3435 The function must take 2 arguments:
3437 column-title The title of the column (*not* the property name)
3438 value The value that should be modified.
3440 The function should return the value that should be displayed,
3441 or nil if the normal value should be used."
3442 :group 'org-properties
3443 :type 'function)
3445 (defcustom org-effort-property "Effort"
3446 "The property that is being used to keep track of effort estimates.
3447 Effort estimates given in this property need to have the format H:MM."
3448 :group 'org-properties
3449 :group 'org-progress
3450 :type '(string :tag "Property"))
3452 (defconst org-global-properties-fixed
3453 '(("VISIBILITY_ALL" . "folded children content all")
3454 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3455 "List of property/value pairs that can be inherited by any entry.
3457 These are fixed values, for the preset properties. The user variable
3458 that can be used to add to this list is `org-global-properties'.
3460 The entries in this list are cons cells where the car is a property
3461 name and cdr is a string with the value. If the value represents
3462 multiple items like an \"_ALL\" property, separate the items by
3463 spaces.")
3465 (defcustom org-global-properties nil
3466 "List of property/value pairs that can be inherited by any entry.
3468 This list will be combined with the constant `org-global-properties-fixed'.
3470 The entries in this list are cons cells where the car is a property
3471 name and cdr is a string with the value.
3473 You can set buffer-local values for the same purpose in the variable
3474 `org-file-properties' this by adding lines like
3476 #+PROPERTY: NAME VALUE"
3477 :group 'org-properties
3478 :type '(repeat
3479 (cons (string :tag "Property")
3480 (string :tag "Value"))))
3482 (defvar org-file-properties nil
3483 "List of property/value pairs that can be inherited by any entry.
3484 Valid for the current buffer.
3485 This variable is populated from #+PROPERTY lines.")
3486 (make-variable-buffer-local 'org-file-properties)
3488 (defgroup org-agenda nil
3489 "Options concerning agenda views in Org-mode."
3490 :tag "Org Agenda"
3491 :group 'org)
3493 (defvar org-category nil
3494 "Variable used by org files to set a category for agenda display.
3495 Such files should use a file variable to set it, for example
3497 # -*- mode: org; org-category: \"ELisp\"
3499 or contain a special line
3501 #+CATEGORY: ELisp
3503 If the file does not specify a category, then file's base name
3504 is used instead.")
3505 (make-variable-buffer-local 'org-category)
3506 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3508 (defcustom org-agenda-files nil
3509 "The files to be used for agenda display.
3510 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3511 \\[org-remove-file]. You can also use customize to edit the list.
3513 If an entry is a directory, all files in that directory that are matched by
3514 `org-agenda-file-regexp' will be part of the file list.
3516 If the value of the variable is not a list but a single file name, then
3517 the list of agenda files is actually stored and maintained in that file, one
3518 agenda file per line. In this file paths can be given relative to
3519 `org-directory'. Tilde expansion and environment variable substitution
3520 are also made."
3521 :group 'org-agenda
3522 :type '(choice
3523 (repeat :tag "List of files and directories" file)
3524 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3526 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3527 "Regular expression to match files for `org-agenda-files'.
3528 If any element in the list in that variable contains a directory instead
3529 of a normal file, all files in that directory that are matched by this
3530 regular expression will be included."
3531 :group 'org-agenda
3532 :type 'regexp)
3534 (defcustom org-agenda-text-search-extra-files nil
3535 "List of extra files to be searched by text search commands.
3536 These files will be search in addition to the agenda files by the
3537 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3538 Note that these files will only be searched for text search commands,
3539 not for the other agenda views like todo lists, tag searches or the weekly
3540 agenda. This variable is intended to list notes and possibly archive files
3541 that should also be searched by these two commands.
3542 In fact, if the first element in the list is the symbol `agenda-archives',
3543 than all archive files of all agenda files will be added to the search
3544 scope."
3545 :group 'org-agenda
3546 :type '(set :greedy t
3547 (const :tag "Agenda Archives" agenda-archives)
3548 (repeat :inline t (file))))
3550 (if (fboundp 'defvaralias)
3551 (defvaralias 'org-agenda-multi-occur-extra-files
3552 'org-agenda-text-search-extra-files))
3554 (defcustom org-agenda-skip-unavailable-files nil
3555 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3556 A nil value means to remove them, after a query, from the list."
3557 :group 'org-agenda
3558 :type 'boolean)
3560 (defcustom org-calendar-to-agenda-key [?c]
3561 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3562 The command `org-calendar-goto-agenda' will be bound to this key. The
3563 default is the character `c' because then `c' can be used to switch back and
3564 forth between agenda and calendar."
3565 :group 'org-agenda
3566 :type 'sexp)
3568 (defcustom org-calendar-insert-diary-entry-key [?i]
3569 "The key to be installed in `calendar-mode-map' for adding diary entries.
3570 This option is irrelevant until `org-agenda-diary-file' has been configured
3571 to point to an Org-mode file. When that is the case, the command
3572 `org-agenda-diary-entry' will be bound to the key given here, by default
3573 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3574 if you want to continue doing this, you need to change this to a different
3575 key."
3576 :group 'org-agenda
3577 :type 'sexp)
3579 (defcustom org-agenda-diary-file 'diary-file
3580 "File to which to add new entries with the `i' key in agenda and calendar.
3581 When this is the symbol `diary-file', the functionality in the Emacs
3582 calendar will be used to add entries to the `diary-file'. But when this
3583 points to a file, `org-agenda-diary-entry' will be used instead."
3584 :group 'org-agenda
3585 :type '(choice
3586 (const :tag "The standard Emacs diary file" diary-file)
3587 (file :tag "Special Org file diary entries")))
3589 (eval-after-load "calendar"
3590 '(progn
3591 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3592 'org-calendar-goto-agenda)
3593 (add-hook 'calendar-mode-hook
3594 (lambda ()
3595 (unless (eq org-agenda-diary-file 'diary-file)
3596 (define-key calendar-mode-map
3597 org-calendar-insert-diary-entry-key
3598 'org-agenda-diary-entry))))))
3600 (defgroup org-latex nil
3601 "Options for embedding LaTeX code into Org-mode."
3602 :tag "Org LaTeX"
3603 :group 'org)
3605 (defcustom org-format-latex-options
3606 '(:foreground default :background default :scale 1.0
3607 :html-foreground "Black" :html-background "Transparent"
3608 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3609 "Options for creating images from LaTeX fragments.
3610 This is a property list with the following properties:
3611 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3612 `default' means use the foreground of the default face.
3613 `auto' means use the foreground from the text face.
3614 :background the background color, or \"Transparent\".
3615 `default' means use the background of the default face.
3616 `auto' means use the background from the text face.
3617 :scale a scaling factor for the size of the images, to get more pixels
3618 :html-foreground, :html-background, :html-scale
3619 the same numbers for HTML export.
3620 :matchers a list indicating which matchers should be used to
3621 find LaTeX fragments. Valid members of this list are:
3622 \"begin\" find environments
3623 \"$1\" find single characters surrounded by $.$
3624 \"$\" find math expressions surrounded by $...$
3625 \"$$\" find math expressions surrounded by $$....$$
3626 \"\\(\" find math expressions surrounded by \\(...\\)
3627 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3628 :group 'org-latex
3629 :type 'plist)
3631 (defcustom org-format-latex-signal-error t
3632 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3633 When nil, just push out a message."
3634 :group 'org-latex
3635 :version "24.1"
3636 :type 'boolean)
3638 (defcustom org-latex-to-mathml-jar-file nil
3639 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3640 Use this to specify additional executable file say a jar file.
3642 When using MathToWeb as the converter, specify the full-path to
3643 your mathtoweb.jar file."
3644 :group 'org-latex
3645 :version "24.1"
3646 :type '(choice
3647 (const :tag "None" nil)
3648 (file :tag "JAR file" :must-match t)))
3650 (defcustom org-latex-to-mathml-convert-command nil
3651 "Command to convert LaTeX fragments to MathML.
3652 Replace format-specifiers in the command as noted below and use
3653 `shell-command' to convert LaTeX to MathML.
3654 %j: Executable file in fully expanded form as specified by
3655 `org-latex-to-mathml-jar-file'.
3656 %I: Input LaTeX file in fully expanded form
3657 %o: Output MathML file
3658 This command is used by `org-create-math-formula'.
3660 When using MathToWeb as the converter, set this to
3661 \"java -jar %j -unicode -force -df %o %I\"."
3662 :group 'org-latex
3663 :version "24.1"
3664 :type '(choice
3665 (const :tag "None" nil)
3666 (string :tag "\nShell command")))
3668 (defcustom org-latex-create-formula-image-program 'dvipng
3669 "Program to convert LaTeX fragments with.
3671 dvipng Process the LaTeX fragments to dvi file, then convert
3672 dvi files to png files using dvipng.
3673 This will also include processing of non-math environments.
3674 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3675 to convert pdf files to png files"
3676 :group 'org-latex
3677 :version "24.1"
3678 :type '(choice
3679 (const :tag "dvipng" dvipng)
3680 (const :tag "imagemagick" imagemagick)))
3682 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3683 "Path to store latex preview images.
3684 A relative path here creates many directories relative to the
3685 processed org files paths. An absolute path puts all preview
3686 images at the same place."
3687 :group 'org-latex
3688 :version "24.3"
3689 :type 'string)
3691 (defun org-format-latex-mathml-available-p ()
3692 "Return t if `org-latex-to-mathml-convert-command' is usable."
3693 (save-match-data
3694 (when (and (boundp 'org-latex-to-mathml-convert-command)
3695 org-latex-to-mathml-convert-command)
3696 (let ((executable (car (split-string
3697 org-latex-to-mathml-convert-command))))
3698 (when (executable-find executable)
3699 (if (string-match
3700 "%j" org-latex-to-mathml-convert-command)
3701 (file-readable-p org-latex-to-mathml-jar-file)
3702 t))))))
3704 (defcustom org-format-latex-header "\\documentclass{article}
3705 \\usepackage[usenames]{color}
3706 \\usepackage{amsmath}
3707 \\usepackage[mathscr]{eucal}
3708 \\pagestyle{empty} % do not remove
3709 \[PACKAGES]
3710 \[DEFAULT-PACKAGES]
3711 % The settings below are copied from fullpage.sty
3712 \\setlength{\\textwidth}{\\paperwidth}
3713 \\addtolength{\\textwidth}{-3cm}
3714 \\setlength{\\oddsidemargin}{1.5cm}
3715 \\addtolength{\\oddsidemargin}{-2.54cm}
3716 \\setlength{\\evensidemargin}{\\oddsidemargin}
3717 \\setlength{\\textheight}{\\paperheight}
3718 \\addtolength{\\textheight}{-\\headheight}
3719 \\addtolength{\\textheight}{-\\headsep}
3720 \\addtolength{\\textheight}{-\\footskip}
3721 \\addtolength{\\textheight}{-3cm}
3722 \\setlength{\\topmargin}{1.5cm}
3723 \\addtolength{\\topmargin}{-2.54cm}"
3724 "The document header used for processing LaTeX fragments.
3725 It is imperative that this header make sure that no page number
3726 appears on the page. The package defined in the variables
3727 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3728 will either replace the placeholder \"[PACKAGES]\" in this
3729 header, or they will be appended."
3730 :group 'org-latex
3731 :type 'string)
3733 (defun org-set-packages-alist (var val)
3734 "Set the packages alist and make sure it has 3 elements per entry."
3735 (set var (mapcar (lambda (x)
3736 (if (and (consp x) (= (length x) 2))
3737 (list (car x) (nth 1 x) t)
3739 val)))
3741 (defun org-get-packages-alist (var)
3742 "Get the packages alist and make sure it has 3 elements per entry."
3743 (mapcar (lambda (x)
3744 (if (and (consp x) (= (length x) 2))
3745 (list (car x) (nth 1 x) t)
3747 (default-value var)))
3749 (defcustom org-latex-default-packages-alist
3750 '(("AUTO" "inputenc" t)
3751 ("T1" "fontenc" t)
3752 ("" "fixltx2e" nil)
3753 ("" "graphicx" t)
3754 ("" "longtable" nil)
3755 ("" "float" nil)
3756 ("" "wrapfig" nil)
3757 ("" "soul" t)
3758 ("" "textcomp" t)
3759 ("" "marvosym" t)
3760 ("" "wasysym" t)
3761 ("" "latexsym" t)
3762 ("" "amssymb" t)
3763 ("" "hyperref" nil)
3764 "\\tolerance=1000")
3765 "Alist of default packages to be inserted in the header.
3767 Change this only if one of the packages here causes an
3768 incompatibility with another package you are using.
3770 The packages in this list are needed by one part or another of
3771 Org mode to function properly:
3773 - inputenc, fontenc: for basic font and character selection
3774 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3775 symbols used for interpreting the entities in `org-entities'.
3776 You can skip some of these packages if you don't use any of the
3777 symbols in it.
3778 - graphicx: for including images
3779 - float, wrapfig: for figure placement
3780 - longtable: for long tables
3781 - hyperref: for cross references
3783 Therefore you should not modify this variable unless you know
3784 what you are doing. The one reason to change it anyway is that
3785 you might be loading some other package that conflicts with one
3786 of the default packages. Each cell is of the format
3787 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3788 the package also needs to be included when compiling LaTeX
3789 snippets into images for inclusion into non-LaTeX output."
3790 :group 'org-latex
3791 :group 'org-export-latex
3792 :set 'org-set-packages-alist
3793 :get 'org-get-packages-alist
3794 :version "24.1"
3795 :type '(repeat
3796 (choice
3797 (list :tag "options/package pair"
3798 (string :tag "options")
3799 (string :tag "package")
3800 (boolean :tag "Snippet"))
3801 (string :tag "A line of LaTeX"))))
3803 (defcustom org-latex-packages-alist nil
3804 "Alist of packages to be inserted in every LaTeX header.
3806 These will be inserted after `org-latex-default-packages-alist'.
3807 Each cell is of the format:
3809 \(\"options\" \"package\" snippet-flag)
3811 SNIPPET-FLAG, when t, indicates that this package is also needed
3812 when turning LaTeX snippets into images for inclusion into
3813 non-LaTeX output.
3815 Make sure that you only list packages here which:
3817 - you want in every file
3818 - do not conflict with the setup in `org-format-latex-header'.
3819 - do not conflict with the default packages in
3820 `org-latex-default-packages-alist'."
3821 :group 'org-latex
3822 :group 'org-export-latex
3823 :set 'org-set-packages-alist
3824 :get 'org-get-packages-alist
3825 :type '(repeat
3826 (choice
3827 (list :tag "options/package pair"
3828 (string :tag "options")
3829 (string :tag "package")
3830 (boolean :tag "Snippet"))
3831 (string :tag "A line of LaTeX"))))
3833 (defgroup org-appearance nil
3834 "Settings for Org-mode appearance."
3835 :tag "Org Appearance"
3836 :group 'org)
3838 (defcustom org-level-color-stars-only nil
3839 "Non-nil means fontify only the stars in each headline.
3840 When nil, the entire headline is fontified.
3841 Changing it requires restart of `font-lock-mode' to become effective
3842 also in regions already fontified."
3843 :group 'org-appearance
3844 :type 'boolean)
3846 (defcustom org-hide-leading-stars nil
3847 "Non-nil means hide the first N-1 stars in a headline.
3848 This works by using the face `org-hide' for these stars. This
3849 face is white for a light background, and black for a dark
3850 background. You may have to customize the face `org-hide' to
3851 make this work.
3852 Changing it requires restart of `font-lock-mode' to become effective
3853 also in regions already fontified.
3854 You may also set this on a per-file basis by adding one of the following
3855 lines to the buffer:
3857 #+STARTUP: hidestars
3858 #+STARTUP: showstars"
3859 :group 'org-appearance
3860 :type 'boolean)
3862 (defcustom org-hidden-keywords nil
3863 "List of symbols corresponding to keywords to be hidden the org buffer.
3864 For example, a value '(title) for this list will make the document's title
3865 appear in the buffer without the initial #+TITLE: keyword."
3866 :group 'org-appearance
3867 :version "24.1"
3868 :type '(set (const :tag "#+AUTHOR" author)
3869 (const :tag "#+DATE" date)
3870 (const :tag "#+EMAIL" email)
3871 (const :tag "#+TITLE" title)))
3873 (defcustom org-custom-properties nil
3874 "List of properties (as strings) with a special meaning.
3875 The default use of these custom properties is to let the user
3876 hide them with `org-toggle-custom-properties-visibility'."
3877 :group 'org-properties
3878 :group 'org-appearance
3879 :version "24.3"
3880 :type '(repeat (string :tag "Property Name")))
3882 (defcustom org-fontify-done-headline nil
3883 "Non-nil means change the face of a headline if it is marked DONE.
3884 Normally, only the TODO/DONE keyword indicates the state of a headline.
3885 When this is non-nil, the headline after the keyword is set to the
3886 `org-headline-done' as an additional indication."
3887 :group 'org-appearance
3888 :type 'boolean)
3890 (defcustom org-fontify-emphasized-text t
3891 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3892 Changing this variable requires a restart of Emacs to take effect."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-fontify-whole-heading-line nil
3897 "Non-nil means fontify the whole line for headings.
3898 This is useful when setting a background color for the
3899 org-level-* faces."
3900 :group 'org-appearance
3901 :type 'boolean)
3903 (defcustom org-hide-emphasis-markers nil
3904 "Non-nil mean font-lock should hide the emphasis marker characters."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-pretty-entities nil
3909 "Non-nil means show entities as UTF8 characters.
3910 When nil, the \\name form remains in the buffer."
3911 :group 'org-appearance
3912 :version "24.1"
3913 :type 'boolean)
3915 (defcustom org-pretty-entities-include-sub-superscripts t
3916 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3917 :group 'org-appearance
3918 :version "24.1"
3919 :type 'boolean)
3921 (defvar org-emph-re nil
3922 "Regular expression for matching emphasis.
3923 After a match, the match groups contain these elements:
3924 0 The match of the full regular expression, including the characters
3925 before and after the proper match
3926 1 The character before the proper match, or empty at beginning of line
3927 2 The proper match, including the leading and trailing markers
3928 3 The leading marker like * or /, indicating the type of highlighting
3929 4 The text between the emphasis markers, not including the markers
3930 5 The character after the match, empty at the end of a line")
3931 (defvar org-verbatim-re nil
3932 "Regular expression for matching verbatim text.")
3933 (defvar org-emphasis-regexp-components) ; defined just below
3934 (defvar org-emphasis-alist) ; defined just below
3935 (defun org-set-emph-re (var val)
3936 "Set variable and compute the emphasis regular expression."
3937 (set var val)
3938 (when (and (boundp 'org-emphasis-alist)
3939 (boundp 'org-emphasis-regexp-components)
3940 org-emphasis-alist org-emphasis-regexp-components)
3941 (let* ((e org-emphasis-regexp-components)
3942 (pre (car e))
3943 (post (nth 1 e))
3944 (border (nth 2 e))
3945 (body (nth 3 e))
3946 (nl (nth 4 e))
3947 (body1 (concat body "*?"))
3948 (markers (mapconcat 'car org-emphasis-alist ""))
3949 (vmarkers (mapconcat
3950 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3951 org-emphasis-alist "")))
3952 ;; make sure special characters appear at the right position in the class
3953 (if (string-match "\\^" markers)
3954 (setq markers (concat (replace-match "" t t markers) "^")))
3955 (if (string-match "-" markers)
3956 (setq markers (concat (replace-match "" t t markers) "-")))
3957 (if (string-match "\\^" vmarkers)
3958 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3959 (if (string-match "-" vmarkers)
3960 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3961 (if (> nl 0)
3962 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3963 (int-to-string nl) "\\}")))
3964 ;; Make the regexp
3965 (setq org-emph-re
3966 (concat "\\([" pre "]\\|^\\)"
3967 "\\("
3968 "\\([" markers "]\\)"
3969 "\\("
3970 "[^" border "]\\|"
3971 "[^" border "]"
3972 body1
3973 "[^" border "]"
3974 "\\)"
3975 "\\3\\)"
3976 "\\([" post "]\\|$\\)"))
3977 (setq org-verbatim-re
3978 (concat "\\([" pre "]\\|^\\)"
3979 "\\("
3980 "\\([" vmarkers "]\\)"
3981 "\\("
3982 "[^" border "]\\|"
3983 "[^" border "]"
3984 body1
3985 "[^" border "]"
3986 "\\)"
3987 "\\3\\)"
3988 "\\([" post "]\\|$\\)")))))
3990 (defcustom org-emphasis-regexp-components
3991 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3992 "Components used to build the regular expression for emphasis.
3993 This is a list with five entries. Terminology: In an emphasis string
3994 like \" *strong word* \", we call the initial space PREMATCH, the final
3995 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3996 and \"trong wor\" is the body. The different components in this variable
3997 specify what is allowed/forbidden in each part:
3999 pre Chars allowed as prematch. Beginning of line will be allowed too.
4000 post Chars allowed as postmatch. End of line will be allowed too.
4001 border The chars *forbidden* as border characters.
4002 body-regexp A regexp like \".\" to match a body character. Don't use
4003 non-shy groups here, and don't allow newline here.
4004 newline The maximum number of newlines allowed in an emphasis exp.
4006 Use customize to modify this, or restart Emacs after changing it."
4007 :group 'org-appearance
4008 :set 'org-set-emph-re
4009 :type '(list
4010 (sexp :tag "Allowed chars in pre ")
4011 (sexp :tag "Allowed chars in post ")
4012 (sexp :tag "Forbidden chars in border ")
4013 (sexp :tag "Regexp for body ")
4014 (integer :tag "number of newlines allowed")
4015 (option (boolean :tag "Please ignore this button"))))
4017 (defcustom org-emphasis-alist
4018 `(("*" bold "<b>" "</b>")
4019 ("/" italic "<i>" "</i>")
4020 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4021 ("=" org-code "<code>" "</code>" verbatim)
4022 ("~" org-verbatim "<code>" "</code>" verbatim)
4023 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4024 "<del>" "</del>")
4026 "Special syntax for emphasized text.
4027 Text starting and ending with a special character will be emphasized, for
4028 example *bold*, _underlined_ and /italic/. This variable sets the marker
4029 characters, the face to be used by font-lock for highlighting in Org-mode
4030 Emacs buffers, and the HTML tags to be used for this.
4031 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4032 Use customize to modify this, or restart Emacs after changing it."
4033 :group 'org-appearance
4034 :set 'org-set-emph-re
4035 :type '(repeat
4036 (list
4037 (string :tag "Marker character")
4038 (choice
4039 (face :tag "Font-lock-face")
4040 (plist :tag "Face property list"))
4041 (string :tag "HTML start tag")
4042 (string :tag "HTML end tag")
4043 (option (const verbatim)))))
4045 (defvar org-syntax-table
4046 (let ((st (make-syntax-table)))
4047 (mapc (lambda(c) (modify-syntax-entry
4048 (string-to-char (car c)) "w p" st))
4049 org-emphasis-alist)
4050 st))
4052 (defvar org-protecting-blocks
4053 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4054 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4055 This is needed for font-lock setup.")
4057 ;;; Miscellaneous options
4059 (defgroup org-completion nil
4060 "Completion in Org-mode."
4061 :tag "Org Completion"
4062 :group 'org)
4064 (defcustom org-completion-use-ido nil
4065 "Non-nil means use ido completion wherever possible.
4066 Note that `ido-mode' must be active for this variable to be relevant.
4067 If you decide to turn this variable on, you might well want to turn off
4068 `org-outline-path-complete-in-steps'.
4069 See also `org-completion-use-iswitchb'."
4070 :group 'org-completion
4071 :type 'boolean)
4073 (defcustom org-completion-use-iswitchb nil
4074 "Non-nil means use iswitchb completion wherever possible.
4075 Note that `iswitchb-mode' must be active for this variable to be relevant.
4076 If you decide to turn this variable on, you might well want to turn off
4077 `org-outline-path-complete-in-steps'.
4078 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4079 :group 'org-completion
4080 :type 'boolean)
4082 (defcustom org-completion-fallback-command 'hippie-expand
4083 "The expansion command called by \\[pcomplete] in normal context.
4084 Normal means, no org-mode-specific context."
4085 :group 'org-completion
4086 :type 'function)
4088 ;;; Functions and variables from their packages
4089 ;; Declared here to avoid compiler warnings
4091 ;; XEmacs only
4092 (defvar outline-mode-menu-heading)
4093 (defvar outline-mode-menu-show)
4094 (defvar outline-mode-menu-hide)
4095 (defvar zmacs-regions) ; XEmacs regions
4097 ;; Emacs only
4098 (defvar mark-active)
4100 ;; Various packages
4101 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4102 (declare-function calendar-forward-day "cal-move" (arg))
4103 (declare-function calendar-goto-date "cal-move" (date))
4104 (declare-function calendar-goto-today "cal-move" ())
4105 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4106 (defvar calc-embedded-close-formula)
4107 (defvar calc-embedded-open-formula)
4108 (declare-function cdlatex-tab "ext:cdlatex" ())
4109 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4110 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4111 (defvar font-lock-unfontify-region-function)
4112 (declare-function iswitchb-read-buffer "iswitchb"
4113 (prompt &optional default require-match start matches-set))
4114 (defvar iswitchb-temp-buflist)
4115 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4116 (defvar org-agenda-tags-todo-honor-ignore-options)
4117 (declare-function org-agenda-skip "org-agenda" ())
4118 (declare-function
4119 org-agenda-format-item "org-agenda"
4120 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4121 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4122 (declare-function org-agenda-change-all-lines "org-agenda"
4123 (newhead hdmarker &optional fixface just-this))
4124 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4125 (declare-function org-agenda-maybe-redo "org-agenda" ())
4126 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4127 (beg end))
4128 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4129 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4130 "org-agenda" (&optional end))
4131 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4132 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4133 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4134 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4135 (declare-function org-indent-mode "org-indent" (&optional arg))
4136 (declare-function parse-time-string "parse-time" (string))
4137 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4138 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4139 (defvar remember-data-file)
4140 (defvar texmathp-why)
4141 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4142 (declare-function table--at-cell-p "table" (position &optional object at-column))
4144 (defvar org-latex-regexps)
4146 ;;; Autoload and prepare some org modules
4148 ;; Some table stuff that needs to be defined here, because it is used
4149 ;; by the functions setting up org-mode or checking for table context.
4151 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4152 "Detect an org-type or table-type table.")
4153 (defconst org-table-line-regexp "^[ \t]*|"
4154 "Detect an org-type table line.")
4155 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4156 "Detect an org-type table line.")
4157 (defconst org-table-hline-regexp "^[ \t]*|-"
4158 "Detect an org-type table hline.")
4159 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4160 "Detect a table-type table hline.")
4161 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4162 "Detect the first line outside a table when searching from within it.
4163 This works for both table types.")
4165 ;; Autoload the functions in org-table.el that are needed by functions here.
4167 (eval-and-compile
4168 (org-autoload "org-table"
4169 '(org-table-begin org-table-blank-field org-table-end)))
4171 ;;;###autoload
4172 (defun turn-on-orgtbl ()
4173 "Unconditionally turn on `orgtbl-mode'."
4174 (require 'org-table)
4175 (orgtbl-mode 1))
4177 (defun org-at-table-p (&optional table-type)
4178 "Return t if the cursor is inside an org-type table.
4179 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4180 (if org-enable-table-editor
4181 (save-excursion
4182 (beginning-of-line 1)
4183 (looking-at (if table-type org-table-any-line-regexp
4184 org-table-line-regexp)))
4185 nil))
4186 (defsubst org-table-p () (org-at-table-p))
4188 (defun org-at-table.el-p ()
4189 "Return t if and only if we are at a table.el table."
4190 (and (org-at-table-p 'any)
4191 (save-excursion
4192 (goto-char (org-table-begin 'any))
4193 (looking-at org-table1-hline-regexp))))
4194 (defun org-table-recognize-table.el ()
4195 "If there is a table.el table nearby, recognize it and move into it."
4196 (if org-table-tab-recognizes-table.el
4197 (if (org-at-table.el-p)
4198 (progn
4199 (beginning-of-line 1)
4200 (if (looking-at org-table-dataline-regexp)
4202 (if (looking-at org-table1-hline-regexp)
4203 (progn
4204 (beginning-of-line 2)
4205 (if (looking-at org-table-any-border-regexp)
4206 (beginning-of-line -1)))))
4207 (if (re-search-forward "|" (org-table-end t) t)
4208 (progn
4209 (require 'table)
4210 (if (table--at-cell-p (point))
4212 (message "recognizing table.el table...")
4213 (table-recognize-table)
4214 (message "recognizing table.el table...done")))
4215 (error "This should not happen"))
4217 nil)
4218 nil))
4220 (defun org-at-table-hline-p ()
4221 "Return t if the cursor is inside a hline in a table."
4222 (if org-enable-table-editor
4223 (save-excursion
4224 (beginning-of-line 1)
4225 (looking-at org-table-hline-regexp))
4226 nil))
4228 (defvar org-table-clean-did-remove-column nil)
4230 (defun org-table-map-tables (function &optional quietly)
4231 "Apply FUNCTION to the start of all tables in the buffer."
4232 (save-excursion
4233 (save-restriction
4234 (widen)
4235 (goto-char (point-min))
4236 (while (re-search-forward org-table-any-line-regexp nil t)
4237 (unless quietly
4238 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4239 (beginning-of-line 1)
4240 (when (and (looking-at org-table-line-regexp)
4241 ;; Exclude tables in src/example/verbatim/clocktable blocks
4242 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4243 (save-excursion (funcall function))
4244 (or (looking-at org-table-line-regexp)
4245 (forward-char 1)))
4246 (re-search-forward org-table-any-border-regexp nil 1))))
4247 (unless quietly (message "Mapping tables: done")))
4249 ;; Declare and autoload functions from ox.el and al.
4251 (declare-function org-export-get-environment "ox"
4252 (&optional backend subtreep ext-plist))
4253 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4255 ;; Declare and autoload functions from org-agenda.el
4257 (eval-and-compile
4258 (org-autoload "org-agenda"
4259 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4261 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4262 (declare-function org-clock-update-mode-line "org-clock" ())
4263 (declare-function org-resolve-clocks "org-clock"
4264 (&optional also-non-dangling-p prompt last-valid))
4265 (defvar org-clock-start-time)
4266 (defvar org-clock-marker (make-marker)
4267 "Marker recording the last clock-in.")
4268 (defvar org-clock-hd-marker (make-marker)
4269 "Marker recording the last clock-in, but the headline position.")
4270 (defvar org-clock-heading ""
4271 "The heading of the current clock entry.")
4272 (defun org-clock-is-active ()
4273 "Return non-nil if clock is currently running.
4274 The return value is actually the clock marker."
4275 (marker-buffer org-clock-marker))
4277 (eval-and-compile
4278 (org-autoload "org-clock" '(org-clock-remove-overlays
4279 org-clock-update-time-maybe
4280 org-clocktable-shift)))
4282 (defun org-check-running-clock ()
4283 "Check if the current buffer contains the running clock.
4284 If yes, offer to stop it and to save the buffer with the changes."
4285 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4286 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4287 (buffer-name))))
4288 (org-clock-out)
4289 (when (y-or-n-p "Save changed buffer?")
4290 (save-buffer))))
4292 (defun org-clocktable-try-shift (dir n)
4293 "Check if this line starts a clock table, if yes, shift the time block."
4294 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4295 (org-clocktable-shift dir n)))
4297 ;;;###autoload
4298 (defun org-clock-persistence-insinuate ()
4299 "Set up hooks for clock persistence."
4300 (require 'org-clock)
4301 (add-hook 'org-mode-hook 'org-clock-load)
4302 (add-hook 'kill-emacs-hook 'org-clock-save))
4304 ;; Define the variable already here, to make sure we have it.
4305 (defvar org-indent-mode nil
4306 "Non-nil if Org-Indent mode is enabled.
4307 Use the command `org-indent-mode' to change this variable.")
4309 ;; Autoload archiving code
4310 ;; The stuff that is needed for cycling and tags has to be defined here.
4312 (defgroup org-archive nil
4313 "Options concerning archiving in Org-mode."
4314 :tag "Org Archive"
4315 :group 'org-structure)
4317 (defcustom org-archive-location "%s_archive::"
4318 "The location where subtrees should be archived.
4320 The value of this variable is a string, consisting of two parts,
4321 separated by a double-colon. The first part is a filename and
4322 the second part is a headline.
4324 When the filename is omitted, archiving happens in the same file.
4325 %s in the filename will be replaced by the current file
4326 name (without the directory part). Archiving to a different file
4327 is useful to keep archived entries from contributing to the
4328 Org-mode Agenda.
4330 The archived entries will be filed as subtrees of the specified
4331 headline. When the headline is omitted, the subtrees are simply
4332 filed away at the end of the file, as top-level entries. Also in
4333 the heading you can use %s to represent the file name, this can be
4334 useful when using the same archive for a number of different files.
4336 Here are a few examples:
4337 \"%s_archive::\"
4338 If the current file is Projects.org, archive in file
4339 Projects.org_archive, as top-level trees. This is the default.
4341 \"::* Archived Tasks\"
4342 Archive in the current file, under the top-level headline
4343 \"* Archived Tasks\".
4345 \"~/org/archive.org::\"
4346 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4348 \"~/org/archive.org::* From %s\"
4349 Archive in file ~/org/archive.org (absolute path), under headlines
4350 \"From FILENAME\" where file name is the current file name.
4352 \"~/org/datetree.org::datetree/* Finished Tasks\"
4353 The \"datetree/\" string is special, signifying to archive
4354 items to the datetree. Items are placed in either the CLOSED
4355 date of the item, or the current date if there is no CLOSED date.
4356 The heading will be a subentry to the current date. There doesn't
4357 need to be a heading, but there always needs to be a slash after
4358 datetree. For example, to store archived items directly in the
4359 datetree, use \"~/org/datetree.org::datetree/\".
4361 \"basement::** Finished Tasks\"
4362 Archive in file ./basement (relative path), as level 3 trees
4363 below the level 2 heading \"** Finished Tasks\".
4365 You may set this option on a per-file basis by adding to the buffer a
4366 line like
4368 #+ARCHIVE: basement::** Finished Tasks
4370 You may also define it locally for a subtree by setting an ARCHIVE property
4371 in the entry. If such a property is found in an entry, or anywhere up
4372 the hierarchy, it will be used."
4373 :group 'org-archive
4374 :type 'string)
4376 (defcustom org-archive-tag "ARCHIVE"
4377 "The tag that marks a subtree as archived.
4378 An archived subtree does not open during visibility cycling, and does
4379 not contribute to the agenda listings.
4380 After changing this, font-lock must be restarted in the relevant buffers to
4381 get the proper fontification."
4382 :group 'org-archive
4383 :group 'org-keywords
4384 :type 'string)
4386 (defcustom org-agenda-skip-archived-trees t
4387 "Non-nil means the agenda will skip any items located in archived trees.
4388 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4389 variable is no longer recommended, you should leave it at the value t.
4390 Instead, use the key `v' to cycle the archives-mode in the agenda."
4391 :group 'org-archive
4392 :group 'org-agenda-skip
4393 :type 'boolean)
4395 (defcustom org-columns-skip-archived-trees t
4396 "Non-nil means ignore archived trees when creating column view."
4397 :group 'org-archive
4398 :group 'org-properties
4399 :type 'boolean)
4401 (defcustom org-cycle-open-archived-trees nil
4402 "Non-nil means `org-cycle' will open archived trees.
4403 An archived tree is a tree marked with the tag ARCHIVE.
4404 When nil, archived trees will stay folded. You can still open them with
4405 normal outline commands like `show-all', but not with the cycling commands."
4406 :group 'org-archive
4407 :group 'org-cycle
4408 :type 'boolean)
4410 (defcustom org-sparse-tree-open-archived-trees nil
4411 "Non-nil means sparse tree construction shows matches in archived trees.
4412 When nil, matches in these trees are highlighted, but the trees are kept in
4413 collapsed state."
4414 :group 'org-archive
4415 :group 'org-sparse-trees
4416 :type 'boolean)
4418 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4419 "The default date type when building a sparse tree.
4420 When this is nil, a date is a scheduled or a deadline timestamp.
4421 Otherwise, these types are allowed:
4423 all: all timestamps
4424 active: only active timestamps (<...>)
4425 inactive: only inactive timestamps (<...)
4426 scheduled: only scheduled timestamps
4427 deadline: only deadline timestamps"
4428 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4429 (const :tag "All timestamps" all)
4430 (const :tag "Only active timestamps" active)
4431 (const :tag "Only inactive timestamps" inactive)
4432 (const :tag "Only scheduled timestamps" scheduled)
4433 (const :tag "Only deadline timestamps" deadline))
4434 :version "24.3"
4435 :group 'org-sparse-trees)
4437 (defun org-cycle-hide-archived-subtrees (state)
4438 "Re-hide all archived subtrees after a visibility state change."
4439 (when (and (not org-cycle-open-archived-trees)
4440 (not (memq state '(overview folded))))
4441 (save-excursion
4442 (let* ((globalp (memq state '(contents all)))
4443 (beg (if globalp (point-min) (point)))
4444 (end (if globalp (point-max) (org-end-of-subtree t))))
4445 (org-hide-archived-subtrees beg end)
4446 (goto-char beg)
4447 (if (looking-at (concat ".*:" org-archive-tag ":"))
4448 (message "%s" (substitute-command-keys
4449 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4451 (defun org-force-cycle-archived ()
4452 "Cycle subtree even if it is archived."
4453 (interactive)
4454 (setq this-command 'org-cycle)
4455 (let ((org-cycle-open-archived-trees t))
4456 (call-interactively 'org-cycle)))
4458 (defun org-hide-archived-subtrees (beg end)
4459 "Re-hide all archived subtrees after a visibility state change."
4460 (save-excursion
4461 (let* ((re (concat ":" org-archive-tag ":")))
4462 (goto-char beg)
4463 (while (re-search-forward re end t)
4464 (when (org-at-heading-p)
4465 (org-flag-subtree t)
4466 (org-end-of-subtree t))))))
4468 (declare-function outline-end-of-heading "outline" ())
4469 (declare-function outline-flag-region "outline" (from to flag))
4470 (defun org-flag-subtree (flag)
4471 (save-excursion
4472 (org-back-to-heading t)
4473 (outline-end-of-heading)
4474 (outline-flag-region (point)
4475 (progn (org-end-of-subtree t) (point))
4476 flag)))
4478 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4480 (eval-and-compile
4481 (org-autoload "org-archive"
4482 '(org-add-archive-files)))
4484 ;; Autoload Column View Code
4486 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4487 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4488 (declare-function org-columns-compute "org-colview" (property))
4490 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4491 '(org-columns-number-to-string
4492 org-columns-get-format-and-top-level
4493 org-columns-compute
4494 org-columns-remove-overlays))
4496 ;; Autoload ID code
4498 (declare-function org-id-store-link "org-id")
4499 (declare-function org-id-locations-load "org-id")
4500 (declare-function org-id-locations-save "org-id")
4501 (defvar org-id-track-globally)
4502 (org-autoload "org-id"
4503 '(org-id-new
4504 org-id-copy
4505 org-id-get-with-outline-path-completion
4506 org-id-get-with-outline-drilling))
4508 ;;; Variables for pre-computed regular expressions, all buffer local
4510 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4511 "Matches first line of a hidden block.")
4512 (make-variable-buffer-local 'org-drawer-regexp)
4513 (defvar org-todo-regexp nil
4514 "Matches any of the TODO state keywords.")
4515 (make-variable-buffer-local 'org-todo-regexp)
4516 (defvar org-not-done-regexp nil
4517 "Matches any of the TODO state keywords except the last one.")
4518 (make-variable-buffer-local 'org-not-done-regexp)
4519 (defvar org-not-done-heading-regexp nil
4520 "Matches a TODO headline that is not done.")
4521 (make-variable-buffer-local 'org-not-done-regexp)
4522 (defvar org-todo-line-regexp nil
4523 "Matches a headline and puts TODO state into group 2 if present.")
4524 (make-variable-buffer-local 'org-todo-line-regexp)
4525 (defvar org-complex-heading-regexp nil
4526 "Matches a headline and puts everything into groups:
4527 group 1: the stars
4528 group 2: The todo keyword, maybe
4529 group 3: Priority cookie
4530 group 4: True headline
4531 group 5: Tags")
4532 (make-variable-buffer-local 'org-complex-heading-regexp)
4533 (defvar org-complex-heading-regexp-format nil
4534 "Printf format to make regexp to match an exact headline.
4535 This regexp will match the headline of any node which has the
4536 exact headline text that is put into the format, but may have any
4537 TODO state, priority and tags.")
4538 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4539 (defvar org-todo-line-tags-regexp nil
4540 "Matches a headline and puts TODO state into group 2 if present.
4541 Also put tags into group 4 if tags are present.")
4542 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4543 (defvar org-ds-keyword-length 12
4544 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4545 (make-variable-buffer-local 'org-ds-keyword-length)
4546 (defvar org-deadline-regexp nil
4547 "Matches the DEADLINE keyword.")
4548 (make-variable-buffer-local 'org-deadline-regexp)
4549 (defvar org-deadline-time-regexp nil
4550 "Matches the DEADLINE keyword together with a time stamp.")
4551 (make-variable-buffer-local 'org-deadline-time-regexp)
4552 (defvar org-deadline-line-regexp nil
4553 "Matches the DEADLINE keyword and the rest of the line.")
4554 (make-variable-buffer-local 'org-deadline-line-regexp)
4555 (defvar org-scheduled-regexp nil
4556 "Matches the SCHEDULED keyword.")
4557 (make-variable-buffer-local 'org-scheduled-regexp)
4558 (defvar org-scheduled-time-regexp nil
4559 "Matches the SCHEDULED keyword together with a time stamp.")
4560 (make-variable-buffer-local 'org-scheduled-time-regexp)
4561 (defvar org-closed-time-regexp nil
4562 "Matches the CLOSED keyword together with a time stamp.")
4563 (make-variable-buffer-local 'org-closed-time-regexp)
4565 (defvar org-keyword-time-regexp nil
4566 "Matches any of the 4 keywords, together with the time stamp.")
4567 (make-variable-buffer-local 'org-keyword-time-regexp)
4568 (defvar org-keyword-time-not-clock-regexp nil
4569 "Matches any of the 3 keywords, together with the time stamp.")
4570 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4571 (defvar org-maybe-keyword-time-regexp nil
4572 "Matches a timestamp, possibly preceded by a keyword.")
4573 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4574 (defvar org-all-time-keywords nil
4575 "List of time keywords.")
4576 (make-variable-buffer-local 'org-all-time-keywords)
4578 (defconst org-plain-time-of-day-regexp
4579 (concat
4580 "\\(\\<[012]?[0-9]"
4581 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4582 "\\(--?"
4583 "\\(\\<[012]?[0-9]"
4584 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4585 "\\)?")
4586 "Regular expression to match a plain time or time range.
4587 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4588 groups carry important information:
4589 0 the full match
4590 1 the first time, range or not
4591 8 the second time, if it is a range.")
4593 (defconst org-plain-time-extension-regexp
4594 (concat
4595 "\\(\\<[012]?[0-9]"
4596 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4597 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4598 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4599 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4600 groups carry important information:
4601 0 the full match
4602 7 hours of duration
4603 9 minutes of duration")
4605 (defconst org-stamp-time-of-day-regexp
4606 (concat
4607 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4608 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4609 "\\(--?"
4610 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4611 "Regular expression to match a timestamp time or time range.
4612 After a match, the following groups carry important information:
4613 0 the full match
4614 1 date plus weekday, for back referencing to make sure both times are on the same day
4615 2 the first time, range or not
4616 4 the second time, if it is a range.")
4618 (defconst org-startup-options
4619 '(("fold" org-startup-folded t)
4620 ("overview" org-startup-folded t)
4621 ("nofold" org-startup-folded nil)
4622 ("showall" org-startup-folded nil)
4623 ("showeverything" org-startup-folded showeverything)
4624 ("content" org-startup-folded content)
4625 ("indent" org-startup-indented t)
4626 ("noindent" org-startup-indented nil)
4627 ("hidestars" org-hide-leading-stars t)
4628 ("showstars" org-hide-leading-stars nil)
4629 ("odd" org-odd-levels-only t)
4630 ("oddeven" org-odd-levels-only nil)
4631 ("align" org-startup-align-all-tables t)
4632 ("noalign" org-startup-align-all-tables nil)
4633 ("inlineimages" org-startup-with-inline-images t)
4634 ("noinlineimages" org-startup-with-inline-images nil)
4635 ("latexpreview" org-startup-with-latex-preview t)
4636 ("nolatexpreview" org-startup-with-latex-preview nil)
4637 ("customtime" org-display-custom-times t)
4638 ("logdone" org-log-done time)
4639 ("lognotedone" org-log-done note)
4640 ("nologdone" org-log-done nil)
4641 ("lognoteclock-out" org-log-note-clock-out t)
4642 ("nolognoteclock-out" org-log-note-clock-out nil)
4643 ("logrepeat" org-log-repeat state)
4644 ("lognoterepeat" org-log-repeat note)
4645 ("logdrawer" org-log-into-drawer t)
4646 ("nologdrawer" org-log-into-drawer nil)
4647 ("logstatesreversed" org-log-states-order-reversed t)
4648 ("nologstatesreversed" org-log-states-order-reversed nil)
4649 ("nologrepeat" org-log-repeat nil)
4650 ("logreschedule" org-log-reschedule time)
4651 ("lognotereschedule" org-log-reschedule note)
4652 ("nologreschedule" org-log-reschedule nil)
4653 ("logredeadline" org-log-redeadline time)
4654 ("lognoteredeadline" org-log-redeadline note)
4655 ("nologredeadline" org-log-redeadline nil)
4656 ("logrefile" org-log-refile time)
4657 ("lognoterefile" org-log-refile note)
4658 ("nologrefile" org-log-refile nil)
4659 ("fninline" org-footnote-define-inline t)
4660 ("nofninline" org-footnote-define-inline nil)
4661 ("fnlocal" org-footnote-section nil)
4662 ("fnauto" org-footnote-auto-label t)
4663 ("fnprompt" org-footnote-auto-label nil)
4664 ("fnconfirm" org-footnote-auto-label confirm)
4665 ("fnplain" org-footnote-auto-label plain)
4666 ("fnadjust" org-footnote-auto-adjust t)
4667 ("nofnadjust" org-footnote-auto-adjust nil)
4668 ("constcgs" constants-unit-system cgs)
4669 ("constSI" constants-unit-system SI)
4670 ("noptag" org-tag-persistent-alist nil)
4671 ("hideblocks" org-hide-block-startup t)
4672 ("nohideblocks" org-hide-block-startup nil)
4673 ("beamer" org-startup-with-beamer-mode t)
4674 ("entitiespretty" org-pretty-entities t)
4675 ("entitiesplain" org-pretty-entities nil))
4676 "Variable associated with STARTUP options for org-mode.
4677 Each element is a list of three items: the startup options (as written
4678 in the #+STARTUP line), the corresponding variable, and the value to set
4679 this variable to if the option is found. An optional forth element PUSH
4680 means to push this value onto the list in the variable.")
4682 (defun org-update-property-plist (key val props)
4683 "Update PROPS with KEY and VAL."
4684 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4685 (key (if appending (substring key 0 (- (length key) 1)) key))
4686 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4687 (previous (cdr (assoc key props))))
4688 (if appending
4689 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4690 (cons (cons key val) remainder))))
4692 (defconst org-block-regexp
4693 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4694 "Regular expression for hiding blocks.")
4695 (defconst org-heading-keyword-regexp-format
4696 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4697 "Printf format for a regexp matching an headline with some keyword.
4698 This regexp will match the headline of any node which has the
4699 exact keyword that is put into the format. The keyword isn't in
4700 any group by default, but the stars and the body are.")
4701 (defconst org-heading-keyword-maybe-regexp-format
4702 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4703 "Printf format for a regexp matching an headline, possibly with some keyword.
4704 This regexp can match any headline with the specified keyword, or
4705 without a keyword. The keyword isn't in any group by default,
4706 but the stars and the body are.")
4708 (defun org-set-regexps-and-options ()
4709 "Precompute regular expressions for current buffer."
4710 (when (derived-mode-p 'org-mode)
4711 (org-set-local 'org-todo-kwd-alist nil)
4712 (org-set-local 'org-todo-key-alist nil)
4713 (org-set-local 'org-todo-key-trigger nil)
4714 (org-set-local 'org-todo-keywords-1 nil)
4715 (org-set-local 'org-done-keywords nil)
4716 (org-set-local 'org-todo-heads nil)
4717 (org-set-local 'org-todo-sets nil)
4718 (org-set-local 'org-todo-log-states nil)
4719 (org-set-local 'org-file-properties nil)
4720 (org-set-local 'org-file-tags nil)
4721 (let ((re (org-make-options-regexp
4722 '("CATEGORY" "TODO" "COLUMNS"
4723 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4724 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4725 "OPTIONS")
4726 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4727 (splitre "[ \t]+")
4728 (scripts org-use-sub-superscripts)
4729 kwds kws0 kwsa key log value cat arch tags const links hw dws
4730 tail sep kws1 prio props ftags drawers beamer-p
4731 ext-setup-or-nil setup-contents (start 0))
4732 (save-excursion
4733 (save-restriction
4734 (widen)
4735 (goto-char (point-min))
4736 (while (or (and ext-setup-or-nil
4737 (string-match re ext-setup-or-nil start)
4738 (setq start (match-end 0)))
4739 (and (setq ext-setup-or-nil nil start 0)
4740 (re-search-forward re nil t)))
4741 (setq key (upcase (match-string 1 ext-setup-or-nil))
4742 value (org-match-string-no-properties 2 ext-setup-or-nil))
4743 (if (stringp value) (setq value (org-trim value)))
4744 (cond
4745 ((equal key "CATEGORY")
4746 (setq cat value))
4747 ((member key '("SEQ_TODO" "TODO"))
4748 (push (cons 'sequence (org-split-string value splitre)) kwds))
4749 ((equal key "TYP_TODO")
4750 (push (cons 'type (org-split-string value splitre)) kwds))
4751 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4752 ;; general TODO-like setup
4753 (push (cons (intern (downcase (match-string 1 key)))
4754 (org-split-string value splitre)) kwds))
4755 ((equal key "TAGS")
4756 (setq tags (append tags (if tags '("\\n") nil)
4757 (org-split-string value splitre))))
4758 ((equal key "COLUMNS")
4759 (org-set-local 'org-columns-default-format value))
4760 ((equal key "LINK")
4761 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4762 (push (cons (match-string 1 value)
4763 (org-trim (match-string 2 value)))
4764 links)))
4765 ((equal key "PRIORITIES")
4766 (setq prio (org-split-string value " +")))
4767 ((equal key "PROPERTY")
4768 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4769 (setq props (org-update-property-plist (match-string 1 value)
4770 (match-string 2 value)
4771 props))))
4772 ((equal key "FILETAGS")
4773 (when (string-match "\\S-" value)
4774 (setq ftags
4775 (append
4776 ftags
4777 (apply 'append
4778 (mapcar (lambda (x) (org-split-string x ":"))
4779 (org-split-string value)))))))
4780 ((equal key "DRAWERS")
4781 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4782 ((equal key "CONSTANTS")
4783 (setq const (append const (org-split-string value splitre))))
4784 ((equal key "STARTUP")
4785 (let ((opts (org-split-string value splitre))
4786 l var val)
4787 (while (setq l (pop opts))
4788 (when (setq l (assoc l org-startup-options))
4789 (setq var (nth 1 l) val (nth 2 l))
4790 (if (not (nth 3 l))
4791 (set (make-local-variable var) val)
4792 (if (not (listp (symbol-value var)))
4793 (set (make-local-variable var) nil))
4794 (set (make-local-variable var) (symbol-value var))
4795 (add-to-list var val))))))
4796 ((equal key "ARCHIVE")
4797 (setq arch value)
4798 (remove-text-properties 0 (length arch)
4799 '(face t fontified t) arch))
4800 ((equal key "LATEX_CLASS")
4801 (setq beamer-p (equal value "beamer")))
4802 ((equal key "OPTIONS")
4803 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4804 (setq scripts (read (match-string 2 value)))))
4805 ((equal key "SETUPFILE")
4806 (setq setup-contents (org-file-contents
4807 (expand-file-name
4808 (org-remove-double-quotes value))
4809 'noerror))
4810 (if (not ext-setup-or-nil)
4811 (setq ext-setup-or-nil setup-contents start 0)
4812 (setq ext-setup-or-nil
4813 (concat (substring ext-setup-or-nil 0 start)
4814 "\n" setup-contents "\n"
4815 (substring ext-setup-or-nil start)))))))
4816 ;; search for property blocks
4817 (goto-char (point-min))
4818 (while (re-search-forward org-block-regexp nil t)
4819 (when (equal "PROPERTY" (upcase (match-string 1)))
4820 (setq value (replace-regexp-in-string
4821 "[\n\r]" " " (match-string 4)))
4822 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4823 (setq props (org-update-property-plist (match-string 1 value)
4824 (match-string 2 value)
4825 props)))))))
4826 (org-set-local 'org-use-sub-superscripts scripts)
4827 (when cat
4828 (org-set-local 'org-category (intern cat))
4829 (push (cons "CATEGORY" cat) props))
4830 (when prio
4831 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4832 (setq prio (mapcar 'string-to-char prio))
4833 (org-set-local 'org-highest-priority (nth 0 prio))
4834 (org-set-local 'org-lowest-priority (nth 1 prio))
4835 (org-set-local 'org-default-priority (nth 2 prio)))
4836 (and props (org-set-local 'org-file-properties (nreverse props)))
4837 (and ftags (org-set-local 'org-file-tags
4838 (mapcar 'org-add-prop-inherited ftags)))
4839 (and drawers (org-set-local 'org-drawers drawers))
4840 (and arch (org-set-local 'org-archive-location arch))
4841 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4842 ;; Process the TODO keywords
4843 (unless kwds
4844 ;; Use the global values as if they had been given locally.
4845 (setq kwds (default-value 'org-todo-keywords))
4846 (if (stringp (car kwds))
4847 (setq kwds (list (cons org-todo-interpretation
4848 (default-value 'org-todo-keywords)))))
4849 (setq kwds (reverse kwds)))
4850 (setq kwds (nreverse kwds))
4851 (let (inter kws kw)
4852 (while (setq kws (pop kwds))
4853 (let ((kws (or
4854 (run-hook-with-args-until-success
4855 'org-todo-setup-filter-hook kws)
4856 kws)))
4857 (setq inter (pop kws) sep (member "|" kws)
4858 kws0 (delete "|" (copy-sequence kws))
4859 kwsa nil
4860 kws1 (mapcar
4861 (lambda (x)
4862 ;; 1 2
4863 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4864 (progn
4865 (setq kw (match-string 1 x)
4866 key (and (match-end 2) (match-string 2 x))
4867 log (org-extract-log-state-settings x))
4868 (push (cons kw (and key (string-to-char key))) kwsa)
4869 (and log (push log org-todo-log-states))
4871 (error "Invalid TODO keyword %s" x)))
4872 kws0)
4873 kwsa (if kwsa (append '((:startgroup))
4874 (nreverse kwsa)
4875 '((:endgroup))))
4876 hw (car kws1)
4877 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4878 tail (list inter hw (car dws) (org-last dws))))
4879 (add-to-list 'org-todo-heads hw 'append)
4880 (push kws1 org-todo-sets)
4881 (setq org-done-keywords (append org-done-keywords dws nil))
4882 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4883 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4884 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4885 (setq org-todo-sets (nreverse org-todo-sets)
4886 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4887 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4888 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4889 ;; Process the constants
4890 (when const
4891 (let (e cst)
4892 (while (setq e (pop const))
4893 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4894 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4895 (setq org-table-formula-constants-local cst)))
4897 ;; Process the tags.
4898 (when tags
4899 (let (e tgs)
4900 (while (setq e (pop tags))
4901 (cond
4902 ((equal e "{") (push '(:startgroup) tgs))
4903 ((equal e "}") (push '(:endgroup) tgs))
4904 ((equal e "\\n") (push '(:newline) tgs))
4905 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4906 (push (cons (match-string 1 e)
4907 (string-to-char (match-string 2 e)))
4908 tgs))
4909 (t (push (list e) tgs))))
4910 (org-set-local 'org-tag-alist nil)
4911 (while (setq e (pop tgs))
4912 (or (and (stringp (car e))
4913 (assoc (car e) org-tag-alist))
4914 (push e org-tag-alist)))))
4916 ;; Compute the regular expressions and other local variables.
4917 ;; Using `org-outline-regexp-bol' would complicate them much,
4918 ;; because of the fixed white space at the end of that string.
4919 (if (not org-done-keywords)
4920 (setq org-done-keywords (and org-todo-keywords-1
4921 (list (org-last org-todo-keywords-1)))))
4922 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4923 (length org-scheduled-string)
4924 (length org-clock-string)
4925 (length org-closed-string)))
4926 org-drawer-regexp
4927 (concat "^[ \t]*:\\("
4928 (mapconcat 'regexp-quote org-drawers "\\|")
4929 "\\):[ \t]*$")
4930 org-not-done-keywords
4931 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4932 org-todo-regexp
4933 (concat "\\("
4934 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4935 "\\)")
4936 org-not-done-regexp
4937 (concat "\\("
4938 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4939 "\\)")
4940 org-not-done-heading-regexp
4941 (format org-heading-keyword-regexp-format org-not-done-regexp)
4942 org-todo-line-regexp
4943 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4944 org-complex-heading-regexp
4945 (concat "^\\(\\*+\\)"
4946 "\\(?: +" org-todo-regexp "\\)?"
4947 "\\(?: +\\(\\[#.\\]\\)\\)?"
4948 "\\(?: +\\(.*?\\)\\)??"
4949 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4950 "[ \t]*$")
4951 org-complex-heading-regexp-format
4952 (concat "^\\(\\*+\\)"
4953 "\\(?: +" org-todo-regexp "\\)?"
4954 "\\(?: +\\(\\[#.\\]\\)\\)?"
4955 "\\(?: +"
4956 ;; Stats cookies can be stuck to body.
4957 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4958 "\\(%s\\)"
4959 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4960 "\\)"
4961 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4962 "[ \t]*$")
4963 org-todo-line-tags-regexp
4964 (concat "^\\(\\*+\\)"
4965 "\\(?: +" org-todo-regexp "\\)?"
4966 "\\(?: +\\(.*?\\)\\)??"
4967 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4968 "[ \t]*$")
4969 org-deadline-regexp (concat "\\<" org-deadline-string)
4970 org-deadline-time-regexp
4971 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4972 org-deadline-line-regexp
4973 (concat "\\<\\(" org-deadline-string "\\).*")
4974 org-scheduled-regexp
4975 (concat "\\<" org-scheduled-string)
4976 org-scheduled-time-regexp
4977 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4978 org-closed-time-regexp
4979 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4980 org-keyword-time-regexp
4981 (concat "\\<\\(" org-scheduled-string
4982 "\\|" org-deadline-string
4983 "\\|" org-closed-string
4984 "\\|" org-clock-string "\\)"
4985 " *[[<]\\([^]>]+\\)[]>]")
4986 org-keyword-time-not-clock-regexp
4987 (concat "\\<\\(" org-scheduled-string
4988 "\\|" org-deadline-string
4989 "\\|" org-closed-string
4990 "\\)"
4991 " *[[<]\\([^]>]+\\)[]>]")
4992 org-maybe-keyword-time-regexp
4993 (concat "\\(\\<\\(" org-scheduled-string
4994 "\\|" org-deadline-string
4995 "\\|" org-closed-string
4996 "\\|" org-clock-string "\\)\\)?"
4997 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4998 org-all-time-keywords
4999 (mapcar (lambda (w) (substring w 0 -1))
5000 (list org-scheduled-string org-deadline-string
5001 org-clock-string org-closed-string)))
5002 (org-set-font-lock-defaults))))
5004 (defun org-file-contents (file &optional noerror)
5005 "Return the contents of FILE, as a string."
5006 (if (or (not file)
5007 (not (file-readable-p file)))
5008 (if noerror
5009 (progn
5010 (message "Cannot read file \"%s\"" file)
5011 (ding) (sit-for 2)
5013 (error "Cannot read file \"%s\"" file))
5014 (with-temp-buffer
5015 (insert-file-contents file)
5016 (buffer-string))))
5018 (defun org-extract-log-state-settings (x)
5019 "Extract the log state setting from a TODO keyword string.
5020 This will extract info from a string like \"WAIT(w@/!)\"."
5021 (let (kw key log1 log2)
5022 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5023 (setq kw (match-string 1 x)
5024 key (and (match-end 2) (match-string 2 x))
5025 log1 (and (match-end 3) (match-string 3 x))
5026 log2 (and (match-end 4) (match-string 4 x)))
5027 (and (or log1 log2)
5028 (list kw
5029 (and log1 (if (equal log1 "!") 'time 'note))
5030 (and log2 (if (equal log2 "!") 'time 'note)))))))
5032 (defun org-remove-keyword-keys (list)
5033 "Remove a pair of parenthesis at the end of each string in LIST."
5034 (mapcar (lambda (x)
5035 (if (string-match "(.*)$" x)
5036 (substring x 0 (match-beginning 0))
5038 list))
5040 (defun org-assign-fast-keys (alist)
5041 "Assign fast keys to a keyword-key alist.
5042 Respect keys that are already there."
5043 (let (new e (alt ?0))
5044 (while (setq e (pop alist))
5045 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5046 (cdr e)) ;; Key already assigned.
5047 (push e new)
5048 (let ((clist (string-to-list (downcase (car e))))
5049 (used (append new alist)))
5050 (when (= (car clist) ?@)
5051 (pop clist))
5052 (while (and clist (rassoc (car clist) used))
5053 (pop clist))
5054 (unless clist
5055 (while (rassoc alt used)
5056 (incf alt)))
5057 (push (cons (car e) (or (car clist) alt)) new))))
5058 (nreverse new)))
5060 ;;; Some variables used in various places
5062 (defvar org-window-configuration nil
5063 "Used in various places to store a window configuration.")
5064 (defvar org-selected-window nil
5065 "Used in various places to store a window configuration.")
5066 (defvar org-finish-function nil
5067 "Function to be called when `C-c C-c' is used.
5068 This is for getting out of special buffers like capture.")
5071 ;; FIXME: Occasionally check by commenting these, to make sure
5072 ;; no other functions uses these, forgetting to let-bind them.
5073 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5074 (defvar org-last-state)
5075 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5077 ;; Defined somewhere in this file, but used before definition.
5078 (defvar org-entities) ;; defined in org-entities.el
5079 (defvar org-struct-menu)
5080 (defvar org-org-menu)
5081 (defvar org-tbl-menu)
5083 ;;;; Define the Org-mode
5085 ;; We use a before-change function to check if a table might need
5086 ;; an update.
5087 (defvar org-table-may-need-update t
5088 "Indicates that a table might need an update.
5089 This variable is set by `org-before-change-function'.
5090 `org-table-align' sets it back to nil.")
5091 (defun org-before-change-function (beg end)
5092 "Every change indicates that a table might need an update."
5093 (setq org-table-may-need-update t))
5094 (defvar org-mode-map)
5095 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5096 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5097 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5098 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5099 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5100 (defvar org-table-buffer-is-an nil)
5102 (defvar bidi-paragraph-direction)
5103 (defvar buffer-face-mode-face)
5105 (require 'outline)
5106 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5107 (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"))
5108 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5110 ;; Other stuff we need.
5111 (require 'time-date)
5112 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5113 (require 'easymenu)
5114 (require 'overlay)
5116 ;; (require 'org-macs) moved higher up in the file before it is first used
5117 (require 'org-entities)
5118 ;; (require 'org-compat) moved higher up in the file before it is first used
5119 (require 'org-faces)
5120 (require 'org-list)
5121 (require 'org-pcomplete)
5122 (require 'org-src)
5123 (require 'org-footnote)
5125 ;; babel
5126 (require 'ob)
5128 ;;;###autoload
5129 (define-derived-mode org-mode outline-mode "Org"
5130 "Outline-based notes management and organizer, alias
5131 \"Carsten's outline-mode for keeping track of everything.\"
5133 Org-mode develops organizational tasks around a NOTES file which
5134 contains information about projects as plain text. Org-mode is
5135 implemented on top of outline-mode, which is ideal to keep the content
5136 of large files well structured. It supports ToDo items, deadlines and
5137 time stamps, which magically appear in the diary listing of the Emacs
5138 calendar. Tables are easily created with a built-in table editor.
5139 Plain text URL-like links connect to websites, emails (VM), Usenet
5140 messages (Gnus), BBDB entries, and any files related to the project.
5141 For printing and sharing of notes, an Org-mode file (or a part of it)
5142 can be exported as a structured ASCII or HTML file.
5144 The following commands are available:
5146 \\{org-mode-map}"
5148 ;; Get rid of Outline menus, they are not needed
5149 ;; Need to do this here because define-derived-mode sets up
5150 ;; the keymap so late. Still, it is a waste to call this each time
5151 ;; we switch another buffer into org-mode.
5152 (if (featurep 'xemacs)
5153 (when (boundp 'outline-mode-menu-heading)
5154 ;; Assume this is Greg's port, it uses easymenu
5155 (easy-menu-remove outline-mode-menu-heading)
5156 (easy-menu-remove outline-mode-menu-show)
5157 (easy-menu-remove outline-mode-menu-hide))
5158 (define-key org-mode-map [menu-bar headings] 'undefined)
5159 (define-key org-mode-map [menu-bar hide] 'undefined)
5160 (define-key org-mode-map [menu-bar show] 'undefined))
5162 (org-load-modules-maybe)
5163 (easy-menu-add org-org-menu)
5164 (easy-menu-add org-tbl-menu)
5165 (org-install-agenda-files-menu)
5166 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5167 (add-to-invisibility-spec '(org-cwidth))
5168 (add-to-invisibility-spec '(org-hide-block . t))
5169 (when (featurep 'xemacs)
5170 (org-set-local 'line-move-ignore-invisible t))
5171 (org-set-local 'outline-regexp org-outline-regexp)
5172 (org-set-local 'outline-level 'org-outline-level)
5173 (setq bidi-paragraph-direction 'left-to-right)
5174 (when (and org-ellipsis
5175 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5176 (fboundp 'make-glyph-code))
5177 (unless org-display-table
5178 (setq org-display-table (make-display-table)))
5179 (set-display-table-slot
5180 org-display-table 4
5181 (vconcat (mapcar
5182 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5183 org-ellipsis)))
5184 (if (stringp org-ellipsis) org-ellipsis "..."))))
5185 (setq buffer-display-table org-display-table))
5186 (org-set-regexps-and-options)
5187 (when (and org-tag-faces (not org-tags-special-faces-re))
5188 ;; tag faces set outside customize.... force initialization.
5189 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5190 ;; Calc embedded
5191 (org-set-local 'calc-embedded-open-mode "# ")
5192 (modify-syntax-entry ?@ "w")
5193 (modify-syntax-entry ?\" "\"")
5194 (if org-startup-truncated (setq truncate-lines t))
5195 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5196 (org-set-local 'font-lock-unfontify-region-function
5197 'org-unfontify-region)
5198 ;; Activate before-change-function
5199 (org-set-local 'org-table-may-need-update t)
5200 (org-add-hook 'before-change-functions 'org-before-change-function nil
5201 'local)
5202 ;; Check for running clock before killing a buffer
5203 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5204 ;; Initialize macros templates.
5205 (org-macro-initialize-templates)
5206 ;; Initialize radio targets.
5207 (org-update-radio-target-regexp)
5208 ;; Indentation.
5209 (org-set-local 'indent-line-function 'org-indent-line)
5210 (org-set-local 'indent-region-function 'org-indent-region)
5211 ;; Filling and auto-filling.
5212 (org-setup-filling)
5213 ;; Comments.
5214 (org-setup-comments-handling)
5215 ;; Beginning/end of defun
5216 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5217 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5218 ;; Next error for sparse trees
5219 (org-set-local 'next-error-function 'org-occur-next-match)
5220 ;; Make sure dependence stuff works reliably, even for users who set it
5221 ;; too late :-(
5222 (if org-enforce-todo-dependencies
5223 (add-hook 'org-blocker-hook
5224 'org-block-todo-from-children-or-siblings-or-parent)
5225 (remove-hook 'org-blocker-hook
5226 'org-block-todo-from-children-or-siblings-or-parent))
5227 (if org-enforce-todo-checkbox-dependencies
5228 (add-hook 'org-blocker-hook
5229 'org-block-todo-from-checkboxes)
5230 (remove-hook 'org-blocker-hook
5231 'org-block-todo-from-checkboxes))
5233 ;; Align options lines
5234 (org-set-local
5235 'align-mode-rules-list
5236 '((org-in-buffer-settings
5237 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5238 (modes . '(org-mode)))))
5240 ;; Imenu
5241 (org-set-local 'imenu-create-index-function
5242 'org-imenu-get-tree)
5244 ;; Make isearch reveal context
5245 (if (or (featurep 'xemacs)
5246 (not (boundp 'outline-isearch-open-invisible-function)))
5247 ;; Emacs 21 and XEmacs make use of the hook
5248 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5249 ;; Emacs 22 deals with this through a special variable
5250 (org-set-local 'outline-isearch-open-invisible-function
5251 (lambda (&rest ignore) (org-show-context 'isearch))))
5253 ;; Setup the pcomplete hooks
5254 (set (make-local-variable 'pcomplete-command-completion-function)
5255 'org-pcomplete-initial)
5256 (set (make-local-variable 'pcomplete-command-name-function)
5257 'org-command-at-point)
5258 (set (make-local-variable 'pcomplete-default-completion-function)
5259 'ignore)
5260 (set (make-local-variable 'pcomplete-parse-arguments-function)
5261 'org-parse-arguments)
5262 (set (make-local-variable 'pcomplete-termination-string) "")
5263 (when (>= emacs-major-version 23)
5264 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5266 ;; If empty file that did not turn on org-mode automatically, make it to.
5267 (if (and org-insert-mode-line-in-empty-file
5268 (org-called-interactively-p 'any)
5269 (= (point-min) (point-max)))
5270 (insert "# -*- mode: org -*-\n\n"))
5271 (unless org-inhibit-startup
5272 (and org-startup-with-beamer-mode (org-beamer-mode))
5273 (when org-startup-align-all-tables
5274 (let ((bmp (buffer-modified-p)))
5275 (org-table-map-tables 'org-table-align 'quietly)
5276 (set-buffer-modified-p bmp)))
5277 (when org-startup-with-inline-images
5278 (org-display-inline-images))
5279 (when org-startup-with-latex-preview
5280 (org-preview-latex-fragment))
5281 (unless org-inhibit-startup-visibility-stuff
5282 (org-set-startup-visibility)))
5283 ;; Try to set org-hide correctly
5284 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5286 (when (fboundp 'abbrev-table-put)
5287 (abbrev-table-put org-mode-abbrev-table
5288 :parents (list text-mode-abbrev-table)))
5290 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5293 (defun org-find-invisible-foreground ()
5294 (let ((candidates (remove
5295 "unspecified-bg"
5296 (nconc
5297 (list (face-background 'default)
5298 (face-background 'org-default))
5299 (mapcar
5300 (lambda (alist)
5301 (when (boundp alist)
5302 (cdr (assoc 'background-color (symbol-value alist)))))
5303 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5304 (list (face-foreground 'org-hide))))))
5305 (car (remove nil candidates))))
5307 (defun org-current-time (&optional rounding-minutes)
5308 "Current time, possibly rounded to ROUNDING-MINUTES.
5309 When ROUNDING-MINUTES is not an integer, fall back on the car of
5310 `org-time-stamp-rounding-minutes'."
5311 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5312 (car org-time-stamp-rounding-minutes)))
5313 (time (decode-time)))
5314 (if (> r 1)
5315 (apply 'encode-time
5316 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5317 (nthcdr 2 time)))
5318 (current-time))))
5320 (defun org-today ()
5321 "Return today date, considering `org-extend-today-until'."
5322 (time-to-days
5323 (time-subtract (current-time)
5324 (list 0 (* 3600 org-extend-today-until) 0))))
5326 ;;;; Font-Lock stuff, including the activators
5328 (defvar org-mouse-map (make-sparse-keymap))
5329 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5330 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5331 (when org-mouse-1-follows-link
5332 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5333 (when org-tab-follows-link
5334 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5335 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5337 (require 'font-lock)
5339 (defconst org-non-link-chars "]\t\n\r<>")
5340 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5341 "shell" "elisp" "doi" "message"))
5342 (defvar org-link-types-re nil
5343 "Matches a link that has a url-like prefix like \"http:\"")
5344 (defvar org-link-re-with-space nil
5345 "Matches a link with spaces, optional angular brackets around it.")
5346 (defvar org-link-re-with-space2 nil
5347 "Matches a link with spaces, optional angular brackets around it.")
5348 (defvar org-link-re-with-space3 nil
5349 "Matches a link with spaces, only for internal part in bracket links.")
5350 (defvar org-angle-link-re nil
5351 "Matches link with angular brackets, spaces are allowed.")
5352 (defvar org-plain-link-re nil
5353 "Matches plain link, without spaces.")
5354 (defvar org-bracket-link-regexp nil
5355 "Matches a link in double brackets.")
5356 (defvar org-bracket-link-analytic-regexp nil
5357 "Regular expression used to analyze links.
5358 Here is what the match groups contain after a match:
5359 1: http:
5360 2: http
5361 3: path
5362 4: [desc]
5363 5: desc")
5364 (defvar org-bracket-link-analytic-regexp++ nil
5365 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5366 (defvar org-any-link-re nil
5367 "Regular expression matching any link.")
5369 (defconst org-match-sexp-depth 3
5370 "Number of stacked braces for sub/superscript matching.")
5372 (defun org-create-multibrace-regexp (left right n)
5373 "Create a regular expression which will match a balanced sexp.
5374 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5375 as single character strings.
5376 The regexp returned will match the entire expression including the
5377 delimiters. It will also define a single group which contains the
5378 match except for the outermost delimiters. The maximum depth of
5379 stacked delimiters is N. Escaping delimiters is not possible."
5380 (let* ((nothing (concat "[^" left right "]*?"))
5381 (or "\\|")
5382 (re nothing)
5383 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5384 (while (> n 1)
5385 (setq n (1- n)
5386 re (concat re or next)
5387 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5388 (concat left "\\(" re "\\)" right)))
5390 (defvar org-match-substring-regexp
5391 (concat
5392 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5393 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5394 "\\|"
5395 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5396 "\\|"
5397 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5398 "The regular expression matching a sub- or superscript.")
5400 (defvar org-match-substring-with-braces-regexp
5401 (concat
5402 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5403 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5404 "\\)")
5405 "The regular expression matching a sub- or superscript, forcing braces.")
5407 (defun org-make-link-regexps ()
5408 "Update the link regular expressions.
5409 This should be called after the variable `org-link-types' has changed."
5410 (setq org-link-types-re
5411 (concat
5412 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5413 org-link-re-with-space
5414 (concat
5415 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5416 "\\([^" org-non-link-chars " ]"
5417 "[^" org-non-link-chars "]*"
5418 "[^" org-non-link-chars " ]\\)>?")
5419 org-link-re-with-space2
5420 (concat
5421 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5422 "\\([^" org-non-link-chars " ]"
5423 "[^\t\n\r]*"
5424 "[^" org-non-link-chars " ]\\)>?")
5425 org-link-re-with-space3
5426 (concat
5427 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5428 "\\([^" org-non-link-chars " ]"
5429 "[^\t\n\r]*\\)")
5430 org-angle-link-re
5431 (concat
5432 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5433 "\\([^" org-non-link-chars " ]"
5434 "[^" org-non-link-chars "]*"
5435 "\\)>")
5436 org-plain-link-re
5437 (concat
5438 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5439 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5440 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5441 org-bracket-link-regexp
5442 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5443 org-bracket-link-analytic-regexp
5444 (concat
5445 "\\[\\["
5446 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5447 "\\([^]]+\\)"
5448 "\\]"
5449 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5450 "\\]")
5451 org-bracket-link-analytic-regexp++
5452 (concat
5453 "\\[\\["
5454 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5455 "\\([^]]+\\)"
5456 "\\]"
5457 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5458 "\\]")
5459 org-any-link-re
5460 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5461 org-angle-link-re "\\)\\|\\("
5462 org-plain-link-re "\\)")))
5464 (org-make-link-regexps)
5466 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5467 "Regular expression for fast time stamp matching.")
5468 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5469 "Regular expression for fast time stamp matching.")
5470 (defconst org-ts-regexp0
5471 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5472 "Regular expression matching time strings for analysis.
5473 This one does not require the space after the date, so it can be used
5474 on a string that terminates immediately after the date.")
5475 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5476 "Regular expression matching time strings for analysis.")
5477 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5478 "Regular expression matching time stamps, with groups.")
5479 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5480 "Regular expression matching time stamps (also [..]), with groups.")
5481 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5482 "Regular expression matching a time stamp range.")
5483 (defconst org-tr-regexp-both
5484 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5485 "Regular expression matching a time stamp range.")
5486 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5487 org-ts-regexp "\\)?")
5488 "Regular expression matching a time stamp or time stamp range.")
5489 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5490 org-ts-regexp-both "\\)?")
5491 "Regular expression matching a time stamp or time stamp range.
5492 The time stamps may be either active or inactive.")
5494 (defvar org-emph-face nil)
5496 (defun org-do-emphasis-faces (limit)
5497 "Run through the buffer and add overlays to emphasized strings."
5498 (let (rtn a)
5499 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5500 (if (not (= (char-after (match-beginning 3))
5501 (char-after (match-beginning 4))))
5502 (progn
5503 (setq rtn t)
5504 (setq a (assoc (match-string 3) org-emphasis-alist))
5505 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5506 'face
5507 (nth 1 a))
5508 (and (nth 4 a)
5509 (org-remove-flyspell-overlays-in
5510 (match-beginning 0) (match-end 0)))
5511 (add-text-properties (match-beginning 2) (match-end 2)
5512 '(font-lock-multiline t org-emphasis t))
5513 (when org-hide-emphasis-markers
5514 (add-text-properties (match-end 4) (match-beginning 5)
5515 '(invisible org-link))
5516 (add-text-properties (match-beginning 3) (match-end 3)
5517 '(invisible org-link)))))
5518 (backward-char 1))
5519 rtn))
5521 (defun org-emphasize (&optional char)
5522 "Insert or change an emphasis, i.e. a font like bold or italic.
5523 If there is an active region, change that region to a new emphasis.
5524 If there is no region, just insert the marker characters and position
5525 the cursor between them.
5526 CHAR should be either the marker character, or the first character of the
5527 HTML tag associated with that emphasis. If CHAR is a space, the means
5528 to remove the emphasis of the selected region.
5529 If char is not given (for example in an interactive call) it
5530 will be prompted for."
5531 (interactive)
5532 (let ((eal org-emphasis-alist) e det
5533 (erc org-emphasis-regexp-components)
5534 (prompt "")
5535 (string "") beg end move tag c s)
5536 (if (org-region-active-p)
5537 (setq beg (region-beginning) end (region-end)
5538 string (buffer-substring beg end))
5539 (setq move t))
5541 (while (setq e (pop eal))
5542 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5543 c (aref tag 0))
5544 (push (cons c (string-to-char (car e))) det)
5545 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5546 (substring tag 1)))))
5547 (setq det (nreverse det))
5548 (unless char
5549 (message "%s" (concat "Emphasis marker or tag:" prompt))
5550 (setq char (read-char-exclusive)))
5551 (setq char (or (cdr (assoc char det)) char))
5552 (if (equal char ?\ )
5553 (setq s "" move nil)
5554 (unless (assoc (char-to-string char) org-emphasis-alist)
5555 (error "No such emphasis marker: \"%c\"" char))
5556 (setq s (char-to-string char)))
5557 (while (and (> (length string) 1)
5558 (equal (substring string 0 1) (substring string -1))
5559 (assoc (substring string 0 1) org-emphasis-alist))
5560 (setq string (substring string 1 -1)))
5561 (setq string (concat s string s))
5562 (if beg (delete-region beg end))
5563 (unless (or (bolp)
5564 (string-match (concat "[" (nth 0 erc) "\n]")
5565 (char-to-string (char-before (point)))))
5566 (insert " "))
5567 (unless (or (eobp)
5568 (string-match (concat "[" (nth 1 erc) "\n]")
5569 (char-to-string (char-after (point)))))
5570 (insert " ") (backward-char 1))
5571 (insert string)
5572 (and move (backward-char 1))))
5574 (defconst org-nonsticky-props
5575 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5577 (defsubst org-rear-nonsticky-at (pos)
5578 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5580 (defun org-activate-plain-links (limit)
5581 "Run through the buffer and add overlays to links."
5582 (catch 'exit
5583 (let (f hl)
5584 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5585 (not (org-in-src-block-p)))
5586 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5587 (setq f (get-text-property (match-beginning 0) 'face))
5588 (setq hl (org-match-string-no-properties 0))
5589 (if (or (eq f 'org-tag)
5590 (and (listp f) (memq 'org-tag f)))
5592 (add-text-properties (match-beginning 0) (match-end 0)
5593 (list 'mouse-face 'highlight
5594 'face 'org-link
5595 'htmlize-link `(:uri ,hl)
5596 'keymap org-mouse-map))
5597 (org-rear-nonsticky-at (match-end 0)))
5598 t))))
5600 (defun org-activate-code (limit)
5601 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5602 (progn
5603 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5604 (remove-text-properties (match-beginning 0) (match-end 0)
5605 '(display t invisible t intangible t))
5606 t)))
5608 (defcustom org-src-fontify-natively nil
5609 "When non-nil, fontify code in code blocks."
5610 :type 'boolean
5611 :version "24.1"
5612 :group 'org-appearance
5613 :group 'org-babel)
5615 (defcustom org-allow-promoting-top-level-subtree nil
5616 "When non-nil, allow promoting a top level subtree.
5617 The leading star of the top level headline will be replaced
5618 by a #."
5619 :type 'boolean
5620 :version "24.1"
5621 :group 'org-appearance)
5623 (defun org-fontify-meta-lines-and-blocks (limit)
5624 (condition-case nil
5625 (org-fontify-meta-lines-and-blocks-1 limit)
5626 (error (message "org-mode fontification error"))))
5628 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5629 "Fontify #+ lines and blocks, in the correct ways."
5630 (let ((case-fold-search t))
5631 (if (re-search-forward
5632 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5633 limit t)
5634 (let ((beg (match-beginning 0))
5635 (block-start (match-end 0))
5636 (block-end nil)
5637 (lang (match-string 7))
5638 (beg1 (line-beginning-position 2))
5639 (dc1 (downcase (match-string 2)))
5640 (dc3 (downcase (match-string 3)))
5641 end end1 quoting block-type ovl)
5642 (cond
5643 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5644 ;; a single line of backend-specific content
5645 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5646 (remove-text-properties (match-beginning 0) (match-end 0)
5647 '(display t invisible t intangible t))
5648 (add-text-properties (match-beginning 1) (match-end 3)
5649 '(font-lock-fontified t face org-meta-line))
5650 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5651 '(font-lock-fontified t face org-block))
5652 ; for backend-specific code
5654 ((and (match-end 4) (equal dc3 "+begin"))
5655 ;; Truly a block
5656 (setq block-type (downcase (match-string 5))
5657 quoting (member block-type org-protecting-blocks))
5658 (when (re-search-forward
5659 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5660 nil t) ;; on purpose, we look further than LIMIT
5661 (setq end (min (point-max) (match-end 0))
5662 end1 (min (point-max) (1- (match-beginning 0))))
5663 (setq block-end (match-beginning 0))
5664 (when quoting
5665 (remove-text-properties beg end
5666 '(display t invisible t intangible t)))
5667 (add-text-properties
5668 beg end
5669 '(font-lock-fontified t font-lock-multiline t))
5670 (add-text-properties beg beg1 '(face org-meta-line))
5671 (add-text-properties end1 (min (point-max) (1+ end))
5672 '(face org-meta-line)) ; for end_src
5673 (cond
5674 ((and lang (not (string= lang "")) org-src-fontify-natively)
5675 (org-src-font-lock-fontify-block lang block-start block-end)
5676 ;; remove old background overlays
5677 (mapc (lambda (ov)
5678 (if (eq (overlay-get ov 'face) 'org-block-background)
5679 (delete-overlay ov)))
5680 (overlays-at (/ (+ beg1 block-end) 2)))
5681 ;; add a background overlay
5682 (setq ovl (make-overlay beg1 block-end))
5683 (overlay-put ovl 'face 'org-block-background)
5684 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5685 (quoting
5686 (add-text-properties beg1 (min (point-max) (1+ end1))
5687 '(face org-block))) ; end of source block
5688 ((not org-fontify-quote-and-verse-blocks))
5689 ((string= block-type "quote")
5690 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5691 ((string= block-type "verse")
5692 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5693 (add-text-properties beg beg1 '(face org-block-begin-line))
5694 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5695 '(face org-block-end-line))
5697 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5698 (add-text-properties
5699 beg (match-end 3)
5700 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5701 '(font-lock-fontified t invisible t)
5702 '(font-lock-fontified t face org-document-info-keyword)))
5703 (add-text-properties
5704 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5705 (if (string-equal dc1 "+title:")
5706 '(font-lock-fontified t face org-document-title)
5707 '(font-lock-fontified t face org-document-info))))
5708 ((or (equal dc1 "+results")
5709 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5710 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5711 "+call:" "+header:" "+headers:" "+name:"))
5712 (and (match-end 4) (equal dc3 "+attr")))
5713 (add-text-properties
5714 beg (match-end 0)
5715 '(font-lock-fontified t face org-meta-line))
5717 ((member dc3 '(" " ""))
5718 (add-text-properties
5719 beg (match-end 0)
5720 '(font-lock-fontified t face font-lock-comment-face)))
5721 ((not (member (char-after beg) '(?\ ?\t)))
5722 ;; just any other in-buffer setting, but not indented
5723 (add-text-properties
5724 beg (match-end 0)
5725 '(font-lock-fontified t face org-meta-line))
5727 (t nil))))))
5729 (defun org-activate-angle-links (limit)
5730 "Run through the buffer and add overlays to links."
5731 (if (and (re-search-forward org-angle-link-re limit t)
5732 (not (org-in-src-block-p)))
5733 (progn
5734 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5735 (add-text-properties (match-beginning 0) (match-end 0)
5736 (list 'mouse-face 'highlight
5737 'keymap org-mouse-map))
5738 (org-rear-nonsticky-at (match-end 0))
5739 t)))
5741 (defun org-activate-footnote-links (limit)
5742 "Run through the buffer and add overlays to footnotes."
5743 (let ((fn (org-footnote-next-reference-or-definition limit)))
5744 (when fn
5745 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5746 (org-remove-flyspell-overlays-in beg end)
5747 (add-text-properties beg end
5748 (list 'mouse-face 'highlight
5749 'keymap org-mouse-map
5750 'help-echo
5751 (if (= (point-at-bol) beg)
5752 "Footnote definition"
5753 "Footnote reference")
5754 'font-lock-fontified t
5755 'font-lock-multiline t
5756 'face 'org-footnote))))))
5758 (defun org-activate-bracket-links (limit)
5759 "Run through the buffer and add overlays to bracketed links."
5760 (if (and (re-search-forward org-bracket-link-regexp limit t)
5761 (not (org-in-src-block-p)))
5762 (let* ((hl (org-match-string-no-properties 1))
5763 (help (concat "LINK: " hl))
5764 ;; FIXME: Above we should remove the escapes. But that
5765 ;; requires another match, protecting match data, a lot
5766 ;; of overhead for font-lock.
5767 (ip (org-maybe-intangible
5768 (list 'invisible 'org-link
5769 'keymap org-mouse-map 'mouse-face 'highlight
5770 'font-lock-multiline t 'help-echo help
5771 'htmlize-link `(:uri ,hl))))
5772 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5773 'font-lock-multiline t 'help-echo help
5774 'htmlize-link `(:uri ,hl))))
5775 ;; We need to remove the invisible property here. Table narrowing
5776 ;; may have made some of this invisible.
5777 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5778 (remove-text-properties (match-beginning 0) (match-end 0)
5779 '(invisible nil))
5780 (if (match-end 3)
5781 (progn
5782 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5783 (org-rear-nonsticky-at (match-beginning 3))
5784 (add-text-properties (match-beginning 3) (match-end 3) vp)
5785 (org-rear-nonsticky-at (match-end 3))
5786 (add-text-properties (match-end 3) (match-end 0) ip)
5787 (org-rear-nonsticky-at (match-end 0)))
5788 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5789 (org-rear-nonsticky-at (match-beginning 1))
5790 (add-text-properties (match-beginning 1) (match-end 1) vp)
5791 (org-rear-nonsticky-at (match-end 1))
5792 (add-text-properties (match-end 1) (match-end 0) ip)
5793 (org-rear-nonsticky-at (match-end 0)))
5794 t)))
5796 (defun org-activate-dates (limit)
5797 "Run through the buffer and add overlays to dates."
5798 (if (re-search-forward org-tsr-regexp-both limit t)
5799 (progn
5800 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5801 (add-text-properties (match-beginning 0) (match-end 0)
5802 (list 'mouse-face 'highlight
5803 'keymap org-mouse-map))
5804 (org-rear-nonsticky-at (match-end 0))
5805 (when org-display-custom-times
5806 (if (match-end 3)
5807 (org-display-custom-time (match-beginning 3) (match-end 3)))
5808 (org-display-custom-time (match-beginning 1) (match-end 1)))
5809 t)))
5811 (defvar org-target-link-regexp nil
5812 "Regular expression matching radio targets in plain text.")
5813 (make-variable-buffer-local 'org-target-link-regexp)
5814 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5815 "Regular expression matching a link target.")
5816 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5817 "Regular expression matching a radio target.")
5818 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5819 "Regular expression matching any target.")
5821 (defun org-activate-target-links (limit)
5822 "Run through the buffer and add overlays to target matches."
5823 (when org-target-link-regexp
5824 (let ((case-fold-search t))
5825 (if (re-search-forward org-target-link-regexp limit t)
5826 (progn
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (add-text-properties (match-beginning 0) (match-end 0)
5829 (list 'mouse-face 'highlight
5830 'keymap org-mouse-map
5831 'help-echo "Radio target link"
5832 'org-linked-text t))
5833 (org-rear-nonsticky-at (match-end 0))
5834 t)))))
5836 (defun org-update-radio-target-regexp ()
5837 "Find all radio targets in this file and update the regular expression."
5838 (interactive)
5839 (when (memq 'radio org-activate-links)
5840 (setq org-target-link-regexp
5841 (org-make-target-link-regexp (org-all-targets 'radio)))
5842 (org-restart-font-lock)))
5844 (defun org-hide-wide-columns (limit)
5845 (let (s e)
5846 (setq s (text-property-any (point) (or limit (point-max))
5847 'org-cwidth t))
5848 (when s
5849 (setq e (next-single-property-change s 'org-cwidth))
5850 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5851 (goto-char e)
5852 t)))
5854 (defvar org-match-substring-regexp)
5855 (defvar org-match-substring-with-braces-regexp)
5857 (defun org-restart-font-lock ()
5858 "Restart `font-lock-mode', to force refontification."
5859 (when (and (boundp 'font-lock-mode) font-lock-mode)
5860 (font-lock-mode -1)
5861 (font-lock-mode 1)))
5863 (defun org-all-targets (&optional radio)
5864 "Return a list of all targets in this file.
5865 When optional argument RADIO is non-nil, only find radio
5866 targets."
5867 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5868 (save-excursion
5869 (goto-char (point-min))
5870 (while (re-search-forward re nil t)
5871 ;; Make sure point is really within the object.
5872 (backward-char)
5873 (let ((obj (org-element-context)))
5874 (when (memq (org-element-type obj) '(radio-target target))
5875 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5876 rtn)))
5878 (defun org-make-target-link-regexp (targets)
5879 "Make regular expression matching all strings in TARGETS.
5880 The regular expression finds the targets also if there is a line break
5881 between words."
5882 (and targets
5883 (concat
5884 "\\<\\("
5885 (mapconcat
5886 (lambda (x)
5887 (setq x (regexp-quote x))
5888 (while (string-match " +" x)
5889 (setq x (replace-match "\\s-+" t t x)))
5891 targets
5892 "\\|")
5893 "\\)\\>")))
5895 (defun org-activate-tags (limit)
5896 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5897 (progn
5898 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5899 (add-text-properties (match-beginning 1) (match-end 1)
5900 (list 'mouse-face 'highlight
5901 'keymap org-mouse-map))
5902 (org-rear-nonsticky-at (match-end 1))
5903 t)))
5905 (defun org-outline-level ()
5906 "Compute the outline level of the heading at point.
5907 If this is called at a normal headline, the level is the number of stars.
5908 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5909 (save-excursion
5910 (if (not (condition-case nil
5911 (org-back-to-heading t)
5912 (error nil)))
5914 (looking-at org-outline-regexp)
5915 (1- (- (match-end 0) (match-beginning 0))))))
5917 (defvar org-font-lock-keywords nil)
5919 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5920 "Regular expression matching a property line.")
5922 (defvar org-font-lock-hook nil
5923 "Functions to be called for special font lock stuff.")
5925 (defvar org-font-lock-set-keywords-hook nil
5926 "Functions that can manipulate `org-font-lock-extra-keywords'.
5927 This is called after `org-font-lock-extra-keywords' is defined, but before
5928 it is installed to be used by font lock. This can be useful if something
5929 needs to be inserted at a specific position in the font-lock sequence.")
5931 (defun org-font-lock-hook (limit)
5932 "Run `org-font-lock-hook' within LIMIT."
5933 (run-hook-with-args 'org-font-lock-hook limit))
5935 (defun org-set-font-lock-defaults ()
5936 "Set font lock defaults for the current buffer."
5937 (let* ((em org-fontify-emphasized-text)
5938 (lk org-activate-links)
5939 (org-font-lock-extra-keywords
5940 (list
5941 ;; Call the hook
5942 '(org-font-lock-hook)
5943 ;; Headlines
5944 `(,(if org-fontify-whole-heading-line
5945 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5946 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5947 (1 (org-get-level-face 1))
5948 (2 (org-get-level-face 2))
5949 (3 (org-get-level-face 3)))
5950 ;; Table lines
5951 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5952 (1 'org-table t))
5953 ;; Table internals
5954 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5955 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5956 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5957 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5958 ;; Drawers
5959 (list org-drawer-regexp '(0 'org-special-keyword t))
5960 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5961 ;; Properties
5962 (list org-property-re
5963 '(1 'org-special-keyword t)
5964 '(3 'org-property-value t))
5965 ;; Links
5966 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5967 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5968 (if (memq 'plain lk) '(org-activate-plain-links))
5969 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5970 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5971 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5972 (if (memq 'footnote lk) '(org-activate-footnote-links))
5973 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5974 '(org-hide-wide-columns (0 nil append))
5975 ;; TODO keyword
5976 (list (format org-heading-keyword-regexp-format
5977 org-todo-regexp)
5978 '(2 (org-get-todo-face 2) t))
5979 ;; DONE
5980 (if org-fontify-done-headline
5981 (list (format org-heading-keyword-regexp-format
5982 (concat
5983 "\\(?:"
5984 (mapconcat 'regexp-quote org-done-keywords "\\|")
5985 "\\)"))
5986 '(2 'org-headline-done t))
5987 nil)
5988 ;; Priorities
5989 '(org-font-lock-add-priority-faces)
5990 ;; Tags
5991 '(org-font-lock-add-tag-faces)
5992 ;; Special keywords
5993 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5994 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5995 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5996 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5997 ;; Emphasis
5998 (if em
5999 (if (featurep 'xemacs)
6000 '(org-do-emphasis-faces (0 nil append))
6001 '(org-do-emphasis-faces)))
6002 ;; Checkboxes
6003 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6004 1 'org-checkbox prepend)
6005 (if (cdr (assq 'checkbox org-list-automatic-rules))
6006 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6007 (0 (org-get-checkbox-statistics-face) t)))
6008 ;; Description list items
6009 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6010 1 'org-list-dt prepend)
6011 ;; ARCHIVEd headings
6012 (list (concat
6013 org-outline-regexp-bol
6014 "\\(.*:" org-archive-tag ":.*\\)")
6015 '(1 'org-archived prepend))
6016 ;; Specials
6017 '(org-fontify-entities)
6018 '(org-raise-scripts)
6019 ;; Code
6020 '(org-activate-code (1 'org-code t))
6021 ;; COMMENT
6022 (list (format org-heading-keyword-regexp-format
6023 (concat "\\("
6024 org-comment-string "\\|" org-quote-string
6025 "\\)"))
6026 '(2 'org-special-keyword t))
6027 ;; Blocks and meta lines
6028 '(org-fontify-meta-lines-and-blocks)
6030 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6031 (run-hooks 'org-font-lock-set-keywords-hook)
6032 ;; Now set the full font-lock-keywords
6033 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6034 (org-set-local 'font-lock-defaults
6035 '(org-font-lock-keywords t nil nil backward-paragraph))
6036 (kill-local-variable 'font-lock-keywords) nil))
6038 (defun org-toggle-pretty-entities ()
6039 "Toggle the composition display of entities as UTF8 characters."
6040 (interactive)
6041 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6042 (org-restart-font-lock)
6043 (if org-pretty-entities
6044 (message "Entities are displayed as UTF8 characters")
6045 (save-restriction
6046 (widen)
6047 (org-decompose-region (point-min) (point-max))
6048 (message "Entities are displayed plain"))))
6050 (defvar org-custom-properties-overlays nil
6051 "List of overlays used for custom properties.")
6052 (make-variable-buffer-local 'org-custom-properties-overlays)
6054 (defun org-toggle-custom-properties-visibility ()
6055 "Display or hide properties in `org-custom-properties'."
6056 (interactive)
6057 (if org-custom-properties-overlays
6058 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6059 (setq org-custom-properties-overlays nil))
6060 (unless (not org-custom-properties)
6061 (save-excursion
6062 (save-restriction
6063 (widen)
6064 (goto-char (point-min))
6065 (while (re-search-forward org-property-re nil t)
6066 (mapc (lambda(p)
6067 (when (equal p (substring (match-string 1) 1 -1))
6068 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6069 (overlay-put o 'invisible t)
6070 (overlay-put o 'org-custom-property t)
6071 (push o org-custom-properties-overlays))))
6072 org-custom-properties)))))))
6074 (defun org-fontify-entities (limit)
6075 "Find an entity to fontify."
6076 (let (ee)
6077 (when org-pretty-entities
6078 (catch 'match
6079 (while (re-search-forward
6080 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6081 limit t)
6082 (if (and (not (org-in-indented-comment-line))
6083 (setq ee (org-entity-get (match-string 1)))
6084 (= (length (nth 6 ee)) 1))
6085 (let*
6086 ((end (if (equal (match-string 2) "{}")
6087 (match-end 2)
6088 (match-end 1))))
6089 (add-text-properties
6090 (match-beginning 0) end
6091 (list 'font-lock-fontified t))
6092 (compose-region (match-beginning 0) end
6093 (nth 6 ee) nil)
6094 (backward-char 1)
6095 (throw 'match t))))
6096 nil))))
6098 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6099 "Fontify string S like in Org-mode."
6100 (with-temp-buffer
6101 (insert s)
6102 (let ((org-odd-levels-only odd-levels))
6103 (org-mode)
6104 (font-lock-fontify-buffer)
6105 (buffer-string))))
6107 (defvar org-m nil)
6108 (defvar org-l nil)
6109 (defvar org-f nil)
6110 (defun org-get-level-face (n)
6111 "Get the right face for match N in font-lock matching of headlines."
6112 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6113 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6114 (if org-cycle-level-faces
6115 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6116 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6117 (cond
6118 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6119 ((eq n 2) org-f)
6120 (t (if org-level-color-stars-only nil org-f))))
6123 (defun org-get-todo-face (kwd)
6124 "Get the right face for a TODO keyword KWD.
6125 If KWD is a number, get the corresponding match group."
6126 (if (numberp kwd) (setq kwd (match-string kwd)))
6127 (or (org-face-from-face-or-color
6128 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6129 (and (member kwd org-done-keywords) 'org-done)
6130 'org-todo))
6132 (defun org-face-from-face-or-color (context inherit face-or-color)
6133 "Create a face list that inherits INHERIT, but sets the foreground color.
6134 When FACE-OR-COLOR is not a string, just return it."
6135 (if (stringp face-or-color)
6136 (list :inherit inherit
6137 (cdr (assoc context org-faces-easy-properties))
6138 face-or-color)
6139 face-or-color))
6141 (defun org-font-lock-add-tag-faces (limit)
6142 "Add the special tag faces."
6143 (when (and org-tag-faces org-tags-special-faces-re)
6144 (while (re-search-forward org-tags-special-faces-re limit t)
6145 (add-text-properties (match-beginning 1) (match-end 1)
6146 (list 'face (org-get-tag-face 1)
6147 'font-lock-fontified t))
6148 (backward-char 1))))
6150 (defun org-font-lock-add-priority-faces (limit)
6151 "Add the special priority faces."
6152 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6153 (when (save-match-data (org-at-heading-p))
6154 (add-text-properties
6155 (match-beginning 0) (match-end 0)
6156 (list 'face (or (org-face-from-face-or-color
6157 'priority 'org-priority
6158 (cdr (assoc (char-after (match-beginning 1))
6159 org-priority-faces)))
6160 'org-priority)
6161 'font-lock-fontified t)))))
6163 (defun org-get-tag-face (kwd)
6164 "Get the right face for a TODO keyword KWD.
6165 If KWD is a number, get the corresponding match group."
6166 (if (numberp kwd) (setq kwd (match-string kwd)))
6167 (or (org-face-from-face-or-color
6168 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6169 'org-tag))
6171 (defun org-unfontify-region (beg end &optional maybe_loudly)
6172 "Remove fontification and activation overlays from links."
6173 (font-lock-default-unfontify-region beg end)
6174 (let* ((buffer-undo-list t)
6175 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6176 (inhibit-modification-hooks t)
6177 deactivate-mark buffer-file-name buffer-file-truename)
6178 (org-decompose-region beg end)
6179 (remove-text-properties beg end
6180 '(mouse-face t keymap t org-linked-text t
6181 invisible t intangible t
6182 org-no-flyspell t org-emphasis t))
6183 (org-remove-font-lock-display-properties beg end)))
6185 (defconst org-script-display '(((raise -0.3) (height 0.7))
6186 ((raise 0.3) (height 0.7))
6187 ((raise -0.5))
6188 ((raise 0.5)))
6189 "Display properties for showing superscripts and subscripts.")
6191 (defun org-remove-font-lock-display-properties (beg end)
6192 "Remove specific display properties that have been added by font lock.
6193 The will remove the raise properties that are used to show superscripts
6194 and subscripts."
6195 (let (next prop)
6196 (while (< beg end)
6197 (setq next (next-single-property-change beg 'display nil end)
6198 prop (get-text-property beg 'display))
6199 (if (member prop org-script-display)
6200 (put-text-property beg next 'display nil))
6201 (setq beg next))))
6203 (defun org-raise-scripts (limit)
6204 "Add raise properties to sub/superscripts."
6205 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6206 (if (re-search-forward
6207 (if (eq org-use-sub-superscripts t)
6208 org-match-substring-regexp
6209 org-match-substring-with-braces-regexp)
6210 limit t)
6211 (let* ((pos (point)) table-p comment-p
6212 (mpos (match-beginning 3))
6213 (emph-p (get-text-property mpos 'org-emphasis))
6214 (link-p (get-text-property mpos 'mouse-face))
6215 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6216 (goto-char (point-at-bol))
6217 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6218 comment-p (org-looking-at-p "[ \t]*#"))
6219 (goto-char pos)
6220 ;; FIXME: Should we go back one character here, for a_b^c
6221 ;; (goto-char (1- pos)) ;????????????????????
6222 (if (or comment-p emph-p link-p keyw-p)
6224 (put-text-property (match-beginning 3) (match-end 0)
6225 'display
6226 (if (equal (char-after (match-beginning 2)) ?^)
6227 (nth (if table-p 3 1) org-script-display)
6228 (nth (if table-p 2 0) org-script-display)))
6229 (add-text-properties (match-beginning 2) (match-end 2)
6230 (list 'invisible t
6231 'org-dwidth t 'org-dwidth-n 1))
6232 (if (and (eq (char-after (match-beginning 3)) ?{)
6233 (eq (char-before (match-end 3)) ?}))
6234 (progn
6235 (add-text-properties
6236 (match-beginning 3) (1+ (match-beginning 3))
6237 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6238 (add-text-properties
6239 (1- (match-end 3)) (match-end 3)
6240 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6241 t)))))
6243 ;;;; Visibility cycling, including org-goto and indirect buffer
6245 ;;; Cycling
6247 (defvar org-cycle-global-status nil)
6248 (make-variable-buffer-local 'org-cycle-global-status)
6249 (put 'org-cycle-global-status 'org-state t)
6250 (defvar org-cycle-subtree-status nil)
6251 (make-variable-buffer-local 'org-cycle-subtree-status)
6252 (put 'org-cycle-subtree-status 'org-state t)
6254 (defvar org-inlinetask-min-level)
6256 ;;;###autoload
6257 (defun org-cycle (&optional arg)
6258 "TAB-action and visibility cycling for Org-mode.
6260 This is the command invoked in Org-mode by the TAB key. Its main purpose
6261 is outline visibility cycling, but it also invokes other actions
6262 in special contexts.
6264 - When this function is called with a prefix argument, rotate the entire
6265 buffer through 3 states (global cycling)
6266 1. OVERVIEW: Show only top-level headlines.
6267 2. CONTENTS: Show all headlines of all levels, but no body text.
6268 3. SHOW ALL: Show everything.
6269 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6270 determined by the variable `org-startup-folded', and by any VISIBILITY
6271 properties in the buffer.
6272 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6273 including any drawers.
6275 - When inside a table, re-align the table and move to the next field.
6277 - When point is at the beginning of a headline, rotate the subtree started
6278 by this line through 3 different states (local cycling)
6279 1. FOLDED: Only the main headline is shown.
6280 2. CHILDREN: The main headline and the direct children are shown.
6281 From this state, you can move to one of the children
6282 and zoom in further.
6283 3. SUBTREE: Show the entire subtree, including body text.
6284 If there is no subtree, switch directly from CHILDREN to FOLDED.
6286 - When point is at the beginning of an empty headline and the variable
6287 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6288 of the headline by demoting and promoting it to likely levels. This
6289 speeds up creation document structure by pressing TAB once or several
6290 times right after creating a new headline.
6292 - When there is a numeric prefix, go up to a heading with level ARG, do
6293 a `show-subtree' and return to the previous cursor position. If ARG
6294 is negative, go up that many levels.
6296 - When point is not at the beginning of a headline, execute the global
6297 binding for TAB, which is re-indenting the line. See the option
6298 `org-cycle-emulate-tab' for details.
6300 - Special case: if point is at the beginning of the buffer and there is
6301 no headline in line 1, this function will act as if called with prefix arg
6302 (C-u TAB, same as S-TAB) also when called without prefix arg.
6303 But only if also the variable `org-cycle-global-at-bob' is t."
6304 (interactive "P")
6305 (org-load-modules-maybe)
6306 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6307 (and org-cycle-level-after-item/entry-creation
6308 (or (org-cycle-level)
6309 (org-cycle-item-indentation))))
6310 (let* (message-log-max ; Don't populate the *Messages* buffer
6311 (limit-level
6312 (or org-cycle-max-level
6313 (and (boundp 'org-inlinetask-min-level)
6314 org-inlinetask-min-level
6315 (1- org-inlinetask-min-level))))
6316 (nstars (and limit-level
6317 (if org-odd-levels-only
6318 (and limit-level (1- (* limit-level 2)))
6319 limit-level)))
6320 (org-outline-regexp
6321 (if (not (derived-mode-p 'org-mode))
6322 outline-regexp
6323 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6324 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6325 (not (looking-at org-outline-regexp))))
6326 (org-cycle-hook
6327 (if bob-special
6328 (delq 'org-optimize-window-after-visibility-change
6329 (copy-sequence org-cycle-hook))
6330 org-cycle-hook))
6331 (pos (point)))
6333 (if (or bob-special (equal arg '(4)))
6334 ;; special case: use global cycling
6335 (setq arg t))
6337 (cond
6339 ((equal arg '(16))
6340 (setq last-command 'dummy)
6341 (org-set-startup-visibility)
6342 (message "Startup visibility, plus VISIBILITY properties"))
6344 ((equal arg '(64))
6345 (show-all)
6346 (message "Entire buffer visible, including drawers"))
6348 ;; Table: enter it or move to the next field.
6349 ((org-at-table-p 'any)
6350 (if (org-at-table.el-p)
6351 (message "Use C-c ' to edit table.el tables")
6352 (if arg (org-table-edit-field t)
6353 (org-table-justify-field-maybe)
6354 (call-interactively 'org-table-next-field))))
6356 ((run-hook-with-args-until-success
6357 'org-tab-after-check-for-table-hook))
6359 ;; Global cycling: delegate to `org-cycle-internal-global'.
6360 ((eq arg t) (org-cycle-internal-global))
6362 ;; Drawers: delegate to `org-flag-drawer'.
6363 ((and org-drawers org-drawer-regexp
6364 (save-excursion
6365 (beginning-of-line 1)
6366 (looking-at org-drawer-regexp)))
6367 (org-flag-drawer ; toggle block visibility
6368 (not (get-char-property (match-end 0) 'invisible))))
6370 ;; Show-subtree, ARG levels up from here.
6371 ((integerp arg)
6372 (save-excursion
6373 (org-back-to-heading)
6374 (outline-up-heading (if (< arg 0) (- arg)
6375 (- (funcall outline-level) arg)))
6376 (org-show-subtree)))
6378 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6379 ((and (featurep 'org-inlinetask)
6380 (org-inlinetask-at-task-p)
6381 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6382 (org-inlinetask-toggle-visibility))
6384 ((org-try-cdlatex-tab))
6386 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6387 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6388 (save-excursion (beginning-of-line 1)
6389 (looking-at org-outline-regexp)))
6390 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6391 (org-cycle-internal-local))
6393 ;; From there: TAB emulation and template completion.
6394 (buffer-read-only (org-back-to-heading))
6396 ((run-hook-with-args-until-success
6397 'org-tab-after-check-for-cycling-hook))
6399 ((org-try-structure-completion))
6401 ((run-hook-with-args-until-success
6402 'org-tab-before-tab-emulation-hook))
6404 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6405 (or (not (bolp))
6406 (not (looking-at org-outline-regexp))))
6407 (call-interactively (global-key-binding "\t")))
6409 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6410 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6411 (or (and (eq org-cycle-emulate-tab 'white)
6412 (= (match-end 0) (point-at-eol)))
6413 (and (eq org-cycle-emulate-tab 'whitestart)
6414 (>= (match-end 0) pos))))
6416 (eq org-cycle-emulate-tab t))
6417 (call-interactively (global-key-binding "\t")))
6419 (t (save-excursion
6420 (org-back-to-heading)
6421 (org-cycle)))))))
6423 (defun org-cycle-internal-global ()
6424 "Do the global cycling action."
6425 ;; Hack to avoid display of messages for .org attachments in Gnus
6426 (let (message-log-max ; Don't populate the *Messages* buffer
6427 (ga (string-match "\\*fontification" (buffer-name))))
6428 (cond
6429 ((and (eq last-command this-command)
6430 (eq org-cycle-global-status 'overview))
6431 ;; We just created the overview - now do table of contents
6432 ;; This can be slow in very large buffers, so indicate action
6433 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6434 (unless ga (message "CONTENTS..."))
6435 (org-content)
6436 (unless ga (message "CONTENTS...done"))
6437 (setq org-cycle-global-status 'contents)
6438 (run-hook-with-args 'org-cycle-hook 'contents))
6440 ((and (eq last-command this-command)
6441 (eq org-cycle-global-status 'contents))
6442 ;; We just showed the table of contents - now show everything
6443 (run-hook-with-args 'org-pre-cycle-hook 'all)
6444 (show-all)
6445 (unless ga (message "SHOW ALL"))
6446 (setq org-cycle-global-status 'all)
6447 (run-hook-with-args 'org-cycle-hook 'all))
6450 ;; Default action: go to overview
6451 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6452 (org-overview)
6453 (unless ga (message "OVERVIEW"))
6454 (setq org-cycle-global-status 'overview)
6455 (run-hook-with-args 'org-cycle-hook 'overview)))))
6457 (defun org-cycle-internal-local ()
6458 "Do the local cycling action."
6459 (let (message-log-max ; Don't populate the *Messages* buffer
6460 (goal-column 0) eoh eol eos has-children children-skipped struct)
6461 ;; First, determine end of headline (EOH), end of subtree or item
6462 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6463 (save-excursion
6464 (if (org-at-item-p)
6465 (progn
6466 (beginning-of-line)
6467 (setq struct (org-list-struct))
6468 (setq eoh (point-at-eol))
6469 (setq eos (org-list-get-item-end-before-blank (point) struct))
6470 (setq has-children (org-list-has-child-p (point) struct)))
6471 (org-back-to-heading)
6472 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6473 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6474 (setq has-children
6475 (or (save-excursion
6476 (let ((level (funcall outline-level)))
6477 (outline-next-heading)
6478 (and (org-at-heading-p t)
6479 (> (funcall outline-level) level))))
6480 (save-excursion
6481 (org-list-search-forward (org-item-beginning-re) eos t)))))
6482 ;; Determine end invisible part of buffer (EOL)
6483 (beginning-of-line 2)
6484 ;; XEmacs doesn't have `next-single-char-property-change'
6485 (if (featurep 'xemacs)
6486 (while (and (not (eobp)) ;; this is like `next-line'
6487 (get-char-property (1- (point)) 'invisible))
6488 (beginning-of-line 2))
6489 (while (and (not (eobp)) ;; this is like `next-line'
6490 (get-char-property (1- (point)) 'invisible))
6491 (goto-char (next-single-char-property-change (point) 'invisible))
6492 (and (eolp) (beginning-of-line 2))))
6493 (setq eol (point)))
6494 ;; Find out what to do next and set `this-command'
6495 (cond
6496 ((= eos eoh)
6497 ;; Nothing is hidden behind this heading
6498 (unless (org-before-first-heading-p)
6499 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6500 (message "EMPTY ENTRY")
6501 (setq org-cycle-subtree-status nil)
6502 (save-excursion
6503 (goto-char eos)
6504 (outline-next-heading)
6505 (if (outline-invisible-p) (org-flag-heading nil))))
6506 ((and (or (>= eol eos)
6507 (not (string-match "\\S-" (buffer-substring eol eos))))
6508 (or has-children
6509 (not (setq children-skipped
6510 org-cycle-skip-children-state-if-no-children))))
6511 ;; Entire subtree is hidden in one line: children view
6512 (unless (org-before-first-heading-p)
6513 (run-hook-with-args 'org-pre-cycle-hook 'children))
6514 (if (org-at-item-p)
6515 (org-list-set-item-visibility (point-at-bol) struct 'children)
6516 (org-show-entry)
6517 (org-with-limited-levels (show-children))
6518 ;; FIXME: This slows down the func way too much.
6519 ;; How keep drawers hidden in subtree anyway?
6520 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6521 ;; (org-cycle-hide-drawers 'subtree))
6523 ;; Fold every list in subtree to top-level items.
6524 (when (eq org-cycle-include-plain-lists 'integrate)
6525 (save-excursion
6526 (org-back-to-heading)
6527 (while (org-list-search-forward (org-item-beginning-re) eos t)
6528 (beginning-of-line 1)
6529 (let* ((struct (org-list-struct))
6530 (prevs (org-list-prevs-alist struct))
6531 (end (org-list-get-bottom-point struct)))
6532 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6533 (org-list-get-all-items (point) struct prevs))
6534 (goto-char end))))))
6535 (message "CHILDREN")
6536 (save-excursion
6537 (goto-char eos)
6538 (outline-next-heading)
6539 (if (outline-invisible-p) (org-flag-heading nil)))
6540 (setq org-cycle-subtree-status 'children)
6541 (unless (org-before-first-heading-p)
6542 (run-hook-with-args 'org-cycle-hook 'children)))
6543 ((or children-skipped
6544 (and (eq last-command this-command)
6545 (eq org-cycle-subtree-status 'children)))
6546 ;; We just showed the children, or no children are there,
6547 ;; now show everything.
6548 (unless (org-before-first-heading-p)
6549 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6550 (outline-flag-region eoh eos nil)
6551 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6552 (setq org-cycle-subtree-status 'subtree)
6553 (unless (org-before-first-heading-p)
6554 (run-hook-with-args 'org-cycle-hook 'subtree)))
6556 ;; Default action: hide the subtree.
6557 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6558 (outline-flag-region eoh eos t)
6559 (message "FOLDED")
6560 (setq org-cycle-subtree-status 'folded)
6561 (unless (org-before-first-heading-p)
6562 (run-hook-with-args 'org-cycle-hook 'folded))))))
6564 ;;;###autoload
6565 (defun org-global-cycle (&optional arg)
6566 "Cycle the global visibility. For details see `org-cycle'.
6567 With \\[universal-argument] prefix arg, switch to startup visibility.
6568 With a numeric prefix, show all headlines up to that level."
6569 (interactive "P")
6570 (let ((org-cycle-include-plain-lists
6571 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6572 (cond
6573 ((integerp arg)
6574 (show-all)
6575 (hide-sublevels arg)
6576 (setq org-cycle-global-status 'contents))
6577 ((equal arg '(4))
6578 (org-set-startup-visibility)
6579 (message "Startup visibility, plus VISIBILITY properties."))
6581 (org-cycle '(4))))))
6583 (defun org-set-startup-visibility ()
6584 "Set the visibility required by startup options and properties."
6585 (cond
6586 ((eq org-startup-folded t)
6587 (org-cycle '(4)))
6588 ((eq org-startup-folded 'content)
6589 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6590 (org-cycle '(4)) (org-cycle '(4)))))
6591 (unless (eq org-startup-folded 'showeverything)
6592 (if org-hide-block-startup (org-hide-block-all))
6593 (org-set-visibility-according-to-property 'no-cleanup)
6594 (org-cycle-hide-archived-subtrees 'all)
6595 (org-cycle-hide-drawers 'all)
6596 (org-cycle-show-empty-lines t)))
6598 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6599 "Switch subtree visibilities according to :VISIBILITY: property."
6600 (interactive)
6601 (let (org-show-entry-below state)
6602 (save-excursion
6603 (goto-char (point-min))
6604 (while (re-search-forward
6605 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6606 nil t)
6607 (setq state (match-string 1))
6608 (save-excursion
6609 (org-back-to-heading t)
6610 (hide-subtree)
6611 (org-reveal)
6612 (cond
6613 ((equal state '("fold" "folded"))
6614 (hide-subtree))
6615 ((equal state "children")
6616 (org-show-hidden-entry)
6617 (show-children))
6618 ((equal state "content")
6619 (save-excursion
6620 (save-restriction
6621 (org-narrow-to-subtree)
6622 (org-content))))
6623 ((member state '("all" "showall"))
6624 (show-subtree)))))
6625 (unless no-cleanup
6626 (org-cycle-hide-archived-subtrees 'all)
6627 (org-cycle-hide-drawers 'all)
6628 (org-cycle-show-empty-lines 'all)))))
6630 ;; This function uses outline-regexp instead of the more fundamental
6631 ;; org-outline-regexp so that org-cycle-global works outside of Org
6632 ;; buffers, where outline-regexp is needed.
6633 (defun org-overview ()
6634 "Switch to overview mode, showing only top-level headlines.
6635 Really, this shows all headlines with level equal or greater than the level
6636 of the first headline in the buffer. This is important, because if the
6637 first headline is not level one, then (hide-sublevels 1) gives confusing
6638 results."
6639 (interactive)
6640 (let ((level (save-excursion
6641 (goto-char (point-min))
6642 (if (re-search-forward (concat "^" outline-regexp) nil t)
6643 (progn
6644 (goto-char (match-beginning 0))
6645 (funcall outline-level))))))
6646 (and level (hide-sublevels level))))
6648 (defun org-content (&optional arg)
6649 "Show all headlines in the buffer, like a table of contents.
6650 With numerical argument N, show content up to level N."
6651 (interactive "P")
6652 (save-excursion
6653 ;; Visit all headings and show their offspring
6654 (and (integerp arg) (org-overview))
6655 (goto-char (point-max))
6656 (catch 'exit
6657 (while (and (progn (condition-case nil
6658 (outline-previous-visible-heading 1)
6659 (error (goto-char (point-min))))
6661 (looking-at org-outline-regexp))
6662 (if (integerp arg)
6663 (show-children (1- arg))
6664 (show-branches))
6665 (if (bobp) (throw 'exit nil))))))
6668 (defun org-optimize-window-after-visibility-change (state)
6669 "Adjust the window after a change in outline visibility.
6670 This function is the default value of the hook `org-cycle-hook'."
6671 (when (get-buffer-window (current-buffer))
6672 (cond
6673 ((eq state 'content) nil)
6674 ((eq state 'all) nil)
6675 ((eq state 'folded) nil)
6676 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6677 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6679 (defun org-remove-empty-overlays-at (pos)
6680 "Remove outline overlays that do not contain non-white stuff."
6681 (mapc
6682 (lambda (o)
6683 (and (eq 'outline (overlay-get o 'invisible))
6684 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6685 (overlay-end o))))
6686 (delete-overlay o)))
6687 (overlays-at pos)))
6689 (defun org-clean-visibility-after-subtree-move ()
6690 "Fix visibility issues after moving a subtree."
6691 ;; First, find a reasonable region to look at:
6692 ;; Start two siblings above, end three below
6693 (let* ((beg (save-excursion
6694 (and (org-get-last-sibling)
6695 (org-get-last-sibling))
6696 (point)))
6697 (end (save-excursion
6698 (and (org-get-next-sibling)
6699 (org-get-next-sibling)
6700 (org-get-next-sibling))
6701 (if (org-at-heading-p)
6702 (point-at-eol)
6703 (point))))
6704 (level (looking-at "\\*+"))
6705 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6706 (save-excursion
6707 (save-restriction
6708 (narrow-to-region beg end)
6709 (when re
6710 ;; Properly fold already folded siblings
6711 (goto-char (point-min))
6712 (while (re-search-forward re nil t)
6713 (if (and (not (outline-invisible-p))
6714 (save-excursion
6715 (goto-char (point-at-eol)) (outline-invisible-p)))
6716 (hide-entry))))
6717 (org-cycle-show-empty-lines 'overview)
6718 (org-cycle-hide-drawers 'overview)))))
6720 (defun org-cycle-show-empty-lines (state)
6721 "Show empty lines above all visible headlines.
6722 The region to be covered depends on STATE when called through
6723 `org-cycle-hook'. Lisp program can use t for STATE to get the
6724 entire buffer covered. Note that an empty line is only shown if there
6725 are at least `org-cycle-separator-lines' empty lines before the headline."
6726 (when (not (= org-cycle-separator-lines 0))
6727 (save-excursion
6728 (let* ((n (abs org-cycle-separator-lines))
6729 (re (cond
6730 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6731 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6732 (t (let ((ns (number-to-string (- n 2))))
6733 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6734 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6735 beg end b e)
6736 (cond
6737 ((memq state '(overview contents t))
6738 (setq beg (point-min) end (point-max)))
6739 ((memq state '(children folded))
6740 (setq beg (point) end (progn (org-end-of-subtree t t)
6741 (beginning-of-line 2)
6742 (point)))))
6743 (when beg
6744 (goto-char beg)
6745 (while (re-search-forward re end t)
6746 (unless (get-char-property (match-end 1) 'invisible)
6747 (setq e (match-end 1))
6748 (if (< org-cycle-separator-lines 0)
6749 (setq b (save-excursion
6750 (goto-char (match-beginning 0))
6751 (org-back-over-empty-lines)
6752 (if (save-excursion
6753 (goto-char (max (point-min) (1- (point))))
6754 (org-at-heading-p))
6755 (1- (point))
6756 (point))))
6757 (setq b (match-beginning 1)))
6758 (outline-flag-region b e nil)))))))
6759 ;; Never hide empty lines at the end of the file.
6760 (save-excursion
6761 (goto-char (point-max))
6762 (outline-previous-heading)
6763 (outline-end-of-heading)
6764 (if (and (looking-at "[ \t\n]+")
6765 (= (match-end 0) (point-max)))
6766 (outline-flag-region (point) (match-end 0) nil))))
6768 (defun org-show-empty-lines-in-parent ()
6769 "Move to the parent and re-show empty lines before visible headlines."
6770 (save-excursion
6771 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6772 (org-cycle-show-empty-lines context))))
6774 (defun org-files-list ()
6775 "Return `org-agenda-files' list, plus all open org-mode files.
6776 This is useful for operations that need to scan all of a user's
6777 open and agenda-wise Org files."
6778 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6779 (dolist (buf (buffer-list))
6780 (with-current-buffer buf
6781 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6782 (let ((file (expand-file-name (buffer-file-name))))
6783 (unless (member file files)
6784 (push file files))))))
6785 files))
6787 (defsubst org-entry-beginning-position ()
6788 "Return the beginning position of the current entry."
6789 (save-excursion (outline-back-to-heading t) (point)))
6791 (defsubst org-entry-end-position ()
6792 "Return the end position of the current entry."
6793 (save-excursion (outline-next-heading) (point)))
6795 (defun org-cycle-hide-drawers (state)
6796 "Re-hide all drawers after a visibility state change."
6797 (when (and (derived-mode-p 'org-mode)
6798 (not (memq state '(overview folded contents))))
6799 (save-excursion
6800 (let* ((globalp (memq state '(contents all)))
6801 (beg (if globalp (point-min) (point)))
6802 (end (if globalp (point-max)
6803 (if (eq state 'children)
6804 (save-excursion (outline-next-heading) (point))
6805 (org-end-of-subtree t)))))
6806 (goto-char beg)
6807 (while (re-search-forward org-drawer-regexp end t)
6808 (org-flag-drawer t))))))
6810 (defun org-cycle-hide-inline-tasks (state)
6811 "Re-hide inline task when switching to 'contents visibility state."
6812 (when (and (eq state 'contents)
6813 (boundp 'org-inlinetask-min-level)
6814 org-inlinetask-min-level)
6815 (hide-sublevels (1- org-inlinetask-min-level))))
6817 (defun org-flag-drawer (flag)
6818 "When FLAG is non-nil, hide the drawer we are within.
6819 Otherwise make it visible."
6820 (save-excursion
6821 (beginning-of-line 1)
6822 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6823 (let ((b (match-end 0)))
6824 (if (re-search-forward
6825 "^[ \t]*:END:"
6826 (save-excursion (outline-next-heading) (point)) t)
6827 (outline-flag-region b (point-at-eol) flag)
6828 (error ":END: line missing at position %s" b))))))
6830 (defun org-subtree-end-visible-p ()
6831 "Is the end of the current subtree visible?"
6832 (pos-visible-in-window-p
6833 (save-excursion (org-end-of-subtree t) (point))))
6835 (defun org-first-headline-recenter (&optional N)
6836 "Move cursor to the first headline and recenter the headline.
6837 Optional argument N means put the headline into the Nth line of the window."
6838 (goto-char (point-min))
6839 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6840 (beginning-of-line)
6841 (recenter (prefix-numeric-value N))))
6843 ;;; Saving and restoring visibility
6845 (defun org-outline-overlay-data (&optional use-markers)
6846 "Return a list of the locations of all outline overlays.
6847 These are overlays with the `invisible' property value `outline'.
6848 The return value is a list of cons cells, with start and stop
6849 positions for each overlay.
6850 If USE-MARKERS is set, return the positions as markers."
6851 (let (beg end)
6852 (save-excursion
6853 (save-restriction
6854 (widen)
6855 (delq nil
6856 (mapcar (lambda (o)
6857 (when (eq (overlay-get o 'invisible) 'outline)
6858 (setq beg (overlay-start o)
6859 end (overlay-end o))
6860 (and beg end (> end beg)
6861 (if use-markers
6862 (cons (move-marker (make-marker) beg)
6863 (move-marker (make-marker) end))
6864 (cons beg end)))))
6865 (overlays-in (point-min) (point-max))))))))
6867 (defun org-set-outline-overlay-data (data)
6868 "Create visibility overlays for all positions in DATA.
6869 DATA should have been made by `org-outline-overlay-data'."
6870 (let (o)
6871 (save-excursion
6872 (save-restriction
6873 (widen)
6874 (show-all)
6875 (mapc (lambda (c)
6876 (outline-flag-region (car c) (cdr c) t))
6877 data)))))
6879 ;;; Folding of blocks
6881 (defvar org-hide-block-overlays nil
6882 "Overlays hiding blocks.")
6883 (make-variable-buffer-local 'org-hide-block-overlays)
6885 (defun org-block-map (function &optional start end)
6886 "Call FUNCTION at the head of all source blocks in the current buffer.
6887 Optional arguments START and END can be used to limit the range."
6888 (let ((start (or start (point-min)))
6889 (end (or end (point-max))))
6890 (save-excursion
6891 (goto-char start)
6892 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6893 (save-excursion
6894 (save-match-data
6895 (goto-char (match-beginning 0))
6896 (funcall function)))))))
6898 (defun org-hide-block-toggle-all ()
6899 "Toggle the visibility of all blocks in the current buffer."
6900 (org-block-map #'org-hide-block-toggle))
6902 (defun org-hide-block-all ()
6903 "Fold all blocks in the current buffer."
6904 (interactive)
6905 (org-show-block-all)
6906 (org-block-map #'org-hide-block-toggle-maybe))
6908 (defun org-show-block-all ()
6909 "Unfold all blocks in the current buffer."
6910 (interactive)
6911 (mapc 'delete-overlay org-hide-block-overlays)
6912 (setq org-hide-block-overlays nil))
6914 (defun org-hide-block-toggle-maybe ()
6915 "Toggle visibility of block at point."
6916 (interactive)
6917 (let ((case-fold-search t))
6918 (if (save-excursion
6919 (beginning-of-line 1)
6920 (looking-at org-block-regexp))
6921 (progn (org-hide-block-toggle)
6922 t) ;; to signal that we took action
6923 nil))) ;; to signal that we did not
6925 (defun org-hide-block-toggle (&optional force)
6926 "Toggle the visibility of the current block."
6927 (interactive)
6928 (save-excursion
6929 (beginning-of-line)
6930 (if (re-search-forward org-block-regexp nil t)
6931 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6932 (end (match-end 0)) ;; end of entire body
6934 (if (memq t (mapcar (lambda (overlay)
6935 (eq (overlay-get overlay 'invisible)
6936 'org-hide-block))
6937 (overlays-at start)))
6938 (if (or (not force) (eq force 'off))
6939 (mapc (lambda (ov)
6940 (when (member ov org-hide-block-overlays)
6941 (setq org-hide-block-overlays
6942 (delq ov org-hide-block-overlays)))
6943 (when (eq (overlay-get ov 'invisible)
6944 'org-hide-block)
6945 (delete-overlay ov)))
6946 (overlays-at start)))
6947 (setq ov (make-overlay start end))
6948 (overlay-put ov 'invisible 'org-hide-block)
6949 ;; make the block accessible to isearch
6950 (overlay-put
6951 ov 'isearch-open-invisible
6952 (lambda (ov)
6953 (when (member ov org-hide-block-overlays)
6954 (setq org-hide-block-overlays
6955 (delq ov org-hide-block-overlays)))
6956 (when (eq (overlay-get ov 'invisible)
6957 'org-hide-block)
6958 (delete-overlay ov))))
6959 (push ov org-hide-block-overlays)))
6960 (error "Not looking at a source block"))))
6962 ;; org-tab-after-check-for-cycling-hook
6963 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6964 ;; Remove overlays when changing major mode
6965 (add-hook 'org-mode-hook
6966 (lambda () (org-add-hook 'change-major-mode-hook
6967 'org-show-block-all 'append 'local)))
6969 ;;; Org-goto
6971 (defvar org-goto-window-configuration nil)
6972 (defvar org-goto-marker nil)
6973 (defvar org-goto-map)
6974 (defun org-goto-map ()
6975 "Set the keymap `org-goto'."
6976 (setq org-goto-map
6977 (let ((map (make-sparse-keymap)))
6978 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6979 mouse-drag-region universal-argument org-occur))
6980 cmd)
6981 (while (setq cmd (pop cmds))
6982 (substitute-key-definition cmd cmd map global-map)))
6983 (suppress-keymap map)
6984 (org-defkey map "\C-m" 'org-goto-ret)
6985 (org-defkey map [(return)] 'org-goto-ret)
6986 (org-defkey map [(left)] 'org-goto-left)
6987 (org-defkey map [(right)] 'org-goto-right)
6988 (org-defkey map [(control ?g)] 'org-goto-quit)
6989 (org-defkey map "\C-i" 'org-cycle)
6990 (org-defkey map [(tab)] 'org-cycle)
6991 (org-defkey map [(down)] 'outline-next-visible-heading)
6992 (org-defkey map [(up)] 'outline-previous-visible-heading)
6993 (if org-goto-auto-isearch
6994 (if (fboundp 'define-key-after)
6995 (define-key-after map [t] 'org-goto-local-auto-isearch)
6996 nil)
6997 (org-defkey map "q" 'org-goto-quit)
6998 (org-defkey map "n" 'outline-next-visible-heading)
6999 (org-defkey map "p" 'outline-previous-visible-heading)
7000 (org-defkey map "f" 'outline-forward-same-level)
7001 (org-defkey map "b" 'outline-backward-same-level)
7002 (org-defkey map "u" 'outline-up-heading))
7003 (org-defkey map "/" 'org-occur)
7004 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7005 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7006 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7007 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7008 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7009 map)))
7011 (defconst org-goto-help
7012 "Browse buffer copy, to find location or copy text.%s
7013 RET=jump to location C-g=quit and return to previous location
7014 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7016 (defvar org-goto-start-pos) ; dynamically scoped parameter
7018 ;; FIXME: Docstring does not mention both interfaces
7019 (defun org-goto (&optional alternative-interface)
7020 "Look up a different location in the current file, keeping current visibility.
7022 When you want look-up or go to a different location in a
7023 document, the fastest way is often to fold the entire buffer and
7024 then dive into the tree. This method has the disadvantage, that
7025 the previous location will be folded, which may not be what you
7026 want.
7028 This command works around this by showing a copy of the current
7029 buffer in an indirect buffer, in overview mode. You can dive
7030 into the tree in that copy, use org-occur and incremental search
7031 to find a location. When pressing RET or `Q', the command
7032 returns to the original buffer in which the visibility is still
7033 unchanged. After RET it will also jump to the location selected
7034 in the indirect buffer and expose the headline hierarchy above.
7036 With a prefix argument, use the alternative interface: e.g. if
7037 `org-goto-interface' is 'outline use 'outline-path-completion."
7038 (interactive "P")
7039 (org-goto-map)
7040 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7041 (org-refile-use-outline-path t)
7042 (org-refile-target-verify-function nil)
7043 (interface
7044 (if (not alternative-interface)
7045 org-goto-interface
7046 (if (eq org-goto-interface 'outline)
7047 'outline-path-completion
7048 'outline)))
7049 (org-goto-start-pos (point))
7050 (selected-point
7051 (if (eq interface 'outline)
7052 (car (org-get-location (current-buffer) org-goto-help))
7053 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7054 (org-refile-check-position pa)
7055 (nth 3 pa)))))
7056 (if selected-point
7057 (progn
7058 (org-mark-ring-push org-goto-start-pos)
7059 (goto-char selected-point)
7060 (if (or (outline-invisible-p) (org-invisible-p2))
7061 (org-show-context 'org-goto)))
7062 (message "Quit"))))
7064 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7065 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7066 (defvar org-goto-local-auto-isearch-map) ; defined below
7068 (defun org-get-location (buf help)
7069 "Let the user select a location in the Org-mode buffer BUF.
7070 This function uses a recursive edit. It returns the selected position
7071 or nil."
7072 (org-no-popups
7073 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7074 (isearch-hide-immediately nil)
7075 (isearch-search-fun-function
7076 (lambda () 'org-goto-local-search-headings))
7077 (org-goto-selected-point org-goto-exit-command))
7078 (save-excursion
7079 (save-window-excursion
7080 (delete-other-windows)
7081 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7082 (org-pop-to-buffer-same-window
7083 (condition-case nil
7084 (make-indirect-buffer (current-buffer) "*org-goto*")
7085 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7086 (with-output-to-temp-buffer "*Org Help*"
7087 (princ (format help (if org-goto-auto-isearch
7088 " Just type for auto-isearch."
7089 " n/p/f/b/u to navigate, q to quit."))))
7090 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7091 (setq buffer-read-only nil)
7092 (let ((org-startup-truncated t)
7093 (org-startup-folded nil)
7094 (org-startup-align-all-tables nil))
7095 (org-mode)
7096 (org-overview))
7097 (setq buffer-read-only t)
7098 (if (and (boundp 'org-goto-start-pos)
7099 (integer-or-marker-p org-goto-start-pos))
7100 (let ((org-show-hierarchy-above t)
7101 (org-show-siblings t)
7102 (org-show-following-heading t))
7103 (goto-char org-goto-start-pos)
7104 (and (outline-invisible-p) (org-show-context)))
7105 (goto-char (point-min)))
7106 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7107 (message "Select location and press RET")
7108 (use-local-map org-goto-map)
7109 (recursive-edit)))
7110 (kill-buffer "*org-goto*")
7111 (cons org-goto-selected-point org-goto-exit-command))))
7113 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7114 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7115 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7116 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7118 (defun org-goto-local-search-headings (string bound noerror)
7119 "Search and make sure that any matches are in headlines."
7120 (catch 'return
7121 (while (if isearch-forward
7122 (search-forward string bound noerror)
7123 (search-backward string bound noerror))
7124 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7125 (and (member :headline context)
7126 (not (member :tags context))))
7127 (throw 'return (point))))))
7129 (defun org-goto-local-auto-isearch ()
7130 "Start isearch."
7131 (interactive)
7132 (goto-char (point-min))
7133 (let ((keys (this-command-keys)))
7134 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7135 (isearch-mode t)
7136 (isearch-process-search-char (string-to-char keys)))))
7138 (defun org-goto-ret (&optional arg)
7139 "Finish `org-goto' by going to the new location."
7140 (interactive "P")
7141 (setq org-goto-selected-point (point)
7142 org-goto-exit-command 'return)
7143 (throw 'exit nil))
7145 (defun org-goto-left ()
7146 "Finish `org-goto' by going to the new location."
7147 (interactive)
7148 (if (org-at-heading-p)
7149 (progn
7150 (beginning-of-line 1)
7151 (setq org-goto-selected-point (point)
7152 org-goto-exit-command 'left)
7153 (throw 'exit nil))
7154 (error "Not on a heading")))
7156 (defun org-goto-right ()
7157 "Finish `org-goto' by going to the new location."
7158 (interactive)
7159 (if (org-at-heading-p)
7160 (progn
7161 (setq org-goto-selected-point (point)
7162 org-goto-exit-command 'right)
7163 (throw 'exit nil))
7164 (error "Not on a heading")))
7166 (defun org-goto-quit ()
7167 "Finish `org-goto' without cursor motion."
7168 (interactive)
7169 (setq org-goto-selected-point nil)
7170 (setq org-goto-exit-command 'quit)
7171 (throw 'exit nil))
7173 ;;; Indirect buffer display of subtrees
7175 (defvar org-indirect-dedicated-frame nil
7176 "This is the frame being used for indirect tree display.")
7177 (defvar org-last-indirect-buffer nil)
7179 (defun org-tree-to-indirect-buffer (&optional arg)
7180 "Create indirect buffer and narrow it to current subtree.
7181 With a numerical prefix ARG, go up to this level and then take that tree.
7182 If ARG is negative, go up that many levels.
7184 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7185 indirect buffer previously made with this command, to avoid proliferation of
7186 indirect buffers. However, when you call the command with a \
7187 \\[universal-argument] prefix, or
7188 when `org-indirect-buffer-display' is `new-frame', the last buffer
7189 is kept so that you can work with several indirect buffers at the same time.
7190 If `org-indirect-buffer-display' is `dedicated-frame', the \
7191 \\[universal-argument] prefix also
7192 requests that a new frame be made for the new buffer, so that the dedicated
7193 frame is not changed."
7194 (interactive "P")
7195 (let ((cbuf (current-buffer))
7196 (cwin (selected-window))
7197 (pos (point))
7198 beg end level heading ibuf)
7199 (save-excursion
7200 (org-back-to-heading t)
7201 (when (numberp arg)
7202 (setq level (org-outline-level))
7203 (if (< arg 0) (setq arg (+ level arg)))
7204 (while (> (setq level (org-outline-level)) arg)
7205 (org-up-heading-safe)))
7206 (setq beg (point)
7207 heading (org-get-heading))
7208 (org-end-of-subtree t t)
7209 (if (org-at-heading-p) (backward-char 1))
7210 (setq end (point)))
7211 (if (and (buffer-live-p org-last-indirect-buffer)
7212 (not (eq org-indirect-buffer-display 'new-frame))
7213 (not arg))
7214 (kill-buffer org-last-indirect-buffer))
7215 (setq ibuf (org-get-indirect-buffer cbuf)
7216 org-last-indirect-buffer ibuf)
7217 (cond
7218 ((or (eq org-indirect-buffer-display 'new-frame)
7219 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7220 (select-frame (make-frame))
7221 (delete-other-windows)
7222 (org-pop-to-buffer-same-window ibuf)
7223 (org-set-frame-title heading))
7224 ((eq org-indirect-buffer-display 'dedicated-frame)
7225 (raise-frame
7226 (select-frame (or (and org-indirect-dedicated-frame
7227 (frame-live-p org-indirect-dedicated-frame)
7228 org-indirect-dedicated-frame)
7229 (setq org-indirect-dedicated-frame (make-frame)))))
7230 (delete-other-windows)
7231 (org-pop-to-buffer-same-window ibuf)
7232 (org-set-frame-title (concat "Indirect: " heading)))
7233 ((eq org-indirect-buffer-display 'current-window)
7234 (org-pop-to-buffer-same-window ibuf))
7235 ((eq org-indirect-buffer-display 'other-window)
7236 (pop-to-buffer ibuf))
7237 (t (error "Invalid value")))
7238 (if (featurep 'xemacs)
7239 (save-excursion (org-mode) (turn-on-font-lock)))
7240 (narrow-to-region beg end)
7241 (show-all)
7242 (goto-char pos)
7243 (run-hook-with-args 'org-cycle-hook 'all)
7244 (and (window-live-p cwin) (select-window cwin))))
7246 (defun org-get-indirect-buffer (&optional buffer)
7247 (setq buffer (or buffer (current-buffer)))
7248 (let ((n 1) (base (buffer-name buffer)) bname)
7249 (while (buffer-live-p
7250 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7251 (setq n (1+ n)))
7252 (condition-case nil
7253 (make-indirect-buffer buffer bname 'clone)
7254 (error (make-indirect-buffer buffer bname)))))
7256 (defun org-set-frame-title (title)
7257 "Set the title of the current frame to the string TITLE."
7258 ;; FIXME: how to name a single frame in XEmacs???
7259 (unless (featurep 'xemacs)
7260 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7262 ;;;; Structure editing
7264 ;;; Inserting headlines
7266 (defun org-previous-line-empty-p ()
7267 (save-excursion
7268 (and (not (bobp))
7269 (or (beginning-of-line 0) t)
7270 (save-match-data
7271 (looking-at "[ \t]*$")))))
7273 (defun org-insert-heading (&optional force-heading invisible-ok)
7274 "Insert a new heading or item with same depth at point.
7275 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7276 If point is at the beginning of a headline, insert a sibling before the
7277 current headline. If point is not at the beginning, split the line,
7278 create the new headline with the text in the current line after point
7279 \(but see also the variable `org-M-RET-may-split-line').
7281 With a double prefix arg, force the heading to be inserted at the
7282 end of the parent subtree.
7284 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7285 This is important for non-interactive uses of the command."
7286 (interactive "P")
7287 (if (or (= (buffer-size) 0)
7288 (and (not (save-excursion
7289 (and (ignore-errors (org-back-to-heading invisible-ok))
7290 (org-at-heading-p))))
7291 (or force-heading (not (org-in-item-p)))))
7292 (progn
7293 (insert "\n* ")
7294 (run-hooks 'org-insert-heading-hook))
7295 (when (or force-heading (not (org-insert-item)))
7296 (let* ((empty-line-p nil)
7297 (level nil)
7298 (on-heading (org-at-heading-p))
7299 (head (save-excursion
7300 (condition-case nil
7301 (progn
7302 (org-back-to-heading invisible-ok)
7303 (when (and (not on-heading)
7304 (featurep 'org-inlinetask)
7305 (integerp org-inlinetask-min-level)
7306 (>= (length (match-string 0))
7307 org-inlinetask-min-level))
7308 ;; Find a heading level before the inline task
7309 (while (and (setq level (org-up-heading-safe))
7310 (>= level org-inlinetask-min-level)))
7311 (if (org-at-heading-p)
7312 (org-back-to-heading invisible-ok)
7313 (error "This should not happen")))
7314 (setq empty-line-p (org-previous-line-empty-p))
7315 (match-string 0))
7316 (error "*"))))
7317 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7318 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7319 pos hide-previous previous-pos)
7320 (cond
7321 ((and (org-at-heading-p) (bolp)
7322 (or (bobp)
7323 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7324 ;; insert before the current line
7325 (open-line (if blank 2 1)))
7326 ((and (bolp)
7327 (not org-insert-heading-respect-content)
7328 (or (bobp)
7329 (save-excursion
7330 (backward-char 1) (not (outline-invisible-p)))))
7331 ;; insert right here
7332 nil)
7334 ;; somewhere in the line
7335 (save-excursion
7336 (setq previous-pos (point-at-bol))
7337 (end-of-line)
7338 (setq hide-previous (outline-invisible-p)))
7339 (and org-insert-heading-respect-content (org-show-subtree))
7340 (let ((split
7341 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7342 (save-excursion
7343 (let ((p (point)))
7344 (goto-char (point-at-bol))
7345 (and (looking-at org-complex-heading-regexp)
7346 (match-beginning 4)
7347 (> p (match-beginning 4)))))))
7348 tags pos)
7349 (cond
7350 (org-insert-heading-respect-content
7351 (if (not (equal force-heading '(16)))
7352 (org-end-of-subtree nil t)
7353 (org-up-heading-safe)
7354 (org-end-of-subtree nil t))
7355 (when (featurep 'org-inlinetask)
7356 (while (and (not (eobp))
7357 (looking-at "\\(\\*+\\)[ \t]+")
7358 (>= (length (match-string 1))
7359 org-inlinetask-min-level))
7360 (org-end-of-subtree nil t)))
7361 (or (bolp) (newline))
7362 (or (org-previous-line-empty-p)
7363 (and blank (newline)))
7364 (open-line 1))
7365 ((org-at-heading-p)
7366 (when hide-previous
7367 (show-children)
7368 (org-show-entry))
7369 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7370 (setq tags (and (match-end 2) (match-string 2)))
7371 (and (match-end 1)
7372 (delete-region (match-beginning 1) (match-end 1)))
7373 (setq pos (point-at-bol))
7374 (or split (end-of-line 1))
7375 (delete-horizontal-space)
7376 (if (string-match "\\`\\*+\\'"
7377 (buffer-substring (point-at-bol) (point)))
7378 (insert " "))
7379 (newline (if blank 2 1))
7380 (when tags
7381 (save-excursion
7382 (goto-char pos)
7383 (end-of-line 1)
7384 (insert " " tags)
7385 (org-set-tags nil 'align))))
7387 (or split (end-of-line 1))
7388 (newline (if blank 2 1)))))))
7389 (insert head) (just-one-space)
7390 (setq pos (point))
7391 (end-of-line 1)
7392 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7393 (when (and org-insert-heading-respect-content hide-previous)
7394 (save-excursion
7395 (goto-char previous-pos)
7396 (hide-subtree)))
7397 (run-hooks 'org-insert-heading-hook)))))
7399 (defun org-get-heading (&optional no-tags no-todo)
7400 "Return the heading of the current entry, without the stars.
7401 When NO-TAGS is non-nil, don't include tags.
7402 When NO-TODO is non-nil, don't include TODO keywords."
7403 (save-excursion
7404 (org-back-to-heading t)
7405 (cond
7406 ((and no-tags no-todo)
7407 (looking-at org-complex-heading-regexp)
7408 (match-string 4))
7409 (no-tags
7410 (looking-at (concat org-outline-regexp
7411 "\\(.*?\\)"
7412 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7413 (match-string 1))
7414 (no-todo
7415 (looking-at org-todo-line-regexp)
7416 (match-string 3))
7417 (t (looking-at org-heading-regexp)
7418 (match-string 2)))))
7420 (defvar orgstruct-mode) ; defined below
7422 (defun org-heading-components ()
7423 "Return the components of the current heading.
7424 This is a list with the following elements:
7425 - the level as an integer
7426 - the reduced level, different if `org-odd-levels-only' is set.
7427 - the TODO keyword, or nil
7428 - the priority character, like ?A, or nil if no priority is given
7429 - the headline text itself, or the tags string if no headline text
7430 - the tags string, or nil."
7431 (save-excursion
7432 (org-back-to-heading t)
7433 (if (let (case-fold-search)
7434 (looking-at
7435 (if orgstruct-mode
7436 org-heading-regexp
7437 org-complex-heading-regexp)))
7438 (if orgstruct-mode
7439 (list (length (match-string 1))
7440 (org-reduced-level (length (match-string 1)))
7443 (match-string 2)
7444 nil)
7445 (list (length (match-string 1))
7446 (org-reduced-level (length (match-string 1)))
7447 (org-match-string-no-properties 2)
7448 (and (match-end 3) (aref (match-string 3) 2))
7449 (org-match-string-no-properties 4)
7450 (org-match-string-no-properties 5))))))
7452 (defun org-get-entry ()
7453 "Get the entry text, after heading, entire subtree."
7454 (save-excursion
7455 (org-back-to-heading t)
7456 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7458 (defun org-insert-heading-after-current ()
7459 "Insert a new heading with same level as current, after current subtree."
7460 (interactive)
7461 (org-back-to-heading)
7462 (org-insert-heading)
7463 (org-move-subtree-down)
7464 (end-of-line 1))
7466 (defun org-insert-heading-respect-content (invisible-ok)
7467 "Insert heading with `org-insert-heading-respect-content' set to t."
7468 (interactive "P")
7469 (let ((org-insert-heading-respect-content t))
7470 (org-insert-heading t invisible-ok)))
7472 (defun org-insert-todo-heading-respect-content (&optional force-state)
7473 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7474 (interactive "P")
7475 (let ((org-insert-heading-respect-content t))
7476 (org-insert-todo-heading force-state t)))
7478 (defun org-insert-todo-heading (arg &optional force-heading)
7479 "Insert a new heading with the same level and TODO state as current heading.
7480 If the heading has no TODO state, or if the state is DONE, use the first
7481 state (TODO by default). Also one prefix arg, force first state. With two
7482 prefix args, force inserting at the end of the parent subtree."
7483 (interactive "P")
7484 (when (or force-heading (not (org-insert-item 'checkbox)))
7485 (org-insert-heading (or (and (equal arg '(16)) '(16))
7486 force-heading))
7487 (save-excursion
7488 (org-back-to-heading)
7489 (outline-previous-heading)
7490 (looking-at org-todo-line-regexp))
7491 (let*
7492 ((new-mark-x
7493 (if (or arg
7494 (not (match-beginning 2))
7495 (member (match-string 2) org-done-keywords))
7496 (car org-todo-keywords-1)
7497 (match-string 2)))
7498 (new-mark
7500 (run-hook-with-args-until-success
7501 'org-todo-get-default-hook new-mark-x nil)
7502 new-mark-x)))
7503 (beginning-of-line 1)
7504 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7505 (if org-treat-insert-todo-heading-as-state-change
7506 (org-todo new-mark)
7507 (insert new-mark " "))))
7508 (when org-provide-todo-statistics
7509 (org-update-parent-todo-statistics))))
7511 (defun org-insert-subheading (arg)
7512 "Insert a new subheading and demote it.
7513 Works for outline headings and for plain lists alike."
7514 (interactive "P")
7515 (org-insert-heading arg)
7516 (cond
7517 ((org-at-heading-p) (org-do-demote))
7518 ((org-at-item-p) (org-indent-item))))
7520 (defun org-insert-todo-subheading (arg)
7521 "Insert a new subheading with TODO keyword or checkbox and demote it.
7522 Works for outline headings and for plain lists alike."
7523 (interactive "P")
7524 (org-insert-todo-heading arg)
7525 (cond
7526 ((org-at-heading-p) (org-do-demote))
7527 ((org-at-item-p) (org-indent-item))))
7529 ;;; Promotion and Demotion
7531 (defvar org-after-demote-entry-hook nil
7532 "Hook run after an entry has been demoted.
7533 The cursor will be at the beginning of the entry.
7534 When a subtree is being demoted, the hook will be called for each node.")
7536 (defvar org-after-promote-entry-hook nil
7537 "Hook run after an entry has been promoted.
7538 The cursor will be at the beginning of the entry.
7539 When a subtree is being promoted, the hook will be called for each node.")
7541 (defun org-promote-subtree ()
7542 "Promote the entire subtree.
7543 See also `org-promote'."
7544 (interactive)
7545 (save-excursion
7546 (org-with-limited-levels (org-map-tree 'org-promote)))
7547 (org-fix-position-after-promote))
7549 (defun org-demote-subtree ()
7550 "Demote the entire subtree. See `org-demote'.
7551 See also `org-promote'."
7552 (interactive)
7553 (save-excursion
7554 (org-with-limited-levels (org-map-tree 'org-demote)))
7555 (org-fix-position-after-promote))
7558 (defun org-do-promote ()
7559 "Promote the current heading higher up the tree.
7560 If the region is active in `transient-mark-mode', promote all headings
7561 in the region."
7562 (interactive)
7563 (save-excursion
7564 (if (org-region-active-p)
7565 (org-map-region 'org-promote (region-beginning) (region-end))
7566 (org-promote)))
7567 (org-fix-position-after-promote))
7569 (defun org-do-demote ()
7570 "Demote the current heading lower down the tree.
7571 If the region is active in `transient-mark-mode', demote all headings
7572 in the region."
7573 (interactive)
7574 (save-excursion
7575 (if (org-region-active-p)
7576 (org-map-region 'org-demote (region-beginning) (region-end))
7577 (org-demote)))
7578 (org-fix-position-after-promote))
7580 (defun org-fix-position-after-promote ()
7581 "Make sure that after pro/demotion cursor position is right."
7582 (let ((pos (point)))
7583 (when (save-excursion
7584 (beginning-of-line 1)
7585 (looking-at org-todo-line-regexp)
7586 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7587 (cond ((eobp) (insert " "))
7588 ((eolp) (insert " "))
7589 ((equal (char-after) ?\ ) (forward-char 1))))))
7591 (defun org-current-level ()
7592 "Return the level of the current entry, or nil if before the first headline.
7593 The level is the number of stars at the beginning of the headline."
7594 (save-excursion
7595 (org-with-limited-levels
7596 (if (ignore-errors (org-back-to-heading t))
7597 (funcall outline-level)))))
7599 (defun org-get-previous-line-level ()
7600 "Return the outline depth of the last headline before the current line.
7601 Returns 0 for the first headline in the buffer, and nil if before the
7602 first headline."
7603 (let ((current-level (org-current-level))
7604 (prev-level (when (> (line-number-at-pos) 1)
7605 (save-excursion
7606 (beginning-of-line 0)
7607 (org-current-level)))))
7608 (cond ((null current-level) nil) ; Before first headline
7609 ((null prev-level) 0) ; At first headline
7610 (prev-level))))
7612 (defun org-reduced-level (l)
7613 "Compute the effective level of a heading.
7614 This takes into account the setting of `org-odd-levels-only'."
7615 (cond
7616 ((zerop l) 0)
7617 (org-odd-levels-only (1+ (floor (/ l 2))))
7618 (t l)))
7620 (defun org-level-increment ()
7621 "Return the number of stars that will be added or removed at a
7622 time to headlines when structure editing, based on the value of
7623 `org-odd-levels-only'."
7624 (if org-odd-levels-only 2 1))
7626 (defun org-get-valid-level (level &optional change)
7627 "Rectify a level change under the influence of `org-odd-levels-only'
7628 LEVEL is a current level, CHANGE is by how much the level should be
7629 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7630 even level numbers will become the next higher odd number."
7631 (if org-odd-levels-only
7632 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7633 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7634 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7635 (max 1 (+ level (or change 0)))))
7637 (if (boundp 'define-obsolete-function-alias)
7638 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7639 (define-obsolete-function-alias 'org-get-legal-level
7640 'org-get-valid-level)
7641 (define-obsolete-function-alias 'org-get-legal-level
7642 'org-get-valid-level "23.1")))
7644 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7645 ;; ̀org-with-limited-levels'
7646 (defun org-promote ()
7647 "Promote the current heading higher up the tree.
7648 If the region is active in `transient-mark-mode', promote all headings
7649 in the region."
7650 (org-back-to-heading t)
7651 (let* ((level (save-match-data (funcall outline-level)))
7652 (after-change-functions (remove 'flyspell-after-change-function
7653 after-change-functions))
7654 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7655 (diff (abs (- level (length up-head) -1))))
7656 (cond ((and (= level 1) org-called-with-limited-levels
7657 org-allow-promoting-top-level-subtree)
7658 (replace-match "# " nil t))
7659 ((= level 1)
7660 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7661 (t (replace-match up-head nil t)))
7662 ;; Fixup tag positioning
7663 (unless (= level 1)
7664 (and org-auto-align-tags (org-set-tags nil t))
7665 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7666 (run-hooks 'org-after-promote-entry-hook)))
7668 (defun org-demote ()
7669 "Demote the current heading lower down the tree.
7670 If the region is active in `transient-mark-mode', demote all headings
7671 in the region."
7672 (org-back-to-heading t)
7673 (let* ((level (save-match-data (funcall outline-level)))
7674 (after-change-functions (remove 'flyspell-after-change-function
7675 after-change-functions))
7676 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7677 (diff (abs (- level (length down-head) -1))))
7678 (replace-match down-head nil t)
7679 ;; Fixup tag positioning
7680 (and org-auto-align-tags (org-set-tags nil t))
7681 (if org-adapt-indentation (org-fixup-indentation diff))
7682 (run-hooks 'org-after-demote-entry-hook)))
7684 (defun org-cycle-level ()
7685 "Cycle the level of an empty headline through possible states.
7686 This goes first to child, then to parent, level, then up the hierarchy.
7687 After top level, it switches back to sibling level."
7688 (interactive)
7689 (let ((org-adapt-indentation nil))
7690 (when (org-point-at-end-of-empty-headline)
7691 (setq this-command 'org-cycle-level) ; Only needed for caching
7692 (let ((cur-level (org-current-level))
7693 (prev-level (org-get-previous-line-level)))
7694 (cond
7695 ;; If first headline in file, promote to top-level.
7696 ((= prev-level 0)
7697 (loop repeat (/ (- cur-level 1) (org-level-increment))
7698 do (org-do-promote)))
7699 ;; If same level as prev, demote one.
7700 ((= prev-level cur-level)
7701 (org-do-demote))
7702 ;; If parent is top-level, promote to top level if not already.
7703 ((= prev-level 1)
7704 (loop repeat (/ (- cur-level 1) (org-level-increment))
7705 do (org-do-promote)))
7706 ;; If top-level, return to prev-level.
7707 ((= cur-level 1)
7708 (loop repeat (/ (- prev-level 1) (org-level-increment))
7709 do (org-do-demote)))
7710 ;; If less than prev-level, promote one.
7711 ((< cur-level prev-level)
7712 (org-do-promote))
7713 ;; If deeper than prev-level, promote until higher than
7714 ;; prev-level.
7715 ((> cur-level prev-level)
7716 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7717 do (org-do-promote))))
7718 t))))
7720 (defun org-map-tree (fun)
7721 "Call FUN for every heading underneath the current one."
7722 (org-back-to-heading)
7723 (let ((level (funcall outline-level)))
7724 (save-excursion
7725 (funcall fun)
7726 (while (and (progn
7727 (outline-next-heading)
7728 (> (funcall outline-level) level))
7729 (not (eobp)))
7730 (funcall fun)))))
7732 (defun org-map-region (fun beg end)
7733 "Call FUN for every heading between BEG and END."
7734 (let ((org-ignore-region t))
7735 (save-excursion
7736 (setq end (copy-marker end))
7737 (goto-char beg)
7738 (if (and (re-search-forward org-outline-regexp-bol nil t)
7739 (< (point) end))
7740 (funcall fun))
7741 (while (and (progn
7742 (outline-next-heading)
7743 (< (point) end))
7744 (not (eobp)))
7745 (funcall fun)))))
7747 (defvar org-property-end-re) ; silence byte-compiler
7748 (defun org-fixup-indentation (diff)
7749 "Change the indentation in the current entry by DIFF.
7750 However, if any line in the current entry has no indentation, or if it
7751 would end up with no indentation after the change, nothing at all is done."
7752 (save-excursion
7753 (let ((end (save-excursion (outline-next-heading)
7754 (point-marker)))
7755 (prohibit (if (> diff 0)
7756 "^\\S-"
7757 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7758 col)
7759 (unless (save-excursion (end-of-line 1)
7760 (re-search-forward prohibit end t))
7761 (while (and (< (point) end)
7762 (re-search-forward "^[ \t]+" end t))
7763 (goto-char (match-end 0))
7764 (setq col (current-column))
7765 (if (< diff 0) (replace-match ""))
7766 (org-indent-to-column (+ diff col))))
7767 (move-marker end nil))))
7769 (defun org-convert-to-odd-levels ()
7770 "Convert an org-mode file with all levels allowed to one with odd levels.
7771 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7772 level 5 etc."
7773 (interactive)
7774 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7775 (let ((outline-level 'org-outline-level)
7776 (org-odd-levels-only nil) n)
7777 (save-excursion
7778 (goto-char (point-min))
7779 (while (re-search-forward "^\\*\\*+ " nil t)
7780 (setq n (- (length (match-string 0)) 2))
7781 (while (>= (setq n (1- n)) 0)
7782 (org-demote))
7783 (end-of-line 1))))))
7785 (defun org-convert-to-oddeven-levels ()
7786 "Convert an org-mode file with only odd levels to one with odd/even levels.
7787 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7788 file contains a section with an even level, conversion would
7789 destroy the structure of the file. An error is signaled in this
7790 case."
7791 (interactive)
7792 (goto-char (point-min))
7793 ;; First check if there are no even levels
7794 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7795 (org-show-context t)
7796 (error "Not all levels are odd in this file. Conversion not possible"))
7797 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7798 (let ((outline-regexp org-outline-regexp)
7799 (outline-level 'org-outline-level)
7800 (org-odd-levels-only nil) n)
7801 (save-excursion
7802 (goto-char (point-min))
7803 (while (re-search-forward "^\\*\\*+ " nil t)
7804 (setq n (/ (1- (length (match-string 0))) 2))
7805 (while (>= (setq n (1- n)) 0)
7806 (org-promote))
7807 (end-of-line 1))))))
7809 (defun org-tr-level (n)
7810 "Make N odd if required."
7811 (if org-odd-levels-only (1+ (/ n 2)) n))
7813 ;;; Vertical tree motion, cutting and pasting of subtrees
7815 (defun org-move-subtree-up (&optional arg)
7816 "Move the current subtree up past ARG headlines of the same level."
7817 (interactive "p")
7818 (org-move-subtree-down (- (prefix-numeric-value arg))))
7820 (defun org-move-subtree-down (&optional arg)
7821 "Move the current subtree down past ARG headlines of the same level."
7822 (interactive "p")
7823 (setq arg (prefix-numeric-value arg))
7824 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7825 'org-get-last-sibling))
7826 (ins-point (make-marker))
7827 (cnt (abs arg))
7828 (col (current-column))
7829 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7830 ;; Select the tree
7831 (org-back-to-heading)
7832 (setq beg0 (point))
7833 (save-excursion
7834 (setq ne-beg (org-back-over-empty-lines))
7835 (setq beg (point)))
7836 (save-match-data
7837 (save-excursion (outline-end-of-heading)
7838 (setq folded (outline-invisible-p)))
7839 (outline-end-of-subtree))
7840 (outline-next-heading)
7841 (setq ne-end (org-back-over-empty-lines))
7842 (setq end (point))
7843 (goto-char beg0)
7844 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7845 ;; include less whitespace
7846 (save-excursion
7847 (goto-char beg)
7848 (forward-line (- ne-beg ne-end))
7849 (setq beg (point))))
7850 ;; Find insertion point, with error handling
7851 (while (> cnt 0)
7852 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7853 (progn (goto-char beg0)
7854 (error "Cannot move past superior level or buffer limit")))
7855 (setq cnt (1- cnt)))
7856 (if (> arg 0)
7857 ;; Moving forward - still need to move over subtree
7858 (progn (org-end-of-subtree t t)
7859 (save-excursion
7860 (org-back-over-empty-lines)
7861 (or (bolp) (newline)))))
7862 (setq ne-ins (org-back-over-empty-lines))
7863 (move-marker ins-point (point))
7864 (setq txt (buffer-substring beg end))
7865 (org-save-markers-in-region beg end)
7866 (delete-region beg end)
7867 (org-remove-empty-overlays-at beg)
7868 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7869 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7870 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7871 (let ((bbb (point)))
7872 (insert-before-markers txt)
7873 (org-reinstall-markers-in-region bbb)
7874 (move-marker ins-point bbb))
7875 (or (bolp) (insert "\n"))
7876 (setq ins-end (point))
7877 (goto-char ins-point)
7878 (org-skip-whitespace)
7879 (when (and (< arg 0)
7880 (org-first-sibling-p)
7881 (> ne-ins ne-beg))
7882 ;; Move whitespace back to beginning
7883 (save-excursion
7884 (goto-char ins-end)
7885 (let ((kill-whole-line t))
7886 (kill-line (- ne-ins ne-beg)) (point)))
7887 (insert (make-string (- ne-ins ne-beg) ?\n)))
7888 (move-marker ins-point nil)
7889 (if folded
7890 (hide-subtree)
7891 (org-show-entry)
7892 (show-children)
7893 (org-cycle-hide-drawers 'children))
7894 (org-clean-visibility-after-subtree-move)
7895 ;; move back to the initial column we were at
7896 (move-to-column col)))
7898 (defvar org-subtree-clip ""
7899 "Clipboard for cut and paste of subtrees.
7900 This is actually only a copy of the kill, because we use the normal kill
7901 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7903 (defvar org-subtree-clip-folded nil
7904 "Was the last copied subtree folded?
7905 This is used to fold the tree back after pasting.")
7907 (defun org-cut-subtree (&optional n)
7908 "Cut the current subtree into the clipboard.
7909 With prefix arg N, cut this many sequential subtrees.
7910 This is a short-hand for marking the subtree and then cutting it."
7911 (interactive "p")
7912 (org-copy-subtree n 'cut))
7914 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7915 "Cut the current subtree into the clipboard.
7916 With prefix arg N, cut this many sequential subtrees.
7917 This is a short-hand for marking the subtree and then copying it.
7918 If CUT is non-nil, actually cut the subtree.
7919 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7920 of some markers in the region, even if CUT is non-nil. This is
7921 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7922 (interactive "p")
7923 (let (beg end folded (beg0 (point)))
7924 (if (org-called-interactively-p 'any)
7925 (org-back-to-heading nil) ; take what looks like a subtree
7926 (org-back-to-heading t)) ; take what is really there
7927 (setq beg (point))
7928 (skip-chars-forward " \t\r\n")
7929 (save-match-data
7930 (if nosubtrees
7931 (outline-next-heading)
7932 (save-excursion (outline-end-of-heading)
7933 (setq folded (outline-invisible-p)))
7934 (condition-case nil
7935 (org-forward-heading-same-level (1- n) t)
7936 (error nil))
7937 (org-end-of-subtree t t)))
7938 (setq end (point))
7939 (goto-char beg0)
7940 (when (> end beg)
7941 (setq org-subtree-clip-folded folded)
7942 (when (or cut force-store-markers)
7943 (org-save-markers-in-region beg end))
7944 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7945 (setq org-subtree-clip (current-kill 0))
7946 (message "%s: Subtree(s) with %d characters"
7947 (if cut "Cut" "Copied")
7948 (length org-subtree-clip)))))
7950 (defun org-paste-subtree (&optional level tree for-yank)
7951 "Paste the clipboard as a subtree, with modification of headline level.
7952 The entire subtree is promoted or demoted in order to match a new headline
7953 level.
7955 If the cursor is at the beginning of a headline, the same level as
7956 that headline is used to paste the tree.
7958 If not, the new level is derived from the *visible* headings
7959 before and after the insertion point, and taken to be the inferior headline
7960 level of the two. So if the previous visible heading is level 3 and the
7961 next is level 4 (or vice versa), level 4 will be used for insertion.
7962 This makes sure that the subtree remains an independent subtree and does
7963 not swallow low level entries.
7965 You can also force a different level, either by using a numeric prefix
7966 argument, or by inserting the heading marker by hand. For example, if the
7967 cursor is after \"*****\", then the tree will be shifted to level 5.
7969 If optional TREE is given, use this text instead of the kill ring.
7971 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7972 move back over whitespace before inserting, and move point to the end of
7973 the inserted text when done."
7974 (interactive "P")
7975 (setq tree (or tree (and kill-ring (current-kill 0))))
7976 (unless (org-kill-is-subtree-p tree)
7977 (error "%s"
7978 (substitute-command-keys
7979 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7980 (org-with-limited-levels
7981 (let* ((visp (not (outline-invisible-p)))
7982 (txt tree)
7983 (^re_ "\\(\\*+\\)[ \t]*")
7984 (old-level (if (string-match org-outline-regexp-bol txt)
7985 (- (match-end 0) (match-beginning 0) 1)
7986 -1))
7987 (force-level (cond (level (prefix-numeric-value level))
7988 ((and (looking-at "[ \t]*$")
7989 (string-match
7990 "^\\*+$" (buffer-substring
7991 (point-at-bol) (point))))
7992 (- (match-end 1) (match-beginning 1)))
7993 ((and (bolp)
7994 (looking-at org-outline-regexp))
7995 (- (match-end 0) (point) 1))))
7996 (previous-level (save-excursion
7997 (condition-case nil
7998 (progn
7999 (outline-previous-visible-heading 1)
8000 (if (looking-at ^re_)
8001 (- (match-end 0) (match-beginning 0) 1)
8003 (error 1))))
8004 (next-level (save-excursion
8005 (condition-case nil
8006 (progn
8007 (or (looking-at org-outline-regexp)
8008 (outline-next-visible-heading 1))
8009 (if (looking-at ^re_)
8010 (- (match-end 0) (match-beginning 0) 1)
8012 (error 1))))
8013 (new-level (or force-level (max previous-level next-level)))
8014 (shift (if (or (= old-level -1)
8015 (= new-level -1)
8016 (= old-level new-level))
8018 (- new-level old-level)))
8019 (delta (if (> shift 0) -1 1))
8020 (func (if (> shift 0) 'org-demote 'org-promote))
8021 (org-odd-levels-only nil)
8022 beg end newend)
8023 ;; Remove the forced level indicator
8024 (if force-level
8025 (delete-region (point-at-bol) (point)))
8026 ;; Paste
8027 (beginning-of-line (if (bolp) 1 2))
8028 (setq beg (point))
8029 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8030 (insert-before-markers txt)
8031 (unless (string-match "\n\\'" txt) (insert "\n"))
8032 (setq newend (point))
8033 (org-reinstall-markers-in-region beg)
8034 (setq end (point))
8035 (goto-char beg)
8036 (skip-chars-forward " \t\n\r")
8037 (setq beg (point))
8038 (if (and (outline-invisible-p) visp)
8039 (save-excursion (outline-show-heading)))
8040 ;; Shift if necessary
8041 (unless (= shift 0)
8042 (save-restriction
8043 (narrow-to-region beg end)
8044 (while (not (= shift 0))
8045 (org-map-region func (point-min) (point-max))
8046 (setq shift (+ delta shift)))
8047 (goto-char (point-min))
8048 (setq newend (point-max))))
8049 (when (or (org-called-interactively-p 'interactive) for-yank)
8050 (message "Clipboard pasted as level %d subtree" new-level))
8051 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8052 kill-ring
8053 (eq org-subtree-clip (current-kill 0))
8054 org-subtree-clip-folded)
8055 ;; The tree was folded before it was killed/copied
8056 (hide-subtree))
8057 (and for-yank (goto-char newend)))))
8059 (defun org-kill-is-subtree-p (&optional txt)
8060 "Check if the current kill is an outline subtree, or a set of trees.
8061 Returns nil if kill does not start with a headline, or if the first
8062 headline level is not the largest headline level in the tree.
8063 So this will actually accept several entries of equal levels as well,
8064 which is OK for `org-paste-subtree'.
8065 If optional TXT is given, check this string instead of the current kill."
8066 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8067 (re (org-get-limited-outline-regexp))
8068 (^re (concat "^" re))
8069 (start-level (and kill
8070 (string-match
8071 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8072 kill)
8073 (- (match-end 2) (match-beginning 2) 1)))
8074 (start (1+ (or (match-beginning 2) -1))))
8075 (if (not start-level)
8076 (progn
8077 nil) ;; does not even start with a heading
8078 (catch 'exit
8079 (while (setq start (string-match ^re kill (1+ start)))
8080 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8081 (throw 'exit nil)))
8082 t))))
8084 (defvar org-markers-to-move nil
8085 "Markers that should be moved with a cut-and-paste operation.
8086 Those markers are stored together with their positions relative to
8087 the start of the region.")
8089 (defun org-save-markers-in-region (beg end)
8090 "Check markers in region.
8091 If these markers are between BEG and END, record their position relative
8092 to BEG, so that after moving the block of text, we can put the markers back
8093 into place.
8094 This function gets called just before an entry or tree gets cut from the
8095 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8096 called immediately, to move the markers with the entries."
8097 (setq org-markers-to-move nil)
8098 (when (featurep 'org-clock)
8099 (org-clock-save-markers-for-cut-and-paste beg end))
8100 (when (featurep 'org-agenda)
8101 (org-agenda-save-markers-for-cut-and-paste beg end)))
8103 (defun org-check-and-save-marker (marker beg end)
8104 "Check if MARKER is between BEG and END.
8105 If yes, remember the marker and the distance to BEG."
8106 (when (and (marker-buffer marker)
8107 (equal (marker-buffer marker) (current-buffer)))
8108 (if (and (>= marker beg) (< marker end))
8109 (push (cons marker (- marker beg)) org-markers-to-move))))
8111 (defun org-reinstall-markers-in-region (beg)
8112 "Move all remembered markers to their position relative to BEG."
8113 (mapc (lambda (x)
8114 (move-marker (car x) (+ beg (cdr x))))
8115 org-markers-to-move)
8116 (setq org-markers-to-move nil))
8118 (defun org-narrow-to-subtree ()
8119 "Narrow buffer to the current subtree."
8120 (interactive)
8121 (save-excursion
8122 (save-match-data
8123 (org-with-limited-levels
8124 (narrow-to-region
8125 (progn (org-back-to-heading t) (point))
8126 (progn (org-end-of-subtree t t)
8127 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8128 (point)))))))
8130 (defun org-narrow-to-block ()
8131 "Narrow buffer to the current block."
8132 (interactive)
8133 (let* ((case-fold-search t)
8134 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8135 "^[ \t]*#\\+end_.*")))
8136 (if blockp
8137 (narrow-to-region (car blockp) (cdr blockp))
8138 (error "Not in a block"))))
8140 (eval-when-compile
8141 (defvar org-property-drawer-re))
8143 (defvar org-property-start-re) ;; defined below
8144 (defun org-clone-subtree-with-time-shift (n &optional shift)
8145 "Clone the task (subtree) at point N times.
8146 The clones will be inserted as siblings.
8148 In interactive use, the user will be prompted for the number of
8149 clones to be produced, and for a time SHIFT, which may be a
8150 repeater as used in time stamps, for example `+3d'.
8152 When a valid repeater is given and the entry contains any time
8153 stamps, the clones will become a sequence in time, with time
8154 stamps in the subtree shifted for each clone produced. If SHIFT
8155 is nil or the empty string, time stamps will be left alone. The
8156 ID property of the original subtree is removed.
8158 If the original subtree did contain time stamps with a repeater,
8159 the following will happen:
8160 - the repeater will be removed in each clone
8161 - an additional clone will be produced, with the current, unshifted
8162 date(s) in the entry.
8163 - the original entry will be placed *after* all the clones, with
8164 repeater intact.
8165 - the start days in the repeater in the original entry will be shifted
8166 to past the last clone.
8167 In this way you can spell out a number of instances of a repeating task,
8168 and still retain the repeater to cover future instances of the task."
8169 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8170 (let (beg end template task idprop
8171 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8172 (drawer-re org-drawer-regexp))
8173 (if (not (and (integerp n) (> n 0)))
8174 (error "Invalid number of replications %s" n))
8175 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8176 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8177 shift)))
8178 (error "Invalid shift specification %s" shift))
8179 (when doshift
8180 (setq shift-n (string-to-number (match-string 1 shift))
8181 shift-what (cdr (assoc (match-string 2 shift)
8182 '(("d" . day) ("w" . week)
8183 ("m" . month) ("y" . year))))))
8184 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8185 (setq nmin 1 nmax n)
8186 (org-back-to-heading t)
8187 (setq beg (point))
8188 (setq idprop (org-entry-get nil "ID"))
8189 (org-end-of-subtree t t)
8190 (or (bolp) (insert "\n"))
8191 (setq end (point))
8192 (setq template (buffer-substring beg end))
8193 (when (and doshift
8194 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8195 (delete-region beg end)
8196 (setq end beg)
8197 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8198 (goto-char end)
8199 (loop for n from nmin to nmax do
8200 ;; prepare clone
8201 (with-temp-buffer
8202 (insert template)
8203 (org-mode)
8204 (goto-char (point-min))
8205 (org-show-subtree)
8206 (and idprop (if org-clone-delete-id
8207 (org-entry-delete nil "ID")
8208 (org-id-get-create t)))
8209 (unless (= n 0)
8210 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8211 (kill-whole-line))
8212 (goto-char (point-min))
8213 (while (re-search-forward drawer-re nil t)
8214 (mapc (lambda (d)
8215 (org-remove-empty-drawer-at d (point))) org-drawers)))
8216 (goto-char (point-min))
8217 (when doshift
8218 (while (re-search-forward org-ts-regexp-both nil t)
8219 (org-timestamp-change (* n shift-n) shift-what))
8220 (unless (= n n-no-remove)
8221 (goto-char (point-min))
8222 (while (re-search-forward org-ts-regexp nil t)
8223 (save-excursion
8224 (goto-char (match-beginning 0))
8225 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8226 (delete-region (match-beginning 1) (match-end 1)))))))
8227 (setq task (buffer-string)))
8228 (insert task))
8229 (goto-char beg)))
8231 ;;; Outline Sorting
8233 (defun org-sort (with-case)
8234 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8235 Optional argument WITH-CASE means sort case-sensitively."
8236 (interactive "P")
8237 (cond
8238 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8239 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8241 (org-call-with-arg 'org-sort-entries with-case))))
8243 (defun org-sort-remove-invisible (s)
8244 (remove-text-properties 0 (length s) org-rm-props s)
8245 (while (string-match org-bracket-link-regexp s)
8246 (setq s (replace-match (if (match-end 2)
8247 (match-string 3 s)
8248 (match-string 1 s)) t t s)))
8251 (defvar org-priority-regexp) ; defined later in the file
8253 (defvar org-after-sorting-entries-or-items-hook nil
8254 "Hook that is run after a bunch of entries or items have been sorted.
8255 When children are sorted, the cursor is in the parent line when this
8256 hook gets called. When a region or a plain list is sorted, the cursor
8257 will be in the first entry of the sorted region/list.")
8259 (defun org-sort-entries
8260 (&optional with-case sorting-type getkey-func compare-func property)
8261 "Sort entries on a certain level of an outline tree.
8262 If there is an active region, the entries in the region are sorted.
8263 Else, if the cursor is before the first entry, sort the top-level items.
8264 Else, the children of the entry at point are sorted.
8266 Sorting can be alphabetically, numerically, by date/time as given by
8267 a time stamp, by a property or by priority.
8269 The command prompts for the sorting type unless it has been given to the
8270 function through the SORTING-TYPE argument, which needs to be a character,
8271 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8272 precise meaning of each character:
8274 n Numerically, by converting the beginning of the entry/item to a number.
8275 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8276 o By order of TODO keywords.
8277 t By date/time, either the first active time stamp in the entry, or, if
8278 none exist, by the first inactive one.
8279 s By the scheduled date/time.
8280 d By deadline date/time.
8281 c By creation time, which is assumed to be the first inactive time stamp
8282 at the beginning of a line.
8283 p By priority according to the cookie.
8284 r By the value of a property.
8286 Capital letters will reverse the sort order.
8288 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8289 called with point at the beginning of the record. It must return either
8290 a string or a number that should serve as the sorting key for that record.
8292 Comparing entries ignores case by default. However, with an optional argument
8293 WITH-CASE, the sorting considers case as well."
8294 (interactive "P")
8295 (let ((case-func (if with-case 'identity 'downcase))
8296 (cmstr
8297 ;; The clock marker is lost when using `sort-subr', let's
8298 ;; store the clocking string.
8299 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8300 (save-excursion
8301 (goto-char org-clock-marker)
8302 (looking-back "^.*") (match-string-no-properties 0))))
8303 start beg end stars re re2
8304 txt what tmp)
8305 ;; Find beginning and end of region to sort
8306 (cond
8307 ((org-region-active-p)
8308 ;; we will sort the region
8309 (setq end (region-end)
8310 what "region")
8311 (goto-char (region-beginning))
8312 (if (not (org-at-heading-p)) (outline-next-heading))
8313 (setq start (point)))
8314 ((or (org-at-heading-p)
8315 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8316 ;; we will sort the children of the current headline
8317 (org-back-to-heading)
8318 (setq start (point)
8319 end (progn (org-end-of-subtree t t)
8320 (or (bolp) (insert "\n"))
8321 (org-back-over-empty-lines)
8322 (point))
8323 what "children")
8324 (goto-char start)
8325 (show-subtree)
8326 (outline-next-heading))
8328 ;; we will sort the top-level entries in this file
8329 (goto-char (point-min))
8330 (or (org-at-heading-p) (outline-next-heading))
8331 (setq start (point))
8332 (goto-char (point-max))
8333 (beginning-of-line 1)
8334 (when (looking-at ".*?\\S-")
8335 ;; File ends in a non-white line
8336 (end-of-line 1)
8337 (insert "\n"))
8338 (setq end (point-max))
8339 (setq what "top-level")
8340 (goto-char start)
8341 (show-all)))
8343 (setq beg (point))
8344 (if (>= beg end) (error "Nothing to sort"))
8346 (looking-at "\\(\\*+\\)")
8347 (setq stars (match-string 1)
8348 re (concat "^" (regexp-quote stars) " +")
8349 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8350 txt (buffer-substring beg end))
8351 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8352 (if (and (not (equal stars "*")) (string-match re2 txt))
8353 (error "Region to sort contains a level above the first entry"))
8355 (unless sorting-type
8356 (message
8357 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8358 [t]ime [s]cheduled [d]eadline [c]reated
8359 A/N/P/R/O/F/T/S/D/C means reversed:"
8360 what)
8361 (setq sorting-type (read-char-exclusive))
8363 (unless getkey-func
8364 (and (= (downcase sorting-type) ?f)
8365 (setq getkey-func
8366 (org-icompleting-read "Sort using function: "
8367 obarray 'fboundp t nil nil))
8368 (setq getkey-func (intern getkey-func))))
8370 (and (= (downcase sorting-type) ?r)
8371 (not property)
8372 (setq property
8373 (org-icompleting-read "Property: "
8374 (mapcar 'list (org-buffer-property-keys t))
8375 nil t))))
8377 (message "Sorting entries...")
8379 (save-restriction
8380 (narrow-to-region start end)
8381 (let ((dcst (downcase sorting-type))
8382 (case-fold-search nil)
8383 (now (current-time)))
8384 (sort-subr
8385 (/= dcst sorting-type)
8386 ;; This function moves to the beginning character of the "record" to
8387 ;; be sorted.
8388 (lambda nil
8389 (if (re-search-forward re nil t)
8390 (goto-char (match-beginning 0))
8391 (goto-char (point-max))))
8392 ;; This function moves to the last character of the "record" being
8393 ;; sorted.
8394 (lambda nil
8395 (save-match-data
8396 (condition-case nil
8397 (outline-forward-same-level 1)
8398 (error
8399 (goto-char (point-max))))))
8400 ;; This function returns the value that gets sorted against.
8401 (lambda nil
8402 (cond
8403 ((= dcst ?n)
8404 (if (looking-at org-complex-heading-regexp)
8405 (string-to-number (match-string 4))
8406 nil))
8407 ((= dcst ?a)
8408 (if (looking-at org-complex-heading-regexp)
8409 (funcall case-func (match-string 4))
8410 nil))
8411 ((= dcst ?t)
8412 (let ((end (save-excursion (outline-next-heading) (point))))
8413 (if (or (re-search-forward org-ts-regexp end t)
8414 (re-search-forward org-ts-regexp-both end t))
8415 (org-time-string-to-seconds (match-string 0))
8416 (org-float-time now))))
8417 ((= dcst ?c)
8418 (let ((end (save-excursion (outline-next-heading) (point))))
8419 (if (re-search-forward
8420 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8421 end t)
8422 (org-time-string-to-seconds (match-string 0))
8423 (org-float-time now))))
8424 ((= dcst ?s)
8425 (let ((end (save-excursion (outline-next-heading) (point))))
8426 (if (re-search-forward org-scheduled-time-regexp end t)
8427 (org-time-string-to-seconds (match-string 1))
8428 (org-float-time now))))
8429 ((= dcst ?d)
8430 (let ((end (save-excursion (outline-next-heading) (point))))
8431 (if (re-search-forward org-deadline-time-regexp end t)
8432 (org-time-string-to-seconds (match-string 1))
8433 (org-float-time now))))
8434 ((= dcst ?p)
8435 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8436 (string-to-char (match-string 2))
8437 org-default-priority))
8438 ((= dcst ?r)
8439 (or (org-entry-get nil property) ""))
8440 ((= dcst ?o)
8441 (if (looking-at org-complex-heading-regexp)
8442 (- 9999 (length (member (match-string 2)
8443 org-todo-keywords-1)))))
8444 ((= dcst ?f)
8445 (if getkey-func
8446 (progn
8447 (setq tmp (funcall getkey-func))
8448 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8449 tmp)
8450 (error "Invalid key function `%s'" getkey-func)))
8451 (t (error "Invalid sorting type `%c'" sorting-type))))
8453 (cond
8454 ((= dcst ?a) 'string<)
8455 ((= dcst ?f) compare-func)
8456 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8457 (run-hooks 'org-after-sorting-entries-or-items-hook)
8458 ;; Reset the clock marker if needed
8459 (when cmstr
8460 (save-excursion
8461 (goto-char start)
8462 (search-forward cmstr nil t)
8463 (move-marker org-clock-marker (point))))
8464 (message "Sorting entries...done")))
8466 (defun org-do-sort (table what &optional with-case sorting-type)
8467 "Sort TABLE of WHAT according to SORTING-TYPE.
8468 The user will be prompted for the SORTING-TYPE if the call to this
8469 function does not specify it. WHAT is only for the prompt, to indicate
8470 what is being sorted. The sorting key will be extracted from
8471 the car of the elements of the table.
8472 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8473 (unless sorting-type
8474 (message
8475 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8476 what)
8477 (setq sorting-type (read-char-exclusive)))
8478 (let ((dcst (downcase sorting-type))
8479 extractfun comparefun)
8480 ;; Define the appropriate functions
8481 (cond
8482 ((= dcst ?n)
8483 (setq extractfun 'string-to-number
8484 comparefun (if (= dcst sorting-type) '< '>)))
8485 ((= dcst ?a)
8486 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8487 (lambda(x) (downcase (org-sort-remove-invisible x))))
8488 comparefun (if (= dcst sorting-type)
8489 'string<
8490 (lambda (a b) (and (not (string< a b))
8491 (not (string= a b)))))))
8492 ((= dcst ?t)
8493 (setq extractfun
8494 (lambda (x)
8495 (if (or (string-match org-ts-regexp x)
8496 (string-match org-ts-regexp-both x))
8497 (org-float-time
8498 (org-time-string-to-time (match-string 0 x)))
8500 comparefun (if (= dcst sorting-type) '< '>)))
8501 (t (error "Invalid sorting type `%c'" sorting-type)))
8503 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8504 table)
8505 (lambda (a b) (funcall comparefun (car a) (car b))))))
8508 ;;; The orgstruct minor mode
8510 ;; Define a minor mode which can be used in other modes in order to
8511 ;; integrate the org-mode structure editing commands.
8513 ;; This is really a hack, because the org-mode structure commands use
8514 ;; keys which normally belong to the major mode. Here is how it
8515 ;; works: The minor mode defines all the keys necessary to operate the
8516 ;; structure commands, but wraps the commands into a function which
8517 ;; tests if the cursor is currently at a headline or a plain list
8518 ;; item. If that is the case, the structure command is used,
8519 ;; temporarily setting many Org-mode variables like regular
8520 ;; expressions for filling etc. However, when any of those keys is
8521 ;; used at a different location, function uses `key-binding' to look
8522 ;; up if the key has an associated command in another currently active
8523 ;; keymap (minor modes, major mode, global), and executes that
8524 ;; command. There might be problems if any of the keys is otherwise
8525 ;; used as a prefix key.
8527 (defcustom orgstruct-heading-prefix-regexp ""
8528 "Regexp that matches the custom prefix of Org headlines in
8529 orgstruct(++)-mode."
8530 :group 'org
8531 :type 'string)
8532 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8534 (defcustom orgstruct-setup-hook nil
8535 "Hook run after orgstruct-mode-map is filled."
8536 :group 'org
8537 :type 'hook)
8539 (defvar orgstruct-initialized nil)
8541 (defvar org-local-vars nil
8542 "List of local variables, for use by `orgstruct-mode'.")
8544 ;;;###autoload
8545 (define-minor-mode orgstruct-mode
8546 "Toggle the minor mode `orgstruct-mode'.
8547 This mode is for using Org-mode structure commands in other
8548 modes. The following keys behave as if Org-mode were active, if
8549 the cursor is on a headline, or on a plain list item (both as
8550 defined by Org-mode)."
8551 nil " OrgStruct" (make-sparse-keymap)
8552 (when orgstruct-mode
8553 (org-load-modules-maybe)
8554 (unless orgstruct-initialized
8555 (orgstruct-setup)
8556 (setq orgstruct-initialized t))))
8558 ;;;###autoload
8559 (defun turn-on-orgstruct ()
8560 "Unconditionally turn on `orgstruct-mode'."
8561 (orgstruct-mode 1))
8563 (defvar org-fb-vars nil)
8564 (make-variable-buffer-local 'org-fb-vars)
8565 (defun orgstruct++-mode (&optional arg)
8566 "Toggle `orgstruct-mode', the enhanced version of it.
8567 In addition to setting orgstruct-mode, this also exports all
8568 indentation and autofilling variables from org-mode into the
8569 buffer. It will also recognize item context in multiline items."
8570 (interactive "P")
8571 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8572 (if (< arg 1)
8573 (progn (orgstruct-mode -1)
8574 (mapc (lambda(v)
8575 (org-set-local (car v)
8576 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8577 org-fb-vars))
8578 (orgstruct-mode 1)
8579 (setq org-fb-vars nil)
8580 (let (var val)
8581 (mapc
8582 (lambda (x)
8583 (when (string-match
8584 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8585 (symbol-name (car x)))
8586 (setq var (car x) val (nth 1 x))
8587 (push (list var `(quote ,(eval var))) org-fb-vars)
8588 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8589 org-local-vars)
8590 (org-set-local 'orgstruct-is-++ t))))
8592 (defvar orgstruct-is-++ nil
8593 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8594 (make-variable-buffer-local 'orgstruct-is-++)
8596 ;;;###autoload
8597 (defun turn-on-orgstruct++ ()
8598 "Unconditionally turn on `orgstruct++-mode'."
8599 (orgstruct++-mode 1))
8601 (defun orgstruct-error ()
8602 "Error when there is no default binding for a structure key."
8603 (interactive)
8604 (error "This key has no function outside structure elements"))
8606 (defun orgstruct-setup ()
8607 "Setup orgstruct keymap."
8608 (dolist (f
8609 '("org-meta"
8610 "org-shiftmeta"
8611 org-shifttab
8612 org-backward-element
8613 org-backward-heading-same-level
8614 org-ctrl-c-ret
8615 org-cycle
8616 org-forward-heading-same-level
8617 org-insert-heading
8618 org-insert-heading-respect-content
8619 org-kill-note-or-show-branches
8620 org-mark-subtree
8621 org-narrow-to-subtree
8622 org-promote-subtree
8623 org-reveal
8624 org-show-subtree
8625 org-sort
8626 org-up-element
8627 outline-demote
8628 outline-next-visible-heading
8629 outline-previous-visible-heading
8630 outline-promote
8631 outline-up-heading
8632 show-children))
8633 (dolist (f (if (stringp f)
8634 (let ((flist))
8635 (dolist (postfix
8636 '("-return" "tab" "left" "right" "up" "down")
8637 flist)
8638 (let ((f (intern (concat f postfix))))
8639 (when (fboundp f)
8640 (push f flist)))))
8641 (list f)))
8642 (dolist (binding (nconc (where-is-internal f org-mode-map)
8643 (where-is-internal f outline-mode-map)))
8644 ;; TODO use local-function-key-map
8645 (dolist (rep '(("<tab>" . "TAB")
8646 ("<ret>" . "RET")
8647 ("<esc>" . "ESC")
8648 ("<del>" . "DEL")))
8649 (setq binding (read-kbd-macro (replace-regexp-in-string
8650 (regexp-quote (car rep))
8651 (cdr rep)
8652 (key-description binding)))))
8653 (let ((key (lookup-key orgstruct-mode-map binding)))
8654 (when (or (not key) (numberp key))
8655 (condition-case nil
8656 (org-defkey orgstruct-mode-map
8657 binding
8658 (orgstruct-make-binding f binding))
8659 (error nil)))))))
8660 (run-hooks 'orgstruct-setup-hook))
8662 (defun orgstruct-make-binding (fun key)
8663 "Create a function for binding in the structure minor mode.
8664 FUN is the command to call inside a table. KEY is the key that
8665 should be checked in for a command to execute outside of tables."
8666 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8667 (let ((nname name)
8668 (i 0))
8669 (while (fboundp (intern nname))
8670 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8671 (setq name (intern nname)))
8672 (eval
8673 `(defun ,name (arg)
8674 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8675 "Outside of structure, run the binding of `"
8676 (key-description key) "'.")
8677 (interactive "p")
8678 (unless
8679 (let* ((org-heading-regexp
8680 (concat "^"
8681 orgstruct-heading-prefix-regexp
8682 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8683 (org-outline-regexp
8684 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8685 (org-outline-regexp-bol
8686 (concat "^" org-outline-regexp))
8687 (outline-regexp org-outline-regexp)
8688 (outline-heading-end-regexp "\n")
8689 (outline-level 'outline-level)
8690 (outline-heading-alist))
8691 (when (org-context-p 'headline 'item
8692 ,(when (memq fun '(org-insert-heading))
8693 '(when orgstruct-is-++
8694 'item-body)))
8695 (org-run-like-in-org-mode ',fun)
8697 (let* ((orgstruct-mode)
8698 (binding (key-binding ,key)))
8699 (if (keymapp binding)
8700 (set-temporary-overlay-map binding)
8701 (call-interactively
8702 (or binding 'orgstruct-error)))))))
8703 name))
8705 (defun org-contextualize-keys (alist contexts)
8706 "Return valid elements in ALIST depending on CONTEXTS.
8708 `org-agenda-custom-commands' or `org-capture-templates' are the
8709 values used for ALIST, and `org-agenda-custom-commands-contexts'
8710 or `org-capture-templates-contexts' are the associated contexts
8711 definitions."
8712 (let ((contexts
8713 ;; normalize contexts
8714 (mapcar
8715 (lambda(c) (cond ((listp (cadr c))
8716 (list (car c) (car c) (cadr c)))
8717 ((string= "" (cadr c))
8718 (list (car c) (car c) (caddr c)))
8719 (t c))) contexts))
8720 (a alist) c r s)
8721 ;; loop over all commands or templates
8722 (while (setq c (pop a))
8723 (let (vrules repl)
8724 (cond
8725 ((not (assoc (car c) contexts))
8726 (push c r))
8727 ((and (assoc (car c) contexts)
8728 (setq vrules (org-contextualize-validate-key
8729 (car c) contexts)))
8730 (mapc (lambda (vr)
8731 (when (not (equal (car vr) (cadr vr)))
8732 (setq repl vr))) vrules)
8733 (if (not repl) (push c r)
8734 (push (cadr repl) s)
8735 (push
8736 (cons (car c)
8737 (cdr (or (assoc (cadr repl) alist)
8738 (error "Undefined key `%s' as contextual replacement for `%s'"
8739 (cadr repl) (car c)))))
8740 r))))))
8741 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8742 (delq
8744 (delete-dups
8745 (mapcar (lambda (x)
8746 (let ((tpl (car x)))
8747 (when (not (delq
8749 (mapcar (lambda(y)
8750 (equal y tpl)) s))) x)))
8751 (reverse r))))))
8753 (defun org-contextualize-validate-key (key contexts)
8754 "Check CONTEXTS for agenda or capture KEY."
8755 (let (r rr res)
8756 (while (setq r (pop contexts))
8757 (mapc
8758 (lambda (rr)
8759 (when
8760 (and (equal key (car r))
8761 (if (functionp rr) (funcall rr)
8762 (or (and (eq (car rr) 'in-file)
8763 (buffer-file-name)
8764 (string-match (cdr rr) (buffer-file-name)))
8765 (and (eq (car rr) 'in-mode)
8766 (string-match (cdr rr) (symbol-name major-mode)))
8767 (and (eq (car rr) 'in-buffer)
8768 (string-match (cdr rr) (buffer-name)))
8769 (when (and (eq (car rr) 'not-in-file)
8770 (buffer-file-name))
8771 (not (string-match (cdr rr) (buffer-file-name))))
8772 (when (eq (car rr) 'not-in-mode)
8773 (not (string-match (cdr rr) (symbol-name major-mode))))
8774 (when (eq (car rr) 'not-in-buffer)
8775 (not (string-match (cdr rr) (buffer-name)))))))
8776 (push r res)))
8777 (car (last r))))
8778 (delete-dups (delq nil res))))
8780 (defun org-context-p (&rest contexts)
8781 "Check if local context is any of CONTEXTS.
8782 Possible values in the list of contexts are `table', `headline', and `item'."
8783 (let ((pos (point)))
8784 (goto-char (point-at-bol))
8785 (prog1 (or (and (memq 'table contexts)
8786 (looking-at "[ \t]*|"))
8787 (and (memq 'headline contexts)
8788 (looking-at org-outline-regexp))
8789 (and (memq 'item contexts)
8790 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8791 (and (memq 'item-body contexts)
8792 (org-in-item-p)))
8793 (goto-char pos))))
8795 (defun org-get-local-variables ()
8796 "Return a list of all local variables in an Org mode buffer."
8797 (let (varlist)
8798 (with-current-buffer (get-buffer-create "*Org tmp*")
8799 (erase-buffer)
8800 (org-mode)
8801 (setq varlist (buffer-local-variables)))
8802 (kill-buffer "*Org tmp*")
8803 (delq nil
8804 (mapcar
8805 (lambda (x)
8806 (setq x
8807 (if (symbolp x)
8808 (list x)
8809 (list (car x) (cdr x))))
8810 (if (and (not (get (car x) 'org-state))
8811 (string-match
8812 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8813 (symbol-name (car x))))
8814 x nil))
8815 varlist))))
8817 (defun org-clone-local-variables (from-buffer &optional regexp)
8818 "Clone local variables from FROM-BUFFER.
8819 Optional argument REGEXP selects variables to clone."
8820 (mapc
8821 (lambda (pair)
8822 (and (symbolp (car pair))
8823 (or (null regexp)
8824 (string-match regexp (symbol-name (car pair))))
8825 (set (make-local-variable (car pair))
8826 (cdr pair))))
8827 (buffer-local-variables from-buffer)))
8829 ;;;###autoload
8830 (defun org-run-like-in-org-mode (cmd)
8831 "Run a command, pretending that the current buffer is in Org-mode.
8832 This will temporarily bind local variables that are typically bound in
8833 Org-mode to the values they have in Org-mode, and then interactively
8834 call CMD."
8835 (org-load-modules-maybe)
8836 (unless org-local-vars
8837 (setq org-local-vars (org-get-local-variables)))
8838 (let (binds)
8839 (dolist (var org-local-vars)
8840 (when (or (not (boundp (car var)))
8841 (eq (symbol-value (car var))
8842 (default-value (car var))))
8843 (push (list (car var) `(quote ,(cadr var))) binds)))
8844 (eval `(let ,binds
8845 (call-interactively (quote ,cmd))))))
8847 ;;;; Archiving
8849 (defun org-get-category (&optional pos force-refresh)
8850 "Get the category applying to position POS."
8851 (save-match-data
8852 (if force-refresh (org-refresh-category-properties))
8853 (let ((pos (or pos (point))))
8854 (or (get-text-property pos 'org-category)
8855 (progn (org-refresh-category-properties)
8856 (get-text-property pos 'org-category))))))
8858 (defun org-refresh-category-properties ()
8859 "Refresh category text properties in the buffer."
8860 (let ((case-fold-search t)
8861 (inhibit-read-only t)
8862 (def-cat (cond
8863 ((null org-category)
8864 (if buffer-file-name
8865 (file-name-sans-extension
8866 (file-name-nondirectory buffer-file-name))
8867 "???"))
8868 ((symbolp org-category) (symbol-name org-category))
8869 (t org-category)))
8870 beg end cat pos optionp)
8871 (org-unmodified
8872 (save-excursion
8873 (save-restriction
8874 (widen)
8875 (goto-char (point-min))
8876 (put-text-property (point) (point-max) 'org-category def-cat)
8877 (while (re-search-forward
8878 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8879 (setq pos (match-end 0)
8880 optionp (equal (char-after (match-beginning 0)) ?#)
8881 cat (org-trim (match-string 2)))
8882 (if optionp
8883 (setq beg (point-at-bol) end (point-max))
8884 (org-back-to-heading t)
8885 (setq beg (point) end (org-end-of-subtree t t)))
8886 (put-text-property beg end 'org-category cat)
8887 (put-text-property beg end 'org-category-position beg)
8888 (goto-char pos)))))))
8890 (defun org-refresh-properties (dprop tprop)
8891 "Refresh buffer text properties.
8892 DPROP is the drawer property and TPROP is the corresponding text
8893 property to set."
8894 (let ((case-fold-search t)
8895 (inhibit-read-only t) p)
8896 (org-unmodified
8897 (save-excursion
8898 (save-restriction
8899 (widen)
8900 (goto-char (point-min))
8901 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8902 (setq p (org-match-string-no-properties 1))
8903 (save-excursion
8904 (org-back-to-heading t)
8905 (put-text-property
8906 (point-at-bol) (point-at-eol) tprop p))))))))
8909 ;;;; Link Stuff
8911 ;;; Link abbreviations
8913 (defun org-link-expand-abbrev (link)
8914 "Apply replacements as defined in `org-link-abbrev-alist'."
8915 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8916 (let* ((key (match-string 1 link))
8917 (as (or (assoc key org-link-abbrev-alist-local)
8918 (assoc key org-link-abbrev-alist)))
8919 (tag (and (match-end 2) (match-string 3 link)))
8920 rpl)
8921 (if (not as)
8922 link
8923 (setq rpl (cdr as))
8924 (cond
8925 ((symbolp rpl) (funcall rpl tag))
8926 ((string-match "%(\\([^)]+\\))" rpl)
8927 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8928 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8929 ((string-match "%h" rpl)
8930 (replace-match (url-hexify-string (or tag "")) t t rpl))
8931 (t (concat rpl tag)))))
8932 link))
8934 ;;; Storing and inserting links
8936 (defvar org-insert-link-history nil
8937 "Minibuffer history for links inserted with `org-insert-link'.")
8939 (defvar org-stored-links nil
8940 "Contains the links stored with `org-store-link'.")
8942 (defvar org-store-link-plist nil
8943 "Plist with info about the most recently link created with `org-store-link'.")
8945 (defvar org-link-protocols nil
8946 "Link protocols added to Org-mode using `org-add-link-type'.")
8948 (defvar org-store-link-functions nil
8949 "List of functions that are called to create and store a link.
8950 Each function will be called in turn until one returns a non-nil
8951 value. Each function should check if it is responsible for creating
8952 this link (for example by looking at the major mode).
8953 If not, it must exit and return nil.
8954 If yes, it should return a non-nil value after a calling
8955 `org-store-link-props' with a list of properties and values.
8956 Special properties are:
8958 :type The link prefix, like \"http\". This must be given.
8959 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8960 This is obligatory as well.
8961 :description Optional default description for the second pair
8962 of brackets in an Org-mode link. The user can still change
8963 this when inserting this link into an Org-mode buffer.
8965 In addition to these, any additional properties can be specified
8966 and then used in capture templates.")
8968 (defun org-add-link-type (type &optional follow export)
8969 "Add TYPE to the list of `org-link-types'.
8970 Re-compute all regular expressions depending on `org-link-types'
8972 FOLLOW and EXPORT are two functions.
8974 FOLLOW should take the link path as the single argument and do whatever
8975 is necessary to follow the link, for example find a file or display
8976 a mail message.
8978 EXPORT should format the link path for export to one of the export formats.
8979 It should be a function accepting three arguments:
8981 path the path of the link, the text after the prefix (like \"http:\")
8982 desc the description of the link, if any, or a description added by
8983 org-export-normalize-links if there is none
8984 format the export format, a symbol like `html' or `latex' or `ascii'..
8986 The function may use the FORMAT information to return different values
8987 depending on the format. The return value will be put literally into
8988 the exported file. If the return value is nil, this means Org should
8989 do what it normally does with links which do not have EXPORT defined.
8991 Org-mode has a built-in default for exporting links. If you are happy with
8992 this default, there is no need to define an export function for the link
8993 type. For a simple example of an export function, see `org-bbdb.el'."
8994 (add-to-list 'org-link-types type t)
8995 (org-make-link-regexps)
8996 (if (assoc type org-link-protocols)
8997 (setcdr (assoc type org-link-protocols) (list follow export))
8998 (push (list type follow export) org-link-protocols)))
9000 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9001 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9003 ;;;###autoload
9004 (defun org-store-link (arg)
9005 "\\<org-mode-map>Store an org-link to the current location.
9006 This link is added to `org-stored-links' and can later be inserted
9007 into an org-buffer with \\[org-insert-link].
9009 For some link types, a prefix arg is interpreted.
9010 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9011 For file links, arg negates `org-context-in-file-links'.
9013 A double prefix arg force skipping storing functions that are not
9014 part of Org's core."
9015 (interactive "P")
9016 (org-load-modules-maybe)
9017 (setq org-store-link-plist nil) ; reset
9018 (org-with-limited-levels
9019 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9020 (cond
9021 ((and (not (equal arg '(16)))
9022 (setq sfuns
9023 (delq
9024 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9025 org-store-link-functions))
9026 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9027 (or (and (cdr sfuns)
9028 (funcall (intern
9029 (completing-read "Which function for creating the link? "
9030 sfunsn t (car sfunsn)))))
9031 (funcall (caar sfuns)))
9032 (setq link (plist-get org-store-link-plist :link)
9033 desc (or (plist-get org-store-link-plist :description) link))))
9034 ((org-src-edit-buffer-p)
9035 (let (label gc)
9036 (while (or (not label)
9037 (save-excursion
9038 (save-restriction
9039 (widen)
9040 (goto-char (point-min))
9041 (re-search-forward
9042 (regexp-quote (format org-coderef-label-format label))
9043 nil t))))
9044 (when label (message "Label exists already") (sit-for 2))
9045 (setq label (read-string "Code line label: " label)))
9046 (end-of-line 1)
9047 (setq link (format org-coderef-label-format label))
9048 (setq gc (- 79 (length link)))
9049 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9050 (insert link)
9051 (setq link (concat "(" label ")") desc nil)))
9053 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9054 ;; We are in the agenda, link to referenced location
9055 (let ((m (or (get-text-property (point) 'org-hd-marker)
9056 (get-text-property (point) 'org-marker))))
9057 (when m
9058 (org-with-point-at m
9059 (setq agenda-link
9060 (if (org-called-interactively-p 'any)
9061 (call-interactively 'org-store-link)
9062 (org-store-link nil)))))))
9064 ((eq major-mode 'calendar-mode)
9065 (let ((cd (calendar-cursor-to-date)))
9066 (setq link
9067 (format-time-string
9068 (car org-time-stamp-formats)
9069 (apply 'encode-time
9070 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9071 nil nil nil))))
9072 (org-store-link-props :type "calendar" :date cd)))
9074 ((eq major-mode 'help-mode)
9075 (setq link (concat "help:" (save-excursion
9076 (goto-char (point-min))
9077 (looking-at "^[^ ]+")
9078 (match-string 0))))
9079 (org-store-link-props :type "help"))
9081 ((eq major-mode 'w3-mode)
9082 (setq cpltxt (if (and (buffer-name)
9083 (not (string-match "Untitled" (buffer-name))))
9084 (buffer-name)
9085 (url-view-url t))
9086 link (url-view-url t))
9087 (org-store-link-props :type "w3" :url (url-view-url t)))
9089 ((setq search (run-hook-with-args-until-success
9090 'org-create-file-search-functions))
9091 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9092 "::" search))
9093 (setq cpltxt (or description link)))
9095 ((eq major-mode 'image-mode)
9096 (setq cpltxt (concat "file:"
9097 (abbreviate-file-name buffer-file-name))
9098 link cpltxt)
9099 (org-store-link-props :type "image" :file buffer-file-name))
9101 ((eq major-mode 'dired-mode)
9102 ;; link to the file in the current line
9103 (let ((file (dired-get-filename nil t)))
9104 (setq file (if file
9105 (abbreviate-file-name
9106 (expand-file-name (dired-get-filename nil t)))
9107 ;; otherwise, no file so use current directory.
9108 default-directory))
9109 (setq cpltxt (concat "file:" file)
9110 link cpltxt)))
9112 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9113 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9114 (cond
9115 ((org-in-regexp "<<\\(.*?\\)>>")
9116 (setq cpltxt
9117 (concat "file:"
9118 (abbreviate-file-name
9119 (buffer-file-name (buffer-base-buffer)))
9120 "::" (match-string 1))
9121 link cpltxt))
9122 ((and (featurep 'org-id)
9123 (or (eq org-id-link-to-org-use-id t)
9124 (and (org-called-interactively-p 'any)
9125 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9126 (and (eq org-id-link-to-org-use-id
9127 'create-if-interactive-and-no-custom-id)
9128 (not custom-id))))
9129 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9130 ;; We can make a link using the ID.
9131 (setq link (condition-case nil
9132 (prog1 (org-id-store-link)
9133 (setq desc (plist-get org-store-link-plist :description)))
9134 (error
9135 ;; probably before first headline, link to file only
9136 (concat "file:"
9137 (abbreviate-file-name
9138 (buffer-file-name (buffer-base-buffer))))))))
9140 ;; Just link to current headline
9141 (setq cpltxt (concat "file:"
9142 (abbreviate-file-name
9143 (buffer-file-name (buffer-base-buffer)))))
9144 ;; Add a context search string
9145 (when (org-xor org-context-in-file-links arg)
9146 (let* ((ee (org-element-at-point))
9147 (et (org-element-type ee))
9148 (ev (plist-get (cadr ee) :value)))
9149 (setq txt (cond
9150 ((org-at-heading-p) nil)
9151 ((eq et 'keyword) ev)
9152 ((org-region-active-p)
9153 (buffer-substring (region-beginning) (region-end)))))
9154 (when (or (null txt) (string-match "\\S-" txt))
9155 (setq cpltxt
9156 (concat cpltxt "::"
9157 (condition-case nil
9158 (org-make-org-heading-search-string txt)
9159 (error "")))
9160 desc (or (and (eq et 'keyword) ev)
9161 (nth 4 (ignore-errors (org-heading-components)))
9162 "NONE")))))
9163 (if (string-match "::\\'" cpltxt)
9164 (setq cpltxt (substring cpltxt 0 -2)))
9165 (setq link cpltxt))))
9167 ((buffer-file-name (buffer-base-buffer))
9168 ;; Just link to this file here.
9169 (setq cpltxt (concat "file:"
9170 (abbreviate-file-name
9171 (buffer-file-name (buffer-base-buffer)))))
9172 ;; Add a context string
9173 (when (org-xor org-context-in-file-links arg)
9174 (setq txt (if (org-region-active-p)
9175 (buffer-substring (region-beginning) (region-end))
9176 (buffer-substring (point-at-bol) (point-at-eol))))
9177 ;; Only use search option if there is some text.
9178 (when (string-match "\\S-" txt)
9179 (setq cpltxt
9180 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9181 desc "NONE")))
9182 (setq link cpltxt))
9184 ((org-called-interactively-p 'interactive)
9185 (user-error "No method for storing a link from this buffer"))
9187 (t (setq link nil)))
9189 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9190 (setq link (or link cpltxt)
9191 desc (or desc cpltxt))
9192 (cond ((equal desc "NONE") (setq desc nil))
9193 ((string-match org-bracket-link-regexp desc)
9194 (setq desc (replace-regexp-in-string
9195 org-bracket-link-regexp
9196 (concat "\\3" (if (equal (length (match-string 0 desc))
9197 (length desc)) "*" "")) desc))))
9199 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9200 (progn
9201 (setq org-stored-links
9202 (cons (list link desc) org-stored-links))
9203 (message "Stored: %s" (or desc link))
9204 (when custom-id
9205 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9206 "::#" custom-id))
9207 (setq org-stored-links
9208 (cons (list link desc) org-stored-links))))
9209 (or agenda-link (and link (org-make-link-string link desc)))))))
9211 (defun org-store-link-props (&rest plist)
9212 "Store link properties, extract names and addresses."
9213 (let (x adr)
9214 (when (setq x (plist-get plist :from))
9215 (setq adr (mail-extract-address-components x))
9216 (setq plist (plist-put plist :fromname (car adr)))
9217 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9218 (when (setq x (plist-get plist :to))
9219 (setq adr (mail-extract-address-components x))
9220 (setq plist (plist-put plist :toname (car adr)))
9221 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9222 (let ((from (plist-get plist :from))
9223 (to (plist-get plist :to)))
9224 (when (and from to org-from-is-user-regexp)
9225 (setq plist
9226 (plist-put plist :fromto
9227 (if (string-match org-from-is-user-regexp from)
9228 (concat "to %t")
9229 (concat "from %f"))))))
9230 (setq org-store-link-plist plist))
9232 (defun org-add-link-props (&rest plist)
9233 "Add these properties to the link property list."
9234 (let (key value)
9235 (while plist
9236 (setq key (pop plist) value (pop plist))
9237 (setq org-store-link-plist
9238 (plist-put org-store-link-plist key value)))))
9240 (defun org-email-link-description (&optional fmt)
9241 "Return the description part of an email link.
9242 This takes information from `org-store-link-plist' and formats it
9243 according to FMT (default from `org-email-link-description-format')."
9244 (setq fmt (or fmt org-email-link-description-format))
9245 (let* ((p org-store-link-plist)
9246 (to (plist-get p :toaddress))
9247 (from (plist-get p :fromaddress))
9248 (table
9249 (list
9250 (cons "%c" (plist-get p :fromto))
9251 (cons "%F" (plist-get p :from))
9252 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9253 (cons "%T" (plist-get p :to))
9254 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9255 (cons "%s" (plist-get p :subject))
9256 (cons "%d" (plist-get p :date))
9257 (cons "%m" (plist-get p :message-id)))))
9258 (when (string-match "%c" fmt)
9259 ;; Check if the user wrote this message
9260 (if (and org-from-is-user-regexp from to
9261 (save-match-data (string-match org-from-is-user-regexp from)))
9262 (setq fmt (replace-match "to %t" t t fmt))
9263 (setq fmt (replace-match "from %f" t t fmt))))
9264 (org-replace-escapes fmt table)))
9266 (defun org-make-org-heading-search-string (&optional string)
9267 "Make search string for the current headline or STRING."
9268 (let ((s (or string
9269 (and (derived-mode-p 'org-mode)
9270 (save-excursion
9271 (org-back-to-heading t)
9272 (plist-get (cadr (org-element-at-point))
9273 :raw-value)))))
9274 (lines org-context-in-file-links))
9275 (or string (setq s (concat "*" s))) ; Add * for headlines
9276 (when (and string (integerp lines) (> lines 0))
9277 (let ((slines (org-split-string s "\n")))
9278 (when (< lines (length slines))
9279 (setq s (mapconcat
9280 'identity
9281 (reverse (nthcdr (- (length slines) lines)
9282 (reverse slines))) "\n")))))
9283 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9285 (defun org-make-link-string (link &optional description)
9286 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9287 (unless (string-match "\\S-" link)
9288 (error "Empty link"))
9289 (when (and description
9290 (stringp description)
9291 (not (string-match "\\S-" description)))
9292 (setq description nil))
9293 (when (stringp description)
9294 ;; Remove brackets from the description, they are fatal.
9295 (while (string-match "\\[" description)
9296 (setq description (replace-match "{" t t description)))
9297 (while (string-match "\\]" description)
9298 (setq description (replace-match "}" t t description))))
9299 (when (equal link description)
9300 ;; No description needed, it is identical
9301 (setq description nil))
9302 (when (and (not description)
9303 (not (string-match (org-image-file-name-regexp) link))
9304 (not (equal link (org-link-escape link))))
9305 (setq description (org-extract-attributes link)))
9306 (setq link
9307 (cond ((string-match (org-image-file-name-regexp) link) link)
9308 ((string-match org-link-types-re link)
9309 (concat (match-string 1 link)
9310 (org-link-escape (substring link (match-end 1)))))
9311 (t (org-link-escape link))))
9312 (concat "[[" link "]"
9313 (if description (concat "[" description "]") "")
9314 "]"))
9316 (defconst org-link-escape-chars
9317 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9318 "List of characters that should be escaped in link.
9319 This is the list that is used for internal purposes.")
9321 (defconst org-link-escape-chars-browser
9322 '(?\ )
9323 "List of escapes for characters that are problematic in links.
9324 This is the list that is used before handing over to the browser.")
9326 (defun org-link-escape (text &optional table merge)
9327 "Return percent escaped representation of TEXT.
9328 TEXT is a string with the text to escape.
9329 Optional argument TABLE is a list with characters that should be
9330 escaped. When nil, `org-link-escape-chars' is used.
9331 If optional argument MERGE is set, merge TABLE into
9332 `org-link-escape-chars'."
9333 (cond
9334 ((and table merge)
9335 (mapc (lambda (defchr)
9336 (unless (member defchr table)
9337 (setq table (cons defchr table)))) org-link-escape-chars))
9338 ((null table)
9339 (setq table org-link-escape-chars)))
9340 (mapconcat
9341 (lambda (char)
9342 (if (or (member char table)
9343 (and (or (< char 32) (= char 37) (> char 126))
9344 org-url-hexify-p))
9345 (mapconcat (lambda (sequence-element)
9346 (format "%%%.2X" sequence-element))
9347 (or (encode-coding-char char 'utf-8)
9348 (error "Unable to percent escape character: %s"
9349 (char-to-string char))) "")
9350 (char-to-string char))) text ""))
9352 (defun org-link-unescape (str)
9353 "Unhex hexified Unicode strings as returned from the JavaScript function
9354 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9355 (unless (and (null str) (string= "" str))
9356 (let ((pos 0) (case-fold-search t) unhexed)
9357 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9358 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9359 (setq str (replace-match unhexed t t str))
9360 (setq pos (+ pos (length unhexed))))))
9361 str)
9363 (defun org-link-unescape-compound (hex)
9364 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9365 Note: this function also decodes single byte encodings like
9366 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9367 (save-match-data
9368 (let* ((bytes (cdr (split-string hex "%")))
9369 (ret "")
9370 (eat 0)
9371 (sum 0))
9372 (while bytes
9373 (let* ((val (string-to-number (pop bytes) 16))
9374 (shift-xor
9375 (if (= 0 eat)
9376 (cond
9377 ((>= val 252) (cons 6 252))
9378 ((>= val 248) (cons 5 248))
9379 ((>= val 240) (cons 4 240))
9380 ((>= val 224) (cons 3 224))
9381 ((>= val 192) (cons 2 192))
9382 (t (cons 0 0)))
9383 (cons 6 128))))
9384 (if (>= val 192) (setq eat (car shift-xor)))
9385 (setq val (logxor val (cdr shift-xor)))
9386 (setq sum (+ (lsh sum (car shift-xor)) val))
9387 (if (> eat 0) (setq eat (- eat 1)))
9388 (cond
9389 ((= 0 eat) ;multi byte
9390 (setq ret (concat ret (org-char-to-string sum)))
9391 (setq sum 0))
9392 ((not bytes) ; single byte(s)
9393 (setq ret (org-link-unescape-single-byte-sequence hex))))
9394 )) ;; end (while bytes
9395 ret )))
9397 (defun org-link-unescape-single-byte-sequence (hex)
9398 "Unhexify hex-encoded single byte character sequences."
9399 (mapconcat (lambda (byte)
9400 (char-to-string (string-to-number byte 16)))
9401 (cdr (split-string hex "%")) ""))
9403 (defun org-xor (a b)
9404 "Exclusive or."
9405 (if a (not b) b))
9407 (defun org-fixup-message-id-for-http (s)
9408 "Replace special characters in a message id, so it can be used in an http query."
9409 (when (string-match "%" s)
9410 (setq s (mapconcat (lambda (c)
9411 (if (eq c ?%)
9412 "%25"
9413 (char-to-string c)))
9414 s "")))
9415 (while (string-match "<" s)
9416 (setq s (replace-match "%3C" t t s)))
9417 (while (string-match ">" s)
9418 (setq s (replace-match "%3E" t t s)))
9419 (while (string-match "@" s)
9420 (setq s (replace-match "%40" t t s)))
9423 (defun org-link-prettify (link)
9424 "Return a human-readable representation of LINK.
9425 The car of LINK must be a raw link the cdr of LINK must be either
9426 a link description or nil."
9427 (let ((desc (or (cadr link) "<no description>")))
9428 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9429 "<" (car link) ">")))
9431 ;;;###autoload
9432 (defun org-insert-link-global ()
9433 "Insert a link like Org-mode does.
9434 This command can be called in any mode to insert a link in Org-mode syntax."
9435 (interactive)
9436 (org-load-modules-maybe)
9437 (org-run-like-in-org-mode 'org-insert-link))
9439 (defun org-insert-all-links (&optional keep)
9440 "Insert all links in `org-stored-links'."
9441 (interactive "P")
9442 (let ((links (copy-sequence org-stored-links)) l)
9443 (while (setq l (if keep (pop links) (pop org-stored-links)))
9444 (insert "- ")
9445 (org-insert-link nil (car l) (cadr l))
9446 (insert "\n"))))
9448 (defun org-link-fontify-links-to-this-file ()
9449 "Fontify links to the current file in `org-stored-links'."
9450 (let ((f (buffer-file-name)) a b)
9451 (setq a (mapcar (lambda(l)
9452 (let ((ll (car l)))
9453 (when (and (string-match "^file:\\(.+\\)::" ll)
9454 (equal f (expand-file-name (match-string 1 ll))))
9455 ll)))
9456 org-stored-links))
9457 (when (featurep 'org-id)
9458 (setq b (mapcar (lambda(l)
9459 (let ((ll (car l)))
9460 (when (and (string-match "^id:\\(.+\\)$" ll)
9461 (equal f (expand-file-name
9462 (or (org-id-find-id-file
9463 (match-string 1 ll)) ""))))
9464 ll)))
9465 org-stored-links)))
9466 (mapcar (lambda(l)
9467 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9468 (delq nil (append a b)))))
9470 (defvar org-link-links-in-this-file nil)
9471 (defun org-insert-link (&optional complete-file link-location default-description)
9472 "Insert a link. At the prompt, enter the link.
9474 Completion can be used to insert any of the link protocol prefixes like
9475 http or ftp in use.
9477 The history can be used to select a link previously stored with
9478 `org-store-link'. When the empty string is entered (i.e. if you just
9479 press RET at the prompt), the link defaults to the most recently
9480 stored link. As SPC triggers completion in the minibuffer, you need to
9481 use M-SPC or C-q SPC to force the insertion of a space character.
9483 You will also be prompted for a description, and if one is given, it will
9484 be displayed in the buffer instead of the link.
9486 If there is already a link at point, this command will allow you to edit link
9487 and description parts.
9489 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9490 be selected using completion. The path to the file will be relative to the
9491 current directory if the file is in the current directory or a subdirectory.
9492 Otherwise, the link will be the absolute path as completed in the minibuffer
9493 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9494 option `org-link-file-path-type'.
9496 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9497 the current directory or below.
9499 With three \\[universal-argument] prefixes, negate the meaning of
9500 `org-keep-stored-link-after-insertion'.
9502 If `org-make-link-description-function' is non-nil, this function will be
9503 called with the link target, and the result will be the default
9504 link description.
9506 If the LINK-LOCATION parameter is non-nil, this value will be
9507 used as the link location instead of reading one interactively.
9509 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9510 be used as the default description."
9511 (interactive "P")
9512 (let* ((wcf (current-window-configuration))
9513 (origbuf (current-buffer))
9514 (region (if (org-region-active-p)
9515 (buffer-substring (region-beginning) (region-end))))
9516 (remove (and region (list (region-beginning) (region-end))))
9517 (desc region)
9518 tmphist ; byte-compile incorrectly complains about this
9519 (link link-location)
9520 (abbrevs org-link-abbrev-alist-local)
9521 entry file all-prefixes auto-desc)
9522 (cond
9523 (link-location) ; specified by arg, just use it.
9524 ((org-in-regexp org-bracket-link-regexp 1)
9525 ;; We do have a link at point, and we are going to edit it.
9526 (setq remove (list (match-beginning 0) (match-end 0)))
9527 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9528 (setq link (read-string "Link: "
9529 (org-link-unescape
9530 (org-match-string-no-properties 1)))))
9531 ((or (org-in-regexp org-angle-link-re)
9532 (org-in-regexp org-plain-link-re))
9533 ;; Convert to bracket link
9534 (setq remove (list (match-beginning 0) (match-end 0))
9535 link (read-string "Link: "
9536 (org-remove-angle-brackets (match-string 0)))))
9537 ((member complete-file '((4) (16)))
9538 ;; Completing read for file names.
9539 (setq link (org-file-complete-link complete-file)))
9541 ;; Read link, with completion for stored links.
9542 (org-link-fontify-links-to-this-file)
9543 (org-switch-to-buffer-other-window "*Org Links*")
9544 (with-current-buffer "*Org Links*"
9545 (erase-buffer)
9546 (insert "Insert a link.
9547 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9548 (when org-stored-links
9549 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9550 (insert (mapconcat 'org-link-prettify
9551 (reverse org-stored-links) "\n")))
9552 (goto-char (point-min)))
9553 (let ((cw (selected-window)))
9554 (select-window (get-buffer-window "*Org Links*" 'visible))
9555 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9556 (unless (pos-visible-in-window-p (point-max))
9557 (org-fit-window-to-buffer))
9558 (and (window-live-p cw) (select-window cw)))
9559 ;; Fake a link history, containing the stored links.
9560 (setq tmphist (append (mapcar 'car org-stored-links)
9561 org-insert-link-history))
9562 (setq all-prefixes (append (mapcar 'car abbrevs)
9563 (mapcar 'car org-link-abbrev-alist)
9564 org-link-types))
9565 (unwind-protect
9566 (progn
9567 (setq link
9568 (org-completing-read
9569 "Link: "
9570 (append
9571 (mapcar (lambda (x) (concat x ":"))
9572 all-prefixes)
9573 (mapcar 'car org-stored-links))
9574 nil nil nil
9575 'tmphist
9576 (caar org-stored-links)))
9577 (if (not (string-match "\\S-" link))
9578 (error "No link selected"))
9579 (mapc (lambda(l)
9580 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9581 org-stored-links)
9582 (if (or (member link all-prefixes)
9583 (and (equal ":" (substring link -1))
9584 (member (substring link 0 -1) all-prefixes)
9585 (setq link (substring link 0 -1))))
9586 (setq link (with-current-buffer origbuf
9587 (org-link-try-special-completion link)))))
9588 (set-window-configuration wcf)
9589 (kill-buffer "*Org Links*"))
9590 (setq entry (assoc link org-stored-links))
9591 (or entry (push link org-insert-link-history))
9592 (setq desc (or desc (nth 1 entry)))))
9594 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9595 (not org-keep-stored-link-after-insertion))
9596 (setq org-stored-links (delq (assoc link org-stored-links)
9597 org-stored-links)))
9599 (if (string-match org-plain-link-re link)
9600 ;; URL-like link, normalize the use of angular brackets.
9601 (setq link (org-remove-angle-brackets link)))
9603 ;; Check if we are linking to the current file with a search
9604 ;; option If yes, simplify the link by using only the search
9605 ;; option.
9606 (when (and buffer-file-name
9607 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9608 (let* ((path (match-string 1 link))
9609 (case-fold-search nil)
9610 (search (match-string 2 link)))
9611 (save-match-data
9612 (if (equal (file-truename buffer-file-name) (file-truename path))
9613 ;; We are linking to this same file, with a search option
9614 (setq link search)))))
9616 ;; Check if we can/should use a relative path. If yes, simplify the link
9617 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9618 (let* ((type (match-string 1 link))
9619 (path (match-string 2 link))
9620 (origpath path)
9621 (case-fold-search nil))
9622 (cond
9623 ((or (eq org-link-file-path-type 'absolute)
9624 (equal complete-file '(16)))
9625 (setq path (abbreviate-file-name (expand-file-name path))))
9626 ((eq org-link-file-path-type 'noabbrev)
9627 (setq path (expand-file-name path)))
9628 ((eq org-link-file-path-type 'relative)
9629 (setq path (file-relative-name path)))
9631 (save-match-data
9632 (if (string-match (concat "^" (regexp-quote
9633 (expand-file-name
9634 (file-name-as-directory
9635 default-directory))))
9636 (expand-file-name path))
9637 ;; We are linking a file with relative path name.
9638 (setq path (substring (expand-file-name path)
9639 (match-end 0)))
9640 (setq path (abbreviate-file-name (expand-file-name path)))))))
9641 (setq link (concat type path))
9642 (if (equal desc origpath)
9643 (setq desc path))))
9645 (if org-make-link-description-function
9646 (setq desc
9647 (or (condition-case nil
9648 (funcall org-make-link-description-function link desc)
9649 (error (progn (message "Can't get link description from `%s'"
9650 (symbol-name org-make-link-description-function))
9651 (sit-for 2) nil)))
9652 (read-string "Description: " default-description)))
9653 (if default-description (setq desc default-description)
9654 (setq desc (or (and auto-desc desc)
9655 (read-string "Description: " desc)))))
9657 (unless (string-match "\\S-" desc) (setq desc nil))
9658 (if remove (apply 'delete-region remove))
9659 (insert (org-make-link-string link desc))))
9661 (defun org-link-try-special-completion (type)
9662 "If there is completion support for link type TYPE, offer it."
9663 (let ((fun (intern (concat "org-" type "-complete-link"))))
9664 (if (functionp fun)
9665 (funcall fun)
9666 (read-string "Link (no completion support): " (concat type ":")))))
9668 (defun org-file-complete-link (&optional arg)
9669 "Create a file link using completion."
9670 (let (file link)
9671 (setq file (org-iread-file-name "File: "))
9672 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9673 (pwd1 (file-name-as-directory (abbreviate-file-name
9674 (expand-file-name ".")))))
9675 (cond
9676 ((equal arg '(16))
9677 (setq link (concat
9678 "file:"
9679 (abbreviate-file-name (expand-file-name file)))))
9680 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9681 (setq link (concat "file:" (match-string 1 file))))
9682 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9683 (expand-file-name file))
9684 (setq link (concat
9685 "file:" (match-string 1 (expand-file-name file)))))
9686 (t (setq link (concat "file:" file)))))
9687 link))
9689 (defun org-iread-file-name (&rest args)
9690 "Read-file-name using `ido-mode' speedup if available.
9691 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9692 See `read-file-name' for a description of parameters."
9693 (org-without-partial-completion
9694 (if (and org-completion-use-ido
9695 (fboundp 'ido-read-file-name)
9696 (boundp 'ido-mode) ido-mode
9697 (listp (second args)))
9698 (let ((ido-enter-matching-directory nil))
9699 (apply 'ido-read-file-name args))
9700 (apply 'read-file-name args))))
9702 (defun org-completing-read (&rest args)
9703 "Completing-read with SPACE being a normal character."
9704 (let ((enable-recursive-minibuffers t)
9705 (minibuffer-local-completion-map
9706 (copy-keymap minibuffer-local-completion-map)))
9707 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9708 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9709 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9710 (apply 'org-icompleting-read args)))
9712 (defun org-completing-read-no-i (&rest args)
9713 (let (org-completion-use-ido org-completion-use-iswitchb)
9714 (apply 'org-completing-read args)))
9716 (defun org-iswitchb-completing-read (prompt choices &rest args)
9717 "Use iswitch as a completing-read replacement to choose from choices.
9718 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9719 from."
9720 (let* ((iswitchb-use-virtual-buffers nil)
9721 (iswitchb-make-buflist-hook
9722 (lambda ()
9723 (setq iswitchb-temp-buflist choices))))
9724 (iswitchb-read-buffer prompt)))
9726 (defun org-icompleting-read (&rest args)
9727 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9728 (org-without-partial-completion
9729 (if (and org-completion-use-ido
9730 (fboundp 'ido-completing-read)
9731 (boundp 'ido-mode) ido-mode
9732 (listp (second args)))
9733 (let ((ido-enter-matching-directory nil))
9734 (apply 'ido-completing-read (concat (car args))
9735 (if (consp (car (nth 1 args)))
9736 (mapcar 'car (nth 1 args))
9737 (nth 1 args))
9738 (cddr args)))
9739 (if (and org-completion-use-iswitchb
9740 (boundp 'iswitchb-mode) iswitchb-mode
9741 (listp (second args)))
9742 (apply 'org-iswitchb-completing-read (concat (car args))
9743 (if (consp (car (nth 1 args)))
9744 (mapcar 'car (nth 1 args))
9745 (nth 1 args))
9746 (cddr args))
9747 (apply 'completing-read args)))))
9749 (defun org-extract-attributes (s)
9750 "Extract the attributes cookie from a string and set as text property."
9751 (let (a attr (start 0) key value)
9752 (save-match-data
9753 (when (string-match "{{\\([^}]+\\)}}$" s)
9754 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9755 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9756 (setq key (match-string 1 a) value (match-string 2 a)
9757 start (match-end 0)
9758 attr (plist-put attr (intern key) value))))
9759 (org-add-props s nil 'org-attr attr))
9762 (defun org-extract-attributes-from-string (tag)
9763 (let (key value attr)
9764 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9765 (setq key (match-string 1 tag) value (match-string 2 tag)
9766 tag (replace-match "" t t tag)
9767 attr (plist-put attr (intern key) value)))
9768 (cons tag attr)))
9770 (defun org-attributes-to-string (plist)
9771 "Format a property list into an HTML attribute list."
9772 (let ((s "") key value)
9773 (while plist
9774 (setq key (pop plist) value (pop plist))
9775 (and value
9776 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9779 ;;; Opening/following a link
9781 (defvar org-link-search-failed nil)
9783 (defvar org-open-link-functions nil
9784 "Hook for functions finding a plain text link.
9785 These functions must take a single argument, the link content.
9786 They will be called for links that look like [[link text][description]]
9787 when LINK TEXT does not have a protocol like \"http:\" and does not look
9788 like a filename (e.g. \"./blue.png\").
9790 These functions will be called *before* Org attempts to resolve the
9791 link by doing text searches in the current buffer - so if you want a
9792 link \"[[target]]\" to still find \"<<target>>\", your function should
9793 handle this as a special case.
9795 When the function does handle the link, it must return a non-nil value.
9796 If it decides that it is not responsible for this link, it must return
9797 nil to indicate that that Org-mode can continue with other options
9798 like exact and fuzzy text search.")
9800 (defun org-next-link ()
9801 "Move forward to the next link.
9802 If the link is in hidden text, expose it."
9803 (interactive)
9804 (when (and org-link-search-failed (eq this-command last-command))
9805 (goto-char (point-min))
9806 (message "Link search wrapped back to beginning of buffer"))
9807 (setq org-link-search-failed nil)
9808 (let* ((pos (point))
9809 (ct (org-context))
9810 (a (assoc :link ct)))
9811 (if a (goto-char (nth 2 a)))
9812 (if (re-search-forward org-any-link-re nil t)
9813 (progn
9814 (goto-char (match-beginning 0))
9815 (if (outline-invisible-p) (org-show-context)))
9816 (goto-char pos)
9817 (setq org-link-search-failed t)
9818 (error "No further link found"))))
9820 (defun org-previous-link ()
9821 "Move backward to the previous link.
9822 If the link is in hidden text, expose it."
9823 (interactive)
9824 (when (and org-link-search-failed (eq this-command last-command))
9825 (goto-char (point-max))
9826 (message "Link search wrapped back to end of buffer"))
9827 (setq org-link-search-failed nil)
9828 (let* ((pos (point))
9829 (ct (org-context))
9830 (a (assoc :link ct)))
9831 (if a (goto-char (nth 1 a)))
9832 (if (re-search-backward org-any-link-re nil t)
9833 (progn
9834 (goto-char (match-beginning 0))
9835 (if (outline-invisible-p) (org-show-context)))
9836 (goto-char pos)
9837 (setq org-link-search-failed t)
9838 (error "No further link found"))))
9840 (defun org-translate-link (s)
9841 "Translate a link string if a translation function has been defined."
9842 (if (and org-link-translation-function
9843 (fboundp org-link-translation-function)
9844 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9845 (progn
9846 (setq s (funcall org-link-translation-function
9847 (match-string 1 s) (match-string 2 s)))
9848 (concat (car s) ":" (cdr s)))
9851 (defun org-translate-link-from-planner (type path)
9852 "Translate a link from Emacs Planner syntax so that Org can follow it.
9853 This is still an experimental function, your mileage may vary."
9854 (cond
9855 ((member type '("http" "https" "news" "ftp"))
9856 ;; standard Internet links are the same.
9857 nil)
9858 ((and (equal type "irc") (string-match "^//" path))
9859 ;; Planner has two / at the beginning of an irc link, we have 1.
9860 ;; We should have zero, actually....
9861 (setq path (substring path 1)))
9862 ((and (equal type "lisp") (string-match "^/" path))
9863 ;; Planner has a slash, we do not.
9864 (setq type "elisp" path (substring path 1)))
9865 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9866 ;; A typical message link. Planner has the id after the final slash,
9867 ;; we separate it with a hash mark
9868 (setq path (concat (match-string 1 path) "#"
9869 (org-remove-angle-brackets (match-string 2 path)))))
9871 (cons type path))
9873 (defun org-find-file-at-mouse (ev)
9874 "Open file link or URL at mouse."
9875 (interactive "e")
9876 (mouse-set-point ev)
9877 (org-open-at-point 'in-emacs))
9879 (defun org-open-at-mouse (ev)
9880 "Open file link or URL at mouse.
9881 See the docstring of `org-open-file' for details."
9882 (interactive "e")
9883 (mouse-set-point ev)
9884 (if (eq major-mode 'org-agenda-mode)
9885 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9886 (org-open-at-point))
9888 (defvar org-window-config-before-follow-link nil
9889 "The window configuration before following a link.
9890 This is saved in case the need arises to restore it.")
9892 (defvar org-open-link-marker (make-marker)
9893 "Marker pointing to the location where `org-open-at-point; was called.")
9895 ;;;###autoload
9896 (defun org-open-at-point-global ()
9897 "Follow a link like Org-mode does.
9898 This command can be called in any mode to follow a link that has
9899 Org-mode syntax."
9900 (interactive)
9901 (org-run-like-in-org-mode 'org-open-at-point))
9903 ;;;###autoload
9904 (defun org-open-link-from-string (s &optional arg reference-buffer)
9905 "Open a link in the string S, as if it was in Org-mode."
9906 (interactive "sLink: \nP")
9907 (let ((reference-buffer (or reference-buffer (current-buffer))))
9908 (with-temp-buffer
9909 (let ((org-inhibit-startup (not reference-buffer)))
9910 (org-mode)
9911 (insert s)
9912 (goto-char (point-min))
9913 (when reference-buffer
9914 (setq org-link-abbrev-alist-local
9915 (with-current-buffer reference-buffer
9916 org-link-abbrev-alist-local)))
9917 (org-open-at-point arg reference-buffer)))))
9919 (defvar org-open-at-point-functions nil
9920 "Hook that is run when following a link at point.
9922 Functions in this hook must return t if they identify and follow
9923 a link at point. If they don't find anything interesting at point,
9924 they must return nil.")
9926 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9927 (defun org-open-at-point (&optional arg reference-buffer)
9928 "Open link at or after point.
9929 If there is no link at point, this function will search forward up to
9930 the end of the current line.
9931 Normally, files will be opened by an appropriate application. If the
9932 optional prefix argument ARG is non-nil, Emacs will visit the file.
9933 With a double prefix argument, try to open outside of Emacs, in the
9934 application the system uses for this file type."
9935 (interactive "P")
9936 ;; if in a code block, then open the block's results
9937 (unless (call-interactively #'org-babel-open-src-block-result)
9938 (org-load-modules-maybe)
9939 (move-marker org-open-link-marker (point))
9940 (setq org-window-config-before-follow-link (current-window-configuration))
9941 (org-remove-occur-highlights nil nil t)
9942 (cond
9943 ((and (org-at-heading-p)
9944 (not (org-at-timestamp-p t))
9945 (not (org-in-regexp
9946 (concat org-plain-link-re "\\|"
9947 org-bracket-link-regexp "\\|"
9948 org-angle-link-re "\\|"
9949 "[ \t]:[^ \t\n]+:[ \t]*$")))
9950 (not (get-text-property (point) 'org-linked-text)))
9951 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9952 (lk0 (car lkall))
9953 (lk (if (stringp lk0) (list lk0) lk0))
9954 (lkend (cdr lkall)))
9955 (mapcar (lambda(l)
9956 (search-forward l nil lkend)
9957 (goto-char (match-beginning 0))
9958 (org-open-at-point))
9959 lk))
9960 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9961 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9962 ((and (org-at-timestamp-p t)
9963 (not (org-in-regexp org-bracket-link-regexp)))
9964 (org-follow-timestamp-link))
9965 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9966 (not (org-in-regexp org-any-link-re)))
9967 (org-footnote-action))
9969 (let (type path link line search (pos (point)))
9970 (catch 'match
9971 (save-excursion
9972 (skip-chars-forward "^]\n\r")
9973 (when (org-in-regexp org-bracket-link-regexp 1)
9974 (setq link (org-extract-attributes
9975 (org-link-unescape (org-match-string-no-properties 1))))
9976 (while (string-match " *\n *" link)
9977 (setq link (replace-match " " t t link)))
9978 (setq link (org-link-expand-abbrev link))
9979 (cond
9980 ((or (file-name-absolute-p link)
9981 (string-match "^\\.\\.?/" link))
9982 (setq type "file" path link))
9983 ((string-match org-link-re-with-space3 link)
9984 (setq type (match-string 1 link) path (match-string 2 link)))
9985 ((string-match "^help:+\\(.+\\)" link)
9986 (setq type "help" path (match-string 1 link)))
9987 (t (setq type "thisfile" path link)))
9988 (throw 'match t)))
9990 (when (get-text-property (point) 'org-linked-text)
9991 (setq type "thisfile"
9992 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9993 (1+ (point)) (point))
9994 path (buffer-substring
9995 (or (previous-single-property-change pos 'org-linked-text)
9996 (point-min))
9997 (or (next-single-property-change pos 'org-linked-text)
9998 (point-max))))
9999 (throw 'match t))
10001 (save-excursion
10002 (when (or (org-in-regexp org-angle-link-re)
10003 (let ((match (org-in-regexp org-plain-link-re)))
10004 ;; Check a plain link is not within a bracket link
10005 (and match
10006 (save-excursion
10007 (progn
10008 (goto-char (car match))
10009 (not (org-in-regexp org-bracket-link-regexp))))))
10010 (let ((line_ending (save-excursion (end-of-line) (point))))
10011 ;; We are in a line before a plain or bracket link
10012 (or (re-search-forward org-plain-link-re line_ending t)
10013 (re-search-forward org-bracket-link-regexp line_ending t))))
10014 (setq type (match-string 1)
10015 path (org-link-unescape (match-string 2)))
10016 (throw 'match t)))
10017 (save-excursion
10018 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10019 (setq type "tags"
10020 path (match-string 1))
10021 (while (string-match ":" path)
10022 (setq path (replace-match "+" t t path)))
10023 (throw 'match t)))
10024 (when (org-in-regexp "<\\([^><\n]+\\)>")
10025 (setq type "tree-match"
10026 path (match-string 1))
10027 (throw 'match t)))
10028 (unless path
10029 (user-error "No link found"))
10031 ;; switch back to reference buffer
10032 ;; needed when if called in a temporary buffer through
10033 ;; org-open-link-from-string
10034 (with-current-buffer (or reference-buffer (current-buffer))
10036 ;; Remove any trailing spaces in path
10037 (if (string-match " +\\'" path)
10038 (setq path (replace-match "" t t path)))
10039 (if (and org-link-translation-function
10040 (fboundp org-link-translation-function))
10041 ;; Check if we need to translate the link
10042 (let ((tmp (funcall org-link-translation-function type path)))
10043 (setq type (car tmp) path (cdr tmp))))
10045 (cond
10047 ((assoc type org-link-protocols)
10048 (funcall (nth 1 (assoc type org-link-protocols)) path))
10050 ((equal type "help")
10051 (let ((f-or-v (intern path)))
10052 (cond ((fboundp f-or-v)
10053 (describe-function f-or-v))
10054 ((boundp f-or-v)
10055 (describe-variable f-or-v))
10056 (t (error "Not a known function or variable")))))
10058 ((equal type "mailto")
10059 (let ((cmd (car org-link-mailto-program))
10060 (args (cdr org-link-mailto-program)) args1
10061 (address path) (subject "") a)
10062 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10063 (setq address (match-string 1 path)
10064 subject (org-link-escape (match-string 2 path))))
10065 (while args
10066 (cond
10067 ((not (stringp (car args))) (push (pop args) args1))
10068 (t (setq a (pop args))
10069 (if (string-match "%a" a)
10070 (setq a (replace-match address t t a)))
10071 (if (string-match "%s" a)
10072 (setq a (replace-match subject t t a)))
10073 (push a args1))))
10074 (apply cmd (nreverse args1))))
10076 ((member type '("http" "https" "ftp" "news"))
10077 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10078 (org-link-escape
10079 path org-link-escape-chars-browser)
10080 path))))
10082 ((string= type "doi")
10083 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10084 (org-link-escape
10085 path org-link-escape-chars-browser)
10086 path))))
10088 ((member type '("message"))
10089 (browse-url (concat type ":" path)))
10091 ((string= type "tags")
10092 (org-tags-view arg path))
10094 ((string= type "tree-match")
10095 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10097 ((string= type "file")
10098 (if (string-match "::\\([0-9]+\\)\\'" path)
10099 (setq line (string-to-number (match-string 1 path))
10100 path (substring path 0 (match-beginning 0)))
10101 (if (string-match "::\\(.+\\)\\'" path)
10102 (setq search (match-string 1 path)
10103 path (substring path 0 (match-beginning 0)))))
10104 (if (string-match "[*?{]" (file-name-nondirectory path))
10105 (dired path)
10106 (org-open-file path arg line search)))
10108 ((string= type "shell")
10109 (let ((buf (generate-new-buffer "*Org Shell Output"))
10110 (cmd path))
10111 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10112 (string-match org-confirm-shell-link-not-regexp cmd))
10113 (not org-confirm-shell-link-function)
10114 (funcall org-confirm-shell-link-function
10115 (format "Execute \"%s\" in shell? "
10116 (org-add-props cmd nil
10117 'face 'org-warning))))
10118 (progn
10119 (message "Executing %s" cmd)
10120 (shell-command cmd buf)
10121 (if (featurep 'midnight)
10122 (setq clean-buffer-list-kill-buffer-names
10123 (cons buf clean-buffer-list-kill-buffer-names))))
10124 (error "Abort"))))
10126 ((string= type "elisp")
10127 (let ((cmd path))
10128 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10129 (string-match org-confirm-elisp-link-not-regexp cmd))
10130 (not org-confirm-elisp-link-function)
10131 (funcall org-confirm-elisp-link-function
10132 (format "Execute \"%s\" as elisp? "
10133 (org-add-props cmd nil
10134 'face 'org-warning))))
10135 (message "%s => %s" cmd
10136 (if (equal (string-to-char cmd) ?\()
10137 (eval (read cmd))
10138 (call-interactively (read cmd))))
10139 (error "Abort"))))
10141 ((and (string= type "thisfile")
10142 (run-hook-with-args-until-success
10143 'org-open-link-functions path)))
10145 ((string= type "thisfile")
10146 (if arg
10147 (switch-to-buffer-other-window
10148 (org-get-buffer-for-internal-link (current-buffer)))
10149 (org-mark-ring-push))
10150 (let ((cmd `(org-link-search
10151 ,path
10152 ,(cond ((equal arg '(4)) ''occur)
10153 ((equal arg '(16)) ''org-occur))
10154 ,pos)))
10155 (condition-case nil (let ((org-link-search-inhibit-query t))
10156 (eval cmd))
10157 (error (progn (widen) (eval cmd))))))
10159 (t (browse-url-at-point)))))))
10160 (move-marker org-open-link-marker nil)
10161 (run-hook-with-args 'org-follow-link-hook)))
10163 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10164 "Offer links in the current entry and return the selected link.
10165 If there is only one link, return it.
10166 If NTH is an integer, return the NTH link found.
10167 If ZERO is a string, check also this string for a link, and if
10168 there is one, return it."
10169 (with-current-buffer buffer
10170 (save-excursion
10171 (save-restriction
10172 (widen)
10173 (goto-char marker)
10174 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10175 "\\(" org-angle-link-re "\\)\\|"
10176 "\\(" org-plain-link-re "\\)"))
10177 (cnt ?0)
10178 (in-emacs (if (integerp nth) nil nth))
10179 have-zero end links link c)
10180 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10181 (push (match-string 0 zero) links)
10182 (setq cnt (1- cnt) have-zero t))
10183 (save-excursion
10184 (org-back-to-heading t)
10185 (setq end (save-excursion (outline-next-heading) (point)))
10186 (while (re-search-forward re end t)
10187 (push (match-string 0) links))
10188 (setq links (org-uniquify (reverse links))))
10189 (cond
10190 ((null links)
10191 (message "No links"))
10192 ((equal (length links) 1)
10193 (setq link (car links)))
10194 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10195 (setq link (nth (if have-zero nth (1- nth)) links)))
10196 (t ; we have to select a link
10197 (save-excursion
10198 (save-window-excursion
10199 (delete-other-windows)
10200 (with-output-to-temp-buffer "*Select Link*"
10201 (mapc (lambda (l)
10202 (if (not (string-match org-bracket-link-regexp l))
10203 (princ (format "[%c] %s\n" (incf cnt)
10204 (org-remove-angle-brackets l)))
10205 (if (match-end 3)
10206 (princ (format "[%c] %s (%s)\n" (incf cnt)
10207 (match-string 3 l) (match-string 1 l)))
10208 (princ (format "[%c] %s\n" (incf cnt)
10209 (match-string 1 l))))))
10210 links))
10211 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10212 (message "Select link to open, RET to open all:")
10213 (setq c (read-char-exclusive))
10214 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10215 (when (equal c ?q) (error "Abort"))
10216 (if (equal c ?\C-m)
10217 (setq link links)
10218 (setq nth (- c ?0))
10219 (if have-zero (setq nth (1+ nth)))
10220 (unless (and (integerp nth) (>= (length links) nth))
10221 (error "Invalid link selection"))
10222 (setq link (nth (1- nth) links)))))
10223 (cons link end))))))
10225 ;; Add special file links that specify the way of opening
10227 (org-add-link-type "file+sys" 'org-open-file-with-system)
10228 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10229 (defun org-open-file-with-system (path)
10230 "Open file at PATH using the system way of opening it."
10231 (org-open-file path 'system))
10232 (defun org-open-file-with-emacs (path)
10233 "Open file at PATH in Emacs."
10234 (org-open-file path 'emacs))
10237 ;;; File search
10239 (defvar org-create-file-search-functions nil
10240 "List of functions to construct the right search string for a file link.
10241 These functions are called in turn with point at the location to
10242 which the link should point.
10244 A function in the hook should first test if it would like to
10245 handle this file type, for example by checking the `major-mode'
10246 or the file extension. If it decides not to handle this file, it
10247 should just return nil to give other functions a chance. If it
10248 does handle the file, it must return the search string to be used
10249 when following the link. The search string will be part of the
10250 file link, given after a double colon, and `org-open-at-point'
10251 will automatically search for it. If special measures must be
10252 taken to make the search successful, another function should be
10253 added to the companion hook `org-execute-file-search-functions',
10254 which see.
10256 A function in this hook may also use `setq' to set the variable
10257 `description' to provide a suggestion for the descriptive text to
10258 be used for this link when it gets inserted into an Org-mode
10259 buffer with \\[org-insert-link].")
10261 (defvar org-execute-file-search-functions nil
10262 "List of functions to execute a file search triggered by a link.
10264 Functions added to this hook must accept a single argument, the
10265 search string that was part of the file link, the part after the
10266 double colon. The function must first check if it would like to
10267 handle this search, for example by checking the `major-mode' or
10268 the file extension. If it decides not to handle this search, it
10269 should just return nil to give other functions a chance. If it
10270 does handle the search, it must return a non-nil value to keep
10271 other functions from trying.
10273 Each function can access the current prefix argument through the
10274 variable `current-prefix-argument'. Note that a single prefix is
10275 used to force opening a link in Emacs, so it may be good to only
10276 use a numeric or double prefix to guide the search function.
10278 In case this is needed, a function in this hook can also restore
10279 the window configuration before `org-open-at-point' was called using:
10281 (set-window-configuration org-window-config-before-follow-link)")
10283 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10284 (defun org-link-search (s &optional type avoid-pos stealth)
10285 "Search for a link search option.
10286 If S is surrounded by forward slashes, it is interpreted as a
10287 regular expression. In org-mode files, this will create an `org-occur'
10288 sparse tree. In ordinary files, `occur' will be used to list matches.
10289 If the current buffer is in `dired-mode', grep will be used to search
10290 in all files. If AVOID-POS is given, ignore matches near that position.
10292 When optional argument STEALTH is non-nil, do not modify
10293 visibility around point, thus ignoring
10294 `org-show-hierarchy-above', `org-show-following-heading' and
10295 `org-show-siblings' variables."
10296 (let ((case-fold-search t)
10297 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10298 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10299 (append '(("") (" ") ("\t") ("\n"))
10300 org-emphasis-alist)
10301 "\\|") "\\)"))
10302 (pos (point))
10303 (pre nil) (post nil)
10304 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10305 (cond
10306 ;; First check if there are any special search functions
10307 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10308 ;; Now try the builtin stuff
10309 ((and (equal (string-to-char s0) ?#)
10310 (> (length s0) 1)
10311 (save-excursion
10312 (goto-char (point-min))
10313 (and
10314 (re-search-forward
10315 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10316 (setq type 'dedicated
10317 pos (match-beginning 0))))
10318 ;; There is an exact target for this
10319 (goto-char pos)
10320 (org-back-to-heading t)))
10321 ((save-excursion
10322 (goto-char (point-min))
10323 (and
10324 (re-search-forward
10325 (concat "<<" (regexp-quote s0) ">>") nil t)
10326 (setq type 'dedicated
10327 pos (match-beginning 0))))
10328 ;; There is an exact target for this
10329 (goto-char pos))
10330 ((save-excursion
10331 (goto-char (point-min))
10332 (and
10333 (re-search-forward
10334 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10335 (setq type 'dedicated pos (match-beginning 0))))
10336 ;; Found an invisible target.
10337 (goto-char pos))
10338 ((save-excursion
10339 (goto-char (point-min))
10340 (and
10341 (re-search-forward
10342 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10343 (setq type 'dedicated pos (match-beginning 0))))
10344 ;; Found an element with a matching #+name affiliated keyword.
10345 (goto-char pos))
10346 ((and (string-match "^(\\(.*\\))$" s0)
10347 (save-excursion
10348 (goto-char (point-min))
10349 (and
10350 (re-search-forward
10351 (concat "[^[]" (regexp-quote
10352 (format org-coderef-label-format
10353 (match-string 1 s0))))
10354 nil t)
10355 (setq type 'dedicated
10356 pos (1+ (match-beginning 0))))))
10357 ;; There is a coderef target for this
10358 (goto-char pos))
10359 ((string-match "^/\\(.*\\)/$" s)
10360 ;; A regular expression
10361 (cond
10362 ((derived-mode-p 'org-mode)
10363 (org-occur (match-string 1 s)))
10364 ;;((eq major-mode 'dired-mode)
10365 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10366 (t (org-do-occur (match-string 1 s)))))
10367 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10368 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10369 (goto-char (point-min))
10370 (cond
10371 ((let (case-fold-search)
10372 (re-search-forward (format org-complex-heading-regexp-format
10373 (regexp-quote s))
10374 nil t))
10375 ;; OK, found a match
10376 (setq type 'dedicated)
10377 (goto-char (match-beginning 0)))
10378 ((and (not org-link-search-inhibit-query)
10379 (eq org-link-search-must-match-exact-headline 'query-to-create)
10380 (y-or-n-p "No match - create this as a new heading? "))
10381 (goto-char (point-max))
10382 (or (bolp) (newline))
10383 (insert "* " s "\n")
10384 (beginning-of-line 0))
10386 (goto-char pos)
10387 (error "No match"))))
10389 ;; A normal search string
10390 (when (equal (string-to-char s) ?*)
10391 ;; Anchor on headlines, post may include tags.
10392 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10393 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10394 s (substring s 1)))
10395 (remove-text-properties
10396 0 (length s)
10397 '(face nil mouse-face nil keymap nil fontified nil) s)
10398 ;; Make a series of regular expressions to find a match
10399 (setq words (org-split-string s "[ \n\r\t]+")
10401 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10402 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10403 "\\)" markers)
10404 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10405 re2a (concat "[ \t\r\n]" re2a_)
10406 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10407 re4 (concat "[^a-zA-Z_]" re4_)
10409 re1 (concat pre re2 post)
10410 re3 (concat pre (if pre re4_ re4) post)
10411 re5 (concat pre ".*" re4)
10412 re2 (concat pre re2)
10413 re2a (concat pre (if pre re2a_ re2a))
10414 re4 (concat pre (if pre re4_ re4))
10415 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10416 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10417 re5 "\\)"
10419 (cond
10420 ((eq type 'org-occur) (org-occur reall))
10421 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10422 (t (goto-char (point-min))
10423 (setq type 'fuzzy)
10424 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10425 (org-search-not-self 1 re1 nil t)
10426 (org-search-not-self 1 re2 nil t)
10427 (org-search-not-self 1 re2a nil t)
10428 (org-search-not-self 1 re3 nil t)
10429 (org-search-not-self 1 re4 nil t)
10430 (org-search-not-self 1 re5 nil t)
10432 (goto-char (match-beginning 1))
10433 (goto-char pos)
10434 (error "No match"))))))
10435 (and (derived-mode-p 'org-mode)
10436 (not stealth)
10437 (org-show-context 'link-search))
10438 type))
10440 (defun org-search-not-self (group &rest args)
10441 "Execute `re-search-forward', but only accept matches that do not
10442 enclose the position of `org-open-link-marker'."
10443 (let ((m org-open-link-marker))
10444 (catch 'exit
10445 (while (apply 're-search-forward args)
10446 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10447 (goto-char (match-end group))
10448 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10449 (> (match-beginning 0) (marker-position m))
10450 (< (match-end 0) (marker-position m)))
10451 (save-match-data
10452 (or (not (org-in-regexp
10453 org-bracket-link-analytic-regexp 1))
10454 (not (match-end 4)) ; no description
10455 (and (<= (match-beginning 4) (point))
10456 (>= (match-end 4) (point))))))
10457 (throw 'exit (point))))))))
10459 (defun org-get-buffer-for-internal-link (buffer)
10460 "Return a buffer to be used for displaying the link target of internal links."
10461 (cond
10462 ((not org-display-internal-link-with-indirect-buffer)
10463 buffer)
10464 ((string-match "(Clone)$" (buffer-name buffer))
10465 (message "Buffer is already a clone, not making another one")
10466 ;; we also do not modify visibility in this case
10467 buffer)
10468 (t ; make a new indirect buffer for displaying the link
10469 (let* ((bn (buffer-name buffer))
10470 (ibn (concat bn "(Clone)"))
10471 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10472 (with-current-buffer ib (org-overview))
10473 ib))))
10475 (defun org-do-occur (regexp &optional cleanup)
10476 "Call the Emacs command `occur'.
10477 If CLEANUP is non-nil, remove the printout of the regular expression
10478 in the *Occur* buffer. This is useful if the regex is long and not useful
10479 to read."
10480 (occur regexp)
10481 (when cleanup
10482 (let ((cwin (selected-window)) win beg end)
10483 (when (setq win (get-buffer-window "*Occur*"))
10484 (select-window win))
10485 (goto-char (point-min))
10486 (when (re-search-forward "match[a-z]+" nil t)
10487 (setq beg (match-end 0))
10488 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10489 (setq end (1- (match-beginning 0)))))
10490 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10491 (goto-char (point-min))
10492 (select-window cwin))))
10494 ;;; The mark ring for links jumps
10496 (defvar org-mark-ring nil
10497 "Mark ring for positions before jumps in Org-mode.")
10498 (defvar org-mark-ring-last-goto nil
10499 "Last position in the mark ring used to go back.")
10500 ;; Fill and close the ring
10501 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10502 (loop for i from 1 to org-mark-ring-length do
10503 (push (make-marker) org-mark-ring))
10504 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10505 org-mark-ring)
10507 (defun org-mark-ring-push (&optional pos buffer)
10508 "Put the current position or POS into the mark ring and rotate it."
10509 (interactive)
10510 (setq pos (or pos (point)))
10511 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10512 (move-marker (car org-mark-ring)
10513 (or pos (point))
10514 (or buffer (current-buffer)))
10515 (message "%s"
10516 (substitute-command-keys
10517 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10519 (defun org-mark-ring-goto (&optional n)
10520 "Jump to the previous position in the mark ring.
10521 With prefix arg N, jump back that many stored positions. When
10522 called several times in succession, walk through the entire ring.
10523 Org-mode commands jumping to a different position in the current file,
10524 or to another Org-mode file, automatically push the old position
10525 onto the ring."
10526 (interactive "p")
10527 (let (p m)
10528 (if (eq last-command this-command)
10529 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10530 (setq p org-mark-ring))
10531 (setq org-mark-ring-last-goto p)
10532 (setq m (car p))
10533 (org-pop-to-buffer-same-window (marker-buffer m))
10534 (goto-char m)
10535 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10537 (defun org-remove-angle-brackets (s)
10538 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10539 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10541 (defun org-add-angle-brackets (s)
10542 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10543 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10545 (defun org-remove-double-quotes (s)
10546 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10547 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10550 ;;; Following specific links
10552 (defun org-follow-timestamp-link ()
10553 "Open an agenda view for the time-stamp date/range at point."
10554 (cond
10555 ((org-at-date-range-p t)
10556 (let ((org-agenda-start-on-weekday)
10557 (t1 (match-string 1))
10558 (t2 (match-string 2)) tt1 tt2)
10559 (setq tt1 (time-to-days (org-time-string-to-time t1))
10560 tt2 (time-to-days (org-time-string-to-time t2)))
10561 (let ((org-agenda-buffer-tmp-name
10562 (format "*Org Agenda(a:%s)"
10563 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10564 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10565 ((org-at-timestamp-p t)
10566 (let ((org-agenda-buffer-tmp-name
10567 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10568 (org-agenda-list nil (time-to-days (org-time-string-to-time
10569 (substring (match-string 1) 0 10)))
10570 1)))
10571 (t (error "This should not happen"))))
10574 ;;; Following file links
10575 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10576 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10577 (declare-function mailcap-mime-info
10578 "mailcap" (string &optional request no-decode))
10579 (defvar org-wait nil)
10580 (defun org-open-file (path &optional in-emacs line search)
10581 "Open the file at PATH.
10582 First, this expands any special file name abbreviations. Then the
10583 configuration variable `org-file-apps' is checked if it contains an
10584 entry for this file type, and if yes, the corresponding command is launched.
10586 If no application is found, Emacs simply visits the file.
10588 With optional prefix argument IN-EMACS, Emacs will visit the file.
10589 With a double \\[universal-argument] \\[universal-argument] \
10590 prefix arg, Org tries to avoid opening in Emacs
10591 and to use an external application to visit the file.
10593 Optional LINE specifies a line to go to, optional SEARCH a string
10594 to search for. If LINE or SEARCH is given, the file will be
10595 opened in Emacs, unless an entry from org-file-apps that makes
10596 use of groups in a regexp matches.
10598 If you want to change the way frames are used when following a
10599 link, please customize `org-link-frame-setup'.
10601 If the file does not exist, an error is thrown."
10602 (let* ((file (if (equal path "")
10603 buffer-file-name
10604 (substitute-in-file-name (expand-file-name path))))
10605 (file-apps (append org-file-apps (org-default-apps)))
10606 (apps (org-remove-if
10607 'org-file-apps-entry-match-against-dlink-p file-apps))
10608 (apps-dlink (org-remove-if-not
10609 'org-file-apps-entry-match-against-dlink-p file-apps))
10610 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10611 (dirp (if remp nil (file-directory-p file)))
10612 (file (if (and dirp org-open-directory-means-index-dot-org)
10613 (concat (file-name-as-directory file) "index.org")
10614 file))
10615 (a-m-a-p (assq 'auto-mode apps))
10616 (dfile (downcase file))
10617 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10618 (link (cond ((and (eq line nil)
10619 (eq search nil))
10620 file)
10621 (line
10622 (concat file "::" (number-to-string line)))
10623 (search
10624 (concat file "::" search))))
10625 (dlink (downcase link))
10626 (old-buffer (current-buffer))
10627 (old-pos (point))
10628 (old-mode major-mode)
10629 ext cmd link-match-data)
10630 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10631 (setq ext (match-string 1 dfile))
10632 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10633 (setq ext (match-string 1 dfile))))
10634 (cond
10635 ((member in-emacs '((16) system))
10636 (setq cmd (cdr (assoc 'system apps))))
10637 (in-emacs (setq cmd 'emacs))
10639 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10640 (and dirp (cdr (assoc 'directory apps)))
10641 ; first, try matching against apps-dlink
10642 ; if we get a match here, store the match data for later
10643 (let ((match (assoc-default dlink apps-dlink
10644 'string-match)))
10645 (if match
10646 (progn (setq link-match-data (match-data))
10647 match)
10648 (progn (setq in-emacs (or in-emacs line search))
10649 nil))) ; if we have no match in apps-dlink,
10650 ; always open the file in emacs if line or search
10651 ; is given (for backwards compatibility)
10652 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10653 'string-match)
10654 (cdr (assoc ext apps))
10655 (cdr (assoc t apps))))))
10656 (when (eq cmd 'system)
10657 (setq cmd (cdr (assoc 'system apps))))
10658 (when (eq cmd 'default)
10659 (setq cmd (cdr (assoc t apps))))
10660 (when (eq cmd 'mailcap)
10661 (require 'mailcap)
10662 (mailcap-parse-mailcaps)
10663 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10664 (command (mailcap-mime-info mime-type)))
10665 (if (stringp command)
10666 (setq cmd command)
10667 (setq cmd 'emacs))))
10668 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10669 (not (file-exists-p file))
10670 (not org-open-non-existing-files))
10671 (error "No such file: %s" file))
10672 (cond
10673 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10674 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10675 (while (string-match "['\"]%s['\"]" cmd)
10676 (setq cmd (replace-match "%s" t t cmd)))
10677 (while (string-match "%s" cmd)
10678 (setq cmd (replace-match
10679 (save-match-data
10680 (shell-quote-argument
10681 (convert-standard-filename file)))
10682 t t cmd)))
10684 ;; Replace "%1", "%2" etc. in command with group matches from regex
10685 (save-match-data
10686 (let ((match-index 1)
10687 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10688 (set-match-data link-match-data)
10689 (while (<= match-index number-of-groups)
10690 (let ((regex (concat "%" (number-to-string match-index)))
10691 (replace-with (match-string match-index dlink)))
10692 (while (string-match regex cmd)
10693 (setq cmd (replace-match replace-with t t cmd))))
10694 (setq match-index (+ match-index 1)))))
10696 (save-window-excursion
10697 (message "Running %s...done" cmd)
10698 (start-process-shell-command cmd nil cmd)
10699 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10700 ((or (stringp cmd)
10701 (eq cmd 'emacs))
10702 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10703 (widen)
10704 (if line (org-goto-line line)
10705 (if search (org-link-search search))))
10706 ((consp cmd)
10707 (let ((file (convert-standard-filename file)))
10708 (save-match-data
10709 (set-match-data link-match-data)
10710 (eval cmd))))
10711 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10712 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10713 (or (not (equal old-buffer (current-buffer)))
10714 (not (equal old-pos (point))))
10715 (org-mark-ring-push old-pos old-buffer))))
10717 (defun org-file-apps-entry-match-against-dlink-p (entry)
10718 "This function returns non-nil if `entry' uses a regular
10719 expression which should be matched against the whole link by
10720 org-open-file.
10722 It assumes that is the case when the entry uses a regular
10723 expression which has at least one grouping construct and the
10724 action is either a lisp form or a command string containing
10725 '%1', i.e. using at least one subexpression match as a
10726 parameter."
10727 (let ((selector (car entry))
10728 (action (cdr entry)))
10729 (if (stringp selector)
10730 (and (> (regexp-opt-depth selector) 0)
10731 (or (and (stringp action)
10732 (string-match "%[0-9]" action))
10733 (consp action)))
10734 nil)))
10736 (defun org-default-apps ()
10737 "Return the default applications for this operating system."
10738 (cond
10739 ((eq system-type 'darwin)
10740 org-file-apps-defaults-macosx)
10741 ((eq system-type 'windows-nt)
10742 org-file-apps-defaults-windowsnt)
10743 (t org-file-apps-defaults-gnu)))
10745 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10746 "Convert extensions to regular expressions in the cars of LIST.
10747 Also, weed out any non-string entries, because the return value is used
10748 only for regexp matching.
10749 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10750 point to the symbol `emacs', indicating that the file should
10751 be opened in Emacs."
10752 (append
10753 (delq nil
10754 (mapcar (lambda (x)
10755 (if (not (stringp (car x)))
10757 (if (string-match "\\W" (car x))
10759 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10760 list))
10761 (if add-auto-mode
10762 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10764 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10765 (defun org-file-remote-p (file)
10766 "Test whether FILE specifies a location on a remote system.
10767 Return non-nil if the location is indeed remote.
10769 For example, the filename \"/user@host:/foo\" specifies a location
10770 on the system \"/user@host:\"."
10771 (cond ((fboundp 'file-remote-p)
10772 (file-remote-p file))
10773 ((fboundp 'tramp-handle-file-remote-p)
10774 (tramp-handle-file-remote-p file))
10775 ((and (boundp 'ange-ftp-name-format)
10776 (string-match (car ange-ftp-name-format) file))
10777 t)))
10780 ;;;; Refiling
10782 (defun org-get-org-file ()
10783 "Read a filename, with default directory `org-directory'."
10784 (let ((default (or org-default-notes-file remember-data-file)))
10785 (read-file-name (format "File name [%s]: " default)
10786 (file-name-as-directory org-directory)
10787 default)))
10789 (defun org-notes-order-reversed-p ()
10790 "Check if the current file should receive notes in reversed order."
10791 (cond
10792 ((not org-reverse-note-order) nil)
10793 ((eq t org-reverse-note-order) t)
10794 ((not (listp org-reverse-note-order)) nil)
10795 (t (catch 'exit
10796 (let ((all org-reverse-note-order)
10797 entry)
10798 (while (setq entry (pop all))
10799 (if (string-match (car entry) buffer-file-name)
10800 (throw 'exit (cdr entry))))
10801 nil)))))
10803 (defvar org-refile-target-table nil
10804 "The list of refile targets, created by `org-refile'.")
10806 (defvar org-agenda-new-buffers nil
10807 "Buffers created to visit agenda files.")
10809 (defvar org-refile-cache nil
10810 "Cache for refile targets.")
10812 (defvar org-refile-markers nil
10813 "All the markers used for caching refile locations.")
10815 (defun org-refile-marker (pos)
10816 "Get a new refile marker, but only if caching is in use."
10817 (if (not org-refile-use-cache)
10819 (let ((m (make-marker)))
10820 (move-marker m pos)
10821 (push m org-refile-markers)
10822 m)))
10824 (defun org-refile-cache-clear ()
10825 "Clear the refile cache and disable all the markers."
10826 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10827 (setq org-refile-markers nil)
10828 (setq org-refile-cache nil)
10829 (message "Refile cache has been cleared"))
10831 (defun org-refile-cache-check-set (set)
10832 "Check if all the markers in the cache still have live buffers."
10833 (let (marker)
10834 (catch 'exit
10835 (while (and set (setq marker (nth 3 (pop set))))
10836 ;; if org-refile-use-outline-path is 'file, marker may be nil
10837 (when (and marker (null (marker-buffer marker)))
10838 (message "not found") (sit-for 3)
10839 (throw 'exit nil)))
10840 t)))
10842 (defun org-refile-cache-put (set &rest identifiers)
10843 "Push the refile targets SET into the cache, under IDENTIFIERS."
10844 (let* ((key (sha1 (prin1-to-string identifiers)))
10845 (entry (assoc key org-refile-cache)))
10846 (if entry
10847 (setcdr entry set)
10848 (push (cons key set) org-refile-cache))))
10850 (defun org-refile-cache-get (&rest identifiers)
10851 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10852 (cond
10853 ((not org-refile-cache) nil)
10854 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10856 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10857 org-refile-cache))))
10858 (and set (org-refile-cache-check-set set) set)))))
10860 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10861 "Produce a table with refile targets."
10862 (let ((case-fold-search nil)
10863 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10864 (entries (or org-refile-targets '((nil . (:level . 1)))))
10865 targets tgs txt re files f desc descre fast-path-p level pos0)
10866 (message "Getting targets...")
10867 (with-current-buffer (or default-buffer (current-buffer))
10868 (while (setq entry (pop entries))
10869 (setq files (car entry) desc (cdr entry))
10870 (setq fast-path-p nil)
10871 (cond
10872 ((null files) (setq files (list (current-buffer))))
10873 ((eq files 'org-agenda-files)
10874 (setq files (org-agenda-files 'unrestricted)))
10875 ((and (symbolp files) (fboundp files))
10876 (setq files (funcall files)))
10877 ((and (symbolp files) (boundp files))
10878 (setq files (symbol-value files))))
10879 (if (stringp files) (setq files (list files)))
10880 (cond
10881 ((eq (car desc) :tag)
10882 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10883 ((eq (car desc) :todo)
10884 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10885 ((eq (car desc) :regexp)
10886 (setq descre (cdr desc)))
10887 ((eq (car desc) :level)
10888 (setq descre (concat "^\\*\\{" (number-to-string
10889 (if org-odd-levels-only
10890 (1- (* 2 (cdr desc)))
10891 (cdr desc)))
10892 "\\}[ \t]")))
10893 ((eq (car desc) :maxlevel)
10894 (setq fast-path-p t)
10895 (setq descre (concat "^\\*\\{1," (number-to-string
10896 (if org-odd-levels-only
10897 (1- (* 2 (cdr desc)))
10898 (cdr desc)))
10899 "\\}[ \t]")))
10900 (t (error "Bad refiling target description %s" desc)))
10901 (while (setq f (pop files))
10902 (with-current-buffer
10903 (if (bufferp f) f (org-get-agenda-file-buffer f))
10905 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10906 (progn
10907 (if (bufferp f) (setq f (buffer-file-name
10908 (buffer-base-buffer f))))
10909 (setq f (and f (expand-file-name f)))
10910 (if (eq org-refile-use-outline-path 'file)
10911 (push (list (file-name-nondirectory f) f nil nil) tgs))
10912 (save-excursion
10913 (save-restriction
10914 (widen)
10915 (goto-char (point-min))
10916 (while (re-search-forward descre nil t)
10917 (goto-char (setq pos0 (point-at-bol)))
10918 (catch 'next
10919 (when org-refile-target-verify-function
10920 (save-match-data
10921 (or (funcall org-refile-target-verify-function)
10922 (throw 'next t))))
10923 (when (and (looking-at org-complex-heading-regexp)
10924 (not (member (match-string 4) excluded-entries))
10925 (match-string 4))
10926 (setq level (org-reduced-level
10927 (- (match-end 1) (match-beginning 1)))
10928 txt (org-link-display-format (match-string 4))
10929 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10930 re (format org-complex-heading-regexp-format
10931 (regexp-quote (match-string 4))))
10932 (when org-refile-use-outline-path
10933 (setq txt (mapconcat
10934 'org-protect-slash
10935 (append
10936 (if (eq org-refile-use-outline-path
10937 'file)
10938 (list (file-name-nondirectory
10939 (buffer-file-name
10940 (buffer-base-buffer))))
10941 (if (eq org-refile-use-outline-path
10942 'full-file-path)
10943 (list (buffer-file-name
10944 (buffer-base-buffer)))))
10945 (org-get-outline-path fast-path-p
10946 level txt)
10947 (list txt))
10948 "/")))
10949 (push (list txt f re (org-refile-marker (point)))
10950 tgs)))
10951 (when (= (point) pos0)
10952 ;; verification function has not moved point
10953 (goto-char (point-at-eol))))))))
10954 (when org-refile-use-cache
10955 (org-refile-cache-put tgs (buffer-file-name) descre))
10956 (setq targets (append tgs targets))
10957 ))))
10958 (message "Getting targets...done")
10959 (nreverse targets)))
10961 (defun org-protect-slash (s)
10962 (while (string-match "/" s)
10963 (setq s (replace-match "\\" t t s)))
10966 (defvar org-olpa (make-vector 20 nil))
10968 (defun org-get-outline-path (&optional fastp level heading)
10969 "Return the outline path to the current entry, as a list.
10971 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10972 routine which makes outline path derivations for an entire file,
10973 avoiding backtracing. Refile target collection makes use of that."
10974 (if fastp
10975 (progn
10976 (if (> level 19)
10977 (error "Outline path failure, more than 19 levels"))
10978 (loop for i from level upto 19 do
10979 (aset org-olpa i nil))
10980 (prog1
10981 (delq nil (append org-olpa nil))
10982 (aset org-olpa level heading)))
10983 (let (rtn case-fold-search)
10984 (save-excursion
10985 (save-restriction
10986 (widen)
10987 (while (org-up-heading-safe)
10988 (when (looking-at org-complex-heading-regexp)
10989 (push (org-match-string-no-properties 4) rtn)))
10990 rtn)))))
10992 (defun org-format-outline-path (path &optional width prefix separator)
10993 "Format the outline path PATH for display.
10994 WIDTH is the maximum number of characters that is available.
10995 PREFIX is a prefix to be included in the returned string,
10996 such as the file name.
10997 SEPARATOR is inserted between the different parts of the path,
10998 the default is \"/\"."
10999 (setq width (or width 79))
11000 (if prefix (setq width (- width (length prefix))))
11001 (if (not path)
11002 (or prefix "")
11003 (let* ((nsteps (length path))
11004 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11005 (maxwidth (if (<= total-width width)
11006 10000 ;; everything fits
11007 ;; we need to shorten the level headings
11008 (/ (- width nsteps) nsteps)))
11009 (org-odd-levels-only nil)
11010 (n 0)
11011 (total (1+ (length prefix))))
11012 (setq maxwidth (max maxwidth 10))
11013 (concat prefix
11014 (if prefix (or separator "/"))
11015 (mapconcat
11016 (lambda (h)
11017 (setq n (1+ n))
11018 (if (and (= n nsteps) (< maxwidth 10000))
11019 (setq maxwidth (- total-width total)))
11020 (if (< (length h) maxwidth)
11021 (progn (setq total (+ total (length h) 1)) h)
11022 (setq h (substring h 0 (- maxwidth 2))
11023 total (+ total maxwidth 1))
11024 (if (string-match "[ \t]+\\'" h)
11025 (setq h (substring h 0 (match-beginning 0))))
11026 (setq h (concat h "..")))
11027 (org-add-props h nil 'face
11028 (nth (% (1- n) org-n-level-faces)
11029 org-level-faces))
11031 path (or separator "/"))))))
11033 (defun org-display-outline-path (&optional file current separator just-return-string)
11034 "Display the current outline path in the echo area.
11036 If FILE is non-nil, prepend the output with the file name.
11037 If CURRENT is non-nil, append the current heading to the output.
11038 SEPARATOR is passed through to `org-format-outline-path'. It separates
11039 the different parts of the path and defaults to \"/\".
11040 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11041 (interactive "P")
11042 (let* (case-fold-search
11043 message-log-max ; Don't populate the *Messages* buffer
11044 (bfn (buffer-file-name (buffer-base-buffer)))
11045 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11046 res)
11047 (if current (setq path (append path
11048 (save-excursion
11049 (org-back-to-heading t)
11050 (if (looking-at org-complex-heading-regexp)
11051 (list (match-string 4)))))))
11052 (setq res
11053 (org-format-outline-path
11054 path
11055 (1- (frame-width))
11056 (and file bfn (concat (file-name-nondirectory bfn) separator))
11057 separator))
11058 (if just-return-string
11059 (org-no-properties res)
11060 (message "%s" res))))
11062 (defvar org-refile-history nil
11063 "History for refiling operations.")
11065 (defvar org-after-refile-insert-hook nil
11066 "Hook run after `org-refile' has inserted its stuff at the new location.
11067 Note that this is still *before* the stuff will be removed from
11068 the *old* location.")
11070 (defvar org-capture-last-stored-marker)
11071 (defvar org-refile-keep nil
11072 "Non-nil means `org-refile' will copy instead of refile.")
11074 (defun org-copy ()
11075 "Like `org-refile', but copy."
11076 (interactive)
11077 (let ((org-refile-keep t))
11078 (funcall 'org-refile nil nil nil "Copy")))
11080 (defun org-refile (&optional goto default-buffer rfloc msg)
11081 "Move the entry or entries at point to another heading.
11082 The list of target headings is compiled using the information in
11083 `org-refile-targets', which see.
11085 At the target location, the entry is filed as a subitem of the target
11086 heading. Depending on `org-reverse-note-order', the new subitem will
11087 either be the first or the last subitem.
11089 If there is an active region, all entries in that region will be moved.
11090 However, the region must fulfill the requirement that the first heading
11091 is the first one sets the top-level of the moved text - at most siblings
11092 below it are allowed.
11094 With prefix arg GOTO, the command will only visit the target location
11095 and not actually move anything.
11097 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11098 go to the location where the last refiling operation has put the subtree.
11099 With a prefix argument of `2', refile to the running clock.
11101 RFLOC can be a refile location obtained in a different way.
11103 MSG is a string to replace \"Refile\" in the default prompt with
11104 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11106 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11108 If you are using target caching (see `org-refile-use-cache'),
11109 you have to clear the target cache in order to find new targets.
11110 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11111 prefix argument (`C-u C-u C-u C-c C-w')."
11113 (interactive "P")
11114 (if (member goto '(0 (64)))
11115 (org-refile-cache-clear)
11116 (let* ((actionmsg (or msg "Refile"))
11117 (cbuf (current-buffer))
11118 (regionp (org-region-active-p))
11119 (region-start (and regionp (region-beginning)))
11120 (region-end (and regionp (region-end)))
11121 (region-length (and regionp (- region-end region-start)))
11122 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11123 pos it nbuf file re level reversed)
11124 (setq last-command nil)
11125 (when regionp
11126 (goto-char region-start)
11127 (or (bolp) (goto-char (point-at-bol)))
11128 (setq region-start (point))
11129 (unless (or (org-kill-is-subtree-p
11130 (buffer-substring region-start region-end))
11131 (prog1 org-refile-active-region-within-subtree
11132 (org-toggle-heading)))
11133 (error "The region is not a (sequence of) subtree(s)")))
11134 (if (equal goto '(16))
11135 (org-refile-goto-last-stored)
11136 (when (or
11137 (and (equal goto 2)
11138 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11139 (prog1
11140 (setq it (list (or org-clock-heading "running clock")
11141 (buffer-file-name
11142 (marker-buffer org-clock-hd-marker))
11144 (marker-position org-clock-hd-marker)))
11145 (setq goto nil)))
11146 (setq it (or rfloc
11147 (let (heading-text)
11148 (save-excursion
11149 (unless goto
11150 (org-back-to-heading t)
11151 (setq heading-text
11152 (nth 4 (org-heading-components))))
11154 (org-refile-get-location
11155 (cond (goto "Goto")
11156 (regionp (concat actionmsg " region to"))
11157 (t (concat actionmsg " subtree \""
11158 heading-text "\" to")))
11159 default-buffer
11160 (and (not (equal '(4) goto))
11161 org-refile-allow-creating-parent-nodes)
11162 goto))))))
11163 (setq file (nth 1 it)
11164 re (nth 2 it)
11165 pos (nth 3 it))
11166 (if (and (not goto)
11168 (equal (buffer-file-name) file)
11169 (if regionp
11170 (and (>= pos region-start)
11171 (<= pos region-end))
11172 (and (>= pos (point))
11173 (< pos (save-excursion
11174 (org-end-of-subtree t t))))))
11175 (error "Cannot refile to position inside the tree or region"))
11177 (setq nbuf (or (find-buffer-visiting file)
11178 (find-file-noselect file)))
11179 (if goto
11180 (progn
11181 (org-pop-to-buffer-same-window nbuf)
11182 (goto-char pos)
11183 (org-show-context 'org-goto))
11184 (if regionp
11185 (progn
11186 (org-kill-new (buffer-substring region-start region-end))
11187 (org-save-markers-in-region region-start region-end))
11188 (org-copy-subtree 1 nil t))
11189 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11190 (find-file-noselect file)))
11191 (setq reversed (org-notes-order-reversed-p))
11192 (save-excursion
11193 (save-restriction
11194 (widen)
11195 (if pos
11196 (progn
11197 (goto-char pos)
11198 (looking-at org-outline-regexp)
11199 (setq level (org-get-valid-level (funcall outline-level) 1))
11200 (goto-char
11201 (if reversed
11202 (or (outline-next-heading) (point-max))
11203 (or (save-excursion (org-get-next-sibling))
11204 (org-end-of-subtree t t)
11205 (point-max)))))
11206 (setq level 1)
11207 (if (not reversed)
11208 (goto-char (point-max))
11209 (goto-char (point-min))
11210 (or (outline-next-heading) (goto-char (point-max)))))
11211 (if (not (bolp)) (newline))
11212 (org-paste-subtree level)
11213 (when org-log-refile
11214 (org-add-log-setup 'refile nil nil 'findpos
11215 org-log-refile)
11216 (unless (eq org-log-refile 'note)
11217 (save-excursion (org-add-log-note))))
11218 (and org-auto-align-tags
11219 (let ((org-loop-over-headlines-in-active-region nil))
11220 (org-set-tags nil t)))
11221 (with-demoted-errors
11222 (bookmark-set "org-refile-last-stored"))
11223 ;; If we are refiling for capture, make sure that the
11224 ;; last-capture pointers point here
11225 (when (org-bound-and-true-p org-refile-for-capture)
11226 (with-demoted-errors
11227 (bookmark-set "org-capture-last-stored-marker"))
11228 (move-marker org-capture-last-stored-marker (point)))
11229 (if (fboundp 'deactivate-mark) (deactivate-mark))
11230 (run-hooks 'org-after-refile-insert-hook))))
11231 (unless org-refile-keep
11232 (if regionp
11233 (delete-region (point) (+ (point) region-length))
11234 (org-cut-subtree)))
11235 (when (featurep 'org-inlinetask)
11236 (org-inlinetask-remove-END-maybe))
11237 (setq org-markers-to-move nil)
11238 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11240 (defun org-refile-goto-last-stored ()
11241 "Go to the location where the last refile was stored."
11242 (interactive)
11243 (bookmark-jump "org-refile-last-stored")
11244 (message "This is the location of the last refile"))
11246 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11247 no-exclude)
11248 "Prompt the user for a refile location, using PROMPT.
11249 PROMPT should not be suffixed with a colon and a space, because
11250 this function appends the default value from
11251 `org-refile-history' automatically, if that is not empty.
11252 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11253 this is used for the GOTO interface."
11254 (let ((org-refile-targets org-refile-targets)
11255 (org-refile-use-outline-path org-refile-use-outline-path)
11256 excluded-entries)
11257 (when (and (derived-mode-p 'org-mode)
11258 (not org-refile-use-cache)
11259 (not no-exclude))
11260 (org-map-tree
11261 (lambda()
11262 (setq excluded-entries
11263 (append excluded-entries (list (org-get-heading t t)))))))
11264 (setq org-refile-target-table
11265 (org-refile-get-targets default-buffer excluded-entries)))
11266 (unless org-refile-target-table
11267 (error "No refile targets"))
11268 (let* ((cbuf (current-buffer))
11269 (partial-completion-mode nil)
11270 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11271 (cfunc (if (and org-refile-use-outline-path
11272 org-outline-path-complete-in-steps)
11273 'org-olpath-completing-read
11274 'org-icompleting-read))
11275 (extra (if org-refile-use-outline-path "/" ""))
11276 (cbnex (concat (buffer-name) extra))
11277 (filename (and cfn (expand-file-name cfn)))
11278 (tbl (mapcar
11279 (lambda (x)
11280 (if (and (not (member org-refile-use-outline-path
11281 '(file full-file-path)))
11282 (not (equal filename (nth 1 x))))
11283 (cons (concat (car x) extra " ("
11284 (file-name-nondirectory (nth 1 x)) ")")
11285 (cdr x))
11286 (cons (concat (car x) extra) (cdr x))))
11287 org-refile-target-table))
11288 (completion-ignore-case t)
11289 cdef
11290 (prompt (concat prompt
11291 (or (and (car org-refile-history)
11292 (concat " (default " (car org-refile-history) ")"))
11293 (and (assoc cbnex tbl) (setq cdef cbnex)
11294 (concat " (default " cbnex ")"))) ": "))
11295 pa answ parent-target child parent old-hist)
11296 (setq old-hist org-refile-history)
11297 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11298 nil 'org-refile-history (or cdef (car org-refile-history))))
11299 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11300 (org-refile-check-position pa)
11301 (if pa
11302 (progn
11303 (when (or (not org-refile-history)
11304 (not (eq old-hist org-refile-history))
11305 (not (equal (car pa) (car org-refile-history))))
11306 (setq org-refile-history
11307 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11308 org-refile-history
11309 (cdr org-refile-history))))
11310 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11311 (pop org-refile-history)))
11313 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11314 (progn
11315 (setq parent (match-string 1 answ)
11316 child (match-string 2 answ))
11317 (setq parent-target (or (assoc parent tbl)
11318 (assoc (concat parent "/") tbl)))
11319 (when (and parent-target
11320 (or (eq new-nodes t)
11321 (and (eq new-nodes 'confirm)
11322 (y-or-n-p (format "Create new node \"%s\"? "
11323 child)))))
11324 (org-refile-new-child parent-target child)))
11325 (error "Invalid target location")))))
11327 (declare-function org-string-nw-p "org-macs" (s))
11328 (defun org-refile-check-position (refile-pointer)
11329 "Check if the refile pointer matches the headline to which it points."
11330 (let* ((file (nth 1 refile-pointer))
11331 (re (nth 2 refile-pointer))
11332 (pos (nth 3 refile-pointer))
11333 buffer)
11334 (if (and (not (markerp pos)) (not file))
11335 (error "Please save the buffer to a file before refiling")
11336 (when (org-string-nw-p re)
11337 (setq buffer (if (markerp pos)
11338 (marker-buffer pos)
11339 (or (find-buffer-visiting file)
11340 (find-file-noselect file))))
11341 (with-current-buffer buffer
11342 (save-excursion
11343 (save-restriction
11344 (widen)
11345 (goto-char pos)
11346 (beginning-of-line 1)
11347 (unless (org-looking-at-p re)
11348 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11350 (defun org-refile-new-child (parent-target child)
11351 "Use refile target PARENT-TARGET to add new CHILD below it."
11352 (unless parent-target
11353 (error "Cannot find parent for new node"))
11354 (let ((file (nth 1 parent-target))
11355 (pos (nth 3 parent-target))
11356 level)
11357 (with-current-buffer (or (find-buffer-visiting file)
11358 (find-file-noselect file))
11359 (save-excursion
11360 (save-restriction
11361 (widen)
11362 (if pos
11363 (goto-char pos)
11364 (goto-char (point-max))
11365 (if (not (bolp)) (newline)))
11366 (when (looking-at org-outline-regexp)
11367 (setq level (funcall outline-level))
11368 (org-end-of-subtree t t))
11369 (org-back-over-empty-lines)
11370 (insert "\n" (make-string
11371 (if pos (org-get-valid-level level 1) 1) ?*)
11372 " " child "\n")
11373 (beginning-of-line 0)
11374 (list (concat (car parent-target) "/" child) file "" (point)))))))
11376 (defun org-olpath-completing-read (prompt collection &rest args)
11377 "Read an outline path like a file name."
11378 (let ((thetable collection)
11379 (org-completion-use-ido nil) ; does not work with ido.
11380 (org-completion-use-iswitchb nil)) ; or iswitchb
11381 (apply
11382 'org-icompleting-read prompt
11383 (lambda (string predicate &optional flag)
11384 (let (rtn r f (l (length string)))
11385 (cond
11386 ((eq flag nil)
11387 ;; try completion
11388 (try-completion string thetable))
11389 ((eq flag t)
11390 ;; all-completions
11391 (setq rtn (all-completions string thetable predicate))
11392 (mapcar
11393 (lambda (x)
11394 (setq r (substring x l))
11395 (if (string-match " ([^)]*)$" x)
11396 (setq f (match-string 0 x))
11397 (setq f ""))
11398 (if (string-match "/" r)
11399 (concat string (substring r 0 (match-end 0)) f)
11401 rtn))
11402 ((eq flag 'lambda)
11403 ;; exact match?
11404 (assoc string thetable)))))
11405 args)))
11407 ;;;; Dynamic blocks
11409 (defun org-find-dblock (name)
11410 "Find the first dynamic block with name NAME in the buffer.
11411 If not found, stay at current position and return nil."
11412 (let ((case-fold-search t) pos)
11413 (save-excursion
11414 (goto-char (point-min))
11415 (setq pos (and (re-search-forward
11416 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11417 (match-beginning 0))))
11418 (if pos (goto-char pos))
11419 pos))
11421 (defconst org-dblock-start-re
11422 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11423 "Matches the start line of a dynamic block, with parameters.")
11425 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11426 "Matches the end of a dynamic block.")
11428 (defun org-create-dblock (plist)
11429 "Create a dynamic block section, with parameters taken from PLIST.
11430 PLIST must contain a :name entry which is used as name of the block."
11431 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11432 (end-of-line 1)
11433 (newline))
11434 (let ((col (current-column))
11435 (name (plist-get plist :name)))
11436 (insert "#+BEGIN: " name)
11437 (while plist
11438 (if (eq (car plist) :name)
11439 (setq plist (cddr plist))
11440 (insert " " (prin1-to-string (pop plist)))))
11441 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11442 (beginning-of-line -2)))
11444 (defun org-prepare-dblock ()
11445 "Prepare dynamic block for refresh.
11446 This empties the block, puts the cursor at the insert position and returns
11447 the property list including an extra property :name with the block name."
11448 (unless (looking-at org-dblock-start-re)
11449 (error "Not at a dynamic block"))
11450 (let* ((begdel (1+ (match-end 0)))
11451 (name (org-no-properties (match-string 1)))
11452 (params (append (list :name name)
11453 (read (concat "(" (match-string 3) ")")))))
11454 (save-excursion
11455 (beginning-of-line 1)
11456 (skip-chars-forward " \t")
11457 (setq params (plist-put params :indentation-column (current-column))))
11458 (unless (re-search-forward org-dblock-end-re nil t)
11459 (error "Dynamic block not terminated"))
11460 (setq params
11461 (append params
11462 (list :content (buffer-substring
11463 begdel (match-beginning 0)))))
11464 (delete-region begdel (match-beginning 0))
11465 (goto-char begdel)
11466 (open-line 1)
11467 params))
11469 (defun org-map-dblocks (&optional command)
11470 "Apply COMMAND to all dynamic blocks in the current buffer.
11471 If COMMAND is not given, use `org-update-dblock'."
11472 (let ((cmd (or command 'org-update-dblock)))
11473 (save-excursion
11474 (goto-char (point-min))
11475 (while (re-search-forward org-dblock-start-re nil t)
11476 (goto-char (match-beginning 0))
11477 (save-excursion
11478 (condition-case nil
11479 (funcall cmd)
11480 (error (message "Error during update of dynamic block"))))
11481 (unless (re-search-forward org-dblock-end-re nil t)
11482 (error "Dynamic block not terminated"))))))
11484 (defun org-dblock-update (&optional arg)
11485 "User command for updating dynamic blocks.
11486 Update the dynamic block at point. With prefix ARG, update all dynamic
11487 blocks in the buffer."
11488 (interactive "P")
11489 (if arg
11490 (org-update-all-dblocks)
11491 (or (looking-at org-dblock-start-re)
11492 (org-beginning-of-dblock))
11493 (org-update-dblock)))
11495 (defun org-update-dblock ()
11496 "Update the dynamic block at point.
11497 This means to empty the block, parse for parameters and then call
11498 the correct writing function."
11499 (interactive)
11500 (save-window-excursion
11501 (let* ((pos (point))
11502 (line (org-current-line))
11503 (params (org-prepare-dblock))
11504 (name (plist-get params :name))
11505 (indent (plist-get params :indentation-column))
11506 (cmd (intern (concat "org-dblock-write:" name))))
11507 (message "Updating dynamic block `%s' at line %d..." name line)
11508 (funcall cmd params)
11509 (message "Updating dynamic block `%s' at line %d...done" name line)
11510 (goto-char pos)
11511 (when (and indent (> indent 0))
11512 (setq indent (make-string indent ?\ ))
11513 (save-excursion
11514 (org-beginning-of-dblock)
11515 (forward-line 1)
11516 (while (not (looking-at org-dblock-end-re))
11517 (insert indent)
11518 (beginning-of-line 2))
11519 (when (looking-at org-dblock-end-re)
11520 (and (looking-at "[ \t]+")
11521 (replace-match ""))
11522 (insert indent)))))))
11524 (defun org-beginning-of-dblock ()
11525 "Find the beginning of the dynamic block at point.
11526 Error if there is no such block at point."
11527 (let ((pos (point))
11528 beg)
11529 (end-of-line 1)
11530 (if (and (re-search-backward org-dblock-start-re nil t)
11531 (setq beg (match-beginning 0))
11532 (re-search-forward org-dblock-end-re nil t)
11533 (> (match-end 0) pos))
11534 (goto-char beg)
11535 (goto-char pos)
11536 (error "Not in a dynamic block"))))
11538 (defun org-update-all-dblocks ()
11539 "Update all dynamic blocks in the buffer.
11540 This function can be used in a hook."
11541 (interactive)
11542 (when (derived-mode-p 'org-mode)
11543 (org-map-dblocks 'org-update-dblock)))
11546 ;;;; Completion
11548 (defun org-get-export-keywords ()
11549 "Return a list of all currently understood export keywords.
11550 Export keywords include options, block names, attributes and
11551 keywords relative to each registered export back-end."
11552 (delq nil
11553 (let (keywords)
11554 (mapc
11555 (lambda (back-end)
11556 (let ((props (cdr back-end)))
11557 ;; Back-end name (for keywords, like #+LATEX:)
11558 (push (upcase (symbol-name (car back-end))) keywords)
11559 ;; Back-end options.
11560 (mapc (lambda (option) (push (cadr option) keywords))
11561 (plist-get (cdr back-end) :options-alist))))
11562 (org-bound-and-true-p org-export-registered-backends))
11563 keywords)))
11565 (defconst org-options-keywords
11566 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11567 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11568 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11569 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11570 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11572 (defcustom org-structure-template-alist
11573 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11574 "<src lang=\"?\">\n\n</src>")
11575 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11576 "<example>\n?\n</example>")
11577 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11578 "<quote>\n?\n</quote>")
11579 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11580 "<verse>\n?\n</verse>")
11581 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11582 "<verbatim>\n?\n</verbatim>")
11583 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11584 "<center>\n?\n</center>")
11585 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11586 "<literal style=\"latex\">\n?\n</literal>")
11587 ("L" "#+LaTeX: "
11588 "<literal style=\"latex\">?</literal>")
11589 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11590 "<literal style=\"html\">\n?\n</literal>")
11591 ("H" "#+HTML: "
11592 "<literal style=\"html\">?</literal>")
11593 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11594 ("A" "#+ASCII: ")
11595 ("i" "#+INDEX: ?"
11596 "#+INDEX: ?")
11597 ("I" "#+INCLUDE: %file ?"
11598 "<include file=%file markup=\"?\">"))
11599 "Structure completion elements.
11600 This is a list of abbreviation keys and values. The value gets inserted
11601 if you type `<' followed by the key and then press the completion key,
11602 usually `M-TAB'. %file will be replaced by a file name after prompting
11603 for the file using completion. The cursor will be placed at the position
11604 of the `?` in the template.
11605 There are two templates for each key, the first uses the original Org syntax,
11606 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11607 the default when the /org-mtags.el/ module has been loaded. See also the
11608 variable `org-mtags-prefer-muse-templates'."
11609 :group 'org-completion
11610 :type '(repeat
11611 (string :tag "Key")
11612 (string :tag "Template")
11613 (string :tag "Muse Template")))
11615 (defun org-try-structure-completion ()
11616 "Try to complete a structure template before point.
11617 This looks for strings like \"<e\" on an otherwise empty line and
11618 expands them."
11619 (let ((l (buffer-substring (point-at-bol) (point)))
11621 (when (and (looking-at "[ \t]*$")
11622 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11623 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11624 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11625 (match-beginning 1)) a)
11626 t)))
11628 (defun org-complete-expand-structure-template (start cell)
11629 "Expand a structure template."
11630 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11631 (rpl (nth (if musep 2 1) cell))
11632 (ind ""))
11633 (delete-region start (point))
11634 (when (string-match "\\`#\\+" rpl)
11635 (cond
11636 ((bolp))
11637 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11638 (setq ind (buffer-substring (point-at-bol) (point))))
11639 (t (newline))))
11640 (setq start (point))
11641 (if (string-match "%file" rpl)
11642 (setq rpl (replace-match
11643 (concat
11644 "\""
11645 (save-match-data
11646 (abbreviate-file-name (read-file-name "Include file: ")))
11647 "\"")
11648 t t rpl)))
11649 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11650 (concat "\n" ind)))
11651 (insert rpl)
11652 (if (re-search-backward "\\?" start t) (delete-char 1))))
11654 ;;;; TODO, DEADLINE, Comments
11656 (defun org-toggle-comment ()
11657 "Change the COMMENT state of an entry."
11658 (interactive)
11659 (save-excursion
11660 (org-back-to-heading)
11661 (let (case-fold-search)
11662 (cond
11663 ((looking-at (format org-heading-keyword-regexp-format
11664 org-comment-string))
11665 (goto-char (match-end 1))
11666 (looking-at (concat " +" org-comment-string))
11667 (replace-match "" t t)
11668 (when (eolp) (insert " ")))
11669 ((looking-at org-outline-regexp)
11670 (goto-char (match-end 0))
11671 (insert org-comment-string " "))))))
11673 (defvar org-last-todo-state-is-todo nil
11674 "This is non-nil when the last TODO state change led to a TODO state.
11675 If the last change removed the TODO tag or switched to DONE, then
11676 this is nil.")
11678 (defvar org-setting-tags nil) ; dynamically skipped
11680 (defvar org-todo-setup-filter-hook nil
11681 "Hook for functions that pre-filter todo specs.
11682 Each function takes a todo spec and returns either nil or the spec
11683 transformed into canonical form." )
11685 (defvar org-todo-get-default-hook nil
11686 "Hook for functions that get a default item for todo.
11687 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11688 nil or a string to be used for the todo mark." )
11690 (defvar org-agenda-headline-snapshot-before-repeat)
11692 (defun org-current-effective-time ()
11693 "Return current time adjusted for `org-extend-today-until' variable."
11694 (let* ((ct (org-current-time))
11695 (dct (decode-time ct))
11696 (ct1
11697 (cond
11698 (org-use-last-clock-out-time-as-effective-time
11699 (or (org-clock-get-last-clock-out-time) ct))
11700 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11701 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11702 (t ct))))
11703 ct1))
11705 (defun org-todo-yesterday (&optional arg)
11706 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11707 (interactive "P")
11708 (if (eq major-mode 'org-agenda-mode)
11709 (apply 'org-agenda-todo-yesterday arg)
11710 (let* ((hour (third (decode-time
11711 (org-current-time))))
11712 (org-extend-today-until (1+ hour)))
11713 (org-todo arg))))
11715 (defvar org-block-entry-blocking ""
11716 "First entry preventing the TODO state change.")
11718 (defun org-todo (&optional arg)
11719 "Change the TODO state of an item.
11720 The state of an item is given by a keyword at the start of the heading,
11721 like
11722 *** TODO Write paper
11723 *** DONE Call mom
11725 The different keywords are specified in the variable `org-todo-keywords'.
11726 By default the available states are \"TODO\" and \"DONE\".
11727 So for this example: when the item starts with TODO, it is changed to DONE.
11728 When it starts with DONE, the DONE is removed. And when neither TODO nor
11729 DONE are present, add TODO at the beginning of the heading.
11731 With \\[universal-argument] prefix arg, use completion to determine the new \
11732 state.
11733 With numeric prefix arg, switch to that state.
11734 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11735 keywords (nextset).
11736 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11737 With a numeric prefix arg of 0, inhibit note taking for the change.
11739 For calling through lisp, arg is also interpreted in the following way:
11740 'none -> empty state
11741 \"\"(empty string) -> switch to empty state
11742 'done -> switch to DONE
11743 'nextset -> switch to the next set of keywords
11744 'previousset -> switch to the previous set of keywords
11745 \"WAITING\" -> switch to the specified keyword, but only if it
11746 really is a member of `org-todo-keywords'."
11747 (interactive "P")
11748 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11749 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11750 'region-start-level 'region))
11751 org-loop-over-headlines-in-active-region)
11752 (org-map-entries
11753 `(org-todo ,arg)
11754 org-loop-over-headlines-in-active-region
11755 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11756 (if (equal arg '(16)) (setq arg 'nextset))
11757 (let ((org-blocker-hook org-blocker-hook)
11758 commentp
11759 case-fold-search)
11760 (when (equal arg '(64))
11761 (setq arg nil org-blocker-hook nil))
11762 (when (and org-blocker-hook
11763 (or org-inhibit-blocking
11764 (org-entry-get nil "NOBLOCKING")))
11765 (setq org-blocker-hook nil))
11766 (save-excursion
11767 (catch 'exit
11768 (org-back-to-heading t)
11769 (when (looking-at (concat "^\\*+ " org-comment-string))
11770 (org-toggle-comment)
11771 (setq commentp t))
11772 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11773 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11774 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11775 (let* ((match-data (match-data))
11776 (startpos (point-at-bol))
11777 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11778 (org-log-done org-log-done)
11779 (org-log-repeat org-log-repeat)
11780 (org-todo-log-states org-todo-log-states)
11781 (org-inhibit-logging
11782 (if (equal arg 0)
11783 (progn (setq arg nil) 'note) org-inhibit-logging))
11784 (this (match-string 1))
11785 (hl-pos (match-beginning 0))
11786 (head (org-get-todo-sequence-head this))
11787 (ass (assoc head org-todo-kwd-alist))
11788 (interpret (nth 1 ass))
11789 (done-word (nth 3 ass))
11790 (final-done-word (nth 4 ass))
11791 (org-last-state (or this ""))
11792 (completion-ignore-case t)
11793 (member (member this org-todo-keywords-1))
11794 (tail (cdr member))
11795 (org-state (cond
11796 ((and org-todo-key-trigger
11797 (or (and (equal arg '(4))
11798 (eq org-use-fast-todo-selection 'prefix))
11799 (and (not arg) org-use-fast-todo-selection
11800 (not (eq org-use-fast-todo-selection
11801 'prefix)))))
11802 ;; Use fast selection
11803 (org-fast-todo-selection))
11804 ((and (equal arg '(4))
11805 (or (not org-use-fast-todo-selection)
11806 (not org-todo-key-trigger)))
11807 ;; Read a state with completion
11808 (org-icompleting-read
11809 "State: " (mapcar (lambda(x) (list x))
11810 org-todo-keywords-1)
11811 nil t))
11812 ((eq arg 'right)
11813 (if this
11814 (if tail (car tail) nil)
11815 (car org-todo-keywords-1)))
11816 ((eq arg 'left)
11817 (if (equal member org-todo-keywords-1)
11819 (if this
11820 (nth (- (length org-todo-keywords-1)
11821 (length tail) 2)
11822 org-todo-keywords-1)
11823 (org-last org-todo-keywords-1))))
11824 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11825 (setq arg nil))) ; hack to fall back to cycling
11826 (arg
11827 ;; user or caller requests a specific state
11828 (cond
11829 ((equal arg "") nil)
11830 ((eq arg 'none) nil)
11831 ((eq arg 'done) (or done-word (car org-done-keywords)))
11832 ((eq arg 'nextset)
11833 (or (car (cdr (member head org-todo-heads)))
11834 (car org-todo-heads)))
11835 ((eq arg 'previousset)
11836 (let ((org-todo-heads (reverse org-todo-heads)))
11837 (or (car (cdr (member head org-todo-heads)))
11838 (car org-todo-heads))))
11839 ((car (member arg org-todo-keywords-1)))
11840 ((stringp arg)
11841 (error "State `%s' not valid in this file" arg))
11842 ((nth (1- (prefix-numeric-value arg))
11843 org-todo-keywords-1))))
11844 ((null member) (or head (car org-todo-keywords-1)))
11845 ((equal this final-done-word) nil) ;; -> make empty
11846 ((null tail) nil) ;; -> first entry
11847 ((memq interpret '(type priority))
11848 (if (eq this-command last-command)
11849 (car tail)
11850 (if (> (length tail) 0)
11851 (or done-word (car org-done-keywords))
11852 nil)))
11854 (car tail))))
11855 (org-state (or
11856 (run-hook-with-args-until-success
11857 'org-todo-get-default-hook org-state org-last-state)
11858 org-state))
11859 (next (if org-state (concat " " org-state " ") " "))
11860 (change-plist (list :type 'todo-state-change :from this :to org-state
11861 :position startpos))
11862 dolog now-done-p)
11863 (when org-blocker-hook
11864 (setq org-last-todo-state-is-todo
11865 (not (member this org-done-keywords)))
11866 (unless (save-excursion
11867 (save-match-data
11868 (org-with-wide-buffer
11869 (run-hook-with-args-until-failure
11870 'org-blocker-hook change-plist))))
11871 (if (org-called-interactively-p 'interactive)
11872 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11873 this org-state org-block-entry-blocking)
11874 ;; fail silently
11875 (message "TODO state change from %s to %s blocked (by \"%s\")"
11876 this org-state org-block-entry-blocking)
11877 (throw 'exit nil))))
11878 (store-match-data match-data)
11879 (replace-match next t t)
11880 (unless (pos-visible-in-window-p hl-pos)
11881 (message "TODO state changed to %s" (org-trim next)))
11882 (unless head
11883 (setq head (org-get-todo-sequence-head org-state)
11884 ass (assoc head org-todo-kwd-alist)
11885 interpret (nth 1 ass)
11886 done-word (nth 3 ass)
11887 final-done-word (nth 4 ass)))
11888 (when (memq arg '(nextset previousset))
11889 (message "Keyword-Set %d/%d: %s"
11890 (- (length org-todo-sets) -1
11891 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11892 (length org-todo-sets)
11893 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11894 (setq org-last-todo-state-is-todo
11895 (not (member org-state org-done-keywords)))
11896 (setq now-done-p (and (member org-state org-done-keywords)
11897 (not (member this org-done-keywords))))
11898 (and logging (org-local-logging logging))
11899 (when (and (or org-todo-log-states org-log-done)
11900 (not (eq org-inhibit-logging t))
11901 (not (memq arg '(nextset previousset))))
11902 ;; we need to look at recording a time and note
11903 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11904 (nth 2 (assoc this org-todo-log-states))))
11905 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11906 (setq dolog 'time))
11907 (when (and org-state
11908 (member org-state org-not-done-keywords)
11909 (not (member this org-not-done-keywords)))
11910 ;; This is now a todo state and was not one before
11911 ;; If there was a CLOSED time stamp, get rid of it.
11912 (org-add-planning-info nil nil 'closed))
11913 (when (and now-done-p org-log-done)
11914 ;; It is now done, and it was not done before
11915 (org-add-planning-info 'closed (org-current-effective-time))
11916 (if (and (not dolog) (eq 'note org-log-done))
11917 (org-add-log-setup 'done org-state this 'findpos 'note)))
11918 (when (and org-state dolog)
11919 ;; This is a non-nil state, and we need to log it
11920 (org-add-log-setup 'state org-state this 'findpos dolog)))
11921 ;; Fixup tag positioning
11922 (org-todo-trigger-tag-changes org-state)
11923 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11924 (when org-provide-todo-statistics
11925 (org-update-parent-todo-statistics))
11926 (run-hooks 'org-after-todo-state-change-hook)
11927 (if (and arg (not (member org-state org-done-keywords)))
11928 (setq head (org-get-todo-sequence-head org-state)))
11929 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11930 ;; Do we need to trigger a repeat?
11931 (when now-done-p
11932 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11933 ;; This is for the agenda, take a snapshot of the headline.
11934 (save-match-data
11935 (setq org-agenda-headline-snapshot-before-repeat
11936 (org-get-heading))))
11937 (org-auto-repeat-maybe org-state))
11938 ;; Fixup cursor location if close to the keyword
11939 (if (and (outline-on-heading-p)
11940 (not (bolp))
11941 (save-excursion (beginning-of-line 1)
11942 (looking-at org-todo-line-regexp))
11943 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11944 (progn
11945 (goto-char (or (match-end 2) (match-end 1)))
11946 (and (looking-at " ") (just-one-space))))
11947 (when org-trigger-hook
11948 (save-excursion
11949 (run-hook-with-args 'org-trigger-hook change-plist)))
11950 (when commentp (org-toggle-comment))))))))
11952 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11953 "Block turning an entry into a TODO, using the hierarchy.
11954 This checks whether the current task should be blocked from state
11955 changes. Such blocking occurs when:
11957 1. The task has children which are not all in a completed state.
11959 2. A task has a parent with the property :ORDERED:, and there
11960 are siblings prior to the current task with incomplete
11961 status.
11963 3. The parent of the task is blocked because it has siblings that should
11964 be done first, or is child of a block grandparent TODO entry."
11966 (if (not org-enforce-todo-dependencies)
11967 t ; if locally turned off don't block
11968 (catch 'dont-block
11969 ;; If this is not a todo state change, or if this entry is already DONE,
11970 ;; do not block
11971 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11972 (member (plist-get change-plist :from)
11973 (cons 'done org-done-keywords))
11974 (member (plist-get change-plist :to)
11975 (cons 'todo org-not-done-keywords))
11976 (not (plist-get change-plist :to)))
11977 (throw 'dont-block t))
11978 ;; If this task has children, and any are undone, it's blocked
11979 (save-excursion
11980 (org-back-to-heading t)
11981 (let ((this-level (funcall outline-level)))
11982 (outline-next-heading)
11983 (let ((child-level (funcall outline-level)))
11984 (while (and (not (eobp))
11985 (> child-level this-level))
11986 ;; this todo has children, check whether they are all
11987 ;; completed
11988 (if (and (not (org-entry-is-done-p))
11989 (org-entry-is-todo-p))
11990 (progn (setq org-block-entry-blocking (org-get-heading))
11991 (throw 'dont-block nil)))
11992 (outline-next-heading)
11993 (setq child-level (funcall outline-level))))))
11994 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11995 ;; any previous siblings are undone, it's blocked
11996 (save-excursion
11997 (org-back-to-heading t)
11998 (let* ((pos (point))
11999 (parent-pos (and (org-up-heading-safe) (point))))
12000 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12001 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12002 (forward-line 1)
12003 (re-search-forward org-not-done-heading-regexp pos t))
12004 (setq org-block-entry-blocking (match-string 0))
12005 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12006 ;; Search further up the hierarchy, to see if an ancestor is blocked
12007 (while t
12008 (goto-char parent-pos)
12009 (if (not (looking-at org-not-done-heading-regexp))
12010 (throw 'dont-block t)) ; do not block, parent is not a TODO
12011 (setq pos (point))
12012 (setq parent-pos (and (org-up-heading-safe) (point)))
12013 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12014 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12015 (forward-line 1)
12016 (re-search-forward org-not-done-heading-regexp pos t)
12017 (setq org-block-entry-blocking (org-get-heading)))
12018 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12020 (defcustom org-track-ordered-property-with-tag nil
12021 "Should the ORDERED property also be shown as a tag?
12022 The ORDERED property decides if an entry should require subtasks to be
12023 completed in sequence. Since a property is not very visible, setting
12024 this option means that toggling the ORDERED property with the command
12025 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12026 not relevant for the behavior, but it makes things more visible.
12028 Note that toggling the tag with tags commands will not change the property
12029 and therefore not influence behavior!
12031 This can be t, meaning the tag ORDERED should be used, It can also be a
12032 string to select a different tag for this task."
12033 :group 'org-todo
12034 :type '(choice
12035 (const :tag "No tracking" nil)
12036 (const :tag "Track with ORDERED tag" t)
12037 (string :tag "Use other tag")))
12039 (defun org-toggle-ordered-property ()
12040 "Toggle the ORDERED property of the current entry.
12041 For better visibility, you can track the value of this property with a tag.
12042 See variable `org-track-ordered-property-with-tag'."
12043 (interactive)
12044 (let* ((t1 org-track-ordered-property-with-tag)
12045 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12046 (save-excursion
12047 (org-back-to-heading)
12048 (if (org-entry-get nil "ORDERED")
12049 (progn
12050 (org-delete-property "ORDERED")
12051 (and tag (org-toggle-tag tag 'off))
12052 (message "Subtasks can be completed in arbitrary order"))
12053 (org-entry-put nil "ORDERED" "t")
12054 (and tag (org-toggle-tag tag 'on))
12055 (message "Subtasks must be completed in sequence")))))
12057 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12058 (defun org-block-todo-from-checkboxes (change-plist)
12059 "Block turning an entry into a TODO, using checkboxes.
12060 This checks whether the current task should be blocked from state
12061 changes because there are unchecked boxes in this entry."
12062 (if (not org-enforce-todo-checkbox-dependencies)
12063 t ; if locally turned off don't block
12064 (catch 'dont-block
12065 ;; If this is not a todo state change, or if this entry is already DONE,
12066 ;; do not block
12067 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12068 (member (plist-get change-plist :from)
12069 (cons 'done org-done-keywords))
12070 (member (plist-get change-plist :to)
12071 (cons 'todo org-not-done-keywords))
12072 (not (plist-get change-plist :to)))
12073 (throw 'dont-block t))
12074 ;; If this task has checkboxes that are not checked, it's blocked
12075 (save-excursion
12076 (org-back-to-heading t)
12077 (let ((beg (point)) end)
12078 (outline-next-heading)
12079 (setq end (point))
12080 (goto-char beg)
12081 (if (org-list-search-forward
12082 (concat (org-item-beginning-re)
12083 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12084 "\\[[- ]\\]")
12085 end t)
12086 (progn
12087 (if (boundp 'org-blocked-by-checkboxes)
12088 (setq org-blocked-by-checkboxes t))
12089 (throw 'dont-block nil)))))
12090 t))) ; do not block
12092 (defun org-entry-blocked-p ()
12093 "Is the current entry blocked?"
12094 (org-with-buffer-modified-unmodified
12095 (if (org-entry-get nil "NOBLOCKING")
12096 nil ;; Never block this entry
12097 (not
12098 (run-hook-with-args-until-failure
12099 'org-blocker-hook
12100 (list :type 'todo-state-change
12101 :position (point)
12102 :from 'todo
12103 :to 'done))))))
12105 (defun org-update-statistics-cookies (all)
12106 "Update the statistics cookie, either from TODO or from checkboxes.
12107 This should be called with the cursor in a line with a statistics cookie."
12108 (interactive "P")
12109 (if all
12110 (progn
12111 (org-update-checkbox-count 'all)
12112 (org-map-entries 'org-update-parent-todo-statistics))
12113 (if (not (org-at-heading-p))
12114 (org-update-checkbox-count)
12115 (let ((pos (point-marker))
12116 end l1 l2)
12117 (ignore-errors (org-back-to-heading t))
12118 (if (not (org-at-heading-p))
12119 (org-update-checkbox-count)
12120 (setq l1 (org-outline-level))
12121 (setq end (save-excursion
12122 (outline-next-heading)
12123 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12124 (point)))
12125 (if (and (save-excursion
12126 (re-search-forward
12127 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12128 (not (save-excursion (re-search-forward
12129 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12130 (org-update-checkbox-count)
12131 (if (and l2 (> l2 l1))
12132 (progn
12133 (goto-char end)
12134 (org-update-parent-todo-statistics))
12135 (goto-char pos)
12136 (beginning-of-line 1)
12137 (while (re-search-forward
12138 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12139 (point-at-eol) t)
12140 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12141 (goto-char pos)
12142 (move-marker pos nil)))))
12144 (defvar org-entry-property-inherited-from) ;; defined below
12145 (defun org-update-parent-todo-statistics ()
12146 "Update any statistics cookie in the parent of the current headline.
12147 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12148 the entire subtree and this will travel up the hierarchy and update
12149 statistics everywhere."
12150 (let* ((prop (save-excursion (org-up-heading-safe)
12151 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12152 (recursive (or (not org-hierarchical-todo-statistics)
12153 (and prop (string-match "\\<recursive\\>" prop))))
12154 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12156 (first t)
12157 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12158 level ltoggle l1 new ndel
12159 (cnt-all 0) (cnt-done 0) is-percent kwd
12160 checkbox-beg ov ovs ove cookie-present)
12161 (catch 'exit
12162 (save-excursion
12163 (beginning-of-line 1)
12164 (setq ltoggle (funcall outline-level))
12165 ;; Three situations are to consider:
12167 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12168 ;; to the top-level ancestor on the headline;
12170 ;; 2. If parent has "recursive" property, repeat up to the
12171 ;; headline setting that property, taking inheritance into
12172 ;; account;
12174 ;; 3. Else, move up to direct parent and proceed only once.
12175 (while (and (setq level (org-up-heading-safe))
12176 (or recursive first)
12177 (>= (point) lim))
12178 (setq first nil cookie-present nil)
12179 (unless (and level
12180 (not (string-match
12181 "\\<checkbox\\>"
12182 (downcase (or (org-entry-get nil "COOKIE_DATA")
12183 "")))))
12184 (throw 'exit nil))
12185 (while (re-search-forward box-re (point-at-eol) t)
12186 (setq cnt-all 0 cnt-done 0 cookie-present t)
12187 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12188 (save-match-data
12189 (unless (outline-next-heading) (throw 'exit nil))
12190 (while (and (looking-at org-complex-heading-regexp)
12191 (> (setq l1 (length (match-string 1))) level))
12192 (setq kwd (and (or recursive (= l1 ltoggle))
12193 (match-string 2)))
12194 (if (or (eq org-provide-todo-statistics 'all-headlines)
12195 (and (listp org-provide-todo-statistics)
12196 (or (member kwd org-provide-todo-statistics)
12197 (member kwd org-done-keywords))))
12198 (setq cnt-all (1+ cnt-all))
12199 (if (eq org-provide-todo-statistics t)
12200 (and kwd (setq cnt-all (1+ cnt-all)))))
12201 (and (member kwd org-done-keywords)
12202 (setq cnt-done (1+ cnt-done)))
12203 (outline-next-heading)))
12204 (setq new
12205 (if is-percent
12206 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12207 (format "[%d/%d]" cnt-done cnt-all))
12208 ndel (- (match-end 0) checkbox-beg))
12209 ;; handle overlays when updating cookie from column view
12210 (when (setq ov (car (overlays-at checkbox-beg)))
12211 (setq ovs (overlay-start ov) ove (overlay-end ov))
12212 (delete-overlay ov))
12213 (goto-char checkbox-beg)
12214 (insert new)
12215 (delete-region (point) (+ (point) ndel))
12216 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12217 (when ov (move-overlay ov ovs ove)))
12218 (when cookie-present
12219 (run-hook-with-args 'org-after-todo-statistics-hook
12220 cnt-done (- cnt-all cnt-done))))))
12221 (run-hooks 'org-todo-statistics-hook)))
12223 (defvar org-after-todo-statistics-hook nil
12224 "Hook that is called after a TODO statistics cookie has been updated.
12225 Each function is called with two arguments: the number of not-done entries
12226 and the number of done entries.
12228 For example, the following function, when added to this hook, will switch
12229 an entry to DONE when all children are done, and back to TODO when new
12230 entries are set to a TODO status. Note that this hook is only called
12231 when there is a statistics cookie in the headline!
12233 (defun org-summary-todo (n-done n-not-done)
12234 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12235 (let (org-log-done org-log-states) ; turn off logging
12236 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12239 (defvar org-todo-statistics-hook nil
12240 "Hook that is run whenever Org thinks TODO statistics should be updated.
12241 This hook runs even if there is no statistics cookie present, in which case
12242 `org-after-todo-statistics-hook' would not run.")
12244 (defun org-todo-trigger-tag-changes (state)
12245 "Apply the changes defined in `org-todo-state-tags-triggers'."
12246 (let ((l org-todo-state-tags-triggers)
12247 changes)
12248 (when (or (not state) (equal state ""))
12249 (setq changes (append changes (cdr (assoc "" l)))))
12250 (when (and (stringp state) (> (length state) 0))
12251 (setq changes (append changes (cdr (assoc state l)))))
12252 (when (member state org-not-done-keywords)
12253 (setq changes (append changes (cdr (assoc 'todo l)))))
12254 (when (member state org-done-keywords)
12255 (setq changes (append changes (cdr (assoc 'done l)))))
12256 (dolist (c changes)
12257 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12259 (defun org-local-logging (value)
12260 "Get logging settings from a property VALUE."
12261 (let* (words w a)
12262 ;; directly set the variables, they are already local.
12263 (setq org-log-done nil
12264 org-log-repeat nil
12265 org-todo-log-states nil)
12266 (setq words (org-split-string value))
12267 (while (setq w (pop words))
12268 (cond
12269 ((setq a (assoc w org-startup-options))
12270 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12271 (set (nth 1 a) (nth 2 a))))
12272 ((setq a (org-extract-log-state-settings w))
12273 (and (member (car a) org-todo-keywords-1)
12274 (push a org-todo-log-states)))))))
12276 (defun org-get-todo-sequence-head (kwd)
12277 "Return the head of the TODO sequence to which KWD belongs.
12278 If KWD is not set, check if there is a text property remembering the
12279 right sequence."
12280 (let (p)
12281 (cond
12282 ((not kwd)
12283 (or (get-text-property (point-at-bol) 'org-todo-head)
12284 (progn
12285 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12286 nil (point-at-eol)))
12287 (get-text-property p 'org-todo-head))))
12288 ((not (member kwd org-todo-keywords-1))
12289 (car org-todo-keywords-1))
12290 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12292 (defun org-fast-todo-selection ()
12293 "Fast TODO keyword selection with single keys.
12294 Returns the new TODO keyword, or nil if no state change should occur."
12295 (let* ((fulltable org-todo-key-alist)
12296 (done-keywords org-done-keywords) ;; needed for the faces.
12297 (maxlen (apply 'max (mapcar
12298 (lambda (x)
12299 (if (stringp (car x)) (string-width (car x)) 0))
12300 fulltable)))
12301 (expert nil)
12302 (fwidth (+ maxlen 3 1 3))
12303 (ncol (/ (- (window-width) 4) fwidth))
12304 tg cnt e c tbl
12305 groups ingroup)
12306 (save-excursion
12307 (save-window-excursion
12308 (if expert
12309 (set-buffer (get-buffer-create " *Org todo*"))
12310 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12311 (erase-buffer)
12312 (org-set-local 'org-done-keywords done-keywords)
12313 (setq tbl fulltable cnt 0)
12314 (while (setq e (pop tbl))
12315 (cond
12316 ((equal e '(:startgroup))
12317 (push '() groups) (setq ingroup t)
12318 (when (not (= cnt 0))
12319 (setq cnt 0)
12320 (insert "\n"))
12321 (insert "{ "))
12322 ((equal e '(:endgroup))
12323 (setq ingroup nil cnt 0)
12324 (insert "}\n"))
12325 ((equal e '(:newline))
12326 (when (not (= cnt 0))
12327 (setq cnt 0)
12328 (insert "\n")
12329 (setq e (car tbl))
12330 (while (equal (car tbl) '(:newline))
12331 (insert "\n")
12332 (setq tbl (cdr tbl)))))
12334 (setq tg (car e) c (cdr e))
12335 (if ingroup (push tg (car groups)))
12336 (setq tg (org-add-props tg nil 'face
12337 (org-get-todo-face tg)))
12338 (if (and (= cnt 0) (not ingroup)) (insert " "))
12339 (insert "[" c "] " tg (make-string
12340 (- fwidth 4 (length tg)) ?\ ))
12341 (when (= (setq cnt (1+ cnt)) ncol)
12342 (insert "\n")
12343 (if ingroup (insert " "))
12344 (setq cnt 0)))))
12345 (insert "\n")
12346 (goto-char (point-min))
12347 (if (not expert) (org-fit-window-to-buffer))
12348 (message "[a-z..]:Set [SPC]:clear")
12349 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12350 (cond
12351 ((or (= c ?\C-g)
12352 (and (= c ?q) (not (rassoc c fulltable))))
12353 (setq quit-flag t))
12354 ((= c ?\ ) nil)
12355 ((setq e (rassoc c fulltable) tg (car e))
12357 (t (setq quit-flag t)))))))
12359 (defun org-entry-is-todo-p ()
12360 (member (org-get-todo-state) org-not-done-keywords))
12362 (defun org-entry-is-done-p ()
12363 (member (org-get-todo-state) org-done-keywords))
12365 (defun org-get-todo-state ()
12366 (save-excursion
12367 (org-back-to-heading t)
12368 (and (looking-at org-todo-line-regexp)
12369 (match-end 2)
12370 (match-string 2))))
12372 (defun org-at-date-range-p (&optional inactive-ok)
12373 "Is the cursor inside a date range?"
12374 (interactive)
12375 (save-excursion
12376 (catch 'exit
12377 (let ((pos (point)))
12378 (skip-chars-backward "^[<\r\n")
12379 (skip-chars-backward "<[")
12380 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12381 (>= (match-end 0) pos)
12382 (throw 'exit t))
12383 (skip-chars-backward "^<[\r\n")
12384 (skip-chars-backward "<[")
12385 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12386 (>= (match-end 0) pos)
12387 (throw 'exit t)))
12388 nil)))
12390 (defun org-get-repeat (&optional tagline)
12391 "Check if there is a deadline/schedule with repeater in this entry."
12392 (save-match-data
12393 (save-excursion
12394 (org-back-to-heading t)
12395 (and (re-search-forward (if tagline
12396 (concat tagline "\\s-*" org-repeat-re)
12397 org-repeat-re)
12398 (org-entry-end-position) t)
12399 (match-string-no-properties 1)))))
12401 (defvar org-last-changed-timestamp)
12402 (defvar org-last-inserted-timestamp)
12403 (defvar org-log-post-message)
12404 (defvar org-log-note-purpose)
12405 (defvar org-log-note-how)
12406 (defvar org-log-note-extra)
12407 (defun org-auto-repeat-maybe (done-word)
12408 "Check if the current headline contains a repeated deadline/schedule.
12409 If yes, set TODO state back to what it was and change the base date
12410 of repeating deadline/scheduled time stamps to new date.
12411 This function is run automatically after each state change to a DONE state."
12412 ;; last-state is dynamically scoped into this function
12413 (let* ((repeat (org-get-repeat))
12414 (aa (assoc org-last-state org-todo-kwd-alist))
12415 (interpret (nth 1 aa))
12416 (head (nth 2 aa))
12417 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12418 (msg "Entry repeats: ")
12419 (org-log-done nil)
12420 (org-todo-log-states nil)
12421 re type n what ts time to-state)
12422 (when repeat
12423 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12424 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12425 org-todo-repeat-to-state))
12426 (unless (and to-state (member to-state org-todo-keywords-1))
12427 (setq to-state (if (eq interpret 'type) org-last-state head)))
12428 (org-todo to-state)
12429 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12430 (org-entry-put nil "LAST_REPEAT" (format-time-string
12431 (org-time-stamp-format t t))))
12432 (when org-log-repeat
12433 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12434 (memq 'org-add-log-note post-command-hook))
12435 ;; OK, we are already setup for some record
12436 (if (eq org-log-repeat 'note)
12437 ;; make sure we take a note, not only a time stamp
12438 (setq org-log-note-how 'note))
12439 ;; Set up for taking a record
12440 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12441 org-last-state
12442 'findpos org-log-repeat)))
12443 (org-back-to-heading t)
12444 (org-add-planning-info nil nil 'closed)
12445 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12446 org-deadline-time-regexp "\\)\\|\\("
12447 org-ts-regexp "\\)"))
12448 (while (re-search-forward
12449 re (save-excursion (outline-next-heading) (point)) t)
12450 (setq type (if (match-end 1) org-scheduled-string
12451 (if (match-end 3) org-deadline-string "Plain:"))
12452 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12453 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12454 (setq n (string-to-number (match-string 2 ts))
12455 what (match-string 3 ts))
12456 (if (equal what "w") (setq n (* n 7) what "d"))
12457 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12458 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12459 ;; Preparation, see if we need to modify the start date for the change
12460 (when (match-end 1)
12461 (setq time (save-match-data (org-time-string-to-time ts)))
12462 (cond
12463 ((equal (match-string 1 ts) ".")
12464 ;; Shift starting date to today
12465 (org-timestamp-change
12466 (- (org-today) (time-to-days time))
12467 'day))
12468 ((equal (match-string 1 ts) "+")
12469 (let ((nshiftmax 10) (nshift 0))
12470 (while (or (= nshift 0)
12471 (<= (time-to-days time)
12472 (time-to-days (current-time))))
12473 (when (= (incf nshift) nshiftmax)
12474 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12475 (error "Abort")))
12476 (org-timestamp-change n (cdr (assoc what whata)))
12477 (org-at-timestamp-p t)
12478 (setq ts (match-string 1))
12479 (setq time (save-match-data (org-time-string-to-time ts)))))
12480 (org-timestamp-change (- n) (cdr (assoc what whata)))
12481 ;; rematch, so that we have everything in place for the real shift
12482 (org-at-timestamp-p t)
12483 (setq ts (match-string 1))
12484 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12485 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12486 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12487 (setq org-log-post-message msg)
12488 (message "%s" msg))))
12490 (defun org-show-todo-tree (arg)
12491 "Make a compact tree which shows all headlines marked with TODO.
12492 The tree will show the lines where the regexp matches, and all higher
12493 headlines above the match.
12494 With a \\[universal-argument] prefix, prompt for a regexp to match.
12495 With a numeric prefix N, construct a sparse tree for the Nth element
12496 of `org-todo-keywords-1'."
12497 (interactive "P")
12498 (let ((case-fold-search nil)
12499 (kwd-re
12500 (cond ((null arg) org-not-done-regexp)
12501 ((equal arg '(4))
12502 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12503 (mapcar 'list org-todo-keywords-1))))
12504 (concat "\\("
12505 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12506 "\\)\\>")))
12507 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12508 (regexp-quote (nth (1- (prefix-numeric-value arg))
12509 org-todo-keywords-1)))
12510 (t (error "Invalid prefix argument: %s" arg)))))
12511 (message "%d TODO entries found"
12512 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12514 (defun org-deadline (&optional arg time)
12515 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12516 With one universal prefix argument, remove any deadline from the item.
12517 With two universal prefix arguments, prompt for a warning delay.
12518 With argument TIME, set the deadline at the corresponding date. TIME
12519 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12520 (interactive "P")
12521 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12522 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12523 'region-start-level 'region))
12524 org-loop-over-headlines-in-active-region)
12525 (org-map-entries
12526 `(org-deadline ',arg ,time)
12527 org-loop-over-headlines-in-active-region
12528 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12529 (let* ((old-date (org-entry-get nil "DEADLINE"))
12530 (repeater (and old-date
12531 (string-match
12532 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12533 old-date)
12534 (match-string 1 old-date))))
12535 (cond
12536 ((equal arg '(4))
12537 (when (and old-date org-log-redeadline)
12538 (org-add-log-setup 'deldeadline nil old-date 'findpos
12539 org-log-redeadline))
12540 (org-remove-timestamp-with-keyword org-deadline-string)
12541 (message "Item no longer has a deadline."))
12542 ((equal arg '(16))
12543 (save-excursion
12544 (if (re-search-forward
12545 org-deadline-time-regexp
12546 (save-excursion (outline-next-heading) (point)) t)
12547 (let* ((rpl0 (match-string 1))
12548 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12549 (replace-match
12550 (concat org-deadline-string
12551 " <" rpl
12552 (format " -%dd" (abs
12553 (- (time-to-days
12554 (save-match-data
12555 (org-read-date nil t nil "Warn starting from")))
12556 (time-to-days nil))))
12557 ">") t t))
12558 (user-error "No deadline information to update"))))
12560 (org-add-planning-info 'deadline time 'closed)
12561 (when (and old-date org-log-redeadline
12562 (not (equal old-date
12563 (substring org-last-inserted-timestamp 1 -1))))
12564 (org-add-log-setup 'redeadline nil old-date 'findpos
12565 org-log-redeadline))
12566 (when repeater
12567 (save-excursion
12568 (org-back-to-heading t)
12569 (when (re-search-forward (concat org-deadline-string " "
12570 org-last-inserted-timestamp)
12571 (save-excursion
12572 (outline-next-heading) (point)) t)
12573 (goto-char (1- (match-end 0)))
12574 (insert " " repeater)
12575 (setq org-last-inserted-timestamp
12576 (concat (substring org-last-inserted-timestamp 0 -1)
12577 " " repeater
12578 (substring org-last-inserted-timestamp -1))))))
12579 (message "Deadline on %s" org-last-inserted-timestamp))))))
12581 (defun org-schedule (&optional arg time)
12582 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12583 With one universal prefix argument, remove any scheduling date from the item.
12584 With two universal prefix arguments, prompt for a delay cookie.
12585 With argument TIME, scheduled at the corresponding date. TIME can
12586 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12587 (interactive "P")
12588 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12589 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12590 'region-start-level 'region))
12591 org-loop-over-headlines-in-active-region)
12592 (org-map-entries
12593 `(org-schedule ',arg ,time)
12594 org-loop-over-headlines-in-active-region
12595 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12596 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12597 (repeater (and old-date
12598 (string-match
12599 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12600 old-date)
12601 (match-string 1 old-date))))
12602 (cond
12603 ((equal arg '(4))
12604 (progn
12605 (when (and old-date org-log-reschedule)
12606 (org-add-log-setup 'delschedule nil old-date 'findpos
12607 org-log-reschedule))
12608 (org-remove-timestamp-with-keyword org-scheduled-string)
12609 (message "Item is no longer scheduled.")))
12610 ((equal arg '(16))
12611 (save-excursion
12612 (if (re-search-forward
12613 org-scheduled-time-regexp
12614 (save-excursion (outline-next-heading) (point)) t)
12615 (let* ((rpl0 (match-string 1))
12616 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12617 (replace-match
12618 (concat org-scheduled-string
12619 " <" rpl
12620 (format " -%dd" (abs
12621 (- (time-to-days
12622 (save-match-data
12623 (org-read-date nil t nil "Delay until")))
12624 (time-to-days nil))))
12625 ">") t t))
12626 (user-error "No scheduled information to update"))))
12628 (org-add-planning-info 'scheduled time 'closed)
12629 (when (and old-date org-log-reschedule
12630 (not (equal old-date
12631 (substring org-last-inserted-timestamp 1 -1))))
12632 (org-add-log-setup 'reschedule nil old-date 'findpos
12633 org-log-reschedule))
12634 (when repeater
12635 (save-excursion
12636 (org-back-to-heading t)
12637 (when (re-search-forward (concat org-scheduled-string " "
12638 org-last-inserted-timestamp)
12639 (save-excursion
12640 (outline-next-heading) (point)) t)
12641 (goto-char (1- (match-end 0)))
12642 (insert " " repeater)
12643 (setq org-last-inserted-timestamp
12644 (concat (substring org-last-inserted-timestamp 0 -1)
12645 " " repeater
12646 (substring org-last-inserted-timestamp -1))))))
12647 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12649 (defun org-get-scheduled-time (pom &optional inherit)
12650 "Get the scheduled time as a time tuple, of a format suitable
12651 for calling org-schedule with, or if there is no scheduling,
12652 returns nil."
12653 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12654 (when time
12655 (apply 'encode-time (org-parse-time-string time)))))
12657 (defun org-get-deadline-time (pom &optional inherit)
12658 "Get the deadline as a time tuple, of a format suitable for
12659 calling org-deadline with, or if there is no scheduling, returns
12660 nil."
12661 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12662 (when time
12663 (apply 'encode-time (org-parse-time-string time)))))
12665 (defun org-remove-timestamp-with-keyword (keyword)
12666 "Remove all time stamps with KEYWORD in the current entry."
12667 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12668 beg)
12669 (save-excursion
12670 (org-back-to-heading t)
12671 (setq beg (point))
12672 (outline-next-heading)
12673 (while (re-search-backward re beg t)
12674 (replace-match "")
12675 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12676 (equal (char-before) ?\ ))
12677 (backward-delete-char 1)
12678 (if (string-match "^[ \t]*$" (buffer-substring
12679 (point-at-bol) (point-at-eol)))
12680 (delete-region (point-at-bol)
12681 (min (point-max) (1+ (point-at-eol))))))))))
12683 (defun org-add-planning-info (what &optional time &rest remove)
12684 "Insert new timestamp with keyword in the line directly after the headline.
12685 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12686 If non is given, the user is prompted for a date.
12687 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12688 be removed."
12689 (interactive)
12690 (let (org-time-was-given org-end-time-was-given ts
12691 end default-time default-input)
12693 (catch 'exit
12694 (when (and (memq what '(scheduled deadline))
12695 (or (not time)
12696 (and (stringp time)
12697 (string-match "^[-+]+[0-9]" time))))
12698 ;; Try to get a default date/time from existing timestamp
12699 (save-excursion
12700 (org-back-to-heading t)
12701 (setq end (save-excursion (outline-next-heading) (point)))
12702 (when (re-search-forward (if (eq what 'scheduled)
12703 org-scheduled-time-regexp
12704 org-deadline-time-regexp)
12705 end t)
12706 (setq ts (match-string 1)
12707 default-time
12708 (apply 'encode-time (org-parse-time-string ts))
12709 default-input (and ts (org-get-compact-tod ts))))))
12710 (when what
12711 (setq time
12712 (if (stringp time)
12713 ;; This is a string (relative or absolute), set proper date
12714 (apply 'encode-time
12715 (org-read-date-analyze
12716 time default-time (decode-time default-time)))
12717 ;; If necessary, get the time from the user
12718 (or time (org-read-date nil 'to-time nil nil
12719 default-time default-input)))))
12721 (when (and org-insert-labeled-timestamps-at-point
12722 (member what '(scheduled deadline)))
12723 (insert
12724 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12725 (org-insert-time-stamp time org-time-was-given
12726 nil nil nil (list org-end-time-was-given))
12727 (setq what nil))
12728 (save-excursion
12729 (save-restriction
12730 (let (col list elt ts buffer-invisibility-spec)
12731 (org-back-to-heading t)
12732 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12733 (goto-char (match-end 1))
12734 (setq col (current-column))
12735 (goto-char (match-end 0))
12736 (if (eobp) (insert "\n") (forward-char 1))
12737 (when (and (not what)
12738 (not (looking-at
12739 (concat "[ \t]*"
12740 org-keyword-time-not-clock-regexp))))
12741 ;; Nothing to add, nothing to remove...... :-)
12742 (throw 'exit nil))
12743 (if (and (not (looking-at org-outline-regexp))
12744 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12745 "[^\r\n]*"))
12746 (not (equal (match-string 1) org-clock-string)))
12747 (narrow-to-region (match-beginning 0) (match-end 0))
12748 (insert-before-markers "\n")
12749 (backward-char 1)
12750 (narrow-to-region (point) (point))
12751 (and org-adapt-indentation (org-indent-to-column col)))
12752 ;; Check if we have to remove something.
12753 (setq list (cons what remove))
12754 (while list
12755 (setq elt (pop list))
12756 (when (or (and (eq elt 'scheduled)
12757 (re-search-forward org-scheduled-time-regexp nil t))
12758 (and (eq elt 'deadline)
12759 (re-search-forward org-deadline-time-regexp nil t))
12760 (and (eq elt 'closed)
12761 (re-search-forward org-closed-time-regexp nil t)))
12762 (replace-match "")
12763 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12764 (and (looking-at "[ \t]+") (replace-match ""))
12765 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12766 (when what
12767 (insert
12768 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12769 (cond ((eq what 'scheduled) org-scheduled-string)
12770 ((eq what 'deadline) org-deadline-string)
12771 ((eq what 'closed) org-closed-string))
12772 " ")
12773 (setq ts (org-insert-time-stamp
12774 time
12775 (or org-time-was-given
12776 (and (eq what 'closed) org-log-done-with-time))
12777 (eq what 'closed)
12778 nil nil (list org-end-time-was-given)))
12779 (insert
12780 (if (not (or (bolp) (eq (char-before) ?\ )
12781 (memq (char-after) '(32 10))
12782 (eobp))) " " ""))
12783 (end-of-line 1))
12784 (goto-char (point-min))
12785 (widen)
12786 (if (and (looking-at "[ \t]*\n")
12787 (equal (char-before) ?\n))
12788 (delete-region (1- (point)) (point-at-eol)))
12789 ts))))))
12791 (defvar org-log-note-marker (make-marker))
12792 (defvar org-log-note-purpose nil)
12793 (defvar org-log-note-state nil)
12794 (defvar org-log-note-previous-state nil)
12795 (defvar org-log-note-how nil)
12796 (defvar org-log-note-extra nil)
12797 (defvar org-log-note-window-configuration nil)
12798 (defvar org-log-note-return-to (make-marker))
12799 (defvar org-log-note-effective-time nil
12800 "Remembered current time so that dynamically scoped
12801 `org-extend-today-until' affects tha timestamps in state change
12802 log")
12804 (defvar org-log-post-message nil
12805 "Message to be displayed after a log note has been stored.
12806 The auto-repeater uses this.")
12808 (defun org-add-note ()
12809 "Add a note to the current entry.
12810 This is done in the same way as adding a state change note."
12811 (interactive)
12812 (org-add-log-setup 'note nil nil 'findpos nil))
12814 (defvar org-property-end-re)
12815 (defun org-add-log-setup (&optional purpose state prev-state
12816 findpos how extra)
12817 "Set up the post command hook to take a note.
12818 If this is about to TODO state change, the new state is expected in STATE.
12819 When FINDPOS is non-nil, find the correct position for the note in
12820 the current entry. If not, assume that it can be inserted at point.
12821 HOW is an indicator what kind of note should be created.
12822 EXTRA is additional text that will be inserted into the notes buffer."
12823 (let* ((org-log-into-drawer (org-log-into-drawer))
12824 (drawer (cond ((stringp org-log-into-drawer)
12825 org-log-into-drawer)
12826 (org-log-into-drawer "LOGBOOK"))))
12827 (save-restriction
12828 (save-excursion
12829 (when findpos
12830 (org-back-to-heading t)
12831 (narrow-to-region (point) (save-excursion
12832 (outline-next-heading) (point)))
12833 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12834 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12835 "[^\r\n]*\\)?"))
12836 (goto-char (match-end 0))
12837 (cond
12838 (drawer
12839 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12840 nil t)
12841 (progn
12842 (goto-char (match-end 0))
12843 (or org-log-states-order-reversed
12844 (and (re-search-forward org-property-end-re nil t)
12845 (goto-char (1- (match-beginning 0))))))
12846 (insert "\n:" drawer ":\n:END:")
12847 (beginning-of-line 0)
12848 (org-indent-line)
12849 (beginning-of-line 2)
12850 (org-indent-line)
12851 (end-of-line 0)))
12852 ((and org-log-state-notes-insert-after-drawers
12853 (save-excursion
12854 (forward-line) (looking-at org-drawer-regexp)))
12855 (forward-line)
12856 (while (looking-at org-drawer-regexp)
12857 (goto-char (match-end 0))
12858 (re-search-forward org-property-end-re (point-max) t)
12859 (forward-line))
12860 (forward-line -1)))
12861 (unless org-log-states-order-reversed
12862 (and (= (char-after) ?\n) (forward-char 1))
12863 (org-skip-over-state-notes)
12864 (skip-chars-backward " \t\n\r")))
12865 (move-marker org-log-note-marker (point))
12866 (setq org-log-note-purpose purpose
12867 org-log-note-state state
12868 org-log-note-previous-state prev-state
12869 org-log-note-how how
12870 org-log-note-extra extra
12871 org-log-note-effective-time (org-current-effective-time))
12872 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12874 (defun org-skip-over-state-notes ()
12875 "Skip past the list of State notes in an entry."
12876 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12877 (when (ignore-errors (goto-char (org-in-item-p)))
12878 (let* ((struct (org-list-struct))
12879 (prevs (org-list-prevs-alist struct)))
12880 (while (looking-at "[ \t]*- State")
12881 (goto-char (or (org-list-get-next-item (point) struct prevs)
12882 (org-list-get-item-end (point) struct)))))))
12884 (defun org-add-log-note (&optional purpose)
12885 "Pop up a window for taking a note, and add this note later at point."
12886 (remove-hook 'post-command-hook 'org-add-log-note)
12887 (setq org-log-note-window-configuration (current-window-configuration))
12888 (delete-other-windows)
12889 (move-marker org-log-note-return-to (point))
12890 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12891 (goto-char org-log-note-marker)
12892 (org-switch-to-buffer-other-window "*Org Note*")
12893 (erase-buffer)
12894 (if (memq org-log-note-how '(time state))
12895 (let (current-prefix-arg) (org-store-log-note))
12896 (let ((org-inhibit-startup t)) (org-mode))
12897 (insert (format "# Insert note for %s.
12898 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12899 (cond
12900 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12901 ((eq org-log-note-purpose 'done) "closed todo item")
12902 ((eq org-log-note-purpose 'state)
12903 (format "state change from \"%s\" to \"%s\""
12904 (or org-log-note-previous-state "")
12905 (or org-log-note-state "")))
12906 ((eq org-log-note-purpose 'reschedule)
12907 "rescheduling")
12908 ((eq org-log-note-purpose 'delschedule)
12909 "no longer scheduled")
12910 ((eq org-log-note-purpose 'redeadline)
12911 "changing deadline")
12912 ((eq org-log-note-purpose 'deldeadline)
12913 "removing deadline")
12914 ((eq org-log-note-purpose 'refile)
12915 "refiling")
12916 ((eq org-log-note-purpose 'note)
12917 "this entry")
12918 (t (error "This should not happen")))))
12919 (if org-log-note-extra (insert org-log-note-extra))
12920 (org-set-local 'org-finish-function 'org-store-log-note)
12921 (run-hooks 'org-log-buffer-setup-hook)))
12923 (defvar org-note-abort nil) ; dynamically scoped
12924 (defun org-store-log-note ()
12925 "Finish taking a log note, and insert it to where it belongs."
12926 (let ((txt (buffer-string)))
12927 (kill-buffer (current-buffer))
12928 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12929 lines ind bul)
12930 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12931 (setq txt (replace-match "" t t txt)))
12932 (if (string-match "\\s-+\\'" txt)
12933 (setq txt (replace-match "" t t txt)))
12934 (setq lines (org-split-string txt "\n"))
12935 (when (and note (string-match "\\S-" note))
12936 (setq note
12937 (org-replace-escapes
12938 note
12939 (list (cons "%u" (user-login-name))
12940 (cons "%U" user-full-name)
12941 (cons "%t" (format-time-string
12942 (org-time-stamp-format 'long 'inactive)
12943 org-log-note-effective-time))
12944 (cons "%T" (format-time-string
12945 (org-time-stamp-format 'long nil)
12946 org-log-note-effective-time))
12947 (cons "%d" (format-time-string
12948 (org-time-stamp-format nil 'inactive)
12949 org-log-note-effective-time))
12950 (cons "%D" (format-time-string
12951 (org-time-stamp-format nil nil)
12952 org-log-note-effective-time))
12953 (cons "%s" (if org-log-note-state
12954 (concat "\"" org-log-note-state "\"")
12955 ""))
12956 (cons "%S" (if org-log-note-previous-state
12957 (concat "\"" org-log-note-previous-state "\"")
12958 "\"\"")))))
12959 (if lines (setq note (concat note " \\\\")))
12960 (push note lines))
12961 (when (or current-prefix-arg org-note-abort)
12962 (when org-log-into-drawer
12963 (org-remove-empty-drawer-at
12964 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12965 org-log-note-marker))
12966 (setq lines nil))
12967 (when lines
12968 (with-current-buffer (marker-buffer org-log-note-marker)
12969 (save-excursion
12970 (goto-char org-log-note-marker)
12971 (move-marker org-log-note-marker nil)
12972 (end-of-line 1)
12973 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12974 (setq ind (save-excursion
12975 (if (ignore-errors (goto-char (org-in-item-p)))
12976 (let ((struct (org-list-struct)))
12977 (org-list-get-ind
12978 (org-list-get-top-point struct) struct))
12979 (skip-chars-backward " \r\t\n")
12980 (cond
12981 ((and (org-at-heading-p)
12982 org-adapt-indentation)
12983 (1+ (org-current-level)))
12984 ((org-at-heading-p) 0)
12985 (t (org-get-indentation))))))
12986 (setq bul (org-list-bullet-string "-"))
12987 (org-indent-line-to ind)
12988 (insert bul (pop lines))
12989 (let ((ind-body (+ (length bul) ind)))
12990 (while lines
12991 (insert "\n")
12992 (org-indent-line-to ind-body)
12993 (insert (pop lines))))
12994 (message "Note stored")
12995 (org-back-to-heading t)
12996 (org-cycle-hide-drawers 'children))))))
12997 (set-window-configuration org-log-note-window-configuration)
12998 (with-current-buffer (marker-buffer org-log-note-return-to)
12999 (goto-char org-log-note-return-to))
13000 (move-marker org-log-note-return-to nil)
13001 (and org-log-post-message (message "%s" org-log-post-message)))
13003 (defun org-remove-empty-drawer-at (drawer pos)
13004 "Remove an empty drawer DRAWER at position POS.
13005 POS may also be a marker."
13006 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13007 (save-excursion
13008 (save-restriction
13009 (widen)
13010 (goto-char pos)
13011 (if (org-in-regexp
13012 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13013 (replace-match ""))))))
13015 (defvar org-ts-type nil)
13016 (defun org-sparse-tree (&optional arg type)
13017 "Create a sparse tree, prompt for the details.
13018 This command can create sparse trees. You first need to select the type
13019 of match used to create the tree:
13021 t Show all TODO entries.
13022 T Show entries with a specific TODO keyword.
13023 m Show entries selected by a tags/property match.
13024 p Enter a property name and its value (both with completion on existing
13025 names/values) and show entries with that property.
13026 r Show entries matching a regular expression (`/' can be used as well).
13027 b Show deadlines and scheduled items before a date.
13028 a Show deadlines and scheduled items after a date.
13029 d Show deadlines due within `org-deadline-warning-days'.
13030 D Show deadlines and scheduled items between a date range."
13031 (interactive "P")
13032 (let (ans kwd value ts-type)
13033 (setq type (or type org-sparse-tree-default-date-type))
13034 (setq org-ts-type type)
13035 (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"
13036 (cond ((eq type 'all) "all timestamps")
13037 ((eq type 'scheduled) "only scheduled")
13038 ((eq type 'deadline) "only deadline")
13039 ((eq type 'active) "only active timestamps")
13040 ((eq type 'inactive) "only inactive timestamps")
13041 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13042 (t "scheduled/deadline")))
13043 (setq ans (read-char-exclusive))
13044 (cond
13045 ((equal ans ?c)
13046 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13047 ((equal ans ?d)
13048 (call-interactively 'org-check-deadlines))
13049 ((equal ans ?b)
13050 (call-interactively 'org-check-before-date))
13051 ((equal ans ?a)
13052 (call-interactively 'org-check-after-date))
13053 ((equal ans ?D)
13054 (call-interactively 'org-check-dates-range))
13055 ((equal ans ?t)
13056 (call-interactively 'org-show-todo-tree))
13057 ((equal ans ?T)
13058 (org-show-todo-tree '(4)))
13059 ((member ans '(?T ?m))
13060 (call-interactively 'org-match-sparse-tree))
13061 ((member ans '(?p ?P))
13062 (setq kwd (org-icompleting-read "Property: "
13063 (mapcar 'list (org-buffer-property-keys))))
13064 (setq value (org-icompleting-read "Value: "
13065 (mapcar 'list (org-property-values kwd))))
13066 (unless (string-match "\\`{.*}\\'" value)
13067 (setq value (concat "\"" value "\"")))
13068 (org-match-sparse-tree arg (concat kwd "=" value)))
13069 ((member ans '(?r ?R ?/))
13070 (call-interactively 'org-occur))
13071 (t (error "No such sparse tree command \"%c\"" ans)))))
13073 (defvar org-occur-highlights nil
13074 "List of overlays used for occur matches.")
13075 (make-variable-buffer-local 'org-occur-highlights)
13076 (defvar org-occur-parameters nil
13077 "Parameters of the active org-occur calls.
13078 This is a list, each call to org-occur pushes as cons cell,
13079 containing the regular expression and the callback, onto the list.
13080 The list can contain several entries if `org-occur' has been called
13081 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13082 will only contain one set of parameters. When the highlights are
13083 removed (for example with `C-c C-c', or with the next edit (depending
13084 on `org-remove-highlights-with-change'), this variable is emptied
13085 as well.")
13086 (make-variable-buffer-local 'org-occur-parameters)
13088 (defun org-occur (regexp &optional keep-previous callback)
13089 "Make a compact tree which shows all matches of REGEXP.
13090 The tree will show the lines where the regexp matches, and all higher
13091 headlines above the match. It will also show the heading after the match,
13092 to make sure editing the matching entry is easy.
13093 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13094 call to `org-occur' will be kept, to allow stacking of calls to this
13095 command.
13096 If CALLBACK is non-nil, it is a function which is called to confirm
13097 that the match should indeed be shown."
13098 (interactive "sRegexp: \nP")
13099 (when (equal regexp "")
13100 (error "Regexp cannot be empty"))
13101 (unless keep-previous
13102 (org-remove-occur-highlights nil nil t))
13103 (push (cons regexp callback) org-occur-parameters)
13104 (let ((cnt 0))
13105 (save-excursion
13106 (goto-char (point-min))
13107 (if (or (not keep-previous) ; do not want to keep
13108 (not org-occur-highlights)) ; no previous matches
13109 ;; hide everything
13110 (org-overview))
13111 (while (re-search-forward regexp nil t)
13112 (when (or (not callback)
13113 (save-match-data (funcall callback)))
13114 (setq cnt (1+ cnt))
13115 (when org-highlight-sparse-tree-matches
13116 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13117 (org-show-context 'occur-tree))))
13118 (when org-remove-highlights-with-change
13119 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13120 nil 'local))
13121 (unless org-sparse-tree-open-archived-trees
13122 (org-hide-archived-subtrees (point-min) (point-max)))
13123 (run-hooks 'org-occur-hook)
13124 (if (org-called-interactively-p 'interactive)
13125 (message "%d match(es) for regexp %s" cnt regexp))
13126 cnt))
13128 (defun org-occur-next-match (&optional n reset)
13129 "Function for `next-error-function' to find sparse tree matches.
13130 N is the number of matches to move, when negative move backwards.
13131 RESET is entirely ignored - this function always goes back to the
13132 starting point when no match is found."
13133 (let* ((limit (if (< n 0) (point-min) (point-max)))
13134 (search-func (if (< n 0)
13135 'previous-single-char-property-change
13136 'next-single-char-property-change))
13137 (n (abs n))
13138 (pos (point))
13140 (catch 'exit
13141 (while (setq p1 (funcall search-func (point) 'org-type))
13142 (when (equal p1 limit)
13143 (goto-char pos)
13144 (error "No more matches"))
13145 (when (equal (get-char-property p1 'org-type) 'org-occur)
13146 (setq n (1- n))
13147 (when (= n 0)
13148 (goto-char p1)
13149 (throw 'exit (point))))
13150 (goto-char p1))
13151 (goto-char p1)
13152 (error "No more matches"))))
13154 (defun org-show-context (&optional key)
13155 "Make sure point and context are visible.
13156 How much context is shown depends upon the variables
13157 `org-show-hierarchy-above', `org-show-following-heading',
13158 `org-show-entry-below' and `org-show-siblings'."
13159 (let ((heading-p (org-at-heading-p t))
13160 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13161 (following-p (org-get-alist-option org-show-following-heading key))
13162 (entry-p (org-get-alist-option org-show-entry-below key))
13163 (siblings-p (org-get-alist-option org-show-siblings key)))
13164 (catch 'exit
13165 ;; Show heading or entry text
13166 (if (and heading-p (not entry-p))
13167 (org-flag-heading nil) ; only show the heading
13168 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13169 (org-show-hidden-entry))) ; show entire entry
13170 (when following-p
13171 ;; Show next sibling, or heading below text
13172 (save-excursion
13173 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13174 (org-flag-heading nil))))
13175 (when siblings-p (org-show-siblings))
13176 (when hierarchy-p
13177 ;; show all higher headings, possibly with siblings
13178 (save-excursion
13179 (while (and (condition-case nil
13180 (progn (org-up-heading-all 1) t)
13181 (error nil))
13182 (not (bobp)))
13183 (org-flag-heading nil)
13184 (when siblings-p (org-show-siblings))))))))
13186 (defvar org-reveal-start-hook nil
13187 "Hook run before revealing a location.")
13189 (defun org-reveal (&optional siblings)
13190 "Show current entry, hierarchy above it, and the following headline.
13191 This can be used to show a consistent set of context around locations
13192 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13193 not t for the search context.
13195 With optional argument SIBLINGS, on each level of the hierarchy all
13196 siblings are shown. This repairs the tree structure to what it would
13197 look like when opened with hierarchical calls to `org-cycle'.
13198 With double optional argument \\[universal-argument] \\[universal-argument], \
13199 go to the parent and show the
13200 entire tree."
13201 (interactive "P")
13202 (run-hooks 'org-reveal-start-hook)
13203 (let ((org-show-hierarchy-above t)
13204 (org-show-following-heading t)
13205 (org-show-siblings (if siblings t org-show-siblings)))
13206 (org-show-context nil))
13207 (when (equal siblings '(16))
13208 (save-excursion
13209 (when (org-up-heading-safe)
13210 (org-show-subtree)
13211 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13213 (defun org-highlight-new-match (beg end)
13214 "Highlight from BEG to END and mark the highlight is an occur headline."
13215 (let ((ov (make-overlay beg end)))
13216 (overlay-put ov 'face 'secondary-selection)
13217 (overlay-put ov 'org-type 'org-occur)
13218 (push ov org-occur-highlights)))
13220 (defun org-remove-occur-highlights (&optional beg end noremove)
13221 "Remove the occur highlights from the buffer.
13222 BEG and END are ignored. If NOREMOVE is nil, remove this function
13223 from the `before-change-functions' in the current buffer."
13224 (interactive)
13225 (unless org-inhibit-highlight-removal
13226 (mapc 'delete-overlay org-occur-highlights)
13227 (setq org-occur-highlights nil)
13228 (setq org-occur-parameters nil)
13229 (unless noremove
13230 (remove-hook 'before-change-functions
13231 'org-remove-occur-highlights 'local))))
13233 ;;;; Priorities
13235 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13236 "Regular expression matching the priority indicator.")
13238 (defvar org-remove-priority-next-time nil)
13240 (defun org-priority-up ()
13241 "Increase the priority of the current item."
13242 (interactive)
13243 (org-priority 'up))
13245 (defun org-priority-down ()
13246 "Decrease the priority of the current item."
13247 (interactive)
13248 (org-priority 'down))
13250 (defun org-priority (&optional action show)
13251 "Change the priority of an item.
13252 ACTION can be `set', `up', `down', or a character."
13253 (interactive "P")
13254 (if (equal action '(4))
13255 (org-show-priority)
13256 (unless org-enable-priority-commands
13257 (error "Priority commands are disabled"))
13258 (setq action (or action 'set))
13259 (let (current new news have remove)
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (if (looking-at org-priority-regexp)
13263 (setq current (string-to-char (match-string 2))
13264 have t))
13265 (cond
13266 ((eq action 'remove)
13267 (setq remove t new ?\ ))
13268 ((or (eq action 'set)
13269 (if (featurep 'xemacs) (characterp action) (integerp action)))
13270 (if (not (eq action 'set))
13271 (setq new action)
13272 (message "Priority %c-%c, SPC to remove: "
13273 org-highest-priority org-lowest-priority)
13274 (save-match-data
13275 (setq new (read-char-exclusive))))
13276 (if (and (= (upcase org-highest-priority) org-highest-priority)
13277 (= (upcase org-lowest-priority) org-lowest-priority))
13278 (setq new (upcase new)))
13279 (cond ((equal new ?\ ) (setq remove t))
13280 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13281 (error "Priority must be between `%c' and `%c'"
13282 org-highest-priority org-lowest-priority))))
13283 ((eq action 'up)
13284 (setq new (if have
13285 (1- current) ; normal cycling
13286 ;; last priority was empty
13287 (if (eq last-command this-command)
13288 org-lowest-priority ; wrap around empty to lowest
13289 ;; default
13290 (if org-priority-start-cycle-with-default
13291 org-default-priority
13292 (1- org-default-priority))))))
13293 ((eq action 'down)
13294 (setq new (if have
13295 (1+ current) ; normal cycling
13296 ;; last priority was empty
13297 (if (eq last-command this-command)
13298 org-highest-priority ; wrap around empty to highest
13299 ;; default
13300 (if org-priority-start-cycle-with-default
13301 org-default-priority
13302 (1+ org-default-priority))))))
13303 (t (error "Invalid action")))
13304 (if (or (< (upcase new) org-highest-priority)
13305 (> (upcase new) org-lowest-priority))
13306 (if (and (memq action '(up down))
13307 (not have) (not (eq last-command this-command)))
13308 ;; `new' is from default priority
13309 (error
13310 "The default can not be set, see `org-default-priority' why")
13311 ;; normal cycling: `new' is beyond highest/lowest priority
13312 ;; and is wrapped around to the empty priority
13313 (setq remove t)))
13314 (setq news (format "%c" new))
13315 (if have
13316 (if remove
13317 (replace-match "" t t nil 1)
13318 (replace-match news t t nil 2))
13319 (if remove
13320 (error "No priority cookie found in line")
13321 (let ((case-fold-search nil))
13322 (looking-at org-todo-line-regexp))
13323 (if (match-end 2)
13324 (progn
13325 (goto-char (match-end 2))
13326 (insert " [#" news "]"))
13327 (goto-char (match-beginning 3))
13328 (insert "[#" news "] "))))
13329 (org-preserve-lc (org-set-tags nil 'align)))
13330 (if remove
13331 (message "Priority removed")
13332 (message "Priority of current item set to %s" news)))))
13334 (defun org-show-priority ()
13335 "Show the priority of the current item.
13336 This priority is composed of the main priority given with the [#A] cookies,
13337 and by additional input from the age of a schedules or deadline entry."
13338 (interactive)
13339 (let ((pri (if (eq major-mode 'org-agenda-mode)
13340 (org-get-at-bol 'priority)
13341 (save-excursion
13342 (save-match-data
13343 (beginning-of-line)
13344 (and (looking-at org-heading-regexp)
13345 (org-get-priority (match-string 0))))))))
13346 (message "Priority is %d" (if pri pri -1000))))
13348 (defun org-get-priority (s)
13349 "Find priority cookie and return priority."
13350 (save-match-data
13351 (if (functionp org-get-priority-function)
13352 (funcall org-get-priority-function)
13353 (if (not (string-match org-priority-regexp s))
13354 (* 1000 (- org-lowest-priority org-default-priority))
13355 (* 1000 (- org-lowest-priority
13356 (string-to-char (match-string 2 s))))))))
13358 ;;;; Tags
13360 (defvar org-agenda-archives-mode)
13361 (defvar org-map-continue-from nil
13362 "Position from where mapping should continue.
13363 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13365 (defvar org-scanner-tags nil
13366 "The current tag list while the tags scanner is running.")
13367 (defvar org-trust-scanner-tags nil
13368 "Should `org-get-tags-at' use the tags for the scanner.
13369 This is for internal dynamical scoping only.
13370 When this is non-nil, the function `org-get-tags-at' will return the value
13371 of `org-scanner-tags' instead of building the list by itself. This
13372 can lead to large speed-ups when the tags scanner is used in a file with
13373 many entries, and when the list of tags is retrieved, for example to
13374 obtain a list of properties. Building the tags list for each entry in such
13375 a file becomes an N^2 operation - but with this variable set, it scales
13376 as N.")
13378 (defun org-scan-tags (action matcher todo-only &optional start-level)
13379 "Scan headline tags with inheritance and produce output ACTION.
13381 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13382 or `agenda' to produce an entry list for an agenda view. It can also be
13383 a Lisp form or a function that should be called at each matched headline, in
13384 this case the return value is a list of all return values from these calls.
13386 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13387 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13388 only lines with a not-done TODO keyword are included in the output.
13389 This should be the same variable that was scoped into
13390 and set by `org-make-tags-matcher' when it constructed MATCHER.
13392 START-LEVEL can be a string with asterisks, reducing the scope to
13393 headlines matching this string."
13394 (require 'org-agenda)
13395 (let* ((re (concat "^"
13396 (if start-level
13397 ;; Get the correct level to match
13398 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13399 org-outline-regexp)
13400 " *\\(\\<\\("
13401 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13402 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13403 (props (list 'face 'default
13404 'done-face 'org-agenda-done
13405 'undone-face 'default
13406 'mouse-face 'highlight
13407 'org-not-done-regexp org-not-done-regexp
13408 'org-todo-regexp org-todo-regexp
13409 'org-complex-heading-regexp org-complex-heading-regexp
13410 'help-echo
13411 (format "mouse-2 or RET jump to org file %s"
13412 (abbreviate-file-name
13413 (or (buffer-file-name (buffer-base-buffer))
13414 (buffer-name (buffer-base-buffer)))))))
13415 (case-fold-search nil)
13416 (org-map-continue-from nil)
13417 lspos tags tags-list
13418 (tags-alist (list (cons 0 org-file-tags)))
13419 (llast 0) rtn rtn1 level category i txt
13420 todo marker entry priority)
13421 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13422 (setq action (list 'lambda nil action)))
13423 (save-excursion
13424 (goto-char (point-min))
13425 (when (eq action 'sparse-tree)
13426 (org-overview)
13427 (org-remove-occur-highlights))
13428 (while (re-search-forward re nil t)
13429 (setq org-map-continue-from nil)
13430 (catch :skip
13431 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13432 tags (if (match-end 4) (org-match-string-no-properties 4)))
13433 (goto-char (setq lspos (match-beginning 0)))
13434 (setq level (org-reduced-level (org-outline-level))
13435 category (org-get-category))
13436 (setq i llast llast level)
13437 ;; remove tag lists from same and sublevels
13438 (while (>= i level)
13439 (when (setq entry (assoc i tags-alist))
13440 (setq tags-alist (delete entry tags-alist)))
13441 (setq i (1- i)))
13442 ;; add the next tags
13443 (when tags
13444 (setq tags (org-split-string tags ":")
13445 tags-alist
13446 (cons (cons level tags) tags-alist)))
13447 ;; compile tags for current headline
13448 (setq tags-list
13449 (if org-use-tag-inheritance
13450 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13451 tags)
13452 org-scanner-tags tags-list)
13453 (when org-use-tag-inheritance
13454 (setcdr (car tags-alist)
13455 (mapcar (lambda (x)
13456 (setq x (copy-sequence x))
13457 (org-add-prop-inherited x))
13458 (cdar tags-alist))))
13459 (when (and tags org-use-tag-inheritance
13460 (or (not (eq t org-use-tag-inheritance))
13461 org-tags-exclude-from-inheritance))
13462 ;; selective inheritance, remove uninherited ones
13463 (setcdr (car tags-alist)
13464 (org-remove-uninherited-tags (cdar tags-alist))))
13465 (when (and
13467 ;; eval matcher only when the todo condition is OK
13468 (and (or (not todo-only) (member todo org-not-done-keywords))
13469 (let ((case-fold-search t) (org-trust-scanner-tags t))
13470 (eval matcher)))
13472 ;; Call the skipper, but return t if it does not skip,
13473 ;; so that the `and' form continues evaluating
13474 (progn
13475 (unless (eq action 'sparse-tree) (org-agenda-skip))
13478 ;; Check if timestamps are deselecting this entry
13479 (or (not todo-only)
13480 (and (member todo org-not-done-keywords)
13481 (or (not org-agenda-tags-todo-honor-ignore-options)
13482 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13484 ;; select this headline
13485 (cond
13486 ((eq action 'sparse-tree)
13487 (and org-highlight-sparse-tree-matches
13488 (org-get-heading) (match-end 0)
13489 (org-highlight-new-match
13490 (match-beginning 1) (match-end 1)))
13491 (org-show-context 'tags-tree))
13492 ((eq action 'agenda)
13493 (setq txt (org-agenda-format-item
13495 (concat
13496 (if (eq org-tags-match-list-sublevels 'indented)
13497 (make-string (1- level) ?.) "")
13498 (org-get-heading))
13499 level category
13500 tags-list)
13501 priority (org-get-priority txt))
13502 (goto-char lspos)
13503 (setq marker (org-agenda-new-marker))
13504 (org-add-props txt props
13505 'org-marker marker 'org-hd-marker marker 'org-category category
13506 'todo-state todo
13507 'priority priority 'type "tagsmatch")
13508 (push txt rtn))
13509 ((functionp action)
13510 (setq org-map-continue-from nil)
13511 (save-excursion
13512 (setq rtn1 (funcall action))
13513 (push rtn1 rtn)))
13514 (t (error "Invalid action")))
13516 ;; if we are to skip sublevels, jump to end of subtree
13517 (unless org-tags-match-list-sublevels
13518 (org-end-of-subtree t)
13519 (backward-char 1))))
13520 ;; Get the correct position from where to continue
13521 (if org-map-continue-from
13522 (goto-char org-map-continue-from)
13523 (and (= (point) lspos) (end-of-line 1)))))
13524 (when (and (eq action 'sparse-tree)
13525 (not org-sparse-tree-open-archived-trees))
13526 (org-hide-archived-subtrees (point-min) (point-max)))
13527 (nreverse rtn)))
13529 (defun org-remove-uninherited-tags (tags)
13530 "Remove all tags that are not inherited from the list TAGS."
13531 (cond
13532 ((eq org-use-tag-inheritance t)
13533 (if org-tags-exclude-from-inheritance
13534 (org-delete-all org-tags-exclude-from-inheritance tags)
13535 tags))
13536 ((not org-use-tag-inheritance) nil)
13537 ((stringp org-use-tag-inheritance)
13538 (delq nil (mapcar
13539 (lambda (x)
13540 (if (and (string-match org-use-tag-inheritance x)
13541 (not (member x org-tags-exclude-from-inheritance)))
13542 x nil))
13543 tags)))
13544 ((listp org-use-tag-inheritance)
13545 (delq nil (mapcar
13546 (lambda (x)
13547 (if (member x org-use-tag-inheritance) x nil))
13548 tags)))))
13550 (defun org-match-sparse-tree (&optional todo-only match)
13551 "Create a sparse tree according to tags string MATCH.
13552 MATCH can contain positive and negative selection of tags, like
13553 \"+WORK+URGENT-WITHBOSS\".
13554 If optional argument TODO-ONLY is non-nil, only select lines that are
13555 also TODO lines."
13556 (interactive "P")
13557 (org-agenda-prepare-buffers (list (current-buffer)))
13558 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13560 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13562 (defvar org-cached-props nil)
13563 (defun org-cached-entry-get (pom property)
13564 (if (or (eq t org-use-property-inheritance)
13565 (and (stringp org-use-property-inheritance)
13566 (string-match org-use-property-inheritance property))
13567 (and (listp org-use-property-inheritance)
13568 (member property org-use-property-inheritance)))
13569 ;; Caching is not possible, check it directly
13570 (org-entry-get pom property 'inherit)
13571 ;; Get all properties, so that we can do complicated checks easily
13572 (cdr (assoc property (or org-cached-props
13573 (setq org-cached-props
13574 (org-entry-properties pom)))))))
13576 (defun org-global-tags-completion-table (&optional files)
13577 "Return the list of all tags in all agenda buffer/files.
13578 Optional FILES argument is a list of files which can be used
13579 instead of the agenda files."
13580 (save-excursion
13581 (org-uniquify
13582 (delq nil
13583 (apply 'append
13584 (mapcar
13585 (lambda (file)
13586 (set-buffer (find-file-noselect file))
13587 (append (org-get-buffer-tags)
13588 (mapcar (lambda (x) (if (stringp (car-safe x))
13589 (list (car-safe x)) nil))
13590 org-tag-alist)))
13591 (if (and files (car files))
13592 files
13593 (org-agenda-files))))))))
13595 (defun org-make-tags-matcher (match)
13596 "Create the TAGS/TODO matcher form for the selection string MATCH.
13598 The variable `todo-only' is scoped dynamically into this function.
13599 It will be set to t if the matcher restricts matching to TODO entries,
13600 otherwise will not be touched.
13602 Returns a cons of the selection string MATCH and the constructed
13603 lisp form implementing the matcher. The matcher is to be evaluated
13604 at an Org entry, with point on the headline, and returns t if the
13605 entry matches the selection string MATCH. The returned lisp form
13606 references two variables with information about the entry, which
13607 must be bound around the form's evaluation: todo, the TODO keyword
13608 at the entry (or nil of none); and tags-list, the list of all tags
13609 at the entry including inherited ones. Additionally, the category
13610 of the entry (if any) must be specified as the text property
13611 'org-category on the headline.
13613 See also `org-scan-tags'.
13615 (declare (special todo-only))
13616 (unless (boundp 'todo-only)
13617 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13618 (unless match
13619 ;; Get a new match request, with completion
13620 (let ((org-last-tags-completion-table
13621 (org-global-tags-completion-table)))
13622 (setq match (org-completing-read-no-i
13623 "Match: " 'org-tags-completion-function nil nil nil
13624 'org-tags-history))))
13626 ;; Parse the string and create a lisp form
13627 (let ((match0 match)
13628 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13629 minus tag mm
13630 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13631 orterms term orlist re-p str-p level-p level-op time-p
13632 prop-p pn pv po gv rest)
13633 (if (string-match "/+" match)
13634 ;; match contains also a todo-matching request
13635 (progn
13636 (setq tagsmatch (substring match 0 (match-beginning 0))
13637 todomatch (substring match (match-end 0)))
13638 (if (string-match "^!" todomatch)
13639 (setq todo-only t todomatch (substring todomatch 1)))
13640 (if (string-match "^\\s-*$" todomatch)
13641 (setq todomatch nil)))
13642 ;; only matching tags
13643 (setq tagsmatch match todomatch nil))
13645 ;; Make the tags matcher
13646 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13647 (setq tagsmatcher t)
13648 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13649 (while (setq term (pop orterms))
13650 (while (and (equal (substring term -1) "\\") orterms)
13651 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13652 (while (string-match re term)
13653 (setq rest (substring term (match-end 0))
13654 minus (and (match-end 1)
13655 (equal (match-string 1 term) "-"))
13656 tag (save-match-data (replace-regexp-in-string
13657 "\\\\-" "-"
13658 (match-string 2 term)))
13659 re-p (equal (string-to-char tag) ?{)
13660 level-p (match-end 4)
13661 prop-p (match-end 5)
13662 mm (cond
13663 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13664 (level-p
13665 (setq level-op (org-op-to-function (match-string 3 term)))
13666 `(,level-op level ,(string-to-number
13667 (match-string 4 term))))
13668 (prop-p
13669 (setq pn (match-string 5 term)
13670 po (match-string 6 term)
13671 pv (match-string 7 term)
13672 re-p (equal (string-to-char pv) ?{)
13673 str-p (equal (string-to-char pv) ?\")
13674 time-p (save-match-data
13675 (string-match "^\"[[<].*[]>]\"$" pv))
13676 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13677 (if time-p (setq pv (org-matcher-time pv)))
13678 (setq po (org-op-to-function po (if time-p 'time str-p)))
13679 (cond
13680 ((equal pn "CATEGORY")
13681 (setq gv '(get-text-property (point) 'org-category)))
13682 ((equal pn "TODO")
13683 (setq gv 'todo))
13685 (setq gv `(org-cached-entry-get nil ,pn))))
13686 (if re-p
13687 (if (eq po 'org<>)
13688 `(not (string-match ,pv (or ,gv "")))
13689 `(string-match ,pv (or ,gv "")))
13690 (if str-p
13691 `(,po (or ,gv "") ,pv)
13692 `(,po (string-to-number (or ,gv ""))
13693 ,(string-to-number pv) ))))
13694 (t `(member ,tag tags-list)))
13695 mm (if minus (list 'not mm) mm)
13696 term rest)
13697 (push mm tagsmatcher))
13698 (push (if (> (length tagsmatcher) 1)
13699 (cons 'and tagsmatcher)
13700 (car tagsmatcher))
13701 orlist)
13702 (setq tagsmatcher nil))
13703 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13704 (setq tagsmatcher
13705 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13706 ;; Make the todo matcher
13707 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13708 (setq todomatcher t)
13709 (setq orterms (org-split-string todomatch "|") orlist nil)
13710 (while (setq term (pop orterms))
13711 (while (string-match re term)
13712 (setq minus (and (match-end 1)
13713 (equal (match-string 1 term) "-"))
13714 kwd (match-string 2 term)
13715 re-p (equal (string-to-char kwd) ?{)
13716 term (substring term (match-end 0))
13717 mm (if re-p
13718 `(string-match ,(substring kwd 1 -1) todo)
13719 (list 'equal 'todo kwd))
13720 mm (if minus (list 'not mm) mm))
13721 (push mm todomatcher))
13722 (push (if (> (length todomatcher) 1)
13723 (cons 'and todomatcher)
13724 (car todomatcher))
13725 orlist)
13726 (setq todomatcher nil))
13727 (setq todomatcher (if (> (length orlist) 1)
13728 (cons 'or orlist) (car orlist))))
13730 ;; Return the string and lisp forms of the matcher
13731 (setq matcher (if todomatcher
13732 (list 'and tagsmatcher todomatcher)
13733 tagsmatcher))
13734 (when todo-only
13735 (setq matcher (list 'and '(member todo org-not-done-keywords)
13736 matcher)))
13737 (cons match0 matcher)))
13739 (defun org-op-to-function (op &optional stringp)
13740 "Turn an operator into the appropriate function."
13741 (setq op
13742 (cond
13743 ((equal op "<" ) '(< string< org-time<))
13744 ((equal op ">" ) '(> org-string> org-time>))
13745 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13746 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13747 ((member op '("=" "==")) '(= string= org-time=))
13748 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13749 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13751 (defun org<> (a b) (not (= a b)))
13752 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13753 (defun org-string>= (a b) (not (string< a b)))
13754 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13755 (defun org-string<> (a b) (not (string= a b)))
13756 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13757 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13758 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13759 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13760 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13761 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13762 (defun org-2ft (s)
13763 "Convert S to a floating point time.
13764 If S is already a number, just return it. If it is a string, parse
13765 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13766 (cond
13767 ((numberp s) s)
13768 ((stringp s)
13769 (condition-case nil
13770 (float-time (apply 'encode-time (org-parse-time-string s)))
13771 (error 0.)))
13772 (t 0.)))
13774 (defun org-time-today ()
13775 "Time in seconds today at 0:00.
13776 Returns the float number of seconds since the beginning of the
13777 epoch to the beginning of today (00:00)."
13778 (float-time (apply 'encode-time
13779 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13781 (defun org-matcher-time (s)
13782 "Interpret a time comparison value."
13783 (save-match-data
13784 (cond
13785 ((string= s "<now>") (float-time))
13786 ((string= s "<today>") (org-time-today))
13787 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13788 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13789 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13790 (+ (org-time-today)
13791 (* (string-to-number (match-string 1 s))
13792 (cdr (assoc (match-string 2 s)
13793 '(("d" . 86400.0) ("w" . 604800.0)
13794 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13795 (t (org-2ft s)))))
13797 (defun org-match-any-p (re list)
13798 "Does re match any element of list?"
13799 (setq list (mapcar (lambda (x) (string-match re x)) list))
13800 (delq nil list))
13802 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13803 (defvar org-tags-overlay (make-overlay 1 1))
13804 (org-detach-overlay org-tags-overlay)
13806 (defun org-get-local-tags-at (&optional pos)
13807 "Get a list of tags defined in the current headline."
13808 (org-get-tags-at pos 'local))
13810 (defun org-get-local-tags ()
13811 "Get a list of tags defined in the current headline."
13812 (org-get-tags-at nil 'local))
13814 (defun org-get-tags-at (&optional pos local)
13815 "Get a list of all headline tags applicable at POS.
13816 POS defaults to point. If tags are inherited, the list contains
13817 the targets in the same sequence as the headlines appear, i.e.
13818 the tags of the current headline come last.
13819 When LOCAL is non-nil, only return tags from the current headline,
13820 ignore inherited ones."
13821 (interactive)
13822 (if (and org-trust-scanner-tags
13823 (or (not pos) (equal pos (point)))
13824 (not local))
13825 org-scanner-tags
13826 (let (tags ltags lastpos parent)
13827 (save-excursion
13828 (save-restriction
13829 (widen)
13830 (goto-char (or pos (point)))
13831 (save-match-data
13832 (catch 'done
13833 (condition-case nil
13834 (progn
13835 (org-back-to-heading t)
13836 (while (not (equal lastpos (point)))
13837 (setq lastpos (point))
13838 (when (looking-at
13839 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13840 (setq ltags (org-split-string
13841 (org-match-string-no-properties 1) ":"))
13842 (when parent
13843 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13844 (setq tags (append
13845 (if parent
13846 (org-remove-uninherited-tags ltags)
13847 ltags)
13848 tags)))
13849 (or org-use-tag-inheritance (throw 'done t))
13850 (if local (throw 'done t))
13851 (or (org-up-heading-safe) (error nil))
13852 (setq parent t)))
13853 (error nil)))))
13854 (if local
13855 tags
13856 (reverse (delete-dups
13857 (reverse (append
13858 (org-remove-uninherited-tags
13859 org-file-tags) tags)))))))))
13861 (defun org-add-prop-inherited (s)
13862 (add-text-properties 0 (length s) '(inherited t) s)
13865 (defun org-toggle-tag (tag &optional onoff)
13866 "Toggle the tag TAG for the current line.
13867 If ONOFF is `on' or `off', don't toggle but set to this state."
13868 (let (res current)
13869 (save-excursion
13870 (org-back-to-heading t)
13871 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13872 (point-at-eol) t)
13873 (progn
13874 (setq current (match-string 1))
13875 (replace-match ""))
13876 (setq current ""))
13877 (setq current (nreverse (org-split-string current ":")))
13878 (cond
13879 ((eq onoff 'on)
13880 (setq res t)
13881 (or (member tag current) (push tag current)))
13882 ((eq onoff 'off)
13883 (or (not (member tag current)) (setq current (delete tag current))))
13884 (t (if (member tag current)
13885 (setq current (delete tag current))
13886 (setq res t)
13887 (push tag current))))
13888 (end-of-line 1)
13889 (if current
13890 (progn
13891 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13892 (org-set-tags nil t))
13893 (delete-horizontal-space))
13894 (run-hooks 'org-after-tags-change-hook))
13895 res))
13897 (defun org-align-tags-here (to-col)
13898 ;; Assumes that this is a headline
13899 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13900 (beginning-of-line 1)
13901 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13902 (< pos (match-beginning 2)))
13903 (progn
13904 (setq tags-l (- (match-end 2) (match-beginning 2)))
13905 (goto-char (match-beginning 1))
13906 (insert " ")
13907 (delete-region (point) (1+ (match-beginning 2)))
13908 (setq ncol (max (current-column)
13909 (1+ col)
13910 (if (> to-col 0)
13911 to-col
13912 (- (abs to-col) tags-l))))
13913 (setq p (point))
13914 (insert (make-string (- ncol (current-column)) ?\ ))
13915 (setq ncol (current-column))
13916 (when indent-tabs-mode (tabify p (point-at-eol)))
13917 (org-move-to-column (min ncol col) t))
13918 (goto-char pos))))
13920 (defun org-set-tags-command (&optional arg just-align)
13921 "Call the set-tags command for the current entry."
13922 (interactive "P")
13923 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13924 (org-set-tags arg just-align)
13925 (save-excursion
13926 (org-back-to-heading t)
13927 (org-set-tags arg just-align))))
13929 (defun org-set-tags-to (data)
13930 "Set the tags of the current entry to DATA, replacing the current tags.
13931 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13932 If DATA is nil or the empty string, any tags will be removed."
13933 (interactive "sTags: ")
13934 (setq data
13935 (cond
13936 ((eq data nil) "")
13937 ((equal data "") "")
13938 ((stringp data)
13939 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13940 ":"))
13941 ((listp data)
13942 (concat ":" (mapconcat 'identity data ":") ":"))))
13943 (when data
13944 (save-excursion
13945 (org-back-to-heading t)
13946 (when (looking-at org-complex-heading-regexp)
13947 (if (match-end 5)
13948 (progn
13949 (goto-char (match-beginning 5))
13950 (insert data)
13951 (delete-region (point) (point-at-eol))
13952 (org-set-tags nil 'align))
13953 (goto-char (point-at-eol))
13954 (insert " " data)
13955 (org-set-tags nil 'align)))
13956 (beginning-of-line 1)
13957 (if (looking-at ".*?\\([ \t]+\\)$")
13958 (delete-region (match-beginning 1) (match-end 1))))))
13960 (defun org-align-all-tags ()
13961 "Align the tags i all headings."
13962 (interactive)
13963 (save-excursion
13964 (or (ignore-errors (org-back-to-heading t))
13965 (outline-next-heading))
13966 (if (org-at-heading-p)
13967 (org-set-tags t)
13968 (message "No headings"))))
13970 (defvar org-indent-indentation-per-level)
13971 (defun org-set-tags (&optional arg just-align)
13972 "Set the tags for the current headline.
13973 With prefix ARG, realign all tags in headings in the current buffer."
13974 (interactive "P")
13975 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13976 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13977 'region-start-level 'region))
13978 org-loop-over-headlines-in-active-region)
13979 (org-map-entries
13980 ;; We don't use ARG and JUST-ALIGN here these args are not
13981 ;; useful when looping over headlines
13982 `(org-set-tags)
13983 org-loop-over-headlines-in-active-region
13984 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13985 (let* ((re org-outline-regexp-bol)
13986 (current (unless arg (org-get-tags-string)))
13987 (col (current-column))
13988 (org-setting-tags t)
13989 table current-tags inherited-tags ; computed below when needed
13990 tags p0 c0 c1 rpl di tc level)
13991 (if arg
13992 (save-excursion
13993 (goto-char (point-min))
13994 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13995 (while (re-search-forward re nil t)
13996 (org-set-tags nil t)
13997 (end-of-line 1)))
13998 (message "All tags realigned to column %d" org-tags-column))
13999 (if just-align
14000 (setq tags current)
14001 ;; Get a new set of tags from the user
14002 (save-excursion
14003 (setq table (append org-tag-persistent-alist
14004 (or org-tag-alist (org-get-buffer-tags))
14005 (and
14006 org-complete-tags-always-offer-all-agenda-tags
14007 (org-global-tags-completion-table
14008 (org-agenda-files))))
14009 org-last-tags-completion-table table
14010 current-tags (org-split-string current ":")
14011 inherited-tags (nreverse
14012 (nthcdr (length current-tags)
14013 (nreverse (org-get-tags-at))))
14014 tags
14015 (if (or (eq t org-use-fast-tag-selection)
14016 (and org-use-fast-tag-selection
14017 (delq nil (mapcar 'cdr table))))
14018 (org-fast-tag-selection
14019 current-tags inherited-tags table
14020 (if org-fast-tag-selection-include-todo
14021 org-todo-key-alist))
14022 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14023 (org-trim
14024 (org-icompleting-read "Tags: "
14025 'org-tags-completion-function
14026 nil nil current 'org-tags-history))))))
14027 (while (string-match "[-+&]+" tags)
14028 ;; No boolean logic, just a list
14029 (setq tags (replace-match ":" t t tags))))
14031 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14033 (if org-tags-sort-function
14034 (setq tags (mapconcat 'identity
14035 (sort (org-split-string
14036 tags (org-re "[^[:alnum:]_@#%]+"))
14037 org-tags-sort-function) ":")))
14039 (if (string-match "\\`[\t ]*\\'" tags)
14040 (setq tags "")
14041 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14042 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14044 ;; Insert new tags at the correct column
14045 (beginning-of-line 1)
14046 (setq level (or (and (looking-at org-outline-regexp)
14047 (- (match-end 0) (point) 1))
14049 (cond
14050 ((and (equal current "") (equal tags "")))
14051 ((re-search-forward
14052 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14053 (point-at-eol) t)
14054 (if (equal tags "")
14055 (setq rpl "")
14056 (goto-char (match-beginning 0))
14057 (setq c0 (current-column)
14058 ;; compute offset for the case of org-indent-mode active
14059 di (if org-indent-mode
14060 (* (1- org-indent-indentation-per-level) (1- level))
14062 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14063 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14064 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14065 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14066 (replace-match rpl t t)
14067 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14068 tags)
14069 (t (error "Tags alignment failed")))
14070 (org-move-to-column col)
14071 (unless just-align
14072 (run-hooks 'org-after-tags-change-hook))))))
14074 (defun org-change-tag-in-region (beg end tag off)
14075 "Add or remove TAG for each entry in the region.
14076 This works in the agenda, and also in an org-mode buffer."
14077 (interactive
14078 (list (region-beginning) (region-end)
14079 (let ((org-last-tags-completion-table
14080 (if (derived-mode-p 'org-mode)
14081 (org-get-buffer-tags)
14082 (org-global-tags-completion-table))))
14083 (org-icompleting-read
14084 "Tag: " 'org-tags-completion-function nil nil nil
14085 'org-tags-history))
14086 (progn
14087 (message "[s]et or [r]emove? ")
14088 (equal (read-char-exclusive) ?r))))
14089 (if (fboundp 'deactivate-mark) (deactivate-mark))
14090 (let ((agendap (equal major-mode 'org-agenda-mode))
14091 l1 l2 m buf pos newhead (cnt 0))
14092 (goto-char end)
14093 (setq l2 (1- (org-current-line)))
14094 (goto-char beg)
14095 (setq l1 (org-current-line))
14096 (loop for l from l1 to l2 do
14097 (org-goto-line l)
14098 (setq m (get-text-property (point) 'org-hd-marker))
14099 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14100 (and agendap m))
14101 (setq buf (if agendap (marker-buffer m) (current-buffer))
14102 pos (if agendap m (point)))
14103 (with-current-buffer buf
14104 (save-excursion
14105 (save-restriction
14106 (goto-char pos)
14107 (setq cnt (1+ cnt))
14108 (org-toggle-tag tag (if off 'off 'on))
14109 (setq newhead (org-get-heading)))))
14110 (and agendap (org-agenda-change-all-lines newhead m))))
14111 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14113 (defun org-tags-completion-function (string predicate &optional flag)
14114 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14115 (confirm (lambda (x) (stringp (car x)))))
14116 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14117 (setq s1 (match-string 1 string)
14118 s2 (match-string 2 string))
14119 (setq s1 "" s2 string))
14120 (cond
14121 ((eq flag nil)
14122 ;; try completion
14123 (setq rtn (try-completion s2 ctable confirm))
14124 (if (stringp rtn)
14125 (setq rtn
14126 (concat s1 s2 (substring rtn (length s2))
14127 (if (and org-add-colon-after-tag-completion
14128 (assoc rtn ctable))
14129 ":" ""))))
14130 rtn)
14131 ((eq flag t)
14132 ;; all-completions
14133 (all-completions s2 ctable confirm)
14135 ((eq flag 'lambda)
14136 ;; exact match?
14137 (assoc s2 ctable)))
14140 (defun org-fast-tag-insert (kwd tags face &optional end)
14141 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14142 (insert (format "%-12s" (concat kwd ":"))
14143 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14144 (or end "")))
14146 (defun org-fast-tag-show-exit (flag)
14147 (save-excursion
14148 (org-goto-line 3)
14149 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14150 (replace-match ""))
14151 (when flag
14152 (end-of-line 1)
14153 (org-move-to-column (- (window-width) 19) t)
14154 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14156 (defun org-set-current-tags-overlay (current prefix)
14157 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14158 (if (featurep 'xemacs)
14159 (org-overlay-display org-tags-overlay (concat prefix s)
14160 'secondary-selection)
14161 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14162 (org-overlay-display org-tags-overlay (concat prefix s)))))
14164 (defvar org-last-tag-selection-key nil)
14165 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14166 "Fast tag selection with single keys.
14167 CURRENT is the current list of tags in the headline, INHERITED is the
14168 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14169 possibly with grouping information. TODO-TABLE is a similar table with
14170 TODO keywords, should these have keys assigned to them.
14171 If the keys are nil, a-z are automatically assigned.
14172 Returns the new tags string, or nil to not change the current settings."
14173 (let* ((fulltable (append table todo-table))
14174 (maxlen (apply 'max (mapcar
14175 (lambda (x)
14176 (if (stringp (car x)) (string-width (car x)) 0))
14177 fulltable)))
14178 (buf (current-buffer))
14179 (expert (eq org-fast-tag-selection-single-key 'expert))
14180 (buffer-tags nil)
14181 (fwidth (+ maxlen 3 1 3))
14182 (ncol (/ (- (window-width) 4) fwidth))
14183 (i-face 'org-done)
14184 (c-face 'org-todo)
14185 tg cnt e c char c1 c2 ntable tbl rtn
14186 ov-start ov-end ov-prefix
14187 (exit-after-next org-fast-tag-selection-single-key)
14188 (done-keywords org-done-keywords)
14189 groups ingroup)
14190 (save-excursion
14191 (beginning-of-line 1)
14192 (if (looking-at
14193 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14194 (setq ov-start (match-beginning 1)
14195 ov-end (match-end 1)
14196 ov-prefix "")
14197 (setq ov-start (1- (point-at-eol))
14198 ov-end (1+ ov-start))
14199 (skip-chars-forward "^\n\r")
14200 (setq ov-prefix
14201 (concat
14202 (buffer-substring (1- (point)) (point))
14203 (if (> (current-column) org-tags-column)
14205 (make-string (- org-tags-column (current-column)) ?\ ))))))
14206 (move-overlay org-tags-overlay ov-start ov-end)
14207 (save-window-excursion
14208 (if expert
14209 (set-buffer (get-buffer-create " *Org tags*"))
14210 (delete-other-windows)
14211 (split-window-vertically)
14212 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14213 (erase-buffer)
14214 (org-set-local 'org-done-keywords done-keywords)
14215 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14216 (org-fast-tag-insert "Current" current c-face "\n\n")
14217 (org-fast-tag-show-exit exit-after-next)
14218 (org-set-current-tags-overlay current ov-prefix)
14219 (setq tbl fulltable char ?a cnt 0)
14220 (while (setq e (pop tbl))
14221 (cond
14222 ((equal (car e) :startgroup)
14223 (push '() groups) (setq ingroup t)
14224 (when (not (= cnt 0))
14225 (setq cnt 0)
14226 (insert "\n"))
14227 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14228 ((equal (car e) :endgroup)
14229 (setq ingroup nil cnt 0)
14230 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14231 ((equal e '(:newline))
14232 (when (not (= cnt 0))
14233 (setq cnt 0)
14234 (insert "\n")
14235 (setq e (car tbl))
14236 (while (equal (car tbl) '(:newline))
14237 (insert "\n")
14238 (setq tbl (cdr tbl)))))
14240 (setq tg (copy-sequence (car e)) c2 nil)
14241 (if (cdr e)
14242 (setq c (cdr e))
14243 ;; automatically assign a character.
14244 (setq c1 (string-to-char
14245 (downcase (substring
14246 tg (if (= (string-to-char tg) ?@) 1 0)))))
14247 (if (or (rassoc c1 ntable) (rassoc c1 table))
14248 (while (or (rassoc char ntable) (rassoc char table))
14249 (setq char (1+ char)))
14250 (setq c2 c1))
14251 (setq c (or c2 char)))
14252 (if ingroup (push tg (car groups)))
14253 (setq tg (org-add-props tg nil 'face
14254 (cond
14255 ((not (assoc tg table))
14256 (org-get-todo-face tg))
14257 ((member tg current) c-face)
14258 ((member tg inherited) i-face))))
14259 (if (and (= cnt 0) (not ingroup)) (insert " "))
14260 (insert "[" c "] " tg (make-string
14261 (- fwidth 4 (length tg)) ?\ ))
14262 (push (cons tg c) ntable)
14263 (when (= (setq cnt (1+ cnt)) ncol)
14264 (insert "\n")
14265 (if ingroup (insert " "))
14266 (setq cnt 0)))))
14267 (setq ntable (nreverse ntable))
14268 (insert "\n")
14269 (goto-char (point-min))
14270 (if (not expert) (org-fit-window-to-buffer))
14271 (setq rtn
14272 (catch 'exit
14273 (while t
14274 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14275 (if (not groups) "no " "")
14276 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14277 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14278 (setq org-last-tag-selection-key c)
14279 (cond
14280 ((= c ?\r) (throw 'exit t))
14281 ((= c ?!)
14282 (setq groups (not groups))
14283 (goto-char (point-min))
14284 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14285 ((= c ?\C-c)
14286 (if (not expert)
14287 (org-fast-tag-show-exit
14288 (setq exit-after-next (not exit-after-next)))
14289 (setq expert nil)
14290 (delete-other-windows)
14291 (set-window-buffer (split-window-vertically) " *Org tags*")
14292 (org-switch-to-buffer-other-window " *Org tags*")
14293 (org-fit-window-to-buffer)))
14294 ((or (= c ?\C-g)
14295 (and (= c ?q) (not (rassoc c ntable))))
14296 (org-detach-overlay org-tags-overlay)
14297 (setq quit-flag t))
14298 ((= c ?\ )
14299 (setq current nil)
14300 (if exit-after-next (setq exit-after-next 'now)))
14301 ((= c ?\t)
14302 (condition-case nil
14303 (setq tg (org-icompleting-read
14304 "Tag: "
14305 (or buffer-tags
14306 (with-current-buffer buf
14307 (org-get-buffer-tags)))))
14308 (quit (setq tg "")))
14309 (when (string-match "\\S-" tg)
14310 (add-to-list 'buffer-tags (list tg))
14311 (if (member tg current)
14312 (setq current (delete tg current))
14313 (push tg current)))
14314 (if exit-after-next (setq exit-after-next 'now)))
14315 ((setq e (rassoc c todo-table) tg (car e))
14316 (with-current-buffer buf
14317 (save-excursion (org-todo tg)))
14318 (if exit-after-next (setq exit-after-next 'now)))
14319 ((setq e (rassoc c ntable) tg (car e))
14320 (if (member tg current)
14321 (setq current (delete tg current))
14322 (loop for g in groups do
14323 (if (member tg g)
14324 (mapc (lambda (x)
14325 (setq current (delete x current)))
14326 g)))
14327 (push tg current))
14328 (if exit-after-next (setq exit-after-next 'now))))
14330 ;; Create a sorted list
14331 (setq current
14332 (sort current
14333 (lambda (a b)
14334 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14335 (if (eq exit-after-next 'now) (throw 'exit t))
14336 (goto-char (point-min))
14337 (beginning-of-line 2)
14338 (delete-region (point) (point-at-eol))
14339 (org-fast-tag-insert "Current" current c-face)
14340 (org-set-current-tags-overlay current ov-prefix)
14341 (while (re-search-forward
14342 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14343 (setq tg (match-string 1))
14344 (add-text-properties
14345 (match-beginning 1) (match-end 1)
14346 (list 'face
14347 (cond
14348 ((member tg current) c-face)
14349 ((member tg inherited) i-face)
14350 (t (get-text-property (match-beginning 1) 'face))))))
14351 (goto-char (point-min)))))
14352 (org-detach-overlay org-tags-overlay)
14353 (if rtn
14354 (mapconcat 'identity current ":")
14355 nil))))
14357 (defun org-get-tags-string ()
14358 "Get the TAGS string in the current headline."
14359 (unless (org-at-heading-p t)
14360 (error "Not on a heading"))
14361 (save-excursion
14362 (beginning-of-line 1)
14363 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14364 (org-match-string-no-properties 1)
14365 "")))
14367 (defun org-get-tags ()
14368 "Get the list of tags specified in the current headline."
14369 (org-split-string (org-get-tags-string) ":"))
14371 (defun org-get-buffer-tags ()
14372 "Get a table of all tags used in the buffer, for completion."
14373 (let (tags)
14374 (save-excursion
14375 (goto-char (point-min))
14376 (while (re-search-forward
14377 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14378 (when (equal (char-after (point-at-bol 0)) ?*)
14379 (mapc (lambda (x) (add-to-list 'tags x))
14380 (org-split-string (org-match-string-no-properties 1) ":")))))
14381 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14382 (mapcar 'list tags)))
14384 ;;;; The mapping API
14386 (defun org-map-entries (func &optional match scope &rest skip)
14387 "Call FUNC at each headline selected by MATCH in SCOPE.
14389 FUNC is a function or a lisp form. The function will be called without
14390 arguments, with the cursor positioned at the beginning of the headline.
14391 The return values of all calls to the function will be collected and
14392 returned as a list.
14394 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14395 does not need to preserve point. After evaluation, the cursor will be
14396 moved to the end of the line (presumably of the headline of the
14397 processed entry) and search continues from there. Under some
14398 circumstances, this may not produce the wanted results. For example,
14399 if you have removed (e.g. archived) the current (sub)tree it could
14400 mean that the next entry will be skipped entirely. In such cases, you
14401 can specify the position from where search should continue by making
14402 FUNC set the variable `org-map-continue-from' to the desired buffer
14403 position.
14405 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14406 Only headlines that are matched by this query will be considered during
14407 the iteration. When MATCH is nil or t, all headlines will be
14408 visited by the iteration.
14410 SCOPE determines the scope of this command. It can be any of:
14412 nil The current buffer, respecting the restriction if any
14413 tree The subtree started with the entry at point
14414 region The entries within the active region, if any
14415 region-start-level
14416 The entries within the active region, but only those at
14417 the same level than the first one.
14418 file The current buffer, without restriction
14419 file-with-archives
14420 The current buffer, and any archives associated with it
14421 agenda All agenda files
14422 agenda-with-archives
14423 All agenda files with any archive files associated with them
14424 \(file1 file2 ...)
14425 If this is a list, all files in the list will be scanned
14427 The remaining args are treated as settings for the skipping facilities of
14428 the scanner. The following items can be given here:
14430 archive skip trees with the archive tag.
14431 comment skip trees with the COMMENT keyword
14432 function or Emacs Lisp form:
14433 will be used as value for `org-agenda-skip-function', so whenever
14434 the function returns t, FUNC will not be called for that
14435 entry and search will continue from the point where the
14436 function leaves it.
14438 If your function needs to retrieve the tags including inherited tags
14439 at the *current* entry, you can use the value of the variable
14440 `org-scanner-tags' which will be much faster than getting the value
14441 with `org-get-tags-at'. If your function gets properties with
14442 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14443 to t around the call to `org-entry-properties' to get the same speedup.
14444 Note that if your function moves around to retrieve tags and properties at
14445 a *different* entry, you cannot use these techniques."
14446 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14447 (not (org-region-active-p)))
14448 (let* ((org-agenda-archives-mode nil) ; just to make sure
14449 (org-agenda-skip-archived-trees (memq 'archive skip))
14450 (org-agenda-skip-comment-trees (memq 'comment skip))
14451 (org-agenda-skip-function
14452 (car (org-delete-all '(comment archive) skip)))
14453 (org-tags-match-list-sublevels t)
14454 (start-level (eq scope 'region-start-level))
14455 matcher file res
14456 org-todo-keywords-for-agenda
14457 org-done-keywords-for-agenda
14458 org-todo-keyword-alist-for-agenda
14459 org-drawers-for-agenda
14460 org-tag-alist-for-agenda
14461 todo-only)
14463 (cond
14464 ((eq match t) (setq matcher t))
14465 ((eq match nil) (setq matcher t))
14466 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14468 (save-excursion
14469 (save-restriction
14470 (cond ((eq scope 'tree)
14471 (org-back-to-heading t)
14472 (org-narrow-to-subtree)
14473 (setq scope nil))
14474 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14475 (org-region-active-p))
14476 ;; If needed, set start-level to a string like "2"
14477 (when start-level
14478 (save-excursion
14479 (goto-char (region-beginning))
14480 (unless (org-at-heading-p) (outline-next-heading))
14481 (setq start-level (org-current-level))))
14482 (narrow-to-region (region-beginning)
14483 (save-excursion
14484 (goto-char (region-end))
14485 (unless (and (bolp) (org-at-heading-p))
14486 (outline-next-heading))
14487 (point)))
14488 (setq scope nil)))
14490 (if (not scope)
14491 (progn
14492 (org-agenda-prepare-buffers
14493 (list (buffer-file-name (current-buffer))))
14494 (setq res (org-scan-tags func matcher todo-only start-level)))
14495 ;; Get the right scope
14496 (cond
14497 ((and scope (listp scope) (symbolp (car scope)))
14498 (setq scope (eval scope)))
14499 ((eq scope 'agenda)
14500 (setq scope (org-agenda-files t)))
14501 ((eq scope 'agenda-with-archives)
14502 (setq scope (org-agenda-files t))
14503 (setq scope (org-add-archive-files scope)))
14504 ((eq scope 'file)
14505 (setq scope (list (buffer-file-name))))
14506 ((eq scope 'file-with-archives)
14507 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14508 (org-agenda-prepare-buffers scope)
14509 (while (setq file (pop scope))
14510 (with-current-buffer (org-find-base-buffer-visiting file)
14511 (save-excursion
14512 (save-restriction
14513 (widen)
14514 (goto-char (point-min))
14515 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14516 res)))
14518 ;;;; Properties
14520 ;;; Setting and retrieving properties
14522 (defconst org-special-properties
14523 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14524 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14525 "The special properties valid in Org-mode.
14527 These are properties that are not defined in the property drawer,
14528 but in some other way.")
14530 (defconst org-default-properties
14531 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14532 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14533 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14534 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14535 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14536 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14537 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14538 "Some properties that are used by Org-mode for various purposes.
14539 Being in this list makes sure that they are offered for completion.")
14541 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14542 "Regular expression matching the first line of a property drawer.")
14544 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14545 "Regular expression matching the last line of a property drawer.")
14547 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14548 "Regular expression matching the first line of a property drawer.")
14550 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14551 "Regular expression matching the first line of a property drawer.")
14553 (defconst org-property-drawer-re
14554 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14555 org-property-end-re "\\)\n?")
14556 "Matches an entire property drawer.")
14558 (defconst org-clock-drawer-re
14559 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14560 org-property-end-re "\\)\n?")
14561 "Matches an entire clock drawer.")
14563 (defsubst org-re-property (property)
14564 "Return a regexp matching a PROPERTY line.
14565 Match group 1 will be set to the value."
14566 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14568 (defsubst org-re-property-keyword (property)
14569 "Return a regexp matching a PROPERTY line, possibly with no
14570 value for the property."
14571 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14573 (defun org-property-action ()
14574 "Do an action on properties."
14575 (interactive)
14576 (let (c)
14577 (org-at-property-p)
14578 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14579 (setq c (read-char-exclusive))
14580 (cond
14581 ((equal c ?s)
14582 (call-interactively 'org-set-property))
14583 ((equal c ?d)
14584 (call-interactively 'org-delete-property))
14585 ((equal c ?D)
14586 (call-interactively 'org-delete-property-globally))
14587 ((equal c ?c)
14588 (call-interactively 'org-compute-property-at-point))
14589 (t (error "No such property action %c" c)))))
14591 (defun org-inc-effort ()
14592 "Increment the value of the effort property in the current entry."
14593 (interactive)
14594 (org-set-effort nil t))
14596 (defun org-set-effort (&optional value increment)
14597 "Set the effort property of the current entry.
14598 With numerical prefix arg, use the nth allowed value, 0 stands for the
14599 10th allowed value.
14601 When INCREMENT is non-nil, set the property to the next allowed value."
14602 (interactive "P")
14603 (if (equal value 0) (setq value 10))
14604 (let* ((completion-ignore-case t)
14605 (prop org-effort-property)
14606 (cur (org-entry-get nil prop))
14607 (allowed (org-property-get-allowed-values nil prop 'table))
14608 (existing (mapcar 'list (org-property-values prop)))
14610 (val (cond
14611 ((stringp value) value)
14612 ((and allowed (integerp value))
14613 (or (car (nth (1- value) allowed))
14614 (car (org-last allowed))))
14615 ((and allowed increment)
14616 (or (caadr (member (list cur) allowed))
14617 (error "Allowed effort values are not set")))
14618 (allowed
14619 (message "Select 1-9,0, [RET%s]: %s"
14620 (if cur (concat "=" cur) "")
14621 (mapconcat 'car allowed " "))
14622 (setq rpl (read-char-exclusive))
14623 (if (equal rpl ?\r)
14625 (setq rpl (- rpl ?0))
14626 (if (equal rpl 0) (setq rpl 10))
14627 (if (and (> rpl 0) (<= rpl (length allowed)))
14628 (car (nth (1- rpl) allowed))
14629 (org-completing-read "Effort: " allowed nil))))
14631 (let (org-completion-use-ido org-completion-use-iswitchb)
14632 (org-completing-read
14633 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14634 (concat "[" cur "]") "")
14635 ": ")
14636 existing nil nil "" nil cur))))))
14637 (unless (equal (org-entry-get nil prop) val)
14638 (org-entry-put nil prop val))
14639 (save-excursion
14640 (org-back-to-heading t)
14641 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14642 (message "%s is now %s" prop val)))
14644 (defun org-at-property-p ()
14645 "Is cursor inside a property drawer?"
14646 (save-excursion
14647 (beginning-of-line 1)
14648 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14649 (save-match-data ;; Used by calling procedures
14650 (let ((p (point))
14651 (range (unless (org-before-first-heading-p)
14652 (org-get-property-block))))
14653 (and range (<= (car range) p) (< p (cdr range))))))))
14655 (defun org-get-property-block (&optional beg end force)
14656 "Return the (beg . end) range of the body of the property drawer.
14657 BEG and END are the beginning and end of the current subtree, or of
14658 the part before the first headline. If they are not given, they will
14659 be found. If the drawer does not exist and FORCE is non-nil, create
14660 the drawer."
14661 (catch 'exit
14662 (save-excursion
14663 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14664 (progn (org-back-to-heading t) (point))))
14665 (end (or end (and (not (outline-next-heading)) (point-max))
14666 (point))))
14667 (goto-char beg)
14668 (if (re-search-forward org-property-start-re end t)
14669 (setq beg (1+ (match-end 0)))
14670 (if force
14671 (save-excursion
14672 (org-insert-property-drawer)
14673 (setq end (progn (outline-next-heading) (point))))
14674 (throw 'exit nil))
14675 (goto-char beg)
14676 (if (re-search-forward org-property-start-re end t)
14677 (setq beg (1+ (match-end 0)))))
14678 (if (re-search-forward org-property-end-re end t)
14679 (setq end (match-beginning 0))
14680 (or force (throw 'exit nil))
14681 (goto-char beg)
14682 (setq end beg)
14683 (org-indent-line)
14684 (insert ":END:\n"))
14685 (cons beg end)))))
14687 (defun org-entry-properties (&optional pom which specific)
14688 "Get all properties of the entry at point-or-marker POM.
14689 This includes the TODO keyword, the tags, time strings for deadline,
14690 scheduled, and clocking, and any additional properties defined in the
14691 entry. The return value is an alist, keys may occur multiple times
14692 if the property key was used several times.
14693 POM may also be nil, in which case the current entry is used.
14694 If WHICH is nil or `all', get all properties. If WHICH is
14695 `special' or `standard', only get that subclass. If WHICH
14696 is a string only get exactly this property. SPECIFIC can be a string, the
14697 specific property we are interested in. Specifying it can speed
14698 things up because then unnecessary parsing is avoided."
14699 (setq which (or which 'all))
14700 (org-with-point-at pom
14701 (let ((clockstr (substring org-clock-string 0 -1))
14702 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14703 (case-fold-search nil)
14704 beg end range props sum-props key key1 value string clocksum clocksumt)
14705 (save-excursion
14706 (when (condition-case nil
14707 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14708 (error nil))
14709 (setq beg (point))
14710 (setq sum-props (get-text-property (point) 'org-summaries))
14711 (setq clocksum (get-text-property (point) :org-clock-minutes)
14712 clocksumt (get-text-property (point) :org-clock-minutes-today))
14713 (outline-next-heading)
14714 (setq end (point))
14715 (when (memq which '(all special))
14716 ;; Get the special properties, like TODO and tags
14717 (goto-char beg)
14718 (when (and (or (not specific) (string= specific "TODO"))
14719 (looking-at org-todo-line-regexp) (match-end 2))
14720 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14721 (when (and (or (not specific) (string= specific "PRIORITY"))
14722 (looking-at org-priority-regexp))
14723 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14724 (when (or (not specific) (string= specific "FILE"))
14725 (push (cons "FILE" buffer-file-name) props))
14726 (when (and (or (not specific) (string= specific "TAGS"))
14727 (setq value (org-get-tags-string))
14728 (string-match "\\S-" value))
14729 (push (cons "TAGS" value) props))
14730 (when (and (or (not specific) (string= specific "ALLTAGS"))
14731 (setq value (org-get-tags-at)))
14732 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14733 ":"))
14734 props))
14735 (when (or (not specific) (string= specific "BLOCKED"))
14736 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14737 (when (or (not specific)
14738 (member specific
14739 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14740 "TIMESTAMP" "TIMESTAMP_IA")))
14741 (catch 'match
14742 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14743 (setq key (if (match-end 1)
14744 (substring (org-match-string-no-properties 1)
14745 0 -1))
14746 string (if (equal key clockstr)
14747 (org-trim
14748 (buffer-substring-no-properties
14749 (match-beginning 3) (goto-char
14750 (point-at-eol))))
14751 (substring (org-match-string-no-properties 3)
14752 1 -1)))
14753 ;; Get the correct property name from the key. This is
14754 ;; necessary if the user has configured time keywords.
14755 (setq key1 (concat key ":"))
14756 (cond
14757 ((not key)
14758 (setq key
14759 (if (= (char-after (match-beginning 3)) ?\[)
14760 "TIMESTAMP_IA" "TIMESTAMP")))
14761 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14762 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14763 ((equal key1 org-closed-string) (setq key "CLOSED"))
14764 ((equal key1 org-clock-string) (setq key "CLOCK")))
14765 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14766 (progn
14767 (push (cons key string) props)
14768 ;; no need to search further if match is found
14769 (throw 'match t))
14770 (when (or (equal key "CLOCK") (not (assoc key props)))
14771 (push (cons key string) props)))))))
14773 (when (memq which '(all standard))
14774 ;; Get the standard properties, like :PROP: ...
14775 (setq range (org-get-property-block beg end))
14776 (when range
14777 (goto-char (car range))
14778 (while (re-search-forward
14779 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14780 (cdr range) t)
14781 (setq key (org-match-string-no-properties 1)
14782 value (org-trim (or (org-match-string-no-properties 2) "")))
14783 (unless (member key excluded)
14784 (push (cons key (or value "")) props)))))
14785 (if clocksum
14786 (push (cons "CLOCKSUM"
14787 (org-columns-number-to-string (/ (float clocksum) 60.)
14788 'add_times))
14789 props))
14790 (if clocksumt
14791 (push (cons "CLOCKSUM_T"
14792 (org-columns-number-to-string (/ (float clocksumt) 60.)
14793 'add_times))
14794 props))
14795 (unless (assoc "CATEGORY" props)
14796 (push (cons "CATEGORY" (org-get-category)) props))
14797 (append sum-props (nreverse props)))))))
14799 (defun org-entry-get (pom property &optional inherit literal-nil)
14800 "Get value of PROPERTY for entry or content at point-or-marker POM.
14801 If INHERIT is non-nil and the entry does not have the property,
14802 then also check higher levels of the hierarchy.
14803 If INHERIT is the symbol `selective', use inheritance only if the setting
14804 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14805 If the property is present but empty, the return value is the empty string.
14806 If the property is not present at all, nil is returned.
14808 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14809 do not interpret it as the list atom nil. This is used for inheritance
14810 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14811 (org-with-point-at pom
14812 (if (and inherit (if (eq inherit 'selective)
14813 (org-property-inherit-p property)
14815 (org-entry-get-with-inheritance property literal-nil)
14816 (if (member property org-special-properties)
14817 ;; We need a special property. Use `org-entry-properties' to
14818 ;; retrieve it, but specify the wanted property
14819 (cdr (assoc property (org-entry-properties nil 'special property)))
14820 (let ((range (org-get-property-block)))
14821 (when (and range (not (eq (car range) (cdr range))))
14822 (let* ((props (list (or (assoc property org-file-properties)
14823 (assoc property org-global-properties)
14824 (assoc property org-global-properties-fixed))))
14825 (ap (lambda (key)
14826 (when (re-search-forward
14827 (org-re-property key) (cdr range) t)
14828 (setq props
14829 (org-update-property-plist
14831 (if (match-end 1)
14832 (org-match-string-no-properties 1) "")
14833 props)))))
14834 val)
14835 (goto-char (car range))
14836 (funcall ap property)
14837 (goto-char (car range))
14838 (while (funcall ap (concat property "+")))
14839 (setq val (cdr (assoc property props)))
14840 (when val (if literal-nil val (org-not-nil val))))))))))
14842 (defun org-property-or-variable-value (var &optional inherit)
14843 "Check if there is a property fixing the value of VAR.
14844 If yes, return this value. If not, return the current value of the variable."
14845 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14846 (if (and prop (stringp prop) (string-match "\\S-" prop))
14847 (read prop)
14848 (symbol-value var))))
14850 (defun org-entry-delete (pom property)
14851 "Delete the property PROPERTY from entry at point-or-marker POM."
14852 (org-with-point-at pom
14853 (if (member property org-special-properties)
14854 nil ; cannot delete these properties.
14855 (let ((range (org-get-property-block)))
14856 (if (and range
14857 (goto-char (car range))
14858 (re-search-forward
14859 (org-re-property property)
14860 (cdr range) t))
14861 (progn
14862 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14864 nil)))))
14866 ;; Multi-values properties are properties that contain multiple values
14867 ;; These values are assumed to be single words, separated by whitespace.
14868 (defun org-entry-add-to-multivalued-property (pom property value)
14869 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14870 (let* ((old (org-entry-get pom property))
14871 (values (and old (org-split-string old "[ \t]"))))
14872 (setq value (org-entry-protect-space value))
14873 (unless (member value values)
14874 (setq values (cons value values))
14875 (org-entry-put pom property
14876 (mapconcat 'identity values " ")))))
14878 (defun org-entry-remove-from-multivalued-property (pom property value)
14879 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14880 (let* ((old (org-entry-get pom property))
14881 (values (and old (org-split-string old "[ \t]"))))
14882 (setq value (org-entry-protect-space value))
14883 (when (member value values)
14884 (setq values (delete value values))
14885 (org-entry-put pom property
14886 (mapconcat 'identity values " ")))))
14888 (defun org-entry-member-in-multivalued-property (pom property value)
14889 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14890 (let* ((old (org-entry-get pom property))
14891 (values (and old (org-split-string old "[ \t]"))))
14892 (setq value (org-entry-protect-space value))
14893 (member value values)))
14895 (defun org-entry-get-multivalued-property (pom property)
14896 "Return a list of values in a multivalued property."
14897 (let* ((value (org-entry-get pom property))
14898 (values (and value (org-split-string value "[ \t]"))))
14899 (mapcar 'org-entry-restore-space values)))
14901 (defun org-entry-put-multivalued-property (pom property &rest values)
14902 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14903 VALUES should be a list of strings. Spaces will be protected."
14904 (org-entry-put pom property
14905 (mapconcat 'org-entry-protect-space values " "))
14906 (let* ((value (org-entry-get pom property))
14907 (values (and value (org-split-string value "[ \t]"))))
14908 (mapcar 'org-entry-restore-space values)))
14910 (defun org-entry-protect-space (s)
14911 "Protect spaces and newline in string S."
14912 (while (string-match " " s)
14913 (setq s (replace-match "%20" t t s)))
14914 (while (string-match "\n" s)
14915 (setq s (replace-match "%0A" t t s)))
14918 (defun org-entry-restore-space (s)
14919 "Restore spaces and newline in string S."
14920 (while (string-match "%20" s)
14921 (setq s (replace-match " " t t s)))
14922 (while (string-match "%0A" s)
14923 (setq s (replace-match "\n" t t s)))
14926 (defvar org-entry-property-inherited-from (make-marker)
14927 "Marker pointing to the entry from where a property was inherited.
14928 Each call to `org-entry-get-with-inheritance' will set this marker to the
14929 location of the entry where the inheritance search matched. If there was
14930 no match, the marker will point nowhere.
14931 Note that also `org-entry-get' calls this function, if the INHERIT flag
14932 is set.")
14934 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14935 "Get PROPERTY of entry or content at point, search higher levels if needed.
14936 The search will stop at the first ancestor which has the property defined.
14937 If the value found is \"nil\", return nil to show that the property
14938 should be considered as undefined (this is the meaning of nil here).
14939 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14940 (move-marker org-entry-property-inherited-from nil)
14941 (let (tmp)
14942 (save-excursion
14943 (save-restriction
14944 (widen)
14945 (catch 'ex
14946 (while t
14947 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14948 (or (ignore-errors (org-back-to-heading t))
14949 (goto-char (point-min)))
14950 (move-marker org-entry-property-inherited-from (point))
14951 (throw 'ex tmp))
14952 (or (ignore-errors (org-up-heading-safe))
14953 (throw 'ex nil))))))
14954 (setq tmp (or tmp
14955 (cdr (assoc property org-file-properties))
14956 (cdr (assoc property org-global-properties))
14957 (cdr (assoc property org-global-properties-fixed))))
14958 (if literal-nil tmp (org-not-nil tmp))))
14960 (defvar org-property-changed-functions nil
14961 "Hook called when the value of a property has changed.
14962 Each hook function should accept two arguments, the name of the property
14963 and the new value.")
14965 (defun org-entry-put (pom property value)
14966 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14967 (org-with-point-at pom
14968 (org-back-to-heading t)
14969 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14970 range)
14971 (cond
14972 ((equal property "TODO")
14973 (when (and (stringp value) (string-match "\\S-" value)
14974 (not (member value org-todo-keywords-1)))
14975 (error "\"%s\" is not a valid TODO state" value))
14976 (if (or (not value)
14977 (not (string-match "\\S-" value)))
14978 (setq value 'none))
14979 (org-todo value)
14980 (org-set-tags nil 'align))
14981 ((equal property "PRIORITY")
14982 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14983 (string-to-char value) ?\ ))
14984 (org-set-tags nil 'align))
14985 ((equal property "CLOCKSUM")
14986 (if (not (re-search-forward
14987 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14988 (error "Cannot find a clock log")
14989 (goto-char (- (match-end 1) 2))
14990 (cond
14991 ((eq value 'earlier) (org-timestamp-down))
14992 ((eq value 'later) (org-timestamp-up)))
14993 (org-clock-sum-current-item)))
14994 ((equal property "SCHEDULED")
14995 (if (re-search-forward org-scheduled-time-regexp end t)
14996 (cond
14997 ((eq value 'earlier) (org-timestamp-change -1 'day))
14998 ((eq value 'later) (org-timestamp-change 1 'day))
14999 (t (call-interactively 'org-schedule)))
15000 (call-interactively 'org-schedule)))
15001 ((equal property "DEADLINE")
15002 (if (re-search-forward org-deadline-time-regexp end t)
15003 (cond
15004 ((eq value 'earlier) (org-timestamp-change -1 'day))
15005 ((eq value 'later) (org-timestamp-change 1 'day))
15006 (t (call-interactively 'org-deadline)))
15007 (call-interactively 'org-deadline)))
15008 ((member property org-special-properties)
15009 (error "The %s property can not yet be set with `org-entry-put'"
15010 property))
15011 (t ; a non-special property
15012 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15013 (setq range (org-get-property-block beg end 'force))
15014 (goto-char (car range))
15015 (if (re-search-forward
15016 (org-re-property-keyword property) (cdr range) t)
15017 (progn
15018 (delete-region (match-beginning 0) (match-end 0))
15019 (goto-char (match-beginning 0)))
15020 (goto-char (cdr range))
15021 (insert "\n")
15022 (backward-char 1)
15023 (org-indent-line))
15024 (insert ":" property ":")
15025 (and value (insert " " value))
15026 (org-indent-line)))))
15027 (run-hook-with-args 'org-property-changed-functions property value)))
15029 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15030 "Get all property keys in the current buffer.
15031 With INCLUDE-SPECIALS, also list the special properties that reflect things
15032 like tags and TODO state.
15033 With INCLUDE-DEFAULTS, also include properties that has special meaning
15034 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15035 and others.
15036 With INCLUDE-COLUMNS, also include property names given in COLUMN
15037 formats in the current buffer."
15038 (let (rtn range cfmt s p)
15039 (save-excursion
15040 (save-restriction
15041 (widen)
15042 (goto-char (point-min))
15043 (while (re-search-forward org-property-start-re nil t)
15044 (setq range (org-get-property-block))
15045 (goto-char (car range))
15046 (while (re-search-forward
15047 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15048 (cdr range) t)
15049 (add-to-list 'rtn (org-match-string-no-properties 1)))
15050 (outline-next-heading))))
15052 (when include-specials
15053 (setq rtn (append org-special-properties rtn)))
15055 (when include-defaults
15056 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15057 (add-to-list 'rtn org-effort-property))
15059 (when include-columns
15060 (save-excursion
15061 (save-restriction
15062 (widen)
15063 (goto-char (point-min))
15064 (while (re-search-forward
15065 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15066 nil t)
15067 (setq cfmt (match-string 2) s 0)
15068 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15069 cfmt s)
15070 (setq s (match-end 0)
15071 p (match-string 1 cfmt))
15072 (unless (or (equal p "ITEM")
15073 (member p org-special-properties))
15074 (add-to-list 'rtn (match-string 1 cfmt))))))))
15076 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15078 (defun org-property-values (key)
15079 "Return a list of all values of property KEY in the current buffer."
15080 (save-excursion
15081 (save-restriction
15082 (widen)
15083 (goto-char (point-min))
15084 (let ((re (org-re-property key))
15085 values)
15086 (while (re-search-forward re nil t)
15087 (add-to-list 'values (org-trim (match-string 1))))
15088 (delete "" values)))))
15090 (defun org-insert-property-drawer ()
15091 "Insert a property drawer into the current entry."
15092 (org-back-to-heading t)
15093 (looking-at org-outline-regexp)
15094 (let ((indent (if org-adapt-indentation
15095 (- (match-end 0) (match-beginning 0))
15097 (beg (point))
15098 (re (concat "^[ \t]*" org-keyword-time-regexp))
15099 end hiddenp)
15100 (outline-next-heading)
15101 (setq end (point))
15102 (goto-char beg)
15103 (while (re-search-forward re end t))
15104 (setq hiddenp (outline-invisible-p))
15105 (end-of-line 1)
15106 (and (equal (char-after) ?\n) (forward-char 1))
15107 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15108 (if (member (match-string 1) '("CLOCK:" ":END:"))
15109 ;; just skip this line
15110 (beginning-of-line 2)
15111 ;; Drawer start, find the end
15112 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15113 (beginning-of-line 1)))
15114 (org-skip-over-state-notes)
15115 (skip-chars-backward " \t\n\r")
15116 (if (eq (char-before) ?*) (forward-char 1))
15117 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15118 (beginning-of-line 0)
15119 (org-indent-to-column indent)
15120 (beginning-of-line 2)
15121 (org-indent-to-column indent)
15122 (beginning-of-line 0)
15123 (if hiddenp
15124 (save-excursion
15125 (org-back-to-heading t)
15126 (hide-entry))
15127 (org-flag-drawer t))))
15129 (defun org-insert-drawer (&optional arg drawer)
15130 "Insert a drawer at point.
15132 Optional argument DRAWER, when non-nil, is a string representing
15133 drawer's name. Otherwise, the user is prompted for a name.
15135 If a region is active, insert the drawer around that region
15136 instead.
15138 Point is left between drawer's boundaries."
15139 (interactive "P")
15140 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15141 "LOGBOOK"))
15142 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15143 ;; internally by Org. They are meant to be inserted
15144 ;; automatically.
15145 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15146 ;; Remove system drawers from list. Note: For some reason,
15147 ;; `org-completing-read' ignores the predicate while
15148 ;; `completing-read' handles it fine.
15149 (drawer (if arg "PROPERTIES"
15150 (or drawer
15151 (completing-read
15152 "Drawer: " org-drawers
15153 (lambda (d) (not (member d system-drawers))))))))
15154 (cond
15155 ;; With C-u, fall back on `org-insert-property-drawer'
15156 (arg (org-insert-property-drawer))
15157 ;; With an active region, insert a drawer at point.
15158 ((not (org-region-active-p))
15159 (progn
15160 (unless (bolp) (insert "\n"))
15161 (insert (format ":%s:\n\n:END:\n" drawer))
15162 (forward-line -2)))
15163 ;; Otherwise, insert the drawer at point
15165 (let ((rbeg (region-beginning))
15166 (rend (copy-marker (region-end))))
15167 (unwind-protect
15168 (progn
15169 (goto-char rbeg)
15170 (beginning-of-line)
15171 (when (save-excursion
15172 (re-search-forward org-outline-regexp-bol rend t))
15173 (error "Drawers cannot contain headlines"))
15174 ;; Position point at the beginning of the first
15175 ;; non-blank line in region. Insert drawer's opening
15176 ;; there, then indent it.
15177 (org-skip-whitespace)
15178 (beginning-of-line)
15179 (insert ":" drawer ":\n")
15180 (forward-line -1)
15181 (indent-for-tab-command)
15182 ;; Move point to the beginning of the first blank line
15183 ;; after the last non-blank line in region. Insert
15184 ;; drawer's closing, then indent it.
15185 (goto-char rend)
15186 (skip-chars-backward " \r\t\n")
15187 (insert "\n:END:")
15188 (deactivate-mark t)
15189 (indent-for-tab-command)
15190 (unless (eolp) (insert "\n")))
15191 ;; Clear marker, whatever the outcome of insertion is.
15192 (set-marker rend nil)))))))
15194 (defvar org-property-set-functions-alist nil
15195 "Property set function alist.
15196 Each entry should have the following format:
15198 (PROPERTY . READ-FUNCTION)
15200 The read function will be called with the same argument as
15201 `org-completing-read'.")
15203 (defun org-set-property-function (property)
15204 "Get the function that should be used to set PROPERTY.
15205 This is computed according to `org-property-set-functions-alist'."
15206 (or (cdr (assoc property org-property-set-functions-alist))
15207 'org-completing-read))
15209 (defun org-read-property-value (property)
15210 "Read PROPERTY value from user."
15211 (let* ((completion-ignore-case t)
15212 (allowed (org-property-get-allowed-values nil property 'table))
15213 (cur (org-entry-get nil property))
15214 (prompt (concat property " value"
15215 (if (and cur (string-match "\\S-" cur))
15216 (concat " [" cur "]") "") ": "))
15217 (set-function (org-set-property-function property))
15218 (val (if allowed
15219 (funcall set-function prompt allowed nil
15220 (not (get-text-property 0 'org-unrestricted
15221 (caar allowed))))
15222 (let (org-completion-use-ido org-completion-use-iswitchb)
15223 (funcall set-function prompt
15224 (mapcar 'list (org-property-values property))
15225 nil nil "" nil cur)))))
15226 (if (equal val "")
15228 val)))
15230 (defvar org-last-set-property nil)
15231 (defvar org-last-set-property-value nil)
15232 (defun org-read-property-name ()
15233 "Read a property name."
15234 (let* ((completion-ignore-case t)
15235 (keys (org-buffer-property-keys nil t t))
15236 (default-prop (or (save-excursion
15237 (save-match-data
15238 (beginning-of-line)
15239 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15240 (null (string= (match-string 1) "END"))
15241 (match-string 1))))
15242 org-last-set-property))
15243 (property (org-icompleting-read
15244 (concat "Property"
15245 (if default-prop (concat " [" default-prop "]") "")
15246 ": ")
15247 (mapcar 'list keys)
15248 nil nil nil nil
15249 default-prop)))
15250 (if (member property keys)
15251 property
15252 (or (cdr (assoc (downcase property)
15253 (mapcar (lambda (x) (cons (downcase x) x))
15254 keys)))
15255 property))))
15257 (defun org-set-property-and-value (use-last)
15258 "Allow to set [PROPERTY]: [value] direction from prompt.
15259 When use-default, don't even ask, just use the last
15260 \"[PROPERTY]: [value]\" string from the history."
15261 (interactive "P")
15262 (let* ((completion-ignore-case t)
15263 (pv (or (and use-last org-last-set-property-value)
15264 (org-completing-read
15265 "Enter a \"[Property]: [value]\" pair: "
15266 nil nil nil nil nil
15267 org-last-set-property-value)))
15268 prop val)
15269 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15270 (setq prop (match-string 1 pv)
15271 val (match-string 2 pv))
15272 (org-set-property prop val))))
15274 (defun org-set-property (property value)
15275 "In the current entry, set PROPERTY to VALUE.
15276 When called interactively, this will prompt for a property name, offering
15277 completion on existing and default properties. And then it will prompt
15278 for a value, offering completion either on allowed values (via an inherited
15279 xxx_ALL property) or on existing values in other instances of this property
15280 in the current file."
15281 (interactive (list nil nil))
15282 (let* ((property (or property (org-read-property-name)))
15283 (value (or value (org-read-property-value property)))
15284 (fn (cdr (assoc property org-properties-postprocess-alist))))
15285 (setq org-last-set-property property)
15286 (setq org-last-set-property-value (concat property ": " value))
15287 ;; Possibly postprocess the inserted value:
15288 (when fn (setq value (funcall fn value)))
15289 (unless (equal (org-entry-get nil property) value)
15290 (org-entry-put nil property value))))
15292 (defun org-delete-property (property)
15293 "In the current entry, delete PROPERTY."
15294 (interactive
15295 (let* ((completion-ignore-case t)
15296 (prop (org-icompleting-read "Property: "
15297 (org-entry-properties nil 'standard))))
15298 (list prop)))
15299 (message "Property %s %s" property
15300 (if (org-entry-delete nil property)
15301 "deleted"
15302 "was not present in the entry")))
15304 (defun org-delete-property-globally (property)
15305 "Remove PROPERTY globally, from all entries."
15306 (interactive
15307 (let* ((completion-ignore-case t)
15308 (prop (org-icompleting-read
15309 "Globally remove property: "
15310 (mapcar 'list (org-buffer-property-keys)))))
15311 (list prop)))
15312 (save-excursion
15313 (save-restriction
15314 (widen)
15315 (goto-char (point-min))
15316 (let ((cnt 0))
15317 (while (re-search-forward
15318 (org-re-property property)
15319 nil t)
15320 (setq cnt (1+ cnt))
15321 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15322 (message "Property \"%s\" removed from %d entries" property cnt)))))
15324 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15326 (defun org-compute-property-at-point ()
15327 "Compute the property at point.
15328 This looks for an enclosing column format, extracts the operator and
15329 then applies it to the property in the column format's scope."
15330 (interactive)
15331 (unless (org-at-property-p)
15332 (error "Not at a property"))
15333 (let ((prop (org-match-string-no-properties 2)))
15334 (org-columns-get-format-and-top-level)
15335 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15336 (error "No operator defined for property %s" prop))
15337 (org-columns-compute prop)))
15339 (defvar org-property-allowed-value-functions nil
15340 "Hook for functions supplying allowed values for a specific property.
15341 The functions must take a single argument, the name of the property, and
15342 return a flat list of allowed values. If \":ETC\" is one of
15343 the values, this means that these values are intended as defaults for
15344 completion, but that other values should be allowed too.
15345 The functions must return nil if they are not responsible for this
15346 property.")
15348 (defun org-property-get-allowed-values (pom property &optional table)
15349 "Get allowed values for the property PROPERTY.
15350 When TABLE is non-nil, return an alist that can directly be used for
15351 completion."
15352 (let (vals)
15353 (cond
15354 ((equal property "TODO")
15355 (setq vals (org-with-point-at pom
15356 (append org-todo-keywords-1 '("")))))
15357 ((equal property "PRIORITY")
15358 (let ((n org-lowest-priority))
15359 (while (>= n org-highest-priority)
15360 (push (char-to-string n) vals)
15361 (setq n (1- n)))))
15362 ((member property org-special-properties))
15363 ((setq vals (run-hook-with-args-until-success
15364 'org-property-allowed-value-functions property)))
15366 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15367 (when (and vals (string-match "\\S-" vals))
15368 (setq vals (car (read-from-string (concat "(" vals ")"))))
15369 (setq vals (mapcar (lambda (x)
15370 (cond ((stringp x) x)
15371 ((numberp x) (number-to-string x))
15372 ((symbolp x) (symbol-name x))
15373 (t "???")))
15374 vals)))))
15375 (when (member ":ETC" vals)
15376 (setq vals (remove ":ETC" vals))
15377 (org-add-props (car vals) '(org-unrestricted t)))
15378 (if table (mapcar 'list vals) vals)))
15380 (defun org-property-previous-allowed-value (&optional previous)
15381 "Switch to the next allowed value for this property."
15382 (interactive)
15383 (org-property-next-allowed-value t))
15385 (defun org-property-next-allowed-value (&optional previous)
15386 "Switch to the next allowed value for this property."
15387 (interactive)
15388 (unless (org-at-property-p)
15389 (error "Not at a property"))
15390 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15391 (key (match-string 2))
15392 (value (match-string 3))
15393 (allowed (or (org-property-get-allowed-values (point) key)
15394 (and (member value '("[ ]" "[-]" "[X]"))
15395 '("[ ]" "[X]"))))
15396 nval)
15397 (unless allowed
15398 (error "Allowed values for this property have not been defined"))
15399 (if previous (setq allowed (reverse allowed)))
15400 (if (member value allowed)
15401 (setq nval (car (cdr (member value allowed)))))
15402 (setq nval (or nval (car allowed)))
15403 (if (equal nval value)
15404 (error "Only one allowed value for this property"))
15405 (org-at-property-p)
15406 (replace-match (concat " :" key ": " nval) t t)
15407 (org-indent-line)
15408 (beginning-of-line 1)
15409 (skip-chars-forward " \t")
15410 (when (equal prop org-effort-property)
15411 (save-excursion
15412 (org-back-to-heading t)
15413 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15414 (run-hook-with-args 'org-property-changed-functions key nval)))
15416 (defun org-find-olp (path &optional this-buffer)
15417 "Return a marker pointing to the entry at outline path OLP.
15418 If anything goes wrong, throw an error.
15419 You can wrap this call to catch the error like this:
15421 (condition-case msg
15422 (org-mobile-locate-entry (match-string 4))
15423 (error (nth 1 msg)))
15425 The return value will then be either a string with the error message,
15426 or a marker if everything is OK.
15428 If THIS-BUFFER is set, the outline path does not contain a file,
15429 only headings."
15430 (let* ((file (if this-buffer buffer-file-name (pop path)))
15431 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15432 (level 1)
15433 (lmin 1)
15434 (lmax 1)
15435 limit re end found pos heading cnt flevel)
15436 (unless buffer (error "File not found :%s" file))
15437 (with-current-buffer buffer
15438 (save-excursion
15439 (save-restriction
15440 (widen)
15441 (setq limit (point-max))
15442 (goto-char (point-min))
15443 (while (setq heading (pop path))
15444 (setq re (format org-complex-heading-regexp-format
15445 (regexp-quote heading)))
15446 (setq cnt 0 pos (point))
15447 (while (re-search-forward re end t)
15448 (setq level (- (match-end 1) (match-beginning 1)))
15449 (if (and (>= level lmin) (<= level lmax))
15450 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15451 (when (= cnt 0) (error "Heading not found on level %d: %s"
15452 lmax heading))
15453 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15454 lmax heading))
15455 (goto-char found)
15456 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15457 (setq end (save-excursion (org-end-of-subtree t t))))
15458 (when (org-at-heading-p)
15459 (point-marker)))))))
15461 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15462 "Find node HEADING in BUFFER.
15463 Return a marker to the heading if it was found, or nil if not.
15464 If POS-ONLY is set, return just the position instead of a marker.
15466 The heading text must match exact, but it may have a TODO keyword,
15467 a priority cookie and tags in the standard locations."
15468 (with-current-buffer (or buffer (current-buffer))
15469 (save-excursion
15470 (save-restriction
15471 (widen)
15472 (goto-char (point-min))
15473 (let (case-fold-search)
15474 (if (re-search-forward
15475 (format org-complex-heading-regexp-format
15476 (regexp-quote heading)) nil t)
15477 (if pos-only
15478 (match-beginning 0)
15479 (move-marker (make-marker) (match-beginning 0)))))))))
15481 (defun org-find-exact-heading-in-directory (heading &optional dir)
15482 "Find Org node headline HEADING in all .org files in directory DIR.
15483 When the target headline is found, return a marker to this location."
15484 (let ((files (directory-files (or dir default-directory)
15485 nil "\\`[^.#].*\\.org\\'"))
15486 file visiting m buffer)
15487 (catch 'found
15488 (while (setq file (pop files))
15489 (message "trying %s" file)
15490 (setq visiting (org-find-base-buffer-visiting file))
15491 (setq buffer (or visiting (find-file-noselect file)))
15492 (setq m (org-find-exact-headline-in-buffer
15493 heading buffer))
15494 (when (and (not m) (not visiting)) (kill-buffer buffer))
15495 (and m (throw 'found m))))))
15497 (defun org-find-entry-with-id (ident)
15498 "Locate the entry that contains the ID property with exact value IDENT.
15499 IDENT can be a string, a symbol or a number, this function will search for
15500 the string representation of it.
15501 Return the position where this entry starts, or nil if there is no such entry."
15502 (interactive "sID: ")
15503 (let ((id (cond
15504 ((stringp ident) ident)
15505 ((symbol-name ident) (symbol-name ident))
15506 ((numberp ident) (number-to-string ident))
15507 (t (error "IDENT %s must be a string, symbol or number" ident))))
15508 (case-fold-search nil))
15509 (save-excursion
15510 (save-restriction
15511 (widen)
15512 (goto-char (point-min))
15513 (when (re-search-forward
15514 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15515 nil t)
15516 (org-back-to-heading t)
15517 (point))))))
15519 ;;;; Timestamps
15521 (defvar org-last-changed-timestamp nil)
15522 (defvar org-last-inserted-timestamp nil
15523 "The last time stamp inserted with `org-insert-time-stamp'.")
15524 (defvar org-time-was-given) ; dynamically scoped parameter
15525 (defvar org-end-time-was-given) ; dynamically scoped parameter
15526 (defvar org-ts-what) ; dynamically scoped parameter
15528 (defun org-time-stamp (arg &optional inactive)
15529 "Prompt for a date/time and insert a time stamp.
15530 If the user specifies a time like HH:MM or if this command is
15531 called with at least one prefix argument, the time stamp contains
15532 the date and the time. Otherwise, only the date is be included.
15534 All parts of a date not specified by the user is filled in from
15535 the current date/time. So if you just press return without
15536 typing anything, the time stamp will represent the current
15537 date/time.
15539 If there is already a timestamp at the cursor, it will be
15540 modified.
15542 With two universal prefix arguments, insert an active timestamp
15543 with the current time without prompting the user."
15544 (interactive "P")
15545 (let* ((ts nil)
15546 (default-time
15547 ;; Default time is either today, or, when entering a range,
15548 ;; the range start.
15549 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15550 (save-excursion
15551 (re-search-backward
15552 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15553 (- (point) 20) t)))
15554 (apply 'encode-time (org-parse-time-string (match-string 1)))
15555 (current-time)))
15556 (default-input (and ts (org-get-compact-tod ts)))
15557 (repeater (save-excursion
15558 (save-match-data
15559 (beginning-of-line)
15560 (when (re-search-forward
15561 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15562 (save-excursion (progn (end-of-line) (point))) t)
15563 (match-string 0)))))
15564 org-time-was-given org-end-time-was-given time)
15565 (cond
15566 ((and (org-at-timestamp-p t)
15567 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15568 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15569 (insert "--")
15570 (setq time (let ((this-command this-command))
15571 (org-read-date arg 'totime nil nil
15572 default-time default-input inactive)))
15573 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15574 ((org-at-timestamp-p t)
15575 (setq time (let ((this-command this-command))
15576 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15577 (when (org-at-timestamp-p t) ; just to get the match data
15578 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15579 (replace-match "")
15580 (setq org-last-changed-timestamp
15581 (org-insert-time-stamp
15582 time (or org-time-was-given arg)
15583 inactive nil nil (list org-end-time-was-given)))
15584 (when repeater (goto-char (1- (point))) (insert " " repeater)
15585 (setq org-last-changed-timestamp
15586 (concat (substring org-last-inserted-timestamp 0 -1)
15587 " " repeater ">"))))
15588 (message "Timestamp updated"))
15589 ((equal arg '(16))
15590 (org-insert-time-stamp (current-time) t))
15592 (setq time (let ((this-command this-command))
15593 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15594 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15595 nil nil (list org-end-time-was-given))))))
15597 ;; FIXME: can we use this for something else, like computing time differences?
15598 (defun org-get-compact-tod (s)
15599 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15600 (let* ((t1 (match-string 1 s))
15601 (h1 (string-to-number (match-string 2 s)))
15602 (m1 (string-to-number (match-string 3 s)))
15603 (t2 (and (match-end 4) (match-string 5 s)))
15604 (h2 (and t2 (string-to-number (match-string 6 s))))
15605 (m2 (and t2 (string-to-number (match-string 7 s))))
15606 dh dm)
15607 (if (not t2)
15609 (setq dh (- h2 h1) dm (- m2 m1))
15610 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15611 (concat t1 "+" (number-to-string dh)
15612 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15614 (defun org-time-stamp-inactive (&optional arg)
15615 "Insert an inactive time stamp.
15616 An inactive time stamp is enclosed in square brackets instead of angle
15617 brackets. It is inactive in the sense that it does not trigger agenda entries,
15618 does not link to the calendar and cannot be changed with the S-cursor keys.
15619 So these are more for recording a certain time/date."
15620 (interactive "P")
15621 (org-time-stamp arg 'inactive))
15623 (defvar org-date-ovl (make-overlay 1 1))
15624 (overlay-put org-date-ovl 'face 'org-date-selected)
15625 (org-detach-overlay org-date-ovl)
15627 (defvar org-ans1) ; dynamically scoped parameter
15628 (defvar org-ans2) ; dynamically scoped parameter
15630 (defvar org-plain-time-of-day-regexp) ; defined below
15632 (defvar org-overriding-default-time nil) ; dynamically scoped
15633 (defvar org-read-date-overlay nil)
15634 (defvar org-dcst nil) ; dynamically scoped
15635 (defvar org-read-date-history nil)
15636 (defvar org-read-date-final-answer nil)
15637 (defvar org-read-date-analyze-futurep nil)
15638 (defvar org-read-date-analyze-forced-year nil)
15639 (defvar org-read-date-inactive)
15641 (defvar org-read-date-minibuffer-local-map
15642 (let ((map (make-sparse-keymap)))
15643 (set-keymap-parent map minibuffer-local-map)
15644 (org-defkey map (kbd ".")
15645 (lambda () (interactive)
15646 (org-eval-in-calendar '(calendar-goto-today))))
15647 (org-defkey map [(meta shift left)]
15648 (lambda () (interactive)
15649 (org-eval-in-calendar '(calendar-backward-month 1))))
15650 (org-defkey map [(meta shift right)]
15651 (lambda () (interactive)
15652 (org-eval-in-calendar '(calendar-forward-month 1))))
15653 (org-defkey map [(meta shift up)]
15654 (lambda () (interactive)
15655 (org-eval-in-calendar '(calendar-backward-year 1))))
15656 (org-defkey map [(meta shift down)]
15657 (lambda () (interactive)
15658 (org-eval-in-calendar '(calendar-forward-year 1))))
15659 (org-defkey map [?\e (shift left)]
15660 (lambda () (interactive)
15661 (org-eval-in-calendar '(calendar-backward-month 1))))
15662 (org-defkey map [?\e (shift right)]
15663 (lambda () (interactive)
15664 (org-eval-in-calendar '(calendar-forward-month 1))))
15665 (org-defkey map [?\e (shift up)]
15666 (lambda () (interactive)
15667 (org-eval-in-calendar '(calendar-backward-year 1))))
15668 (org-defkey map [?\e (shift down)]
15669 (lambda () (interactive)
15670 (org-eval-in-calendar '(calendar-forward-year 1))))
15671 (org-defkey map [(shift up)]
15672 (lambda () (interactive)
15673 (org-eval-in-calendar '(calendar-backward-week 1))))
15674 (org-defkey map [(shift down)]
15675 (lambda () (interactive)
15676 (org-eval-in-calendar '(calendar-forward-week 1))))
15677 (org-defkey map [(shift left)]
15678 (lambda () (interactive)
15679 (org-eval-in-calendar '(calendar-backward-day 1))))
15680 (org-defkey map [(shift right)]
15681 (lambda () (interactive)
15682 (org-eval-in-calendar '(calendar-forward-day 1))))
15683 (org-defkey map "!"
15684 (lambda () (interactive)
15685 (org-eval-in-calendar '(diary-view-entries))
15686 (message "")))
15687 (org-defkey map ">"
15688 (lambda () (interactive)
15689 (org-eval-in-calendar '(scroll-calendar-left 1))))
15690 (org-defkey map "<"
15691 (lambda () (interactive)
15692 (org-eval-in-calendar '(scroll-calendar-right 1))))
15693 (org-defkey map "\C-v"
15694 (lambda () (interactive)
15695 (org-eval-in-calendar
15696 '(calendar-scroll-left-three-months 1))))
15697 (org-defkey map "\M-v"
15698 (lambda () (interactive)
15699 (org-eval-in-calendar
15700 '(calendar-scroll-right-three-months 1))))
15701 map)
15702 "Keymap for minibuffer commands when using `org-read-date'.")
15704 (defun org-read-date (&optional org-with-time to-time from-string prompt
15705 default-time default-input inactive)
15706 "Read a date, possibly a time, and make things smooth for the user.
15707 The prompt will suggest to enter an ISO date, but you can also enter anything
15708 which will at least partially be understood by `parse-time-string'.
15709 Unrecognized parts of the date will default to the current day, month, year,
15710 hour and minute. If this command is called to replace a timestamp at point,
15711 or to enter the second timestamp of a range, the default time is taken
15712 from the existing stamp. Furthermore, the command prefers the future,
15713 so if you are giving a date where the year is not given, and the day-month
15714 combination is already past in the current year, it will assume you
15715 mean next year. For details, see the manual. A few examples:
15717 3-2-5 --> 2003-02-05
15718 feb 15 --> currentyear-02-15
15719 2/15 --> currentyear-02-15
15720 sep 12 9 --> 2009-09-12
15721 12:45 --> today 12:45
15722 22 sept 0:34 --> currentyear-09-22 0:34
15723 12 --> currentyear-currentmonth-12
15724 Fri --> nearest Friday (today or later)
15725 etc.
15727 Furthermore you can specify a relative date by giving, as the *first* thing
15728 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15729 change in days weeks, months, years.
15730 With a single plus or minus, the date is relative to today. With a double
15731 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15732 +4d --> four days from today
15733 +4 --> same as above
15734 +2w --> two weeks from today
15735 ++5 --> five days from default date
15737 The function understands only English month and weekday abbreviations.
15739 While prompting, a calendar is popped up - you can also select the
15740 date with the mouse (button 1). The calendar shows a period of three
15741 months. To scroll it to other months, use the keys `>' and `<'.
15742 If you don't like the calendar, turn it off with
15743 \(setq org-read-date-popup-calendar nil)
15745 With optional argument TO-TIME, the date will immediately be converted
15746 to an internal time.
15747 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15748 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15749 still enter a time, and this function will inform the calling routine
15750 about this change. The calling routine may then choose to change the
15751 format used to insert the time stamp into the buffer to include the time.
15752 With optional argument FROM-STRING, read from this string instead from
15753 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15754 the time/date that is used for everything that is not specified by the
15755 user."
15756 (require 'parse-time)
15757 (let* ((org-time-stamp-rounding-minutes
15758 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15759 (org-dcst org-display-custom-times)
15760 (ct (org-current-time))
15761 (org-def (or org-overriding-default-time default-time ct))
15762 (org-defdecode (decode-time org-def))
15763 (dummy (progn
15764 (when (< (nth 2 org-defdecode) org-extend-today-until)
15765 (setcar (nthcdr 2 org-defdecode) -1)
15766 (setcar (nthcdr 1 org-defdecode) 59)
15767 (setq org-def (apply 'encode-time org-defdecode)
15768 org-defdecode (decode-time org-def)))))
15769 (mouse-autoselect-window nil) ; Don't let the mouse jump
15770 (calendar-frame-setup nil)
15771 (calendar-setup nil)
15772 (calendar-move-hook nil)
15773 (calendar-view-diary-initially-flag nil)
15774 (calendar-view-holidays-initially-flag nil)
15775 (timestr (format-time-string
15776 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15777 (prompt (concat (if prompt (concat prompt " ") "")
15778 (format "Date+time [%s]: " timestr)))
15779 ans (org-ans0 "") org-ans1 org-ans2 final)
15781 (cond
15782 (from-string (setq ans from-string))
15783 (org-read-date-popup-calendar
15784 (save-excursion
15785 (save-window-excursion
15786 (calendar)
15787 (org-eval-in-calendar '(setq cursor-type nil) t)
15788 (unwind-protect
15789 (progn
15790 (calendar-forward-day (- (time-to-days org-def)
15791 (calendar-absolute-from-gregorian
15792 (calendar-current-date))))
15793 (org-eval-in-calendar nil t)
15794 (let* ((old-map (current-local-map))
15795 (map (copy-keymap calendar-mode-map))
15796 (minibuffer-local-map
15797 (copy-keymap org-read-date-minibuffer-local-map)))
15798 (org-defkey map (kbd "RET") 'org-calendar-select)
15799 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15800 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15801 (unwind-protect
15802 (progn
15803 (use-local-map map)
15804 (setq org-read-date-inactive inactive)
15805 (add-hook 'post-command-hook 'org-read-date-display)
15806 (setq org-ans0 (read-string prompt default-input
15807 'org-read-date-history nil))
15808 ;; org-ans0: from prompt
15809 ;; org-ans1: from mouse click
15810 ;; org-ans2: from calendar motion
15811 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15812 (remove-hook 'post-command-hook 'org-read-date-display)
15813 (use-local-map old-map)
15814 (when org-read-date-overlay
15815 (delete-overlay org-read-date-overlay)
15816 (setq org-read-date-overlay nil)))))
15817 (bury-buffer "*Calendar*")))))
15819 (t ; Naked prompt only
15820 (unwind-protect
15821 (setq ans (read-string prompt default-input
15822 'org-read-date-history timestr))
15823 (when org-read-date-overlay
15824 (delete-overlay org-read-date-overlay)
15825 (setq org-read-date-overlay nil)))))
15827 (setq final (org-read-date-analyze ans org-def org-defdecode))
15829 (when org-read-date-analyze-forced-year
15830 (message "Year was forced into %s"
15831 (if org-read-date-force-compatible-dates
15832 "compatible range (1970-2037)"
15833 "range representable on this machine"))
15834 (ding))
15836 ;; One round trip to get rid of 34th of August and stuff like that....
15837 (setq final (decode-time (apply 'encode-time final)))
15839 (setq org-read-date-final-answer ans)
15841 (if to-time
15842 (apply 'encode-time final)
15843 (if (and (boundp 'org-time-was-given) org-time-was-given)
15844 (format "%04d-%02d-%02d %02d:%02d"
15845 (nth 5 final) (nth 4 final) (nth 3 final)
15846 (nth 2 final) (nth 1 final))
15847 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15849 (defvar org-def)
15850 (defvar org-defdecode)
15851 (defvar org-with-time)
15852 (defun org-read-date-display ()
15853 "Display the current date prompt interpretation in the minibuffer."
15854 (when org-read-date-display-live
15855 (when org-read-date-overlay
15856 (delete-overlay org-read-date-overlay))
15857 (when (minibufferp (current-buffer))
15858 (save-excursion
15859 (end-of-line 1)
15860 (while (not (equal (buffer-substring
15861 (max (point-min) (- (point) 4)) (point))
15862 " "))
15863 (insert " ")))
15864 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15865 " " (or org-ans1 org-ans2)))
15866 (org-end-time-was-given nil)
15867 (f (org-read-date-analyze ans org-def org-defdecode))
15868 (fmts (if org-dcst
15869 org-time-stamp-custom-formats
15870 org-time-stamp-formats))
15871 (fmt (if (or org-with-time
15872 (and (boundp 'org-time-was-given) org-time-was-given))
15873 (cdr fmts)
15874 (car fmts)))
15875 (txt (format-time-string fmt (apply 'encode-time f)))
15876 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15877 (txt (concat "=> " txt)))
15878 (when (and org-end-time-was-given
15879 (string-match org-plain-time-of-day-regexp txt))
15880 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15881 org-end-time-was-given
15882 (substring txt (match-end 0)))))
15883 (when org-read-date-analyze-futurep
15884 (setq txt (concat txt " (=>F)")))
15885 (setq org-read-date-overlay
15886 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15887 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15889 (defun org-read-date-analyze (ans org-def org-defdecode)
15890 "Analyze the combined answer of the date prompt."
15891 ;; FIXME: cleanup and comment
15892 (let ((nowdecode (decode-time (current-time)))
15893 delta deltan deltaw deltadef year month day
15894 hour minute second wday pm h2 m2 tl wday1
15895 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15896 (setq org-read-date-analyze-futurep nil
15897 org-read-date-analyze-forced-year nil)
15898 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15899 (setq ans "+0"))
15901 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15902 (setq ans (replace-match "" t t ans)
15903 deltan (car delta)
15904 deltaw (nth 1 delta)
15905 deltadef (nth 2 delta)))
15907 ;; Check if there is an iso week date in there. If yes, store the
15908 ;; info and postpone interpreting it until the rest of the parsing
15909 ;; is done.
15910 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15911 (setq iso-year (if (match-end 1)
15912 (org-small-year-to-year
15913 (string-to-number (match-string 1 ans))))
15914 iso-weekday (if (match-end 3)
15915 (string-to-number (match-string 3 ans)))
15916 iso-week (string-to-number (match-string 2 ans)))
15917 (setq ans (replace-match "" t t ans)))
15919 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15920 (when (string-match
15921 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15922 (setq year (if (match-end 2)
15923 (string-to-number (match-string 2 ans))
15924 (progn (setq kill-year t)
15925 (string-to-number (format-time-string "%Y"))))
15926 month (string-to-number (match-string 3 ans))
15927 day (string-to-number (match-string 4 ans)))
15928 (if (< year 100) (setq year (+ 2000 year)))
15929 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15930 t nil ans)))
15932 ;; Help matching dotted european dates
15933 (when (string-match
15934 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15935 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15936 (setq kill-year t)
15937 (string-to-number (format-time-string "%Y")))
15938 day (string-to-number (match-string 1 ans))
15939 month (string-to-number (match-string 2 ans))
15940 ans (replace-match (format "%04d-%02d-%02d" year month day)
15941 t nil ans)))
15943 ;; Help matching american dates, like 5/30 or 5/30/7
15944 (when (string-match
15945 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15946 (setq year (if (match-end 4)
15947 (string-to-number (match-string 4 ans))
15948 (progn (setq kill-year t)
15949 (string-to-number (format-time-string "%Y"))))
15950 month (string-to-number (match-string 1 ans))
15951 day (string-to-number (match-string 2 ans)))
15952 (if (< year 100) (setq year (+ 2000 year)))
15953 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15954 t nil ans)))
15955 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15956 ;; If there is a time with am/pm, and *no* time without it, we convert
15957 ;; so that matching will be successful.
15958 (loop for i from 1 to 2 do ; twice, for end time as well
15959 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15960 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15961 (setq hour (string-to-number (match-string 1 ans))
15962 minute (if (match-end 3)
15963 (string-to-number (match-string 3 ans))
15965 pm (equal ?p
15966 (string-to-char (downcase (match-string 4 ans)))))
15967 (if (and (= hour 12) (not pm))
15968 (setq hour 0)
15969 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15970 (setq ans (replace-match (format "%02d:%02d" hour minute)
15971 t t ans))))
15973 ;; Check if a time range is given as a duration
15974 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15975 (setq hour (string-to-number (match-string 1 ans))
15976 h2 (+ hour (string-to-number (match-string 3 ans)))
15977 minute (string-to-number (match-string 2 ans))
15978 m2 (+ minute (if (match-end 5) (string-to-number
15979 (match-string 5 ans))0)))
15980 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15981 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15982 t t ans)))
15984 ;; Check if there is a time range
15985 (when (boundp 'org-end-time-was-given)
15986 (setq org-time-was-given nil)
15987 (when (and (string-match org-plain-time-of-day-regexp ans)
15988 (match-end 8))
15989 (setq org-end-time-was-given (match-string 8 ans))
15990 (setq ans (concat (substring ans 0 (match-beginning 7))
15991 (substring ans (match-end 7))))))
15993 (setq tl (parse-time-string ans)
15994 day (or (nth 3 tl) (nth 3 org-defdecode))
15995 month (or (nth 4 tl)
15996 (if (and org-read-date-prefer-future
15997 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15998 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15999 (nth 4 org-defdecode)))
16000 year (or (and (not kill-year) (nth 5 tl))
16001 (if (and org-read-date-prefer-future
16002 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16003 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16004 (nth 5 org-defdecode)))
16005 hour (or (nth 2 tl) (nth 2 org-defdecode))
16006 minute (or (nth 1 tl) (nth 1 org-defdecode))
16007 second (or (nth 0 tl) 0)
16008 wday (nth 6 tl))
16010 (when (and (eq org-read-date-prefer-future 'time)
16011 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16012 (equal day (nth 3 nowdecode))
16013 (equal month (nth 4 nowdecode))
16014 (equal year (nth 5 nowdecode))
16015 (nth 2 tl)
16016 (or (< (nth 2 tl) (nth 2 nowdecode))
16017 (and (= (nth 2 tl) (nth 2 nowdecode))
16018 (nth 1 tl)
16019 (< (nth 1 tl) (nth 1 nowdecode)))))
16020 (setq day (1+ day)
16021 futurep t))
16023 ;; Special date definitions below
16024 (cond
16025 (iso-week
16026 ;; There was an iso week
16027 (require 'cal-iso)
16028 (setq futurep nil)
16029 (setq year (or iso-year year)
16030 day (or iso-weekday wday 1)
16031 wday nil ; to make sure that the trigger below does not match
16032 iso-date (calendar-gregorian-from-absolute
16033 (calendar-absolute-from-iso
16034 (list iso-week day year))))
16035 ; FIXME: Should we also push ISO weeks into the future?
16036 ; (when (and org-read-date-prefer-future
16037 ; (not iso-year)
16038 ; (< (calendar-absolute-from-gregorian iso-date)
16039 ; (time-to-days (current-time))))
16040 ; (setq year (1+ year)
16041 ; iso-date (calendar-gregorian-from-absolute
16042 ; (calendar-absolute-from-iso
16043 ; (list iso-week day year)))))
16044 (setq month (car iso-date)
16045 year (nth 2 iso-date)
16046 day (nth 1 iso-date)))
16047 (deltan
16048 (setq futurep nil)
16049 (unless deltadef
16050 (let ((now (decode-time (current-time))))
16051 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16052 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16053 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16054 ((equal deltaw "m") (setq month (+ month deltan)))
16055 ((equal deltaw "y") (setq year (+ year deltan)))))
16056 ((and wday (not (nth 3 tl)))
16057 ;; Weekday was given, but no day, so pick that day in the week
16058 ;; on or after the derived date.
16059 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16060 (unless (equal wday wday1)
16061 (setq day (+ day (% (- wday wday1 -7) 7))))))
16062 (if (and (boundp 'org-time-was-given)
16063 (nth 2 tl))
16064 (setq org-time-was-given t))
16065 (if (< year 100) (setq year (+ 2000 year)))
16066 ;; Check of the date is representable
16067 (if org-read-date-force-compatible-dates
16068 (progn
16069 (if (< year 1970)
16070 (setq year 1970 org-read-date-analyze-forced-year t))
16071 (if (> year 2037)
16072 (setq year 2037 org-read-date-analyze-forced-year t)))
16073 (condition-case nil
16074 (ignore (encode-time second minute hour day month year))
16075 (error
16076 (setq year (nth 5 org-defdecode))
16077 (setq org-read-date-analyze-forced-year t))))
16078 (setq org-read-date-analyze-futurep futurep)
16079 (list second minute hour day month year)))
16081 (defvar parse-time-weekdays)
16082 (defun org-read-date-get-relative (s today default)
16083 "Check string S for special relative date string.
16084 TODAY and DEFAULT are internal times, for today and for a default.
16085 Return shift list (N what def-flag)
16086 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16087 N is the number of WHATs to shift.
16088 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16089 the DEFAULT date rather than TODAY."
16090 (require 'parse-time)
16091 (when (and
16092 (string-match
16093 (concat
16094 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16095 "\\([0-9]+\\)?"
16096 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16097 "\\([ \t]\\|$\\)") s)
16098 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16099 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16100 (string-to-char (substring (match-string 1 s) -1))
16101 ?+))
16102 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16103 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16104 (what (if (match-end 3) (match-string 3 s) "d"))
16105 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16106 (date (if rel default today))
16107 (wday (nth 6 (decode-time date)))
16108 delta)
16109 (if wday1
16110 (progn
16111 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16112 (if (= dir ?-) (setq delta (- delta 7)))
16113 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16114 (list delta "d" rel))
16115 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16117 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16118 "Turn a user-specified date into the internal representation.
16119 The internal representation needed by the calendar is (month day year).
16120 This is a wrapper to handle the brain-dead convention in calendar that
16121 user function argument order change dependent on argument order."
16122 (if (boundp 'calendar-date-style)
16123 (cond
16124 ((eq calendar-date-style 'american)
16125 (list arg1 arg2 arg3))
16126 ((eq calendar-date-style 'european)
16127 (list arg2 arg1 arg3))
16128 ((eq calendar-date-style 'iso)
16129 (list arg2 arg3 arg1)))
16130 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16131 (if (org-bound-and-true-p european-calendar-style)
16132 (list arg2 arg1 arg3)
16133 (list arg1 arg2 arg3)))))
16135 (defun org-eval-in-calendar (form &optional keepdate)
16136 "Eval FORM in the calendar window and return to current window.
16137 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16138 otherwise stick to the current value of `org-ans2'."
16139 (let ((sf (selected-frame))
16140 (sw (selected-window)))
16141 (select-window (get-buffer-window "*Calendar*" t))
16142 (eval form)
16143 (when (and (not keepdate) (calendar-cursor-to-date))
16144 (let* ((date (calendar-cursor-to-date))
16145 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16146 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16147 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16148 (select-window sw)
16149 (org-select-frame-set-input-focus sf)))
16151 (defun org-calendar-select ()
16152 "Return to `org-read-date' with the date currently selected.
16153 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16154 (interactive)
16155 (when (calendar-cursor-to-date)
16156 (let* ((date (calendar-cursor-to-date))
16157 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16158 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16159 (if (active-minibuffer-window) (exit-minibuffer))))
16161 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16162 "Insert a date stamp for the date given by the internal TIME.
16163 WITH-HM means use the stamp format that includes the time of the day.
16164 INACTIVE means use square brackets instead of angular ones, so that the
16165 stamp will not contribute to the agenda.
16166 PRE and POST are optional strings to be inserted before and after the
16167 stamp.
16168 The command returns the inserted time stamp."
16169 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16170 stamp)
16171 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16172 (insert-before-markers (or pre ""))
16173 (when (listp extra)
16174 (setq extra (car extra))
16175 (if (and (stringp extra)
16176 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16177 (setq extra (format "-%02d:%02d"
16178 (string-to-number (match-string 1 extra))
16179 (string-to-number (match-string 2 extra))))
16180 (setq extra nil)))
16181 (when extra
16182 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16183 (insert-before-markers (setq stamp (format-time-string fmt time)))
16184 (insert-before-markers (or post ""))
16185 (setq org-last-inserted-timestamp stamp)))
16187 (defun org-toggle-time-stamp-overlays ()
16188 "Toggle the use of custom time stamp formats."
16189 (interactive)
16190 (setq org-display-custom-times (not org-display-custom-times))
16191 (unless org-display-custom-times
16192 (let ((p (point-min)) (bmp (buffer-modified-p)))
16193 (while (setq p (next-single-property-change p 'display))
16194 (if (and (get-text-property p 'display)
16195 (eq (get-text-property p 'face) 'org-date))
16196 (remove-text-properties
16197 p (setq p (next-single-property-change p 'display))
16198 '(display t))))
16199 (set-buffer-modified-p bmp)))
16200 (if (featurep 'xemacs)
16201 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16202 (org-restart-font-lock)
16203 (setq org-table-may-need-update t)
16204 (if org-display-custom-times
16205 (message "Time stamps are overlaid with custom format")
16206 (message "Time stamp overlays removed")))
16208 (defun org-display-custom-time (beg end)
16209 "Overlay modified time stamp format over timestamp between BEG and END."
16210 (let* ((ts (buffer-substring beg end))
16211 t1 w1 with-hm tf time str w2 (off 0))
16212 (save-match-data
16213 (setq t1 (org-parse-time-string ts t))
16214 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16215 (setq off (- (match-end 0) (match-beginning 0)))))
16216 (setq end (- end off))
16217 (setq w1 (- end beg)
16218 with-hm (and (nth 1 t1) (nth 2 t1))
16219 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16220 time (org-fix-decoded-time t1)
16221 str (org-add-props
16222 (format-time-string
16223 (substring tf 1 -1) (apply 'encode-time time))
16224 nil 'mouse-face 'highlight)
16225 w2 (length str))
16226 (if (not (= w2 w1))
16227 (add-text-properties (1+ beg) (+ 2 beg)
16228 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16229 (if (featurep 'xemacs)
16230 (progn
16231 (put-text-property beg end 'invisible t)
16232 (put-text-property beg end 'end-glyph (make-glyph str)))
16233 (put-text-property beg end 'display str))))
16235 (defun org-translate-time (string)
16236 "Translate all timestamps in STRING to custom format.
16237 But do this only if the variable `org-display-custom-times' is set."
16238 (when org-display-custom-times
16239 (save-match-data
16240 (let* ((start 0)
16241 (re org-ts-regexp-both)
16242 t1 with-hm inactive tf time str beg end)
16243 (while (setq start (string-match re string start))
16244 (setq beg (match-beginning 0)
16245 end (match-end 0)
16246 t1 (save-match-data
16247 (org-parse-time-string (substring string beg end) t))
16248 with-hm (and (nth 1 t1) (nth 2 t1))
16249 inactive (equal (substring string beg (1+ beg)) "[")
16250 tf (funcall (if with-hm 'cdr 'car)
16251 org-time-stamp-custom-formats)
16252 time (org-fix-decoded-time t1)
16253 str (format-time-string
16254 (concat
16255 (if inactive "[" "<") (substring tf 1 -1)
16256 (if inactive "]" ">"))
16257 (apply 'encode-time time))
16258 string (replace-match str t t string)
16259 start (+ start (length str)))))))
16260 string)
16262 (defun org-fix-decoded-time (time)
16263 "Set 0 instead of nil for the first 6 elements of time.
16264 Don't touch the rest."
16265 (let ((n 0))
16266 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16268 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16270 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16271 "Difference between TIMESTAMP-STRING and now in days.
16272 If SECONDS is non-nil, return the difference in seconds."
16273 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16274 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16275 (funcall fdiff (current-time)))))
16277 (defun org-deadline-close (timestamp-string &optional ndays)
16278 "Is the time in TIMESTAMP-STRING close to the current date?"
16279 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16280 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16281 (not (org-entry-is-done-p))))
16283 (defun org-get-wdays (ts &optional delay zero-delay)
16284 "Get the deadline lead time appropriate for timestring TS.
16285 When DELAY is non-nil, get the delay time for scheduled items
16286 instead of the deadline lead time. When ZERO-DELAY is non-nil
16287 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16288 don't try to find the delay cookie in the scheduled timestamp."
16289 (let ((tv (if delay org-scheduled-delay-days
16290 org-deadline-warning-days)))
16291 (cond
16292 ((or (and delay (< tv 0))
16293 (and delay zero-delay (<= tv 0))
16294 (and (not delay) (<= tv 0)))
16295 ;; Enforce this value no matter what
16296 (- tv))
16297 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16298 ;; lead time is specified.
16299 (floor (* (string-to-number (match-string 1 ts))
16300 (cdr (assoc (match-string 2 ts)
16301 '(("d" . 1) ("w" . 7)
16302 ("m" . 30.4) ("y" . 365.25)
16303 ("h" . 0.041667)))))))
16304 ;; go for the default.
16305 (t tv))))
16307 (defun org-calendar-select-mouse (ev)
16308 "Return to `org-read-date' with the date currently selected.
16309 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16310 (interactive "e")
16311 (mouse-set-point ev)
16312 (when (calendar-cursor-to-date)
16313 (let* ((date (calendar-cursor-to-date))
16314 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16315 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16316 (if (active-minibuffer-window) (exit-minibuffer))))
16318 (defun org-check-deadlines (ndays)
16319 "Check if there are any deadlines due or past due.
16320 A deadline is considered due if it happens within `org-deadline-warning-days'
16321 days from today's date. If the deadline appears in an entry marked DONE,
16322 it is not shown. The prefix arg NDAYS can be used to test that many
16323 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16324 (interactive "P")
16325 (let* ((org-warn-days
16326 (cond
16327 ((equal ndays '(4)) 100000)
16328 (ndays (prefix-numeric-value ndays))
16329 (t (abs org-deadline-warning-days))))
16330 (case-fold-search nil)
16331 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16332 (callback
16333 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16335 (message "%d deadlines past-due or due within %d days"
16336 (org-occur regexp nil callback)
16337 org-warn-days)))
16339 (defsubst org-re-timestamp (type)
16340 "Return a regexp for timestamp TYPE.
16341 Allowed values for TYPE are:
16343 all: all timestamps
16344 active: only active timestamps (<...>)
16345 inactive: only inactive timestamps ([...])
16346 scheduled: only scheduled timestamps
16347 deadline: only deadline timestamps
16349 When TYPE is nil, fall back on returning a regexp that matches
16350 both scheduled and deadline timestamps."
16351 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16352 ((eq type 'active) org-ts-regexp)
16353 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16354 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16355 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16356 ((eq type 'scheduled-or-deadline)
16357 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16359 (defun org-check-before-date (date)
16360 "Check if there are deadlines or scheduled entries before DATE."
16361 (interactive (list (org-read-date)))
16362 (let ((case-fold-search nil)
16363 (regexp (org-re-timestamp org-ts-type))
16364 (callback
16365 (lambda () (time-less-p
16366 (org-time-string-to-time (match-string 1))
16367 (org-time-string-to-time date)))))
16368 (message "%d entries before %s"
16369 (org-occur regexp nil callback) date)))
16371 (defun org-check-after-date (date)
16372 "Check if there are deadlines or scheduled entries after DATE."
16373 (interactive (list (org-read-date)))
16374 (let ((case-fold-search nil)
16375 (regexp (org-re-timestamp org-ts-type))
16376 (callback
16377 (lambda () (not
16378 (time-less-p
16379 (org-time-string-to-time (match-string 1))
16380 (org-time-string-to-time date))))))
16381 (message "%d entries after %s"
16382 (org-occur regexp nil callback) date)))
16384 (defun org-check-dates-range (start-date end-date)
16385 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16386 (interactive (list (org-read-date nil nil nil "Range starts")
16387 (org-read-date nil nil nil "Range end")))
16388 (let ((case-fold-search nil)
16389 (regexp (org-re-timestamp org-ts-type))
16390 (callback
16391 (lambda ()
16392 (let ((match (match-string 1)))
16393 (and
16394 (not (time-less-p
16395 (org-time-string-to-time match)
16396 (org-time-string-to-time start-date)))
16397 (time-less-p
16398 (org-time-string-to-time match)
16399 (org-time-string-to-time end-date)))))))
16400 (message "%d entries between %s and %s"
16401 (org-occur regexp nil callback) start-date end-date)))
16403 (defun org-evaluate-time-range (&optional to-buffer)
16404 "Evaluate a time range by computing the difference between start and end.
16405 Normally the result is just printed in the echo area, but with prefix arg
16406 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16407 If the time range is actually in a table, the result is inserted into the
16408 next column.
16409 For time difference computation, a year is assumed to be exactly 365
16410 days in order to avoid rounding problems."
16411 (interactive "P")
16413 (org-clock-update-time-maybe)
16414 (save-excursion
16415 (unless (org-at-date-range-p t)
16416 (goto-char (point-at-bol))
16417 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16418 (if (not (org-at-date-range-p t))
16419 (error "Not at a time-stamp range, and none found in current line")))
16420 (let* ((ts1 (match-string 1))
16421 (ts2 (match-string 2))
16422 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16423 (match-end (match-end 0))
16424 (time1 (org-time-string-to-time ts1))
16425 (time2 (org-time-string-to-time ts2))
16426 (t1 (org-float-time time1))
16427 (t2 (org-float-time time2))
16428 (diff (abs (- t2 t1)))
16429 (negative (< (- t2 t1) 0))
16430 ;; (ys (floor (* 365 24 60 60)))
16431 (ds (* 24 60 60))
16432 (hs (* 60 60))
16433 (fy "%dy %dd %02d:%02d")
16434 (fy1 "%dy %dd")
16435 (fd "%dd %02d:%02d")
16436 (fd1 "%dd")
16437 (fh "%02d:%02d")
16438 y d h m align)
16439 (if havetime
16440 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16442 d (floor (/ diff ds)) diff (mod diff ds)
16443 h (floor (/ diff hs)) diff (mod diff hs)
16444 m (floor (/ diff 60)))
16445 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16447 d (floor (+ (/ diff ds) 0.5))
16448 h 0 m 0))
16449 (if (not to-buffer)
16450 (message "%s" (org-make-tdiff-string y d h m))
16451 (if (org-at-table-p)
16452 (progn
16453 (goto-char match-end)
16454 (setq align t)
16455 (and (looking-at " *|") (goto-char (match-end 0))))
16456 (goto-char match-end))
16457 (if (looking-at
16458 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16459 (replace-match ""))
16460 (if negative (insert " -"))
16461 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16462 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16463 (insert " " (format fh h m))))
16464 (if align (org-table-align))
16465 (message "Time difference inserted")))))
16467 (defun org-make-tdiff-string (y d h m)
16468 (let ((fmt "")
16469 (l nil))
16470 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16471 l (push y l)))
16472 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16473 l (push d l)))
16474 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16475 l (push h l)))
16476 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16477 l (push m l)))
16478 (apply 'format fmt (nreverse l))))
16480 (defun org-time-string-to-time (s &optional buffer pos)
16481 "Convert a timestamp string into internal time."
16482 (condition-case errdata
16483 (apply 'encode-time (org-parse-time-string s))
16484 (error (error "Bad timestamp `%s'%s\nError was: %s"
16485 s (if (not (and buffer pos))
16487 (format " at %d in buffer `%s'" pos buffer))
16488 (cdr errdata)))))
16490 (defun org-time-string-to-seconds (s)
16491 "Convert a timestamp string to a number of seconds."
16492 (org-float-time (org-time-string-to-time s)))
16494 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16495 "Convert a time stamp to an absolute day number.
16496 If there is a specifier for a cyclic time stamp, get the closest
16497 date to DAYNR.
16498 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16499 The variable date is bound by the calendar when this is called."
16500 (cond
16501 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16502 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16503 daynr
16504 (+ daynr 1000)))
16505 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16506 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16507 (time-to-days (current-time))) (match-string 0 s)
16508 prefer show-all))
16509 (t (time-to-days
16510 (condition-case errdata
16511 (apply 'encode-time (org-parse-time-string s))
16512 (error (error "Bad timestamp `%s'%s\nError was: %s"
16513 s (if (not (and buffer pos))
16515 (format " at %d in buffer `%s'" pos buffer))
16516 (cdr errdata))))))))
16518 (defun org-days-to-iso-week (days)
16519 "Return the iso week number."
16520 (require 'cal-iso)
16521 (car (calendar-iso-from-absolute days)))
16523 (defun org-small-year-to-year (year)
16524 "Convert 2-digit years into 4-digit years.
16525 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16526 The year 2000 cannot be abbreviated. Any year larger than 99
16527 is returned unchanged."
16528 (if (< year 38)
16529 (setq year (+ 2000 year))
16530 (if (< year 100)
16531 (setq year (+ 1900 year))))
16532 year)
16534 (defun org-time-from-absolute (d)
16535 "Return the time corresponding to date D.
16536 D may be an absolute day number, or a calendar-type list (month day year)."
16537 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16538 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16540 (defun org-calendar-holiday ()
16541 "List of holidays, for Diary display in Org-mode."
16542 (require 'holidays)
16543 (let ((hl (funcall
16544 (if (fboundp 'calendar-check-holidays)
16545 'calendar-check-holidays 'check-calendar-holidays) date)))
16546 (if hl (mapconcat 'identity hl "; "))))
16548 (defun org-diary-sexp-entry (sexp entry date)
16549 "Process a SEXP diary ENTRY for DATE."
16550 (require 'diary-lib)
16551 (let ((result (if calendar-debug-sexp
16552 (let ((stack-trace-on-error t))
16553 (eval (car (read-from-string sexp))))
16554 (condition-case nil
16555 (eval (car (read-from-string sexp)))
16556 (error
16557 (beep)
16558 (message "Bad sexp at line %d in %s: %s"
16559 (org-current-line)
16560 (buffer-file-name) sexp)
16561 (sleep-for 2))))))
16562 (cond ((stringp result) (split-string result "; "))
16563 ((and (consp result)
16564 (not (consp (cdr result)))
16565 (stringp (cdr result))) (cdr result))
16566 ((and (consp result)
16567 (stringp (car result))) result)
16568 (result entry))))
16570 (defun org-diary-to-ical-string (frombuf)
16571 "Get iCalendar entries from diary entries in buffer FROMBUF.
16572 This uses the icalendar.el library."
16573 (let* ((tmpdir (if (featurep 'xemacs)
16574 (temp-directory)
16575 temporary-file-directory))
16576 (tmpfile (make-temp-name
16577 (expand-file-name "orgics" tmpdir)))
16578 buf rtn b e)
16579 (with-current-buffer frombuf
16580 (icalendar-export-region (point-min) (point-max) tmpfile)
16581 (setq buf (find-buffer-visiting tmpfile))
16582 (set-buffer buf)
16583 (goto-char (point-min))
16584 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16585 (setq b (match-beginning 0)))
16586 (goto-char (point-max))
16587 (if (re-search-backward "^END:VEVENT" nil t)
16588 (setq e (match-end 0)))
16589 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16590 (kill-buffer buf)
16591 (delete-file tmpfile)
16592 rtn))
16594 (defun org-closest-date (start current change prefer show-all)
16595 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16596 When PREFER is `past', return a date that is either CURRENT or past.
16597 When PREFER is `future', return a date that is either CURRENT or future.
16598 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16599 ;; Make the proper lists from the dates
16600 (catch 'exit
16601 (let ((a1 '(("h" . hour)
16602 ("d" . day)
16603 ("w" . week)
16604 ("m" . month)
16605 ("y" . year)))
16606 (shour (nth 2 (org-parse-time-string start)))
16607 dn dw sday cday n1 n2 n0
16608 d m y y1 y2 date1 date2 nmonths nm ny m2)
16610 (setq start (org-date-to-gregorian start)
16611 current (org-date-to-gregorian
16612 (if show-all
16613 current
16614 (time-to-days (current-time))))
16615 sday (calendar-absolute-from-gregorian start)
16616 cday (calendar-absolute-from-gregorian current))
16618 (if (<= cday sday) (throw 'exit sday))
16620 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16621 (setq dn (string-to-number (match-string 1 change))
16622 dw (cdr (assoc (match-string 2 change) a1)))
16623 (error "Invalid change specifier: %s" change))
16624 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16625 (cond
16626 ((eq dw 'hour)
16627 (let ((missing-hours
16628 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16629 dn)))
16630 (setq n1 (if (zerop missing-hours) cday
16631 (- cday (1+ (floor (/ missing-hours 24)))))
16632 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16633 ((eq dw 'day)
16634 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16635 n2 (+ n1 dn)))
16636 ((eq dw 'year)
16637 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16638 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16639 (setq date1 (list m d y1)
16640 n1 (calendar-absolute-from-gregorian date1)
16641 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16642 n2 (calendar-absolute-from-gregorian date2)))
16643 ((eq dw 'month)
16644 ;; approx number of month between the two dates
16645 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16646 ;; How often does dn fit in there?
16647 (setq d (nth 1 start) m (car start) y (nth 2 start)
16648 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16649 m (+ m nm)
16650 ny (floor (/ m 12))
16651 y (+ y ny)
16652 m (- m (* ny 12)))
16653 (while (> m 12) (setq m (- m 12) y (1+ y)))
16654 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16655 (setq m2 (+ m dn) y2 y)
16656 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16657 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16658 (while (<= n2 cday)
16659 (setq n1 n2 m m2 y y2)
16660 (setq m2 (+ m dn) y2 y)
16661 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16662 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16663 ;; Make sure n1 is the earlier date
16664 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16665 (if show-all
16666 (cond
16667 ((eq prefer 'past) (if (= cday n2) n2 n1))
16668 ((eq prefer 'future) (if (= cday n1) n1 n2))
16669 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16670 (cond
16671 ((eq prefer 'past) (if (= cday n2) n2 n1))
16672 ((eq prefer 'future) (if (= cday n1) n1 n2))
16673 (t (if (= cday n1) n1 n2)))))))
16675 (defun org-date-to-gregorian (date)
16676 "Turn any specification of DATE into a Gregorian date for the calendar."
16677 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16678 ((and (listp date) (= (length date) 3)) date)
16679 ((stringp date)
16680 (setq date (org-parse-time-string date))
16681 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16682 ((listp date)
16683 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16685 (defun org-parse-time-string (s &optional nodefault)
16686 "Parse the standard Org-mode time string.
16687 This should be a lot faster than the normal `parse-time-string'.
16688 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16689 hour and minute fields will be nil if not given."
16690 (cond ((string-match org-ts-regexp0 s)
16691 (list 0
16692 (if (or (match-beginning 8) (not nodefault))
16693 (string-to-number (or (match-string 8 s) "0")))
16694 (if (or (match-beginning 7) (not nodefault))
16695 (string-to-number (or (match-string 7 s) "0")))
16696 (string-to-number (match-string 4 s))
16697 (string-to-number (match-string 3 s))
16698 (string-to-number (match-string 2 s))
16699 nil nil nil))
16700 ((string-match "^<[^>]+>$" s)
16701 (decode-time (seconds-to-time (org-matcher-time s))))
16702 (t (error "Not a standard Org-mode time string: %s" s))))
16704 (defun org-timestamp-up (&optional arg)
16705 "Increase the date item at the cursor by one.
16706 If the cursor is on the year, change the year. If it is on the month,
16707 the day or the time, change that.
16708 With prefix ARG, change by that many units."
16709 (interactive "p")
16710 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16712 (defun org-timestamp-down (&optional arg)
16713 "Decrease the date item at the cursor by one.
16714 If the cursor is on the year, change the year. If it is on the month,
16715 the day or the time, change that.
16716 With prefix ARG, change by that many units."
16717 (interactive "p")
16718 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16720 (defun org-timestamp-up-day (&optional arg)
16721 "Increase the date in the time stamp by one day.
16722 With prefix ARG, change that many days."
16723 (interactive "p")
16724 (if (and (not (org-at-timestamp-p t))
16725 (org-at-heading-p))
16726 (org-todo 'up)
16727 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16729 (defun org-timestamp-down-day (&optional arg)
16730 "Decrease the date in the time stamp by one day.
16731 With prefix ARG, change that many days."
16732 (interactive "p")
16733 (if (and (not (org-at-timestamp-p t))
16734 (org-at-heading-p))
16735 (org-todo 'down)
16736 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16738 (defun org-at-timestamp-p (&optional inactive-ok)
16739 "Determine if the cursor is in or at a timestamp."
16740 (interactive)
16741 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16742 (pos (point))
16743 (ans (or (looking-at tsr)
16744 (save-excursion
16745 (skip-chars-backward "^[<\n\r\t")
16746 (if (> (point) (point-min)) (backward-char 1))
16747 (and (looking-at tsr)
16748 (> (- (match-end 0) pos) -1))))))
16749 (and ans
16750 (boundp 'org-ts-what)
16751 (setq org-ts-what
16752 (cond
16753 ((= pos (match-beginning 0)) 'bracket)
16754 ;; Point is considered to be "on the bracket" whether
16755 ;; it's really on it or right after it.
16756 ((= pos (1- (match-end 0))) 'bracket)
16757 ((= pos (match-end 0)) 'after)
16758 ((org-pos-in-match-range pos 2) 'year)
16759 ((org-pos-in-match-range pos 3) 'month)
16760 ((org-pos-in-match-range pos 7) 'hour)
16761 ((org-pos-in-match-range pos 8) 'minute)
16762 ((or (org-pos-in-match-range pos 4)
16763 (org-pos-in-match-range pos 5)) 'day)
16764 ((and (> pos (or (match-end 8) (match-end 5)))
16765 (< pos (match-end 0)))
16766 (- pos (or (match-end 8) (match-end 5))))
16767 (t 'day))))
16768 ans))
16770 (defun org-toggle-timestamp-type ()
16771 "Toggle the type (<active> or [inactive]) of a time stamp."
16772 (interactive)
16773 (when (org-at-timestamp-p t)
16774 (let ((beg (match-beginning 0)) (end (match-end 0))
16775 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16776 (save-excursion
16777 (goto-char beg)
16778 (while (re-search-forward "[][<>]" end t)
16779 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16780 t t)))
16781 (message "Timestamp is now %sactive"
16782 (if (equal (char-after beg) ?<) "" "in")))))
16784 (defvar org-clock-history) ; defined in org-clock.el
16785 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16786 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16787 "Change the date in the time stamp at point.
16788 The date will be changed by N times WHAT. WHAT can be `day', `month',
16789 `year', `minute', `second'. If WHAT is not given, the cursor position
16790 in the timestamp determines what will be changed.
16791 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16792 (let ((origin (point)) origin-cat
16793 with-hm inactive
16794 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16795 org-ts-what
16796 extra rem
16797 ts time time0 fixnext clrgx)
16798 (if (not (org-at-timestamp-p t))
16799 (error "Not at a timestamp"))
16800 (if (and (not what) (eq org-ts-what 'bracket))
16801 (org-toggle-timestamp-type)
16802 ;; Point isn't on brackets. Remember the part of the time-stamp
16803 ;; the point was in. Indeed, size of time-stamps may change,
16804 ;; but point must be kept in the same category nonetheless.
16805 (setq origin-cat org-ts-what)
16806 (if (and (not what) (not (eq org-ts-what 'day))
16807 org-display-custom-times
16808 (get-text-property (point) 'display)
16809 (not (get-text-property (1- (point)) 'display)))
16810 (setq org-ts-what 'day))
16811 (setq org-ts-what (or what org-ts-what)
16812 inactive (= (char-after (match-beginning 0)) ?\[)
16813 ts (match-string 0))
16814 (replace-match "")
16815 (when (string-match
16816 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16818 (setq extra (match-string 1 ts))
16819 (if suppress-tmp-delay
16820 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16821 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16822 (setq with-hm t))
16823 (setq time0 (org-parse-time-string ts))
16824 (when (and updown
16825 (eq org-ts-what 'minute)
16826 (not current-prefix-arg))
16827 ;; This looks like s-up and s-down. Change by one rounding step.
16828 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16829 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16830 (setcar (cdr time0) (+ (nth 1 time0)
16831 (if (> n 0) (- rem) (- dm rem))))))
16832 (setq time
16833 (encode-time (or (car time0) 0)
16834 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16835 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16836 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16837 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16838 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16839 (nthcdr 6 time0)))
16840 (when (and (member org-ts-what '(hour minute))
16841 extra
16842 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16843 (setq extra (org-modify-ts-extra
16844 extra
16845 (if (eq org-ts-what 'hour) 2 5)
16846 n dm)))
16847 (when (integerp org-ts-what)
16848 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16849 (if (eq what 'calendar)
16850 (let ((cal-date (org-get-date-from-calendar)))
16851 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16852 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16853 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16854 (setcar time0 (or (car time0) 0))
16855 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16856 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16857 (setq time (apply 'encode-time time0))))
16858 ;; Insert the new time-stamp, and ensure point stays in the same
16859 ;; category as before (i.e. not after the last position in that
16860 ;; category).
16861 (let ((pos (point)))
16862 ;; Stay before inserted string. `save-excursion' is of no use.
16863 (setq org-last-changed-timestamp
16864 (org-insert-time-stamp time with-hm inactive nil nil extra))
16865 (goto-char pos))
16866 (save-match-data
16867 (looking-at org-ts-regexp3)
16868 (goto-char (cond
16869 ;; `day' category ends before `hour' if any, or at
16870 ;; the end of the day name.
16871 ((eq origin-cat 'day)
16872 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16873 ((eq origin-cat 'hour) (min (match-end 7) origin))
16874 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16875 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16876 ;; `year' and `month' have both fixed size: point
16877 ;; couldn't have moved into another part.
16878 (t origin))))
16879 ;; Update clock if on a CLOCK line.
16880 (org-clock-update-time-maybe)
16881 ;; Maybe adjust the closest clock in `org-clock-history'
16882 (when org-clock-adjust-closest
16883 (if (not (and (org-at-clock-log-p)
16884 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16885 org-clock-history))))))
16886 (message "No clock to adjust")
16887 (cond ((save-excursion ; fix previous clock?
16888 (re-search-backward org-ts-regexp0 nil t)
16889 (org-looking-back (concat org-clock-string " \\[")))
16890 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16891 ((save-excursion ; fix next clock?
16892 (re-search-backward org-ts-regexp0 nil t)
16893 (looking-at (concat org-ts-regexp0 "\\] =>")))
16894 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16895 (save-window-excursion
16896 ;; Find closest clock to point, adjust the previous/next one in history
16897 (let* ((p (save-excursion (org-back-to-heading t)))
16898 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16899 (clfixnth
16900 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16901 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16902 (if (not clfixpos)
16903 (message "No clock to adjust")
16904 (save-excursion
16905 (org-goto-marker-or-bmk clfixpos)
16906 (org-show-subtree)
16907 (when (re-search-forward clrgx nil t)
16908 (goto-char (match-beginning 1))
16909 (let (org-clock-adjust-closest)
16910 (org-timestamp-change n org-ts-what updown))
16911 (message "Clock adjusted in %s for heading: %s"
16912 (file-name-nondirectory (buffer-file-name))
16913 (org-get-heading t t)))))))))
16914 ;; Try to recenter the calendar window, if any.
16915 (if (and org-calendar-follow-timestamp-change
16916 (get-buffer-window "*Calendar*" t)
16917 (memq org-ts-what '(day month year)))
16918 (org-recenter-calendar (time-to-days time))))))
16920 (defun org-modify-ts-extra (s pos n dm)
16921 "Change the different parts of the lead-time and repeat fields in timestamp."
16922 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16923 ng h m new rem)
16924 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16925 (cond
16926 ((or (org-pos-in-match-range pos 2)
16927 (org-pos-in-match-range pos 3))
16928 (setq m (string-to-number (match-string 3 s))
16929 h (string-to-number (match-string 2 s)))
16930 (if (org-pos-in-match-range pos 2)
16931 (setq h (+ h n))
16932 (setq n (* dm (org-no-warnings (signum n))))
16933 (when (not (= 0 (setq rem (% m dm))))
16934 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16935 (setq m (+ m n)))
16936 (if (< m 0) (setq m (+ m 60) h (1- h)))
16937 (if (> m 59) (setq m (- m 60) h (1+ h)))
16938 (setq h (min 24 (max 0 h)))
16939 (setq ng 1 new (format "-%02d:%02d" h m)))
16940 ((org-pos-in-match-range pos 6)
16941 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16942 ((org-pos-in-match-range pos 5)
16943 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16945 ((org-pos-in-match-range pos 9)
16946 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16947 ((org-pos-in-match-range pos 8)
16948 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16950 (when ng
16951 (setq s (concat
16952 (substring s 0 (match-beginning ng))
16954 (substring s (match-end ng))))))
16957 (defun org-recenter-calendar (date)
16958 "If the calendar is visible, recenter it to DATE."
16959 (let ((cwin (get-buffer-window "*Calendar*" t)))
16960 (when cwin
16961 (let ((calendar-move-hook nil))
16962 (with-selected-window cwin
16963 (calendar-goto-date (if (listp date) date
16964 (calendar-gregorian-from-absolute date))))))))
16966 (defun org-goto-calendar (&optional arg)
16967 "Go to the Emacs calendar at the current date.
16968 If there is a time stamp in the current line, go to that date.
16969 A prefix ARG can be used to force the current date."
16970 (interactive "P")
16971 (let ((tsr org-ts-regexp) diff
16972 (calendar-move-hook nil)
16973 (calendar-view-holidays-initially-flag nil)
16974 (calendar-view-diary-initially-flag nil))
16975 (if (or (org-at-timestamp-p)
16976 (save-excursion
16977 (beginning-of-line 1)
16978 (looking-at (concat ".*" tsr))))
16979 (let ((d1 (time-to-days (current-time)))
16980 (d2 (time-to-days
16981 (org-time-string-to-time (match-string 1)))))
16982 (setq diff (- d2 d1))))
16983 (calendar)
16984 (calendar-goto-today)
16985 (if (and diff (not arg)) (calendar-forward-day diff))))
16987 (defun org-get-date-from-calendar ()
16988 "Return a list (month day year) of date at point in calendar."
16989 (with-current-buffer "*Calendar*"
16990 (save-match-data
16991 (calendar-cursor-to-date))))
16993 (defun org-date-from-calendar ()
16994 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16995 If there is already a time stamp at the cursor position, update it."
16996 (interactive)
16997 (if (org-at-timestamp-p t)
16998 (org-timestamp-change 0 'calendar)
16999 (let ((cal-date (org-get-date-from-calendar)))
17000 (org-insert-time-stamp
17001 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17003 (defcustom org-effort-durations
17004 `(("h" . 60)
17005 ("d" . ,(* 60 8))
17006 ("w" . ,(* 60 8 5))
17007 ("m" . ,(* 60 8 5 4))
17008 ("y" . ,(* 60 8 5 40)))
17009 "Conversion factor to minutes for an effort modifier.
17011 Each entry has the form (MODIFIER . MINUTES).
17013 In an effort string, a number followed by MODIFIER is multiplied
17014 by the specified number of MINUTES to obtain an effort in
17015 minutes.
17017 For example, if the value of this variable is ((\"hours\" . 60)), then an
17018 effort string \"2hours\" is equivalent to 120 minutes."
17019 :group 'org-agenda
17020 :version "24.1"
17021 :type '(alist :key-type (string :tag "Modifier")
17022 :value-type (number :tag "Minutes")))
17024 (defun org-minutes-to-clocksum-string (m)
17025 "Format number of minutes as a clocksum string.
17026 The format is determined by `org-time-clocksum-format',
17027 `org-time-clocksum-use-fractional' and
17028 `org-time-clocksum-fractional-format' and
17029 `org-time-clocksum-use-effort-durations'."
17030 (let ((clocksum "") h d w mo y fmt n)
17031 (setq h (if org-time-clocksum-use-effort-durations
17032 (cdr (assoc "h" org-effort-durations)) 60)
17033 d (if org-time-clocksum-use-effort-durations
17034 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17035 w (if org-time-clocksum-use-effort-durations
17036 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17037 mo (if org-time-clocksum-use-effort-durations
17038 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17039 y (if org-time-clocksum-use-effort-durations
17040 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17041 ;; fractional format
17042 (if org-time-clocksum-use-fractional
17043 (cond
17044 ;; single format string
17045 ((stringp org-time-clocksum-fractional-format)
17046 (format org-time-clocksum-fractional-format (/ m (float h))))
17047 ;; choice of fractional formats for different time units
17048 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17049 (> (/ (truncate m) (* y d h)) 0))
17050 (format fmt (/ m (* y d (float h)))))
17051 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17052 (> (/ (truncate m) (* mo d h)) 0))
17053 (format fmt (/ m (* mo d (float h)))))
17054 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17055 (> (/ (truncate m) (* w d h)) 0))
17056 (format fmt (/ m (* w d (float h)))))
17057 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17058 (> (/ (truncate m) (* d h)) 0))
17059 (format fmt (/ m (* d (float h)))))
17060 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17061 (> (/ (truncate m) h) 0))
17062 (format fmt (/ m (float h))))
17063 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17064 (format fmt m))
17065 ;; fall back to smallest time unit with a format
17066 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17067 (format fmt (/ m (float h))))
17068 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17069 (format fmt (/ m (* d (float h)))))
17070 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17071 (format fmt (/ m (* w d (float h)))))
17072 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17073 (format fmt (/ m (* mo d (float h)))))
17074 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17075 (format fmt (/ m (* y d (float h))))))
17076 ;; standard (non-fractional) format, with single format string
17077 (if (stringp org-time-clocksum-format)
17078 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17079 ;; separate formats components
17080 (and (setq fmt (plist-get org-time-clocksum-format :years))
17081 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17082 (plist-get org-time-clocksum-format :require-years))
17083 (setq clocksum (concat clocksum (format fmt n))
17084 m (- m (* n y d h))))
17085 (and (setq fmt (plist-get org-time-clocksum-format :months))
17086 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17087 (plist-get org-time-clocksum-format :require-months))
17088 (setq clocksum (concat clocksum (format fmt n))
17089 m (- m (* n mo d h))))
17090 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17091 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17092 (plist-get org-time-clocksum-format :require-weeks))
17093 (setq clocksum (concat clocksum (format fmt n))
17094 m (- m (* n w d h))))
17095 (and (setq fmt (plist-get org-time-clocksum-format :days))
17096 (or (> (setq n (/ (truncate m) (* d h))) 0)
17097 (plist-get org-time-clocksum-format :require-days))
17098 (setq clocksum (concat clocksum (format fmt n))
17099 m (- m (* n d h))))
17100 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17101 (or (> (setq n (/ (truncate m) h)) 0)
17102 (plist-get org-time-clocksum-format :require-hours))
17103 (setq clocksum (concat clocksum (format fmt n))
17104 m (- m (* n h))))
17105 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17106 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17107 (setq clocksum (concat clocksum (format fmt m))))
17108 ;; return formatted time duration
17109 clocksum))))
17111 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17112 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17113 "Org mode version 8.0")
17115 (defun org-hours-to-clocksum-string (n)
17116 (org-minutes-to-clocksum-string (* n 60)))
17118 (defun org-hh:mm-string-to-minutes (s)
17119 "Convert a string H:MM to a number of minutes.
17120 If the string is just a number, interpret it as minutes.
17121 In fact, the first hh:mm or number in the string will be taken,
17122 there can be extra stuff in the string.
17123 If no number is found, the return value is 0."
17124 (cond
17125 ((integerp s) s)
17126 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17127 (+ (* (string-to-number (match-string 1 s)) 60)
17128 (string-to-number (match-string 2 s))))
17129 ((string-match "\\([0-9]+\\)" s)
17130 (string-to-number (match-string 1 s)))
17131 (t 0)))
17133 (defcustom org-image-actual-width t
17134 "Should we use the actual width of images when inlining them?
17136 When set to `t', always use the image width.
17138 When set to a number, use imagemagick (when available) to set
17139 the image's width to this value.
17141 When set to a number in a list, try to get the width from the
17142 #+ATTR.* keyword if it matches a width specification like
17143 width=\"[0-9]+\", and fall back on that number if none is found.
17145 When set to nil, try to get the width from an #+ATTR.* keyword
17146 and fall back on the original width if none is found.
17148 This requires Emacs >= 24.1, build with imagemagick support."
17149 :group 'org-appearance
17150 :version "24.3"
17151 :type '(choice
17152 (const :tag "Use the image width" t)
17153 (integer :tag "Use a number of pixels")
17154 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17155 (const :tag "Use #+ATTR* or don't resize" nil)))
17157 (defcustom org-agenda-inhibit-startup t
17158 "Inhibit startup when preparing agenda buffers.
17159 When this variable is `t' (the default), the initialization of
17160 the Org agenda buffers is inhibited: e.g. the visibility state
17161 is not set, the tables are not re-aligned, etc."
17162 :type 'boolean
17163 :version "24.3"
17164 :group 'org-agenda)
17166 (defun org-duration-string-to-minutes (s &optional output-to-string)
17167 "Convert a duration string S to minutes.
17169 A bare number is interpreted as minutes, modifiers can be set by
17170 customizing `org-effort-durations' (which see).
17172 Entries containing a colon are interpreted as H:MM by
17173 `org-hh:mm-string-to-minutes'."
17174 (let ((result 0)
17175 (re (concat "\\([0-9.]+\\) *\\("
17176 (regexp-opt (mapcar 'car org-effort-durations))
17177 "\\)")))
17178 (while (string-match re s)
17179 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17180 (string-to-number (match-string 1 s))))
17181 (setq s (replace-match "" nil t s)))
17182 (setq result (floor result))
17183 (incf result (org-hh:mm-string-to-minutes s))
17184 (if output-to-string (number-to-string result) result)))
17186 ;;;; Files
17188 (defun org-save-all-org-buffers ()
17189 "Save all Org-mode buffers without user confirmation."
17190 (interactive)
17191 (message "Saving all Org-mode buffers...")
17192 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17193 (when (featurep 'org-id) (org-id-locations-save))
17194 (message "Saving all Org-mode buffers... done"))
17196 (defun org-revert-all-org-buffers ()
17197 "Revert all Org-mode buffers.
17198 Prompt for confirmation when there are unsaved changes.
17199 Be sure you know what you are doing before letting this function
17200 overwrite your changes.
17202 This function is useful in a setup where one tracks org files
17203 with a version control system, to revert on one machine after pulling
17204 changes from another. I believe the procedure must be like this:
17206 1. M-x org-save-all-org-buffers
17207 2. Pull changes from the other machine, resolve conflicts
17208 3. M-x org-revert-all-org-buffers"
17209 (interactive)
17210 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17211 (error "Abort"))
17212 (save-excursion
17213 (save-window-excursion
17214 (mapc
17215 (lambda (b)
17216 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17217 (with-current-buffer b buffer-file-name))
17218 (org-pop-to-buffer-same-window b)
17219 (revert-buffer t 'no-confirm)))
17220 (buffer-list))
17221 (when (and (featurep 'org-id) org-id-track-globally)
17222 (org-id-locations-load)))))
17224 ;;;; Agenda files
17226 ;;;###autoload
17227 (defun org-switchb (&optional arg)
17228 "Switch between Org buffers.
17229 With one prefix argument, restrict available buffers to files.
17230 With two prefix arguments, restrict available buffers to agenda files.
17232 Defaults to `iswitchb' for buffer name completion.
17233 Set `org-completion-use-ido' to make it use ido instead."
17234 (interactive "P")
17235 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17236 ((equal arg '(16)) (org-buffer-list 'agenda))
17237 (t (org-buffer-list))))
17238 (org-completion-use-iswitchb org-completion-use-iswitchb)
17239 (org-completion-use-ido org-completion-use-ido))
17240 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17241 (setq org-completion-use-iswitchb t))
17242 (org-pop-to-buffer-same-window
17243 (org-icompleting-read "Org buffer: "
17244 (mapcar 'list (mapcar 'buffer-name blist))
17245 nil t))))
17247 ;;; Define some older names previously used for this functionality
17248 ;;;###autoload
17249 (defalias 'org-ido-switchb 'org-switchb)
17250 ;;;###autoload
17251 (defalias 'org-iswitchb 'org-switchb)
17253 (defun org-buffer-list (&optional predicate exclude-tmp)
17254 "Return a list of Org buffers.
17255 PREDICATE can be `export', `files' or `agenda'.
17257 export restrict the list to Export buffers.
17258 files restrict the list to buffers visiting Org files.
17259 agenda restrict the list to buffers visiting agenda files.
17261 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17262 (let* ((bfn nil)
17263 (agenda-files (and (eq predicate 'agenda)
17264 (mapcar 'file-truename (org-agenda-files t))))
17265 (filter
17266 (cond
17267 ((eq predicate 'files)
17268 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17269 ((eq predicate 'export)
17270 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17271 ((eq predicate 'agenda)
17272 (lambda (b)
17273 (with-current-buffer b
17274 (and (derived-mode-p 'org-mode)
17275 (setq bfn (buffer-file-name b))
17276 (member (file-truename bfn) agenda-files)))))
17277 (t (lambda (b) (with-current-buffer b
17278 (or (derived-mode-p 'org-mode)
17279 (string-match "\*Org .*Export"
17280 (buffer-name b)))))))))
17281 (delq nil
17282 (mapcar
17283 (lambda(b)
17284 (if (and (funcall filter b)
17285 (or (not exclude-tmp)
17286 (not (string-match "tmp" (buffer-name b)))))
17288 nil))
17289 (buffer-list)))))
17291 (defun org-agenda-files (&optional unrestricted archives)
17292 "Get the list of agenda files.
17293 Optional UNRESTRICTED means return the full list even if a restriction
17294 is currently in place.
17295 When ARCHIVES is t, include all archive files that are really being
17296 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17297 `org-agenda-archives-mode' is t."
17298 (let ((files
17299 (cond
17300 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17301 ((stringp org-agenda-files) (org-read-agenda-file-list))
17302 ((listp org-agenda-files) org-agenda-files)
17303 (t (error "Invalid value of `org-agenda-files'")))))
17304 (setq files (apply 'append
17305 (mapcar (lambda (f)
17306 (if (file-directory-p f)
17307 (directory-files
17308 f t org-agenda-file-regexp)
17309 (list f)))
17310 files)))
17311 (when org-agenda-skip-unavailable-files
17312 (setq files (delq nil
17313 (mapcar (function
17314 (lambda (file)
17315 (and (file-readable-p file) file)))
17316 files))))
17317 (when (or (eq archives t)
17318 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17319 (setq files (org-add-archive-files files)))
17320 files))
17322 (defun org-agenda-file-p (&optional file)
17323 "Return non-nil, if FILE is an agenda file.
17324 If FILE is omitted, use the file associated with the current
17325 buffer."
17326 (member (or file (buffer-file-name))
17327 (org-agenda-files t)))
17329 (defun org-edit-agenda-file-list ()
17330 "Edit the list of agenda files.
17331 Depending on setup, this either uses customize to edit the variable
17332 `org-agenda-files', or it visits the file that is holding the list. In the
17333 latter case, the buffer is set up in a way that saving it automatically kills
17334 the buffer and restores the previous window configuration."
17335 (interactive)
17336 (if (stringp org-agenda-files)
17337 (let ((cw (current-window-configuration)))
17338 (find-file org-agenda-files)
17339 (org-set-local 'org-window-configuration cw)
17340 (org-add-hook 'after-save-hook
17341 (lambda ()
17342 (set-window-configuration
17343 (prog1 org-window-configuration
17344 (kill-buffer (current-buffer))))
17345 (org-install-agenda-files-menu)
17346 (message "New agenda file list installed"))
17347 nil 'local)
17348 (message "%s" (substitute-command-keys
17349 "Edit list and finish with \\[save-buffer]")))
17350 (customize-variable 'org-agenda-files)))
17352 (defun org-store-new-agenda-file-list (list)
17353 "Set new value for the agenda file list and save it correctly."
17354 (if (stringp org-agenda-files)
17355 (let ((fe (org-read-agenda-file-list t)) b u)
17356 (while (setq b (find-buffer-visiting org-agenda-files))
17357 (kill-buffer b))
17358 (with-temp-file org-agenda-files
17359 (insert
17360 (mapconcat
17361 (lambda (f) ;; Keep un-expanded entries.
17362 (if (setq u (assoc f fe))
17363 (cdr u)
17365 list "\n")
17366 "\n")))
17367 (let ((org-mode-hook nil) (org-inhibit-startup t)
17368 (org-insert-mode-line-in-empty-file nil))
17369 (setq org-agenda-files list)
17370 (customize-save-variable 'org-agenda-files org-agenda-files))))
17372 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17373 "Read the list of agenda files from a file.
17374 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17375 filenames, used by `org-store-new-agenda-file-list' to write back
17376 un-expanded file names."
17377 (when (file-directory-p org-agenda-files)
17378 (error "`org-agenda-files' cannot be a single directory"))
17379 (when (stringp org-agenda-files)
17380 (with-temp-buffer
17381 (insert-file-contents org-agenda-files)
17382 (mapcar
17383 (lambda (f)
17384 (let ((e (expand-file-name (substitute-in-file-name f)
17385 org-directory)))
17386 (if pair-with-expansion
17387 (cons e f)
17388 e)))
17389 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17391 ;;;###autoload
17392 (defun org-cycle-agenda-files ()
17393 "Cycle through the files in `org-agenda-files'.
17394 If the current buffer visits an agenda file, find the next one in the list.
17395 If the current buffer does not, find the first agenda file."
17396 (interactive)
17397 (let* ((fs (org-agenda-files t))
17398 (files (append fs (list (car fs))))
17399 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17400 file)
17401 (unless files (error "No agenda files"))
17402 (catch 'exit
17403 (while (setq file (pop files))
17404 (if (equal (file-truename file) tcf)
17405 (when (car files)
17406 (find-file (car files))
17407 (throw 'exit t))))
17408 (find-file (car fs)))
17409 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17411 (defun org-agenda-file-to-front (&optional to-end)
17412 "Move/add the current file to the top of the agenda file list.
17413 If the file is not present in the list, it is added to the front. If it is
17414 present, it is moved there. With optional argument TO-END, add/move to the
17415 end of the list."
17416 (interactive "P")
17417 (let ((org-agenda-skip-unavailable-files nil)
17418 (file-alist (mapcar (lambda (x)
17419 (cons (file-truename x) x))
17420 (org-agenda-files t)))
17421 (ctf (file-truename
17422 (or buffer-file-name
17423 (error "Please save the current buffer to a file"))))
17424 x had)
17425 (setq x (assoc ctf file-alist) had x)
17427 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17428 (if to-end
17429 (setq file-alist (append (delq x file-alist) (list x)))
17430 (setq file-alist (cons x (delq x file-alist))))
17431 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17432 (org-install-agenda-files-menu)
17433 (message "File %s to %s of agenda file list"
17434 (if had "moved" "added") (if to-end "end" "front"))))
17436 (defun org-remove-file (&optional file)
17437 "Remove current file from the list of files in variable `org-agenda-files'.
17438 These are the files which are being checked for agenda entries.
17439 Optional argument FILE means use this file instead of the current."
17440 (interactive)
17441 (let* ((org-agenda-skip-unavailable-files nil)
17442 (file (or file buffer-file-name
17443 (error "Current buffer does not visit a file")))
17444 (true-file (file-truename file))
17445 (afile (abbreviate-file-name file))
17446 (files (delq nil (mapcar
17447 (lambda (x)
17448 (if (equal true-file
17449 (file-truename x))
17450 nil x))
17451 (org-agenda-files t)))))
17452 (if (not (= (length files) (length (org-agenda-files t))))
17453 (progn
17454 (org-store-new-agenda-file-list files)
17455 (org-install-agenda-files-menu)
17456 (message "Removed file: %s" afile))
17457 (message "File was not in list: %s (not removed)" afile))))
17459 (defun org-file-menu-entry (file)
17460 (vector file (list 'find-file file) t))
17462 (defun org-check-agenda-file (file)
17463 "Make sure FILE exists. If not, ask user what to do."
17464 (when (not (file-exists-p file))
17465 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17466 (abbreviate-file-name file))
17467 (let ((r (downcase (read-char-exclusive))))
17468 (cond
17469 ((equal r ?r)
17470 (org-remove-file file)
17471 (throw 'nextfile t))
17472 (t (error "Abort"))))))
17474 (defun org-get-agenda-file-buffer (file)
17475 "Get a buffer visiting FILE. If the buffer needs to be created, add
17476 it to the list of buffers which might be released later."
17477 (let ((buf (org-find-base-buffer-visiting file)))
17478 (if buf
17479 buf ; just return it
17480 ;; Make a new buffer and remember it
17481 (setq buf (find-file-noselect file))
17482 (if buf (push buf org-agenda-new-buffers))
17483 buf)))
17485 (defun org-release-buffers (blist)
17486 "Release all buffers in list, asking the user for confirmation when needed.
17487 When a buffer is unmodified, it is just killed. When modified, it is saved
17488 \(if the user agrees) and then killed."
17489 (let (buf file)
17490 (while (setq buf (pop blist))
17491 (setq file (buffer-file-name buf))
17492 (when (and (buffer-modified-p buf)
17493 file
17494 (y-or-n-p (format "Save file %s? " file)))
17495 (with-current-buffer buf (save-buffer)))
17496 (kill-buffer buf))))
17498 (defun org-agenda-prepare-buffers (files)
17499 "Create buffers for all agenda files, protect archived trees and comments."
17500 (interactive)
17501 (let ((pa '(:org-archived t))
17502 (pc '(:org-comment t))
17503 (pall '(:org-archived t :org-comment t))
17504 (inhibit-read-only t)
17505 (org-inhibit-startup org-agenda-inhibit-startup)
17506 (rea (concat ":" org-archive-tag ":"))
17507 file re)
17508 (save-excursion
17509 (save-restriction
17510 (while (setq file (pop files))
17511 (catch 'nextfile
17512 (if (bufferp file)
17513 (set-buffer file)
17514 (org-check-agenda-file file)
17515 (set-buffer (org-get-agenda-file-buffer file)))
17516 (widen)
17517 (org-unmodified
17518 (org-refresh-category-properties)
17519 (org-refresh-properties org-effort-property 'org-effort)
17520 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17521 (setq org-todo-keywords-for-agenda
17522 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17523 (setq org-done-keywords-for-agenda
17524 (append org-done-keywords-for-agenda org-done-keywords))
17525 (setq org-todo-keyword-alist-for-agenda
17526 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17527 (setq org-drawers-for-agenda
17528 (append org-drawers-for-agenda org-drawers))
17529 (setq org-tag-alist-for-agenda
17530 (append org-tag-alist-for-agenda org-tag-alist))
17532 (save-excursion
17533 (remove-text-properties (point-min) (point-max) pall)
17534 (when org-agenda-skip-archived-trees
17535 (goto-char (point-min))
17536 (while (re-search-forward rea nil t)
17537 (if (org-at-heading-p t)
17538 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17539 (goto-char (point-min))
17540 (setq re (format org-heading-keyword-regexp-format
17541 org-comment-string))
17542 (while (re-search-forward re nil t)
17543 (add-text-properties
17544 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17545 (setq org-todo-keywords-for-agenda
17546 (org-uniquify org-todo-keywords-for-agenda))
17547 (setq org-todo-keyword-alist-for-agenda
17548 (org-uniquify org-todo-keyword-alist-for-agenda)
17549 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17553 ;;;; CDLaTeX minor mode
17555 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17556 "Keymap for the minor `org-cdlatex-mode'.")
17558 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17559 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17560 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17561 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17562 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17564 (defvar org-cdlatex-texmathp-advice-is-done nil
17565 "Flag remembering if we have applied the advice to texmathp already.")
17567 (define-minor-mode org-cdlatex-mode
17568 "Toggle the minor `org-cdlatex-mode'.
17569 This mode supports entering LaTeX environment and math in LaTeX fragments
17570 in Org-mode.
17571 \\{org-cdlatex-mode-map}"
17572 nil " OCDL" nil
17573 (when org-cdlatex-mode
17574 (require 'cdlatex)
17575 (run-hooks 'cdlatex-mode-hook)
17576 (cdlatex-compute-tables))
17577 (unless org-cdlatex-texmathp-advice-is-done
17578 (setq org-cdlatex-texmathp-advice-is-done t)
17579 (defadvice texmathp (around org-math-always-on activate)
17580 "Always return t in org-mode buffers.
17581 This is because we want to insert math symbols without dollars even outside
17582 the LaTeX math segments. If Orgmode thinks that point is actually inside
17583 an embedded LaTeX fragment, let texmathp do its job.
17584 \\[org-cdlatex-mode-map]"
17585 (interactive)
17586 (let (p)
17587 (cond
17588 ((not (derived-mode-p 'org-mode)) ad-do-it)
17589 ((eq this-command 'cdlatex-math-symbol)
17590 (setq ad-return-value t
17591 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17593 (let ((p (org-inside-LaTeX-fragment-p)))
17594 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17595 (setq ad-return-value t
17596 texmathp-why '("Org-mode embedded math" . 0))
17597 (if p ad-do-it)))))))))
17599 (defun turn-on-org-cdlatex ()
17600 "Unconditionally turn on `org-cdlatex-mode'."
17601 (org-cdlatex-mode 1))
17603 (defun org-try-cdlatex-tab ()
17604 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17605 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17606 - inside a LaTeX fragment, or
17607 - after the first word in a line, where an abbreviation expansion could
17608 insert a LaTeX environment."
17609 (when org-cdlatex-mode
17610 (cond
17611 ;; Before any word on the line: No expansion possible.
17612 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17613 ;; Just after first word on the line: Expand it. Make sure it
17614 ;; cannot happen on headlines, though.
17615 ((save-excursion
17616 (skip-chars-backward "a-zA-Z0-9*")
17617 (skip-chars-backward " \t")
17618 (and (bolp) (not (org-at-heading-p))))
17619 (cdlatex-tab) t)
17620 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17622 (defun org-cdlatex-underscore-caret (&optional arg)
17623 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17624 Revert to the normal definition outside of these fragments."
17625 (interactive "P")
17626 (if (org-inside-LaTeX-fragment-p)
17627 (call-interactively 'cdlatex-sub-superscript)
17628 (let (org-cdlatex-mode)
17629 (call-interactively (key-binding (vector last-input-event))))))
17631 (defun org-cdlatex-math-modify (&optional arg)
17632 "Execute `cdlatex-math-modify' in LaTeX fragments.
17633 Revert to the normal definition outside of these fragments."
17634 (interactive "P")
17635 (if (org-inside-LaTeX-fragment-p)
17636 (call-interactively 'cdlatex-math-modify)
17637 (let (org-cdlatex-mode)
17638 (call-interactively (key-binding (vector last-input-event))))))
17642 ;;;; LaTeX fragments
17644 (defvar org-latex-regexps
17645 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17646 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17647 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17648 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17649 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17650 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17651 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17652 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17653 "Regular expressions for matching embedded LaTeX.")
17655 (defun org-inside-LaTeX-fragment-p ()
17656 "Test if point is inside a LaTeX fragment.
17657 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17658 sequence appearing also before point.
17659 Even though the matchers for math are configurable, this function assumes
17660 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17661 delimiters are skipped when they have been removed by customization.
17662 The return value is nil, or a cons cell with the delimiter and the
17663 position of this delimiter.
17665 This function does a reasonably good job, but can locally be fooled by
17666 for example currency specifications. For example it will assume being in
17667 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17668 fragments that are properly closed, but during editing, we have to live
17669 with the uncertainty caused by missing closing delimiters. This function
17670 looks only before point, not after."
17671 (catch 'exit
17672 (let ((pos (point))
17673 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17674 (lim (progn
17675 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17676 (point)))
17677 dd-on str (start 0) m re)
17678 (goto-char pos)
17679 (when dodollar
17680 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17681 re (nth 1 (assoc "$" org-latex-regexps)))
17682 (while (string-match re str start)
17683 (cond
17684 ((= (match-end 0) (length str))
17685 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17686 ((= (match-end 0) (- (length str) 5))
17687 (throw 'exit nil))
17688 (t (setq start (match-end 0))))))
17689 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17690 (goto-char pos)
17691 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17692 (and (match-beginning 2) (throw 'exit nil))
17693 ;; count $$
17694 (while (re-search-backward "\\$\\$" lim t)
17695 (setq dd-on (not dd-on)))
17696 (goto-char pos)
17697 (if dd-on (cons "$$" m))))))
17699 (defun org-inside-latex-macro-p ()
17700 "Is point inside a LaTeX macro or its arguments?"
17701 (save-match-data
17702 (org-in-regexp
17703 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17705 (defvar org-latex-fragment-image-overlays nil
17706 "List of overlays carrying the images of latex fragments.")
17707 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17709 (defun org-remove-latex-fragment-image-overlays ()
17710 "Remove all overlays with LaTeX fragment images in current buffer."
17711 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17712 (setq org-latex-fragment-image-overlays nil))
17714 (defun org-preview-latex-fragment (&optional subtree)
17715 "Preview the LaTeX fragment at point, or all locally or globally.
17716 If the cursor is in a LaTeX fragment, create the image and overlay
17717 it over the source code. If there is no fragment at point, display
17718 all fragments in the current text, from one headline to the next. With
17719 prefix SUBTREE, display all fragments in the current subtree. With a
17720 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17721 the cursor is before the first headline,
17722 display all fragments in the buffer.
17723 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17724 (interactive "P")
17725 (unless buffer-file-name
17726 (error "Can't preview LaTeX fragment in a non-file buffer"))
17727 (org-remove-latex-fragment-image-overlays)
17728 (save-excursion
17729 (save-restriction
17730 (let (beg end at msg)
17731 (cond
17732 ((or (equal subtree '(16))
17733 (not (save-excursion
17734 (re-search-backward org-outline-regexp-bol nil t))))
17735 (setq beg (point-min) end (point-max)
17736 msg "Creating images for buffer...%s"))
17737 ((equal subtree '(4))
17738 (org-back-to-heading)
17739 (setq beg (point) end (org-end-of-subtree t)
17740 msg "Creating images for subtree...%s"))
17742 (if (setq at (org-inside-LaTeX-fragment-p))
17743 (goto-char (max (point-min) (- (cdr at) 2)))
17744 (org-back-to-heading))
17745 (setq beg (point) end (progn (outline-next-heading) (point))
17746 msg (if at "Creating image...%s"
17747 "Creating images for entry...%s"))))
17748 (message msg "")
17749 (narrow-to-region beg end)
17750 (goto-char beg)
17751 (org-format-latex
17752 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17753 (file-name-nondirectory
17754 buffer-file-name)))
17755 default-directory 'overlays msg at 'forbuffer
17756 org-latex-create-formula-image-program)
17757 (message msg "done. Use `C-c C-c' to remove images.")))))
17759 (defun org-format-latex (prefix &optional dir overlays msg at
17760 forbuffer processing-type)
17761 "Replace LaTeX fragments with links to an image, and produce images.
17762 Some of the options can be changed using the variable
17763 `org-format-latex-options'."
17764 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17765 (let* ((prefixnodir (file-name-nondirectory prefix))
17766 (absprefix (expand-file-name prefix dir))
17767 (todir (file-name-directory absprefix))
17768 (opt org-format-latex-options)
17769 (optnew org-format-latex-options)
17770 (matchers (plist-get opt :matchers))
17771 (re-list org-latex-regexps)
17772 (cnt 0) txt hash link beg end re e checkdir
17773 string
17774 m n block-type block linkfile movefile ov)
17775 ;; Check the different regular expressions
17776 (while (setq e (pop re-list))
17777 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17778 block (if block-type "\n\n" ""))
17779 (when (member m matchers)
17780 (goto-char (point-min))
17781 (while (re-search-forward re nil t)
17782 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17783 (or (not overlays)
17784 (not (eq (get-char-property (match-beginning n)
17785 'org-overlay-type)
17786 'org-latex-overlay))))
17787 (cond
17788 ((eq processing-type 'verbatim))
17789 ((eq processing-type 'mathjax)
17790 ;; Prepare for MathJax processing.
17791 (setq string (match-string n))
17792 (when (member m '("$" "$1"))
17793 (save-excursion
17794 (delete-region (match-beginning n) (match-end n))
17795 (goto-char (match-beginning n))
17796 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17797 ((or (eq processing-type 'dvipng)
17798 (eq processing-type 'imagemagick))
17799 ;; Process to an image.
17800 (setq txt (match-string n)
17801 beg (match-beginning n) end (match-end n)
17802 cnt (1+ cnt))
17803 (let ((face (face-at-point))
17804 (fg (plist-get opt :foreground))
17805 (bg (plist-get opt :background))
17806 ;; Ensure full list is printed.
17807 print-length print-level)
17808 (when forbuffer
17809 ;; Get the colors from the face at point.
17810 (goto-char beg)
17811 (when (eq fg 'auto)
17812 (setq fg (face-attribute face :foreground nil 'default)))
17813 (when (eq bg 'auto)
17814 (setq bg (face-attribute face :background nil 'default)))
17815 (setq optnew (copy-sequence opt))
17816 (plist-put optnew :foreground fg)
17817 (plist-put optnew :background bg))
17818 (setq hash (sha1 (prin1-to-string
17819 (list org-format-latex-header
17820 org-latex-default-packages-alist
17821 org-latex-packages-alist
17822 org-format-latex-options
17823 forbuffer txt fg bg)))
17824 linkfile (format "%s_%s.png" prefix hash)
17825 movefile (format "%s_%s.png" absprefix hash)))
17826 (setq link (concat block "[[file:" linkfile "]]" block))
17827 (if msg (message msg cnt))
17828 (goto-char beg)
17829 (unless checkdir ; Ensure the directory exists.
17830 (setq checkdir t)
17831 (or (file-directory-p todir) (make-directory todir t)))
17832 (unless (file-exists-p movefile)
17833 (org-create-formula-image
17834 txt movefile optnew forbuffer processing-type))
17835 (if overlays
17836 (progn
17837 (mapc (lambda (o)
17838 (if (eq (overlay-get o 'org-overlay-type)
17839 'org-latex-overlay)
17840 (delete-overlay o)))
17841 (overlays-in beg end))
17842 (setq ov (make-overlay beg end))
17843 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17844 (if (featurep 'xemacs)
17845 (progn
17846 (overlay-put ov 'invisible t)
17847 (overlay-put
17848 ov 'end-glyph
17849 (make-glyph (vector 'png :file movefile))))
17850 (overlay-put
17851 ov 'display
17852 (list 'image :type 'png :file movefile :ascent 'center)))
17853 (push ov org-latex-fragment-image-overlays)
17854 (goto-char end))
17855 (delete-region beg end)
17856 (insert (org-add-props link
17857 (list 'org-latex-src
17858 (replace-regexp-in-string
17859 "\"" "" txt)
17860 'org-latex-src-embed-type
17861 (if block-type 'paragraph 'character))))))
17862 ((eq processing-type 'mathml)
17863 ;; Process to MathML
17864 (unless (save-match-data (org-format-latex-mathml-available-p))
17865 (error "LaTeX to MathML converter not configured"))
17866 (setq txt (match-string n)
17867 beg (match-beginning n) end (match-end n)
17868 cnt (1+ cnt))
17869 (if msg (message msg cnt))
17870 (goto-char beg)
17871 (delete-region beg end)
17872 (insert (org-format-latex-as-mathml
17873 txt block-type prefix dir)))
17875 (error "Unknown conversion type %s for latex fragments"
17876 processing-type)))))))))
17878 (defun org-create-math-formula (latex-frag &optional mathml-file)
17879 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17880 Use `org-latex-to-mathml-convert-command'. If the conversion is
17881 sucessful, return the portion between \"<math...> </math>\"
17882 elements otherwise return nil. When MATHML-FILE is specified,
17883 write the results in to that file. When invoked as an
17884 interactive command, prompt for LATEX-FRAG, with initial value
17885 set to the current active region and echo the results for user
17886 inspection."
17887 (interactive (list (let ((frag (when (org-region-active-p)
17888 (buffer-substring-no-properties
17889 (region-beginning) (region-end)))))
17890 (read-string "LaTeX Fragment: " frag nil frag))))
17891 (unless latex-frag (error "Invalid latex-frag"))
17892 (let* ((tmp-in-file (file-relative-name
17893 (make-temp-name (expand-file-name "ltxmathml-in"))))
17894 (ignore (write-region latex-frag nil tmp-in-file))
17895 (tmp-out-file (file-relative-name
17896 (make-temp-name (expand-file-name "ltxmathml-out"))))
17897 (cmd (format-spec
17898 org-latex-to-mathml-convert-command
17899 `((?j . ,(shell-quote-argument
17900 (expand-file-name org-latex-to-mathml-jar-file)))
17901 (?I . ,(shell-quote-argument tmp-in-file))
17902 (?o . ,(shell-quote-argument tmp-out-file)))))
17903 mathml shell-command-output)
17904 (when (org-called-interactively-p 'any)
17905 (unless (org-format-latex-mathml-available-p)
17906 (error "LaTeX to MathML converter not configured")))
17907 (message "Running %s" cmd)
17908 (setq shell-command-output (shell-command-to-string cmd))
17909 (setq mathml
17910 (when (file-readable-p tmp-out-file)
17911 (with-current-buffer (find-file-noselect tmp-out-file t)
17912 (goto-char (point-min))
17913 (when (re-search-forward
17914 (concat
17915 (regexp-quote
17916 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17917 "\\(.\\|\n\\)*"
17918 (regexp-quote "</math>")) nil t)
17919 (prog1 (match-string 0) (kill-buffer))))))
17920 (cond
17921 (mathml
17922 (setq mathml
17923 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17924 (when mathml-file
17925 (write-region mathml nil mathml-file))
17926 (when (org-called-interactively-p 'any)
17927 (message mathml)))
17928 ((message "LaTeX to MathML conversion failed")
17929 (message shell-command-output)))
17930 (delete-file tmp-in-file)
17931 (when (file-exists-p tmp-out-file)
17932 (delete-file tmp-out-file))
17933 mathml))
17935 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17936 prefix &optional dir)
17937 "Use `org-create-math-formula' but check local cache first."
17938 (let* ((absprefix (expand-file-name prefix dir))
17939 (print-length nil) (print-level nil)
17940 (formula-id (concat
17941 "formula-"
17942 (sha1
17943 (prin1-to-string
17944 (list latex-frag
17945 org-latex-to-mathml-convert-command)))))
17946 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17947 (formula-cache-dir (file-name-directory formula-cache)))
17949 (unless (file-directory-p formula-cache-dir)
17950 (make-directory formula-cache-dir t))
17952 (unless (file-exists-p formula-cache)
17953 (org-create-math-formula latex-frag formula-cache))
17955 (if (file-exists-p formula-cache)
17956 ;; Successful conversion. Return the link to MathML file.
17957 (org-add-props
17958 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17959 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17960 'org-latex-src-embed-type (if latex-frag-type
17961 'paragraph 'character)))
17962 ;; Failed conversion. Return the LaTeX fragment verbatim
17963 latex-frag)))
17965 (defun org-create-formula-image (string tofile options buffer &optional type)
17966 "Create an image from LaTeX source using dvipng or convert.
17967 This function calls either `org-create-formula-image-with-dvipng'
17968 or `org-create-formula-image-with-imagemagick' depending on the
17969 value of `org-latex-create-formula-image-program' or on the value
17970 of the optional TYPE variable.
17972 Note: ultimately these two function should be combined as they
17973 share a good deal of logic."
17974 (org-check-external-command
17975 "latex" "needed to convert LaTeX fragments to images")
17976 (funcall
17977 (case (or type org-latex-create-formula-image-program)
17978 ('dvipng
17979 (org-check-external-command
17980 "dvipng" "needed to convert LaTeX fragments to images")
17981 #'org-create-formula-image-with-dvipng)
17982 ('imagemagick
17983 (org-check-external-command
17984 "convert" "you need to install imagemagick")
17985 #'org-create-formula-image-with-imagemagick)
17986 (t (error
17987 "invalid value of `org-latex-create-formula-image-program'")))
17988 string tofile options buffer))
17990 ;; This function borrows from Ganesh Swami's latex2png.el
17991 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17992 "This calls dvipng."
17993 (let* ((tmpdir (if (featurep 'xemacs)
17994 (temp-directory)
17995 temporary-file-directory))
17996 (texfilebase (make-temp-name
17997 (expand-file-name "orgtex" tmpdir)))
17998 (texfile (concat texfilebase ".tex"))
17999 (dvifile (concat texfilebase ".dvi"))
18000 (pngfile (concat texfilebase ".png"))
18001 (fnh (if (featurep 'xemacs)
18002 (font-height (face-font 'default))
18003 (face-attribute 'default :height nil)))
18004 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18005 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18006 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18007 "Black"))
18008 (bg (or (plist-get options (if buffer :background :html-background))
18009 "Transparent")))
18010 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18011 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18012 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18013 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18014 (with-temp-file texfile
18015 (require 'ox-latex)
18016 (insert (org-latex-guess-inputenc
18017 (org-splice-latex-header
18018 org-format-latex-header
18019 org-latex-default-packages-alist
18020 org-latex-packages-alist t)))
18021 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18022 (let ((dir default-directory))
18023 (condition-case nil
18024 (progn
18025 (cd tmpdir)
18026 (call-process "latex" nil nil nil texfile))
18027 (error nil))
18028 (cd dir))
18029 (if (not (file-exists-p dvifile))
18030 (progn (message "Failed to create dvi file from %s" texfile) nil)
18031 (condition-case nil
18032 (if (featurep 'xemacs)
18033 (call-process "dvipng" nil nil nil
18034 "-fg" fg "-bg" bg
18035 "-T" "tight"
18036 "-o" pngfile
18037 dvifile)
18038 (call-process "dvipng" nil nil nil
18039 "-fg" fg "-bg" bg
18040 "-D" dpi
18041 ;;"-x" scale "-y" scale
18042 "-T" "tight"
18043 "-o" pngfile
18044 dvifile))
18045 (error nil))
18046 (if (not (file-exists-p pngfile))
18047 (if org-format-latex-signal-error
18048 (error "Failed to create png file from %s" texfile)
18049 (message "Failed to create png file from %s" texfile)
18050 nil)
18051 ;; Use the requested file name and clean up
18052 (copy-file pngfile tofile 'replace)
18053 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18054 (if (file-exists-p (concat texfilebase e))
18055 (delete-file (concat texfilebase e))))
18056 pngfile))))
18058 (defvar org-latex-pdf-process) ; From ox-latex.el
18059 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18060 "This calls convert, which is included into imagemagick."
18061 (let* ((tmpdir (if (featurep 'xemacs)
18062 (temp-directory)
18063 temporary-file-directory))
18064 (texfilebase (make-temp-name
18065 (expand-file-name "orgtex" tmpdir)))
18066 (texfile (concat texfilebase ".tex"))
18067 (pdffile (concat texfilebase ".pdf"))
18068 (pngfile (concat texfilebase ".png"))
18069 (fnh (if (featurep 'xemacs)
18070 (font-height (face-font 'default))
18071 (face-attribute 'default :height nil)))
18072 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18073 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18074 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18075 "black"))
18076 (bg (or (plist-get options (if buffer :background :html-background))
18077 "white")))
18078 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18079 (setq fg (org-latex-color-format fg)))
18080 (if (eq bg 'default) (setq bg (org-latex-color :background))
18081 (setq bg (org-latex-color-format
18082 (if (string= bg "Transparent") "white" bg))))
18083 (with-temp-file texfile
18084 (require 'ox-latex)
18085 (insert (org-latex-guess-inputenc
18086 (org-splice-latex-header
18087 org-format-latex-header
18088 org-latex-default-packages-alist
18089 org-latex-packages-alist t)))
18090 (insert "\n\\begin{document}\n"
18091 "\\definecolor{fg}{rgb}{" fg "}\n"
18092 "\\definecolor{bg}{rgb}{" bg "}\n"
18093 "\n\\pagecolor{bg}\n"
18094 "\n{\\color{fg}\n"
18095 string
18096 "\n}\n"
18097 "\n\\end{document}\n"))
18098 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18099 (condition-case nil
18100 (progn
18101 (cd tmpdir)
18102 (setq cmds org-latex-pdf-process)
18103 (while cmds
18104 (setq latex-frags-cmds (pop cmds))
18105 (if (listp latex-frags-cmds)
18106 (setq cmds nil)
18107 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18108 (while latex-frags-cmds
18109 (setq cmd (pop latex-frags-cmds))
18110 (while (string-match "%b" cmd)
18111 (setq cmd (replace-match
18112 (save-match-data
18113 (shell-quote-argument texfile))
18114 t t cmd)))
18115 (while (string-match "%f" cmd)
18116 (setq cmd (replace-match
18117 (save-match-data
18118 (shell-quote-argument
18119 (file-name-nondirectory texfile)))
18120 t t cmd)))
18121 (while (string-match "%o" cmd)
18122 (setq cmd (replace-match
18123 (save-match-data
18124 (shell-quote-argument
18125 (file-name-directory texfile)))
18126 t t cmd)))
18127 (setq cmd (split-string cmd))
18128 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18129 (error nil))
18130 (cd dir))
18131 (if (not (file-exists-p pdffile))
18132 (progn (message "Failed to create pdf file from %s" texfile) nil)
18133 (condition-case nil
18134 (if (featurep 'xemacs)
18135 (call-process "convert" nil nil nil
18136 "-density" "96"
18137 "-trim"
18138 "-antialias"
18139 pdffile
18140 "-quality" "100"
18141 ;; "-sharpen" "0x1.0"
18142 pngfile)
18143 (call-process "convert" nil nil nil
18144 "-density" dpi
18145 "-trim"
18146 "-antialias"
18147 pdffile
18148 "-quality" "100"
18149 ;; "-sharpen" "0x1.0"
18150 pngfile))
18151 (error nil))
18152 (if (not (file-exists-p pngfile))
18153 (if org-format-latex-signal-error
18154 (error "Failed to create png file from %s" texfile)
18155 (message "Failed to create png file from %s" texfile)
18156 nil)
18157 ;; Use the requested file name and clean up
18158 (copy-file pngfile tofile 'replace)
18159 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18160 (if (file-exists-p (concat texfilebase e))
18161 (delete-file (concat texfilebase e))))
18162 pngfile))))
18164 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18165 "Fill a LaTeX header template TPL.
18166 In the template, the following place holders will be recognized:
18168 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18169 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18170 [PACKAGES] \\usepackage statements for PKG
18171 [NO-PACKAGES] do not include PKG
18172 [EXTRA] the string EXTRA
18173 [NO-EXTRA] do not include EXTRA
18175 For backward compatibility, if both the positive and the negative place
18176 holder is missing, the positive one (without the \"NO-\") will be
18177 assumed to be present at the end of the template.
18178 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18179 EXTRA is a string.
18180 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18181 (let (rpl (end ""))
18182 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18183 (setq rpl (if (or (match-end 1) (not def-pkg))
18184 "" (org-latex-packages-to-string def-pkg snippets-p t))
18185 tpl (replace-match rpl t t tpl))
18186 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18188 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18189 (setq rpl (if (or (match-end 1) (not pkg))
18190 "" (org-latex-packages-to-string pkg snippets-p t))
18191 tpl (replace-match rpl t t tpl))
18192 (if pkg (setq end
18193 (concat end "\n"
18194 (org-latex-packages-to-string pkg snippets-p)))))
18196 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18197 (setq rpl (if (or (match-end 1) (not extra))
18198 "" (concat extra "\n"))
18199 tpl (replace-match rpl t t tpl))
18200 (if (and extra (string-match "\\S-" extra))
18201 (setq end (concat end "\n" extra))))
18203 (if (string-match "\\S-" end)
18204 (concat tpl "\n" end)
18205 tpl)))
18207 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18208 "Turn an alist of packages into a string with the \\usepackage macros."
18209 (setq pkg (mapconcat (lambda(p)
18210 (cond
18211 ((stringp p) p)
18212 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18213 (format "%% Package %s omitted" (cadr p)))
18214 ((equal "" (car p))
18215 (format "\\usepackage{%s}" (cadr p)))
18217 (format "\\usepackage[%s]{%s}"
18218 (car p) (cadr p)))))
18220 "\n"))
18221 (if newline (concat pkg "\n") pkg))
18223 (defun org-dvipng-color (attr)
18224 "Return a RGB color specification for dvipng."
18225 (apply 'format "rgb %s %s %s"
18226 (mapcar 'org-normalize-color
18227 (if (featurep 'xemacs)
18228 (color-rgb-components
18229 (face-property 'default
18230 (cond ((eq attr :foreground) 'foreground)
18231 ((eq attr :background) 'background))))
18232 (color-values (face-attribute 'default attr nil))))))
18234 (defun org-dvipng-color-format (color-name)
18235 "Convert COLOR-NAME to a RGB color value for dvipng."
18236 (apply 'format "rgb %s %s %s"
18237 (mapcar 'org-normalize-color
18238 (color-values color-name))))
18240 (defun org-latex-color (attr)
18241 "Return a RGB color for the LaTeX color package."
18242 (apply 'format "%s,%s,%s"
18243 (mapcar 'org-normalize-color
18244 (if (featurep 'xemacs)
18245 (color-rgb-components
18246 (face-property 'default
18247 (cond ((eq attr :foreground) 'foreground)
18248 ((eq attr :background) 'background))))
18249 (color-values (face-attribute 'default attr nil))))))
18251 (defun org-latex-color-format (color-name)
18252 "Convert COLOR-NAME to a RGB color value."
18253 (apply 'format "%s,%s,%s"
18254 (mapcar 'org-normalize-color
18255 (color-values color-name))))
18257 (defun org-normalize-color (value)
18258 "Return string to be used as color value for an RGB component."
18259 (format "%g" (/ value 65535.0)))
18263 ;; Image display
18265 (defvar org-inline-image-overlays nil)
18266 (make-variable-buffer-local 'org-inline-image-overlays)
18268 (defun org-toggle-inline-images (&optional include-linked)
18269 "Toggle the display of inline images.
18270 INCLUDE-LINKED is passed to `org-display-inline-images'."
18271 (interactive "P")
18272 (if org-inline-image-overlays
18273 (progn
18274 (org-remove-inline-images)
18275 (message "Inline image display turned off"))
18276 (org-display-inline-images include-linked)
18277 (if (and (org-called-interactively-p)
18278 org-inline-image-overlays)
18279 (message "%d images displayed inline"
18280 (length org-inline-image-overlays))
18281 (message "No images to display inline"))))
18283 (defun org-redisplay-inline-images ()
18284 "Refresh the display of inline images."
18285 (interactive)
18286 (if (not org-inline-image-overlays)
18287 (org-toggle-inline-images)
18288 (org-toggle-inline-images)
18289 (org-toggle-inline-images)))
18291 (defun org-display-inline-images (&optional include-linked refresh beg end)
18292 "Display inline images.
18293 Normally only links without a description part are inlined, because this
18294 is how it will work for export. When INCLUDE-LINKED is set, also links
18295 with a description part will be inlined. This can be nice for a quick
18296 look at those images, but it does not reflect what exported files will look
18297 like.
18298 When REFRESH is set, refresh existing images between BEG and END.
18299 This will create new image displays only if necessary.
18300 BEG and END default to the buffer boundaries."
18301 (interactive "P")
18302 (unless refresh
18303 (org-remove-inline-images)
18304 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18305 (save-excursion
18306 (save-restriction
18307 (widen)
18308 (setq beg (or beg (point-min)) end (or end (point-max)))
18309 (goto-char beg)
18310 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18311 (substring (org-image-file-name-regexp) 0 -2)
18312 "\\)\\]" (if include-linked "" "\\]")))
18313 old file ov img type attrwidth width)
18314 (while (re-search-forward re end t)
18315 (setq old (get-char-property-and-overlay (match-beginning 1)
18316 'org-image-overlay)
18317 file (expand-file-name
18318 (concat (or (match-string 3) "") (match-string 4))))
18319 (when (image-type-available-p 'imagemagick)
18320 (setq attrwidth (if (or (listp org-image-actual-width)
18321 (null org-image-actual-width))
18322 (save-excursion
18323 (save-match-data
18324 (when (re-search-backward
18325 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18326 (save-excursion
18327 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18328 (string-to-number (match-string 1))))))
18329 width (cond ((eq org-image-actual-width t) nil)
18330 ((null org-image-actual-width) attrwidth)
18331 ((numberp org-image-actual-width)
18332 org-image-actual-width)
18333 ((listp org-image-actual-width)
18334 (or attrwidth (car org-image-actual-width))))
18335 type (if width 'imagemagick)))
18336 (when (file-exists-p file)
18337 (if (and (car-safe old) refresh)
18338 (image-refresh (overlay-get (cdr old) 'display))
18339 (setq img (save-match-data (create-image file type nil :width width)))
18340 (when img
18341 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18342 (overlay-put ov 'display img)
18343 (overlay-put ov 'face 'default)
18344 (overlay-put ov 'org-image-overlay t)
18345 (overlay-put ov 'modification-hooks
18346 (list 'org-display-inline-remove-overlay))
18347 (push ov org-inline-image-overlays)))))))))
18349 (define-obsolete-function-alias
18350 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18352 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18353 "Remove inline-display overlay if a corresponding region is modified."
18354 (let ((inhibit-modification-hooks t))
18355 (when (and ov after)
18356 (delete ov org-inline-image-overlays)
18357 (delete-overlay ov))))
18359 (defun org-remove-inline-images ()
18360 "Remove inline display of images."
18361 (interactive)
18362 (mapc 'delete-overlay org-inline-image-overlays)
18363 (setq org-inline-image-overlays nil))
18365 ;;;; Key bindings
18367 ;; Outline functions from `outline-mode-prefix-map'
18368 ;; that can be remapped in Org:
18369 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18370 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18371 (define-key org-mode-map [remap outline-forward-same-level]
18372 'org-forward-heading-same-level)
18373 (define-key org-mode-map [remap outline-backward-same-level]
18374 'org-backward-heading-same-level)
18375 (define-key org-mode-map [remap show-branches]
18376 'org-kill-note-or-show-branches)
18377 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18378 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18379 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18381 ;; Outline functions from `outline-mode-prefix-map' that can not
18382 ;; be remapped in Org:
18384 ;; - the column "key binding" shows whether the Outline function is still
18385 ;; available in Org mode on the same key that it has been bound to in
18386 ;; Outline mode:
18387 ;; - "overridden": key used for a different functionality in Org mode
18388 ;; - else: key still bound to the same Outline function in Org mode
18390 ;; | Outline function | key binding | Org replacement |
18391 ;; |------------------------------------+-------------+-----------------------|
18392 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18393 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18394 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18395 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18396 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18397 ;; | `show-entry' | overridden | no replacement |
18398 ;; | `show-children' | `C-c C-i' | visibility cycling |
18399 ;; | `show-branches' | `C-c C-k' | still same function |
18400 ;; | `show-subtree' | overridden | visibility cycling |
18401 ;; | `show-all' | overridden | no replacement |
18402 ;; | `hide-subtree' | overridden | visibility cycling |
18403 ;; | `hide-body' | overridden | no replacement |
18404 ;; | `hide-entry' | overridden | visibility cycling |
18405 ;; | `hide-leaves' | overridden | no replacement |
18406 ;; | `hide-sublevels' | overridden | no replacement |
18407 ;; | `hide-other' | overridden | no replacement |
18409 ;; Make `C-c C-x' a prefix key
18410 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18412 ;; TAB key with modifiers
18413 (org-defkey org-mode-map "\C-i" 'org-cycle)
18414 (org-defkey org-mode-map [(tab)] 'org-cycle)
18415 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18416 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18417 ;; The following line is necessary under Suse GNU/Linux
18418 (unless (featurep 'xemacs)
18419 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18420 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18421 (define-key org-mode-map [backtab] 'org-shifttab)
18423 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18424 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18425 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18427 ;; Cursor keys with modifiers
18428 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18429 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18430 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18431 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18433 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18434 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18435 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18436 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18438 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18439 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18440 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18441 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18443 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18444 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18445 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18446 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18448 ;; Babel keys
18449 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18450 (mapc (lambda (pair)
18451 (define-key org-babel-map (car pair) (cdr pair)))
18452 org-babel-key-bindings)
18454 ;;; Extra keys for tty access.
18455 ;; We only set them when really needed because otherwise the
18456 ;; menus don't show the simple keys
18458 (when (or org-use-extra-keys
18459 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18460 (not window-system))
18461 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18462 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18463 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18464 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18465 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18466 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18467 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18468 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18469 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18470 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18471 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18472 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18473 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18474 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18475 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18476 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18477 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18478 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18479 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18480 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18481 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18482 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18483 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18484 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18485 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18486 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18487 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18488 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18490 ;; All the other keys
18492 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18493 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18494 (if (boundp 'narrow-map)
18495 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18496 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18497 (if (boundp 'narrow-map)
18498 (org-defkey narrow-map "b" 'org-narrow-to-block)
18499 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18500 (if (boundp 'narrow-map)
18501 (org-defkey narrow-map "e" 'org-narrow-to-element)
18502 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18503 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18504 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18505 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18506 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18507 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18508 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18509 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18510 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18511 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18512 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18513 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18514 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18515 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18516 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18517 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18518 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18519 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18520 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18521 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18522 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18523 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18524 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18525 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18526 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18527 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18528 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18529 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18530 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18531 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18532 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18533 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18534 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18535 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18536 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18537 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18538 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18539 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18540 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18541 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18542 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18543 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18544 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18545 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18546 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18547 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18548 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18549 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18550 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18551 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18552 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18553 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18554 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18555 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18556 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18557 (org-defkey org-mode-map "\C-c^" 'org-sort)
18558 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18559 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18560 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18561 (org-defkey org-mode-map "\C-m" 'org-return)
18562 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18563 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18564 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18565 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18566 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18567 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18568 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18569 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18570 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18571 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18572 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18573 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18574 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18575 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18576 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18577 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18578 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18579 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18580 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18581 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18582 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18583 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18584 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18586 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18587 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18588 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18590 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18591 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18592 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18593 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18594 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18595 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18596 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18597 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18598 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18599 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18600 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18601 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18602 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18603 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18604 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18605 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18606 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18607 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18608 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18609 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18610 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18611 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18612 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18614 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18615 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18616 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18617 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18618 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18620 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18622 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18624 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18625 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18627 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18630 (when (featurep 'xemacs)
18631 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18634 (defconst org-speed-commands-default
18636 ("Outline Navigation")
18637 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18638 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18639 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18640 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18641 ("F" . org-next-block)
18642 ("B" . org-previous-block)
18643 ("u" . (org-speed-move-safe 'outline-up-heading))
18644 ("j" . org-goto)
18645 ("g" . (org-refile t))
18646 ("Outline Visibility")
18647 ("c" . org-cycle)
18648 ("C" . org-shifttab)
18649 (" " . org-display-outline-path)
18650 ("=" . org-columns)
18651 ("Outline Structure Editing")
18652 ("U" . org-shiftmetaup)
18653 ("D" . org-shiftmetadown)
18654 ("r" . org-metaright)
18655 ("l" . org-metaleft)
18656 ("R" . org-shiftmetaright)
18657 ("L" . org-shiftmetaleft)
18658 ("i" . (progn (forward-char 1) (call-interactively
18659 'org-insert-heading-respect-content)))
18660 ("^" . org-sort)
18661 ("w" . org-refile)
18662 ("a" . org-archive-subtree-default-with-confirmation)
18663 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18664 ("#" . org-toggle-comment)
18665 ("Clock Commands")
18666 ("I" . org-clock-in)
18667 ("O" . org-clock-out)
18668 ("Meta Data Editing")
18669 ("t" . org-todo)
18670 ("," . (org-priority))
18671 ("0" . (org-priority ?\ ))
18672 ("1" . (org-priority ?A))
18673 ("2" . (org-priority ?B))
18674 ("3" . (org-priority ?C))
18675 (":" . org-set-tags-command)
18676 ("e" . org-set-effort)
18677 ("E" . org-inc-effort)
18678 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18679 (org-entry-put (point) "APPT_WARNTIME" m)))
18680 ("Agenda Views etc")
18681 ("v" . org-agenda)
18682 ("/" . org-sparse-tree)
18683 ("Misc")
18684 ("o" . org-open-at-point)
18685 ("?" . org-speed-command-help)
18686 ("<" . (org-agenda-set-restriction-lock 'subtree))
18687 (">" . (org-agenda-remove-restriction-lock))
18689 "The default speed commands.")
18691 (defun org-print-speed-command (e)
18692 (if (> (length (car e)) 1)
18693 (progn
18694 (princ "\n")
18695 (princ (car e))
18696 (princ "\n")
18697 (princ (make-string (length (car e)) ?-))
18698 (princ "\n"))
18699 (princ (car e))
18700 (princ " ")
18701 (if (symbolp (cdr e))
18702 (princ (symbol-name (cdr e)))
18703 (prin1 (cdr e)))
18704 (princ "\n")))
18706 (defun org-speed-command-help ()
18707 "Show the available speed commands."
18708 (interactive)
18709 (if (not org-use-speed-commands)
18710 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18711 (with-output-to-temp-buffer "*Help*"
18712 (princ "User-defined Speed commands\n===========================\n")
18713 (mapc 'org-print-speed-command org-speed-commands-user)
18714 (princ "\n")
18715 (princ "Built-in Speed commands\n=======================\n")
18716 (mapc 'org-print-speed-command org-speed-commands-default))
18717 (with-current-buffer "*Help*"
18718 (setq truncate-lines t))))
18720 (defun org-speed-move-safe (cmd)
18721 "Execute CMD, but make sure that the cursor always ends up in a headline.
18722 If not, return to the original position and throw an error."
18723 (interactive)
18724 (let ((pos (point)))
18725 (call-interactively cmd)
18726 (unless (and (bolp) (org-at-heading-p))
18727 (goto-char pos)
18728 (error "Boundary reached while executing %s" cmd))))
18730 (defvar org-self-insert-command-undo-counter 0)
18732 (defvar org-table-auto-blank-field) ; defined in org-table.el
18733 (defvar org-speed-command nil)
18735 (define-obsolete-function-alias
18736 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18738 (defun org-speed-command-activate (keys)
18739 "Hook for activating single-letter speed commands.
18740 `org-speed-commands-default' specifies a minimal command set.
18741 Use `org-speed-commands-user' for further customization."
18742 (when (or (and (bolp) (looking-at org-outline-regexp))
18743 (and (functionp org-use-speed-commands)
18744 (funcall org-use-speed-commands)))
18745 (cdr (assoc keys (append org-speed-commands-user
18746 org-speed-commands-default)))))
18748 (define-obsolete-function-alias
18749 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18751 (defun org-babel-speed-command-activate (keys)
18752 "Hook for activating single-letter code block commands."
18753 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18754 (cdr (assoc keys org-babel-key-bindings))))
18756 (defcustom org-speed-command-hook
18757 '(org-speed-command-default-hook org-babel-speed-command-hook)
18758 "Hook for activating speed commands at strategic locations.
18759 Hook functions are called in sequence until a valid handler is
18760 found.
18762 Each hook takes a single argument, a user-pressed command key
18763 which is also a `self-insert-command' from the global map.
18765 Within the hook, examine the cursor position and the command key
18766 and return nil or a valid handler as appropriate. Handler could
18767 be one of an interactive command, a function, or a form.
18769 Set `org-use-speed-commands' to non-nil value to enable this
18770 hook. The default setting is `org-speed-command-activate'."
18771 :group 'org-structure
18772 :version "24.1"
18773 :type 'hook)
18775 (defun org-self-insert-command (N)
18776 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18777 If the cursor is in a table looking at whitespace, the whitespace is
18778 overwritten, and the table is not marked as requiring realignment."
18779 (interactive "p")
18780 (org-check-before-invisible-edit 'insert)
18781 (cond
18782 ((and org-use-speed-commands
18783 (setq org-speed-command
18784 (run-hook-with-args-until-success
18785 'org-speed-command-hook (this-command-keys))))
18786 (cond
18787 ((commandp org-speed-command)
18788 (setq this-command org-speed-command)
18789 (call-interactively org-speed-command))
18790 ((functionp org-speed-command)
18791 (funcall org-speed-command))
18792 ((and org-speed-command (listp org-speed-command))
18793 (eval org-speed-command))
18794 (t (let (org-use-speed-commands)
18795 (call-interactively 'org-self-insert-command)))))
18796 ((and
18797 (org-table-p)
18798 (progn
18799 ;; check if we blank the field, and if that triggers align
18800 (and (featurep 'org-table) org-table-auto-blank-field
18801 (member last-command
18802 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18803 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18804 ;; got extra space, this field does not determine column width
18805 (let (org-table-may-need-update) (org-table-blank-field))
18806 ;; no extra space, this field may determine column width
18807 (org-table-blank-field)))
18809 (eq N 1)
18810 (looking-at "[^|\n]* |"))
18811 (let (org-table-may-need-update)
18812 (goto-char (1- (match-end 0)))
18813 (backward-delete-char 1)
18814 (goto-char (match-beginning 0))
18815 (self-insert-command N)))
18817 (setq org-table-may-need-update t)
18818 (self-insert-command N)
18819 (org-fix-tags-on-the-fly)
18820 (if org-self-insert-cluster-for-undo
18821 (if (not (eq last-command 'org-self-insert-command))
18822 (setq org-self-insert-command-undo-counter 1)
18823 (if (>= org-self-insert-command-undo-counter 20)
18824 (setq org-self-insert-command-undo-counter 1)
18825 (and (> org-self-insert-command-undo-counter 0)
18826 buffer-undo-list (listp buffer-undo-list)
18827 (not (cadr buffer-undo-list)) ; remove nil entry
18828 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18829 (setq org-self-insert-command-undo-counter
18830 (1+ org-self-insert-command-undo-counter))))))))
18832 (defun org-check-before-invisible-edit (kind)
18833 "Check is editing if kind KIND would be dangerous with invisible text around.
18834 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18835 ;; First, try to get out of here as quickly as possible, to reduce overhead
18836 (if (and org-catch-invisible-edits
18837 (or (not (boundp 'visible-mode)) (not visible-mode))
18838 (or (get-char-property (point) 'invisible)
18839 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18840 ;; OK, we need to take a closer look
18841 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18842 (invisible-before-point (if (bobp) nil (get-char-property
18843 (1- (point)) 'invisible)))
18844 (border-and-ok-direction
18846 ;; Check if we are acting predictably before invisible text
18847 (and invisible-at-point (not invisible-before-point)
18848 (memq kind '(insert delete-backward)))
18849 ;; Check if we are acting predictably after invisible text
18850 ;; This works not well, and I have turned it off. It seems
18851 ;; better to always show and stop after invisible text.
18852 ;; (and (not invisible-at-point) invisible-before-point
18853 ;; (memq kind '(insert delete)))
18855 (when (or (memq invisible-at-point '(outline org-hide-block t))
18856 (memq invisible-before-point '(outline org-hide-block t)))
18857 (if (eq org-catch-invisible-edits 'error)
18858 (error "Editing in invisible areas is prohibited - make visible first"))
18859 (if (and org-custom-properties-overlays
18860 (y-or-n-p "Display invisible properties in this buffer? "))
18861 (org-toggle-custom-properties-visibility)
18862 ;; Make the area visible
18863 (save-excursion
18864 (if invisible-before-point
18865 (goto-char (previous-single-char-property-change
18866 (point) 'invisible)))
18867 (org-cycle))
18868 (cond
18869 ((eq org-catch-invisible-edits 'show)
18870 ;; That's it, we do the edit after showing
18871 (message
18872 "Unfolding invisible region around point before editing")
18873 (sit-for 1))
18874 ((and (eq org-catch-invisible-edits 'smart)
18875 border-and-ok-direction)
18876 (message "Unfolding invisible region around point before editing"))
18878 ;; Don't do the edit, make the user repeat it in full visibility
18879 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18881 (defun org-fix-tags-on-the-fly ()
18882 (when (and (equal (char-after (point-at-bol)) ?*)
18883 (org-at-heading-p))
18884 (org-align-tags-here org-tags-column)))
18886 (defun org-delete-backward-char (N)
18887 "Like `delete-backward-char', insert whitespace at field end in tables.
18888 When deleting backwards, in tables this function will insert whitespace in
18889 front of the next \"|\" separator, to keep the table aligned. The table will
18890 still be marked for re-alignment if the field did fill the entire column,
18891 because, in this case the deletion might narrow the column."
18892 (interactive "p")
18893 (save-match-data
18894 (org-check-before-invisible-edit 'delete-backward)
18895 (if (and (org-table-p)
18896 (eq N 1)
18897 (string-match "|" (buffer-substring (point-at-bol) (point)))
18898 (looking-at ".*?|"))
18899 (let ((pos (point))
18900 (noalign (looking-at "[^|\n\r]* |"))
18901 (c org-table-may-need-update))
18902 (backward-delete-char N)
18903 (if (not overwrite-mode)
18904 (progn
18905 (skip-chars-forward "^|")
18906 (insert " ")
18907 (goto-char (1- pos))))
18908 ;; noalign: if there were two spaces at the end, this field
18909 ;; does not determine the width of the column.
18910 (if noalign (setq org-table-may-need-update c)))
18911 (backward-delete-char N)
18912 (org-fix-tags-on-the-fly))))
18914 (defun org-delete-char (N)
18915 "Like `delete-char', but insert whitespace at field end in tables.
18916 When deleting characters, in tables this function will insert whitespace in
18917 front of the next \"|\" separator, to keep the table aligned. The table will
18918 still be marked for re-alignment if the field did fill the entire column,
18919 because, in this case the deletion might narrow the column."
18920 (interactive "p")
18921 (save-match-data
18922 (org-check-before-invisible-edit 'delete)
18923 (if (and (org-table-p)
18924 (not (bolp))
18925 (not (= (char-after) ?|))
18926 (eq N 1))
18927 (if (looking-at ".*?|")
18928 (let ((pos (point))
18929 (noalign (looking-at "[^|\n\r]* |"))
18930 (c org-table-may-need-update))
18931 (replace-match (concat
18932 (substring (match-string 0) 1 -1)
18933 " |"))
18934 (goto-char pos)
18935 ;; noalign: if there were two spaces at the end, this field
18936 ;; does not determine the width of the column.
18937 (if noalign (setq org-table-may-need-update c)))
18938 (delete-char N))
18939 (delete-char N)
18940 (org-fix-tags-on-the-fly))))
18942 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18943 (put 'org-self-insert-command 'delete-selection t)
18944 (put 'orgtbl-self-insert-command 'delete-selection t)
18945 (put 'org-delete-char 'delete-selection 'supersede)
18946 (put 'org-delete-backward-char 'delete-selection 'supersede)
18947 (put 'org-yank 'delete-selection 'yank)
18949 ;; Make `flyspell-mode' delay after some commands
18950 (put 'org-self-insert-command 'flyspell-delayed t)
18951 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18952 (put 'org-delete-char 'flyspell-delayed t)
18953 (put 'org-delete-backward-char 'flyspell-delayed t)
18955 ;; Make pabbrev-mode expand after org-mode commands
18956 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18957 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18959 ;; How to do this: Measure non-white length of current string
18960 ;; If equal to column width, we should realign.
18962 (defun org-remap (map &rest commands)
18963 "In MAP, remap the functions given in COMMANDS.
18964 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18965 (let (new old)
18966 (while commands
18967 (setq old (pop commands) new (pop commands))
18968 (if (fboundp 'command-remapping)
18969 (org-defkey map (vector 'remap old) new)
18970 (substitute-key-definition old new map global-map)))))
18972 (when (eq org-enable-table-editor 'optimized)
18973 ;; If the user wants maximum table support, we need to hijack
18974 ;; some standard editing functions
18975 (org-remap org-mode-map
18976 'self-insert-command 'org-self-insert-command
18977 'delete-char 'org-delete-char
18978 'delete-backward-char 'org-delete-backward-char)
18979 (org-defkey org-mode-map "|" 'org-force-self-insert))
18981 (defvar org-ctrl-c-ctrl-c-hook nil
18982 "Hook for functions attaching themselves to `C-c C-c'.
18984 This can be used to add additional functionality to the C-c C-c
18985 key which executes context-dependent commands. This hook is run
18986 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18987 run after the last test.
18989 Each function will be called with no arguments. The function
18990 must check if the context is appropriate for it to act. If yes,
18991 it should do its thing and then return a non-nil value. If the
18992 context is wrong, just do nothing and return nil.")
18994 (defvar org-ctrl-c-ctrl-c-final-hook nil
18995 "Hook for functions attaching themselves to `C-c C-c'.
18997 This can be used to add additional functionality to the C-c C-c
18998 key which executes context-dependent commands. This hook is run
18999 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19000 before the first test.
19002 Each function will be called with no arguments. The function
19003 must check if the context is appropriate for it to act. If yes,
19004 it should do its thing and then return a non-nil value. If the
19005 context is wrong, just do nothing and return nil.")
19007 (defvar org-tab-first-hook nil
19008 "Hook for functions to attach themselves to TAB.
19009 See `org-ctrl-c-ctrl-c-hook' for more information.
19010 This hook runs as the first action when TAB is pressed, even before
19011 `org-cycle' messes around with the `outline-regexp' to cater for
19012 inline tasks and plain list item folding.
19013 If any function in this hook returns t, any other actions that
19014 would have been caused by TAB (such as table field motion or visibility
19015 cycling) will not occur.")
19017 (defvar org-tab-after-check-for-table-hook nil
19018 "Hook for functions to attach themselves to TAB.
19019 See `org-ctrl-c-ctrl-c-hook' for more information.
19020 This hook runs after it has been established that the cursor is not in a
19021 table, but before checking if the cursor is in a headline or if global cycling
19022 should be done.
19023 If any function in this hook returns t, not other actions like visibility
19024 cycling will be done.")
19026 (defvar org-tab-after-check-for-cycling-hook nil
19027 "Hook for functions to attach themselves to TAB.
19028 See `org-ctrl-c-ctrl-c-hook' for more information.
19029 This hook runs after it has been established that not table field motion and
19030 not visibility should be done because of current context. This is probably
19031 the place where a package like yasnippets can hook in.")
19033 (defvar org-tab-before-tab-emulation-hook nil
19034 "Hook for functions to attach themselves to TAB.
19035 See `org-ctrl-c-ctrl-c-hook' for more information.
19036 This hook runs after every other options for TAB have been exhausted, but
19037 before indentation and \t insertion takes place.")
19039 (defvar org-metaleft-hook nil
19040 "Hook for functions attaching themselves to `M-left'.
19041 See `org-ctrl-c-ctrl-c-hook' for more information.")
19042 (defvar org-metaright-hook nil
19043 "Hook for functions attaching themselves to `M-right'.
19044 See `org-ctrl-c-ctrl-c-hook' for more information.")
19045 (defvar org-metaup-hook nil
19046 "Hook for functions attaching themselves to `M-up'.
19047 See `org-ctrl-c-ctrl-c-hook' for more information.")
19048 (defvar org-metadown-hook nil
19049 "Hook for functions attaching themselves to `M-down'.
19050 See `org-ctrl-c-ctrl-c-hook' for more information.")
19051 (defvar org-shiftmetaleft-hook nil
19052 "Hook for functions attaching themselves to `M-S-left'.
19053 See `org-ctrl-c-ctrl-c-hook' for more information.")
19054 (defvar org-shiftmetaright-hook nil
19055 "Hook for functions attaching themselves to `M-S-right'.
19056 See `org-ctrl-c-ctrl-c-hook' for more information.")
19057 (defvar org-shiftmetaup-hook nil
19058 "Hook for functions attaching themselves to `M-S-up'.
19059 See `org-ctrl-c-ctrl-c-hook' for more information.")
19060 (defvar org-shiftmetadown-hook nil
19061 "Hook for functions attaching themselves to `M-S-down'.
19062 See `org-ctrl-c-ctrl-c-hook' for more information.")
19063 (defvar org-metareturn-hook nil
19064 "Hook for functions attaching themselves to `M-RET'.
19065 See `org-ctrl-c-ctrl-c-hook' for more information.")
19066 (defvar org-shiftup-hook nil
19067 "Hook for functions attaching themselves to `S-up'.
19068 See `org-ctrl-c-ctrl-c-hook' for more information.")
19069 (defvar org-shiftup-final-hook nil
19070 "Hook for functions attaching themselves to `S-up'.
19071 This one runs after all other options except shift-select have been excluded.
19072 See `org-ctrl-c-ctrl-c-hook' for more information.")
19073 (defvar org-shiftdown-hook nil
19074 "Hook for functions attaching themselves to `S-down'.
19075 See `org-ctrl-c-ctrl-c-hook' for more information.")
19076 (defvar org-shiftdown-final-hook nil
19077 "Hook for functions attaching themselves to `S-down'.
19078 This one runs after all other options except shift-select have been excluded.
19079 See `org-ctrl-c-ctrl-c-hook' for more information.")
19080 (defvar org-shiftleft-hook nil
19081 "Hook for functions attaching themselves to `S-left'.
19082 See `org-ctrl-c-ctrl-c-hook' for more information.")
19083 (defvar org-shiftleft-final-hook nil
19084 "Hook for functions attaching themselves to `S-left'.
19085 This one runs after all other options except shift-select have been excluded.
19086 See `org-ctrl-c-ctrl-c-hook' for more information.")
19087 (defvar org-shiftright-hook nil
19088 "Hook for functions attaching themselves to `S-right'.
19089 See `org-ctrl-c-ctrl-c-hook' for more information.")
19090 (defvar org-shiftright-final-hook nil
19091 "Hook for functions attaching themselves to `S-right'.
19092 This one runs after all other options except shift-select have been excluded.
19093 See `org-ctrl-c-ctrl-c-hook' for more information.")
19095 (defun org-modifier-cursor-error ()
19096 "Throw an error, a modified cursor command was applied in wrong context."
19097 (error "This command is active in special context like tables, headlines or items"))
19099 (defun org-shiftselect-error ()
19100 "Throw an error because Shift-Cursor command was applied in wrong context."
19101 (if (and (boundp 'shift-select-mode) shift-select-mode)
19102 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19103 (error "This command works only in special context like headlines or timestamps")))
19105 (defun org-call-for-shift-select (cmd)
19106 (let ((this-command-keys-shift-translated t))
19107 (call-interactively cmd)))
19109 (defun org-shifttab (&optional arg)
19110 "Global visibility cycling or move to previous table field.
19111 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19112 on context.
19113 See the individual commands for more information."
19114 (interactive "P")
19115 (cond
19116 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19117 ((integerp arg)
19118 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19119 (message "Content view to level: %d" arg)
19120 (org-content (prefix-numeric-value arg2))
19121 (setq org-cycle-global-status 'overview)))
19122 (t (call-interactively 'org-global-cycle))))
19124 (defun org-shiftmetaleft ()
19125 "Promote subtree or delete table column.
19126 Calls `org-promote-subtree', `org-outdent-item-tree', or
19127 `org-table-delete-column', depending on context. See the
19128 individual commands for more information."
19129 (interactive)
19130 (cond
19131 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19132 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19133 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19134 ((if (not (org-region-active-p)) (org-at-item-p)
19135 (save-excursion (goto-char (region-beginning))
19136 (org-at-item-p)))
19137 (call-interactively 'org-outdent-item-tree))
19138 (t (org-modifier-cursor-error))))
19140 (defun org-shiftmetaright ()
19141 "Demote subtree or insert table column.
19142 Calls `org-demote-subtree', `org-indent-item-tree', or
19143 `org-table-insert-column', depending on context. See the
19144 individual commands for more information."
19145 (interactive)
19146 (cond
19147 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19148 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19149 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19150 ((if (not (org-region-active-p)) (org-at-item-p)
19151 (save-excursion (goto-char (region-beginning))
19152 (org-at-item-p)))
19153 (call-interactively 'org-indent-item-tree))
19154 (t (org-modifier-cursor-error))))
19156 (defun org-shiftmetaup (&optional arg)
19157 "Move subtree up or kill table row.
19158 Calls `org-move-subtree-up' or `org-table-kill-row' or
19159 `org-move-item-up' or `org-timestamp-up', depending on context.
19160 See the individual commands for more information."
19161 (interactive "P")
19162 (cond
19163 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19164 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19165 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19166 ((org-at-item-p) (call-interactively 'org-move-item-up))
19167 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19168 (call-interactively 'org-timestamp-up)))
19169 (t (org-modifier-cursor-error))))
19171 (defun org-shiftmetadown (&optional arg)
19172 "Move subtree down or insert table row.
19173 Calls `org-move-subtree-down' or `org-table-insert-row' or
19174 `org-move-item-down' or `org-timestamp-up', depending on context.
19175 See the individual commands for more information."
19176 (interactive "P")
19177 (cond
19178 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19179 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19180 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19181 ((org-at-item-p) (call-interactively 'org-move-item-down))
19182 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19183 (call-interactively 'org-timestamp-down)))
19184 (t (org-modifier-cursor-error))))
19186 (defsubst org-hidden-tree-error ()
19187 (error
19188 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19190 (defun org-metaleft (&optional arg)
19191 "Promote heading or move table column to left.
19192 Calls `org-do-promote' or `org-table-move-column', depending on context.
19193 With no specific context, calls the Emacs default `backward-word'.
19194 See the individual commands for more information."
19195 (interactive "P")
19196 (cond
19197 ((run-hook-with-args-until-success 'org-metaleft-hook))
19198 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19199 ((org-with-limited-levels
19200 (or (org-at-heading-p)
19201 (and (org-region-active-p)
19202 (save-excursion
19203 (goto-char (region-beginning))
19204 (org-at-heading-p)))))
19205 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19206 (call-interactively 'org-do-promote))
19207 ;; At an inline task.
19208 ((org-at-heading-p)
19209 (call-interactively 'org-inlinetask-promote))
19210 ((or (org-at-item-p)
19211 (and (org-region-active-p)
19212 (save-excursion
19213 (goto-char (region-beginning))
19214 (org-at-item-p))))
19215 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19216 (call-interactively 'org-outdent-item))
19217 (t (call-interactively 'backward-word))))
19219 (defun org-metaright (&optional arg)
19220 "Demote a subtree, a list item or move table column to right.
19221 In front of a drawer or a block keyword, indent it correctly.
19222 With no specific context, calls the Emacs default `forward-word'.
19223 See the individual commands for more information."
19224 (interactive "P")
19225 (cond
19226 ((run-hook-with-args-until-success 'org-metaright-hook))
19227 ((org-at-table-p) (call-interactively 'org-table-move-column))
19228 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19229 ((org-at-block-p) (call-interactively 'org-indent-block))
19230 ((org-with-limited-levels
19231 (or (org-at-heading-p)
19232 (and (org-region-active-p)
19233 (save-excursion
19234 (goto-char (region-beginning))
19235 (org-at-heading-p)))))
19236 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19237 (call-interactively 'org-do-demote))
19238 ;; At an inline task.
19239 ((org-at-heading-p)
19240 (call-interactively 'org-inlinetask-demote))
19241 ((or (org-at-item-p)
19242 (and (org-region-active-p)
19243 (save-excursion
19244 (goto-char (region-beginning))
19245 (org-at-item-p))))
19246 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19247 (call-interactively 'org-indent-item))
19248 (t (call-interactively 'forward-word))))
19250 (defun org-check-for-hidden (what)
19251 "Check if there are hidden headlines/items in the current visual line.
19252 WHAT can be either `headlines' or `items'. If the current line is
19253 an outline or item heading and it has a folded subtree below it,
19254 this function returns t, nil otherwise."
19255 (let ((re (cond
19256 ((eq what 'headlines) org-outline-regexp-bol)
19257 ((eq what 'items) (org-item-beginning-re))
19258 (t (error "This should not happen"))))
19259 beg end)
19260 (save-excursion
19261 (catch 'exit
19262 (unless (org-region-active-p)
19263 (setq beg (point-at-bol))
19264 (beginning-of-line 2)
19265 (while (and (not (eobp)) ;; this is like `next-line'
19266 (get-char-property (1- (point)) 'invisible))
19267 (beginning-of-line 2))
19268 (setq end (point))
19269 (goto-char beg)
19270 (goto-char (point-at-eol))
19271 (setq end (max end (point)))
19272 (while (re-search-forward re end t)
19273 (if (get-char-property (match-beginning 0) 'invisible)
19274 (throw 'exit t))))
19275 nil))))
19277 (defun org-metaup (&optional arg)
19278 "Move subtree up or move table row up.
19279 Calls `org-move-subtree-up' or `org-table-move-row' or
19280 `org-move-item-up', depending on context. See the individual commands
19281 for more information."
19282 (interactive "P")
19283 (cond
19284 ((run-hook-with-args-until-success 'org-metaup-hook))
19285 ((org-region-active-p)
19286 (let* ((a (min (region-beginning) (region-end)))
19287 (b (1- (max (region-beginning) (region-end))))
19288 (c (save-excursion (goto-char a)
19289 (move-beginning-of-line 0)))
19290 (d (save-excursion (goto-char a)
19291 (move-end-of-line 0) (point))))
19292 (transpose-regions a b c d)
19293 (goto-char c)))
19294 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19295 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19296 ((org-at-item-p) (call-interactively 'org-move-item-up))
19297 (t (org-drag-element-backward))))
19299 (defun org-metadown (&optional arg)
19300 "Move subtree down or move table row down.
19301 Calls `org-move-subtree-down' or `org-table-move-row' or
19302 `org-move-item-down', depending on context. See the individual
19303 commands for more information."
19304 (interactive "P")
19305 (cond
19306 ((run-hook-with-args-until-success 'org-metadown-hook))
19307 ((org-region-active-p)
19308 (let* ((a (min (region-beginning) (region-end)))
19309 (b (max (region-beginning) (region-end)))
19310 (c (save-excursion (goto-char b)
19311 (move-beginning-of-line 1)))
19312 (d (save-excursion (goto-char b)
19313 (move-end-of-line 1) (1+ (point)))))
19314 (transpose-regions a b c d)
19315 (goto-char d)))
19316 ((org-at-table-p) (call-interactively 'org-table-move-row))
19317 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19318 ((org-at-item-p) (call-interactively 'org-move-item-down))
19319 (t (org-drag-element-forward))))
19321 (defun org-shiftup (&optional arg)
19322 "Increase item in timestamp or increase priority of current headline.
19323 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19324 depending on context. See the individual commands for more information."
19325 (interactive "P")
19326 (cond
19327 ((run-hook-with-args-until-success 'org-shiftup-hook))
19328 ((and org-support-shift-select (org-region-active-p))
19329 (org-call-for-shift-select 'previous-line))
19330 ((org-at-timestamp-p t)
19331 (call-interactively (if org-edit-timestamp-down-means-later
19332 'org-timestamp-down 'org-timestamp-up)))
19333 ((and (not (eq org-support-shift-select 'always))
19334 org-enable-priority-commands
19335 (org-at-heading-p))
19336 (call-interactively 'org-priority-up))
19337 ((and (not org-support-shift-select) (org-at-item-p))
19338 (call-interactively 'org-previous-item))
19339 ((org-clocktable-try-shift 'up arg))
19340 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19341 (org-support-shift-select
19342 (org-call-for-shift-select 'previous-line))
19343 (t (org-shiftselect-error))))
19345 (defun org-shiftdown (&optional arg)
19346 "Decrease item in timestamp or decrease priority of current headline.
19347 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19348 depending on context. See the individual commands for more information."
19349 (interactive "P")
19350 (cond
19351 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19352 ((and org-support-shift-select (org-region-active-p))
19353 (org-call-for-shift-select 'next-line))
19354 ((org-at-timestamp-p t)
19355 (call-interactively (if org-edit-timestamp-down-means-later
19356 'org-timestamp-up 'org-timestamp-down)))
19357 ((and (not (eq org-support-shift-select 'always))
19358 org-enable-priority-commands
19359 (org-at-heading-p))
19360 (call-interactively 'org-priority-down))
19361 ((and (not org-support-shift-select) (org-at-item-p))
19362 (call-interactively 'org-next-item))
19363 ((org-clocktable-try-shift 'down arg))
19364 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19365 (org-support-shift-select
19366 (org-call-for-shift-select 'next-line))
19367 (t (org-shiftselect-error))))
19369 (defun org-shiftright (&optional arg)
19370 "Cycle the thing at point or in the current line, depending on context.
19371 Depending on context, this does one of the following:
19373 - switch a timestamp at point one day into the future
19374 - on a headline, switch to the next TODO keyword.
19375 - on an item, switch entire list to the next bullet type
19376 - on a property line, switch to the next allowed value
19377 - on a clocktable definition line, move time block into the future"
19378 (interactive "P")
19379 (cond
19380 ((run-hook-with-args-until-success 'org-shiftright-hook))
19381 ((and org-support-shift-select (org-region-active-p))
19382 (org-call-for-shift-select 'forward-char))
19383 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19384 ((and (not (eq org-support-shift-select 'always))
19385 (org-at-heading-p))
19386 (let ((org-inhibit-logging
19387 (not org-treat-S-cursor-todo-selection-as-state-change))
19388 (org-inhibit-blocking
19389 (not org-treat-S-cursor-todo-selection-as-state-change)))
19390 (org-call-with-arg 'org-todo 'right)))
19391 ((or (and org-support-shift-select
19392 (not (eq org-support-shift-select 'always))
19393 (org-at-item-bullet-p))
19394 (and (not org-support-shift-select) (org-at-item-p)))
19395 (org-call-with-arg 'org-cycle-list-bullet nil))
19396 ((and (not (eq org-support-shift-select 'always))
19397 (org-at-property-p))
19398 (call-interactively 'org-property-next-allowed-value))
19399 ((org-clocktable-try-shift 'right arg))
19400 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19401 (org-support-shift-select
19402 (org-call-for-shift-select 'forward-char))
19403 (t (org-shiftselect-error))))
19405 (defun org-shiftleft (&optional arg)
19406 "Cycle the thing at point or in the current line, depending on context.
19407 Depending on context, this does one of the following:
19409 - switch a timestamp at point one day into the past
19410 - on a headline, switch to the previous TODO keyword.
19411 - on an item, switch entire list to the previous bullet type
19412 - on a property line, switch to the previous allowed value
19413 - on a clocktable definition line, move time block into the past"
19414 (interactive "P")
19415 (cond
19416 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19417 ((and org-support-shift-select (org-region-active-p))
19418 (org-call-for-shift-select 'backward-char))
19419 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19420 ((and (not (eq org-support-shift-select 'always))
19421 (org-at-heading-p))
19422 (let ((org-inhibit-logging
19423 (not org-treat-S-cursor-todo-selection-as-state-change))
19424 (org-inhibit-blocking
19425 (not org-treat-S-cursor-todo-selection-as-state-change)))
19426 (org-call-with-arg 'org-todo 'left)))
19427 ((or (and org-support-shift-select
19428 (not (eq org-support-shift-select 'always))
19429 (org-at-item-bullet-p))
19430 (and (not org-support-shift-select) (org-at-item-p)))
19431 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19432 ((and (not (eq org-support-shift-select 'always))
19433 (org-at-property-p))
19434 (call-interactively 'org-property-previous-allowed-value))
19435 ((org-clocktable-try-shift 'left arg))
19436 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19437 (org-support-shift-select
19438 (org-call-for-shift-select 'backward-char))
19439 (t (org-shiftselect-error))))
19441 (defun org-shiftcontrolright ()
19442 "Switch to next TODO set."
19443 (interactive)
19444 (cond
19445 ((and org-support-shift-select (org-region-active-p))
19446 (org-call-for-shift-select 'forward-word))
19447 ((and (not (eq org-support-shift-select 'always))
19448 (org-at-heading-p))
19449 (org-call-with-arg 'org-todo 'nextset))
19450 (org-support-shift-select
19451 (org-call-for-shift-select 'forward-word))
19452 (t (org-shiftselect-error))))
19454 (defun org-shiftcontrolleft ()
19455 "Switch to previous TODO set."
19456 (interactive)
19457 (cond
19458 ((and org-support-shift-select (org-region-active-p))
19459 (org-call-for-shift-select 'backward-word))
19460 ((and (not (eq org-support-shift-select 'always))
19461 (org-at-heading-p))
19462 (org-call-with-arg 'org-todo 'previousset))
19463 (org-support-shift-select
19464 (org-call-for-shift-select 'backward-word))
19465 (t (org-shiftselect-error))))
19467 (defun org-shiftcontrolup (&optional n)
19468 "Change timestamps synchronously up in CLOCK log lines.
19469 Optional argument N tells to change by that many units."
19470 (interactive "P")
19471 (cond ((and (not org-support-shift-select)
19472 (org-at-clock-log-p)
19473 (org-at-timestamp-p t))
19474 (org-clock-timestamps-up n))
19475 (t (org-shiftselect-error))))
19477 (defun org-shiftcontroldown (&optional n)
19478 "Change timestamps synchronously down in CLOCK log lines.
19479 Optional argument N tells to change by that many units."
19480 (interactive "P")
19481 (cond ((and (not org-support-shift-select)
19482 (org-at-clock-log-p)
19483 (org-at-timestamp-p t))
19484 (org-clock-timestamps-down n))
19485 (t (org-shiftselect-error))))
19487 (defun org-ctrl-c-ret ()
19488 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19489 (interactive)
19490 (cond
19491 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19492 (t (call-interactively 'org-insert-heading))))
19494 (defun org-find-visible ()
19495 (let ((s (point)))
19496 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19497 (get-char-property s 'invisible)))
19499 (defun org-find-invisible ()
19500 (let ((s (point)))
19501 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19502 (not (get-char-property s 'invisible))))
19505 (defun org-copy-visible (beg end)
19506 "Copy the visible parts of the region."
19507 (interactive "r")
19508 (let (snippets s)
19509 (save-excursion
19510 (save-restriction
19511 (narrow-to-region beg end)
19512 (setq s (goto-char (point-min)))
19513 (while (not (= (point) (point-max)))
19514 (goto-char (org-find-invisible))
19515 (push (buffer-substring s (point)) snippets)
19516 (setq s (goto-char (org-find-visible))))))
19517 (kill-new (apply 'concat (nreverse snippets)))))
19519 (defun org-copy-special ()
19520 "Copy region in table or copy current subtree.
19521 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19522 See the individual commands for more information."
19523 (interactive)
19524 (call-interactively
19525 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19527 (defun org-cut-special ()
19528 "Cut region in table or cut current subtree.
19529 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19530 See the individual commands for more information."
19531 (interactive)
19532 (call-interactively
19533 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19535 (defun org-paste-special (arg)
19536 "Paste rectangular region into table, or past subtree relative to level.
19537 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19538 See the individual commands for more information."
19539 (interactive "P")
19540 (if (org-at-table-p)
19541 (org-table-paste-rectangle)
19542 (org-paste-subtree arg)))
19544 (defsubst org-in-fixed-width-region-p ()
19545 "Is point in a fixed-width region?"
19546 (save-match-data
19547 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19549 (defun org-edit-special (&optional arg)
19550 "Call a special editor for the element at point.
19551 When at a table, call the formula editor with `org-table-edit-formulas'.
19552 When in a source code block, call `org-edit-src-code'.
19553 When in a fixed-width region, call `org-edit-fixed-width-region'.
19554 When at an #+INCLUDE keyword, visit the included file.
19555 On a link, call `ffap' to visit the link at point.
19556 Otherwise, return a user error."
19557 (interactive)
19558 (let ((element (org-element-at-point)))
19559 (assert (not buffer-read-only) nil
19560 "Buffer is read-only: %s" (buffer-name))
19561 (case (org-element-type element)
19562 (src-block
19563 (if (not arg) (org-edit-src-code)
19564 (let* ((info (org-babel-get-src-block-info))
19565 (lang (nth 0 info))
19566 (params (nth 2 info))
19567 (session (cdr (assq :session params))))
19568 (if (not session) (org-edit-src-code)
19569 ;; At a src-block with a session and function called with
19570 ;; an ARG: switch to the buffer related to the inferior
19571 ;; process.
19572 (funcall (intern (concat "org-babel-prep-session:" lang))
19573 session params)))))
19574 (keyword
19575 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19576 (find-file
19577 (org-remove-double-quotes
19578 (car (org-split-string (org-element-property :value element)))))
19579 (user-error "No special environment to edit here")))
19580 (table
19581 (if (eq (org-element-property :type element) 'table.el)
19582 (org-edit-src-code)
19583 (call-interactively 'org-table-edit-formulas)))
19584 ;; Only Org tables contain `table-row' type elements.
19585 (table-row (call-interactively 'org-table-edit-formulas))
19586 ((example-block export-block) (org-edit-src-code))
19587 (fixed-width (org-edit-fixed-width-region))
19588 (otherwise
19589 ;; No notable element at point. Though, we may be at a link,
19590 ;; which is an object. Thus, scan deeper.
19591 (if (eq (org-element-type (org-element-context element)) 'link)
19592 (call-interactively 'ffap)
19593 (user-error "No special environment to edit here"))))))
19595 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19596 (defun org-ctrl-c-ctrl-c (&optional arg)
19597 "Set tags in headline, or update according to changed information at point.
19599 This command does many different things, depending on context:
19601 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19602 this is what we do.
19604 - If the cursor is on a statistics cookie, update it.
19606 - If the cursor is in a headline, prompt for tags and insert them
19607 into the current line, aligned to `org-tags-column'. When called
19608 with prefix arg, realign all tags in the current buffer.
19610 - If the cursor is in one of the special #+KEYWORD lines, this
19611 triggers scanning the buffer for these lines and updating the
19612 information.
19614 - If the cursor is inside a table, realign the table. This command
19615 works even if the automatic table editor has been turned off.
19617 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19618 the entire table.
19620 - If the cursor is at a footnote reference or definition, jump to
19621 the corresponding definition or references, respectively.
19623 - If the cursor is a the beginning of a dynamic block, update it.
19625 - If the current buffer is a capture buffer, close note and file it.
19627 - If the cursor is on a <<<target>>>, update radio targets and
19628 corresponding links in this buffer.
19630 - If the cursor is on a numbered item in a plain list, renumber the
19631 ordered list.
19633 - If the cursor is on a checkbox, toggle it.
19635 - If the cursor is on a code block, evaluate it. The variable
19636 `org-confirm-babel-evaluate' can be used to control prompting
19637 before code block evaluation, by default every code block
19638 evaluation requires confirmation. Code block evaluation can be
19639 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19640 (interactive "P")
19641 (cond
19642 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19643 org-occur-highlights
19644 org-latex-fragment-image-overlays)
19645 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19646 (org-remove-occur-highlights)
19647 (org-remove-latex-fragment-image-overlays)
19648 (message "Temporary highlights/overlays removed from current buffer"))
19649 ((and (local-variable-p 'org-finish-function (current-buffer))
19650 (fboundp org-finish-function))
19651 (funcall org-finish-function))
19652 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19654 (let* ((context (org-element-context)) (type (org-element-type context)))
19655 ;; Test if point is within blanks at the end of an element.
19656 (if (save-excursion
19657 (or (not context)
19658 (beginning-of-line)
19659 (and (looking-at "[ \t]*$")
19660 (skip-chars-forward " \r\t\n")
19661 (>= (point) (org-element-property :end context)))))
19662 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19663 (user-error "C-c C-c can do nothing useful at this location"))
19664 ;; For convenience: at the first line of a paragraph on the
19665 ;; same line as an item, apply function on that item instead.
19666 (when (eq type 'paragraph)
19667 (let ((parent (org-element-property :parent context)))
19668 (when (and (eq (org-element-type parent) 'item)
19669 (= (point-at-bol) (org-element-property :begin parent)))
19670 (setq context parent type 'item))))
19671 ;; Act according to type of element or object at point.
19672 (case type
19673 (clock (org-clock-update-time-maybe))
19674 (dynamic-block
19675 (save-excursion
19676 (goto-char (org-element-property :post-affiliated context))
19677 (org-update-dblock)))
19678 (footnote-definition
19679 (goto-char (org-element-property :post-affiliated context))
19680 (call-interactively 'org-footnote-action))
19681 (footnote-reference (call-interactively 'org-footnote-action))
19682 ((headline inlinetask)
19683 (save-excursion (goto-char (org-element-property :begin context))
19684 (call-interactively 'org-set-tags)))
19685 (item
19686 ;; At an item: a double C-u set checkbox to "[-]"
19687 ;; unconditionally, whereas a single one will toggle its
19688 ;; presence. Without an universal argument, if the item
19689 ;; has a checkbox, toggle it. Otherwise repair the list.
19690 (let* ((box (org-element-property :checkbox context))
19691 (struct (org-element-property :structure context))
19692 (old-struct (copy-tree struct))
19693 (parents (org-list-parents-alist struct))
19694 (prevs (org-list-prevs-alist struct))
19695 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19696 (org-list-set-checkbox
19697 (org-element-property :begin context) struct
19698 (cond ((equal arg '(16)) "[-]")
19699 ((and (not box) (equal arg '(4))) "[ ]")
19700 ((or (not box) (equal arg '(4))) nil)
19701 ((eq box 'on) "[ ]")
19702 (t "[X]")))
19703 ;; Mimic `org-list-write-struct' but with grabbing
19704 ;; a return value from `org-list-struct-fix-box'.
19705 (org-list-struct-fix-ind struct parents 2)
19706 (org-list-struct-fix-item-end struct)
19707 (org-list-struct-fix-bul struct prevs)
19708 (org-list-struct-fix-ind struct parents)
19709 (let ((block-item
19710 (org-list-struct-fix-box struct parents prevs orderedp)))
19711 (if (and box (equal struct old-struct))
19712 (if (equal arg '(16))
19713 (message "Checkboxes already reset")
19714 (user-error "Cannot toggle this checkbox: %s"
19715 (if (eq box 'on)
19716 "all subitems checked"
19717 "unchecked subitems")))
19718 (org-list-struct-apply-struct struct old-struct)
19719 (org-update-checkbox-count-maybe))
19720 (when block-item
19721 (message "Checkboxes were removed due to empty box at line %d"
19722 (org-current-line block-item))))))
19723 (keyword
19724 (let ((org-inhibit-startup-visibility-stuff t)
19725 (org-startup-align-all-tables nil))
19726 (when (boundp 'org-table-coordinate-overlays)
19727 (mapc 'delete-overlay org-table-coordinate-overlays)
19728 (setq org-table-coordinate-overlays nil))
19729 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19730 (message "Local setup has been refreshed"))
19731 (plain-list
19732 ;; At a plain list, with a double C-u argument, set
19733 ;; checkboxes of each item to "[-]", whereas a single one
19734 ;; will toggle their presence according to the state of the
19735 ;; first item in the list. Without an argument, repair the
19736 ;; list.
19737 (let* ((begin (org-element-property :contents-begin context))
19738 (struct (org-element-property :structure context))
19739 (old-struct (copy-tree struct))
19740 (first-box (save-excursion
19741 (goto-char begin)
19742 (looking-at org-list-full-item-re)
19743 (match-string-no-properties 3)))
19744 (new-box (cond ((equal arg '(16)) "[-]")
19745 ((equal arg '(4)) (unless first-box "[ ]"))
19746 ((equal first-box "[X]") "[ ]")
19747 (t "[X]"))))
19748 (cond
19749 (arg
19750 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19751 (org-list-get-all-items
19752 begin struct (org-list-prevs-alist struct))))
19753 ((and first-box (eq (point) begin))
19754 ;; For convenience, when point is at bol on the first
19755 ;; item of the list and no argument is provided, simply
19756 ;; toggle checkbox of that item, if any.
19757 (org-list-set-checkbox begin struct new-box)))
19758 (org-list-write-struct
19759 struct (org-list-parents-alist struct) old-struct)
19760 (org-update-checkbox-count-maybe)
19761 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19762 ((property-drawer node-property)
19763 (call-interactively 'org-property-action))
19764 ((radio-target target)
19765 (call-interactively 'org-update-radio-target-regexp))
19766 (statistics-cookie
19767 (call-interactively 'org-update-statistics-cookies))
19768 ((table table-cell table-row)
19769 ;; At a table, recalculate every field and align it. Also
19770 ;; send the table if necessary. If the table has
19771 ;; a `table.el' type, just give up. At a table row or
19772 ;; cell, maybe recalculate line but always align table.
19773 (if (eq (org-element-property :type context) 'table.el)
19774 (message "Use C-c ' to edit table.el tables")
19775 (let ((org-enable-table-editor t))
19776 (if (or (eq type 'table)
19777 ;; Check if point is at a TBLFM line.
19778 (and (eq type 'table-row)
19779 (= (point) (org-element-property :end context))))
19780 (save-excursion
19781 (goto-char (org-element-property :contents-begin context))
19782 (org-call-with-arg 'org-table-recalculate (or arg t))
19783 (orgtbl-send-table 'maybe))
19784 (org-table-maybe-eval-formula)
19785 (cond (arg (call-interactively 'org-table-recalculate))
19786 ((org-table-maybe-recalculate-line))
19787 (t (org-table-align)))))))
19788 (timestamp (org-timestamp-change 0 'day))
19789 (otherwise
19790 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19791 (user-error
19792 "C-c C-c can do nothing useful at this location")))))))))
19794 (defun org-mode-restart ()
19795 "Restart Org-mode, to scan again for special lines.
19796 Also updates the keyword regular expressions."
19797 (interactive)
19798 (org-mode)
19799 (message "Org-mode restarted"))
19801 (defun org-kill-note-or-show-branches ()
19802 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19803 (interactive)
19804 (if (not org-finish-function)
19805 (progn
19806 (hide-subtree)
19807 (call-interactively 'show-branches))
19808 (let ((org-note-abort t))
19809 (funcall org-finish-function))))
19811 (defun org-return (&optional indent)
19812 "Goto next table row or insert a newline.
19813 Calls `org-table-next-row' or `newline', depending on context.
19814 See the individual commands for more information."
19815 (interactive)
19816 (let (org-ts-what)
19817 (cond
19818 ((or (bobp) (org-in-src-block-p))
19819 (if indent (newline-and-indent) (newline)))
19820 ((org-at-table-p)
19821 (org-table-justify-field-maybe)
19822 (call-interactively 'org-table-next-row))
19823 ;; when `newline-and-indent' is called within a list, make sure
19824 ;; text moved stays inside the item.
19825 ((and (org-in-item-p) indent)
19826 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19827 (progn
19828 (save-match-data (newline))
19829 (org-indent-line-to (length (match-string 0))))
19830 (let ((ind (org-get-indentation)))
19831 (newline)
19832 (if (org-looking-back org-list-end-re)
19833 (org-indent-line)
19834 (org-indent-line-to ind)))))
19835 ((and org-return-follows-link
19836 (org-at-timestamp-p t)
19837 (not (eq org-ts-what 'after)))
19838 (org-follow-timestamp-link))
19839 ((and org-return-follows-link
19840 (let ((tprop (get-text-property (point) 'face)))
19841 (or (eq tprop 'org-link)
19842 (and (listp tprop) (memq 'org-link tprop)))))
19843 (call-interactively 'org-open-at-point))
19844 ((and (org-at-heading-p)
19845 (looking-at
19846 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19847 (org-show-entry)
19848 (end-of-line 1)
19849 (newline))
19850 (t (if indent (newline-and-indent) (newline))))))
19852 (defun org-return-indent ()
19853 "Goto next table row or insert a newline and indent.
19854 Calls `org-table-next-row' or `newline-and-indent', depending on
19855 context. See the individual commands for more information."
19856 (interactive)
19857 (org-return t))
19859 (defun org-ctrl-c-star ()
19860 "Compute table, or change heading status of lines.
19861 Calls `org-table-recalculate' or `org-toggle-heading',
19862 depending on context."
19863 (interactive)
19864 (cond
19865 ((org-at-table-p)
19866 (call-interactively 'org-table-recalculate))
19868 ;; Convert all lines in region to list items
19869 (call-interactively 'org-toggle-heading))))
19871 (defun org-ctrl-c-minus ()
19872 "Insert separator line in table or modify bullet status of line.
19873 Also turns a plain line or a region of lines into list items.
19874 Calls `org-table-insert-hline', `org-toggle-item', or
19875 `org-cycle-list-bullet', depending on context."
19876 (interactive)
19877 (cond
19878 ((org-at-table-p)
19879 (call-interactively 'org-table-insert-hline))
19880 ((org-region-active-p)
19881 (call-interactively 'org-toggle-item))
19882 ((org-in-item-p)
19883 (call-interactively 'org-cycle-list-bullet))
19885 (call-interactively 'org-toggle-item))))
19887 (defun org-toggle-item (arg)
19888 "Convert headings or normal lines to items, items to normal lines.
19889 If there is no active region, only the current line is considered.
19891 If the first non blank line in the region is an headline, convert
19892 all headlines to items, shifting text accordingly.
19894 If it is an item, convert all items to normal lines.
19896 If it is normal text, change region into an item. With a prefix
19897 argument ARG, change each line in region into an item."
19898 (interactive "P")
19899 (let ((shift-text
19900 (function
19901 ;; Shift text in current section to IND, from point to END.
19902 ;; The function leaves point to END line.
19903 (lambda (ind end)
19904 (let ((min-i 1000) (end (copy-marker end)))
19905 ;; First determine the minimum indentation (MIN-I) of
19906 ;; the text.
19907 (save-excursion
19908 (catch 'exit
19909 (while (< (point) end)
19910 (let ((i (org-get-indentation)))
19911 (cond
19912 ;; Skip blank lines and inline tasks.
19913 ((looking-at "^[ \t]*$"))
19914 ((looking-at org-outline-regexp-bol))
19915 ;; We can't find less than 0 indentation.
19916 ((zerop i) (throw 'exit (setq min-i 0)))
19917 ((< i min-i) (setq min-i i))))
19918 (forward-line))))
19919 ;; Then indent each line so that a line indented to
19920 ;; MIN-I becomes indented to IND. Ignore blank lines
19921 ;; and inline tasks in the process.
19922 (let ((delta (- ind min-i)))
19923 (while (< (point) end)
19924 (unless (or (looking-at "^[ \t]*$")
19925 (looking-at org-outline-regexp-bol))
19926 (org-indent-line-to (+ (org-get-indentation) delta)))
19927 (forward-line)))))))
19928 (skip-blanks
19929 (function
19930 ;; Return beginning of first non-blank line, starting from
19931 ;; line at POS.
19932 (lambda (pos)
19933 (save-excursion
19934 (goto-char pos)
19935 (skip-chars-forward " \r\t\n")
19936 (point-at-bol)))))
19937 beg end)
19938 ;; Determine boundaries of changes.
19939 (if (org-region-active-p)
19940 (setq beg (funcall skip-blanks (region-beginning))
19941 end (copy-marker (region-end)))
19942 (setq beg (funcall skip-blanks (point-at-bol))
19943 end (copy-marker (point-at-eol))))
19944 ;; Depending on the starting line, choose an action on the text
19945 ;; between BEG and END.
19946 (org-with-limited-levels
19947 (save-excursion
19948 (goto-char beg)
19949 (cond
19950 ;; Case 1. Start at an item: de-itemize. Note that it only
19951 ;; happens when a region is active: `org-ctrl-c-minus'
19952 ;; would call `org-cycle-list-bullet' otherwise.
19953 ((org-at-item-p)
19954 (while (< (point) end)
19955 (when (org-at-item-p)
19956 (skip-chars-forward " \t")
19957 (delete-region (point) (match-end 0)))
19958 (forward-line)))
19959 ;; Case 2. Start at an heading: convert to items.
19960 ((org-at-heading-p)
19961 (let* ((bul (org-list-bullet-string "-"))
19962 (bul-len (length bul))
19963 ;; Indentation of the first heading. It should be
19964 ;; relative to the indentation of its parent, if any.
19965 (start-ind (save-excursion
19966 (cond
19967 ((not org-adapt-indentation) 0)
19968 ((not (outline-previous-heading)) 0)
19969 (t (length (match-string 0))))))
19970 ;; Level of first heading. Further headings will be
19971 ;; compared to it to determine hierarchy in the list.
19972 (ref-level (org-reduced-level (org-outline-level))))
19973 (while (< (point) end)
19974 (let* ((level (org-reduced-level (org-outline-level)))
19975 (delta (max 0 (- level ref-level))))
19976 ;; If current headline is less indented than the first
19977 ;; one, set it as reference, in order to preserve
19978 ;; subtrees.
19979 (when (< level ref-level) (setq ref-level level))
19980 (replace-match bul t t)
19981 (org-indent-line-to (+ start-ind (* delta bul-len)))
19982 ;; Ensure all text down to END (or SECTION-END) belongs
19983 ;; to the newly created item.
19984 (let ((section-end (save-excursion
19985 (or (outline-next-heading) (point)))))
19986 (forward-line)
19987 (funcall shift-text
19988 (+ start-ind (* (1+ delta) bul-len))
19989 (min end section-end)))))))
19990 ;; Case 3. Normal line with ARG: turn each non-item line into
19991 ;; an item.
19992 (arg
19993 (while (< (point) end)
19994 (unless (or (org-at-heading-p) (org-at-item-p))
19995 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19996 (replace-match
19997 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19998 (forward-line)))
19999 ;; Case 4. Normal line without ARG: make the first line of
20000 ;; region an item, and shift indentation of others
20001 ;; lines to set them as item's body.
20002 (t (let* ((bul (org-list-bullet-string "-"))
20003 (bul-len (length bul))
20004 (ref-ind (org-get-indentation)))
20005 (skip-chars-forward " \t")
20006 (insert bul)
20007 (forward-line)
20008 (while (< (point) end)
20009 ;; Ensure that lines less indented than first one
20010 ;; still get included in item body.
20011 (funcall shift-text
20012 (+ ref-ind bul-len)
20013 (min end (save-excursion (or (outline-next-heading)
20014 (point)))))
20015 (forward-line)))))))))
20017 (defun org-toggle-heading (&optional nstars)
20018 "Convert headings to normal text, or items or text to headings.
20019 If there is no active region, only the current line is considered.
20021 With a \\[universal-argument] prefix, convert the whole list at
20022 point into heading.
20024 In a region:
20026 - If the first non blank line is an headline, remove the stars
20027 from all headlines in the region.
20029 - If it is a normal line turn each and every normal line (i.e. not an
20030 heading or an item) in the region into a heading.
20032 - If it is a plain list item, turn all plain list items into headings.
20034 When converting a line into a heading, the number of stars is chosen
20035 such that the lines become children of the current entry. However,
20036 when a prefix argument is given, its value determines the number of
20037 stars to add."
20038 (interactive "P")
20039 (let ((skip-blanks
20040 (function
20041 ;; Return beginning of first non-blank line, starting from
20042 ;; line at POS.
20043 (lambda (pos)
20044 (save-excursion
20045 (goto-char pos)
20046 (while (org-at-comment-p) (forward-line))
20047 (skip-chars-forward " \r\t\n")
20048 (point-at-bol)))))
20049 beg end toggled)
20050 ;; Determine boundaries of changes. If a universal prefix has
20051 ;; been given, put the list in a region. If region ends at a bol,
20052 ;; do not consider the last line to be in the region.
20054 (when (and current-prefix-arg (org-at-item-p))
20055 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20056 (org-mark-element))
20058 (if (org-region-active-p)
20059 (setq beg (funcall skip-blanks (region-beginning))
20060 end (copy-marker (save-excursion
20061 (goto-char (region-end))
20062 (if (bolp) (point) (point-at-eol)))))
20063 (setq beg (funcall skip-blanks (point-at-bol))
20064 end (copy-marker (point-at-eol))))
20065 ;; Ensure inline tasks don't count as headings.
20066 (org-with-limited-levels
20067 (save-excursion
20068 (goto-char beg)
20069 (cond
20070 ;; Case 1. Started at an heading: de-star headings.
20071 ((org-at-heading-p)
20072 (while (< (point) end)
20073 (when (org-at-heading-p t)
20074 (looking-at org-outline-regexp) (replace-match "")
20075 (setq toggled t))
20076 (forward-line)))
20077 ;; Case 2. Started at an item: change items into headlines.
20078 ;; One star will be added by `org-list-to-subtree'.
20079 ((org-at-item-p)
20080 (let* ((stars (make-string
20081 (if nstars
20082 ;; subtract the star that will be added again by
20083 ;; `org-list-to-subtree'
20084 (1- (prefix-numeric-value current-prefix-arg))
20085 (or (org-current-level) 0))
20086 ?*))
20087 (add-stars
20088 (cond (nstars "") ; stars from prefix only
20089 ((equal stars "") "") ; before first heading
20090 (org-odd-levels-only "*") ; inside heading, odd
20091 (t "")))) ; inside heading, oddeven
20092 (while (< (point) end)
20093 (when (org-at-item-p)
20094 ;; Pay attention to cases when region ends before list.
20095 (let* ((struct (org-list-struct))
20096 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20097 (save-restriction
20098 (narrow-to-region (point) list-end)
20099 (insert
20100 (org-list-to-subtree
20101 (org-list-parse-list t)
20102 '(:istart (concat stars add-stars (funcall get-stars depth))
20103 :icount (concat stars add-stars (funcall get-stars depth)))))))
20104 (setq toggled t))
20105 (forward-line))))
20106 ;; Case 3. Started at normal text: make every line an heading,
20107 ;; skipping headlines and items.
20108 (t (let* ((stars (make-string
20109 (if nstars
20110 (prefix-numeric-value current-prefix-arg)
20111 (or (org-current-level) 0))
20112 ?*))
20113 (add-stars
20114 (cond (nstars "") ; stars from prefix only
20115 ((equal stars "") "*") ; before first heading
20116 (org-odd-levels-only "**") ; inside heading, odd
20117 (t "*"))) ; inside heading, oddeven
20118 (rpl (concat stars add-stars " ")))
20119 (while (< (point) end)
20120 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20121 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20122 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20123 (forward-line)))))))
20124 (unless toggled (message "Cannot toggle heading from here"))))
20126 (defun org-meta-return (&optional arg)
20127 "Insert a new heading or wrap a region in a table.
20128 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20129 See the individual commands for more information."
20130 (interactive "P")
20131 (cond
20132 ((run-hook-with-args-until-success 'org-metareturn-hook))
20133 ((or (org-at-drawer-p) (org-at-property-p))
20134 (newline-and-indent))
20135 ((org-at-table-p)
20136 (call-interactively 'org-table-wrap-region))
20137 (t (call-interactively 'org-insert-heading))))
20139 ;;; Menu entries
20141 (defsubst org-in-subtree-not-table-p ()
20142 "Are we in a subtree and not in a table?"
20143 (and (not (org-before-first-heading-p))
20144 (not (org-at-table-p))))
20146 ;; Define the Org-mode menus
20147 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20148 '("Tbl"
20149 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20150 ["Next Field" org-cycle (org-at-table-p)]
20151 ["Previous Field" org-shifttab (org-at-table-p)]
20152 ["Next Row" org-return (org-at-table-p)]
20153 "--"
20154 ["Blank Field" org-table-blank-field (org-at-table-p)]
20155 ["Edit Field" org-table-edit-field (org-at-table-p)]
20156 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20157 "--"
20158 ("Column"
20159 ["Move Column Left" org-metaleft (org-at-table-p)]
20160 ["Move Column Right" org-metaright (org-at-table-p)]
20161 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20162 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20163 ("Row"
20164 ["Move Row Up" org-metaup (org-at-table-p)]
20165 ["Move Row Down" org-metadown (org-at-table-p)]
20166 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20167 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20168 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20169 "--"
20170 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20171 ("Rectangle"
20172 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20173 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20174 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20175 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20176 "--"
20177 ("Calculate"
20178 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20179 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20180 ["Edit Formulas" org-edit-special (org-at-table-p)]
20181 "--"
20182 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20183 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20184 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20185 "--"
20186 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20187 "--"
20188 ["Sum Column/Rectangle" org-table-sum
20189 (or (org-at-table-p) (org-region-active-p))]
20190 ["Which Column?" org-table-current-column (org-at-table-p)])
20191 ["Debug Formulas"
20192 org-table-toggle-formula-debugger
20193 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20194 ["Show Col/Row Numbers"
20195 org-table-toggle-coordinate-overlays
20196 :style toggle
20197 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20198 "--"
20199 ["Create" org-table-create (and (not (org-at-table-p))
20200 org-enable-table-editor)]
20201 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20202 ["Import from File" org-table-import (not (org-at-table-p))]
20203 ["Export to File" org-table-export (org-at-table-p)]
20204 "--"
20205 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20207 (easy-menu-define org-org-menu org-mode-map "Org menu"
20208 '("Org"
20209 ("Show/Hide"
20210 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20211 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20212 ["Sparse Tree..." org-sparse-tree t]
20213 ["Reveal Context" org-reveal t]
20214 ["Show All" show-all t]
20215 "--"
20216 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20217 "--"
20218 ["New Heading" org-insert-heading t]
20219 ("Navigate Headings"
20220 ["Up" outline-up-heading t]
20221 ["Next" outline-next-visible-heading t]
20222 ["Previous" outline-previous-visible-heading t]
20223 ["Next Same Level" outline-forward-same-level t]
20224 ["Previous Same Level" outline-backward-same-level t]
20225 "--"
20226 ["Jump" org-goto t])
20227 ("Edit Structure"
20228 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20229 "--"
20230 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20231 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20232 "--"
20233 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20234 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20235 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20236 "--"
20237 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20238 "--"
20239 ["Copy visible text" org-copy-visible t]
20240 "--"
20241 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20242 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20243 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20244 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20245 "--"
20246 ["Sort Region/Children" org-sort t]
20247 "--"
20248 ["Convert to odd levels" org-convert-to-odd-levels t]
20249 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20250 ("Editing"
20251 ["Emphasis..." org-emphasize t]
20252 ["Edit Source Example" org-edit-special t]
20253 "--"
20254 ["Footnote new/jump" org-footnote-action t]
20255 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20256 ("Archive"
20257 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20258 "--"
20259 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20260 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20261 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20263 "--"
20264 ("Hyperlinks"
20265 ["Store Link (Global)" org-store-link t]
20266 ["Find existing link to here" org-occur-link-in-agenda-files t]
20267 ["Insert Link" org-insert-link t]
20268 ["Follow Link" org-open-at-point t]
20269 "--"
20270 ["Next link" org-next-link t]
20271 ["Previous link" org-previous-link t]
20272 "--"
20273 ["Descriptive Links"
20274 org-toggle-link-display
20275 :style radio
20276 :selected org-descriptive-links
20278 ["Literal Links"
20279 org-toggle-link-display
20280 :style radio
20281 :selected (not org-descriptive-links)])
20282 "--"
20283 ("TODO Lists"
20284 ["TODO/DONE/-" org-todo t]
20285 ("Select keyword"
20286 ["Next keyword" org-shiftright (org-at-heading-p)]
20287 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20288 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20289 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20290 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20291 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20292 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20293 "--"
20294 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20295 :selected org-enforce-todo-dependencies :style toggle :active t]
20296 "Settings for tree at point"
20297 ["Do Children sequentially" org-toggle-ordered-property :style radio
20298 :selected (org-entry-get nil "ORDERED")
20299 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20300 ["Do Children parallel" org-toggle-ordered-property :style radio
20301 :selected (not (org-entry-get nil "ORDERED"))
20302 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20303 "--"
20304 ["Set Priority" org-priority t]
20305 ["Priority Up" org-shiftup t]
20306 ["Priority Down" org-shiftdown t]
20307 "--"
20308 ["Get news from all feeds" org-feed-update-all t]
20309 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20310 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20311 ("TAGS and Properties"
20312 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20313 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20314 "--"
20315 ["Set property" org-set-property (not (org-before-first-heading-p))]
20316 ["Column view of properties" org-columns t]
20317 ["Insert Column View DBlock" org-insert-columns-dblock t])
20318 ("Dates and Scheduling"
20319 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20320 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20321 ("Change Date"
20322 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20323 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20324 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20325 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20326 ["Compute Time Range" org-evaluate-time-range t]
20327 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20328 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20329 "--"
20330 ["Custom time format" org-toggle-time-stamp-overlays
20331 :style radio :selected org-display-custom-times]
20332 "--"
20333 ["Goto Calendar" org-goto-calendar t]
20334 ["Date from Calendar" org-date-from-calendar t]
20335 "--"
20336 ["Start/Restart Timer" org-timer-start t]
20337 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20338 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20339 ["Insert Timer String" org-timer t]
20340 ["Insert Timer Item" org-timer-item t])
20341 ("Logging work"
20342 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20343 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20344 ["Clock out" org-clock-out t]
20345 ["Clock cancel" org-clock-cancel t]
20346 "--"
20347 ["Mark as default task" org-clock-mark-default-task t]
20348 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20349 ["Goto running clock" org-clock-goto t]
20350 "--"
20351 ["Display times" org-clock-display t]
20352 ["Create clock table" org-clock-report t]
20353 "--"
20354 ["Record DONE time"
20355 (progn (setq org-log-done (not org-log-done))
20356 (message "Switching to %s will %s record a timestamp"
20357 (car org-done-keywords)
20358 (if org-log-done "automatically" "not")))
20359 :style toggle :selected org-log-done])
20360 "--"
20361 ["Agenda Command..." org-agenda t]
20362 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20363 ("File List for Agenda")
20364 ("Special views current file"
20365 ["TODO Tree" org-show-todo-tree t]
20366 ["Check Deadlines" org-check-deadlines t]
20367 ["Timeline" org-timeline t]
20368 ["Tags/Property tree" org-match-sparse-tree t])
20369 "--"
20370 ["Export/Publish..." org-export-dispatch t]
20371 ("LaTeX"
20372 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20373 :selected org-cdlatex-mode]
20374 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20375 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20376 ["Modify math symbol" org-cdlatex-math-modify
20377 (org-inside-LaTeX-fragment-p)]
20378 ["Insert citation" org-reftex-citation t]
20379 "--"
20380 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20381 "--"
20382 ("MobileOrg"
20383 ["Push Files and Views" org-mobile-push t]
20384 ["Get Captured and Flagged" org-mobile-pull t]
20385 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20386 "--"
20387 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20388 "--"
20389 ("Documentation"
20390 ["Show Version" org-version t]
20391 ["Info Documentation" org-info t])
20392 ("Customize"
20393 ["Browse Org Group" org-customize t]
20394 "--"
20395 ["Expand This Menu" org-create-customize-menu
20396 (fboundp 'customize-menu-create)])
20397 ["Send bug report" org-submit-bug-report t]
20398 "--"
20399 ("Refresh/Reload"
20400 ["Refresh setup current buffer" org-mode-restart t]
20401 ["Reload Org (after update)" org-reload t]
20402 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20405 (defun org-info (&optional node)
20406 "Read documentation for Org-mode in the info system.
20407 With optional NODE, go directly to that node."
20408 (interactive)
20409 (info (format "(org)%s" (or node ""))))
20411 ;;;###autoload
20412 (defun org-submit-bug-report ()
20413 "Submit a bug report on Org-mode via mail.
20415 Don't hesitate to report any problems or inaccurate documentation.
20417 If you don't have setup sending mail from (X)Emacs, please copy the
20418 output buffer into your mail program, as it gives us important
20419 information about your Org-mode version and configuration."
20420 (interactive)
20421 (require 'reporter)
20422 (org-load-modules-maybe)
20423 (org-require-autoloaded-modules)
20424 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20425 (reporter-submit-bug-report
20426 "emacs-orgmode@gnu.org"
20427 (org-version nil 'full)
20428 (let (list)
20429 (save-window-excursion
20430 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20431 (delete-other-windows)
20432 (erase-buffer)
20433 (insert "You are about to submit a bug report to the Org-mode mailing list.
20435 We would like to add your full Org-mode and Outline configuration to the
20436 bug report. This greatly simplifies the work of the maintainer and
20437 other experts on the mailing list.
20439 HOWEVER, some variables you have customized may contain private
20440 information. The names of customers, colleagues, or friends, might
20441 appear in the form of file names, tags, todo states, or search strings.
20442 If you answer yes to the prompt, you might want to check and remove
20443 such private information before sending the email.")
20444 (add-text-properties (point-min) (point-max) '(face org-warning))
20445 (when (yes-or-no-p "Include your Org-mode configuration ")
20446 (mapatoms
20447 (lambda (v)
20448 (and (boundp v)
20449 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20450 (or (and (symbol-value v)
20451 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20452 (and
20453 (get v 'custom-type) (get v 'standard-value)
20454 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20455 (push v list)))))
20456 (kill-buffer (get-buffer "*Warn about privacy*"))
20457 list))
20458 nil nil
20459 "Remember to cover the basics, that is, what you expected to happen and
20460 what in fact did happen. You don't know how to make a good report? See
20462 http://orgmode.org/manual/Feedback.html#Feedback
20464 Your bug report will be posted to the Org-mode mailing list.
20465 ------------------------------------------------------------------------")
20466 (save-excursion
20467 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20468 (replace-match "\\1Bug: \\3 [\\2]")))))
20471 (defun org-install-agenda-files-menu ()
20472 (let ((bl (buffer-list)))
20473 (save-excursion
20474 (while bl
20475 (set-buffer (pop bl))
20476 (if (derived-mode-p 'org-mode) (setq bl nil)))
20477 (when (derived-mode-p 'org-mode)
20478 (easy-menu-change
20479 '("Org") "File List for Agenda"
20480 (append
20481 (list
20482 ["Edit File List" (org-edit-agenda-file-list) t]
20483 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20484 ["Remove Current File from List" org-remove-file t]
20485 ["Cycle through agenda files" org-cycle-agenda-files t]
20486 ["Occur in all agenda files" org-occur-in-agenda-files t]
20487 "--")
20488 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20490 ;;;; Documentation
20492 (defun org-require-autoloaded-modules ()
20493 (interactive)
20494 (mapc 'require
20495 '(org-agenda org-archive org-attach org-clock org-colview org-id
20496 org-remember org-table org-timer)))
20498 ;;;###autoload
20499 (defun org-reload (&optional uncompiled)
20500 "Reload all org lisp files.
20501 With prefix arg UNCOMPILED, load the uncompiled versions."
20502 (interactive "P")
20503 (require 'loadhist)
20504 (let* ((org-dir (org-find-library-dir "org"))
20505 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20506 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20507 (remove-re (mapconcat 'identity
20508 (mapcar (lambda (f) (concat "^" f "$"))
20509 (list (if (featurep 'xemacs)
20510 "org-colview"
20511 "org-colview-xemacs")
20512 "org" "org-loaddefs" "org-version"))
20513 "\\|"))
20514 (feats (delete-dups
20515 (mapcar 'file-name-sans-extension
20516 (mapcar 'file-name-nondirectory
20517 (delq nil
20518 (mapcar 'feature-file
20519 features))))))
20520 (lfeat (append
20521 (sort
20522 (setq feats
20523 (delq nil (mapcar
20524 (lambda (f)
20525 (if (and (string-match feature-re f)
20526 (not (string-match remove-re f)))
20527 f nil))
20528 feats)))
20529 'string-lessp)
20530 (list "org-version" "org")))
20531 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20532 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20533 load-uncore load-misses)
20534 (setq load-misses
20535 (delq 't
20536 (mapcar (lambda (f)
20537 (or (org-load-noerror-mustsuffix (concat org-dir f))
20538 (and (string= org-dir contrib-dir)
20539 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20540 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20541 (add-to-list 'load-uncore f 'append)
20544 lfeat)))
20545 (if load-uncore
20546 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20547 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20548 (if load-misses
20549 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20550 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20551 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20553 ;;;###autoload
20554 (defun org-customize ()
20555 "Call the customize function with org as argument."
20556 (interactive)
20557 (org-load-modules-maybe)
20558 (org-require-autoloaded-modules)
20559 (customize-browse 'org))
20561 (defun org-create-customize-menu ()
20562 "Create a full customization menu for Org-mode, insert it into the menu."
20563 (interactive)
20564 (org-load-modules-maybe)
20565 (org-require-autoloaded-modules)
20566 (if (fboundp 'customize-menu-create)
20567 (progn
20568 (easy-menu-change
20569 '("Org") "Customize"
20570 `(["Browse Org group" org-customize t]
20571 "--"
20572 ,(customize-menu-create 'org)
20573 ["Set" Custom-set t]
20574 ["Save" Custom-save t]
20575 ["Reset to Current" Custom-reset-current t]
20576 ["Reset to Saved" Custom-reset-saved t]
20577 ["Reset to Standard Settings" Custom-reset-standard t]))
20578 (message "\"Org\"-menu now contains full customization menu"))
20579 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20581 ;;;; Miscellaneous stuff
20583 ;;; Generally useful functions
20585 (defun org-get-at-bol (property)
20586 "Get text property PROPERTY at beginning of line."
20587 (get-text-property (point-at-bol) property))
20589 (defun org-find-text-property-in-string (prop s)
20590 "Return the first non-nil value of property PROP in string S."
20591 (or (get-text-property 0 prop s)
20592 (get-text-property (or (next-single-property-change 0 prop s) 0)
20593 prop s)))
20595 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20596 "Display the given MESSAGE as a warning."
20597 (if (fboundp 'display-warning)
20598 (display-warning 'org message
20599 (if (featurep 'xemacs) 'warning :warning))
20600 (let ((buf (get-buffer-create "*Org warnings*")))
20601 (with-current-buffer buf
20602 (goto-char (point-max))
20603 (insert "Warning (Org): " message)
20604 (unless (bolp)
20605 (newline)))
20606 (display-buffer buf)
20607 (sit-for 0))))
20609 (defun org-eval (form)
20610 "Eval FORM and return result."
20611 (condition-case error
20612 (eval form)
20613 (error (format "%%![Error: %s]" error))))
20615 (defun org-in-clocktable-p ()
20616 "Check if the cursor is in a clocktable."
20617 (let ((pos (point)) start)
20618 (save-excursion
20619 (end-of-line 1)
20620 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20621 (setq start (match-beginning 0))
20622 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20623 (>= (match-end 0) pos)
20624 start))))
20626 (defun org-in-commented-line ()
20627 "Is point in a line starting with `#'?"
20628 (equal (char-after (point-at-bol)) ?#))
20630 (defun org-in-indented-comment-line ()
20631 "Is point in a line starting with `#' after some white space?"
20632 (save-excursion
20633 (save-match-data
20634 (goto-char (point-at-bol))
20635 (looking-at "[ \t]*#"))))
20637 (defun org-in-verbatim-emphasis ()
20638 (save-match-data
20639 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20641 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20642 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20643 (if (and marker (marker-buffer marker)
20644 (buffer-live-p (marker-buffer marker)))
20645 (progn
20646 (org-pop-to-buffer-same-window (marker-buffer marker))
20647 (if (or (> marker (point-max)) (< marker (point-min)))
20648 (widen))
20649 (goto-char marker)
20650 (org-show-context 'org-goto))
20651 (if bookmark
20652 (bookmark-jump bookmark)
20653 (error "Cannot find location"))))
20655 (defun org-quote-csv-field (s)
20656 "Quote field for inclusion in CSV material."
20657 (if (string-match "[\",]" s)
20658 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20661 (defun org-force-self-insert (N)
20662 "Needed to enforce self-insert under remapping."
20663 (interactive "p")
20664 (self-insert-command N))
20666 (defun org-string-width (s)
20667 "Compute width of string, ignoring invisible characters.
20668 This ignores character with invisibility property `org-link', and also
20669 characters with property `org-cwidth', because these will become invisible
20670 upon the next fontification round."
20671 (let (b l)
20672 (when (or (eq t buffer-invisibility-spec)
20673 (assq 'org-link buffer-invisibility-spec))
20674 (while (setq b (text-property-any 0 (length s)
20675 'invisible 'org-link s))
20676 (setq s (concat (substring s 0 b)
20677 (substring s (or (next-single-property-change
20678 b 'invisible s) (length s)))))))
20679 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20680 (setq s (concat (substring s 0 b)
20681 (substring s (or (next-single-property-change
20682 b 'org-cwidth s) (length s))))))
20683 (setq l (string-width s) b -1)
20684 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20685 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20688 (defun org-shorten-string (s maxlength)
20689 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20690 If the string is shorter or has length MAXLENGTH, just return the
20691 original string. If it is longer, the functions finds a space in the
20692 string, breaks this string off at that locations and adds three dots
20693 as ellipsis. Including the ellipsis, the string will not be longer
20694 than MAXLENGTH. If finding a good breaking point in the string does
20695 not work, the string is just chopped off in the middle of a word
20696 if necessary."
20697 (if (<= (length s) maxlength)
20699 (let* ((n (max (- maxlength 4) 1))
20700 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20701 (if (string-match re s)
20702 (concat (match-string 1 s) "...")
20703 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20705 (defun org-get-indentation (&optional line)
20706 "Get the indentation of the current line, interpreting tabs.
20707 When LINE is given, assume it represents a line and compute its indentation."
20708 (if line
20709 (if (string-match "^ *" (org-remove-tabs line))
20710 (match-end 0))
20711 (save-excursion
20712 (beginning-of-line 1)
20713 (skip-chars-forward " \t")
20714 (current-column))))
20716 (defun org-get-string-indentation (s)
20717 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20718 (let ((n -1) (i 0) (w tab-width) c)
20719 (catch 'exit
20720 (while (< (setq n (1+ n)) (length s))
20721 (setq c (aref s n))
20722 (cond ((= c ?\ ) (setq i (1+ i)))
20723 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20724 (t (throw 'exit t)))))
20727 (defun org-remove-tabs (s &optional width)
20728 "Replace tabulators in S with spaces.
20729 Assumes that s is a single line, starting in column 0."
20730 (setq width (or width tab-width))
20731 (while (string-match "\t" s)
20732 (setq s (replace-match
20733 (make-string
20734 (- (* width (/ (+ (match-beginning 0) width) width))
20735 (match-beginning 0)) ?\ )
20736 t t s)))
20739 (defun org-fix-indentation (line ind)
20740 "Fix indentation in LINE.
20741 IND is a cons cell with target and minimum indentation.
20742 If the current indentation in LINE is smaller than the minimum,
20743 leave it alone. If it is larger than ind, set it to the target."
20744 (let* ((l (org-remove-tabs line))
20745 (i (org-get-indentation l))
20746 (i1 (car ind)) (i2 (cdr ind)))
20747 (if (>= i i2) (setq l (substring line i2)))
20748 (if (> i1 0)
20749 (concat (make-string i1 ?\ ) l)
20750 l)))
20752 (defun org-remove-indentation (code &optional n)
20753 "Remove the maximum common indentation from the lines in CODE.
20754 N may optionally be the number of spaces to remove."
20755 (with-temp-buffer
20756 (insert code)
20757 (org-do-remove-indentation n)
20758 (buffer-string)))
20760 (defun org-do-remove-indentation (&optional n)
20761 "Remove the maximum common indentation from the buffer."
20762 (untabify (point-min) (point-max))
20763 (let ((min 10000) re)
20764 (if n
20765 (setq min n)
20766 (goto-char (point-min))
20767 (while (re-search-forward "^ *[^ \n]" nil t)
20768 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20769 (unless (or (= min 0) (= min 10000))
20770 (setq re (format "^ \\{%d\\}" min))
20771 (goto-char (point-min))
20772 (while (re-search-forward re nil t)
20773 (replace-match "")
20774 (end-of-line 1))
20775 min)))
20777 (defun org-fill-template (template alist)
20778 "Find each %key of ALIST in TEMPLATE and replace it."
20779 (let ((case-fold-search nil)
20780 entry key value)
20781 (setq alist (sort (copy-sequence alist)
20782 (lambda (a b) (< (length (car a)) (length (car b))))))
20783 (while (setq entry (pop alist))
20784 (setq template
20785 (replace-regexp-in-string
20786 (concat "%" (regexp-quote (car entry)))
20787 (or (cdr entry) "") template t t)))
20788 template))
20790 (defun org-base-buffer (buffer)
20791 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20792 (if (not buffer)
20793 buffer
20794 (or (buffer-base-buffer buffer)
20795 buffer)))
20797 (defun org-trim (s)
20798 "Remove whitespace at beginning and end of string."
20799 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20800 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20803 (defun org-wrap (string &optional width lines)
20804 "Wrap string to either a number of lines, or a width in characters.
20805 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20806 that costs. If there is a word longer than WIDTH, the text is actually
20807 wrapped to the length of that word.
20808 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20809 many lines, whatever width that takes.
20810 The return value is a list of lines, without newlines at the end."
20811 (let* ((words (org-split-string string "[ \t\n]+"))
20812 (maxword (apply 'max (mapcar 'org-string-width words)))
20813 w ll)
20814 (cond (width
20815 (org-do-wrap words (max maxword width)))
20816 (lines
20817 (setq w maxword)
20818 (setq ll (org-do-wrap words maxword))
20819 (if (<= (length ll) lines)
20821 (setq ll words)
20822 (while (> (length ll) lines)
20823 (setq w (1+ w))
20824 (setq ll (org-do-wrap words w)))
20825 ll))
20826 (t (error "Cannot wrap this")))))
20828 (defun org-do-wrap (words width)
20829 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20830 (let (lines line)
20831 (while words
20832 (setq line (pop words))
20833 (while (and words (< (+ (length line) (length (car words))) width))
20834 (setq line (concat line " " (pop words))))
20835 (setq lines (push line lines)))
20836 (nreverse lines)))
20838 (defun org-split-string (string &optional separators)
20839 "Splits STRING into substrings at SEPARATORS.
20840 No empty strings are returned if there are matches at the beginning
20841 and end of string."
20842 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20843 (start 0)
20844 notfirst
20845 (list nil))
20846 (while (and (string-match rexp string
20847 (if (and notfirst
20848 (= start (match-beginning 0))
20849 (< start (length string)))
20850 (1+ start) start))
20851 (< (match-beginning 0) (length string)))
20852 (setq notfirst t)
20853 (or (eq (match-beginning 0) 0)
20854 (and (eq (match-beginning 0) (match-end 0))
20855 (eq (match-beginning 0) start))
20856 (setq list
20857 (cons (substring string start (match-beginning 0))
20858 list)))
20859 (setq start (match-end 0)))
20860 (or (eq start (length string))
20861 (setq list
20862 (cons (substring string start)
20863 list)))
20864 (nreverse list)))
20866 (defun org-quote-vert (s)
20867 "Replace \"|\" with \"\\vert\"."
20868 (while (string-match "|" s)
20869 (setq s (replace-match "\\vert" t t s)))
20872 (defun org-uuidgen-p (s)
20873 "Is S an ID created by UUIDGEN?"
20874 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20876 (defun org-in-src-block-p (&optional inside)
20877 "Whether point is in a code source block.
20878 When INSIDE is non-nil, don't consider we are within a src block
20879 when point is at #+BEGIN_SRC or #+END_SRC."
20880 (let ((case-fold-search t) ov)
20881 (or (and (setq ov (overlays-at (point)))
20882 (memq 'org-block-background
20883 (overlay-properties (car ov))))
20884 (and (not inside)
20885 (save-match-data
20886 (save-excursion
20887 (beginning-of-line)
20888 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20890 (defun org-context ()
20891 "Return a list of contexts of the current cursor position.
20892 If several contexts apply, all are returned.
20893 Each context entry is a list with a symbol naming the context, and
20894 two positions indicating start and end of the context. Possible
20895 contexts are:
20897 :headline anywhere in a headline
20898 :headline-stars on the leading stars in a headline
20899 :todo-keyword on a TODO keyword (including DONE) in a headline
20900 :tags on the TAGS in a headline
20901 :priority on the priority cookie in a headline
20902 :item on the first line of a plain list item
20903 :item-bullet on the bullet/number of a plain list item
20904 :checkbox on the checkbox in a plain list item
20905 :table in an org-mode table
20906 :table-special on a special filed in a table
20907 :table-table in a table.el table
20908 :clocktable in a clocktable
20909 :src-block in a source block
20910 :link on a hyperlink
20911 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20912 :target on a <<target>>
20913 :radio-target on a <<<radio-target>>>
20914 :latex-fragment on a LaTeX fragment
20915 :latex-preview on a LaTeX fragment with overlaid preview image
20917 This function expects the position to be visible because it uses font-lock
20918 faces as a help to recognize the following contexts: :table-special, :link,
20919 and :keyword."
20920 (let* ((f (get-text-property (point) 'face))
20921 (faces (if (listp f) f (list f)))
20922 (case-fold-search t)
20923 (p (point)) clist o)
20924 ;; First the large context
20925 (cond
20926 ((org-at-heading-p t)
20927 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20928 (when (progn
20929 (beginning-of-line 1)
20930 (looking-at org-todo-line-tags-regexp))
20931 (push (org-point-in-group p 1 :headline-stars) clist)
20932 (push (org-point-in-group p 2 :todo-keyword) clist)
20933 (push (org-point-in-group p 4 :tags) clist))
20934 (goto-char p)
20935 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20936 (if (looking-at "\\[#[A-Z0-9]\\]")
20937 (push (org-point-in-group p 0 :priority) clist)))
20939 ((org-at-item-p)
20940 (push (org-point-in-group p 2 :item-bullet) clist)
20941 (push (list :item (point-at-bol)
20942 (save-excursion (org-end-of-item) (point)))
20943 clist)
20944 (and (org-at-item-checkbox-p)
20945 (push (org-point-in-group p 0 :checkbox) clist)))
20947 ((org-at-table-p)
20948 (push (list :table (org-table-begin) (org-table-end)) clist)
20949 (if (memq 'org-formula faces)
20950 (push (list :table-special
20951 (previous-single-property-change p 'face)
20952 (next-single-property-change p 'face)) clist)))
20953 ((org-at-table-p 'any)
20954 (push (list :table-table) clist)))
20955 (goto-char p)
20957 (let ((case-fold-search t))
20958 ;; New the "medium" contexts: clocktables, source blocks
20959 (cond ((org-in-clocktable-p)
20960 (push (list :clocktable
20961 (and (or (looking-at "#\\+BEGIN: clocktable")
20962 (search-backward "#+BEGIN: clocktable" nil t))
20963 (match-beginning 0))
20964 (and (re-search-forward "#\\+END:?" nil t)
20965 (match-end 0))) clist))
20966 ((org-in-src-block-p)
20967 (push (list :src-block
20968 (and (or (looking-at "#\\+BEGIN_SRC")
20969 (search-backward "#+BEGIN_SRC" nil t))
20970 (match-beginning 0))
20971 (and (search-forward "#+END_SRC" nil t)
20972 (match-beginning 0))) clist))))
20973 (goto-char p)
20975 ;; Now the small context
20976 (cond
20977 ((org-at-timestamp-p)
20978 (push (org-point-in-group p 0 :timestamp) clist))
20979 ((memq 'org-link faces)
20980 (push (list :link
20981 (previous-single-property-change p 'face)
20982 (next-single-property-change p 'face)) clist))
20983 ((memq 'org-special-keyword faces)
20984 (push (list :keyword
20985 (previous-single-property-change p 'face)
20986 (next-single-property-change p 'face)) clist))
20987 ((org-at-target-p)
20988 (push (org-point-in-group p 0 :target) clist)
20989 (goto-char (1- (match-beginning 0)))
20990 (if (looking-at org-radio-target-regexp)
20991 (push (org-point-in-group p 0 :radio-target) clist))
20992 (goto-char p))
20993 ((setq o (car (delq nil
20994 (mapcar
20995 (lambda (x)
20996 (if (memq x org-latex-fragment-image-overlays) x))
20997 (overlays-at (point))))))
20998 (push (list :latex-fragment
20999 (overlay-start o) (overlay-end o)) clist)
21000 (push (list :latex-preview
21001 (overlay-start o) (overlay-end o)) clist))
21002 ((org-inside-LaTeX-fragment-p)
21003 ;; FIXME: positions wrong.
21004 (push (list :latex-fragment (point) (point)) clist)))
21006 (setq clist (nreverse (delq nil clist)))
21007 clist))
21009 ;; FIXME: Compare with at-regexp-p Do we need both?
21010 (defun org-in-regexp (re &optional nlines visually)
21011 "Check if point is inside a match of regexp.
21012 Normally only the current line is checked, but you can include NLINES extra
21013 lines both before and after point into the search.
21014 If VISUALLY is set, require that the cursor is not after the match but
21015 really on, so that the block visually is on the match."
21016 (catch 'exit
21017 (let ((pos (point))
21018 (eol (point-at-eol (+ 1 (or nlines 0))))
21019 (inc (if visually 1 0)))
21020 (save-excursion
21021 (beginning-of-line (- 1 (or nlines 0)))
21022 (while (re-search-forward re eol t)
21023 (if (and (<= (match-beginning 0) pos)
21024 (>= (+ inc (match-end 0)) pos))
21025 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21027 (defun org-at-regexp-p (regexp)
21028 "Is point inside a match of REGEXP in the current line?"
21029 (catch 'exit
21030 (save-excursion
21031 (let ((pos (point)) (end (point-at-eol)))
21032 (beginning-of-line 1)
21033 (while (re-search-forward regexp end t)
21034 (if (and (<= (match-beginning 0) pos)
21035 (>= (match-end 0) pos))
21036 (throw 'exit t)))
21037 nil))))
21039 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21040 "Non-nil when point is between matches of START-RE and END-RE.
21042 Also return a non-nil value when point is on one of the matches.
21044 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21045 buffer positions. Default values are the positions of headlines
21046 surrounding the point.
21048 The functions returns a cons cell whose car (resp. cdr) is the
21049 position before START-RE (resp. after END-RE)."
21050 (save-match-data
21051 (let ((pos (point))
21052 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21053 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21054 beg end)
21055 (save-excursion
21056 ;; Point is on a block when on START-RE or if START-RE can be
21057 ;; found before it...
21058 (and (or (org-at-regexp-p start-re)
21059 (re-search-backward start-re limit-up t))
21060 (setq beg (match-beginning 0))
21061 ;; ... and END-RE after it...
21062 (goto-char (match-end 0))
21063 (re-search-forward end-re limit-down t)
21064 (> (setq end (match-end 0)) pos)
21065 ;; ... without another START-RE in-between.
21066 (goto-char (match-beginning 0))
21067 (not (re-search-backward start-re (1+ beg) t))
21068 ;; Return value.
21069 (cons beg end))))))
21071 (defun org-in-block-p (names)
21072 "Non-nil when point belongs to a block whose name belongs to NAMES.
21074 NAMES is a list of strings containing names of blocks.
21076 Return first block name matched, or nil. Beware that in case of
21077 nested blocks, the returned name may not belong to the closest
21078 block from point."
21079 (save-match-data
21080 (catch 'exit
21081 (let ((case-fold-search t)
21082 (lim-up (save-excursion (outline-previous-heading)))
21083 (lim-down (save-excursion (outline-next-heading))))
21084 (mapc (lambda (name)
21085 (let ((n (regexp-quote name)))
21086 (when (org-between-regexps-p
21087 (concat "^[ \t]*#\\+begin_" n)
21088 (concat "^[ \t]*#\\+end_" n)
21089 lim-up lim-down)
21090 (throw 'exit n))))
21091 names))
21092 nil)))
21094 (defun org-occur-in-agenda-files (regexp &optional nlines)
21095 "Call `multi-occur' with buffers for all agenda files."
21096 (interactive "sOrg-files matching: \np")
21097 (let* ((files (org-agenda-files))
21098 (tnames (mapcar 'file-truename files))
21099 (extra org-agenda-text-search-extra-files)
21101 (when (eq (car extra) 'agenda-archives)
21102 (setq extra (cdr extra))
21103 (setq files (org-add-archive-files files)))
21104 (while (setq f (pop extra))
21105 (unless (member (file-truename f) tnames)
21106 (add-to-list 'files f 'append)
21107 (add-to-list 'tnames (file-truename f) 'append)))
21108 (multi-occur
21109 (mapcar (lambda (x)
21110 (with-current-buffer
21111 (or (get-file-buffer x) (find-file-noselect x))
21112 (widen)
21113 (current-buffer)))
21114 files)
21115 regexp)))
21117 (if (boundp 'occur-mode-find-occurrence-hook)
21118 ;; Emacs 23
21119 (add-hook 'occur-mode-find-occurrence-hook
21120 (lambda ()
21121 (when (derived-mode-p 'org-mode)
21122 (org-reveal))))
21123 ;; Emacs 22
21124 (defadvice occur-mode-goto-occurrence
21125 (after org-occur-reveal activate)
21126 (and (derived-mode-p 'org-mode) (org-reveal)))
21127 (defadvice occur-mode-goto-occurrence-other-window
21128 (after org-occur-reveal activate)
21129 (and (derived-mode-p 'org-mode) (org-reveal)))
21130 (defadvice occur-mode-display-occurrence
21131 (after org-occur-reveal activate)
21132 (when (derived-mode-p 'org-mode)
21133 (let ((pos (occur-mode-find-occurrence)))
21134 (with-current-buffer (marker-buffer pos)
21135 (save-excursion
21136 (goto-char pos)
21137 (org-reveal)))))))
21139 (defun org-occur-link-in-agenda-files ()
21140 "Create a link and search for it in the agendas.
21141 The link is not stored in `org-stored-links', it is just created
21142 for the search purpose."
21143 (interactive)
21144 (let ((link (condition-case nil
21145 (org-store-link nil)
21146 (error "Unable to create a link to here"))))
21147 (org-occur-in-agenda-files (regexp-quote link))))
21149 (defun org-reverse-string (string)
21150 "Return the reverse of STRING."
21151 (apply 'string (reverse (string-to-list string))))
21153 (defun org-uniquify (list)
21154 "Remove duplicate elements from LIST."
21155 (let (res)
21156 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21157 res))
21159 (defun org-delete-all (elts list)
21160 "Remove all elements in ELTS from LIST."
21161 (while elts
21162 (setq list (delete (pop elts) list)))
21163 list)
21165 (defun org-count (cl-item cl-seq)
21166 "Count the number of occurrences of ITEM in SEQ.
21167 Taken from `count' in cl-seq.el with all keyword arguments removed."
21168 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21169 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21170 (while (< cl-start cl-end)
21171 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21172 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21173 (setq cl-start (1+ cl-start)))
21174 cl-count))
21176 (defun org-remove-if (predicate seq)
21177 "Remove everything from SEQ that fulfills PREDICATE."
21178 (let (res e)
21179 (while seq
21180 (setq e (pop seq))
21181 (if (not (funcall predicate e)) (push e res)))
21182 (nreverse res)))
21184 (defun org-remove-if-not (predicate seq)
21185 "Remove everything from SEQ that does not fulfill PREDICATE."
21186 (let (res e)
21187 (while seq
21188 (setq e (pop seq))
21189 (if (funcall predicate e) (push e res)))
21190 (nreverse res)))
21192 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21193 "Reduce two-argument FUNCTION across SEQ.
21194 Taken from `reduce' in cl-seq.el with all keyword arguments but
21195 \":initial-value\" removed."
21196 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21197 (cadr (memq :initial-value cl-keys)))
21198 (cl-seq (pop cl-seq))
21199 (t (funcall cl-func)))))
21200 (while cl-seq
21201 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21202 cl-accum))
21204 (defun org-back-over-empty-lines ()
21205 "Move backwards over whitespace, to the beginning of the first empty line.
21206 Returns the number of empty lines passed."
21207 (let ((pos (point)))
21208 (if (cdr (assoc 'heading org-blank-before-new-entry))
21209 (skip-chars-backward " \t\n\r")
21210 (unless (eobp)
21211 (forward-line -1)))
21212 (beginning-of-line 2)
21213 (goto-char (min (point) pos))
21214 (count-lines (point) pos)))
21216 (defun org-skip-whitespace ()
21217 (skip-chars-forward " \t\n\r"))
21219 (defun org-point-in-group (point group &optional context)
21220 "Check if POINT is in match-group GROUP.
21221 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21222 match. If the match group does not exist or point is not inside it,
21223 return nil."
21224 (and (match-beginning group)
21225 (>= point (match-beginning group))
21226 (<= point (match-end group))
21227 (if context
21228 (list context (match-beginning group) (match-end group))
21229 t)))
21231 (defun org-switch-to-buffer-other-window (&rest args)
21232 "Switch to buffer in a second window on the current frame.
21233 In particular, do not allow pop-up frames.
21234 Returns the newly created buffer."
21235 (org-no-popups
21236 (apply 'switch-to-buffer-other-window args)))
21238 (defun org-combine-plists (&rest plists)
21239 "Create a single property list from all plists in PLISTS.
21240 The process starts by copying the first list, and then setting properties
21241 from the other lists. Settings in the last list are the most significant
21242 ones and overrule settings in the other lists."
21243 (let ((rtn (copy-sequence (pop plists)))
21244 p v ls)
21245 (while plists
21246 (setq ls (pop plists))
21247 (while ls
21248 (setq p (pop ls) v (pop ls))
21249 (setq rtn (plist-put rtn p v))))
21250 rtn))
21252 (defun org-replace-escapes (string table)
21253 "Replace %-escapes in STRING with values in TABLE.
21254 TABLE is an association list with keys like \"%a\" and string values.
21255 The sequences in STRING may contain normal field width and padding information,
21256 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21257 so values can contain further %-escapes if they are define later in TABLE."
21258 (let ((tbl (copy-alist table))
21259 (case-fold-search nil)
21260 (pchg 0)
21261 e re rpl)
21262 (while (setq e (pop tbl))
21263 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21264 (when (and (cdr e) (string-match re (cdr e)))
21265 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21266 (safe "SREF"))
21267 (add-text-properties 0 3 (list 'sref sref) safe)
21268 (setcdr e (replace-match safe t t (cdr e)))))
21269 (while (string-match re string)
21270 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21271 (cdr e)))
21272 (setq string (replace-match rpl t t string))))
21273 (while (setq pchg (next-property-change pchg string))
21274 (let ((sref (get-text-property pchg 'sref string)))
21275 (when (and sref (string-match "SREF" string pchg))
21276 (setq string (replace-match sref t t string)))))
21277 string))
21279 (defun org-sublist (list start end)
21280 "Return a section of LIST, from START to END.
21281 Counting starts at 1."
21282 (let (rtn (c start))
21283 (setq list (nthcdr (1- start) list))
21284 (while (and list (<= c end))
21285 (push (pop list) rtn)
21286 (setq c (1+ c)))
21287 (nreverse rtn)))
21289 (defun org-find-base-buffer-visiting (file)
21290 "Like `find-buffer-visiting' but always return the base buffer and
21291 not an indirect buffer."
21292 (let ((buf (or (get-file-buffer file)
21293 (find-buffer-visiting file))))
21294 (if buf
21295 (or (buffer-base-buffer buf) buf)
21296 nil)))
21298 (defun org-image-file-name-regexp (&optional extensions)
21299 "Return regexp matching the file names of images.
21300 If EXTENSIONS is given, only match these."
21301 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21302 (image-file-name-regexp)
21303 (let ((image-file-name-extensions
21304 (or extensions
21305 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21306 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21307 (concat "\\."
21308 (regexp-opt (nconc (mapcar 'upcase
21309 image-file-name-extensions)
21310 image-file-name-extensions)
21312 "\\'"))))
21314 (defun org-file-image-p (file &optional extensions)
21315 "Return non-nil if FILE is an image."
21316 (save-match-data
21317 (string-match (org-image-file-name-regexp extensions) file)))
21319 (defun org-get-cursor-date (&optional with-time)
21320 "Return the date at cursor in as a time.
21321 This works in the calendar and in the agenda, anywhere else it just
21322 returns the current time.
21323 If WITH-TIME is non-nil, returns the time of the event at point (in
21324 the agenda) or the current time of the day."
21325 (let (date day defd tp tm hod mod)
21326 (when with-time
21327 (setq tp (get-text-property (point) 'time))
21328 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21329 (setq hod (string-to-number (match-string 1 tp))
21330 mod (string-to-number (match-string 2 tp))))
21331 (or tp (setq hod (nth 2 (decode-time (current-time)))
21332 mod (nth 1 (decode-time (current-time))))))
21333 (cond
21334 ((eq major-mode 'calendar-mode)
21335 (setq date (calendar-cursor-to-date)
21336 defd (encode-time 0 (or mod 0) (or hod 0)
21337 (nth 1 date) (nth 0 date) (nth 2 date))))
21338 ((eq major-mode 'org-agenda-mode)
21339 (setq day (get-text-property (point) 'day))
21340 (if day
21341 (setq date (calendar-gregorian-from-absolute day)
21342 defd (encode-time 0 (or mod 0) (or hod 0)
21343 (nth 1 date) (nth 0 date) (nth 2 date))))))
21344 (or defd (current-time))))
21346 (defun org-mark-subtree (&optional up)
21347 "Mark the current subtree.
21348 This puts point at the start of the current subtree, and mark at
21349 the end. If a numeric prefix UP is given, move up into the
21350 hierarchy of headlines by UP levels before marking the subtree."
21351 (interactive "P")
21352 (org-with-limited-levels
21353 (cond ((org-at-heading-p) (beginning-of-line))
21354 ((org-before-first-heading-p) (error "Not in a subtree"))
21355 (t (outline-previous-visible-heading 1))))
21356 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21357 (if (org-called-interactively-p 'any)
21358 (call-interactively 'org-mark-element)
21359 (org-mark-element)))
21362 ;;; Macros
21364 ;; Macros are expanded with `org-macro-replace-all', which relies
21365 ;; internally on `org-macro-expand'.
21367 ;; Default templates for expansion are stored in the buffer-local
21368 ;; variable `org-macro-templates'. This variable is updated by
21369 ;; `org-macro-initialize-templates'.
21371 ;; Along with macros defined through #+MACRO: keyword, default
21372 ;; templates include the following hard-coded macros:
21373 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21374 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21376 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21377 ;; {{{title}}} will also be provided.
21380 (defvar org-macro-templates nil
21381 "Alist containing all macro templates in current buffer.
21382 Associations are in the shape of (NAME . TEMPLATE) where NAME
21383 stands for macro's name and template for its replacement value,
21384 both as strings. This is an internal variable. Do not set it
21385 directly, use instead:
21387 #+MACRO: name template")
21388 (make-variable-buffer-local 'org-macro-templates)
21390 (defun org-macro-expand (macro templates)
21391 "Return expanded MACRO, as a string.
21392 MACRO is an object, obtained, for example, with
21393 `org-element-context'. TEMPLATES is an alist of templates used
21394 for expansion. See `org-macro-templates' for a buffer-local
21395 default value. Return nil if no template was found."
21396 (let ((template
21397 ;; Macro names are case-insensitive.
21398 (cdr (assoc-string (org-element-property :key macro) templates t))))
21399 (when template
21400 (let ((value (replace-regexp-in-string
21401 "\\$[0-9]+"
21402 (lambda (arg)
21403 (or (nth (1- (string-to-number (substring arg 1)))
21404 (org-element-property :args macro))
21405 ;; No argument provided: remove
21406 ;; place-holder.
21407 ""))
21408 template)))
21409 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21410 (when (string-match "\\`(eval\\>" value)
21411 (setq value (eval (read value))))
21412 ;; Return string.
21413 (format "%s" (or value ""))))))
21415 (defun org-macro-replace-all (templates)
21416 "Replace all macros in current buffer by their expansion.
21417 TEMPLATES is an alist of templates used for expansion. See
21418 `org-macro-templates' for a buffer-local default value."
21419 (save-excursion
21420 (goto-char (point-min))
21421 (let (record)
21422 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21423 (let ((object (org-element-context)))
21424 (when (eq (org-element-type object) 'macro)
21425 (let* ((value (org-macro-expand object templates))
21426 (begin (org-element-property :begin object))
21427 (signature (list begin
21428 object
21429 (org-element-property :args object))))
21430 ;; Avoid circular dependencies by checking if the same
21431 ;; macro with the same arguments is expanded at the same
21432 ;; position twice.
21433 (if (member signature record)
21434 (error "Circular macro expansion: %s"
21435 (org-element-property :key object))
21436 (when value
21437 (push signature record)
21438 (delete-region
21439 begin
21440 ;; Preserve white spaces after the macro.
21441 (progn (goto-char (org-element-property :end object))
21442 (skip-chars-backward " \t")
21443 (point)))
21444 ;; Leave point before replacement in case of recursive
21445 ;; expansions.
21446 (save-excursion (insert value)))))))))))
21448 (defun org-macro-initialize-templates ()
21449 "Collect macro templates defined in current buffer.
21450 Templates are stored in buffer-local variable
21451 `org-macro-templates'. In addition to buffer-defined macros, the
21452 function installs the following ones: \"property\",
21453 \"time\". and, if the buffer is associated to a file,
21454 \"input-file\" and \"modification-time\"."
21455 (let ((case-fold-search t)
21456 (set-template
21457 (lambda (cell)
21458 ;; Add CELL to `org-macro-templates' if there's no
21459 ;; association matching its name already. Otherwise,
21460 ;; replace old association with the new one in that
21461 ;; variable.
21462 (let ((old-template (assoc (car cell) org-macro-templates)))
21463 (if old-template (setcdr old-template (cdr cell))
21464 (push cell org-macro-templates))))))
21465 ;; Install buffer-local macros.
21466 (org-with-wide-buffer
21467 (goto-char (point-min))
21468 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21469 (let ((element (org-element-at-point)))
21470 (when (eq (org-element-type element) 'keyword)
21471 (let ((value (org-element-property :value element)))
21472 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21473 (funcall set-template
21474 (cons (match-string 1 value)
21475 (or (match-string 2 value) "")))))))))
21476 ;; Install hard-coded macros.
21477 (mapc (lambda (cell) (funcall set-template cell))
21478 (list
21479 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21480 (cons "time" "(eval (format-time-string \"$1\"))")))
21481 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21482 (when (and visited-file (file-exists-p visited-file))
21483 (mapc (lambda (cell) (funcall set-template cell))
21484 (list
21485 (cons "input-file" (file-name-nondirectory visited-file))
21486 (cons "modification-time"
21487 (format "(eval (format-time-string \"$1\" '%s))"
21488 (prin1-to-string
21489 (nth 5 (file-attributes visited-file)))))))))))
21492 ;;; Indentation
21494 (defun org-indent-line ()
21495 "Indent line depending on context."
21496 (interactive)
21497 (let* ((pos (point))
21498 (itemp (org-at-item-p))
21499 (case-fold-search t)
21500 (org-drawer-regexp (or org-drawer-regexp "\000"))
21501 (inline-task-p (and (featurep 'org-inlinetask)
21502 (org-inlinetask-in-task-p)))
21503 (inline-re (and inline-task-p
21504 (org-inlinetask-outline-regexp)))
21505 column)
21506 (if (and orgstruct-is-++ (eq pos (point)))
21507 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21508 (indent-according-to-mode))
21509 (beginning-of-line 1)
21510 (cond
21511 ;; Headings
21512 ((looking-at org-outline-regexp) (setq column 0))
21513 ;; Footnote definition
21514 ((looking-at org-footnote-definition-re) (setq column 0))
21515 ;; Literal examples
21516 ((looking-at "[ \t]*:\\( \\|$\\)")
21517 (setq column (org-get-indentation))) ; do nothing
21518 ;; Lists
21519 ((ignore-errors (goto-char (org-in-item-p)))
21520 (setq column (if itemp
21521 (org-get-indentation)
21522 (org-list-item-body-column (point))))
21523 (goto-char pos))
21524 ;; Drawers
21525 ((and (looking-at "[ \t]*:END:")
21526 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21527 (save-excursion
21528 (goto-char (1- (match-beginning 1)))
21529 (setq column (current-column))))
21530 ;; Special blocks
21531 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21532 (save-excursion
21533 (re-search-backward
21534 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21535 (setq column (org-get-indentation (match-string 0))))
21536 ((and (not (looking-at "[ \t]*#\\+begin_"))
21537 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21538 (save-excursion
21539 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21540 (setq column
21541 (cond ((equal (downcase (match-string 1)) "src")
21542 ;; src blocks: let `org-edit-src-exit' handle them
21543 (org-get-indentation))
21544 ((equal (downcase (match-string 1)) "example")
21545 (max (org-get-indentation)
21546 (org-get-indentation (match-string 0))))
21548 (org-get-indentation (match-string 0))))))
21549 ;; This line has nothing special, look at the previous relevant
21550 ;; line to compute indentation
21552 (beginning-of-line 0)
21553 (while (and (not (bobp))
21554 (not (looking-at org-table-line-regexp))
21555 (not (looking-at org-drawer-regexp))
21556 ;; When point started in an inline task, do not move
21557 ;; above task starting line.
21558 (not (and inline-task-p (looking-at inline-re)))
21559 ;; Skip drawers, blocks, empty lines, verbatim,
21560 ;; comments, tables, footnotes definitions, lists,
21561 ;; inline tasks.
21562 (or (and (looking-at "[ \t]*:END:")
21563 (re-search-backward org-drawer-regexp nil t))
21564 (and (looking-at "[ \t]*#\\+end_")
21565 (re-search-backward "[ \t]*#\\+begin_"nil t))
21566 (looking-at "[ \t]*[\n:#|]")
21567 (looking-at org-footnote-definition-re)
21568 (and (ignore-errors (goto-char (org-in-item-p)))
21569 (goto-char
21570 (org-list-get-top-point (org-list-struct))))
21571 (and (not inline-task-p)
21572 (featurep 'org-inlinetask)
21573 (org-inlinetask-in-task-p)
21574 (or (org-inlinetask-goto-beginning) t))))
21575 (beginning-of-line 0))
21576 (cond
21577 ;; There was an heading above.
21578 ((looking-at "\\*+[ \t]+")
21579 (if (not org-adapt-indentation)
21580 (setq column 0)
21581 (goto-char (match-end 0))
21582 (setq column (current-column))))
21583 ;; A drawer had started and is unfinished
21584 ((looking-at org-drawer-regexp)
21585 (goto-char (1- (match-beginning 1)))
21586 (setq column (current-column)))
21587 ;; Else, nothing noticeable found: get indentation and go on.
21588 (t (setq column (org-get-indentation))))))
21589 ;; Now apply indentation and move cursor accordingly
21590 (goto-char pos)
21591 (if (<= (current-column) (current-indentation))
21592 (org-indent-line-to column)
21593 (save-excursion (org-indent-line-to column)))
21594 ;; Special polishing for properties, see `org-property-format'
21595 (setq column (current-column))
21596 (beginning-of-line 1)
21597 (if (looking-at
21598 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21599 (replace-match (concat (match-string 1)
21600 (format org-property-format
21601 (match-string 2) (match-string 3)))
21602 t t))
21603 (org-move-to-column column))))
21605 (defun org-indent-drawer ()
21606 "Indent the drawer at point."
21607 (interactive)
21608 (let ((p (point))
21609 (e (and (save-excursion (re-search-forward ":END:" nil t))
21610 (match-end 0)))
21611 (folded
21612 (save-excursion
21613 (end-of-line)
21614 (when (overlays-at (point))
21615 (member 'invisible (overlay-properties
21616 (car (overlays-at (point)))))))))
21617 (when folded (org-cycle))
21618 (indent-for-tab-command)
21619 (while (and (move-beginning-of-line 2) (< (point) e))
21620 (indent-for-tab-command))
21621 (goto-char p)
21622 (when folded (org-cycle)))
21623 (message "Drawer at point indented"))
21625 (defun org-indent-block ()
21626 "Indent the block at point."
21627 (interactive)
21628 (let ((p (point))
21629 (case-fold-search t)
21630 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21631 (match-end 0)))
21632 (folded
21633 (save-excursion
21634 (end-of-line)
21635 (when (overlays-at (point))
21636 (member 'invisible (overlay-properties
21637 (car (overlays-at (point)))))))))
21638 (when folded (org-cycle))
21639 (indent-for-tab-command)
21640 (while (and (move-beginning-of-line 2) (< (point) e))
21641 (indent-for-tab-command))
21642 (goto-char p)
21643 (when folded (org-cycle)))
21644 (message "Block at point indented"))
21646 (defun org-indent-region (start end)
21647 "Indent region."
21648 (interactive "r")
21649 (save-excursion
21650 (let ((line-end (org-current-line end)))
21651 (goto-char start)
21652 (while (< (org-current-line) line-end)
21653 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21654 (t (call-interactively 'org-indent-line)))
21655 (move-beginning-of-line 2)))))
21658 ;;; Filling
21660 ;; We use our own fill-paragraph and auto-fill functions.
21662 ;; `org-fill-paragraph' relies on adaptive filling and context
21663 ;; checking. Appropriate `fill-prefix' is computed with
21664 ;; `org-adaptive-fill-function'.
21666 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21667 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21668 ;; `org-adaptive-fill-function' value. Internally,
21669 ;; `org-comment-line-break-function' breaks the line.
21671 ;; `org-setup-filling' installs filling and auto-filling related
21672 ;; variables during `org-mode' initialization.
21674 (defun org-setup-filling ()
21675 (interactive)
21676 ;; Prevent auto-fill from inserting unwanted new items.
21677 (when (boundp 'fill-nobreak-predicate)
21678 (org-set-local
21679 'fill-nobreak-predicate
21680 (org-uniquify
21681 (append fill-nobreak-predicate
21682 '(org-fill-paragraph-separate-nobreak-p
21683 org-fill-line-break-nobreak-p
21684 org-fill-paragraph-with-timestamp-nobreak-p)))))
21685 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21686 (org-set-local 'auto-fill-inhibit-regexp nil)
21687 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21688 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21689 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21691 (defvar org-element-paragraph-separate) ; org-element.el
21692 (defun org-fill-paragraph-separate-nobreak-p ()
21693 "Non-nil when a line break at point would insert a new item."
21694 (looking-at (substring org-element-paragraph-separate 1)))
21696 (defun org-fill-line-break-nobreak-p ()
21697 "Non-nil when a line break at point would create an Org line break."
21698 (save-excursion
21699 (skip-chars-backward "[ \t]")
21700 (skip-chars-backward "\\\\")
21701 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21703 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21704 "Non-nil when a line break at point would insert a new item."
21705 (and (org-at-timestamp-p t)
21706 (not (looking-at org-ts-regexp-both))))
21708 (declare-function message-in-body-p "message" ())
21709 (defvar orgtbl-line-start-regexp) ; From org-table.el
21710 (defun org-adaptive-fill-function ()
21711 "Compute a fill prefix for the current line.
21712 Return fill prefix, as a string, or nil if current line isn't
21713 meant to be filled."
21714 (let (prefix)
21715 (catch 'exit
21716 (when (derived-mode-p 'message-mode)
21717 (save-excursion
21718 (beginning-of-line)
21719 (cond ((or (not (message-in-body-p))
21720 (looking-at orgtbl-line-start-regexp))
21721 (throw 'exit nil))
21722 ((looking-at message-cite-prefix-regexp)
21723 (throw 'exit (match-string-no-properties 0)))
21724 ((looking-at org-outline-regexp)
21725 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21726 (org-with-wide-buffer
21727 (let* ((p (line-beginning-position))
21728 (element (save-excursion (beginning-of-line)
21729 (org-element-at-point)))
21730 (type (org-element-type element))
21731 (post-affiliated (org-element-property :post-affiliated element)))
21732 (unless (and post-affiliated (< p post-affiliated))
21733 (case type
21734 (comment (looking-at "[ \t]*# ?") (match-string 0))
21735 (footnote-definition "")
21736 ((item plain-list)
21737 (make-string (org-list-item-body-column
21738 (or post-affiliated
21739 (org-element-property :begin element)))
21740 ? ))
21741 (paragraph
21742 ;; Fill prefix is usually the same as the current line,
21743 ;; except if the paragraph is at the beginning of an item.
21744 (let ((parent (org-element-property :parent element)))
21745 (cond ((eq (org-element-type parent) 'item)
21746 (make-string (org-list-item-body-column
21747 (org-element-property :begin parent))
21748 ? ))
21749 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21750 (match-string 0))
21751 (t ""))))
21752 (comment-block
21753 ;; Only fill contents if P is within block boundaries.
21754 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21755 (forward-line)
21756 (point)))
21757 (cend (save-excursion
21758 (goto-char (org-element-property :end element))
21759 (skip-chars-backward " \r\t\n")
21760 (line-beginning-position))))
21761 (when (and (>= p cbeg) (< p cend))
21762 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21763 (match-string 0)
21764 "")))))))))))
21766 (declare-function message-goto-body "message" ())
21767 (defvar message-cite-prefix-regexp) ; From message.el
21768 (defvar org-element-all-objects) ; From org-element.el
21769 (defun org-fill-paragraph (&optional justify)
21770 "Fill element at point, when applicable.
21772 This function only applies to comment blocks, comments, example
21773 blocks and paragraphs. Also, as a special case, re-align table
21774 when point is at one.
21776 If JUSTIFY is non-nil (interactively, with prefix argument),
21777 justify as well. If `sentence-end-double-space' is non-nil, then
21778 period followed by one space does not end a sentence, so don't
21779 break a line there. The variable `fill-column' controls the
21780 width for filling.
21782 For convenience, when point is at a plain list, an item or
21783 a footnote definition, try to fill the first paragraph within."
21784 (interactive)
21785 (if (and (derived-mode-p 'message-mode)
21786 (or (not (message-in-body-p))
21787 (save-excursion (move-beginning-of-line 1)
21788 (looking-at message-cite-prefix-regexp))))
21789 ;; First ensure filling is correct in message-mode.
21790 (let ((fill-paragraph-function
21791 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21792 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21793 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21794 (paragraph-separate
21795 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21796 (fill-paragraph nil))
21797 (save-excursion
21798 ;; Move to end of line in order to get the first paragraph
21799 ;; within a plain list or a footnote definition.
21800 (end-of-line)
21801 (let ((element (org-element-at-point)))
21802 ;; First check if point is in a blank line at the beginning of
21803 ;; the buffer. In that case, ignore filling.
21804 (if (< (point) (org-element-property :begin element)) t
21805 (case (org-element-type element)
21806 ;; Use major mode filling function is src blocks.
21807 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21808 ;; Align Org tables, leave table.el tables as-is.
21809 (table-row (org-table-align) t)
21810 (table
21811 (when (eq (org-element-property :type element) 'org)
21812 (org-table-align))
21814 (paragraph
21815 ;; Paragraphs may contain `line-break' type objects.
21816 (let ((beg (max (point-min)
21817 (org-element-property :contents-begin element)))
21818 (end (min (point-max)
21819 (org-element-property :contents-end element))))
21820 ;; Do nothing if point is at an affiliated keyword.
21821 (if (< (point) beg) t
21822 (when (derived-mode-p 'message-mode)
21823 ;; In `message-mode', do not fill following
21824 ;; citation in current paragraph nor text before
21825 ;; message body.
21826 (let ((body-start (save-excursion (message-goto-body))))
21827 (when body-start (setq beg (max body-start beg))))
21828 (when (save-excursion
21829 (re-search-forward
21830 (concat "^" message-cite-prefix-regexp) end t))
21831 (setq end (match-beginning 0))))
21832 ;; Fill paragraph, taking line breaks into
21833 ;; consideration. For that, slice the paragraph
21834 ;; using line breaks as separators, and fill the
21835 ;; parts in reverse order to avoid messing with
21836 ;; markers.
21837 (save-excursion
21838 (goto-char end)
21839 (mapc
21840 (lambda (pos)
21841 (fill-region-as-paragraph pos (point) justify)
21842 (goto-char pos))
21843 ;; Find the list of ending positions for line
21844 ;; breaks in the current paragraph. Add paragraph
21845 ;; beginning to include first slice.
21846 (nreverse
21847 (cons
21849 (org-element-map
21850 (org-element--parse-objects
21851 beg end nil org-element-all-objects)
21852 'line-break
21853 (lambda (lb) (org-element-property :end lb)))))))
21854 t)))
21855 ;; Contents of `comment-block' type elements should be
21856 ;; filled as plain text, but only if point is within block
21857 ;; markers.
21858 (comment-block
21859 (let* ((case-fold-search t)
21860 (beg (save-excursion
21861 (goto-char (org-element-property :begin element))
21862 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21863 (forward-line)
21864 (point)))
21865 (end (save-excursion
21866 (goto-char (org-element-property :end element))
21867 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21868 (line-beginning-position))))
21869 (when (and (>= (point) beg) (< (point) end))
21870 (fill-region-as-paragraph
21871 (save-excursion
21872 (end-of-line)
21873 (re-search-backward "^[ \t]*$" beg 'move)
21874 (line-beginning-position))
21875 (save-excursion
21876 (beginning-of-line)
21877 (re-search-forward "^[ \t]*$" end 'move)
21878 (line-beginning-position))
21879 justify)))
21881 ;; Fill comments.
21882 (comment (fill-comment-paragraph justify))
21883 ;; Ignore every other element.
21884 (otherwise t)))))))
21886 (defun org-auto-fill-function ()
21887 "Auto-fill function."
21888 ;; Check if auto-filling is meaningful.
21889 (let ((fc (current-fill-column)))
21890 (when (and fc (> (current-column) fc))
21891 (let* ((fill-prefix (org-adaptive-fill-function))
21892 ;; Enforce empty fill prefix, if required. Otherwise, it
21893 ;; will be computed again.
21894 (adaptive-fill-mode (not (equal fill-prefix ""))))
21895 (when fill-prefix (do-auto-fill))))))
21897 (defun org-comment-line-break-function (&optional soft)
21898 "Break line at point and indent, continuing comment if within one.
21899 The inserted newline is marked hard if variable
21900 `use-hard-newlines' is true, unless optional argument SOFT is
21901 non-nil."
21902 (if soft (insert-and-inherit ?\n) (newline 1))
21903 (save-excursion (forward-char -1) (delete-horizontal-space))
21904 (delete-horizontal-space)
21905 (indent-to-left-margin)
21906 (insert-before-markers-and-inherit fill-prefix))
21909 ;;; Comments
21911 ;; Org comments syntax is quite complex. It requires the entire line
21912 ;; to be just a comment. Also, even with the right syntax at the
21913 ;; beginning of line, some some elements (i.e. verse-block or
21914 ;; example-block) don't accept comments. Usual Emacs comment commands
21915 ;; cannot cope with those requirements. Therefore, Org replaces them.
21917 ;; Org still relies on `comment-dwim', but cannot trust
21918 ;; `comment-only-p'. So, `comment-region-function' and
21919 ;; `uncomment-region-function' both point
21920 ;; to`org-comment-or-uncomment-region'. Eventually,
21921 ;; `org-insert-comment' takes care of insertion of comments at the
21922 ;; beginning of line.
21924 ;; `org-setup-comments-handling' install comments related variables
21925 ;; during `org-mode' initialization.
21927 (defun org-setup-comments-handling ()
21928 (interactive)
21929 (org-set-local 'comment-use-syntax nil)
21930 (org-set-local 'comment-start "# ")
21931 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21932 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21933 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21934 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21936 (defun org-insert-comment ()
21937 "Insert an empty comment above current line.
21938 If the line is empty, insert comment at its beginning."
21939 (beginning-of-line)
21940 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21941 (org-indent-line)
21942 (insert "# "))
21944 (defvar comment-empty-lines) ; From newcomment.el.
21945 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21946 "Comment or uncomment each non-blank line in the region.
21947 Uncomment each non-blank line between BEG and END if it only
21948 contains commented lines. Otherwise, comment them."
21949 (save-restriction
21950 ;; Restrict region
21951 (narrow-to-region (save-excursion (goto-char beg)
21952 (skip-chars-forward " \r\t\n" end)
21953 (line-beginning-position))
21954 (save-excursion (goto-char end)
21955 (skip-chars-backward " \r\t\n" beg)
21956 (line-end-position)))
21957 (let ((uncommentp
21958 ;; UNCOMMENTP is non-nil when every non blank line between
21959 ;; BEG and END is a comment.
21960 (save-excursion
21961 (goto-char (point-min))
21962 (while (and (not (eobp))
21963 (let ((element (org-element-at-point)))
21964 (and (eq (org-element-type element) 'comment)
21965 (goto-char (min (point-max)
21966 (org-element-property
21967 :end element)))))))
21968 (eobp))))
21969 (if uncommentp
21970 ;; Only blank lines and comments in region: uncomment it.
21971 (save-excursion
21972 (goto-char (point-min))
21973 (while (not (eobp))
21974 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21975 (replace-match "" nil nil nil 1))
21976 (forward-line)))
21977 ;; Comment each line in region.
21978 (let ((min-indent (point-max)))
21979 ;; First find the minimum indentation across all lines.
21980 (save-excursion
21981 (goto-char (point-min))
21982 (while (and (not (eobp)) (not (zerop min-indent)))
21983 (unless (looking-at "[ \t]*$")
21984 (setq min-indent (min min-indent (current-indentation))))
21985 (forward-line)))
21986 ;; Then loop over all lines.
21987 (save-excursion
21988 (goto-char (point-min))
21989 (while (not (eobp))
21990 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21991 (org-move-to-column min-indent t)
21992 (insert comment-start))
21993 (forward-line))))))))
21996 ;;; Planning
21998 ;; This section contains tools to operate on timestamp objects, as
21999 ;; returned by, e.g. `org-element-context'.
22001 (defun org-timestamp-has-time-p (timestamp)
22002 "Non-nil when TIMESTAMP has a time specified."
22003 (org-element-property :hour-start timestamp))
22005 (defun org-timestamp-format (timestamp format &optional end utc)
22006 "Format a TIMESTAMP element into a string.
22008 FORMAT is a format specifier to be passed to
22009 `format-time-string'.
22011 When optional argument END is non-nil, use end of date-range or
22012 time-range, if possible.
22014 When optional argument UTC is non-nil, time will be expressed as
22015 Universal Time."
22016 (format-time-string
22017 format
22018 (apply 'encode-time
22019 (cons 0
22020 (mapcar
22021 (lambda (prop) (or (org-element-property prop timestamp) 0))
22022 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22023 '(:minute-start :hour-start :day-start :month-start
22024 :year-start)))))
22025 utc))
22027 (defun org-timestamp-split-range (timestamp &optional end)
22028 "Extract a timestamp object from a date or time range.
22030 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22031 the end of the range. Otherwise, extract its start.
22033 Return a new timestamp object sharing the same parent as
22034 TIMESTAMP."
22035 (let ((type (org-element-property :type timestamp)))
22036 (if (memq type '(active inactive diary)) timestamp
22037 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22038 ;; Set new type.
22039 (org-element-put-property
22040 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22041 ;; Copy start properties over end properties if END is
22042 ;; non-nil. Otherwise, copy end properties over `start' ones.
22043 (let ((p-alist '((:minute-start . :minute-end)
22044 (:hour-start . :hour-end)
22045 (:day-start . :day-end)
22046 (:month-start . :month-end)
22047 (:year-start . :year-end))))
22048 (dolist (p-cell p-alist)
22049 (org-element-put-property
22050 split-ts
22051 (funcall (if end 'car 'cdr) p-cell)
22052 (org-element-property
22053 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22054 ;; Eventually refresh `:raw-value'.
22055 (org-element-put-property split-ts :raw-value nil)
22056 (org-element-put-property
22057 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22059 (defun org-timestamp-translate (timestamp &optional boundary)
22060 "Apply `org-translate-time' on a TIMESTAMP object.
22061 When optional argument BOUNDARY is non-nil, it is either the
22062 symbol `start' or `end'. In this case, only translate the
22063 starting or ending part of TIMESTAMP if it is a date or time
22064 range. Otherwise, translate both parts."
22065 (if (and (not boundary)
22066 (memq (org-element-property :type timestamp)
22067 '(active-range inactive-range)))
22068 (concat
22069 (org-translate-time
22070 (org-element-property :raw-value
22071 (org-timestamp-split-range timestamp)))
22072 "--"
22073 (org-translate-time
22074 (org-element-property :raw-value
22075 (org-timestamp-split-range timestamp t))))
22076 (org-translate-time
22077 (org-element-property
22078 :raw-value
22079 (if (not boundary) timestamp
22080 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22084 ;;; Other stuff.
22086 (defun org-toggle-fixed-width-section (arg)
22087 "Toggle the fixed-width export.
22088 If there is no active region, the QUOTE keyword at the current headline is
22089 inserted or removed. When present, it causes the text between this headline
22090 and the next to be exported as fixed-width text, and unmodified.
22091 If there is an active region, this command adds or removes a colon as the
22092 first character of this line. If the first character of a line is a colon,
22093 this line is also exported in fixed-width font."
22094 (interactive "P")
22095 (let* ((cc 0)
22096 (regionp (org-region-active-p))
22097 (beg (if regionp (region-beginning) (point)))
22098 (end (if regionp (region-end)))
22099 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22100 (case-fold-search nil)
22101 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22102 off)
22103 (if regionp
22104 (save-excursion
22105 (goto-char beg)
22106 (setq cc (current-column))
22107 (beginning-of-line 1)
22108 (setq off (looking-at re))
22109 (while (> nlines 0)
22110 (setq nlines (1- nlines))
22111 (beginning-of-line 1)
22112 (cond
22113 (arg
22114 (org-move-to-column cc t)
22115 (insert ": \n")
22116 (forward-line -1))
22117 ((and off (looking-at re))
22118 (replace-match "" t t nil 1))
22119 ((not off) (org-move-to-column cc t) (insert ": ")))
22120 (forward-line 1)))
22121 (save-excursion
22122 (org-back-to-heading)
22123 (cond
22124 ((looking-at (format org-heading-keyword-regexp-format
22125 org-quote-string))
22126 (goto-char (match-end 1))
22127 (looking-at (concat " +" org-quote-string))
22128 (replace-match "" t t)
22129 (when (eolp) (insert " ")))
22130 ((looking-at org-outline-regexp)
22131 (goto-char (match-end 0))
22132 (insert org-quote-string " ")))))))
22134 (defun org-reftex-citation ()
22135 "Use reftex-citation to insert a citation into the buffer.
22136 This looks for a line like
22138 #+BIBLIOGRAPHY: foo plain option:-d
22140 and derives from it that foo.bib is the bibliography file relevant
22141 for this document. It then installs the necessary environment for RefTeX
22142 to work in this buffer and calls `reftex-citation' to insert a citation
22143 into the buffer.
22145 Export of such citations to both LaTeX and HTML is handled by the contributed
22146 package org-exp-bibtex by Taru Karttunen."
22147 (interactive)
22148 (let ((reftex-docstruct-symbol 'rds)
22149 (reftex-cite-format "\\cite{%l}")
22150 rds bib)
22151 (save-excursion
22152 (save-restriction
22153 (widen)
22154 (let ((case-fold-search t)
22155 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22156 (if (not (save-excursion
22157 (or (re-search-forward re nil t)
22158 (re-search-backward re nil t))))
22159 (error "No bibliography defined in file")
22160 (setq bib (concat (match-string 1) ".bib")
22161 rds (list (list 'bib bib)))))))
22162 (call-interactively 'reftex-citation)))
22164 ;;;; Functions extending outline functionality
22166 (defun org-beginning-of-line (&optional arg)
22167 "Go to the beginning of the current line. If that is invisible, continue
22168 to a visible line beginning. This makes the function of C-a more intuitive.
22169 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22170 first attempt, and only move to after the tags when the cursor is already
22171 beyond the end of the headline."
22172 (interactive "P")
22173 (let ((pos (point))
22174 (special (if (consp org-special-ctrl-a/e)
22175 (car org-special-ctrl-a/e)
22176 org-special-ctrl-a/e))
22177 refpos)
22178 (if (org-bound-and-true-p visual-line-mode)
22179 (beginning-of-visual-line 1)
22180 (beginning-of-line 1))
22181 (if (and arg (fboundp 'move-beginning-of-line))
22182 (call-interactively 'move-beginning-of-line)
22183 (if (bobp)
22185 (backward-char 1)
22186 (if (org-truely-invisible-p)
22187 (while (and (not (bobp)) (org-truely-invisible-p))
22188 (backward-char 1)
22189 (beginning-of-line 1))
22190 (forward-char 1))))
22191 (when special
22192 (cond
22193 ((and (looking-at org-complex-heading-regexp)
22194 (= (char-after (match-end 1)) ?\ ))
22195 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22196 (point-at-eol)))
22197 (goto-char
22198 (if (eq special t)
22199 (cond ((> pos refpos) refpos)
22200 ((= pos (point)) refpos)
22201 (t (point)))
22202 (cond ((> pos (point)) (point))
22203 ((not (eq last-command this-command)) (point))
22204 (t refpos)))))
22205 ((org-at-item-p)
22206 ;; Being at an item and not looking at an the item means point
22207 ;; was previously moved to beginning of a visual line, which
22208 ;; doesn't contain the item. Therefore, do nothing special,
22209 ;; just stay here.
22210 (when (looking-at org-list-full-item-re)
22211 ;; Set special position at first white space character after
22212 ;; bullet, and check-box, if any.
22213 (let ((after-bullet
22214 (let ((box (match-end 3)))
22215 (if (not box) (match-end 1)
22216 (let ((after (char-after box)))
22217 (if (and after (= after ? )) (1+ box) box))))))
22218 ;; Special case: Move point to special position when
22219 ;; currently after it or at beginning of line.
22220 (if (eq special t)
22221 (when (or (> pos after-bullet) (= (point) pos))
22222 (goto-char after-bullet))
22223 ;; Reversed case: Move point to special position when
22224 ;; point was already at beginning of line and command is
22225 ;; repeated.
22226 (when (and (= (point) pos) (eq last-command this-command))
22227 (goto-char after-bullet))))))))
22228 (org-no-warnings
22229 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22231 (defun org-end-of-line (&optional arg)
22232 "Go to the end of the line.
22233 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22234 tags on the first attempt, and only move to after the tags when
22235 the cursor is already beyond the end of the headline."
22236 (interactive "P")
22237 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22238 org-special-ctrl-a/e))
22239 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22240 'end-of-visual-line)
22241 ((fboundp 'move-end-of-line) 'move-end-of-line)
22242 (t 'end-of-line))))
22243 (if (or (not special) arg) (call-interactively move-fun)
22244 (let* ((element (ignore-errors
22245 ;; Don't throw an error outside elements
22246 (save-excursion (beginning-of-line)
22247 (org-element-at-point))))
22248 (type (org-element-type element)))
22249 (cond
22250 ((memq type '(headline inlinetask))
22251 (let ((pos (point)))
22252 (beginning-of-line 1)
22253 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22254 (if (eq special t)
22255 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22256 (goto-char (match-beginning 1))
22257 (goto-char (match-end 0)))
22258 (if (or (< pos (match-end 0))
22259 (not (eq this-command last-command)))
22260 (goto-char (match-end 0))
22261 (goto-char (match-beginning 1))))
22262 (call-interactively move-fun))))
22263 ((org-element-property :hiddenp element)
22264 ;; If element is hidden, `move-end-of-line' would put point
22265 ;; after it. Use `end-of-line' to stay on current line.
22266 (call-interactively 'end-of-line))
22267 (t (call-interactively move-fun)))))
22268 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22270 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22271 (define-key org-mode-map "\C-e" 'org-end-of-line)
22273 (defun org-backward-sentence (&optional arg)
22274 "Go to beginning of sentence, or beginning of table field.
22275 This will call `backward-sentence' or `org-table-beginning-of-field',
22276 depending on context."
22277 (interactive "P")
22278 (cond
22279 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22280 (t (call-interactively 'backward-sentence))))
22282 (defun org-forward-sentence (&optional arg)
22283 "Go to end of sentence, or end of table field.
22284 This will call `forward-sentence' or `org-table-end-of-field',
22285 depending on context."
22286 (interactive "P")
22287 (cond
22288 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22289 (t (call-interactively 'forward-sentence))))
22291 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22292 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22294 (defun org-kill-line (&optional arg)
22295 "Kill line, to tags or end of line."
22296 (interactive "P")
22297 (cond
22298 ((or (not org-special-ctrl-k)
22299 (bolp)
22300 (not (org-at-heading-p)))
22301 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22302 org-ctrl-k-protect-subtree)
22303 (if (or (eq org-ctrl-k-protect-subtree 'error)
22304 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22305 (error "C-k aborted - would kill hidden subtree")))
22306 (call-interactively
22307 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22308 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22309 (kill-region (point) (match-beginning 1))
22310 (org-set-tags nil t))
22311 (t (kill-region (point) (point-at-eol)))))
22313 (define-key org-mode-map "\C-k" 'org-kill-line)
22315 (defun org-yank (&optional arg)
22316 "Yank. If the kill is a subtree, treat it specially.
22317 This command will look at the current kill and check if is a single
22318 subtree, or a series of subtrees[1]. If it passes the test, and if the
22319 cursor is at the beginning of a line or after the stars of a currently
22320 empty headline, then the yank is handled specially. How exactly depends
22321 on the value of the following variables, both set by default.
22323 org-yank-folded-subtrees
22324 When set, the subtree(s) will be folded after insertion, but only
22325 if doing so would now swallow text after the yanked text.
22327 org-yank-adjusted-subtrees
22328 When set, the subtree will be promoted or demoted in order to
22329 fit into the local outline tree structure, which means that the level
22330 will be adjusted so that it becomes the smaller one of the two
22331 *visible* surrounding headings.
22333 Any prefix to this command will cause `yank' to be called directly with
22334 no special treatment. In particular, a simple \\[universal-argument] prefix \
22335 will just
22336 plainly yank the text as it is.
22338 \[1] The test checks if the first non-white line is a heading
22339 and if there are no other headings with fewer stars."
22340 (interactive "P")
22341 (org-yank-generic 'yank arg))
22343 (defun org-yank-generic (command arg)
22344 "Perform some yank-like command.
22346 This function implements the behavior described in the `org-yank'
22347 documentation. However, it has been generalized to work for any
22348 interactive command with similar behavior."
22350 ;; pretend to be command COMMAND
22351 (setq this-command command)
22353 (if arg
22354 (call-interactively command)
22356 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22357 (and (org-kill-is-subtree-p)
22358 (or (bolp)
22359 (and (looking-at "[ \t]*$")
22360 (string-match
22361 "\\`\\*+\\'"
22362 (buffer-substring (point-at-bol) (point)))))))
22363 swallowp)
22364 (cond
22365 ((and subtreep org-yank-folded-subtrees)
22366 (let ((beg (point))
22367 end)
22368 (if (and subtreep org-yank-adjusted-subtrees)
22369 (org-paste-subtree nil nil 'for-yank)
22370 (call-interactively command))
22372 (setq end (point))
22373 (goto-char beg)
22374 (when (and (bolp) subtreep
22375 (not (setq swallowp
22376 (org-yank-folding-would-swallow-text beg end))))
22377 (org-with-limited-levels
22378 (or (looking-at org-outline-regexp)
22379 (re-search-forward org-outline-regexp-bol end t))
22380 (while (and (< (point) end) (looking-at org-outline-regexp))
22381 (hide-subtree)
22382 (org-cycle-show-empty-lines 'folded)
22383 (condition-case nil
22384 (outline-forward-same-level 1)
22385 (error (goto-char end))))))
22386 (when swallowp
22387 (message
22388 "Inserted text not folded because that would swallow text"))
22390 (goto-char end)
22391 (skip-chars-forward " \t\n\r")
22392 (beginning-of-line 1)
22393 (push-mark beg 'nomsg)))
22394 ((and subtreep org-yank-adjusted-subtrees)
22395 (let ((beg (point-at-bol)))
22396 (org-paste-subtree nil nil 'for-yank)
22397 (push-mark beg 'nomsg)))
22399 (call-interactively command))))))
22401 (defun org-yank-folding-would-swallow-text (beg end)
22402 "Would hide-subtree at BEG swallow any text after END?"
22403 (let (level)
22404 (org-with-limited-levels
22405 (save-excursion
22406 (goto-char beg)
22407 (when (or (looking-at org-outline-regexp)
22408 (re-search-forward org-outline-regexp-bol end t))
22409 (setq level (org-outline-level)))
22410 (goto-char end)
22411 (skip-chars-forward " \t\r\n\v\f")
22412 (if (or (eobp)
22413 (and (bolp) (looking-at org-outline-regexp)
22414 (<= (org-outline-level) level)))
22415 nil ; Nothing would be swallowed
22416 t))))) ; something would swallow
22418 (define-key org-mode-map "\C-y" 'org-yank)
22420 (defun org-truely-invisible-p ()
22421 "Check if point is at a character currently not visible.
22422 This version does not only check the character property, but also
22423 `visible-mode'."
22424 ;; Early versions of noutline don't have `outline-invisible-p'.
22425 (if (org-bound-and-true-p visible-mode)
22427 (outline-invisible-p)))
22429 (defun org-invisible-p2 ()
22430 "Check if point is at a character currently not visible."
22431 (save-excursion
22432 (if (and (eolp) (not (bobp))) (backward-char 1))
22433 ;; Early versions of noutline don't have `outline-invisible-p'.
22434 (outline-invisible-p)))
22436 (defun org-back-to-heading (&optional invisible-ok)
22437 "Call `outline-back-to-heading', but provide a better error message."
22438 (condition-case nil
22439 (outline-back-to-heading invisible-ok)
22440 (error (error "Before first headline at position %d in buffer %s"
22441 (point) (current-buffer)))))
22443 (defun org-before-first-heading-p ()
22444 "Before first heading?"
22445 (save-excursion
22446 (end-of-line)
22447 (null (re-search-backward org-outline-regexp-bol nil t))))
22449 (defun org-at-heading-p (&optional ignored)
22450 (outline-on-heading-p t))
22451 ;; Compatibility alias with Org versions < 7.8.03
22452 (defalias 'org-on-heading-p 'org-at-heading-p)
22454 (defun org-at-comment-p nil
22455 "Is cursor in a line starting with a # character?"
22456 (save-excursion
22457 (beginning-of-line)
22458 (looking-at "^#")))
22460 (defun org-at-drawer-p nil
22461 "Is cursor at a drawer keyword?"
22462 (save-excursion
22463 (move-beginning-of-line 1)
22464 (looking-at org-drawer-regexp)))
22466 (defun org-at-block-p nil
22467 "Is cursor at a block keyword?"
22468 (save-excursion
22469 (move-beginning-of-line 1)
22470 (looking-at org-block-regexp)))
22472 (defun org-point-at-end-of-empty-headline ()
22473 "If point is at the end of an empty headline, return t, else nil.
22474 If the heading only contains a TODO keyword, it is still still considered
22475 empty."
22476 (and (looking-at "[ \t]*$")
22477 (when org-todo-line-regexp
22478 (save-excursion
22479 (beginning-of-line 1)
22480 (let ((case-fold-search nil))
22481 (looking-at org-todo-line-regexp)
22482 (string= (match-string 3) ""))))))
22484 (defun org-at-heading-or-item-p ()
22485 (or (org-at-heading-p) (org-at-item-p)))
22487 (defun org-at-target-p ()
22488 (or (org-in-regexp org-radio-target-regexp)
22489 (org-in-regexp org-target-regexp)))
22490 ;; Compatibility alias with Org versions < 7.8.03
22491 (defalias 'org-on-target-p 'org-at-target-p)
22493 (defun org-up-heading-all (arg)
22494 "Move to the heading line of which the present line is a subheading.
22495 This function considers both visible and invisible heading lines.
22496 With argument, move up ARG levels."
22497 (if (fboundp 'outline-up-heading-all)
22498 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22499 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22501 (defun org-up-heading-safe ()
22502 "Move to the heading line of which the present line is a subheading.
22503 This version will not throw an error. It will return the level of the
22504 headline found, or nil if no higher level is found.
22506 Also, this function will be a lot faster than `outline-up-heading',
22507 because it relies on stars being the outline starters. This can really
22508 make a significant difference in outlines with very many siblings."
22509 (let (start-level re)
22510 (org-back-to-heading t)
22511 (setq start-level (funcall outline-level))
22512 (if (equal start-level 1)
22514 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22515 (if (re-search-backward re nil t)
22516 (funcall outline-level)))))
22518 (defun org-first-sibling-p ()
22519 "Is this heading the first child of its parents?"
22520 (interactive)
22521 (let ((re org-outline-regexp-bol)
22522 level l)
22523 (unless (org-at-heading-p t)
22524 (error "Not at a heading"))
22525 (setq level (funcall outline-level))
22526 (save-excursion
22527 (if (not (re-search-backward re nil t))
22529 (setq l (funcall outline-level))
22530 (< l level)))))
22532 (defun org-goto-sibling (&optional previous)
22533 "Goto the next sibling, even if it is invisible.
22534 When PREVIOUS is set, go to the previous sibling instead. Returns t
22535 when a sibling was found. When none is found, return nil and don't
22536 move point."
22537 (let ((fun (if previous 're-search-backward 're-search-forward))
22538 (pos (point))
22539 (re org-outline-regexp-bol)
22540 level l)
22541 (when (condition-case nil (org-back-to-heading t) (error nil))
22542 (setq level (funcall outline-level))
22543 (catch 'exit
22544 (or previous (forward-char 1))
22545 (while (funcall fun re nil t)
22546 (setq l (funcall outline-level))
22547 (when (< l level) (goto-char pos) (throw 'exit nil))
22548 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22549 (goto-char pos)
22550 nil))))
22552 (defun org-show-siblings ()
22553 "Show all siblings of the current headline."
22554 (save-excursion
22555 (while (org-goto-sibling) (org-flag-heading nil)))
22556 (save-excursion
22557 (while (org-goto-sibling 'previous)
22558 (org-flag-heading nil))))
22560 (defun org-goto-first-child ()
22561 "Goto the first child, even if it is invisible.
22562 Return t when a child was found. Otherwise don't move point and
22563 return nil."
22564 (let (level (pos (point)) (re org-outline-regexp-bol))
22565 (when (condition-case nil (org-back-to-heading t) (error nil))
22566 (setq level (outline-level))
22567 (forward-char 1)
22568 (if (and (re-search-forward re nil t) (> (outline-level) level))
22569 (progn (goto-char (match-beginning 0)) t)
22570 (goto-char pos) nil))))
22572 (defun org-show-hidden-entry ()
22573 "Show an entry where even the heading is hidden."
22574 (save-excursion
22575 (org-show-entry)))
22577 (defun org-flag-heading (flag &optional entry)
22578 "Flag the current heading. FLAG non-nil means make invisible.
22579 When ENTRY is non-nil, show the entire entry."
22580 (save-excursion
22581 (org-back-to-heading t)
22582 ;; Check if we should show the entire entry
22583 (if entry
22584 (progn
22585 (org-show-entry)
22586 (save-excursion
22587 (and (outline-next-heading)
22588 (org-flag-heading nil))))
22589 (outline-flag-region (max (point-min) (1- (point)))
22590 (save-excursion (outline-end-of-heading) (point))
22591 flag))))
22593 (defun org-get-next-sibling ()
22594 "Move to next heading of the same level, and return point.
22595 If there is no such heading, return nil.
22596 This is like outline-next-sibling, but invisible headings are ok."
22597 (let ((level (funcall outline-level)))
22598 (outline-next-heading)
22599 (while (and (not (eobp)) (> (funcall outline-level) level))
22600 (outline-next-heading))
22601 (if (or (eobp) (< (funcall outline-level) level))
22603 (point))))
22605 (defun org-get-last-sibling ()
22606 "Move to previous heading of the same level, and return point.
22607 If there is no such heading, return nil."
22608 (let ((opoint (point))
22609 (level (funcall outline-level)))
22610 (outline-previous-heading)
22611 (when (and (/= (point) opoint) (outline-on-heading-p t))
22612 (while (and (> (funcall outline-level) level)
22613 (not (bobp)))
22614 (outline-previous-heading))
22615 (if (< (funcall outline-level) level)
22617 (point)))))
22619 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22620 "Goto to the end of a subtree."
22621 ;; This contains an exact copy of the original function, but it uses
22622 ;; `org-back-to-heading', to make it work also in invisible
22623 ;; trees. And is uses an invisible-ok argument.
22624 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22625 ;; Furthermore, when used inside Org, finding the end of a large subtree
22626 ;; with many children and grandchildren etc, this can be much faster
22627 ;; than the outline version.
22628 (org-back-to-heading invisible-ok)
22629 (let ((first t)
22630 (level (funcall outline-level)))
22631 (if (and (derived-mode-p 'org-mode) (< level 1000))
22632 ;; A true heading (not a plain list item), in Org-mode
22633 ;; This means we can easily find the end by looking
22634 ;; only for the right number of stars. Using a regexp to do
22635 ;; this is so much faster than using a Lisp loop.
22636 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22637 (forward-char 1)
22638 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22639 ;; something else, do it the slow way
22640 (while (and (not (eobp))
22641 (or first (> (funcall outline-level) level)))
22642 (setq first nil)
22643 (outline-next-heading)))
22644 (unless to-heading
22645 (if (memq (preceding-char) '(?\n ?\^M))
22646 (progn
22647 ;; Go to end of line before heading
22648 (forward-char -1)
22649 (if (memq (preceding-char) '(?\n ?\^M))
22650 ;; leave blank line before heading
22651 (forward-char -1))))))
22652 (point))
22654 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22655 "Use Org version in org-mode, for dramatic speed-up."
22656 (if (derived-mode-p 'org-mode)
22657 (progn
22658 (org-end-of-subtree nil t)
22659 (unless (eobp) (backward-char 1)))
22660 ad-do-it))
22662 (defun org-end-of-meta-data-and-drawers ()
22663 "Jump to the first text after meta data and drawers in the current entry.
22664 This will move over empty lines, lines with planning time stamps,
22665 clocking lines, and drawers."
22666 (org-back-to-heading t)
22667 (let ((end (save-excursion (outline-next-heading) (point)))
22668 (re (concat "\\(" org-drawer-regexp "\\)"
22669 "\\|" "[ \t]*" org-keyword-time-regexp)))
22670 (forward-line 1)
22671 (while (re-search-forward re end t)
22672 (if (not (match-end 1))
22673 ;; empty or planning line
22674 (forward-line 1)
22675 ;; a drawer, find the end
22676 (re-search-forward "^[ \t]*:END:" end 'move)
22677 (forward-line 1)))
22678 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22679 (point)))
22681 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22682 "Move forward to the ARG'th subheading at same level as this one.
22683 Stop at the first and last subheadings of a superior heading.
22684 Normally this only looks at visible headings, but when INVISIBLE-OK is
22685 non-nil it will also look at invisible ones."
22686 (interactive "p")
22687 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22688 (if (and arg (< arg 0))
22689 (goto-char (point-min))
22690 (outline-next-heading))
22691 (org-at-heading-p)
22692 (let ((level (- (match-end 0) (match-beginning 0) 1))
22693 (f (if (and arg (< arg 0))
22694 're-search-backward
22695 're-search-forward))
22696 (count (if arg (abs arg) 1))
22697 (result (point)))
22698 (forward-char (if (and arg (< arg 0)) -1 1))
22699 (while (and (> count 0)
22700 (funcall f org-outline-regexp-bol nil 'move))
22701 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22702 (cond ((< l level) (setq count 0))
22703 ((and (= l level)
22704 (or invisible-ok
22705 (progn
22706 (goto-char (line-beginning-position))
22707 (not (outline-invisible-p)))))
22708 (setq count (1- count))
22709 (when (eq l level)
22710 (setq result (point)))))))
22711 (goto-char result))
22712 (beginning-of-line 1)))
22714 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22715 "Move backward to the ARG'th subheading at same level as this one.
22716 Stop at the first and last subheadings of a superior heading."
22717 (interactive "p")
22718 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22720 (defun org-next-block (arg &optional backward block-regexp)
22721 "Jump to the next block.
22722 With a prefix argument ARG, jump forward ARG many source blocks.
22723 When BACKWARD is non-nil, jump to the previous block.
22724 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22725 (interactive "p")
22726 (let ((re (or block-regexp org-block-regexp))
22727 (re-search-fn (or (and backward 're-search-backward)
22728 're-search-forward)))
22729 (if (looking-at re) (forward-char 1))
22730 (condition-case nil
22731 (funcall re-search-fn re nil nil arg)
22732 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22733 (goto-char (match-beginning 0)) (org-show-context)))
22735 (defun org-previous-block (arg &optional block-regexp)
22736 "Jump to the previous block.
22737 With a prefix argument ARG, jump backward ARG many source blocks.
22738 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22739 (interactive "p")
22740 (org-next-block arg t block-regexp))
22742 (defun org-forward-element ()
22743 "Move forward by one element.
22744 Move to the next element at the same level, when possible."
22745 (interactive)
22746 (cond ((eobp) (error "Cannot move further down"))
22747 ((org-with-limited-levels (org-at-heading-p))
22748 (let ((origin (point)))
22749 (goto-char (org-end-of-subtree nil t))
22750 (unless (org-with-limited-levels (org-at-heading-p))
22751 (goto-char origin)
22752 (error "Cannot move further down"))))
22754 (let* ((elem (org-element-at-point))
22755 (end (org-element-property :end elem))
22756 (parent (org-element-property :parent elem)))
22757 (if (and parent (= (org-element-property :contents-end parent) end))
22758 (goto-char (org-element-property :end parent))
22759 (goto-char end))))))
22761 (defun org-backward-element ()
22762 "Move backward by one element.
22763 Move to the previous element at the same level, when possible."
22764 (interactive)
22765 (cond ((bobp) (error "Cannot move further up"))
22766 ((org-with-limited-levels (org-at-heading-p))
22767 ;; At an headline, move to the previous one, if any, or stay
22768 ;; here.
22769 (let ((origin (point)))
22770 (org-with-limited-levels (org-backward-heading-same-level 1))
22771 ;; When current headline has no sibling above, move to its
22772 ;; parent.
22773 (when (= (point) origin)
22774 (or (org-with-limited-levels (org-up-heading-safe))
22775 (progn (goto-char origin)
22776 (error "Cannot move further up"))))))
22778 (let* ((trail (org-element-at-point 'keep-trail))
22779 (elem (car trail))
22780 (prev-elem (nth 1 trail))
22781 (beg (org-element-property :begin elem)))
22782 (cond
22783 ;; Move to beginning of current element if point isn't
22784 ;; there already.
22785 ((/= (point) beg) (goto-char beg))
22786 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22787 ((org-before-first-heading-p) (goto-char (point-min)))
22788 (t (org-back-to-heading)))))))
22790 (defun org-up-element ()
22791 "Move to upper element."
22792 (interactive)
22793 (if (org-with-limited-levels (org-at-heading-p))
22794 (unless (org-up-heading-safe) (error "No surrounding element"))
22795 (let* ((elem (org-element-at-point))
22796 (parent (org-element-property :parent elem)))
22797 (if parent (goto-char (org-element-property :begin parent))
22798 (if (org-with-limited-levels (org-before-first-heading-p))
22799 (error "No surrounding element")
22800 (org-with-limited-levels (org-back-to-heading)))))))
22802 (defvar org-element-greater-elements)
22803 (defun org-down-element ()
22804 "Move to inner element."
22805 (interactive)
22806 (let ((element (org-element-at-point)))
22807 (cond
22808 ((memq (org-element-type element) '(plain-list table))
22809 (goto-char (org-element-property :contents-begin element))
22810 (forward-char))
22811 ((memq (org-element-type element) org-element-greater-elements)
22812 ;; If contents are hidden, first disclose them.
22813 (when (org-element-property :hiddenp element) (org-cycle))
22814 (goto-char (or (org-element-property :contents-begin element)
22815 (error "No content for this element"))))
22816 (t (error "No inner element")))))
22818 (defun org-drag-element-backward ()
22819 "Move backward element at point."
22820 (interactive)
22821 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22822 (let* ((trail (org-element-at-point 'keep-trail))
22823 (elem (car trail))
22824 (prev-elem (nth 1 trail)))
22825 ;; Error out if no previous element or previous element is
22826 ;; a parent of the current one.
22827 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22828 (error "Cannot drag element backward")
22829 (let ((pos (point)))
22830 (org-element-swap-A-B prev-elem elem)
22831 (goto-char (+ (org-element-property :begin prev-elem)
22832 (- pos (org-element-property :begin elem)))))))))
22834 (defun org-drag-element-forward ()
22835 "Move forward element at point."
22836 (interactive)
22837 (let* ((pos (point))
22838 (elem (org-element-at-point)))
22839 (when (= (point-max) (org-element-property :end elem))
22840 (error "Cannot drag element forward"))
22841 (goto-char (org-element-property :end elem))
22842 (let ((next-elem (org-element-at-point)))
22843 (when (or (org-element-nested-p elem next-elem)
22844 (and (eq (org-element-type next-elem) 'headline)
22845 (not (eq (org-element-type elem) 'headline))))
22846 (goto-char pos)
22847 (error "Cannot drag element forward"))
22848 ;; Compute new position of point: it's shifted by NEXT-ELEM
22849 ;; body's length (without final blanks) and by the length of
22850 ;; blanks between ELEM and NEXT-ELEM.
22851 (let ((size-next (- (save-excursion
22852 (goto-char (org-element-property :end next-elem))
22853 (skip-chars-backward " \r\t\n")
22854 (forward-line)
22855 ;; Small correction if buffer doesn't end
22856 ;; with a newline character.
22857 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22858 (org-element-property :begin next-elem)))
22859 (size-blank (- (org-element-property :end elem)
22860 (save-excursion
22861 (goto-char (org-element-property :end elem))
22862 (skip-chars-backward " \r\t\n")
22863 (forward-line)
22864 (point)))))
22865 (org-element-swap-A-B elem next-elem)
22866 (goto-char (+ pos size-next size-blank))))))
22868 (defun org-mark-element ()
22869 "Put point at beginning of this element, mark at end.
22871 Interactively, if this command is repeated or (in Transient Mark
22872 mode) if the mark is active, it marks the next element after the
22873 ones already marked."
22874 (interactive)
22875 (let (deactivate-mark)
22876 (if (and (org-called-interactively-p 'any)
22877 (or (and (eq last-command this-command) (mark t))
22878 (and transient-mark-mode mark-active)))
22879 (set-mark
22880 (save-excursion
22881 (goto-char (mark))
22882 (goto-char (org-element-property :end (org-element-at-point)))))
22883 (let ((element (org-element-at-point)))
22884 (end-of-line)
22885 (push-mark (org-element-property :end element) t t)
22886 (goto-char (org-element-property :begin element))))))
22888 (defun org-narrow-to-element ()
22889 "Narrow buffer to current element."
22890 (interactive)
22891 (let ((elem (org-element-at-point)))
22892 (cond
22893 ((eq (car elem) 'headline)
22894 (narrow-to-region
22895 (org-element-property :begin elem)
22896 (org-element-property :end elem)))
22897 ((memq (car elem) org-element-greater-elements)
22898 (narrow-to-region
22899 (org-element-property :contents-begin elem)
22900 (org-element-property :contents-end elem)))
22902 (narrow-to-region
22903 (org-element-property :begin elem)
22904 (org-element-property :end elem))))))
22906 (defun org-transpose-words ()
22907 "Transpose words, using `org-mode' syntax table."
22908 (interactive)
22909 (with-syntax-table org-syntax-table
22910 (call-interactively 'transpose-words)))
22911 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22913 (defun org-transpose-element ()
22914 "Transpose current and previous elements, keeping blank lines between.
22915 Point is moved after both elements."
22916 (interactive)
22917 (org-skip-whitespace)
22918 (let ((end (org-element-property :end (org-element-at-point))))
22919 (org-drag-element-backward)
22920 (goto-char end)))
22922 (defun org-unindent-buffer ()
22923 "Un-indent the visible part of the buffer.
22924 Relative indentation (between items, inside blocks, etc.) isn't
22925 modified."
22926 (interactive)
22927 (unless (eq major-mode 'org-mode)
22928 (error "Cannot un-indent a buffer not in Org mode"))
22929 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22930 unindent-tree ; For byte-compiler.
22931 (unindent-tree
22932 (function
22933 (lambda (contents)
22934 (mapc
22935 (lambda (element)
22936 (if (memq (org-element-type element) '(headline section))
22937 (funcall unindent-tree (org-element-contents element))
22938 (save-excursion
22939 (save-restriction
22940 (narrow-to-region
22941 (org-element-property :begin element)
22942 (org-element-property :end element))
22943 (org-do-remove-indentation)))))
22944 (reverse contents))))))
22945 (funcall unindent-tree (org-element-contents parse-tree))))
22947 (defun org-show-subtree ()
22948 "Show everything after this heading at deeper levels."
22949 (interactive)
22950 (outline-flag-region
22951 (point)
22952 (save-excursion
22953 (org-end-of-subtree t t))
22954 nil))
22956 (defun org-show-entry ()
22957 "Show the body directly following this heading.
22958 Show the heading too, if it is currently invisible."
22959 (interactive)
22960 (save-excursion
22961 (condition-case nil
22962 (progn
22963 (org-back-to-heading t)
22964 (outline-flag-region
22965 (max (point-min) (1- (point)))
22966 (save-excursion
22967 (if (re-search-forward
22968 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22969 (match-beginning 1)
22970 (point-max)))
22971 nil)
22972 (org-cycle-hide-drawers 'children))
22973 (error nil))))
22975 (defun org-make-options-regexp (kwds &optional extra)
22976 "Make a regular expression for keyword lines."
22977 (concat
22978 "^#\\+\\("
22979 (mapconcat 'regexp-quote kwds "\\|")
22980 (if extra (concat "\\|" extra))
22981 "\\):[ \t]*\\(.*\\)"))
22983 ;; Make isearch reveal the necessary context
22984 (defun org-isearch-end ()
22985 "Reveal context after isearch exits."
22986 (when isearch-success ; only if search was successful
22987 (if (featurep 'xemacs)
22988 ;; Under XEmacs, the hook is run in the correct place,
22989 ;; we directly show the context.
22990 (org-show-context 'isearch)
22991 ;; In Emacs the hook runs *before* restoring the overlays.
22992 ;; So we have to use a one-time post-command-hook to do this.
22993 ;; (Emacs 22 has a special variable, see function `org-mode')
22994 (unless (and (boundp 'isearch-mode-end-hook-quit)
22995 isearch-mode-end-hook-quit)
22996 ;; Only when the isearch was not quitted.
22997 (org-add-hook 'post-command-hook 'org-isearch-post-command
22998 'append 'local)))))
23000 (defun org-isearch-post-command ()
23001 "Remove self from hook, and show context."
23002 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23003 (org-show-context 'isearch))
23006 ;;;; Integration with and fixes for other packages
23008 ;;; Imenu support
23010 (defvar org-imenu-markers nil
23011 "All markers currently used by Imenu.")
23012 (make-variable-buffer-local 'org-imenu-markers)
23014 (defun org-imenu-new-marker (&optional pos)
23015 "Return a new marker for use by Imenu, and remember the marker."
23016 (let ((m (make-marker)))
23017 (move-marker m (or pos (point)))
23018 (push m org-imenu-markers)
23021 (defun org-imenu-get-tree ()
23022 "Produce the index for Imenu."
23023 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23024 (setq org-imenu-markers nil)
23025 (let* ((n org-imenu-depth)
23026 (re (concat "^" (org-get-limited-outline-regexp)))
23027 (subs (make-vector (1+ n) nil))
23028 (last-level 0)
23029 m level head)
23030 (save-excursion
23031 (save-restriction
23032 (widen)
23033 (goto-char (point-max))
23034 (while (re-search-backward re nil t)
23035 (setq level (org-reduced-level (funcall outline-level)))
23036 (when (and (<= level n)
23037 (looking-at org-complex-heading-regexp))
23038 (setq head (org-link-display-format
23039 (org-match-string-no-properties 4))
23040 m (org-imenu-new-marker))
23041 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23042 (if (>= level last-level)
23043 (push (cons head m) (aref subs level))
23044 (push (cons head (aref subs (1+ level))) (aref subs level))
23045 (loop for i from (1+ level) to n do (aset subs i nil)))
23046 (setq last-level level)))))
23047 (aref subs 1)))
23049 (eval-after-load "imenu"
23050 '(progn
23051 (add-hook 'imenu-after-jump-hook
23052 (lambda ()
23053 (if (derived-mode-p 'org-mode)
23054 (org-show-context 'org-goto))))))
23056 (defun org-link-display-format (link)
23057 "Replace a link with either the description, or the link target
23058 if no description is present"
23059 (save-match-data
23060 (if (string-match org-bracket-link-analytic-regexp link)
23061 (replace-match (if (match-end 5)
23062 (match-string 5 link)
23063 (concat (match-string 1 link)
23064 (match-string 3 link)))
23065 nil t link)
23066 link)))
23068 (defun org-toggle-link-display ()
23069 "Toggle the literal or descriptive display of links."
23070 (interactive)
23071 (if org-descriptive-links
23072 (progn (org-remove-from-invisibility-spec '(org-link))
23073 (org-restart-font-lock)
23074 (setq org-descriptive-links nil))
23075 (progn (add-to-invisibility-spec '(org-link))
23076 (org-restart-font-lock)
23077 (setq org-descriptive-links t))))
23079 ;; Speedbar support
23081 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23082 "Overlay marking the agenda restriction line in speedbar.")
23083 (overlay-put org-speedbar-restriction-lock-overlay
23084 'face 'org-agenda-restriction-lock)
23085 (overlay-put org-speedbar-restriction-lock-overlay
23086 'help-echo "Agendas are currently limited to this item.")
23087 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23089 (defun org-speedbar-set-agenda-restriction ()
23090 "Restrict future agenda commands to the location at point in speedbar.
23091 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23092 (interactive)
23093 (require 'org-agenda)
23094 (let (p m tp np dir txt)
23095 (cond
23096 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23097 'org-imenu t))
23098 (setq m (get-text-property p 'org-imenu-marker))
23099 (with-current-buffer (marker-buffer m)
23100 (goto-char m)
23101 (org-agenda-set-restriction-lock 'subtree)))
23102 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23103 'speedbar-function 'speedbar-find-file))
23104 (setq tp (previous-single-property-change
23105 (1+ p) 'speedbar-function)
23106 np (next-single-property-change
23107 tp 'speedbar-function)
23108 dir (speedbar-line-directory)
23109 txt (buffer-substring-no-properties (or tp (point-min))
23110 (or np (point-max))))
23111 (with-current-buffer (find-file-noselect
23112 (let ((default-directory dir))
23113 (expand-file-name txt)))
23114 (unless (derived-mode-p 'org-mode)
23115 (error "Cannot restrict to non-Org-mode file"))
23116 (org-agenda-set-restriction-lock 'file)))
23117 (t (error "Don't know how to restrict Org-mode's agenda")))
23118 (move-overlay org-speedbar-restriction-lock-overlay
23119 (point-at-bol) (point-at-eol))
23120 (setq current-prefix-arg nil)
23121 (org-agenda-maybe-redo)))
23123 (eval-after-load "speedbar"
23124 '(progn
23125 (speedbar-add-supported-extension ".org")
23126 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23127 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23128 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23129 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23130 (add-hook 'speedbar-visiting-tag-hook
23131 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23133 ;;; Fixes and Hacks for problems with other packages
23135 ;; Make flyspell not check words in links, to not mess up our keymap
23136 (defvar org-element-affiliated-keywords) ; From org-element.el
23137 (defvar org-element-block-name-alist) ; From org-element.el
23138 (defun org-mode-flyspell-verify ()
23139 "Don't let flyspell put overlays at active buttons, or on
23140 {todo,all-time,additional-option-like}-keywords."
23141 (let ((pos (max (1- (point)) (point-min)))
23142 (word (thing-at-point 'word)))
23143 (and (not (get-text-property pos 'keymap))
23144 (not (get-text-property pos 'org-no-flyspell))
23145 (not (member word org-todo-keywords-1))
23146 (not (member word org-all-time-keywords))
23147 (not (member word org-options-keywords))
23148 (not (member word (mapcar 'car org-startup-options)))
23149 (not (member-ignore-case word org-element-affiliated-keywords))
23150 (not (member-ignore-case word (org-get-export-keywords)))
23151 (not (member-ignore-case
23152 word (mapcar 'car org-element-block-name-alist)))
23153 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23155 (defun org-remove-flyspell-overlays-in (beg end)
23156 "Remove flyspell overlays in region."
23157 (and (org-bound-and-true-p flyspell-mode)
23158 (fboundp 'flyspell-delete-region-overlays)
23159 (flyspell-delete-region-overlays beg end))
23160 (add-text-properties beg end '(org-no-flyspell t)))
23162 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23163 (eval-after-load "bookmark"
23164 '(if (boundp 'bookmark-after-jump-hook)
23165 ;; We can use the hook
23166 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23167 ;; Hook not available, use advice
23168 (defadvice bookmark-jump (after org-make-visible activate)
23169 "Make the position visible."
23170 (org-bookmark-jump-unhide))))
23172 ;; Make sure saveplace shows the location if it was hidden
23173 (eval-after-load "saveplace"
23174 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23175 "Make the position visible."
23176 (org-bookmark-jump-unhide)))
23178 ;; Make sure ecb shows the location if it was hidden
23179 (eval-after-load "ecb"
23180 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23181 "Make hierarchy visible when jumping into location from ECB tree buffer."
23182 (if (derived-mode-p 'org-mode)
23183 (org-show-context))))
23185 (defun org-bookmark-jump-unhide ()
23186 "Unhide the current position, to show the bookmark location."
23187 (and (derived-mode-p 'org-mode)
23188 (or (outline-invisible-p)
23189 (save-excursion (goto-char (max (point-min) (1- (point))))
23190 (outline-invisible-p)))
23191 (org-show-context 'bookmark-jump)))
23193 ;; Make session.el ignore our circular variable
23194 (eval-after-load "session"
23195 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23197 ;;;; Experimental code
23199 (defun org-closed-in-range ()
23200 "Sparse tree of items closed in a certain time range.
23201 Still experimental, may disappear in the future."
23202 (interactive)
23203 ;; Get the time interval from the user.
23204 (let* ((time1 (org-float-time
23205 (org-read-date nil 'to-time nil "Starting date: ")))
23206 (time2 (org-float-time
23207 (org-read-date nil 'to-time nil "End date:")))
23208 ;; callback function
23209 (callback (lambda ()
23210 (let ((time
23211 (org-float-time
23212 (apply 'encode-time
23213 (org-parse-time-string
23214 (match-string 1))))))
23215 ;; check if time in interval
23216 (and (>= time time1) (<= time time2))))))
23217 ;; make tree, check each match with the callback
23218 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23220 ;;;; Finish up
23222 (provide 'org)
23224 (run-hooks 'org-load-hook)
23226 ;;; org.el ends here