ox-publish: Small refactoring
[org-mode.git] / lisp / org.el
blob91763d3c2213c491cadbe7d0ed5c67bec6e7285d
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 In tables, the special behavior of RET has precedence."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-mouse-1-follows-link
1667 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1668 "Non-nil means mouse-1 on a link will follow the link.
1669 A longer mouse click will still set point. Does not work on XEmacs.
1670 Needs to be set before org.el is loaded."
1671 :group 'org-link-follow
1672 :type 'boolean)
1674 (defcustom org-mark-ring-length 4
1675 "Number of different positions to be recorded in the ring.
1676 Changing this requires a restart of Emacs to work correctly."
1677 :group 'org-link-follow
1678 :type 'integer)
1680 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1681 "Non-nil means internal links in Org files must exactly match a headline.
1682 When nil, the link search tries to match a phrase with all words
1683 in the search text."
1684 :group 'org-link-follow
1685 :version "24.1"
1686 :type '(choice
1687 (const :tag "Use fuzzy text search" nil)
1688 (const :tag "Match only exact headline" t)
1689 (const :tag "Match exact headline or query to create it"
1690 query-to-create)))
1692 (defcustom org-link-frame-setup
1693 '((vm . vm-visit-folder-other-frame)
1694 (vm-imap . vm-visit-imap-folder-other-frame)
1695 (gnus . org-gnus-no-new-news)
1696 (file . find-file-other-window)
1697 (wl . wl-other-frame))
1698 "Setup the frame configuration for following links.
1699 When following a link with Emacs, it may often be useful to display
1700 this link in another window or frame. This variable can be used to
1701 set this up for the different types of links.
1702 For VM, use any of
1703 `vm-visit-folder'
1704 `vm-visit-folder-other-window'
1705 `vm-visit-folder-other-frame'
1706 For Gnus, use any of
1707 `gnus'
1708 `gnus-other-frame'
1709 `org-gnus-no-new-news'
1710 For FILE, use any of
1711 `find-file'
1712 `find-file-other-window'
1713 `find-file-other-frame'
1714 For Wanderlust use any of
1715 `wl'
1716 `wl-other-frame'
1717 For the calendar, use the variable `calendar-setup'.
1718 For BBDB, it is currently only possible to display the matches in
1719 another window."
1720 :group 'org-link-follow
1721 :type '(list
1722 (cons (const vm)
1723 (choice
1724 (const vm-visit-folder)
1725 (const vm-visit-folder-other-window)
1726 (const vm-visit-folder-other-frame)))
1727 (cons (const gnus)
1728 (choice
1729 (const gnus)
1730 (const gnus-other-frame)
1731 (const org-gnus-no-new-news)))
1732 (cons (const file)
1733 (choice
1734 (const find-file)
1735 (const find-file-other-window)
1736 (const find-file-other-frame)))
1737 (cons (const wl)
1738 (choice
1739 (const wl)
1740 (const wl-other-frame)))))
1742 (defcustom org-display-internal-link-with-indirect-buffer nil
1743 "Non-nil means use indirect buffer to display infile links.
1744 Activating internal links (from one location in a file to another location
1745 in the same file) normally just jumps to the location. When the link is
1746 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1747 is displayed in
1748 another window. When this option is set, the other window actually displays
1749 an indirect buffer clone of the current buffer, to avoid any visibility
1750 changes to the current buffer."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-open-non-existing-files nil
1755 "Non-nil means `org-open-file' will open non-existing files.
1756 When nil, an error will be generated.
1757 This variable applies only to external applications because they
1758 might choke on non-existing files. If the link is to a file that
1759 will be opened in Emacs, the variable is ignored."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-directory-means-index-dot-org nil
1764 "Non-nil means a link to a directory really means to index.org.
1765 When nil, following a directory link will run dired or open a finder/explorer
1766 window on that directory."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1771 "Function and arguments to call for following mailto links.
1772 This is a list with the first element being a Lisp function, and the
1773 remaining elements being arguments to the function. In string arguments,
1774 %a will be replaced by the address, and %s will be replaced by the subject
1775 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1776 :group 'org-link-follow
1777 :type '(choice
1778 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1779 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1780 (const :tag "message-mail" (message-mail "%a" "%s"))
1781 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1783 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1784 "Non-nil means ask for confirmation before executing shell links.
1785 Shell links can be dangerous: just think about a link
1787 [[shell:rm -rf ~/*][Google Search]]
1789 This link would show up in your Org-mode document as \"Google Search\",
1790 but really it would remove your entire home directory.
1791 Therefore we advise against setting this variable to nil.
1792 Just change it to `y-or-n-p' if you want to confirm with a
1793 single keystroke rather than having to type \"yes\"."
1794 :group 'org-link-follow
1795 :type '(choice
1796 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1797 (const :tag "with y-or-n (faster)" y-or-n-p)
1798 (const :tag "no confirmation (dangerous)" nil)))
1799 (put 'org-confirm-shell-link-function
1800 'safe-local-variable
1801 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1803 (defcustom org-confirm-shell-link-not-regexp ""
1804 "A regexp to skip confirmation for shell links."
1805 :group 'org-link-follow
1806 :version "24.1"
1807 :type 'regexp)
1809 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1810 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1811 Elisp links can be dangerous: just think about a link
1813 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1815 This link would show up in your Org-mode document as \"Google Search\",
1816 but really it would remove your entire home directory.
1817 Therefore we advise against setting this variable to nil.
1818 Just change it to `y-or-n-p' if you want to confirm with a
1819 single keystroke rather than having to type \"yes\"."
1820 :group 'org-link-follow
1821 :type '(choice
1822 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1823 (const :tag "with y-or-n (faster)" y-or-n-p)
1824 (const :tag "no confirmation (dangerous)" nil)))
1825 (put 'org-confirm-shell-link-function
1826 'safe-local-variable
1827 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1829 (defcustom org-confirm-elisp-link-not-regexp ""
1830 "A regexp to skip confirmation for Elisp links."
1831 :group 'org-link-follow
1832 :version "24.1"
1833 :type 'regexp)
1835 (defconst org-file-apps-defaults-gnu
1836 '((remote . emacs)
1837 (system . mailcap)
1838 (t . mailcap))
1839 "Default file applications on a UNIX or GNU/Linux system.
1840 See `org-file-apps'.")
1842 (defconst org-file-apps-defaults-macosx
1843 '((remote . emacs)
1844 (t . "open %s")
1845 (system . "open %s")
1846 ("ps.gz" . "gv %s")
1847 ("eps.gz" . "gv %s")
1848 ("dvi" . "xdvi %s")
1849 ("fig" . "xfig %s"))
1850 "Default file applications on a MacOS X system.
1851 The system \"open\" is known as a default, but we use X11 applications
1852 for some files for which the OS does not have a good default.
1853 See `org-file-apps'.")
1855 (defconst org-file-apps-defaults-windowsnt
1856 (list
1857 '(remote . emacs)
1858 (cons t
1859 (list (if (featurep 'xemacs)
1860 'mswindows-shell-execute
1861 'w32-shell-execute)
1862 "open" 'file))
1863 (cons 'system
1864 (list (if (featurep 'xemacs)
1865 'mswindows-shell-execute
1866 'w32-shell-execute)
1867 "open" 'file)))
1868 "Default file applications on a Windows NT system.
1869 The system \"open\" is used for most files.
1870 See `org-file-apps'.")
1872 (defcustom org-file-apps
1874 (auto-mode . emacs)
1875 ("\\.mm\\'" . default)
1876 ("\\.x?html?\\'" . default)
1877 ("\\.pdf\\'" . default)
1879 "External applications for opening `file:path' items in a document.
1880 Org-mode uses system defaults for different file types, but
1881 you can use this variable to set the application for a given file
1882 extension. The entries in this list are cons cells where the car identifies
1883 files and the cdr the corresponding command. Possible values for the
1884 file identifier are
1885 \"string\" A string as a file identifier can be interpreted in different
1886 ways, depending on its contents:
1888 - Alphanumeric characters only:
1889 Match links with this file extension.
1890 Example: (\"pdf\" . \"evince %s\")
1891 to open PDFs with evince.
1893 - Regular expression: Match links where the
1894 filename matches the regexp. If you want to
1895 use groups here, use shy groups.
1897 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1898 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1899 to open *.html and *.xhtml with firefox.
1901 - Regular expression which contains (non-shy) groups:
1902 Match links where the whole link, including \"::\", and
1903 anything after that, matches the regexp.
1904 In a custom command string, %1, %2, etc. are replaced with
1905 the parts of the link that were matched by the groups.
1906 For backwards compatibility, if a command string is given
1907 that does not use any of the group matches, this case is
1908 handled identically to the second one (i.e. match against
1909 file name only).
1910 In a custom lisp form, you can access the group matches with
1911 (match-string n link).
1913 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1914 to open [[file:document.pdf::5]] with evince at page 5.
1916 `directory' Matches a directory
1917 `remote' Matches a remote file, accessible through tramp or efs.
1918 Remote files most likely should be visited through Emacs
1919 because external applications cannot handle such paths.
1920 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1921 so all files Emacs knows how to handle. Using this with
1922 command `emacs' will open most files in Emacs. Beware that this
1923 will also open html files inside Emacs, unless you add
1924 (\"html\" . default) to the list as well.
1925 t Default for files not matched by any of the other options.
1926 `system' The system command to open files, like `open' on Windows
1927 and Mac OS X, and mailcap under GNU/Linux. This is the command
1928 that will be selected if you call `C-c C-o' with a double
1929 \\[universal-argument] \\[universal-argument] prefix.
1931 Possible values for the command are:
1932 `emacs' The file will be visited by the current Emacs process.
1933 `default' Use the default application for this file type, which is the
1934 association for t in the list, most likely in the system-specific
1935 part.
1936 This can be used to overrule an unwanted setting in the
1937 system-specific variable.
1938 `system' Use the system command for opening files, like \"open\".
1939 This command is specified by the entry whose car is `system'.
1940 Most likely, the system-specific version of this variable
1941 does define this command, but you can overrule/replace it
1942 here.
1943 string A command to be executed by a shell; %s will be replaced
1944 by the path to the file.
1945 sexp A Lisp form which will be evaluated. The file path will
1946 be available in the Lisp variable `file'.
1947 For more examples, see the system specific constants
1948 `org-file-apps-defaults-macosx'
1949 `org-file-apps-defaults-windowsnt'
1950 `org-file-apps-defaults-gnu'."
1951 :group 'org-link-follow
1952 :type '(repeat
1953 (cons (choice :value ""
1954 (string :tag "Extension")
1955 (const :tag "System command to open files" system)
1956 (const :tag "Default for unrecognized files" t)
1957 (const :tag "Remote file" remote)
1958 (const :tag "Links to a directory" directory)
1959 (const :tag "Any files that have Emacs modes"
1960 auto-mode))
1961 (choice :value ""
1962 (const :tag "Visit with Emacs" emacs)
1963 (const :tag "Use default" default)
1964 (const :tag "Use the system command" system)
1965 (string :tag "Command")
1966 (sexp :tag "Lisp form")))))
1968 (defcustom org-doi-server-url "http://dx.doi.org/"
1969 "The URL of the DOI server."
1970 :type 'string
1971 :version "24.3"
1972 :group 'org-link-follow)
1974 (defgroup org-refile nil
1975 "Options concerning refiling entries in Org-mode."
1976 :tag "Org Refile"
1977 :group 'org)
1979 (defcustom org-directory "~/org"
1980 "Directory with org files.
1981 This is just a default location to look for Org files. There is no need
1982 at all to put your files into this directory. It is only used in the
1983 following situations:
1985 1. When a capture template specifies a target file that is not an
1986 absolute path. The path will then be interpreted relative to
1987 `org-directory'
1988 2. When a capture note is filed away in an interactive way (when exiting the
1989 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1990 with `org-directory' as the default path."
1991 :group 'org-refile
1992 :group 'org-remember
1993 :group 'org-capture
1994 :type 'directory)
1996 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1997 "Default target for storing notes.
1998 Used as a fall back file for org-remember.el and org-capture.el, for
1999 templates that do not specify a target file."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type '(choice
2004 (const :tag "Default from remember-data-file" nil)
2005 file))
2007 (defcustom org-goto-interface 'outline
2008 "The default interface to be used for `org-goto'.
2009 Allowed values are:
2010 outline The interface shows an outline of the relevant file
2011 and the correct heading is found by moving through
2012 the outline or by searching with incremental search.
2013 outline-path-completion Headlines in the current buffer are offered via
2014 completion. This is the interface also used by
2015 the refile command."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Outline" outline)
2019 (const :tag "Outline-path-completion" outline-path-completion)))
2021 (defcustom org-goto-max-level 5
2022 "Maximum target level when running `org-goto' with refile interface."
2023 :group 'org-refile
2024 :type 'integer)
2026 (defcustom org-reverse-note-order nil
2027 "Non-nil means store new notes at the beginning of a file or entry.
2028 When nil, new notes will be filed to the end of a file or entry.
2029 This can also be a list with cons cells of regular expressions that
2030 are matched against file names, and values."
2031 :group 'org-remember
2032 :group 'org-capture
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Reverse always" t)
2036 (const :tag "Reverse never" nil)
2037 (repeat :tag "By file name regexp"
2038 (cons regexp boolean))))
2040 (defcustom org-log-refile nil
2041 "Information to record when a task is refiled.
2043 Possible values are:
2045 nil Don't add anything
2046 time Add a time stamp to the task
2047 note Prompt for a note and add it with template `org-log-note-headings'
2049 This option can also be set with on a per-file-basis with
2051 #+STARTUP: nologrefile
2052 #+STARTUP: logrefile
2053 #+STARTUP: lognoterefile
2055 You can have local logging settings for a subtree by setting the LOGGING
2056 property to one or more of these keywords.
2058 When bulk-refiling from the agenda, the value `note' is forbidden and
2059 will temporarily be changed to `time'."
2060 :group 'org-refile
2061 :group 'org-progress
2062 :version "24.1"
2063 :type '(choice
2064 (const :tag "No logging" nil)
2065 (const :tag "Record timestamp" time)
2066 (const :tag "Record timestamp with note." note)))
2068 (defcustom org-refile-targets nil
2069 "Targets for refiling entries with \\[org-refile].
2070 This is a list of cons cells. Each cell contains:
2071 - a specification of the files to be considered, either a list of files,
2072 or a symbol whose function or variable value will be used to retrieve
2073 a file name or a list of file names. If you use `org-agenda-files' for
2074 that, all agenda files will be scanned for targets. Nil means consider
2075 headings in the current buffer.
2076 - A specification of how to find candidate refile targets. This may be
2077 any of:
2078 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2079 This tag has to be present in all target headlines, inheritance will
2080 not be considered.
2081 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2082 todo keyword.
2083 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2084 headlines that are refiling targets.
2085 - a cons cell (:level . N). Any headline of level N is considered a target.
2086 Note that, when `org-odd-levels-only' is set, level corresponds to
2087 order in hierarchy, not to the number of stars.
2088 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2089 Note that, when `org-odd-levels-only' is set, level corresponds to
2090 order in hierarchy, not to the number of stars.
2092 Each element of this list generates a set of possible targets.
2093 The union of these sets is presented (with completion) to
2094 the user by `org-refile'.
2096 You can set the variable `org-refile-target-verify-function' to a function
2097 to verify each headline found by the simple criteria above.
2099 When this variable is nil, all top-level headlines in the current buffer
2100 are used, equivalent to the value `((nil . (:level . 1))'."
2101 :group 'org-refile
2102 :type '(repeat
2103 (cons
2104 (choice :value org-agenda-files
2105 (const :tag "All agenda files" org-agenda-files)
2106 (const :tag "Current buffer" nil)
2107 (function) (variable) (file))
2108 (choice :tag "Identify target headline by"
2109 (cons :tag "Specific tag" (const :value :tag) (string))
2110 (cons :tag "TODO keyword" (const :value :todo) (string))
2111 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2112 (cons :tag "Level number" (const :value :level) (integer))
2113 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2115 (defcustom org-refile-target-verify-function nil
2116 "Function to verify if the headline at point should be a refile target.
2117 The function will be called without arguments, with point at the
2118 beginning of the headline. It should return t and leave point
2119 where it is if the headline is a valid target for refiling.
2121 If the target should not be selected, the function must return nil.
2122 In addition to this, it may move point to a place from where the search
2123 should be continued. For example, the function may decide that the entire
2124 subtree of the current entry should be excluded and move point to the end
2125 of the subtree."
2126 :group 'org-refile
2127 :type 'function)
2129 (defcustom org-refile-use-cache nil
2130 "Non-nil means cache refile targets to speed up the process.
2131 The cache for a particular file will be updated automatically when
2132 the buffer has been killed, or when any of the marker used for flagging
2133 refile targets no longer points at a live buffer.
2134 If you have added new entries to a buffer that might themselves be targets,
2135 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2136 find that easier, `C-u C-u C-u C-c C-w'."
2137 :group 'org-refile
2138 :version "24.1"
2139 :type 'boolean)
2141 (defcustom org-refile-use-outline-path nil
2142 "Non-nil means provide refile targets as paths.
2143 So a level 3 headline will be available as level1/level2/level3.
2145 When the value is `file', also include the file name (without directory)
2146 into the path. In this case, you can also stop the completion after
2147 the file name, to get entries inserted as top level in the file.
2149 When `full-file-path', include the full file path."
2150 :group 'org-refile
2151 :type '(choice
2152 (const :tag "Not" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Start with file name" file)
2155 (const :tag "Start with full file path" full-file-path)))
2157 (defcustom org-outline-path-complete-in-steps t
2158 "Non-nil means complete the outline path in hierarchical steps.
2159 When Org-mode uses the refile interface to select an outline path
2160 \(see variable `org-refile-use-outline-path'), the completion of
2161 the path can be done is a single go, or if can be done in steps down
2162 the headline hierarchy. Going in steps is probably the best if you
2163 do not use a special completion package like `ido' or `icicles'.
2164 However, when using these packages, going in one step can be very
2165 fast, while still showing the whole path to the entry."
2166 :group 'org-refile
2167 :type 'boolean)
2169 (defcustom org-refile-allow-creating-parent-nodes nil
2170 "Non-nil means allow to create new nodes as refile targets.
2171 New nodes are then created by adding \"/new node name\" to the completion
2172 of an existing node. When the value of this variable is `confirm',
2173 new node creation must be confirmed by the user (recommended)
2174 When nil, the completion must match an existing entry.
2176 Note that, if the new heading is not seen by the criteria
2177 listed in `org-refile-targets', multiple instances of the same
2178 heading would be created by trying again to file under the new
2179 heading."
2180 :group 'org-refile
2181 :type '(choice
2182 (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "Prompt for confirmation" confirm)))
2186 (defcustom org-refile-active-region-within-subtree nil
2187 "Non-nil means also refile active region within a subtree.
2189 By default `org-refile' doesn't allow refiling regions if they
2190 don't contain a set of subtrees, but it might be convenient to
2191 do so sometimes: in that case, the first line of the region is
2192 converted to a headline before refiling."
2193 :group 'org-refile
2194 :version "24.1"
2195 :type 'boolean)
2197 (defgroup org-todo nil
2198 "Options concerning TODO items in Org-mode."
2199 :tag "Org TODO"
2200 :group 'org)
2202 (defgroup org-progress nil
2203 "Options concerning Progress logging in Org-mode."
2204 :tag "Org Progress"
2205 :group 'org-time)
2207 (defvar org-todo-interpretation-widgets
2208 '((:tag "Sequence (cycling hits every state)" sequence)
2209 (:tag "Type (cycling directly to DONE)" type))
2210 "The available interpretation symbols for customizing `org-todo-keywords'.
2211 Interested libraries should add to this list.")
2213 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2214 "List of TODO entry keyword sequences and their interpretation.
2215 \\<org-mode-map>This is a list of sequences.
2217 Each sequence starts with a symbol, either `sequence' or `type',
2218 indicating if the keywords should be interpreted as a sequence of
2219 action steps, or as different types of TODO items. The first
2220 keywords are states requiring action - these states will select a headline
2221 for inclusion into the global TODO list Org-mode produces. If one of
2222 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2223 signify that no further action is necessary. If \"|\" is not found,
2224 the last keyword is treated as the only DONE state of the sequence.
2226 The command \\[org-todo] cycles an entry through these states, and one
2227 additional state where no keyword is present. For details about this
2228 cycling, see the manual.
2230 TODO keywords and interpretation can also be set on a per-file basis with
2231 the special #+SEQ_TODO and #+TYP_TODO lines.
2233 Each keyword can optionally specify a character for fast state selection
2234 \(in combination with the variable `org-use-fast-todo-selection')
2235 and specifiers for state change logging, using the same syntax that
2236 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2237 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2238 indicates to record a time stamp each time this state is selected.
2240 Each keyword may also specify if a timestamp or a note should be
2241 recorded when entering or leaving the state, by adding additional
2242 characters in the parenthesis after the keyword. This looks like this:
2243 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2244 record only the time of the state change. With X and Y being either
2245 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2246 Y when leaving the state if and only if the *target* state does not
2247 define X. You may omit any of the fast-selection key or X or /Y,
2248 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2250 For backward compatibility, this variable may also be just a list
2251 of keywords. In this case the interpretation (sequence or type) will be
2252 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2253 :group 'org-todo
2254 :group 'org-keywords
2255 :type '(choice
2256 (repeat :tag "Old syntax, just keywords"
2257 (string :tag "Keyword"))
2258 (repeat :tag "New syntax"
2259 (cons
2260 (choice
2261 :tag "Interpretation"
2262 ;;Quick and dirty way to see
2263 ;;`org-todo-interpretations'. This takes the
2264 ;;place of item arguments
2265 :convert-widget
2266 (lambda (widget)
2267 (widget-put widget
2268 :args (mapcar
2269 #'(lambda (x)
2270 (widget-convert
2271 (cons 'const x)))
2272 org-todo-interpretation-widgets))
2273 widget))
2274 (repeat
2275 (string :tag "Keyword"))))))
2277 (defvar org-todo-keywords-1 nil
2278 "All TODO and DONE keywords active in a buffer.")
2279 (make-variable-buffer-local 'org-todo-keywords-1)
2280 (defvar org-todo-keywords-for-agenda nil)
2281 (defvar org-done-keywords-for-agenda nil)
2282 (defvar org-drawers-for-agenda nil)
2283 (defvar org-todo-keyword-alist-for-agenda nil)
2284 (defvar org-tag-alist-for-agenda nil)
2285 (defvar org-agenda-contributing-files nil)
2286 (defvar org-not-done-keywords nil)
2287 (make-variable-buffer-local 'org-not-done-keywords)
2288 (defvar org-done-keywords nil)
2289 (make-variable-buffer-local 'org-done-keywords)
2290 (defvar org-todo-heads nil)
2291 (make-variable-buffer-local 'org-todo-heads)
2292 (defvar org-todo-sets nil)
2293 (make-variable-buffer-local 'org-todo-sets)
2294 (defvar org-todo-log-states nil)
2295 (make-variable-buffer-local 'org-todo-log-states)
2296 (defvar org-todo-kwd-alist nil)
2297 (make-variable-buffer-local 'org-todo-kwd-alist)
2298 (defvar org-todo-key-alist nil)
2299 (make-variable-buffer-local 'org-todo-key-alist)
2300 (defvar org-todo-key-trigger nil)
2301 (make-variable-buffer-local 'org-todo-key-trigger)
2303 (defcustom org-todo-interpretation 'sequence
2304 "Controls how TODO keywords are interpreted.
2305 This variable is in principle obsolete and is only used for
2306 backward compatibility, if the interpretation of todo keywords is
2307 not given already in `org-todo-keywords'. See that variable for
2308 more information."
2309 :group 'org-todo
2310 :group 'org-keywords
2311 :type '(choice (const sequence)
2312 (const type)))
2314 (defcustom org-use-fast-todo-selection t
2315 "Non-nil means use the fast todo selection scheme with C-c C-t.
2316 This variable describes if and under what circumstances the cycling
2317 mechanism for TODO keywords will be replaced by a single-key, direct
2318 selection scheme.
2320 When nil, fast selection is never used.
2322 When the symbol `prefix', it will be used when `org-todo' is called
2323 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2324 `C-u t' in an agenda buffer.
2326 When t, fast selection is used by default. In this case, the prefix
2327 argument forces cycling instead.
2329 In all cases, the special interface is only used if access keys have
2330 actually been assigned by the user, i.e. if keywords in the configuration
2331 are followed by a letter in parenthesis, like TODO(t)."
2332 :group 'org-todo
2333 :type '(choice
2334 (const :tag "Never" nil)
2335 (const :tag "By default" t)
2336 (const :tag "Only with C-u C-c C-t" prefix)))
2338 (defcustom org-provide-todo-statistics t
2339 "Non-nil means update todo statistics after insert and toggle.
2340 ALL-HEADLINES means update todo statistics by including headlines
2341 with no TODO keyword as well, counting them as not done.
2342 A list of TODO keywords means the same, but skip keywords that are
2343 not in this list.
2345 When this is set, todo statistics is updated in the parent of the
2346 current entry each time a todo state is changed."
2347 :group 'org-todo
2348 :type '(choice
2349 (const :tag "Yes, only for TODO entries" t)
2350 (const :tag "Yes, including all entries" 'all-headlines)
2351 (repeat :tag "Yes, for TODOs in this list"
2352 (string :tag "TODO keyword"))
2353 (other :tag "No TODO statistics" nil)))
2355 (defcustom org-hierarchical-todo-statistics t
2356 "Non-nil means TODO statistics covers just direct children.
2357 When nil, all entries in the subtree are considered.
2358 This has only an effect if `org-provide-todo-statistics' is set.
2359 To set this to nil for only a single subtree, use a COOKIE_DATA
2360 property and include the word \"recursive\" into the value."
2361 :group 'org-todo
2362 :type 'boolean)
2364 (defcustom org-after-todo-state-change-hook nil
2365 "Hook which is run after the state of a TODO item was changed.
2366 The new state (a string with a TODO keyword, or nil) is available in the
2367 Lisp variable `org-state'."
2368 :group 'org-todo
2369 :type 'hook)
2371 (defvar org-blocker-hook nil
2372 "Hook for functions that are allowed to block a state change.
2374 Functions in this hook should not modify the buffer.
2375 Each function gets as its single argument a property list,
2376 see `org-trigger-hook' for more information about this list.
2378 If any of the functions in this hook returns nil, the state change
2379 is blocked.")
2381 (defvar org-trigger-hook nil
2382 "Hook for functions that are triggered by a state change.
2384 Each function gets as its single argument a property list with at
2385 least the following elements:
2387 (:type type-of-change :position pos-at-entry-start
2388 :from old-state :to new-state)
2390 Depending on the type, more properties may be present.
2392 This mechanism is currently implemented for:
2394 TODO state changes
2395 ------------------
2396 :type todo-state-change
2397 :from previous state (keyword as a string), or nil, or a symbol
2398 'todo' or 'done', to indicate the general type of state.
2399 :to new state, like in :from")
2401 (defcustom org-enforce-todo-dependencies nil
2402 "Non-nil means undone TODO entries will block switching the parent to DONE.
2403 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2404 be blocked if any prior sibling is not yet done.
2405 Finally, if the parent is blocked because of ordered siblings of its own,
2406 the child will also be blocked."
2407 :set (lambda (var val)
2408 (set var val)
2409 (if val
2410 (add-hook 'org-blocker-hook
2411 'org-block-todo-from-children-or-siblings-or-parent)
2412 (remove-hook 'org-blocker-hook
2413 'org-block-todo-from-children-or-siblings-or-parent)))
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-enforce-todo-checkbox-dependencies nil
2418 "Non-nil means unchecked boxes will block switching the parent to DONE.
2419 When this is nil, checkboxes have no influence on switching TODO states.
2420 When non-nil, you first need to check off all check boxes before the TODO
2421 entry can be switched to DONE.
2422 This variable needs to be set before org.el is loaded, and you need to
2423 restart Emacs after a change to make the change effective. The only way
2424 to change is while Emacs is running is through the customize interface."
2425 :set (lambda (var val)
2426 (set var val)
2427 (if val
2428 (add-hook 'org-blocker-hook
2429 'org-block-todo-from-checkboxes)
2430 (remove-hook 'org-blocker-hook
2431 'org-block-todo-from-checkboxes)))
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-treat-insert-todo-heading-as-state-change nil
2436 "Non-nil means inserting a TODO heading is treated as state change.
2437 So when the command \\[org-insert-todo-heading] is used, state change
2438 logging will apply if appropriate. When nil, the new TODO item will
2439 be inserted directly, and no logging will take place."
2440 :group 'org-todo
2441 :type 'boolean)
2443 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2444 "Non-nil means switching TODO states with S-cursor counts as state change.
2445 This is the default behavior. However, setting this to nil allows a
2446 convenient way to select a TODO state and bypass any logging associated
2447 with that."
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-todo-state-tags-triggers nil
2452 "Tag changes that should be triggered by TODO state changes.
2453 This is a list. Each entry is
2455 (state-change (tag . flag) .......)
2457 State-change can be a string with a state, and empty string to indicate the
2458 state that has no TODO keyword, or it can be one of the symbols `todo'
2459 or `done', meaning any not-done or done state, respectively."
2460 :group 'org-todo
2461 :group 'org-tags
2462 :type '(repeat
2463 (cons (choice :tag "When changing to"
2464 (const :tag "Not-done state" todo)
2465 (const :tag "Done state" done)
2466 (string :tag "State"))
2467 (repeat
2468 (cons :tag "Tag action"
2469 (string :tag "Tag")
2470 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2472 (defcustom org-log-done nil
2473 "Information to record when a task moves to the DONE state.
2475 Possible values are:
2477 nil Don't add anything, just change the keyword
2478 time Add a time stamp to the task
2479 note Prompt for a note and add it with template `org-log-note-headings'
2481 This option can also be set with on a per-file-basis with
2483 #+STARTUP: nologdone
2484 #+STARTUP: logdone
2485 #+STARTUP: lognotedone
2487 You can have local logging settings for a subtree by setting the LOGGING
2488 property to one or more of these keywords."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "No logging" nil)
2493 (const :tag "Record CLOSED timestamp" time)
2494 (const :tag "Record CLOSED timestamp with note." note)))
2496 ;; Normalize old uses of org-log-done.
2497 (cond
2498 ((eq org-log-done t) (setq org-log-done 'time))
2499 ((and (listp org-log-done) (memq 'done org-log-done))
2500 (setq org-log-done 'note)))
2502 (defcustom org-log-reschedule nil
2503 "Information to record when the scheduling date of a tasks is modified.
2505 Possible values are:
2507 nil Don't add anything, just change the date
2508 time Add a time stamp to the task
2509 note Prompt for a note and add it with template `org-log-note-headings'
2511 This option can also be set with on a per-file-basis with
2513 #+STARTUP: nologreschedule
2514 #+STARTUP: logreschedule
2515 #+STARTUP: lognotereschedule"
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type '(choice
2519 (const :tag "No logging" nil)
2520 (const :tag "Record timestamp" time)
2521 (const :tag "Record timestamp with note." note)))
2523 (defcustom org-log-redeadline nil
2524 "Information to record when the deadline date of a tasks is modified.
2526 Possible values are:
2528 nil Don't add anything, just change the date
2529 time Add a time stamp to the task
2530 note Prompt for a note and add it with template `org-log-note-headings'
2532 This option can also be set with on a per-file-basis with
2534 #+STARTUP: nologredeadline
2535 #+STARTUP: logredeadline
2536 #+STARTUP: lognoteredeadline
2538 You can have local logging settings for a subtree by setting the LOGGING
2539 property to one or more of these keywords."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type '(choice
2543 (const :tag "No logging" nil)
2544 (const :tag "Record timestamp" time)
2545 (const :tag "Record timestamp with note." note)))
2547 (defcustom org-log-note-clock-out nil
2548 "Non-nil means record a note when clocking out of an item.
2549 This can also be configured on a per-file basis by adding one of
2550 the following lines anywhere in the buffer:
2552 #+STARTUP: lognoteclock-out
2553 #+STARTUP: nolognoteclock-out"
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type 'boolean)
2558 (defcustom org-log-done-with-time t
2559 "Non-nil means the CLOSED time stamp will contain date and time.
2560 When nil, only the date will be recorded."
2561 :group 'org-progress
2562 :type 'boolean)
2564 (defcustom org-log-note-headings
2565 '((done . "CLOSING NOTE %t")
2566 (state . "State %-12s from %-12S %t")
2567 (note . "Note taken on %t")
2568 (reschedule . "Rescheduled from %S on %t")
2569 (delschedule . "Not scheduled, was %S on %t")
2570 (redeadline . "New deadline from %S on %t")
2571 (deldeadline . "Removed deadline, was %S on %t")
2572 (refile . "Refiled on %t")
2573 (clock-out . ""))
2574 "Headings for notes added to entries.
2575 The value is an alist, with the car being a symbol indicating the note
2576 context, and the cdr is the heading to be used. The heading may also be the
2577 empty string.
2578 %t in the heading will be replaced by a time stamp.
2579 %T will be an active time stamp instead the default inactive one
2580 %d will be replaced by a short-format time stamp.
2581 %D will be replaced by an active short-format time stamp.
2582 %s will be replaced by the new TODO state, in double quotes.
2583 %S will be replaced by the old TODO state, in double quotes.
2584 %u will be replaced by the user name.
2585 %U will be replaced by the full user name.
2587 In fact, it is not a good idea to change the `state' entry, because
2588 agenda log mode depends on the format of these entries."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(list :greedy t
2592 (cons (const :tag "Heading when closing an item" done) string)
2593 (cons (const :tag
2594 "Heading when changing todo state (todo sequence only)"
2595 state) string)
2596 (cons (const :tag "Heading when just taking a note" note) string)
2597 (cons (const :tag "Heading when clocking out" clock-out) string)
2598 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2599 (cons (const :tag "Heading when rescheduling" reschedule) string)
2600 (cons (const :tag "Heading when changing deadline" redeadline) string)
2601 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2602 (cons (const :tag "Heading when refiling" refile) string)))
2604 (unless (assq 'note org-log-note-headings)
2605 (push '(note . "%t") org-log-note-headings))
2607 (defcustom org-log-into-drawer nil
2608 "Non-nil means insert state change notes and time stamps into a drawer.
2609 When nil, state changes notes will be inserted after the headline and
2610 any scheduling and clock lines, but not inside a drawer.
2612 The value of this variable should be the name of the drawer to use.
2613 LOGBOOK is proposed as the default drawer for this purpose, you can
2614 also set this to a string to define the drawer of your choice.
2616 A value of t is also allowed, representing \"LOGBOOK\".
2618 A value of t or nil can also be set with on a per-file-basis with
2620 #+STARTUP: logdrawer
2621 #+STARTUP: nologdrawer
2623 If this variable is set, `org-log-state-notes-insert-after-drawers'
2624 will be ignored.
2626 You can set the property LOG_INTO_DRAWER to overrule this setting for
2627 a subtree."
2628 :group 'org-todo
2629 :group 'org-progress
2630 :type '(choice
2631 (const :tag "Not into a drawer" nil)
2632 (const :tag "LOGBOOK" t)
2633 (string :tag "Other")))
2635 (if (fboundp 'defvaralias)
2636 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2638 (defun org-log-into-drawer ()
2639 "Return the value of `org-log-into-drawer', but let properties overrule.
2640 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2641 used instead of the default value."
2642 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2643 (cond
2644 ((not p) org-log-into-drawer)
2645 ((equal p "nil") nil)
2646 ((equal p "t") "LOGBOOK")
2647 (t p))))
2649 (defcustom org-log-state-notes-insert-after-drawers nil
2650 "Non-nil means insert state change notes after any drawers in entry.
2651 Only the drawers that *immediately* follow the headline and the
2652 deadline/scheduled line are skipped.
2653 When nil, insert notes right after the heading and perhaps the line
2654 with deadline/scheduling if present.
2656 This variable will have no effect if `org-log-into-drawer' is
2657 set."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-log-states-order-reversed t
2663 "Non-nil means the latest state note will be directly after heading.
2664 When nil, the state change notes will be ordered according to time.
2666 This option can also be set with on a per-file-basis with
2668 #+STARTUP: logstatesreversed
2669 #+STARTUP: nologstatesreversed"
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type 'boolean)
2674 (defcustom org-todo-repeat-to-state nil
2675 "The TODO state to which a repeater should return the repeating task.
2676 By default this is the first task in a TODO sequence, or the previous state
2677 in a TODO_TYP set. But you can specify another task here.
2678 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2679 :group 'org-todo
2680 :version "24.1"
2681 :type '(choice (const :tag "Head of sequence" nil)
2682 (string :tag "Specific state")))
2684 (defcustom org-log-repeat 'time
2685 "Non-nil means record moving through the DONE state when triggering repeat.
2686 An auto-repeating task is immediately switched back to TODO when
2687 marked DONE. If you are not logging state changes (by adding \"@\"
2688 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2689 record a closing note, there will be no record of the task moving
2690 through DONE. This variable forces taking a note anyway.
2692 nil Don't force a record
2693 time Record a time stamp
2694 note Prompt for a note and add it with template `org-log-note-headings'
2696 This option can also be set with on a per-file-basis with
2698 #+STARTUP: nologrepeat
2699 #+STARTUP: logrepeat
2700 #+STARTUP: lognoterepeat
2702 You can have local logging settings for a subtree by setting the LOGGING
2703 property to one or more of these keywords."
2704 :group 'org-todo
2705 :group 'org-progress
2706 :type '(choice
2707 (const :tag "Don't force a record" nil)
2708 (const :tag "Force recording the DONE state" time)
2709 (const :tag "Force recording a note with the DONE state" note)))
2712 (defgroup org-priorities nil
2713 "Priorities in Org-mode."
2714 :tag "Org Priorities"
2715 :group 'org-todo)
2717 (defcustom org-enable-priority-commands t
2718 "Non-nil means priority commands are active.
2719 When nil, these commands will be disabled, so that you never accidentally
2720 set a priority."
2721 :group 'org-priorities
2722 :type 'boolean)
2724 (defcustom org-highest-priority ?A
2725 "The highest priority of TODO items. A character like ?A, ?B etc.
2726 Must have a smaller ASCII number than `org-lowest-priority'."
2727 :group 'org-priorities
2728 :type 'character)
2730 (defcustom org-lowest-priority ?C
2731 "The lowest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a larger ASCII number than `org-highest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-default-priority ?B
2737 "The default priority of TODO items.
2738 This is the priority an item gets if no explicit priority is given.
2739 When starting to cycle on an empty priority the first step in the cycle
2740 depends on `org-priority-start-cycle-with-default'. The resulting first
2741 step priority must not exceed the range from `org-highest-priority' to
2742 `org-lowest-priority' which means that `org-default-priority' has to be
2743 in this range exclusive or inclusive the range boundaries. Else the
2744 first step refuses to set the default and the second will fall back
2745 to (depending on the command used) the highest or lowest priority."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-priority-start-cycle-with-default t
2750 "Non-nil means start with default priority when starting to cycle.
2751 When this is nil, the first step in the cycle will be (depending on the
2752 command used) one higher or lower than the default priority.
2753 See also `org-default-priority'."
2754 :group 'org-priorities
2755 :type 'boolean)
2757 (defcustom org-get-priority-function nil
2758 "Function to extract the priority from a string.
2759 The string is normally the headline. If this is nil Org computes the
2760 priority from the priority cookie like [#A] in the headline. It returns
2761 an integer, increasing by 1000 for each priority level.
2762 The user can set a different function here, which should take a string
2763 as an argument and return the numeric priority."
2764 :group 'org-priorities
2765 :version "24.1"
2766 :type 'function)
2768 (defgroup org-time nil
2769 "Options concerning time stamps and deadlines in Org-mode."
2770 :tag "Org Time"
2771 :group 'org)
2773 (defcustom org-insert-labeled-timestamps-at-point nil
2774 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2775 When nil, these labeled time stamps are forces into the second line of an
2776 entry, just after the headline. When scheduling from the global TODO list,
2777 the time stamp will always be forced into the second line."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2782 "Formats for `format-time-string' which are used for time stamps.
2783 It is not recommended to change this constant.")
2785 (defcustom org-time-stamp-rounding-minutes '(0 5)
2786 "Number of minutes to round time stamps to.
2787 These are two values, the first applies when first creating a time stamp.
2788 The second applies when changing it with the commands `S-up' and `S-down'.
2789 When changing the time stamp, this means that it will change in steps
2790 of N minutes, as given by the second value.
2792 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2793 numbers should be factors of 60, so for example 5, 10, 15.
2795 When this is larger than 1, you can still force an exact time stamp by using
2796 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2797 and by using a prefix arg to `S-up/down' to specify the exact number
2798 of minutes to shift."
2799 :group 'org-time
2800 :get #'(lambda (var) ; Make sure both elements are there
2801 (if (integerp (default-value var))
2802 (list (default-value var) 5)
2803 (default-value var)))
2804 :type '(list
2805 (integer :tag "when inserting times")
2806 (integer :tag "when modifying times")))
2808 ;; Normalize old customizations of this variable.
2809 (when (integerp org-time-stamp-rounding-minutes)
2810 (setq org-time-stamp-rounding-minutes
2811 (list org-time-stamp-rounding-minutes
2812 org-time-stamp-rounding-minutes)))
2814 (defcustom org-display-custom-times nil
2815 "Non-nil means overlay custom formats over all time stamps.
2816 The formats are defined through the variable `org-time-stamp-custom-formats'.
2817 To turn this on on a per-file basis, insert anywhere in the file:
2818 #+STARTUP: customtime"
2819 :group 'org-time
2820 :set 'set-default
2821 :type 'sexp)
2822 (make-variable-buffer-local 'org-display-custom-times)
2824 (defcustom org-time-stamp-custom-formats
2825 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2826 "Custom formats for time stamps. See `format-time-string' for the syntax.
2827 These are overlaid over the default ISO format if the variable
2828 `org-display-custom-times' is set. Time like %H:%M should be at the
2829 end of the second format. The custom formats are also honored by export
2830 commands, if custom time display is turned on at the time of export."
2831 :group 'org-time
2832 :type 'sexp)
2834 (defun org-time-stamp-format (&optional long inactive)
2835 "Get the right format for a time string."
2836 (let ((f (if long (cdr org-time-stamp-formats)
2837 (car org-time-stamp-formats))))
2838 (if inactive
2839 (concat "[" (substring f 1 -1) "]")
2840 f)))
2842 (defcustom org-time-clocksum-format
2843 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2844 "The format string used when creating CLOCKSUM lines.
2845 This is also used when Org mode generates a time duration.
2847 The value can be a single format string containing two
2848 %-sequences, which will be filled with the number of hours and
2849 minutes in that order.
2851 Alternatively, the value can be a plist associating any of the
2852 keys :years, :months, :weeks, :days, :hours or :minutes with
2853 format strings. The time duration is formatted using only the
2854 time components that are needed and concatenating the results.
2855 If a time unit in absent, it falls back to the next smallest
2856 unit.
2858 The keys :require-years, :require-months, :require-days,
2859 :require-weeks, :require-hours, :require-minutes are also
2860 meaningful. A non-nil value for these keys indicates that the
2861 corresponding time component should always be included, even if
2862 its value is 0.
2865 For example,
2867 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2868 :require-minutes t)
2870 means durations longer than a day will be expressed in days,
2871 hours and minutes, and durations less than a day will always be
2872 expressed in hours and minutes (even for durations less than an
2873 hour).
2875 The value
2877 \(:days \"%dd\" :minutes \"%dm\")
2879 means durations longer than a day will be expressed in days and
2880 minutes, and durations less than a day will be expressed entirely
2881 in minutes (even for durations longer than an hour)."
2882 :group 'org-time
2883 :group 'org-clock
2884 :version "24.3"
2885 :type '(choice (string :tag "Format string")
2886 (set :tag "Plist"
2887 (group :inline t (const :tag "Years" :years)
2888 (string :tag "Format string"))
2889 (group :inline t
2890 (const :tag "Always show years" :require-years)
2891 (const t))
2892 (group :inline t (const :tag "Months" :months)
2893 (string :tag "Format string"))
2894 (group :inline t
2895 (const :tag "Always show months" :require-months)
2896 (const t))
2897 (group :inline t (const :tag "Weeks" :weeks)
2898 (string :tag "Format string"))
2899 (group :inline t
2900 (const :tag "Always show weeks" :require-weeks)
2901 (const t))
2902 (group :inline t (const :tag "Days" :days)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show days" :require-days)
2906 (const t))
2907 (group :inline t (const :tag "Hours" :hours)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show hours" :require-hours)
2911 (const t))
2912 (group :inline t (const :tag "Minutes" :minutes)
2913 (string :tag "Format string"))
2914 (group :inline t
2915 (const :tag "Always show minutes" :require-minutes)
2916 (const t)))))
2918 (defcustom org-time-clocksum-use-fractional nil
2919 "When non-nil, \\[org-clock-display] uses fractional times.
2920 See `org-time-clocksum-format' for more on time clock formats."
2921 :group 'org-time
2922 :group 'org-clock
2923 :version "24.3"
2924 :type 'boolean)
2926 (defcustom org-time-clocksum-use-effort-durations t
2927 "When non-nil, \\[org-clock-display] uses effort durations.
2928 E.g. by default, one day is considered to be a 8 hours effort,
2929 so a task that has been clocked for 16 hours will be displayed
2930 as during 2 days in the clock display or in the clocktable.
2932 See `org-effort-durations' on how to set effort durations
2933 and `org-time-clocksum-format' for more on time clock formats."
2934 :group 'org-time
2935 :group 'org-clock
2936 :version "24.3"
2937 :type 'boolean)
2939 (defcustom org-time-clocksum-fractional-format "%.2f"
2940 "The format string used when creating CLOCKSUM lines,
2941 or when Org mode generates a time duration, if
2942 `org-time-clocksum-use-fractional' is enabled.
2944 The value can be a single format string containing one
2945 %-sequence, which will be filled with the number of hours as
2946 a float.
2948 Alternatively, the value can be a plist associating any of the
2949 keys :years, :months, :weeks, :days, :hours or :minutes with
2950 a format string. The time duration is formatted using the
2951 largest time unit which gives a non-zero integer part. If all
2952 specified formats have zero integer part, the smallest time unit
2953 is used."
2954 :group 'org-time
2955 :type '(choice (string :tag "Format string")
2956 (set (group :inline t (const :tag "Years" :years)
2957 (string :tag "Format string"))
2958 (group :inline t (const :tag "Months" :months)
2959 (string :tag "Format string"))
2960 (group :inline t (const :tag "Weeks" :weeks)
2961 (string :tag "Format string"))
2962 (group :inline t (const :tag "Days" :days)
2963 (string :tag "Format string"))
2964 (group :inline t (const :tag "Hours" :hours)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string")))))
2969 (defcustom org-deadline-warning-days 14
2970 "Number of days before expiration during which a deadline becomes active.
2971 This variable governs the display in sparse trees and in the agenda.
2972 When 0 or negative, it means use this number (the absolute value of it)
2973 even if a deadline has a different individual lead time specified.
2975 Custom commands can set this variable in the options section."
2976 :group 'org-time
2977 :group 'org-agenda-daily/weekly
2978 :type 'integer)
2980 (defcustom org-scheduled-delay-days 0
2981 "Number of days before a scheduled item becomes active.
2982 This variable governs the display in sparse trees and in the agenda.
2983 The default value (i.e. 0) means: don't delay scheduled item.
2984 When negative, it means use this number (the absolute value of it)
2985 even if a scheduled item has a different individual delay time
2986 specified.
2988 Custom commands can set this variable in the options section."
2989 :group 'org-time
2990 :group 'org-agenda-daily/weekly
2991 :version "24.3"
2992 :type 'integer)
2994 (defcustom org-read-date-prefer-future t
2995 "Non-nil means assume future for incomplete date input from user.
2996 This affects the following situations:
2997 1. The user gives a month but not a year.
2998 For example, if it is April and you enter \"feb 2\", this will be read
2999 as Feb 2, *next* year. \"May 5\", however, will be this year.
3000 2. The user gives a day, but no month.
3001 For example, if today is the 15th, and you enter \"3\", Org-mode will
3002 read this as the third of *next* month. However, if you enter \"17\",
3003 it will be considered as *this* month.
3005 If you set this variable to the symbol `time', then also the following
3006 will work:
3008 3. If the user gives a time.
3009 If the time is before now, it will be interpreted as tomorrow.
3011 Currently none of this works for ISO week specifications.
3013 When this option is nil, the current day, month and year will always be
3014 used as defaults.
3016 See also `org-agenda-jump-prefer-future'."
3017 :group 'org-time
3018 :type '(choice
3019 (const :tag "Never" nil)
3020 (const :tag "Check month and day" t)
3021 (const :tag "Check month, day, and time" time)))
3023 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3024 "Should the agenda jump command prefer the future for incomplete dates?
3025 The default is to do the same as configured in `org-read-date-prefer-future'.
3026 But you can also set a deviating value here.
3027 This may t or nil, or the symbol `org-read-date-prefer-future'."
3028 :group 'org-agenda
3029 :group 'org-time
3030 :version "24.1"
3031 :type '(choice
3032 (const :tag "Use org-read-date-prefer-future"
3033 org-read-date-prefer-future)
3034 (const :tag "Never" nil)
3035 (const :tag "Always" t)))
3037 (defcustom org-read-date-force-compatible-dates t
3038 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3040 Depending on the system Emacs is running on, certain dates cannot
3041 be represented with the type used internally to represent time.
3042 Dates between 1970-1-1 and 2038-1-1 can always be represented
3043 correctly. Some systems allow for earlier dates, some for later,
3044 some for both. One way to find out it to insert any date into an
3045 Org buffer, putting the cursor on the year and hitting S-up and
3046 S-down to test the range.
3048 When this variable is set to t, the date/time prompt will not let
3049 you specify dates outside the 1970-2037 range, so it is certain that
3050 these dates will work in whatever version of Emacs you are
3051 running, and also that you can move a file from one Emacs implementation
3052 to another. WHenever Org is forcing the year for you, it will display
3053 a message and beep.
3055 When this variable is nil, Org will check if the date is
3056 representable in the specific Emacs implementation you are using.
3057 If not, it will force a year, usually the current year, and beep
3058 to remind you. Currently this setting is not recommended because
3059 the likelihood that you will open your Org files in an Emacs that
3060 has limited date range is not negligible.
3062 A workaround for this problem is to use diary sexp dates for time
3063 stamps outside of this range."
3064 :group 'org-time
3065 :version "24.1"
3066 :type 'boolean)
3068 (defcustom org-read-date-display-live t
3069 "Non-nil means display current interpretation of date prompt live.
3070 This display will be in an overlay, in the minibuffer."
3071 :group 'org-time
3072 :type 'boolean)
3074 (defcustom org-read-date-popup-calendar t
3075 "Non-nil means pop up a calendar when prompting for a date.
3076 In the calendar, the date can be selected with mouse-1. However, the
3077 minibuffer will also be active, and you can simply enter the date as well.
3078 When nil, only the minibuffer will be available."
3079 :group 'org-time
3080 :type 'boolean)
3081 (if (fboundp 'defvaralias)
3082 (defvaralias 'org-popup-calendar-for-date-prompt
3083 'org-read-date-popup-calendar))
3085 (make-obsolete-variable
3086 'org-read-date-minibuffer-setup-hook
3087 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3088 (defcustom org-read-date-minibuffer-setup-hook nil
3089 "Hook to be used to set up keys for the date/time interface.
3090 Add key definitions to `minibuffer-local-map', which will be a
3091 temporary copy.
3093 WARNING: This option is obsolete, you should use
3094 `org-read-date-minibuffer-local-map' to set up keys."
3095 :group 'org-time
3096 :type 'hook)
3098 (defcustom org-extend-today-until 0
3099 "The hour when your day really ends. Must be an integer.
3100 This has influence for the following applications:
3101 - When switching the agenda to \"today\". It it is still earlier than
3102 the time given here, the day recognized as TODAY is actually yesterday.
3103 - When a date is read from the user and it is still before the time given
3104 here, the current date and time will be assumed to be yesterday, 23:59.
3105 Also, timestamps inserted in capture templates follow this rule.
3107 IMPORTANT: This is a feature whose implementation is and likely will
3108 remain incomplete. Really, it is only here because past midnight seems to
3109 be the favorite working time of John Wiegley :-)"
3110 :group 'org-time
3111 :type 'integer)
3113 (defcustom org-use-effective-time nil
3114 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3115 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3116 \"effective time\" of any timestamps between midnight and 8am will be
3117 23:59 of the previous day."
3118 :group 'org-time
3119 :version "24.1"
3120 :type 'boolean)
3122 (defcustom org-use-last-clock-out-time-as-effective-time nil
3123 "When non-nil, use the last clock out time for `org-todo'.
3124 Note that this option has precedence over the combined use of
3125 `org-use-effective-time' and `org-extend-today-until'."
3126 :group 'org-time
3127 ;; :version "24.3"
3128 :type 'boolean)
3130 (defcustom org-edit-timestamp-down-means-later nil
3131 "Non-nil means S-down will increase the time in a time stamp.
3132 When nil, S-up will increase."
3133 :group 'org-time
3134 :type 'boolean)
3136 (defcustom org-calendar-follow-timestamp-change t
3137 "Non-nil means make the calendar window follow timestamp changes.
3138 When a timestamp is modified and the calendar window is visible, it will be
3139 moved to the new date."
3140 :group 'org-time
3141 :type 'boolean)
3143 (defgroup org-tags nil
3144 "Options concerning tags in Org-mode."
3145 :tag "Org Tags"
3146 :group 'org)
3148 (defcustom org-tag-alist nil
3149 "List of tags allowed in Org-mode files.
3150 When this list is nil, Org-mode will base TAG input on what is already in the
3151 buffer.
3152 The value of this variable is an alist, the car of each entry must be a
3153 keyword as a string, the cdr may be a character that is used to select
3154 that tag through the fast-tag-selection interface.
3155 See the manual for details."
3156 :group 'org-tags
3157 :type '(repeat
3158 (choice
3159 (cons (string :tag "Tag name")
3160 (character :tag "Access char"))
3161 (list :tag "Start radio group"
3162 (const :startgroup)
3163 (option (string :tag "Group description")))
3164 (list :tag "End radio group"
3165 (const :endgroup)
3166 (option (string :tag "Group description")))
3167 (const :tag "New line" (:newline)))))
3169 (defcustom org-tag-persistent-alist nil
3170 "List of tags that will always appear in all Org-mode files.
3171 This is in addition to any in buffer settings or customizations
3172 of `org-tag-alist'.
3173 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3174 The value of this variable is an alist, the car of each entry must be a
3175 keyword as a string, the cdr may be a character that is used to select
3176 that tag through the fast-tag-selection interface.
3177 See the manual for details.
3178 To disable these tags on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: noptag"
3180 :group 'org-tags
3181 :type '(repeat
3182 (choice
3183 (cons (string :tag "Tag name")
3184 (character :tag "Access char"))
3185 (const :tag "Start radio group" (:startgroup))
3186 (const :tag "End radio group" (:endgroup))
3187 (const :tag "New line" (:newline)))))
3189 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3190 "If non-nil, always offer completion for all tags of all agenda files.
3191 Instead of customizing this variable directly, you might want to
3192 set it locally for capture buffers, because there no list of
3193 tags in that file can be created dynamically (there are none).
3195 (add-hook 'org-capture-mode-hook
3196 (lambda ()
3197 (set (make-local-variable
3198 'org-complete-tags-always-offer-all-agenda-tags)
3199 t)))"
3200 :group 'org-tags
3201 :version "24.1"
3202 :type 'boolean)
3204 (defvar org-file-tags nil
3205 "List of tags that can be inherited by all entries in the file.
3206 The tags will be inherited if the variable `org-use-tag-inheritance'
3207 says they should be.
3208 This variable is populated from #+FILETAGS lines.")
3210 (defcustom org-use-fast-tag-selection 'auto
3211 "Non-nil means use fast tag selection scheme.
3212 This is a special interface to select and deselect tags with single keys.
3213 When nil, fast selection is never used.
3214 When the symbol `auto', fast selection is used if and only if selection
3215 characters for tags have been configured, either through the variable
3216 `org-tag-alist' or through a #+TAGS line in the buffer.
3217 When t, fast selection is always used and selection keys are assigned
3218 automatically if necessary."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "Always" t)
3222 (const :tag "Never" nil)
3223 (const :tag "When selection characters are configured" 'auto)))
3225 (defcustom org-fast-tag-selection-single-key nil
3226 "Non-nil means fast tag selection exits after first change.
3227 When nil, you have to press RET to exit it.
3228 During fast tag selection, you can toggle this flag with `C-c'.
3229 This variable can also have the value `expert'. In this case, the window
3230 displaying the tags menu is not even shown, until you press C-c again."
3231 :group 'org-tags
3232 :type '(choice
3233 (const :tag "No" nil)
3234 (const :tag "Yes" t)
3235 (const :tag "Expert" expert)))
3237 (defvar org-fast-tag-selection-include-todo nil
3238 "Non-nil means fast tags selection interface will also offer TODO states.
3239 This is an undocumented feature, you should not rely on it.")
3241 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3242 "The column to which tags should be indented in a headline.
3243 If this number is positive, it specifies the column. If it is negative,
3244 it means that the tags should be flushright to that column. For example,
3245 -80 works well for a normal 80 character screen.
3246 When 0, place tags directly after headline text, with only one space in
3247 between."
3248 :group 'org-tags
3249 :type 'integer)
3251 (defcustom org-auto-align-tags t
3252 "Non-nil keeps tags aligned when modifying headlines.
3253 Some operations (i.e. demoting) change the length of a headline and
3254 therefore shift the tags around. With this option turned on, after
3255 each such operation the tags are again aligned to `org-tags-column'."
3256 :group 'org-tags
3257 :type 'boolean)
3259 (defcustom org-use-tag-inheritance t
3260 "Non-nil means tags in levels apply also for sublevels.
3261 When nil, only the tags directly given in a specific line apply there.
3262 This may also be a list of tags that should be inherited, or a regexp that
3263 matches tags that should be inherited. Additional control is possible
3264 with the variable `org-tags-exclude-from-inheritance' which gives an
3265 explicit list of tags to be excluded from inheritance, even if the value of
3266 `org-use-tag-inheritance' would select it for inheritance.
3268 If this option is t, a match early-on in a tree can lead to a large
3269 number of matches in the subtree when constructing the agenda or creating
3270 a sparse tree. If you only want to see the first match in a tree during
3271 a search, check out the variable `org-tags-match-list-sublevels'."
3272 :group 'org-tags
3273 :type '(choice
3274 (const :tag "Not" nil)
3275 (const :tag "Always" t)
3276 (repeat :tag "Specific tags" (string :tag "Tag"))
3277 (regexp :tag "Tags matched by regexp")))
3279 (defcustom org-tags-exclude-from-inheritance nil
3280 "List of tags that should never be inherited.
3281 This is a way to exclude a few tags from inheritance. For way to do
3282 the opposite, to actively allow inheritance for selected tags,
3283 see the variable `org-use-tag-inheritance'."
3284 :group 'org-tags
3285 :type '(repeat (string :tag "Tag")))
3287 (defun org-tag-inherit-p (tag)
3288 "Check if TAG is one that should be inherited."
3289 (cond
3290 ((member tag org-tags-exclude-from-inheritance) nil)
3291 ((eq org-use-tag-inheritance t) t)
3292 ((not org-use-tag-inheritance) nil)
3293 ((stringp org-use-tag-inheritance)
3294 (string-match org-use-tag-inheritance tag))
3295 ((listp org-use-tag-inheritance)
3296 (member tag org-use-tag-inheritance))
3297 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3299 (defcustom org-tags-match-list-sublevels t
3300 "Non-nil means list also sublevels of headlines matching a search.
3301 This variable applies to tags/property searches, and also to stuck
3302 projects because this search is based on a tags match as well.
3304 When set to the symbol `indented', sublevels are indented with
3305 leading dots.
3307 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3308 the sublevels of a headline matching a tag search often also match
3309 the same search. Listing all of them can create very long lists.
3310 Setting this variable to nil causes subtrees of a match to be skipped.
3312 This variable is semi-obsolete and probably should always be true. It
3313 is better to limit inheritance to certain tags using the variables
3314 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3315 :group 'org-tags
3316 :type '(choice
3317 (const :tag "No, don't list them" nil)
3318 (const :tag "Yes, do list them" t)
3319 (const :tag "List them, indented with leading dots" indented)))
3321 (defcustom org-tags-sort-function nil
3322 "When set, tags are sorted using this function as a comparator."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "No sorting" nil)
3326 (const :tag "Alphabetical" string<)
3327 (const :tag "Reverse alphabetical" string>)
3328 (function :tag "Custom function" nil)))
3330 (defvar org-tags-history nil
3331 "History of minibuffer reads for tags.")
3332 (defvar org-last-tags-completion-table nil
3333 "The last used completion table for tags.")
3334 (defvar org-after-tags-change-hook nil
3335 "Hook that is run after the tags in a line have changed.")
3337 (defgroup org-properties nil
3338 "Options concerning properties in Org-mode."
3339 :tag "Org Properties"
3340 :group 'org)
3342 (defcustom org-property-format "%-10s %s"
3343 "How property key/value pairs should be formatted by `indent-line'.
3344 When `indent-line' hits a property definition, it will format the line
3345 according to this format, mainly to make sure that the values are
3346 lined-up with respect to each other."
3347 :group 'org-properties
3348 :type 'string)
3350 (defcustom org-properties-postprocess-alist nil
3351 "Alist of properties and functions to adjust inserted values.
3352 Elements of this alist must be of the form
3354 ([string] [function])
3356 where [string] must be a property name and [function] must be a
3357 lambda expression: this lambda expression must take one argument,
3358 the value to adjust, and return the new value as a string.
3360 For example, this element will allow the property \"Remaining\"
3361 to be updated wrt the relation between the \"Effort\" property
3362 and the clock summary:
3364 ((\"Remaining\" (lambda(value)
3365 (let ((clocksum (org-clock-sum-current-item))
3366 (effort (org-duration-string-to-minutes
3367 (org-entry-get (point) \"Effort\"))))
3368 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3369 :group 'org-properties
3370 :version "24.1"
3371 :type '(alist :key-type (string :tag "Property")
3372 :value-type (function :tag "Function")))
3374 (defcustom org-use-property-inheritance nil
3375 "Non-nil means properties apply also for sublevels.
3377 This setting is chiefly used during property searches. Turning it on can
3378 cause significant overhead when doing a search, which is why it is not
3379 on by default.
3381 When nil, only the properties directly given in the current entry count.
3382 When t, every property is inherited. The value may also be a list of
3383 properties that should have inheritance, or a regular expression matching
3384 properties that should be inherited.
3386 However, note that some special properties use inheritance under special
3387 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3388 and the properties ending in \"_ALL\" when they are used as descriptor
3389 for valid values of a property.
3391 Note for programmers:
3392 When querying an entry with `org-entry-get', you can control if inheritance
3393 should be used. By default, `org-entry-get' looks only at the local
3394 properties. You can request inheritance by setting the inherit argument
3395 to t (to force inheritance) or to `selective' (to respect the setting
3396 in this variable)."
3397 :group 'org-properties
3398 :type '(choice
3399 (const :tag "Not" nil)
3400 (const :tag "Always" t)
3401 (repeat :tag "Specific properties" (string :tag "Property"))
3402 (regexp :tag "Properties matched by regexp")))
3404 (defun org-property-inherit-p (property)
3405 "Check if PROPERTY is one that should be inherited."
3406 (cond
3407 ((eq org-use-property-inheritance t) t)
3408 ((not org-use-property-inheritance) nil)
3409 ((stringp org-use-property-inheritance)
3410 (string-match org-use-property-inheritance property))
3411 ((listp org-use-property-inheritance)
3412 (member property org-use-property-inheritance))
3413 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3415 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3416 "The default column format, if no other format has been defined.
3417 This variable can be set on the per-file basis by inserting a line
3419 #+COLUMNS: %25ITEM ....."
3420 :group 'org-properties
3421 :type 'string)
3423 (defcustom org-columns-ellipses ".."
3424 "The ellipses to be used when a field in column view is truncated.
3425 When this is the empty string, as many characters as possible are shown,
3426 but then there will be no visual indication that the field has been truncated.
3427 When this is a string of length N, the last N characters of a truncated
3428 field are replaced by this string. If the column is narrower than the
3429 ellipses string, only part of the ellipses string will be shown."
3430 :group 'org-properties
3431 :type 'string)
3433 (defcustom org-columns-modify-value-for-display-function nil
3434 "Function that modifies values for display in column view.
3435 For example, it can be used to cut out a certain part from a time stamp.
3436 The function must take 2 arguments:
3438 column-title The title of the column (*not* the property name)
3439 value The value that should be modified.
3441 The function should return the value that should be displayed,
3442 or nil if the normal value should be used."
3443 :group 'org-properties
3444 :type 'function)
3446 (defcustom org-effort-property "Effort"
3447 "The property that is being used to keep track of effort estimates.
3448 Effort estimates given in this property need to have the format H:MM."
3449 :group 'org-properties
3450 :group 'org-progress
3451 :type '(string :tag "Property"))
3453 (defconst org-global-properties-fixed
3454 '(("VISIBILITY_ALL" . "folded children content all")
3455 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3456 "List of property/value pairs that can be inherited by any entry.
3458 These are fixed values, for the preset properties. The user variable
3459 that can be used to add to this list is `org-global-properties'.
3461 The entries in this list are cons cells where the car is a property
3462 name and cdr is a string with the value. If the value represents
3463 multiple items like an \"_ALL\" property, separate the items by
3464 spaces.")
3466 (defcustom org-global-properties nil
3467 "List of property/value pairs that can be inherited by any entry.
3469 This list will be combined with the constant `org-global-properties-fixed'.
3471 The entries in this list are cons cells where the car is a property
3472 name and cdr is a string with the value.
3474 You can set buffer-local values for the same purpose in the variable
3475 `org-file-properties' this by adding lines like
3477 #+PROPERTY: NAME VALUE"
3478 :group 'org-properties
3479 :type '(repeat
3480 (cons (string :tag "Property")
3481 (string :tag "Value"))))
3483 (defvar org-file-properties nil
3484 "List of property/value pairs that can be inherited by any entry.
3485 Valid for the current buffer.
3486 This variable is populated from #+PROPERTY lines.")
3487 (make-variable-buffer-local 'org-file-properties)
3489 (defgroup org-agenda nil
3490 "Options concerning agenda views in Org-mode."
3491 :tag "Org Agenda"
3492 :group 'org)
3494 (defvar org-category nil
3495 "Variable used by org files to set a category for agenda display.
3496 Such files should use a file variable to set it, for example
3498 # -*- mode: org; org-category: \"ELisp\"
3500 or contain a special line
3502 #+CATEGORY: ELisp
3504 If the file does not specify a category, then file's base name
3505 is used instead.")
3506 (make-variable-buffer-local 'org-category)
3507 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3509 (defcustom org-agenda-files nil
3510 "The files to be used for agenda display.
3511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3512 \\[org-remove-file]. You can also use customize to edit the list.
3514 If an entry is a directory, all files in that directory that are matched by
3515 `org-agenda-file-regexp' will be part of the file list.
3517 If the value of the variable is not a list but a single file name, then
3518 the list of agenda files is actually stored and maintained in that file, one
3519 agenda file per line. In this file paths can be given relative to
3520 `org-directory'. Tilde expansion and environment variable substitution
3521 are also made."
3522 :group 'org-agenda
3523 :type '(choice
3524 (repeat :tag "List of files and directories" file)
3525 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3527 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3528 "Regular expression to match files for `org-agenda-files'.
3529 If any element in the list in that variable contains a directory instead
3530 of a normal file, all files in that directory that are matched by this
3531 regular expression will be included."
3532 :group 'org-agenda
3533 :type 'regexp)
3535 (defcustom org-agenda-text-search-extra-files nil
3536 "List of extra files to be searched by text search commands.
3537 These files will be search in addition to the agenda files by the
3538 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3539 Note that these files will only be searched for text search commands,
3540 not for the other agenda views like todo lists, tag searches or the weekly
3541 agenda. This variable is intended to list notes and possibly archive files
3542 that should also be searched by these two commands.
3543 In fact, if the first element in the list is the symbol `agenda-archives',
3544 than all archive files of all agenda files will be added to the search
3545 scope."
3546 :group 'org-agenda
3547 :type '(set :greedy t
3548 (const :tag "Agenda Archives" agenda-archives)
3549 (repeat :inline t (file))))
3551 (if (fboundp 'defvaralias)
3552 (defvaralias 'org-agenda-multi-occur-extra-files
3553 'org-agenda-text-search-extra-files))
3555 (defcustom org-agenda-skip-unavailable-files nil
3556 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3557 A nil value means to remove them, after a query, from the list."
3558 :group 'org-agenda
3559 :type 'boolean)
3561 (defcustom org-calendar-to-agenda-key [?c]
3562 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3563 The command `org-calendar-goto-agenda' will be bound to this key. The
3564 default is the character `c' because then `c' can be used to switch back and
3565 forth between agenda and calendar."
3566 :group 'org-agenda
3567 :type 'sexp)
3569 (defcustom org-calendar-insert-diary-entry-key [?i]
3570 "The key to be installed in `calendar-mode-map' for adding diary entries.
3571 This option is irrelevant until `org-agenda-diary-file' has been configured
3572 to point to an Org-mode file. When that is the case, the command
3573 `org-agenda-diary-entry' will be bound to the key given here, by default
3574 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3575 if you want to continue doing this, you need to change this to a different
3576 key."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-agenda-diary-file 'diary-file
3581 "File to which to add new entries with the `i' key in agenda and calendar.
3582 When this is the symbol `diary-file', the functionality in the Emacs
3583 calendar will be used to add entries to the `diary-file'. But when this
3584 points to a file, `org-agenda-diary-entry' will be used instead."
3585 :group 'org-agenda
3586 :type '(choice
3587 (const :tag "The standard Emacs diary file" diary-file)
3588 (file :tag "Special Org file diary entries")))
3590 (eval-after-load "calendar"
3591 '(progn
3592 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3593 'org-calendar-goto-agenda)
3594 (add-hook 'calendar-mode-hook
3595 (lambda ()
3596 (unless (eq org-agenda-diary-file 'diary-file)
3597 (define-key calendar-mode-map
3598 org-calendar-insert-diary-entry-key
3599 'org-agenda-diary-entry))))))
3601 (defgroup org-latex nil
3602 "Options for embedding LaTeX code into Org-mode."
3603 :tag "Org LaTeX"
3604 :group 'org)
3606 (defcustom org-format-latex-options
3607 '(:foreground default :background default :scale 1.0
3608 :html-foreground "Black" :html-background "Transparent"
3609 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3610 "Options for creating images from LaTeX fragments.
3611 This is a property list with the following properties:
3612 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3613 `default' means use the foreground of the default face.
3614 `auto' means use the foreground from the text face.
3615 :background the background color, or \"Transparent\".
3616 `default' means use the background of the default face.
3617 `auto' means use the background from the text face.
3618 :scale a scaling factor for the size of the images, to get more pixels
3619 :html-foreground, :html-background, :html-scale
3620 the same numbers for HTML export.
3621 :matchers a list indicating which matchers should be used to
3622 find LaTeX fragments. Valid members of this list are:
3623 \"begin\" find environments
3624 \"$1\" find single characters surrounded by $.$
3625 \"$\" find math expressions surrounded by $...$
3626 \"$$\" find math expressions surrounded by $$....$$
3627 \"\\(\" find math expressions surrounded by \\(...\\)
3628 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3629 :group 'org-latex
3630 :type 'plist)
3632 (defcustom org-format-latex-signal-error t
3633 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3634 When nil, just push out a message."
3635 :group 'org-latex
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-latex-to-mathml-jar-file nil
3640 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3641 Use this to specify additional executable file say a jar file.
3643 When using MathToWeb as the converter, specify the full-path to
3644 your mathtoweb.jar file."
3645 :group 'org-latex
3646 :version "24.1"
3647 :type '(choice
3648 (const :tag "None" nil)
3649 (file :tag "JAR file" :must-match t)))
3651 (defcustom org-latex-to-mathml-convert-command nil
3652 "Command to convert LaTeX fragments to MathML.
3653 Replace format-specifiers in the command as noted below and use
3654 `shell-command' to convert LaTeX to MathML.
3655 %j: Executable file in fully expanded form as specified by
3656 `org-latex-to-mathml-jar-file'.
3657 %I: Input LaTeX file in fully expanded form
3658 %o: Output MathML file
3659 This command is used by `org-create-math-formula'.
3661 When using MathToWeb as the converter, set this to
3662 \"java -jar %j -unicode -force -df %o %I\"."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (string :tag "\nShell command")))
3669 (defcustom org-latex-create-formula-image-program 'dvipng
3670 "Program to convert LaTeX fragments with.
3672 dvipng Process the LaTeX fragments to dvi file, then convert
3673 dvi files to png files using dvipng.
3674 This will also include processing of non-math environments.
3675 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3676 to convert pdf files to png files"
3677 :group 'org-latex
3678 :version "24.1"
3679 :type '(choice
3680 (const :tag "dvipng" dvipng)
3681 (const :tag "imagemagick" imagemagick)))
3683 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3684 "Path to store latex preview images.
3685 A relative path here creates many directories relative to the
3686 processed org files paths. An absolute path puts all preview
3687 images at the same place."
3688 :group 'org-latex
3689 :version "24.3"
3690 :type 'string)
3692 (defun org-format-latex-mathml-available-p ()
3693 "Return t if `org-latex-to-mathml-convert-command' is usable."
3694 (save-match-data
3695 (when (and (boundp 'org-latex-to-mathml-convert-command)
3696 org-latex-to-mathml-convert-command)
3697 (let ((executable (car (split-string
3698 org-latex-to-mathml-convert-command))))
3699 (when (executable-find executable)
3700 (if (string-match
3701 "%j" org-latex-to-mathml-convert-command)
3702 (file-readable-p org-latex-to-mathml-jar-file)
3703 t))))))
3705 (defcustom org-format-latex-header "\\documentclass{article}
3706 \\usepackage[usenames]{color}
3707 \\usepackage{amsmath}
3708 \\usepackage[mathscr]{eucal}
3709 \\pagestyle{empty} % do not remove
3710 \[PACKAGES]
3711 \[DEFAULT-PACKAGES]
3712 % The settings below are copied from fullpage.sty
3713 \\setlength{\\textwidth}{\\paperwidth}
3714 \\addtolength{\\textwidth}{-3cm}
3715 \\setlength{\\oddsidemargin}{1.5cm}
3716 \\addtolength{\\oddsidemargin}{-2.54cm}
3717 \\setlength{\\evensidemargin}{\\oddsidemargin}
3718 \\setlength{\\textheight}{\\paperheight}
3719 \\addtolength{\\textheight}{-\\headheight}
3720 \\addtolength{\\textheight}{-\\headsep}
3721 \\addtolength{\\textheight}{-\\footskip}
3722 \\addtolength{\\textheight}{-3cm}
3723 \\setlength{\\topmargin}{1.5cm}
3724 \\addtolength{\\topmargin}{-2.54cm}"
3725 "The document header used for processing LaTeX fragments.
3726 It is imperative that this header make sure that no page number
3727 appears on the page. The package defined in the variables
3728 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3729 will either replace the placeholder \"[PACKAGES]\" in this
3730 header, or they will be appended."
3731 :group 'org-latex
3732 :type 'string)
3734 (defun org-set-packages-alist (var val)
3735 "Set the packages alist and make sure it has 3 elements per entry."
3736 (set var (mapcar (lambda (x)
3737 (if (and (consp x) (= (length x) 2))
3738 (list (car x) (nth 1 x) t)
3740 val)))
3742 (defun org-get-packages-alist (var)
3743 "Get the packages alist and make sure it has 3 elements per entry."
3744 (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 (default-value var)))
3750 (defcustom org-latex-default-packages-alist
3751 '(("AUTO" "inputenc" t)
3752 ("T1" "fontenc" t)
3753 ("" "fixltx2e" nil)
3754 ("" "graphicx" t)
3755 ("" "longtable" nil)
3756 ("" "float" nil)
3757 ("" "wrapfig" nil)
3758 ("" "soul" t)
3759 ("" "textcomp" t)
3760 ("" "marvosym" t)
3761 ("" "wasysym" t)
3762 ("" "latexsym" t)
3763 ("" "amssymb" t)
3764 ("" "hyperref" nil)
3765 "\\tolerance=1000")
3766 "Alist of default packages to be inserted in the header.
3768 Change this only if one of the packages here causes an
3769 incompatibility with another package you are using.
3771 The packages in this list are needed by one part or another of
3772 Org mode to function properly:
3774 - inputenc, fontenc: for basic font and character selection
3775 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3776 symbols used for interpreting the entities in `org-entities'.
3777 You can skip some of these packages if you don't use any of the
3778 symbols in it.
3779 - graphicx: for including images
3780 - float, wrapfig: for figure placement
3781 - longtable: for long tables
3782 - hyperref: for cross references
3784 Therefore you should not modify this variable unless you know
3785 what you are doing. The one reason to change it anyway is that
3786 you might be loading some other package that conflicts with one
3787 of the default packages. Each cell is of the format
3788 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3789 the package also needs to be included when compiling LaTeX
3790 snippets into images for inclusion into non-LaTeX output."
3791 :group 'org-latex
3792 :group 'org-export-latex
3793 :set 'org-set-packages-alist
3794 :get 'org-get-packages-alist
3795 :version "24.1"
3796 :type '(repeat
3797 (choice
3798 (list :tag "options/package pair"
3799 (string :tag "options")
3800 (string :tag "package")
3801 (boolean :tag "Snippet"))
3802 (string :tag "A line of LaTeX"))))
3804 (defcustom org-latex-packages-alist nil
3805 "Alist of packages to be inserted in every LaTeX header.
3807 These will be inserted after `org-latex-default-packages-alist'.
3808 Each cell is of the format:
3810 \(\"options\" \"package\" snippet-flag)
3812 SNIPPET-FLAG, when t, indicates that this package is also needed
3813 when turning LaTeX snippets into images for inclusion into
3814 non-LaTeX output.
3816 Make sure that you only list packages here which:
3818 - you want in every file
3819 - do not conflict with the setup in `org-format-latex-header'.
3820 - do not conflict with the default packages in
3821 `org-latex-default-packages-alist'."
3822 :group 'org-latex
3823 :group 'org-export-latex
3824 :set 'org-set-packages-alist
3825 :get 'org-get-packages-alist
3826 :type '(repeat
3827 (choice
3828 (list :tag "options/package pair"
3829 (string :tag "options")
3830 (string :tag "package")
3831 (boolean :tag "Snippet"))
3832 (string :tag "A line of LaTeX"))))
3834 (defgroup org-appearance nil
3835 "Settings for Org-mode appearance."
3836 :tag "Org Appearance"
3837 :group 'org)
3839 (defcustom org-level-color-stars-only nil
3840 "Non-nil means fontify only the stars in each headline.
3841 When nil, the entire headline is fontified.
3842 Changing it requires restart of `font-lock-mode' to become effective
3843 also in regions already fontified."
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hide-leading-stars nil
3848 "Non-nil means hide the first N-1 stars in a headline.
3849 This works by using the face `org-hide' for these stars. This
3850 face is white for a light background, and black for a dark
3851 background. You may have to customize the face `org-hide' to
3852 make this work.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified.
3855 You may also set this on a per-file basis by adding one of the following
3856 lines to the buffer:
3858 #+STARTUP: hidestars
3859 #+STARTUP: showstars"
3860 :group 'org-appearance
3861 :type 'boolean)
3863 (defcustom org-hidden-keywords nil
3864 "List of symbols corresponding to keywords to be hidden the org buffer.
3865 For example, a value '(title) for this list will make the document's title
3866 appear in the buffer without the initial #+TITLE: keyword."
3867 :group 'org-appearance
3868 :version "24.1"
3869 :type '(set (const :tag "#+AUTHOR" author)
3870 (const :tag "#+DATE" date)
3871 (const :tag "#+EMAIL" email)
3872 (const :tag "#+TITLE" title)))
3874 (defcustom org-custom-properties nil
3875 "List of properties (as strings) with a special meaning.
3876 The default use of these custom properties is to let the user
3877 hide them with `org-toggle-custom-properties-visibility'."
3878 :group 'org-properties
3879 :group 'org-appearance
3880 :version "24.3"
3881 :type '(repeat (string :tag "Property Name")))
3883 (defcustom org-fontify-done-headline nil
3884 "Non-nil means change the face of a headline if it is marked DONE.
3885 Normally, only the TODO/DONE keyword indicates the state of a headline.
3886 When this is non-nil, the headline after the keyword is set to the
3887 `org-headline-done' as an additional indication."
3888 :group 'org-appearance
3889 :type 'boolean)
3891 (defcustom org-fontify-emphasized-text t
3892 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3893 Changing this variable requires a restart of Emacs to take effect."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-fontify-whole-heading-line nil
3898 "Non-nil means fontify the whole line for headings.
3899 This is useful when setting a background color for the
3900 org-level-* faces."
3901 :group 'org-appearance
3902 :type 'boolean)
3904 (defcustom org-hide-emphasis-markers nil
3905 "Non-nil mean font-lock should hide the emphasis marker characters."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-pretty-entities nil
3910 "Non-nil means show entities as UTF8 characters.
3911 When nil, the \\name form remains in the buffer."
3912 :group 'org-appearance
3913 :version "24.1"
3914 :type 'boolean)
3916 (defcustom org-pretty-entities-include-sub-superscripts t
3917 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3918 :group 'org-appearance
3919 :version "24.1"
3920 :type 'boolean)
3922 (defvar org-emph-re nil
3923 "Regular expression for matching emphasis.
3924 After a match, the match groups contain these elements:
3925 0 The match of the full regular expression, including the characters
3926 before and after the proper match
3927 1 The character before the proper match, or empty at beginning of line
3928 2 The proper match, including the leading and trailing markers
3929 3 The leading marker like * or /, indicating the type of highlighting
3930 4 The text between the emphasis markers, not including the markers
3931 5 The character after the match, empty at the end of a line")
3932 (defvar org-verbatim-re nil
3933 "Regular expression for matching verbatim text.")
3934 (defvar org-emphasis-regexp-components) ; defined just below
3935 (defvar org-emphasis-alist) ; defined just below
3936 (defun org-set-emph-re (var val)
3937 "Set variable and compute the emphasis regular expression."
3938 (set var val)
3939 (when (and (boundp 'org-emphasis-alist)
3940 (boundp 'org-emphasis-regexp-components)
3941 org-emphasis-alist org-emphasis-regexp-components)
3942 (let* ((e org-emphasis-regexp-components)
3943 (pre (car e))
3944 (post (nth 1 e))
3945 (border (nth 2 e))
3946 (body (nth 3 e))
3947 (nl (nth 4 e))
3948 (body1 (concat body "*?"))
3949 (markers (mapconcat 'car org-emphasis-alist ""))
3950 (vmarkers (mapconcat
3951 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3952 org-emphasis-alist "")))
3953 ;; make sure special characters appear at the right position in the class
3954 (if (string-match "\\^" markers)
3955 (setq markers (concat (replace-match "" t t markers) "^")))
3956 (if (string-match "-" markers)
3957 (setq markers (concat (replace-match "" t t markers) "-")))
3958 (if (string-match "\\^" vmarkers)
3959 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3960 (if (string-match "-" vmarkers)
3961 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3962 (if (> nl 0)
3963 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3964 (int-to-string nl) "\\}")))
3965 ;; Make the regexp
3966 (setq org-emph-re
3967 (concat "\\([" pre "]\\|^\\)"
3968 "\\("
3969 "\\([" markers "]\\)"
3970 "\\("
3971 "[^" border "]\\|"
3972 "[^" border "]"
3973 body1
3974 "[^" border "]"
3975 "\\)"
3976 "\\3\\)"
3977 "\\([" post "]\\|$\\)"))
3978 (setq org-verbatim-re
3979 (concat "\\([" pre "]\\|^\\)"
3980 "\\("
3981 "\\([" vmarkers "]\\)"
3982 "\\("
3983 "[^" border "]\\|"
3984 "[^" border "]"
3985 body1
3986 "[^" border "]"
3987 "\\)"
3988 "\\3\\)"
3989 "\\([" post "]\\|$\\)")))))
3991 (defcustom org-emphasis-regexp-components
3992 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3993 "Components used to build the regular expression for emphasis.
3994 This is a list with five entries. Terminology: In an emphasis string
3995 like \" *strong word* \", we call the initial space PREMATCH, the final
3996 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3997 and \"trong wor\" is the body. The different components in this variable
3998 specify what is allowed/forbidden in each part:
4000 pre Chars allowed as prematch. Beginning of line will be allowed too.
4001 post Chars allowed as postmatch. End of line will be allowed too.
4002 border The chars *forbidden* as border characters.
4003 body-regexp A regexp like \".\" to match a body character. Don't use
4004 non-shy groups here, and don't allow newline here.
4005 newline The maximum number of newlines allowed in an emphasis exp.
4007 Use customize to modify this, or restart Emacs after changing it."
4008 :group 'org-appearance
4009 :set 'org-set-emph-re
4010 :type '(list
4011 (sexp :tag "Allowed chars in pre ")
4012 (sexp :tag "Allowed chars in post ")
4013 (sexp :tag "Forbidden chars in border ")
4014 (sexp :tag "Regexp for body ")
4015 (integer :tag "number of newlines allowed")
4016 (option (boolean :tag "Please ignore this button"))))
4018 (defcustom org-emphasis-alist
4019 `(("*" bold "<b>" "</b>")
4020 ("/" italic "<i>" "</i>")
4021 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4022 ("=" org-code "<code>" "</code>" verbatim)
4023 ("~" org-verbatim "<code>" "</code>" verbatim)
4024 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4025 "<del>" "</del>")
4027 "Special syntax for emphasized text.
4028 Text starting and ending with a special character will be emphasized, for
4029 example *bold*, _underlined_ and /italic/. This variable sets the marker
4030 characters, the face to be used by font-lock for highlighting in Org-mode
4031 Emacs buffers, and the HTML tags to be used for this.
4032 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4033 Use customize to modify this, or restart Emacs after changing it."
4034 :group 'org-appearance
4035 :set 'org-set-emph-re
4036 :type '(repeat
4037 (list
4038 (string :tag "Marker character")
4039 (choice
4040 (face :tag "Font-lock-face")
4041 (plist :tag "Face property list"))
4042 (string :tag "HTML start tag")
4043 (string :tag "HTML end tag")
4044 (option (const verbatim)))))
4046 (defvar org-protecting-blocks
4047 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4048 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4049 This is needed for font-lock setup.")
4051 ;;; Miscellaneous options
4053 (defgroup org-completion nil
4054 "Completion in Org-mode."
4055 :tag "Org Completion"
4056 :group 'org)
4058 (defcustom org-completion-use-ido nil
4059 "Non-nil means use ido completion wherever possible.
4060 Note that `ido-mode' must be active for this variable to be relevant.
4061 If you decide to turn this variable on, you might well want to turn off
4062 `org-outline-path-complete-in-steps'.
4063 See also `org-completion-use-iswitchb'."
4064 :group 'org-completion
4065 :type 'boolean)
4067 (defcustom org-completion-use-iswitchb nil
4068 "Non-nil means use iswitchb completion wherever possible.
4069 Note that `iswitchb-mode' must be active for this variable to be relevant.
4070 If you decide to turn this variable on, you might well want to turn off
4071 `org-outline-path-complete-in-steps'.
4072 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4073 :group 'org-completion
4074 :type 'boolean)
4076 (defcustom org-completion-fallback-command 'hippie-expand
4077 "The expansion command called by \\[pcomplete] in normal context.
4078 Normal means, no org-mode-specific context."
4079 :group 'org-completion
4080 :type 'function)
4082 ;;; Functions and variables from their packages
4083 ;; Declared here to avoid compiler warnings
4085 ;; XEmacs only
4086 (defvar outline-mode-menu-heading)
4087 (defvar outline-mode-menu-show)
4088 (defvar outline-mode-menu-hide)
4089 (defvar zmacs-regions) ; XEmacs regions
4091 ;; Emacs only
4092 (defvar mark-active)
4094 ;; Various packages
4095 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4096 (declare-function calendar-forward-day "cal-move" (arg))
4097 (declare-function calendar-goto-date "cal-move" (date))
4098 (declare-function calendar-goto-today "cal-move" ())
4099 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4100 (defvar calc-embedded-close-formula)
4101 (defvar calc-embedded-open-formula)
4102 (declare-function cdlatex-tab "ext:cdlatex" ())
4103 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4104 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4105 (defvar font-lock-unfontify-region-function)
4106 (declare-function iswitchb-read-buffer "iswitchb"
4107 (prompt &optional default require-match start matches-set))
4108 (defvar iswitchb-temp-buflist)
4109 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4110 (defvar org-agenda-tags-todo-honor-ignore-options)
4111 (declare-function org-agenda-skip "org-agenda" ())
4112 (declare-function
4113 org-agenda-format-item "org-agenda"
4114 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4115 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4116 (declare-function org-agenda-change-all-lines "org-agenda"
4117 (newhead hdmarker &optional fixface just-this))
4118 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4119 (declare-function org-agenda-maybe-redo "org-agenda" ())
4120 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4121 (beg end))
4122 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4123 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4124 "org-agenda" (&optional end))
4125 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4126 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4127 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4128 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4129 (declare-function org-indent-mode "org-indent" (&optional arg))
4130 (declare-function parse-time-string "parse-time" (string))
4131 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4132 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4133 (defvar remember-data-file)
4134 (defvar texmathp-why)
4135 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4136 (declare-function table--at-cell-p "table" (position &optional object at-column))
4138 (defvar org-latex-regexps)
4140 ;;; Autoload and prepare some org modules
4142 ;; Some table stuff that needs to be defined here, because it is used
4143 ;; by the functions setting up org-mode or checking for table context.
4145 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4146 "Detect an org-type or table-type table.")
4147 (defconst org-table-line-regexp "^[ \t]*|"
4148 "Detect an org-type table line.")
4149 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4150 "Detect an org-type table line.")
4151 (defconst org-table-hline-regexp "^[ \t]*|-"
4152 "Detect an org-type table hline.")
4153 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4154 "Detect a table-type table hline.")
4155 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4156 "Detect the first line outside a table when searching from within it.
4157 This works for both table types.")
4159 ;; Autoload the functions in org-table.el that are needed by functions here.
4161 (eval-and-compile
4162 (org-autoload "org-table"
4163 '(org-table-begin org-table-blank-field org-table-end)))
4165 ;;;###autoload
4166 (defun turn-on-orgtbl ()
4167 "Unconditionally turn on `orgtbl-mode'."
4168 (require 'org-table)
4169 (orgtbl-mode 1))
4171 (defun org-at-table-p (&optional table-type)
4172 "Return t if the cursor is inside an org-type table.
4173 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4174 (if org-enable-table-editor
4175 (save-excursion
4176 (beginning-of-line 1)
4177 (looking-at (if table-type org-table-any-line-regexp
4178 org-table-line-regexp)))
4179 nil))
4180 (defsubst org-table-p () (org-at-table-p))
4182 (defun org-at-table.el-p ()
4183 "Return t if and only if we are at a table.el table."
4184 (and (org-at-table-p 'any)
4185 (save-excursion
4186 (goto-char (org-table-begin 'any))
4187 (looking-at org-table1-hline-regexp))))
4188 (defun org-table-recognize-table.el ()
4189 "If there is a table.el table nearby, recognize it and move into it."
4190 (if org-table-tab-recognizes-table.el
4191 (if (org-at-table.el-p)
4192 (progn
4193 (beginning-of-line 1)
4194 (if (looking-at org-table-dataline-regexp)
4196 (if (looking-at org-table1-hline-regexp)
4197 (progn
4198 (beginning-of-line 2)
4199 (if (looking-at org-table-any-border-regexp)
4200 (beginning-of-line -1)))))
4201 (if (re-search-forward "|" (org-table-end t) t)
4202 (progn
4203 (require 'table)
4204 (if (table--at-cell-p (point))
4206 (message "recognizing table.el table...")
4207 (table-recognize-table)
4208 (message "recognizing table.el table...done")))
4209 (error "This should not happen"))
4211 nil)
4212 nil))
4214 (defun org-at-table-hline-p ()
4215 "Return t if the cursor is inside a hline in a table."
4216 (if org-enable-table-editor
4217 (save-excursion
4218 (beginning-of-line 1)
4219 (looking-at org-table-hline-regexp))
4220 nil))
4222 (defvar org-table-clean-did-remove-column nil)
4224 (defun org-table-map-tables (function &optional quietly)
4225 "Apply FUNCTION to the start of all tables in the buffer."
4226 (save-excursion
4227 (save-restriction
4228 (widen)
4229 (goto-char (point-min))
4230 (while (re-search-forward org-table-any-line-regexp nil t)
4231 (unless quietly
4232 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4233 (beginning-of-line 1)
4234 (when (and (looking-at org-table-line-regexp)
4235 ;; Exclude tables in src/example/verbatim/clocktable blocks
4236 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4237 (save-excursion (funcall function))
4238 (or (looking-at org-table-line-regexp)
4239 (forward-char 1)))
4240 (re-search-forward org-table-any-border-regexp nil 1))))
4241 (unless quietly (message "Mapping tables: done")))
4243 ;; Declare and autoload functions from ox.el and al.
4245 (declare-function org-export-get-environment "ox"
4246 (&optional backend subtreep ext-plist))
4247 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4249 ;; Declare and autoload functions from org-agenda.el
4251 (eval-and-compile
4252 (org-autoload "org-agenda"
4253 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4255 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4256 (declare-function org-clock-update-mode-line "org-clock" ())
4257 (declare-function org-resolve-clocks "org-clock"
4258 (&optional also-non-dangling-p prompt last-valid))
4259 (defvar org-clock-start-time)
4260 (defvar org-clock-marker (make-marker)
4261 "Marker recording the last clock-in.")
4262 (defvar org-clock-hd-marker (make-marker)
4263 "Marker recording the last clock-in, but the headline position.")
4264 (defvar org-clock-heading ""
4265 "The heading of the current clock entry.")
4266 (defun org-clock-is-active ()
4267 "Return non-nil if clock is currently running.
4268 The return value is actually the clock marker."
4269 (marker-buffer org-clock-marker))
4271 (eval-and-compile
4272 (org-autoload "org-clock" '(org-clock-remove-overlays
4273 org-clock-update-time-maybe
4274 org-clocktable-shift)))
4276 (defun org-check-running-clock ()
4277 "Check if the current buffer contains the running clock.
4278 If yes, offer to stop it and to save the buffer with the changes."
4279 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4280 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4281 (buffer-name))))
4282 (org-clock-out)
4283 (when (y-or-n-p "Save changed buffer?")
4284 (save-buffer))))
4286 (defun org-clocktable-try-shift (dir n)
4287 "Check if this line starts a clock table, if yes, shift the time block."
4288 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4289 (org-clocktable-shift dir n)))
4291 ;;;###autoload
4292 (defun org-clock-persistence-insinuate ()
4293 "Set up hooks for clock persistence."
4294 (require 'org-clock)
4295 (add-hook 'org-mode-hook 'org-clock-load)
4296 (add-hook 'kill-emacs-hook 'org-clock-save))
4298 ;; Define the variable already here, to make sure we have it.
4299 (defvar org-indent-mode nil
4300 "Non-nil if Org-Indent mode is enabled.
4301 Use the command `org-indent-mode' to change this variable.")
4303 ;; Autoload archiving code
4304 ;; The stuff that is needed for cycling and tags has to be defined here.
4306 (defgroup org-archive nil
4307 "Options concerning archiving in Org-mode."
4308 :tag "Org Archive"
4309 :group 'org-structure)
4311 (defcustom org-archive-location "%s_archive::"
4312 "The location where subtrees should be archived.
4314 The value of this variable is a string, consisting of two parts,
4315 separated by a double-colon. The first part is a filename and
4316 the second part is a headline.
4318 When the filename is omitted, archiving happens in the same file.
4319 %s in the filename will be replaced by the current file
4320 name (without the directory part). Archiving to a different file
4321 is useful to keep archived entries from contributing to the
4322 Org-mode Agenda.
4324 The archived entries will be filed as subtrees of the specified
4325 headline. When the headline is omitted, the subtrees are simply
4326 filed away at the end of the file, as top-level entries. Also in
4327 the heading you can use %s to represent the file name, this can be
4328 useful when using the same archive for a number of different files.
4330 Here are a few examples:
4331 \"%s_archive::\"
4332 If the current file is Projects.org, archive in file
4333 Projects.org_archive, as top-level trees. This is the default.
4335 \"::* Archived Tasks\"
4336 Archive in the current file, under the top-level headline
4337 \"* Archived Tasks\".
4339 \"~/org/archive.org::\"
4340 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4342 \"~/org/archive.org::* From %s\"
4343 Archive in file ~/org/archive.org (absolute path), under headlines
4344 \"From FILENAME\" where file name is the current file name.
4346 \"~/org/datetree.org::datetree/* Finished Tasks\"
4347 The \"datetree/\" string is special, signifying to archive
4348 items to the datetree. Items are placed in either the CLOSED
4349 date of the item, or the current date if there is no CLOSED date.
4350 The heading will be a subentry to the current date. There doesn't
4351 need to be a heading, but there always needs to be a slash after
4352 datetree. For example, to store archived items directly in the
4353 datetree, use \"~/org/datetree.org::datetree/\".
4355 \"basement::** Finished Tasks\"
4356 Archive in file ./basement (relative path), as level 3 trees
4357 below the level 2 heading \"** Finished Tasks\".
4359 You may set this option on a per-file basis by adding to the buffer a
4360 line like
4362 #+ARCHIVE: basement::** Finished Tasks
4364 You may also define it locally for a subtree by setting an ARCHIVE property
4365 in the entry. If such a property is found in an entry, or anywhere up
4366 the hierarchy, it will be used."
4367 :group 'org-archive
4368 :type 'string)
4370 (defcustom org-archive-tag "ARCHIVE"
4371 "The tag that marks a subtree as archived.
4372 An archived subtree does not open during visibility cycling, and does
4373 not contribute to the agenda listings.
4374 After changing this, font-lock must be restarted in the relevant buffers to
4375 get the proper fontification."
4376 :group 'org-archive
4377 :group 'org-keywords
4378 :type 'string)
4380 (defcustom org-agenda-skip-archived-trees t
4381 "Non-nil means the agenda will skip any items located in archived trees.
4382 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4383 variable is no longer recommended, you should leave it at the value t.
4384 Instead, use the key `v' to cycle the archives-mode in the agenda."
4385 :group 'org-archive
4386 :group 'org-agenda-skip
4387 :type 'boolean)
4389 (defcustom org-columns-skip-archived-trees t
4390 "Non-nil means ignore archived trees when creating column view."
4391 :group 'org-archive
4392 :group 'org-properties
4393 :type 'boolean)
4395 (defcustom org-cycle-open-archived-trees nil
4396 "Non-nil means `org-cycle' will open archived trees.
4397 An archived tree is a tree marked with the tag ARCHIVE.
4398 When nil, archived trees will stay folded. You can still open them with
4399 normal outline commands like `show-all', but not with the cycling commands."
4400 :group 'org-archive
4401 :group 'org-cycle
4402 :type 'boolean)
4404 (defcustom org-sparse-tree-open-archived-trees nil
4405 "Non-nil means sparse tree construction shows matches in archived trees.
4406 When nil, matches in these trees are highlighted, but the trees are kept in
4407 collapsed state."
4408 :group 'org-archive
4409 :group 'org-sparse-trees
4410 :type 'boolean)
4412 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4413 "The default date type when building a sparse tree.
4414 When this is nil, a date is a scheduled or a deadline timestamp.
4415 Otherwise, these types are allowed:
4417 all: all timestamps
4418 active: only active timestamps (<...>)
4419 inactive: only inactive timestamps (<...)
4420 scheduled: only scheduled timestamps
4421 deadline: only deadline timestamps"
4422 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4423 (const :tag "All timestamps" all)
4424 (const :tag "Only active timestamps" active)
4425 (const :tag "Only inactive timestamps" inactive)
4426 (const :tag "Only scheduled timestamps" scheduled)
4427 (const :tag "Only deadline timestamps" deadline))
4428 :version "24.3"
4429 :group 'org-sparse-trees)
4431 (defun org-cycle-hide-archived-subtrees (state)
4432 "Re-hide all archived subtrees after a visibility state change."
4433 (when (and (not org-cycle-open-archived-trees)
4434 (not (memq state '(overview folded))))
4435 (save-excursion
4436 (let* ((globalp (memq state '(contents all)))
4437 (beg (if globalp (point-min) (point)))
4438 (end (if globalp (point-max) (org-end-of-subtree t))))
4439 (org-hide-archived-subtrees beg end)
4440 (goto-char beg)
4441 (if (looking-at (concat ".*:" org-archive-tag ":"))
4442 (message "%s" (substitute-command-keys
4443 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4445 (defun org-force-cycle-archived ()
4446 "Cycle subtree even if it is archived."
4447 (interactive)
4448 (setq this-command 'org-cycle)
4449 (let ((org-cycle-open-archived-trees t))
4450 (call-interactively 'org-cycle)))
4452 (defun org-hide-archived-subtrees (beg end)
4453 "Re-hide all archived subtrees after a visibility state change."
4454 (save-excursion
4455 (let* ((re (concat ":" org-archive-tag ":")))
4456 (goto-char beg)
4457 (while (re-search-forward re end t)
4458 (when (org-at-heading-p)
4459 (org-flag-subtree t)
4460 (org-end-of-subtree t))))))
4462 (declare-function outline-end-of-heading "outline" ())
4463 (declare-function outline-flag-region "outline" (from to flag))
4464 (defun org-flag-subtree (flag)
4465 (save-excursion
4466 (org-back-to-heading t)
4467 (outline-end-of-heading)
4468 (outline-flag-region (point)
4469 (progn (org-end-of-subtree t) (point))
4470 flag)))
4472 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4474 (eval-and-compile
4475 (org-autoload "org-archive"
4476 '(org-add-archive-files)))
4478 ;; Autoload Column View Code
4480 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4481 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4482 (declare-function org-columns-compute "org-colview" (property))
4484 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4485 '(org-columns-number-to-string
4486 org-columns-get-format-and-top-level
4487 org-columns-compute
4488 org-columns-remove-overlays))
4490 ;; Autoload ID code
4492 (declare-function org-id-store-link "org-id")
4493 (declare-function org-id-locations-load "org-id")
4494 (declare-function org-id-locations-save "org-id")
4495 (defvar org-id-track-globally)
4496 (org-autoload "org-id"
4497 '(org-id-new
4498 org-id-copy
4499 org-id-get-with-outline-path-completion
4500 org-id-get-with-outline-drilling))
4502 ;;; Variables for pre-computed regular expressions, all buffer local
4504 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4505 "Matches first line of a hidden block.")
4506 (make-variable-buffer-local 'org-drawer-regexp)
4507 (defvar org-todo-regexp nil
4508 "Matches any of the TODO state keywords.")
4509 (make-variable-buffer-local 'org-todo-regexp)
4510 (defvar org-not-done-regexp nil
4511 "Matches any of the TODO state keywords except the last one.")
4512 (make-variable-buffer-local 'org-not-done-regexp)
4513 (defvar org-not-done-heading-regexp nil
4514 "Matches a TODO headline that is not done.")
4515 (make-variable-buffer-local 'org-not-done-regexp)
4516 (defvar org-todo-line-regexp nil
4517 "Matches a headline and puts TODO state into group 2 if present.")
4518 (make-variable-buffer-local 'org-todo-line-regexp)
4519 (defvar org-complex-heading-regexp nil
4520 "Matches a headline and puts everything into groups:
4521 group 1: the stars
4522 group 2: The todo keyword, maybe
4523 group 3: Priority cookie
4524 group 4: True headline
4525 group 5: Tags")
4526 (make-variable-buffer-local 'org-complex-heading-regexp)
4527 (defvar org-complex-heading-regexp-format nil
4528 "Printf format to make regexp to match an exact headline.
4529 This regexp will match the headline of any node which has the
4530 exact headline text that is put into the format, but may have any
4531 TODO state, priority and tags.")
4532 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4533 (defvar org-todo-line-tags-regexp nil
4534 "Matches a headline and puts TODO state into group 2 if present.
4535 Also put tags into group 4 if tags are present.")
4536 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4537 (defvar org-ds-keyword-length 12
4538 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4539 (make-variable-buffer-local 'org-ds-keyword-length)
4540 (defvar org-deadline-regexp nil
4541 "Matches the DEADLINE keyword.")
4542 (make-variable-buffer-local 'org-deadline-regexp)
4543 (defvar org-deadline-time-regexp nil
4544 "Matches the DEADLINE keyword together with a time stamp.")
4545 (make-variable-buffer-local 'org-deadline-time-regexp)
4546 (defvar org-deadline-line-regexp nil
4547 "Matches the DEADLINE keyword and the rest of the line.")
4548 (make-variable-buffer-local 'org-deadline-line-regexp)
4549 (defvar org-scheduled-regexp nil
4550 "Matches the SCHEDULED keyword.")
4551 (make-variable-buffer-local 'org-scheduled-regexp)
4552 (defvar org-scheduled-time-regexp nil
4553 "Matches the SCHEDULED keyword together with a time stamp.")
4554 (make-variable-buffer-local 'org-scheduled-time-regexp)
4555 (defvar org-closed-time-regexp nil
4556 "Matches the CLOSED keyword together with a time stamp.")
4557 (make-variable-buffer-local 'org-closed-time-regexp)
4559 (defvar org-keyword-time-regexp nil
4560 "Matches any of the 4 keywords, together with the time stamp.")
4561 (make-variable-buffer-local 'org-keyword-time-regexp)
4562 (defvar org-keyword-time-not-clock-regexp nil
4563 "Matches any of the 3 keywords, together with the time stamp.")
4564 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4565 (defvar org-maybe-keyword-time-regexp nil
4566 "Matches a timestamp, possibly preceded by a keyword.")
4567 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4568 (defvar org-all-time-keywords nil
4569 "List of time keywords.")
4570 (make-variable-buffer-local 'org-all-time-keywords)
4572 (defconst org-plain-time-of-day-regexp
4573 (concat
4574 "\\(\\<[012]?[0-9]"
4575 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4576 "\\(--?"
4577 "\\(\\<[012]?[0-9]"
4578 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4579 "\\)?")
4580 "Regular expression to match a plain time or time range.
4581 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4582 groups carry important information:
4583 0 the full match
4584 1 the first time, range or not
4585 8 the second time, if it is a range.")
4587 (defconst org-plain-time-extension-regexp
4588 (concat
4589 "\\(\\<[012]?[0-9]"
4590 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4591 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4592 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4593 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4594 groups carry important information:
4595 0 the full match
4596 7 hours of duration
4597 9 minutes of duration")
4599 (defconst org-stamp-time-of-day-regexp
4600 (concat
4601 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4602 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4603 "\\(--?"
4604 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4605 "Regular expression to match a timestamp time or time range.
4606 After a match, the following groups carry important information:
4607 0 the full match
4608 1 date plus weekday, for back referencing to make sure both times are on the same day
4609 2 the first time, range or not
4610 4 the second time, if it is a range.")
4612 (defconst org-startup-options
4613 '(("fold" org-startup-folded t)
4614 ("overview" org-startup-folded t)
4615 ("nofold" org-startup-folded nil)
4616 ("showall" org-startup-folded nil)
4617 ("showeverything" org-startup-folded showeverything)
4618 ("content" org-startup-folded content)
4619 ("indent" org-startup-indented t)
4620 ("noindent" org-startup-indented nil)
4621 ("hidestars" org-hide-leading-stars t)
4622 ("showstars" org-hide-leading-stars nil)
4623 ("odd" org-odd-levels-only t)
4624 ("oddeven" org-odd-levels-only nil)
4625 ("align" org-startup-align-all-tables t)
4626 ("noalign" org-startup-align-all-tables nil)
4627 ("inlineimages" org-startup-with-inline-images t)
4628 ("noinlineimages" org-startup-with-inline-images nil)
4629 ("latexpreview" org-startup-with-latex-preview t)
4630 ("nolatexpreview" org-startup-with-latex-preview nil)
4631 ("customtime" org-display-custom-times t)
4632 ("logdone" org-log-done time)
4633 ("lognotedone" org-log-done note)
4634 ("nologdone" org-log-done nil)
4635 ("lognoteclock-out" org-log-note-clock-out t)
4636 ("nolognoteclock-out" org-log-note-clock-out nil)
4637 ("logrepeat" org-log-repeat state)
4638 ("lognoterepeat" org-log-repeat note)
4639 ("logdrawer" org-log-into-drawer t)
4640 ("nologdrawer" org-log-into-drawer nil)
4641 ("logstatesreversed" org-log-states-order-reversed t)
4642 ("nologstatesreversed" org-log-states-order-reversed nil)
4643 ("nologrepeat" org-log-repeat nil)
4644 ("logreschedule" org-log-reschedule time)
4645 ("lognotereschedule" org-log-reschedule note)
4646 ("nologreschedule" org-log-reschedule nil)
4647 ("logredeadline" org-log-redeadline time)
4648 ("lognoteredeadline" org-log-redeadline note)
4649 ("nologredeadline" org-log-redeadline nil)
4650 ("logrefile" org-log-refile time)
4651 ("lognoterefile" org-log-refile note)
4652 ("nologrefile" org-log-refile nil)
4653 ("fninline" org-footnote-define-inline t)
4654 ("nofninline" org-footnote-define-inline nil)
4655 ("fnlocal" org-footnote-section nil)
4656 ("fnauto" org-footnote-auto-label t)
4657 ("fnprompt" org-footnote-auto-label nil)
4658 ("fnconfirm" org-footnote-auto-label confirm)
4659 ("fnplain" org-footnote-auto-label plain)
4660 ("fnadjust" org-footnote-auto-adjust t)
4661 ("nofnadjust" org-footnote-auto-adjust nil)
4662 ("constcgs" constants-unit-system cgs)
4663 ("constSI" constants-unit-system SI)
4664 ("noptag" org-tag-persistent-alist nil)
4665 ("hideblocks" org-hide-block-startup t)
4666 ("nohideblocks" org-hide-block-startup nil)
4667 ("beamer" org-startup-with-beamer-mode t)
4668 ("entitiespretty" org-pretty-entities t)
4669 ("entitiesplain" org-pretty-entities nil))
4670 "Variable associated with STARTUP options for org-mode.
4671 Each element is a list of three items: the startup options (as written
4672 in the #+STARTUP line), the corresponding variable, and the value to set
4673 this variable to if the option is found. An optional forth element PUSH
4674 means to push this value onto the list in the variable.")
4676 (defun org-update-property-plist (key val props)
4677 "Update PROPS with KEY and VAL."
4678 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4679 (key (if appending (substring key 0 (- (length key) 1)) key))
4680 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4681 (previous (cdr (assoc key props))))
4682 (if appending
4683 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4684 (cons (cons key val) remainder))))
4686 (defconst org-block-regexp
4687 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4688 "Regular expression for hiding blocks.")
4689 (defconst org-heading-keyword-regexp-format
4690 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4691 "Printf format for a regexp matching an headline with some keyword.
4692 This regexp will match the headline of any node which has the
4693 exact keyword that is put into the format. The keyword isn't in
4694 any group by default, but the stars and the body are.")
4695 (defconst org-heading-keyword-maybe-regexp-format
4696 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4697 "Printf format for a regexp matching an headline, possibly with some keyword.
4698 This regexp can match any headline with the specified keyword, or
4699 without a keyword. The keyword isn't in any group by default,
4700 but the stars and the body are.")
4702 (defun org-set-regexps-and-options ()
4703 "Precompute regular expressions for current buffer."
4704 (when (derived-mode-p 'org-mode)
4705 (org-set-local 'org-todo-kwd-alist nil)
4706 (org-set-local 'org-todo-key-alist nil)
4707 (org-set-local 'org-todo-key-trigger nil)
4708 (org-set-local 'org-todo-keywords-1 nil)
4709 (org-set-local 'org-done-keywords nil)
4710 (org-set-local 'org-todo-heads nil)
4711 (org-set-local 'org-todo-sets nil)
4712 (org-set-local 'org-todo-log-states nil)
4713 (org-set-local 'org-file-properties nil)
4714 (org-set-local 'org-file-tags nil)
4715 (let ((re (org-make-options-regexp
4716 '("CATEGORY" "TODO" "COLUMNS"
4717 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4718 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4719 "OPTIONS")
4720 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4721 (splitre "[ \t]+")
4722 (scripts org-use-sub-superscripts)
4723 kwds kws0 kwsa key log value cat arch tags const links hw dws
4724 tail sep kws1 prio props ftags drawers beamer-p
4725 ext-setup-or-nil setup-contents (start 0))
4726 (save-excursion
4727 (save-restriction
4728 (widen)
4729 (goto-char (point-min))
4730 (while (or (and ext-setup-or-nil
4731 (string-match re ext-setup-or-nil start)
4732 (setq start (match-end 0)))
4733 (and (setq ext-setup-or-nil nil start 0)
4734 (re-search-forward re nil t)))
4735 (setq key (upcase (match-string 1 ext-setup-or-nil))
4736 value (org-match-string-no-properties 2 ext-setup-or-nil))
4737 (if (stringp value) (setq value (org-trim value)))
4738 (cond
4739 ((equal key "CATEGORY")
4740 (setq cat value))
4741 ((member key '("SEQ_TODO" "TODO"))
4742 (push (cons 'sequence (org-split-string value splitre)) kwds))
4743 ((equal key "TYP_TODO")
4744 (push (cons 'type (org-split-string value splitre)) kwds))
4745 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4746 ;; general TODO-like setup
4747 (push (cons (intern (downcase (match-string 1 key)))
4748 (org-split-string value splitre)) kwds))
4749 ((equal key "TAGS")
4750 (setq tags (append tags (if tags '("\\n") nil)
4751 (org-split-string value splitre))))
4752 ((equal key "COLUMNS")
4753 (org-set-local 'org-columns-default-format value))
4754 ((equal key "LINK")
4755 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4756 (push (cons (match-string 1 value)
4757 (org-trim (match-string 2 value)))
4758 links)))
4759 ((equal key "PRIORITIES")
4760 (setq prio (org-split-string value " +")))
4761 ((equal key "PROPERTY")
4762 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4763 (setq props (org-update-property-plist (match-string 1 value)
4764 (match-string 2 value)
4765 props))))
4766 ((equal key "FILETAGS")
4767 (when (string-match "\\S-" value)
4768 (setq ftags
4769 (append
4770 ftags
4771 (apply 'append
4772 (mapcar (lambda (x) (org-split-string x ":"))
4773 (org-split-string value)))))))
4774 ((equal key "DRAWERS")
4775 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4776 ((equal key "CONSTANTS")
4777 (setq const (append const (org-split-string value splitre))))
4778 ((equal key "STARTUP")
4779 (let ((opts (org-split-string value splitre))
4780 l var val)
4781 (while (setq l (pop opts))
4782 (when (setq l (assoc l org-startup-options))
4783 (setq var (nth 1 l) val (nth 2 l))
4784 (if (not (nth 3 l))
4785 (set (make-local-variable var) val)
4786 (if (not (listp (symbol-value var)))
4787 (set (make-local-variable var) nil))
4788 (set (make-local-variable var) (symbol-value var))
4789 (add-to-list var val))))))
4790 ((equal key "ARCHIVE")
4791 (setq arch value)
4792 (remove-text-properties 0 (length arch)
4793 '(face t fontified t) arch))
4794 ((equal key "LATEX_CLASS")
4795 (setq beamer-p (equal value "beamer")))
4796 ((equal key "OPTIONS")
4797 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4798 (setq scripts (read (match-string 2 value)))))
4799 ((equal key "SETUPFILE")
4800 (setq setup-contents (org-file-contents
4801 (expand-file-name
4802 (org-remove-double-quotes value))
4803 'noerror))
4804 (if (not ext-setup-or-nil)
4805 (setq ext-setup-or-nil setup-contents start 0)
4806 (setq ext-setup-or-nil
4807 (concat (substring ext-setup-or-nil 0 start)
4808 "\n" setup-contents "\n"
4809 (substring ext-setup-or-nil start)))))))
4810 ;; search for property blocks
4811 (goto-char (point-min))
4812 (while (re-search-forward org-block-regexp nil t)
4813 (when (equal "PROPERTY" (upcase (match-string 1)))
4814 (setq value (replace-regexp-in-string
4815 "[\n\r]" " " (match-string 4)))
4816 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4817 (setq props (org-update-property-plist (match-string 1 value)
4818 (match-string 2 value)
4819 props)))))))
4820 (org-set-local 'org-use-sub-superscripts scripts)
4821 (when cat
4822 (org-set-local 'org-category (intern cat))
4823 (push (cons "CATEGORY" cat) props))
4824 (when prio
4825 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4826 (setq prio (mapcar 'string-to-char prio))
4827 (org-set-local 'org-highest-priority (nth 0 prio))
4828 (org-set-local 'org-lowest-priority (nth 1 prio))
4829 (org-set-local 'org-default-priority (nth 2 prio)))
4830 (and props (org-set-local 'org-file-properties (nreverse props)))
4831 (and ftags (org-set-local 'org-file-tags
4832 (mapcar 'org-add-prop-inherited ftags)))
4833 (and drawers (org-set-local 'org-drawers drawers))
4834 (and arch (org-set-local 'org-archive-location arch))
4835 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4836 ;; Process the TODO keywords
4837 (unless kwds
4838 ;; Use the global values as if they had been given locally.
4839 (setq kwds (default-value 'org-todo-keywords))
4840 (if (stringp (car kwds))
4841 (setq kwds (list (cons org-todo-interpretation
4842 (default-value 'org-todo-keywords)))))
4843 (setq kwds (reverse kwds)))
4844 (setq kwds (nreverse kwds))
4845 (let (inter kws kw)
4846 (while (setq kws (pop kwds))
4847 (let ((kws (or
4848 (run-hook-with-args-until-success
4849 'org-todo-setup-filter-hook kws)
4850 kws)))
4851 (setq inter (pop kws) sep (member "|" kws)
4852 kws0 (delete "|" (copy-sequence kws))
4853 kwsa nil
4854 kws1 (mapcar
4855 (lambda (x)
4856 ;; 1 2
4857 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4858 (progn
4859 (setq kw (match-string 1 x)
4860 key (and (match-end 2) (match-string 2 x))
4861 log (org-extract-log-state-settings x))
4862 (push (cons kw (and key (string-to-char key))) kwsa)
4863 (and log (push log org-todo-log-states))
4865 (error "Invalid TODO keyword %s" x)))
4866 kws0)
4867 kwsa (if kwsa (append '((:startgroup))
4868 (nreverse kwsa)
4869 '((:endgroup))))
4870 hw (car kws1)
4871 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4872 tail (list inter hw (car dws) (org-last dws))))
4873 (add-to-list 'org-todo-heads hw 'append)
4874 (push kws1 org-todo-sets)
4875 (setq org-done-keywords (append org-done-keywords dws nil))
4876 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4877 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4878 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4879 (setq org-todo-sets (nreverse org-todo-sets)
4880 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4881 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4882 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4883 ;; Process the constants
4884 (when const
4885 (let (e cst)
4886 (while (setq e (pop const))
4887 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4888 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4889 (setq org-table-formula-constants-local cst)))
4891 ;; Process the tags.
4892 (when tags
4893 (let (e tgs)
4894 (while (setq e (pop tags))
4895 (cond
4896 ((equal e "{") (push '(:startgroup) tgs))
4897 ((equal e "}") (push '(:endgroup) tgs))
4898 ((equal e "\\n") (push '(:newline) tgs))
4899 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4900 (push (cons (match-string 1 e)
4901 (string-to-char (match-string 2 e)))
4902 tgs))
4903 (t (push (list e) tgs))))
4904 (org-set-local 'org-tag-alist nil)
4905 (while (setq e (pop tgs))
4906 (or (and (stringp (car e))
4907 (assoc (car e) org-tag-alist))
4908 (push e org-tag-alist)))))
4910 ;; Compute the regular expressions and other local variables.
4911 ;; Using `org-outline-regexp-bol' would complicate them much,
4912 ;; because of the fixed white space at the end of that string.
4913 (if (not org-done-keywords)
4914 (setq org-done-keywords (and org-todo-keywords-1
4915 (list (org-last org-todo-keywords-1)))))
4916 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4917 (length org-scheduled-string)
4918 (length org-clock-string)
4919 (length org-closed-string)))
4920 org-drawer-regexp
4921 (concat "^[ \t]*:\\("
4922 (mapconcat 'regexp-quote org-drawers "\\|")
4923 "\\):[ \t]*$")
4924 org-not-done-keywords
4925 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4926 org-todo-regexp
4927 (concat "\\("
4928 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4929 "\\)")
4930 org-not-done-regexp
4931 (concat "\\("
4932 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4933 "\\)")
4934 org-not-done-heading-regexp
4935 (format org-heading-keyword-regexp-format org-not-done-regexp)
4936 org-todo-line-regexp
4937 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4938 org-complex-heading-regexp
4939 (concat "^\\(\\*+\\)"
4940 "\\(?: +" org-todo-regexp "\\)?"
4941 "\\(?: +\\(\\[#.\\]\\)\\)?"
4942 "\\(?: +\\(.*?\\)\\)??"
4943 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4944 "[ \t]*$")
4945 org-complex-heading-regexp-format
4946 (concat "^\\(\\*+\\)"
4947 "\\(?: +" org-todo-regexp "\\)?"
4948 "\\(?: +\\(\\[#.\\]\\)\\)?"
4949 "\\(?: +"
4950 ;; Stats cookies can be stuck to body.
4951 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4952 "\\(%s\\)"
4953 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4954 "\\)"
4955 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4956 "[ \t]*$")
4957 org-todo-line-tags-regexp
4958 (concat "^\\(\\*+\\)"
4959 "\\(?: +" org-todo-regexp "\\)?"
4960 "\\(?: +\\(.*?\\)\\)??"
4961 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4962 "[ \t]*$")
4963 org-deadline-regexp (concat "\\<" org-deadline-string)
4964 org-deadline-time-regexp
4965 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4966 org-deadline-line-regexp
4967 (concat "\\<\\(" org-deadline-string "\\).*")
4968 org-scheduled-regexp
4969 (concat "\\<" org-scheduled-string)
4970 org-scheduled-time-regexp
4971 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4972 org-closed-time-regexp
4973 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4974 org-keyword-time-regexp
4975 (concat "\\<\\(" org-scheduled-string
4976 "\\|" org-deadline-string
4977 "\\|" org-closed-string
4978 "\\|" org-clock-string "\\)"
4979 " *[[<]\\([^]>]+\\)[]>]")
4980 org-keyword-time-not-clock-regexp
4981 (concat "\\<\\(" org-scheduled-string
4982 "\\|" org-deadline-string
4983 "\\|" org-closed-string
4984 "\\)"
4985 " *[[<]\\([^]>]+\\)[]>]")
4986 org-maybe-keyword-time-regexp
4987 (concat "\\(\\<\\(" org-scheduled-string
4988 "\\|" org-deadline-string
4989 "\\|" org-closed-string
4990 "\\|" org-clock-string "\\)\\)?"
4991 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4992 org-all-time-keywords
4993 (mapcar (lambda (w) (substring w 0 -1))
4994 (list org-scheduled-string org-deadline-string
4995 org-clock-string org-closed-string)))
4996 (org-set-font-lock-defaults))))
4998 (defun org-file-contents (file &optional noerror)
4999 "Return the contents of FILE, as a string."
5000 (if (or (not file)
5001 (not (file-readable-p file)))
5002 (if noerror
5003 (progn
5004 (message "Cannot read file \"%s\"" file)
5005 (ding) (sit-for 2)
5007 (error "Cannot read file \"%s\"" file))
5008 (with-temp-buffer
5009 (insert-file-contents file)
5010 (buffer-string))))
5012 (defun org-extract-log-state-settings (x)
5013 "Extract the log state setting from a TODO keyword string.
5014 This will extract info from a string like \"WAIT(w@/!)\"."
5015 (let (kw key log1 log2)
5016 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5017 (setq kw (match-string 1 x)
5018 key (and (match-end 2) (match-string 2 x))
5019 log1 (and (match-end 3) (match-string 3 x))
5020 log2 (and (match-end 4) (match-string 4 x)))
5021 (and (or log1 log2)
5022 (list kw
5023 (and log1 (if (equal log1 "!") 'time 'note))
5024 (and log2 (if (equal log2 "!") 'time 'note)))))))
5026 (defun org-remove-keyword-keys (list)
5027 "Remove a pair of parenthesis at the end of each string in LIST."
5028 (mapcar (lambda (x)
5029 (if (string-match "(.*)$" x)
5030 (substring x 0 (match-beginning 0))
5032 list))
5034 (defun org-assign-fast-keys (alist)
5035 "Assign fast keys to a keyword-key alist.
5036 Respect keys that are already there."
5037 (let (new e (alt ?0))
5038 (while (setq e (pop alist))
5039 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5040 (cdr e)) ;; Key already assigned.
5041 (push e new)
5042 (let ((clist (string-to-list (downcase (car e))))
5043 (used (append new alist)))
5044 (when (= (car clist) ?@)
5045 (pop clist))
5046 (while (and clist (rassoc (car clist) used))
5047 (pop clist))
5048 (unless clist
5049 (while (rassoc alt used)
5050 (incf alt)))
5051 (push (cons (car e) (or (car clist) alt)) new))))
5052 (nreverse new)))
5054 ;;; Some variables used in various places
5056 (defvar org-window-configuration nil
5057 "Used in various places to store a window configuration.")
5058 (defvar org-selected-window nil
5059 "Used in various places to store a window configuration.")
5060 (defvar org-finish-function nil
5061 "Function to be called when `C-c C-c' is used.
5062 This is for getting out of special buffers like capture.")
5065 ;; FIXME: Occasionally check by commenting these, to make sure
5066 ;; no other functions uses these, forgetting to let-bind them.
5067 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5068 (defvar org-last-state)
5069 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5071 ;; Defined somewhere in this file, but used before definition.
5072 (defvar org-entities) ;; defined in org-entities.el
5073 (defvar org-struct-menu)
5074 (defvar org-org-menu)
5075 (defvar org-tbl-menu)
5077 ;;;; Define the Org-mode
5079 ;; We use a before-change function to check if a table might need
5080 ;; an update.
5081 (defvar org-table-may-need-update t
5082 "Indicates that a table might need an update.
5083 This variable is set by `org-before-change-function'.
5084 `org-table-align' sets it back to nil.")
5085 (defun org-before-change-function (beg end)
5086 "Every change indicates that a table might need an update."
5087 (setq org-table-may-need-update t))
5088 (defvar org-mode-map)
5089 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5090 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5091 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5092 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5093 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5094 (defvar org-table-buffer-is-an nil)
5096 (defvar bidi-paragraph-direction)
5097 (defvar buffer-face-mode-face)
5099 (require 'outline)
5100 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5101 (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"))
5102 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5104 ;; Other stuff we need.
5105 (require 'time-date)
5106 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5107 (require 'easymenu)
5108 (require 'overlay)
5110 ;; (require 'org-macs) moved higher up in the file before it is first used
5111 (require 'org-entities)
5112 ;; (require 'org-compat) moved higher up in the file before it is first used
5113 (require 'org-faces)
5114 (require 'org-list)
5115 (require 'org-pcomplete)
5116 (require 'org-src)
5117 (require 'org-footnote)
5118 (require 'org-macro)
5120 ;; babel
5121 (require 'ob)
5123 ;;;###autoload
5124 (define-derived-mode org-mode outline-mode "Org"
5125 "Outline-based notes management and organizer, alias
5126 \"Carsten's outline-mode for keeping track of everything.\"
5128 Org-mode develops organizational tasks around a NOTES file which
5129 contains information about projects as plain text. Org-mode is
5130 implemented on top of outline-mode, which is ideal to keep the content
5131 of large files well structured. It supports ToDo items, deadlines and
5132 time stamps, which magically appear in the diary listing of the Emacs
5133 calendar. Tables are easily created with a built-in table editor.
5134 Plain text URL-like links connect to websites, emails (VM), Usenet
5135 messages (Gnus), BBDB entries, and any files related to the project.
5136 For printing and sharing of notes, an Org-mode file (or a part of it)
5137 can be exported as a structured ASCII or HTML file.
5139 The following commands are available:
5141 \\{org-mode-map}"
5143 ;; Get rid of Outline menus, they are not needed
5144 ;; Need to do this here because define-derived-mode sets up
5145 ;; the keymap so late. Still, it is a waste to call this each time
5146 ;; we switch another buffer into org-mode.
5147 (if (featurep 'xemacs)
5148 (when (boundp 'outline-mode-menu-heading)
5149 ;; Assume this is Greg's port, it uses easymenu
5150 (easy-menu-remove outline-mode-menu-heading)
5151 (easy-menu-remove outline-mode-menu-show)
5152 (easy-menu-remove outline-mode-menu-hide))
5153 (define-key org-mode-map [menu-bar headings] 'undefined)
5154 (define-key org-mode-map [menu-bar hide] 'undefined)
5155 (define-key org-mode-map [menu-bar show] 'undefined))
5157 (org-load-modules-maybe)
5158 (easy-menu-add org-org-menu)
5159 (easy-menu-add org-tbl-menu)
5160 (org-install-agenda-files-menu)
5161 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5162 (add-to-invisibility-spec '(org-cwidth))
5163 (add-to-invisibility-spec '(org-hide-block . t))
5164 (when (featurep 'xemacs)
5165 (org-set-local 'line-move-ignore-invisible t))
5166 (org-set-local 'outline-regexp org-outline-regexp)
5167 (org-set-local 'outline-level 'org-outline-level)
5168 (setq bidi-paragraph-direction 'left-to-right)
5169 (when (and org-ellipsis
5170 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5171 (fboundp 'make-glyph-code))
5172 (unless org-display-table
5173 (setq org-display-table (make-display-table)))
5174 (set-display-table-slot
5175 org-display-table 4
5176 (vconcat (mapcar
5177 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5178 org-ellipsis)))
5179 (if (stringp org-ellipsis) org-ellipsis "..."))))
5180 (setq buffer-display-table org-display-table))
5181 (org-set-regexps-and-options)
5182 (when (and org-tag-faces (not org-tags-special-faces-re))
5183 ;; tag faces set outside customize.... force initialization.
5184 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5185 ;; Calc embedded
5186 (org-set-local 'calc-embedded-open-mode "# ")
5187 (mapc (lambda(c) (modify-syntax-entry (string-to-char (car c)) "w p"))
5188 org-emphasis-alist)
5189 (modify-syntax-entry ?< "(")
5190 (modify-syntax-entry ?> ")")
5191 (modify-syntax-entry ?{ "(")
5192 (modify-syntax-entry ?} ")")
5193 (modify-syntax-entry ?@ "w")
5194 (modify-syntax-entry ?\" "\"")
5195 (if org-startup-truncated (setq truncate-lines t))
5196 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5197 (org-set-local 'font-lock-unfontify-region-function
5198 'org-unfontify-region)
5199 ;; Activate before-change-function
5200 (org-set-local 'org-table-may-need-update t)
5201 (org-add-hook 'before-change-functions 'org-before-change-function nil
5202 'local)
5203 ;; Check for running clock before killing a buffer
5204 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5205 ;; Initialize macros templates.
5206 (org-macro-initialize-templates)
5207 ;; Initialize radio targets.
5208 (org-update-radio-target-regexp)
5209 ;; Indentation.
5210 (org-set-local 'indent-line-function 'org-indent-line)
5211 (org-set-local 'indent-region-function 'org-indent-region)
5212 ;; Filling and auto-filling.
5213 (org-setup-filling)
5214 ;; Comments.
5215 (org-setup-comments-handling)
5216 ;; Beginning/end of defun
5217 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5218 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5219 ;; Next error for sparse trees
5220 (org-set-local 'next-error-function 'org-occur-next-match)
5221 ;; Make sure dependence stuff works reliably, even for users who set it
5222 ;; too late :-(
5223 (if org-enforce-todo-dependencies
5224 (add-hook 'org-blocker-hook
5225 'org-block-todo-from-children-or-siblings-or-parent)
5226 (remove-hook 'org-blocker-hook
5227 'org-block-todo-from-children-or-siblings-or-parent))
5228 (if org-enforce-todo-checkbox-dependencies
5229 (add-hook 'org-blocker-hook
5230 'org-block-todo-from-checkboxes)
5231 (remove-hook 'org-blocker-hook
5232 'org-block-todo-from-checkboxes))
5234 ;; Align options lines
5235 (org-set-local
5236 'align-mode-rules-list
5237 '((org-in-buffer-settings
5238 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5239 (modes . '(org-mode)))))
5241 ;; Imenu
5242 (org-set-local 'imenu-create-index-function
5243 'org-imenu-get-tree)
5245 ;; Make isearch reveal context
5246 (if (or (featurep 'xemacs)
5247 (not (boundp 'outline-isearch-open-invisible-function)))
5248 ;; Emacs 21 and XEmacs make use of the hook
5249 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5250 ;; Emacs 22 deals with this through a special variable
5251 (org-set-local 'outline-isearch-open-invisible-function
5252 (lambda (&rest ignore) (org-show-context 'isearch))))
5254 ;; Setup the pcomplete hooks
5255 (set (make-local-variable 'pcomplete-command-completion-function)
5256 'org-pcomplete-initial)
5257 (set (make-local-variable 'pcomplete-command-name-function)
5258 'org-command-at-point)
5259 (set (make-local-variable 'pcomplete-default-completion-function)
5260 'ignore)
5261 (set (make-local-variable 'pcomplete-parse-arguments-function)
5262 'org-parse-arguments)
5263 (set (make-local-variable 'pcomplete-termination-string) "")
5264 (when (>= emacs-major-version 23)
5265 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5267 ;; If empty file that did not turn on org-mode automatically, make it to.
5268 (if (and org-insert-mode-line-in-empty-file
5269 (org-called-interactively-p 'any)
5270 (= (point-min) (point-max)))
5271 (insert "# -*- mode: org -*-\n\n"))
5272 (unless org-inhibit-startup
5273 (org-unmodified
5274 (and org-startup-with-beamer-mode (org-beamer-mode))
5275 (when org-startup-align-all-tables
5276 (org-table-map-tables 'org-table-align 'quietly))
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 (org-element-property :raw-value (org-element-at-point))))))
9273 (lines org-context-in-file-links))
9274 (or string (setq s (concat "*" s))) ; Add * for headlines
9275 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
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 (t (org-do-occur (match-string 1 s)))))
10365 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10366 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10367 (goto-char (point-min))
10368 (cond
10369 ((let (case-fold-search)
10370 (re-search-forward (format org-complex-heading-regexp-format
10371 (regexp-quote s))
10372 nil t))
10373 ;; OK, found a match
10374 (setq type 'dedicated)
10375 (goto-char (match-beginning 0)))
10376 ((and (not org-link-search-inhibit-query)
10377 (eq org-link-search-must-match-exact-headline 'query-to-create)
10378 (y-or-n-p "No match - create this as a new heading? "))
10379 (goto-char (point-max))
10380 (or (bolp) (newline))
10381 (insert "* " s "\n")
10382 (beginning-of-line 0))
10384 (goto-char pos)
10385 (error "No match"))))
10387 ;; A normal search string
10388 (when (equal (string-to-char s) ?*)
10389 ;; Anchor on headlines, post may include tags.
10390 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10391 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10392 s (substring s 1)))
10393 (remove-text-properties
10394 0 (length s)
10395 '(face nil mouse-face nil keymap nil fontified nil) s)
10396 ;; Make a series of regular expressions to find a match
10397 (setq words (org-split-string s "[ \n\r\t]+")
10399 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10400 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10401 "\\)" markers)
10402 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10403 re2a (concat "[ \t\r\n]" re2a_)
10404 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10405 re4 (concat "[^a-zA-Z_]" re4_)
10407 re1 (concat pre re2 post)
10408 re3 (concat pre (if pre re4_ re4) post)
10409 re5 (concat pre ".*" re4)
10410 re2 (concat pre re2)
10411 re2a (concat pre (if pre re2a_ re2a))
10412 re4 (concat pre (if pre re4_ re4))
10413 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10414 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10415 re5 "\\)"
10417 (cond
10418 ((eq type 'org-occur) (org-occur reall))
10419 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10420 (t (goto-char (point-min))
10421 (setq type 'fuzzy)
10422 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10423 (org-search-not-self 1 re1 nil t)
10424 (org-search-not-self 1 re2 nil t)
10425 (org-search-not-self 1 re2a nil t)
10426 (org-search-not-self 1 re3 nil t)
10427 (org-search-not-self 1 re4 nil t)
10428 (org-search-not-self 1 re5 nil t)
10430 (goto-char (match-beginning 1))
10431 (goto-char pos)
10432 (error "No match"))))))
10433 (and (derived-mode-p 'org-mode)
10434 (not stealth)
10435 (org-show-context 'link-search))
10436 type))
10438 (defun org-search-not-self (group &rest args)
10439 "Execute `re-search-forward', but only accept matches that do not
10440 enclose the position of `org-open-link-marker'."
10441 (let ((m org-open-link-marker))
10442 (catch 'exit
10443 (while (apply 're-search-forward args)
10444 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10445 (goto-char (match-end group))
10446 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10447 (> (match-beginning 0) (marker-position m))
10448 (< (match-end 0) (marker-position m)))
10449 (save-match-data
10450 (or (not (org-in-regexp
10451 org-bracket-link-analytic-regexp 1))
10452 (not (match-end 4)) ; no description
10453 (and (<= (match-beginning 4) (point))
10454 (>= (match-end 4) (point))))))
10455 (throw 'exit (point))))))))
10457 (defun org-get-buffer-for-internal-link (buffer)
10458 "Return a buffer to be used for displaying the link target of internal links."
10459 (cond
10460 ((not org-display-internal-link-with-indirect-buffer)
10461 buffer)
10462 ((string-match "(Clone)$" (buffer-name buffer))
10463 (message "Buffer is already a clone, not making another one")
10464 ;; we also do not modify visibility in this case
10465 buffer)
10466 (t ; make a new indirect buffer for displaying the link
10467 (let* ((bn (buffer-name buffer))
10468 (ibn (concat bn "(Clone)"))
10469 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10470 (with-current-buffer ib (org-overview))
10471 ib))))
10473 (defun org-do-occur (regexp &optional cleanup)
10474 "Call the Emacs command `occur'.
10475 If CLEANUP is non-nil, remove the printout of the regular expression
10476 in the *Occur* buffer. This is useful if the regex is long and not useful
10477 to read."
10478 (occur regexp)
10479 (when cleanup
10480 (let ((cwin (selected-window)) win beg end)
10481 (when (setq win (get-buffer-window "*Occur*"))
10482 (select-window win))
10483 (goto-char (point-min))
10484 (when (re-search-forward "match[a-z]+" nil t)
10485 (setq beg (match-end 0))
10486 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10487 (setq end (1- (match-beginning 0)))))
10488 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10489 (goto-char (point-min))
10490 (select-window cwin))))
10492 ;;; The mark ring for links jumps
10494 (defvar org-mark-ring nil
10495 "Mark ring for positions before jumps in Org-mode.")
10496 (defvar org-mark-ring-last-goto nil
10497 "Last position in the mark ring used to go back.")
10498 ;; Fill and close the ring
10499 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10500 (loop for i from 1 to org-mark-ring-length do
10501 (push (make-marker) org-mark-ring))
10502 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10503 org-mark-ring)
10505 (defun org-mark-ring-push (&optional pos buffer)
10506 "Put the current position or POS into the mark ring and rotate it."
10507 (interactive)
10508 (setq pos (or pos (point)))
10509 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10510 (move-marker (car org-mark-ring)
10511 (or pos (point))
10512 (or buffer (current-buffer)))
10513 (message "%s"
10514 (substitute-command-keys
10515 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10517 (defun org-mark-ring-goto (&optional n)
10518 "Jump to the previous position in the mark ring.
10519 With prefix arg N, jump back that many stored positions. When
10520 called several times in succession, walk through the entire ring.
10521 Org-mode commands jumping to a different position in the current file,
10522 or to another Org-mode file, automatically push the old position
10523 onto the ring."
10524 (interactive "p")
10525 (let (p m)
10526 (if (eq last-command this-command)
10527 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10528 (setq p org-mark-ring))
10529 (setq org-mark-ring-last-goto p)
10530 (setq m (car p))
10531 (org-pop-to-buffer-same-window (marker-buffer m))
10532 (goto-char m)
10533 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10535 (defun org-remove-angle-brackets (s)
10536 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10537 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10539 (defun org-add-angle-brackets (s)
10540 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10541 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10543 (defun org-remove-double-quotes (s)
10544 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10545 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10548 ;;; Following specific links
10550 (defun org-follow-timestamp-link ()
10551 "Open an agenda view for the time-stamp date/range at point."
10552 (cond
10553 ((org-at-date-range-p t)
10554 (let ((org-agenda-start-on-weekday)
10555 (t1 (match-string 1))
10556 (t2 (match-string 2)) tt1 tt2)
10557 (setq tt1 (time-to-days (org-time-string-to-time t1))
10558 tt2 (time-to-days (org-time-string-to-time t2)))
10559 (let ((org-agenda-buffer-tmp-name
10560 (format "*Org Agenda(a:%s)"
10561 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10562 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10563 ((org-at-timestamp-p t)
10564 (let ((org-agenda-buffer-tmp-name
10565 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10566 (org-agenda-list nil (time-to-days (org-time-string-to-time
10567 (substring (match-string 1) 0 10)))
10568 1)))
10569 (t (error "This should not happen"))))
10572 ;;; Following file links
10573 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10574 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10575 (declare-function mailcap-mime-info
10576 "mailcap" (string &optional request no-decode))
10577 (defvar org-wait nil)
10578 (defun org-open-file (path &optional in-emacs line search)
10579 "Open the file at PATH.
10580 First, this expands any special file name abbreviations. Then the
10581 configuration variable `org-file-apps' is checked if it contains an
10582 entry for this file type, and if yes, the corresponding command is launched.
10584 If no application is found, Emacs simply visits the file.
10586 With optional prefix argument IN-EMACS, Emacs will visit the file.
10587 With a double \\[universal-argument] \\[universal-argument] \
10588 prefix arg, Org tries to avoid opening in Emacs
10589 and to use an external application to visit the file.
10591 Optional LINE specifies a line to go to, optional SEARCH a string
10592 to search for. If LINE or SEARCH is given, the file will be
10593 opened in Emacs, unless an entry from org-file-apps that makes
10594 use of groups in a regexp matches.
10596 If you want to change the way frames are used when following a
10597 link, please customize `org-link-frame-setup'.
10599 If the file does not exist, an error is thrown."
10600 (let* ((file (if (equal path "")
10601 buffer-file-name
10602 (substitute-in-file-name (expand-file-name path))))
10603 (file-apps (append org-file-apps (org-default-apps)))
10604 (apps (org-remove-if
10605 'org-file-apps-entry-match-against-dlink-p file-apps))
10606 (apps-dlink (org-remove-if-not
10607 'org-file-apps-entry-match-against-dlink-p file-apps))
10608 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10609 (dirp (if remp nil (file-directory-p file)))
10610 (file (if (and dirp org-open-directory-means-index-dot-org)
10611 (concat (file-name-as-directory file) "index.org")
10612 file))
10613 (a-m-a-p (assq 'auto-mode apps))
10614 (dfile (downcase file))
10615 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10616 (link (cond ((and (eq line nil)
10617 (eq search nil))
10618 file)
10619 (line
10620 (concat file "::" (number-to-string line)))
10621 (search
10622 (concat file "::" search))))
10623 (dlink (downcase link))
10624 (old-buffer (current-buffer))
10625 (old-pos (point))
10626 (old-mode major-mode)
10627 ext cmd link-match-data)
10628 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10629 (setq ext (match-string 1 dfile))
10630 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10631 (setq ext (match-string 1 dfile))))
10632 (cond
10633 ((member in-emacs '((16) system))
10634 (setq cmd (cdr (assoc 'system apps))))
10635 (in-emacs (setq cmd 'emacs))
10637 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10638 (and dirp (cdr (assoc 'directory apps)))
10639 ; first, try matching against apps-dlink
10640 ; if we get a match here, store the match data for later
10641 (let ((match (assoc-default dlink apps-dlink
10642 'string-match)))
10643 (if match
10644 (progn (setq link-match-data (match-data))
10645 match)
10646 (progn (setq in-emacs (or in-emacs line search))
10647 nil))) ; if we have no match in apps-dlink,
10648 ; always open the file in emacs if line or search
10649 ; is given (for backwards compatibility)
10650 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10651 'string-match)
10652 (cdr (assoc ext apps))
10653 (cdr (assoc t apps))))))
10654 (when (eq cmd 'system)
10655 (setq cmd (cdr (assoc 'system apps))))
10656 (when (eq cmd 'default)
10657 (setq cmd (cdr (assoc t apps))))
10658 (when (eq cmd 'mailcap)
10659 (require 'mailcap)
10660 (mailcap-parse-mailcaps)
10661 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10662 (command (mailcap-mime-info mime-type)))
10663 (if (stringp command)
10664 (setq cmd command)
10665 (setq cmd 'emacs))))
10666 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10667 (not (file-exists-p file))
10668 (not org-open-non-existing-files))
10669 (error "No such file: %s" file))
10670 (cond
10671 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10672 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10673 (while (string-match "['\"]%s['\"]" cmd)
10674 (setq cmd (replace-match "%s" t t cmd)))
10675 (while (string-match "%s" cmd)
10676 (setq cmd (replace-match
10677 (save-match-data
10678 (shell-quote-argument
10679 (convert-standard-filename file)))
10680 t t cmd)))
10682 ;; Replace "%1", "%2" etc. in command with group matches from regex
10683 (save-match-data
10684 (let ((match-index 1)
10685 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10686 (set-match-data link-match-data)
10687 (while (<= match-index number-of-groups)
10688 (let ((regex (concat "%" (number-to-string match-index)))
10689 (replace-with (match-string match-index dlink)))
10690 (while (string-match regex cmd)
10691 (setq cmd (replace-match replace-with t t cmd))))
10692 (setq match-index (+ match-index 1)))))
10694 (save-window-excursion
10695 (message "Running %s...done" cmd)
10696 (start-process-shell-command cmd nil cmd)
10697 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10698 ((or (stringp cmd)
10699 (eq cmd 'emacs))
10700 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10701 (widen)
10702 (if line (org-goto-line line)
10703 (if search (org-link-search search))))
10704 ((consp cmd)
10705 (let ((file (convert-standard-filename file)))
10706 (save-match-data
10707 (set-match-data link-match-data)
10708 (eval cmd))))
10709 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10710 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10711 (or (not (equal old-buffer (current-buffer)))
10712 (not (equal old-pos (point))))
10713 (org-mark-ring-push old-pos old-buffer))))
10715 (defun org-file-apps-entry-match-against-dlink-p (entry)
10716 "This function returns non-nil if `entry' uses a regular
10717 expression which should be matched against the whole link by
10718 org-open-file.
10720 It assumes that is the case when the entry uses a regular
10721 expression which has at least one grouping construct and the
10722 action is either a lisp form or a command string containing
10723 '%1', i.e. using at least one subexpression match as a
10724 parameter."
10725 (let ((selector (car entry))
10726 (action (cdr entry)))
10727 (if (stringp selector)
10728 (and (> (regexp-opt-depth selector) 0)
10729 (or (and (stringp action)
10730 (string-match "%[0-9]" action))
10731 (consp action)))
10732 nil)))
10734 (defun org-default-apps ()
10735 "Return the default applications for this operating system."
10736 (cond
10737 ((eq system-type 'darwin)
10738 org-file-apps-defaults-macosx)
10739 ((eq system-type 'windows-nt)
10740 org-file-apps-defaults-windowsnt)
10741 (t org-file-apps-defaults-gnu)))
10743 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10744 "Convert extensions to regular expressions in the cars of LIST.
10745 Also, weed out any non-string entries, because the return value is used
10746 only for regexp matching.
10747 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10748 point to the symbol `emacs', indicating that the file should
10749 be opened in Emacs."
10750 (append
10751 (delq nil
10752 (mapcar (lambda (x)
10753 (if (not (stringp (car x)))
10755 (if (string-match "\\W" (car x))
10757 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10758 list))
10759 (if add-auto-mode
10760 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10762 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10763 (defun org-file-remote-p (file)
10764 "Test whether FILE specifies a location on a remote system.
10765 Return non-nil if the location is indeed remote.
10767 For example, the filename \"/user@host:/foo\" specifies a location
10768 on the system \"/user@host:\"."
10769 (cond ((fboundp 'file-remote-p)
10770 (file-remote-p file))
10771 ((fboundp 'tramp-handle-file-remote-p)
10772 (tramp-handle-file-remote-p file))
10773 ((and (boundp 'ange-ftp-name-format)
10774 (string-match (car ange-ftp-name-format) file))
10775 t)))
10778 ;;;; Refiling
10780 (defun org-get-org-file ()
10781 "Read a filename, with default directory `org-directory'."
10782 (let ((default (or org-default-notes-file remember-data-file)))
10783 (read-file-name (format "File name [%s]: " default)
10784 (file-name-as-directory org-directory)
10785 default)))
10787 (defun org-notes-order-reversed-p ()
10788 "Check if the current file should receive notes in reversed order."
10789 (cond
10790 ((not org-reverse-note-order) nil)
10791 ((eq t org-reverse-note-order) t)
10792 ((not (listp org-reverse-note-order)) nil)
10793 (t (catch 'exit
10794 (let ((all org-reverse-note-order)
10795 entry)
10796 (while (setq entry (pop all))
10797 (if (string-match (car entry) buffer-file-name)
10798 (throw 'exit (cdr entry))))
10799 nil)))))
10801 (defvar org-refile-target-table nil
10802 "The list of refile targets, created by `org-refile'.")
10804 (defvar org-agenda-new-buffers nil
10805 "Buffers created to visit agenda files.")
10807 (defvar org-refile-cache nil
10808 "Cache for refile targets.")
10810 (defvar org-refile-markers nil
10811 "All the markers used for caching refile locations.")
10813 (defun org-refile-marker (pos)
10814 "Get a new refile marker, but only if caching is in use."
10815 (if (not org-refile-use-cache)
10817 (let ((m (make-marker)))
10818 (move-marker m pos)
10819 (push m org-refile-markers)
10820 m)))
10822 (defun org-refile-cache-clear ()
10823 "Clear the refile cache and disable all the markers."
10824 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10825 (setq org-refile-markers nil)
10826 (setq org-refile-cache nil)
10827 (message "Refile cache has been cleared"))
10829 (defun org-refile-cache-check-set (set)
10830 "Check if all the markers in the cache still have live buffers."
10831 (let (marker)
10832 (catch 'exit
10833 (while (and set (setq marker (nth 3 (pop set))))
10834 ;; if org-refile-use-outline-path is 'file, marker may be nil
10835 (when (and marker (null (marker-buffer marker)))
10836 (message "not found") (sit-for 3)
10837 (throw 'exit nil)))
10838 t)))
10840 (defun org-refile-cache-put (set &rest identifiers)
10841 "Push the refile targets SET into the cache, under IDENTIFIERS."
10842 (let* ((key (sha1 (prin1-to-string identifiers)))
10843 (entry (assoc key org-refile-cache)))
10844 (if entry
10845 (setcdr entry set)
10846 (push (cons key set) org-refile-cache))))
10848 (defun org-refile-cache-get (&rest identifiers)
10849 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10850 (cond
10851 ((not org-refile-cache) nil)
10852 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10854 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10855 org-refile-cache))))
10856 (and set (org-refile-cache-check-set set) set)))))
10858 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10859 "Produce a table with refile targets."
10860 (let ((case-fold-search nil)
10861 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10862 (entries (or org-refile-targets '((nil . (:level . 1)))))
10863 targets tgs txt re files f desc descre fast-path-p level pos0)
10864 (message "Getting targets...")
10865 (with-current-buffer (or default-buffer (current-buffer))
10866 (while (setq entry (pop entries))
10867 (setq files (car entry) desc (cdr entry))
10868 (setq fast-path-p nil)
10869 (cond
10870 ((null files) (setq files (list (current-buffer))))
10871 ((eq files 'org-agenda-files)
10872 (setq files (org-agenda-files 'unrestricted)))
10873 ((and (symbolp files) (fboundp files))
10874 (setq files (funcall files)))
10875 ((and (symbolp files) (boundp files))
10876 (setq files (symbol-value files))))
10877 (if (stringp files) (setq files (list files)))
10878 (cond
10879 ((eq (car desc) :tag)
10880 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10881 ((eq (car desc) :todo)
10882 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10883 ((eq (car desc) :regexp)
10884 (setq descre (cdr desc)))
10885 ((eq (car desc) :level)
10886 (setq descre (concat "^\\*\\{" (number-to-string
10887 (if org-odd-levels-only
10888 (1- (* 2 (cdr desc)))
10889 (cdr desc)))
10890 "\\}[ \t]")))
10891 ((eq (car desc) :maxlevel)
10892 (setq fast-path-p t)
10893 (setq descre (concat "^\\*\\{1," (number-to-string
10894 (if org-odd-levels-only
10895 (1- (* 2 (cdr desc)))
10896 (cdr desc)))
10897 "\\}[ \t]")))
10898 (t (error "Bad refiling target description %s" desc)))
10899 (while (setq f (pop files))
10900 (with-current-buffer
10901 (if (bufferp f) f (org-get-agenda-file-buffer f))
10903 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10904 (progn
10905 (if (bufferp f) (setq f (buffer-file-name
10906 (buffer-base-buffer f))))
10907 (setq f (and f (expand-file-name f)))
10908 (if (eq org-refile-use-outline-path 'file)
10909 (push (list (file-name-nondirectory f) f nil nil) tgs))
10910 (save-excursion
10911 (save-restriction
10912 (widen)
10913 (goto-char (point-min))
10914 (while (re-search-forward descre nil t)
10915 (goto-char (setq pos0 (point-at-bol)))
10916 (catch 'next
10917 (when org-refile-target-verify-function
10918 (save-match-data
10919 (or (funcall org-refile-target-verify-function)
10920 (throw 'next t))))
10921 (when (and (looking-at org-complex-heading-regexp)
10922 (not (member (match-string 4) excluded-entries))
10923 (match-string 4))
10924 (setq level (org-reduced-level
10925 (- (match-end 1) (match-beginning 1)))
10926 txt (org-link-display-format (match-string 4))
10927 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10928 re (format org-complex-heading-regexp-format
10929 (regexp-quote (match-string 4))))
10930 (when org-refile-use-outline-path
10931 (setq txt (mapconcat
10932 'org-protect-slash
10933 (append
10934 (if (eq org-refile-use-outline-path
10935 'file)
10936 (list (file-name-nondirectory
10937 (buffer-file-name
10938 (buffer-base-buffer))))
10939 (if (eq org-refile-use-outline-path
10940 'full-file-path)
10941 (list (buffer-file-name
10942 (buffer-base-buffer)))))
10943 (org-get-outline-path fast-path-p
10944 level txt)
10945 (list txt))
10946 "/")))
10947 (push (list txt f re (org-refile-marker (point)))
10948 tgs)))
10949 (when (= (point) pos0)
10950 ;; verification function has not moved point
10951 (goto-char (point-at-eol))))))))
10952 (when org-refile-use-cache
10953 (org-refile-cache-put tgs (buffer-file-name) descre))
10954 (setq targets (append tgs targets))
10955 ))))
10956 (message "Getting targets...done")
10957 (nreverse targets)))
10959 (defun org-protect-slash (s)
10960 (while (string-match "/" s)
10961 (setq s (replace-match "\\" t t s)))
10964 (defvar org-olpa (make-vector 20 nil))
10966 (defun org-get-outline-path (&optional fastp level heading)
10967 "Return the outline path to the current entry, as a list.
10969 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10970 routine which makes outline path derivations for an entire file,
10971 avoiding backtracing. Refile target collection makes use of that."
10972 (if fastp
10973 (progn
10974 (if (> level 19)
10975 (error "Outline path failure, more than 19 levels"))
10976 (loop for i from level upto 19 do
10977 (aset org-olpa i nil))
10978 (prog1
10979 (delq nil (append org-olpa nil))
10980 (aset org-olpa level heading)))
10981 (let (rtn case-fold-search)
10982 (save-excursion
10983 (save-restriction
10984 (widen)
10985 (while (org-up-heading-safe)
10986 (when (looking-at org-complex-heading-regexp)
10987 (push (org-match-string-no-properties 4) rtn)))
10988 rtn)))))
10990 (defun org-format-outline-path (path &optional width prefix separator)
10991 "Format the outline path PATH for display.
10992 WIDTH is the maximum number of characters that is available.
10993 PREFIX is a prefix to be included in the returned string,
10994 such as the file name.
10995 SEPARATOR is inserted between the different parts of the path,
10996 the default is \"/\"."
10997 (setq width (or width 79))
10998 (if prefix (setq width (- width (length prefix))))
10999 (if (not path)
11000 (or prefix "")
11001 (let* ((nsteps (length path))
11002 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11003 (maxwidth (if (<= total-width width)
11004 10000 ;; everything fits
11005 ;; we need to shorten the level headings
11006 (/ (- width nsteps) nsteps)))
11007 (org-odd-levels-only nil)
11008 (n 0)
11009 (total (1+ (length prefix))))
11010 (setq maxwidth (max maxwidth 10))
11011 (concat prefix
11012 (if prefix (or separator "/"))
11013 (mapconcat
11014 (lambda (h)
11015 (setq n (1+ n))
11016 (if (and (= n nsteps) (< maxwidth 10000))
11017 (setq maxwidth (- total-width total)))
11018 (if (< (length h) maxwidth)
11019 (progn (setq total (+ total (length h) 1)) h)
11020 (setq h (substring h 0 (- maxwidth 2))
11021 total (+ total maxwidth 1))
11022 (if (string-match "[ \t]+\\'" h)
11023 (setq h (substring h 0 (match-beginning 0))))
11024 (setq h (concat h "..")))
11025 (org-add-props h nil 'face
11026 (nth (% (1- n) org-n-level-faces)
11027 org-level-faces))
11029 path (or separator "/"))))))
11031 (defun org-display-outline-path (&optional file current separator just-return-string)
11032 "Display the current outline path in the echo area.
11034 If FILE is non-nil, prepend the output with the file name.
11035 If CURRENT is non-nil, append the current heading to the output.
11036 SEPARATOR is passed through to `org-format-outline-path'. It separates
11037 the different parts of the path and defaults to \"/\".
11038 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11039 (interactive "P")
11040 (let* (case-fold-search
11041 message-log-max ; Don't populate the *Messages* buffer
11042 (bfn (buffer-file-name (buffer-base-buffer)))
11043 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11044 res)
11045 (if current (setq path (append path
11046 (save-excursion
11047 (org-back-to-heading t)
11048 (if (looking-at org-complex-heading-regexp)
11049 (list (match-string 4)))))))
11050 (setq res
11051 (org-format-outline-path
11052 path
11053 (1- (frame-width))
11054 (and file bfn (concat (file-name-nondirectory bfn) separator))
11055 separator))
11056 (if just-return-string
11057 (org-no-properties res)
11058 (message "%s" res))))
11060 (defvar org-refile-history nil
11061 "History for refiling operations.")
11063 (defvar org-after-refile-insert-hook nil
11064 "Hook run after `org-refile' has inserted its stuff at the new location.
11065 Note that this is still *before* the stuff will be removed from
11066 the *old* location.")
11068 (defvar org-capture-last-stored-marker)
11069 (defvar org-refile-keep nil
11070 "Non-nil means `org-refile' will copy instead of refile.")
11072 (defun org-copy ()
11073 "Like `org-refile', but copy."
11074 (interactive)
11075 (let ((org-refile-keep t))
11076 (funcall 'org-refile nil nil nil "Copy")))
11078 (defun org-refile (&optional goto default-buffer rfloc msg)
11079 "Move the entry or entries at point to another heading.
11080 The list of target headings is compiled using the information in
11081 `org-refile-targets', which see.
11083 At the target location, the entry is filed as a subitem of the target
11084 heading. Depending on `org-reverse-note-order', the new subitem will
11085 either be the first or the last subitem.
11087 If there is an active region, all entries in that region will be moved.
11088 However, the region must fulfill the requirement that the first heading
11089 is the first one sets the top-level of the moved text - at most siblings
11090 below it are allowed.
11092 With prefix arg GOTO, the command will only visit the target location
11093 and not actually move anything.
11095 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11096 go to the location where the last refiling operation has put the subtree.
11097 With a prefix argument of `2', refile to the running clock.
11099 RFLOC can be a refile location obtained in a different way.
11101 MSG is a string to replace \"Refile\" in the default prompt with
11102 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11104 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11106 If you are using target caching (see `org-refile-use-cache'),
11107 you have to clear the target cache in order to find new targets.
11108 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11109 prefix argument (`C-u C-u C-u C-c C-w')."
11111 (interactive "P")
11112 (if (member goto '(0 (64)))
11113 (org-refile-cache-clear)
11114 (let* ((actionmsg (or msg "Refile"))
11115 (cbuf (current-buffer))
11116 (regionp (org-region-active-p))
11117 (region-start (and regionp (region-beginning)))
11118 (region-end (and regionp (region-end)))
11119 (region-length (and regionp (- region-end region-start)))
11120 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11121 pos it nbuf file re level reversed)
11122 (setq last-command nil)
11123 (when regionp
11124 (goto-char region-start)
11125 (or (bolp) (goto-char (point-at-bol)))
11126 (setq region-start (point))
11127 (unless (or (org-kill-is-subtree-p
11128 (buffer-substring region-start region-end))
11129 (prog1 org-refile-active-region-within-subtree
11130 (org-toggle-heading)))
11131 (error "The region is not a (sequence of) subtree(s)")))
11132 (if (equal goto '(16))
11133 (org-refile-goto-last-stored)
11134 (when (or
11135 (and (equal goto 2)
11136 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11137 (prog1
11138 (setq it (list (or org-clock-heading "running clock")
11139 (buffer-file-name
11140 (marker-buffer org-clock-hd-marker))
11142 (marker-position org-clock-hd-marker)))
11143 (setq goto nil)))
11144 (setq it (or rfloc
11145 (let (heading-text)
11146 (save-excursion
11147 (unless goto
11148 (org-back-to-heading t)
11149 (setq heading-text
11150 (nth 4 (org-heading-components))))
11152 (org-refile-get-location
11153 (cond (goto "Goto")
11154 (regionp (concat actionmsg " region to"))
11155 (t (concat actionmsg " subtree \""
11156 heading-text "\" to")))
11157 default-buffer
11158 (and (not (equal '(4) goto))
11159 org-refile-allow-creating-parent-nodes)
11160 goto))))))
11161 (setq file (nth 1 it)
11162 re (nth 2 it)
11163 pos (nth 3 it))
11164 (if (and (not goto)
11166 (equal (buffer-file-name) file)
11167 (if regionp
11168 (and (>= pos region-start)
11169 (<= pos region-end))
11170 (and (>= pos (point))
11171 (< pos (save-excursion
11172 (org-end-of-subtree t t))))))
11173 (error "Cannot refile to position inside the tree or region"))
11175 (setq nbuf (or (find-buffer-visiting file)
11176 (find-file-noselect file)))
11177 (if goto
11178 (progn
11179 (org-pop-to-buffer-same-window nbuf)
11180 (goto-char pos)
11181 (org-show-context 'org-goto))
11182 (if regionp
11183 (progn
11184 (org-kill-new (buffer-substring region-start region-end))
11185 (org-save-markers-in-region region-start region-end))
11186 (org-copy-subtree 1 nil t))
11187 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11188 (find-file-noselect file)))
11189 (setq reversed (org-notes-order-reversed-p))
11190 (save-excursion
11191 (save-restriction
11192 (widen)
11193 (if pos
11194 (progn
11195 (goto-char pos)
11196 (looking-at org-outline-regexp)
11197 (setq level (org-get-valid-level (funcall outline-level) 1))
11198 (goto-char
11199 (if reversed
11200 (or (outline-next-heading) (point-max))
11201 (or (save-excursion (org-get-next-sibling))
11202 (org-end-of-subtree t t)
11203 (point-max)))))
11204 (setq level 1)
11205 (if (not reversed)
11206 (goto-char (point-max))
11207 (goto-char (point-min))
11208 (or (outline-next-heading) (goto-char (point-max)))))
11209 (if (not (bolp)) (newline))
11210 (org-paste-subtree level)
11211 (when org-log-refile
11212 (org-add-log-setup 'refile nil nil 'findpos
11213 org-log-refile)
11214 (unless (eq org-log-refile 'note)
11215 (save-excursion (org-add-log-note))))
11216 (and org-auto-align-tags
11217 (let ((org-loop-over-headlines-in-active-region nil))
11218 (org-set-tags nil t)))
11219 (with-demoted-errors
11220 (bookmark-set "org-refile-last-stored"))
11221 ;; If we are refiling for capture, make sure that the
11222 ;; last-capture pointers point here
11223 (when (org-bound-and-true-p org-refile-for-capture)
11224 (with-demoted-errors
11225 (bookmark-set "org-capture-last-stored-marker"))
11226 (move-marker org-capture-last-stored-marker (point)))
11227 (if (fboundp 'deactivate-mark) (deactivate-mark))
11228 (run-hooks 'org-after-refile-insert-hook))))
11229 (unless org-refile-keep
11230 (if regionp
11231 (delete-region (point) (+ (point) region-length))
11232 (org-cut-subtree)))
11233 (when (featurep 'org-inlinetask)
11234 (org-inlinetask-remove-END-maybe))
11235 (setq org-markers-to-move nil)
11236 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11238 (defun org-refile-goto-last-stored ()
11239 "Go to the location where the last refile was stored."
11240 (interactive)
11241 (bookmark-jump "org-refile-last-stored")
11242 (message "This is the location of the last refile"))
11244 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11245 no-exclude)
11246 "Prompt the user for a refile location, using PROMPT.
11247 PROMPT should not be suffixed with a colon and a space, because
11248 this function appends the default value from
11249 `org-refile-history' automatically, if that is not empty.
11250 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11251 this is used for the GOTO interface."
11252 (let ((org-refile-targets org-refile-targets)
11253 (org-refile-use-outline-path org-refile-use-outline-path)
11254 excluded-entries)
11255 (when (and (derived-mode-p 'org-mode)
11256 (not org-refile-use-cache)
11257 (not no-exclude))
11258 (org-map-tree
11259 (lambda()
11260 (setq excluded-entries
11261 (append excluded-entries (list (org-get-heading t t)))))))
11262 (setq org-refile-target-table
11263 (org-refile-get-targets default-buffer excluded-entries)))
11264 (unless org-refile-target-table
11265 (error "No refile targets"))
11266 (let* ((cbuf (current-buffer))
11267 (partial-completion-mode nil)
11268 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11269 (cfunc (if (and org-refile-use-outline-path
11270 org-outline-path-complete-in-steps)
11271 'org-olpath-completing-read
11272 'org-icompleting-read))
11273 (extra (if org-refile-use-outline-path "/" ""))
11274 (cbnex (concat (buffer-name) extra))
11275 (filename (and cfn (expand-file-name cfn)))
11276 (tbl (mapcar
11277 (lambda (x)
11278 (if (and (not (member org-refile-use-outline-path
11279 '(file full-file-path)))
11280 (not (equal filename (nth 1 x))))
11281 (cons (concat (car x) extra " ("
11282 (file-name-nondirectory (nth 1 x)) ")")
11283 (cdr x))
11284 (cons (concat (car x) extra) (cdr x))))
11285 org-refile-target-table))
11286 (completion-ignore-case t)
11287 cdef
11288 (prompt (concat prompt
11289 (or (and (car org-refile-history)
11290 (concat " (default " (car org-refile-history) ")"))
11291 (and (assoc cbnex tbl) (setq cdef cbnex)
11292 (concat " (default " cbnex ")"))) ": "))
11293 pa answ parent-target child parent old-hist)
11294 (setq old-hist org-refile-history)
11295 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11296 nil 'org-refile-history (or cdef (car org-refile-history))))
11297 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11298 (org-refile-check-position pa)
11299 (if pa
11300 (progn
11301 (when (or (not org-refile-history)
11302 (not (eq old-hist org-refile-history))
11303 (not (equal (car pa) (car org-refile-history))))
11304 (setq org-refile-history
11305 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11306 org-refile-history
11307 (cdr org-refile-history))))
11308 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11309 (pop org-refile-history)))
11311 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11312 (progn
11313 (setq parent (match-string 1 answ)
11314 child (match-string 2 answ))
11315 (setq parent-target (or (assoc parent tbl)
11316 (assoc (concat parent "/") tbl)))
11317 (when (and parent-target
11318 (or (eq new-nodes t)
11319 (and (eq new-nodes 'confirm)
11320 (y-or-n-p (format "Create new node \"%s\"? "
11321 child)))))
11322 (org-refile-new-child parent-target child)))
11323 (error "Invalid target location")))))
11325 (declare-function org-string-nw-p "org-macs" (s))
11326 (defun org-refile-check-position (refile-pointer)
11327 "Check if the refile pointer matches the headline to which it points."
11328 (let* ((file (nth 1 refile-pointer))
11329 (re (nth 2 refile-pointer))
11330 (pos (nth 3 refile-pointer))
11331 buffer)
11332 (if (and (not (markerp pos)) (not file))
11333 (error "Please save the buffer to a file before refiling")
11334 (when (org-string-nw-p re)
11335 (setq buffer (if (markerp pos)
11336 (marker-buffer pos)
11337 (or (find-buffer-visiting file)
11338 (find-file-noselect file))))
11339 (with-current-buffer buffer
11340 (save-excursion
11341 (save-restriction
11342 (widen)
11343 (goto-char pos)
11344 (beginning-of-line 1)
11345 (unless (org-looking-at-p re)
11346 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11348 (defun org-refile-new-child (parent-target child)
11349 "Use refile target PARENT-TARGET to add new CHILD below it."
11350 (unless parent-target
11351 (error "Cannot find parent for new node"))
11352 (let ((file (nth 1 parent-target))
11353 (pos (nth 3 parent-target))
11354 level)
11355 (with-current-buffer (or (find-buffer-visiting file)
11356 (find-file-noselect file))
11357 (save-excursion
11358 (save-restriction
11359 (widen)
11360 (if pos
11361 (goto-char pos)
11362 (goto-char (point-max))
11363 (if (not (bolp)) (newline)))
11364 (when (looking-at org-outline-regexp)
11365 (setq level (funcall outline-level))
11366 (org-end-of-subtree t t))
11367 (org-back-over-empty-lines)
11368 (insert "\n" (make-string
11369 (if pos (org-get-valid-level level 1) 1) ?*)
11370 " " child "\n")
11371 (beginning-of-line 0)
11372 (list (concat (car parent-target) "/" child) file "" (point)))))))
11374 (defun org-olpath-completing-read (prompt collection &rest args)
11375 "Read an outline path like a file name."
11376 (let ((thetable collection)
11377 (org-completion-use-ido nil) ; does not work with ido.
11378 (org-completion-use-iswitchb nil)) ; or iswitchb
11379 (apply
11380 'org-icompleting-read prompt
11381 (lambda (string predicate &optional flag)
11382 (let (rtn r f (l (length string)))
11383 (cond
11384 ((eq flag nil)
11385 ;; try completion
11386 (try-completion string thetable))
11387 ((eq flag t)
11388 ;; all-completions
11389 (setq rtn (all-completions string thetable predicate))
11390 (mapcar
11391 (lambda (x)
11392 (setq r (substring x l))
11393 (if (string-match " ([^)]*)$" x)
11394 (setq f (match-string 0 x))
11395 (setq f ""))
11396 (if (string-match "/" r)
11397 (concat string (substring r 0 (match-end 0)) f)
11399 rtn))
11400 ((eq flag 'lambda)
11401 ;; exact match?
11402 (assoc string thetable)))))
11403 args)))
11405 ;;;; Dynamic blocks
11407 (defun org-find-dblock (name)
11408 "Find the first dynamic block with name NAME in the buffer.
11409 If not found, stay at current position and return nil."
11410 (let ((case-fold-search t) pos)
11411 (save-excursion
11412 (goto-char (point-min))
11413 (setq pos (and (re-search-forward
11414 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11415 (match-beginning 0))))
11416 (if pos (goto-char pos))
11417 pos))
11419 (defconst org-dblock-start-re
11420 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11421 "Matches the start line of a dynamic block, with parameters.")
11423 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11424 "Matches the end of a dynamic block.")
11426 (defun org-create-dblock (plist)
11427 "Create a dynamic block section, with parameters taken from PLIST.
11428 PLIST must contain a :name entry which is used as name of the block."
11429 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11430 (end-of-line 1)
11431 (newline))
11432 (let ((col (current-column))
11433 (name (plist-get plist :name)))
11434 (insert "#+BEGIN: " name)
11435 (while plist
11436 (if (eq (car plist) :name)
11437 (setq plist (cddr plist))
11438 (insert " " (prin1-to-string (pop plist)))))
11439 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11440 (beginning-of-line -2)))
11442 (defun org-prepare-dblock ()
11443 "Prepare dynamic block for refresh.
11444 This empties the block, puts the cursor at the insert position and returns
11445 the property list including an extra property :name with the block name."
11446 (unless (looking-at org-dblock-start-re)
11447 (error "Not at a dynamic block"))
11448 (let* ((begdel (1+ (match-end 0)))
11449 (name (org-no-properties (match-string 1)))
11450 (params (append (list :name name)
11451 (read (concat "(" (match-string 3) ")")))))
11452 (save-excursion
11453 (beginning-of-line 1)
11454 (skip-chars-forward " \t")
11455 (setq params (plist-put params :indentation-column (current-column))))
11456 (unless (re-search-forward org-dblock-end-re nil t)
11457 (error "Dynamic block not terminated"))
11458 (setq params
11459 (append params
11460 (list :content (buffer-substring
11461 begdel (match-beginning 0)))))
11462 (delete-region begdel (match-beginning 0))
11463 (goto-char begdel)
11464 (open-line 1)
11465 params))
11467 (defun org-map-dblocks (&optional command)
11468 "Apply COMMAND to all dynamic blocks in the current buffer.
11469 If COMMAND is not given, use `org-update-dblock'."
11470 (let ((cmd (or command 'org-update-dblock)))
11471 (save-excursion
11472 (goto-char (point-min))
11473 (while (re-search-forward org-dblock-start-re nil t)
11474 (goto-char (match-beginning 0))
11475 (save-excursion
11476 (condition-case nil
11477 (funcall cmd)
11478 (error (message "Error during update of dynamic block"))))
11479 (unless (re-search-forward org-dblock-end-re nil t)
11480 (error "Dynamic block not terminated"))))))
11482 (defun org-dblock-update (&optional arg)
11483 "User command for updating dynamic blocks.
11484 Update the dynamic block at point. With prefix ARG, update all dynamic
11485 blocks in the buffer."
11486 (interactive "P")
11487 (if arg
11488 (org-update-all-dblocks)
11489 (or (looking-at org-dblock-start-re)
11490 (org-beginning-of-dblock))
11491 (org-update-dblock)))
11493 (defun org-update-dblock ()
11494 "Update the dynamic block at point.
11495 This means to empty the block, parse for parameters and then call
11496 the correct writing function."
11497 (interactive)
11498 (save-window-excursion
11499 (let* ((pos (point))
11500 (line (org-current-line))
11501 (params (org-prepare-dblock))
11502 (name (plist-get params :name))
11503 (indent (plist-get params :indentation-column))
11504 (cmd (intern (concat "org-dblock-write:" name))))
11505 (message "Updating dynamic block `%s' at line %d..." name line)
11506 (funcall cmd params)
11507 (message "Updating dynamic block `%s' at line %d...done" name line)
11508 (goto-char pos)
11509 (when (and indent (> indent 0))
11510 (setq indent (make-string indent ?\ ))
11511 (save-excursion
11512 (org-beginning-of-dblock)
11513 (forward-line 1)
11514 (while (not (looking-at org-dblock-end-re))
11515 (insert indent)
11516 (beginning-of-line 2))
11517 (when (looking-at org-dblock-end-re)
11518 (and (looking-at "[ \t]+")
11519 (replace-match ""))
11520 (insert indent)))))))
11522 (defun org-beginning-of-dblock ()
11523 "Find the beginning of the dynamic block at point.
11524 Error if there is no such block at point."
11525 (let ((pos (point))
11526 beg)
11527 (end-of-line 1)
11528 (if (and (re-search-backward org-dblock-start-re nil t)
11529 (setq beg (match-beginning 0))
11530 (re-search-forward org-dblock-end-re nil t)
11531 (> (match-end 0) pos))
11532 (goto-char beg)
11533 (goto-char pos)
11534 (error "Not in a dynamic block"))))
11536 (defun org-update-all-dblocks ()
11537 "Update all dynamic blocks in the buffer.
11538 This function can be used in a hook."
11539 (interactive)
11540 (when (derived-mode-p 'org-mode)
11541 (org-map-dblocks 'org-update-dblock)))
11544 ;;;; Completion
11546 (defun org-get-export-keywords ()
11547 "Return a list of all currently understood export keywords.
11548 Export keywords include options, block names, attributes and
11549 keywords relative to each registered export back-end."
11550 (delq nil
11551 (let (keywords)
11552 (mapc
11553 (lambda (back-end)
11554 (let ((props (cdr back-end)))
11555 ;; Back-end name (for keywords, like #+LATEX:)
11556 (push (upcase (symbol-name (car back-end))) keywords)
11557 ;; Back-end options.
11558 (mapc (lambda (option) (push (cadr option) keywords))
11559 (plist-get (cdr back-end) :options-alist))))
11560 (org-bound-and-true-p org-export-registered-backends))
11561 keywords)))
11563 (defconst org-options-keywords
11564 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11565 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11566 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11567 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11568 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11570 (defcustom org-structure-template-alist
11571 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11572 "<src lang=\"?\">\n\n</src>")
11573 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11574 "<example>\n?\n</example>")
11575 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11576 "<quote>\n?\n</quote>")
11577 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11578 "<verse>\n?\n</verse>")
11579 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11580 "<verbatim>\n?\n</verbatim>")
11581 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11582 "<center>\n?\n</center>")
11583 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11584 "<literal style=\"latex\">\n?\n</literal>")
11585 ("L" "#+LaTeX: "
11586 "<literal style=\"latex\">?</literal>")
11587 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11588 "<literal style=\"html\">\n?\n</literal>")
11589 ("H" "#+HTML: "
11590 "<literal style=\"html\">?</literal>")
11591 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11592 ("A" "#+ASCII: ")
11593 ("i" "#+INDEX: ?"
11594 "#+INDEX: ?")
11595 ("I" "#+INCLUDE: %file ?"
11596 "<include file=%file markup=\"?\">"))
11597 "Structure completion elements.
11598 This is a list of abbreviation keys and values. The value gets inserted
11599 if you type `<' followed by the key and then press the completion key,
11600 usually `M-TAB'. %file will be replaced by a file name after prompting
11601 for the file using completion. The cursor will be placed at the position
11602 of the `?` in the template.
11603 There are two templates for each key, the first uses the original Org syntax,
11604 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11605 the default when the /org-mtags.el/ module has been loaded. See also the
11606 variable `org-mtags-prefer-muse-templates'."
11607 :group 'org-completion
11608 :type '(repeat
11609 (string :tag "Key")
11610 (string :tag "Template")
11611 (string :tag "Muse Template")))
11613 (defun org-try-structure-completion ()
11614 "Try to complete a structure template before point.
11615 This looks for strings like \"<e\" on an otherwise empty line and
11616 expands them."
11617 (let ((l (buffer-substring (point-at-bol) (point)))
11619 (when (and (looking-at "[ \t]*$")
11620 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11621 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11622 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11623 (match-beginning 1)) a)
11624 t)))
11626 (defun org-complete-expand-structure-template (start cell)
11627 "Expand a structure template."
11628 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11629 (rpl (nth (if musep 2 1) cell))
11630 (ind ""))
11631 (delete-region start (point))
11632 (when (string-match "\\`#\\+" rpl)
11633 (cond
11634 ((bolp))
11635 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11636 (setq ind (buffer-substring (point-at-bol) (point))))
11637 (t (newline))))
11638 (setq start (point))
11639 (if (string-match "%file" rpl)
11640 (setq rpl (replace-match
11641 (concat
11642 "\""
11643 (save-match-data
11644 (abbreviate-file-name (read-file-name "Include file: ")))
11645 "\"")
11646 t t rpl)))
11647 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11648 (concat "\n" ind)))
11649 (insert rpl)
11650 (if (re-search-backward "\\?" start t) (delete-char 1))))
11652 ;;;; TODO, DEADLINE, Comments
11654 (defun org-toggle-comment ()
11655 "Change the COMMENT state of an entry."
11656 (interactive)
11657 (save-excursion
11658 (org-back-to-heading)
11659 (let (case-fold-search)
11660 (cond
11661 ((looking-at (format org-heading-keyword-regexp-format
11662 org-comment-string))
11663 (goto-char (match-end 1))
11664 (looking-at (concat " +" org-comment-string))
11665 (replace-match "" t t)
11666 (when (eolp) (insert " ")))
11667 ((looking-at org-outline-regexp)
11668 (goto-char (match-end 0))
11669 (insert org-comment-string " "))))))
11671 (defvar org-last-todo-state-is-todo nil
11672 "This is non-nil when the last TODO state change led to a TODO state.
11673 If the last change removed the TODO tag or switched to DONE, then
11674 this is nil.")
11676 (defvar org-setting-tags nil) ; dynamically skipped
11678 (defvar org-todo-setup-filter-hook nil
11679 "Hook for functions that pre-filter todo specs.
11680 Each function takes a todo spec and returns either nil or the spec
11681 transformed into canonical form." )
11683 (defvar org-todo-get-default-hook nil
11684 "Hook for functions that get a default item for todo.
11685 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11686 nil or a string to be used for the todo mark." )
11688 (defvar org-agenda-headline-snapshot-before-repeat)
11690 (defun org-current-effective-time ()
11691 "Return current time adjusted for `org-extend-today-until' variable."
11692 (let* ((ct (org-current-time))
11693 (dct (decode-time ct))
11694 (ct1
11695 (cond
11696 (org-use-last-clock-out-time-as-effective-time
11697 (or (org-clock-get-last-clock-out-time) ct))
11698 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11699 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11700 (t ct))))
11701 ct1))
11703 (defun org-todo-yesterday (&optional arg)
11704 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11705 (interactive "P")
11706 (if (eq major-mode 'org-agenda-mode)
11707 (apply 'org-agenda-todo-yesterday arg)
11708 (let* ((hour (third (decode-time
11709 (org-current-time))))
11710 (org-extend-today-until (1+ hour)))
11711 (org-todo arg))))
11713 (defvar org-block-entry-blocking ""
11714 "First entry preventing the TODO state change.")
11716 (defun org-todo (&optional arg)
11717 "Change the TODO state of an item.
11718 The state of an item is given by a keyword at the start of the heading,
11719 like
11720 *** TODO Write paper
11721 *** DONE Call mom
11723 The different keywords are specified in the variable `org-todo-keywords'.
11724 By default the available states are \"TODO\" and \"DONE\".
11725 So for this example: when the item starts with TODO, it is changed to DONE.
11726 When it starts with DONE, the DONE is removed. And when neither TODO nor
11727 DONE are present, add TODO at the beginning of the heading.
11729 With \\[universal-argument] prefix arg, use completion to determine the new \
11730 state.
11731 With numeric prefix arg, switch to that state.
11732 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11733 keywords (nextset).
11734 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11735 With a numeric prefix arg of 0, inhibit note taking for the change.
11737 For calling through lisp, arg is also interpreted in the following way:
11738 'none -> empty state
11739 \"\"(empty string) -> switch to empty state
11740 'done -> switch to DONE
11741 'nextset -> switch to the next set of keywords
11742 'previousset -> switch to the previous set of keywords
11743 \"WAITING\" -> switch to the specified keyword, but only if it
11744 really is a member of `org-todo-keywords'."
11745 (interactive "P")
11746 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11747 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11748 'region-start-level 'region))
11749 org-loop-over-headlines-in-active-region)
11750 (org-map-entries
11751 `(org-todo ,arg)
11752 org-loop-over-headlines-in-active-region
11753 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11754 (if (equal arg '(16)) (setq arg 'nextset))
11755 (let ((org-blocker-hook org-blocker-hook)
11756 commentp
11757 case-fold-search)
11758 (when (equal arg '(64))
11759 (setq arg nil org-blocker-hook nil))
11760 (when (and org-blocker-hook
11761 (or org-inhibit-blocking
11762 (org-entry-get nil "NOBLOCKING")))
11763 (setq org-blocker-hook nil))
11764 (save-excursion
11765 (catch 'exit
11766 (org-back-to-heading t)
11767 (when (looking-at (concat "^\\*+ " org-comment-string))
11768 (org-toggle-comment)
11769 (setq commentp t))
11770 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11771 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11772 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11773 (let* ((match-data (match-data))
11774 (startpos (point-at-bol))
11775 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11776 (org-log-done org-log-done)
11777 (org-log-repeat org-log-repeat)
11778 (org-todo-log-states org-todo-log-states)
11779 (org-inhibit-logging
11780 (if (equal arg 0)
11781 (progn (setq arg nil) 'note) org-inhibit-logging))
11782 (this (match-string 1))
11783 (hl-pos (match-beginning 0))
11784 (head (org-get-todo-sequence-head this))
11785 (ass (assoc head org-todo-kwd-alist))
11786 (interpret (nth 1 ass))
11787 (done-word (nth 3 ass))
11788 (final-done-word (nth 4 ass))
11789 (org-last-state (or this ""))
11790 (completion-ignore-case t)
11791 (member (member this org-todo-keywords-1))
11792 (tail (cdr member))
11793 (org-state (cond
11794 ((and org-todo-key-trigger
11795 (or (and (equal arg '(4))
11796 (eq org-use-fast-todo-selection 'prefix))
11797 (and (not arg) org-use-fast-todo-selection
11798 (not (eq org-use-fast-todo-selection
11799 'prefix)))))
11800 ;; Use fast selection
11801 (org-fast-todo-selection))
11802 ((and (equal arg '(4))
11803 (or (not org-use-fast-todo-selection)
11804 (not org-todo-key-trigger)))
11805 ;; Read a state with completion
11806 (org-icompleting-read
11807 "State: " (mapcar (lambda(x) (list x))
11808 org-todo-keywords-1)
11809 nil t))
11810 ((eq arg 'right)
11811 (if this
11812 (if tail (car tail) nil)
11813 (car org-todo-keywords-1)))
11814 ((eq arg 'left)
11815 (if (equal member org-todo-keywords-1)
11817 (if this
11818 (nth (- (length org-todo-keywords-1)
11819 (length tail) 2)
11820 org-todo-keywords-1)
11821 (org-last org-todo-keywords-1))))
11822 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11823 (setq arg nil))) ; hack to fall back to cycling
11824 (arg
11825 ;; user or caller requests a specific state
11826 (cond
11827 ((equal arg "") nil)
11828 ((eq arg 'none) nil)
11829 ((eq arg 'done) (or done-word (car org-done-keywords)))
11830 ((eq arg 'nextset)
11831 (or (car (cdr (member head org-todo-heads)))
11832 (car org-todo-heads)))
11833 ((eq arg 'previousset)
11834 (let ((org-todo-heads (reverse org-todo-heads)))
11835 (or (car (cdr (member head org-todo-heads)))
11836 (car org-todo-heads))))
11837 ((car (member arg org-todo-keywords-1)))
11838 ((stringp arg)
11839 (error "State `%s' not valid in this file" arg))
11840 ((nth (1- (prefix-numeric-value arg))
11841 org-todo-keywords-1))))
11842 ((null member) (or head (car org-todo-keywords-1)))
11843 ((equal this final-done-word) nil) ;; -> make empty
11844 ((null tail) nil) ;; -> first entry
11845 ((memq interpret '(type priority))
11846 (if (eq this-command last-command)
11847 (car tail)
11848 (if (> (length tail) 0)
11849 (or done-word (car org-done-keywords))
11850 nil)))
11852 (car tail))))
11853 (org-state (or
11854 (run-hook-with-args-until-success
11855 'org-todo-get-default-hook org-state org-last-state)
11856 org-state))
11857 (next (if org-state (concat " " org-state " ") " "))
11858 (change-plist (list :type 'todo-state-change :from this :to org-state
11859 :position startpos))
11860 dolog now-done-p)
11861 (when org-blocker-hook
11862 (setq org-last-todo-state-is-todo
11863 (not (member this org-done-keywords)))
11864 (unless (save-excursion
11865 (save-match-data
11866 (org-with-wide-buffer
11867 (run-hook-with-args-until-failure
11868 'org-blocker-hook change-plist))))
11869 (if (org-called-interactively-p 'interactive)
11870 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11871 this org-state org-block-entry-blocking)
11872 ;; fail silently
11873 (message "TODO state change from %s to %s blocked (by \"%s\")"
11874 this org-state org-block-entry-blocking)
11875 (throw 'exit nil))))
11876 (store-match-data match-data)
11877 (replace-match next t t)
11878 (unless (pos-visible-in-window-p hl-pos)
11879 (message "TODO state changed to %s" (org-trim next)))
11880 (unless head
11881 (setq head (org-get-todo-sequence-head org-state)
11882 ass (assoc head org-todo-kwd-alist)
11883 interpret (nth 1 ass)
11884 done-word (nth 3 ass)
11885 final-done-word (nth 4 ass)))
11886 (when (memq arg '(nextset previousset))
11887 (message "Keyword-Set %d/%d: %s"
11888 (- (length org-todo-sets) -1
11889 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11890 (length org-todo-sets)
11891 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11892 (setq org-last-todo-state-is-todo
11893 (not (member org-state org-done-keywords)))
11894 (setq now-done-p (and (member org-state org-done-keywords)
11895 (not (member this org-done-keywords))))
11896 (and logging (org-local-logging logging))
11897 (when (and (or org-todo-log-states org-log-done)
11898 (not (eq org-inhibit-logging t))
11899 (not (memq arg '(nextset previousset))))
11900 ;; we need to look at recording a time and note
11901 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11902 (nth 2 (assoc this org-todo-log-states))))
11903 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11904 (setq dolog 'time))
11905 (when (and org-state
11906 (member org-state org-not-done-keywords)
11907 (not (member this org-not-done-keywords)))
11908 ;; This is now a todo state and was not one before
11909 ;; If there was a CLOSED time stamp, get rid of it.
11910 (org-add-planning-info nil nil 'closed))
11911 (when (and now-done-p org-log-done)
11912 ;; It is now done, and it was not done before
11913 (org-add-planning-info 'closed (org-current-effective-time))
11914 (if (and (not dolog) (eq 'note org-log-done))
11915 (org-add-log-setup 'done org-state this 'findpos 'note)))
11916 (when (and org-state dolog)
11917 ;; This is a non-nil state, and we need to log it
11918 (org-add-log-setup 'state org-state this 'findpos dolog)))
11919 ;; Fixup tag positioning
11920 (org-todo-trigger-tag-changes org-state)
11921 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11922 (when org-provide-todo-statistics
11923 (org-update-parent-todo-statistics))
11924 (run-hooks 'org-after-todo-state-change-hook)
11925 (if (and arg (not (member org-state org-done-keywords)))
11926 (setq head (org-get-todo-sequence-head org-state)))
11927 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11928 ;; Do we need to trigger a repeat?
11929 (when now-done-p
11930 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11931 ;; This is for the agenda, take a snapshot of the headline.
11932 (save-match-data
11933 (setq org-agenda-headline-snapshot-before-repeat
11934 (org-get-heading))))
11935 (org-auto-repeat-maybe org-state))
11936 ;; Fixup cursor location if close to the keyword
11937 (if (and (outline-on-heading-p)
11938 (not (bolp))
11939 (save-excursion (beginning-of-line 1)
11940 (looking-at org-todo-line-regexp))
11941 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11942 (progn
11943 (goto-char (or (match-end 2) (match-end 1)))
11944 (and (looking-at " ") (just-one-space))))
11945 (when org-trigger-hook
11946 (save-excursion
11947 (run-hook-with-args 'org-trigger-hook change-plist)))
11948 (when commentp (org-toggle-comment))))))))
11950 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11951 "Block turning an entry into a TODO, using the hierarchy.
11952 This checks whether the current task should be blocked from state
11953 changes. Such blocking occurs when:
11955 1. The task has children which are not all in a completed state.
11957 2. A task has a parent with the property :ORDERED:, and there
11958 are siblings prior to the current task with incomplete
11959 status.
11961 3. The parent of the task is blocked because it has siblings that should
11962 be done first, or is child of a block grandparent TODO entry."
11964 (if (not org-enforce-todo-dependencies)
11965 t ; if locally turned off don't block
11966 (catch 'dont-block
11967 ;; If this is not a todo state change, or if this entry is already DONE,
11968 ;; do not block
11969 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11970 (member (plist-get change-plist :from)
11971 (cons 'done org-done-keywords))
11972 (member (plist-get change-plist :to)
11973 (cons 'todo org-not-done-keywords))
11974 (not (plist-get change-plist :to)))
11975 (throw 'dont-block t))
11976 ;; If this task has children, and any are undone, it's blocked
11977 (save-excursion
11978 (org-back-to-heading t)
11979 (let ((this-level (funcall outline-level)))
11980 (outline-next-heading)
11981 (let ((child-level (funcall outline-level)))
11982 (while (and (not (eobp))
11983 (> child-level this-level))
11984 ;; this todo has children, check whether they are all
11985 ;; completed
11986 (if (and (not (org-entry-is-done-p))
11987 (org-entry-is-todo-p))
11988 (progn (setq org-block-entry-blocking (org-get-heading))
11989 (throw 'dont-block nil)))
11990 (outline-next-heading)
11991 (setq child-level (funcall outline-level))))))
11992 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11993 ;; any previous siblings are undone, it's blocked
11994 (save-excursion
11995 (org-back-to-heading t)
11996 (let* ((pos (point))
11997 (parent-pos (and (org-up-heading-safe) (point))))
11998 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11999 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12000 (forward-line 1)
12001 (re-search-forward org-not-done-heading-regexp pos t))
12002 (setq org-block-entry-blocking (match-string 0))
12003 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12004 ;; Search further up the hierarchy, to see if an ancestor is blocked
12005 (while t
12006 (goto-char parent-pos)
12007 (if (not (looking-at org-not-done-heading-regexp))
12008 (throw 'dont-block t)) ; do not block, parent is not a TODO
12009 (setq pos (point))
12010 (setq parent-pos (and (org-up-heading-safe) (point)))
12011 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12012 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12013 (forward-line 1)
12014 (re-search-forward org-not-done-heading-regexp pos t)
12015 (setq org-block-entry-blocking (org-get-heading)))
12016 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12018 (defcustom org-track-ordered-property-with-tag nil
12019 "Should the ORDERED property also be shown as a tag?
12020 The ORDERED property decides if an entry should require subtasks to be
12021 completed in sequence. Since a property is not very visible, setting
12022 this option means that toggling the ORDERED property with the command
12023 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12024 not relevant for the behavior, but it makes things more visible.
12026 Note that toggling the tag with tags commands will not change the property
12027 and therefore not influence behavior!
12029 This can be t, meaning the tag ORDERED should be used, It can also be a
12030 string to select a different tag for this task."
12031 :group 'org-todo
12032 :type '(choice
12033 (const :tag "No tracking" nil)
12034 (const :tag "Track with ORDERED tag" t)
12035 (string :tag "Use other tag")))
12037 (defun org-toggle-ordered-property ()
12038 "Toggle the ORDERED property of the current entry.
12039 For better visibility, you can track the value of this property with a tag.
12040 See variable `org-track-ordered-property-with-tag'."
12041 (interactive)
12042 (let* ((t1 org-track-ordered-property-with-tag)
12043 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12044 (save-excursion
12045 (org-back-to-heading)
12046 (if (org-entry-get nil "ORDERED")
12047 (progn
12048 (org-delete-property "ORDERED")
12049 (and tag (org-toggle-tag tag 'off))
12050 (message "Subtasks can be completed in arbitrary order"))
12051 (org-entry-put nil "ORDERED" "t")
12052 (and tag (org-toggle-tag tag 'on))
12053 (message "Subtasks must be completed in sequence")))))
12055 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12056 (defun org-block-todo-from-checkboxes (change-plist)
12057 "Block turning an entry into a TODO, using checkboxes.
12058 This checks whether the current task should be blocked from state
12059 changes because there are unchecked boxes in this entry."
12060 (if (not org-enforce-todo-checkbox-dependencies)
12061 t ; if locally turned off don't block
12062 (catch 'dont-block
12063 ;; If this is not a todo state change, or if this entry is already DONE,
12064 ;; do not block
12065 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12066 (member (plist-get change-plist :from)
12067 (cons 'done org-done-keywords))
12068 (member (plist-get change-plist :to)
12069 (cons 'todo org-not-done-keywords))
12070 (not (plist-get change-plist :to)))
12071 (throw 'dont-block t))
12072 ;; If this task has checkboxes that are not checked, it's blocked
12073 (save-excursion
12074 (org-back-to-heading t)
12075 (let ((beg (point)) end)
12076 (outline-next-heading)
12077 (setq end (point))
12078 (goto-char beg)
12079 (if (org-list-search-forward
12080 (concat (org-item-beginning-re)
12081 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12082 "\\[[- ]\\]")
12083 end t)
12084 (progn
12085 (if (boundp 'org-blocked-by-checkboxes)
12086 (setq org-blocked-by-checkboxes t))
12087 (throw 'dont-block nil)))))
12088 t))) ; do not block
12090 (defun org-entry-blocked-p ()
12091 "Is the current entry blocked?"
12092 (org-with-buffer-modified-unmodified
12093 (if (org-entry-get nil "NOBLOCKING")
12094 nil ;; Never block this entry
12095 (not
12096 (run-hook-with-args-until-failure
12097 'org-blocker-hook
12098 (list :type 'todo-state-change
12099 :position (point)
12100 :from 'todo
12101 :to 'done))))))
12103 (defun org-update-statistics-cookies (all)
12104 "Update the statistics cookie, either from TODO or from checkboxes.
12105 This should be called with the cursor in a line with a statistics cookie."
12106 (interactive "P")
12107 (if all
12108 (progn
12109 (org-update-checkbox-count 'all)
12110 (org-map-entries 'org-update-parent-todo-statistics))
12111 (if (not (org-at-heading-p))
12112 (org-update-checkbox-count)
12113 (let ((pos (point-marker))
12114 end l1 l2)
12115 (ignore-errors (org-back-to-heading t))
12116 (if (not (org-at-heading-p))
12117 (org-update-checkbox-count)
12118 (setq l1 (org-outline-level))
12119 (setq end (save-excursion
12120 (outline-next-heading)
12121 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12122 (point)))
12123 (if (and (save-excursion
12124 (re-search-forward
12125 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12126 (not (save-excursion (re-search-forward
12127 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12128 (org-update-checkbox-count)
12129 (if (and l2 (> l2 l1))
12130 (progn
12131 (goto-char end)
12132 (org-update-parent-todo-statistics))
12133 (goto-char pos)
12134 (beginning-of-line 1)
12135 (while (re-search-forward
12136 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12137 (point-at-eol) t)
12138 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12139 (goto-char pos)
12140 (move-marker pos nil)))))
12142 (defvar org-entry-property-inherited-from) ;; defined below
12143 (defun org-update-parent-todo-statistics ()
12144 "Update any statistics cookie in the parent of the current headline.
12145 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12146 the entire subtree and this will travel up the hierarchy and update
12147 statistics everywhere."
12148 (let* ((prop (save-excursion (org-up-heading-safe)
12149 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12150 (recursive (or (not org-hierarchical-todo-statistics)
12151 (and prop (string-match "\\<recursive\\>" prop))))
12152 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12154 (first t)
12155 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12156 level ltoggle l1 new ndel
12157 (cnt-all 0) (cnt-done 0) is-percent kwd
12158 checkbox-beg ov ovs ove cookie-present)
12159 (catch 'exit
12160 (save-excursion
12161 (beginning-of-line 1)
12162 (setq ltoggle (funcall outline-level))
12163 ;; Three situations are to consider:
12165 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12166 ;; to the top-level ancestor on the headline;
12168 ;; 2. If parent has "recursive" property, repeat up to the
12169 ;; headline setting that property, taking inheritance into
12170 ;; account;
12172 ;; 3. Else, move up to direct parent and proceed only once.
12173 (while (and (setq level (org-up-heading-safe))
12174 (or recursive first)
12175 (>= (point) lim))
12176 (setq first nil cookie-present nil)
12177 (unless (and level
12178 (not (string-match
12179 "\\<checkbox\\>"
12180 (downcase (or (org-entry-get nil "COOKIE_DATA")
12181 "")))))
12182 (throw 'exit nil))
12183 (while (re-search-forward box-re (point-at-eol) t)
12184 (setq cnt-all 0 cnt-done 0 cookie-present t)
12185 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12186 (save-match-data
12187 (unless (outline-next-heading) (throw 'exit nil))
12188 (while (and (looking-at org-complex-heading-regexp)
12189 (> (setq l1 (length (match-string 1))) level))
12190 (setq kwd (and (or recursive (= l1 ltoggle))
12191 (match-string 2)))
12192 (if (or (eq org-provide-todo-statistics 'all-headlines)
12193 (and (listp org-provide-todo-statistics)
12194 (or (member kwd org-provide-todo-statistics)
12195 (member kwd org-done-keywords))))
12196 (setq cnt-all (1+ cnt-all))
12197 (if (eq org-provide-todo-statistics t)
12198 (and kwd (setq cnt-all (1+ cnt-all)))))
12199 (and (member kwd org-done-keywords)
12200 (setq cnt-done (1+ cnt-done)))
12201 (outline-next-heading)))
12202 (setq new
12203 (if is-percent
12204 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12205 (format "[%d/%d]" cnt-done cnt-all))
12206 ndel (- (match-end 0) checkbox-beg))
12207 ;; handle overlays when updating cookie from column view
12208 (when (setq ov (car (overlays-at checkbox-beg)))
12209 (setq ovs (overlay-start ov) ove (overlay-end ov))
12210 (delete-overlay ov))
12211 (goto-char checkbox-beg)
12212 (insert new)
12213 (delete-region (point) (+ (point) ndel))
12214 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12215 (when ov (move-overlay ov ovs ove)))
12216 (when cookie-present
12217 (run-hook-with-args 'org-after-todo-statistics-hook
12218 cnt-done (- cnt-all cnt-done))))))
12219 (run-hooks 'org-todo-statistics-hook)))
12221 (defvar org-after-todo-statistics-hook nil
12222 "Hook that is called after a TODO statistics cookie has been updated.
12223 Each function is called with two arguments: the number of not-done entries
12224 and the number of done entries.
12226 For example, the following function, when added to this hook, will switch
12227 an entry to DONE when all children are done, and back to TODO when new
12228 entries are set to a TODO status. Note that this hook is only called
12229 when there is a statistics cookie in the headline!
12231 (defun org-summary-todo (n-done n-not-done)
12232 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12233 (let (org-log-done org-log-states) ; turn off logging
12234 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12237 (defvar org-todo-statistics-hook nil
12238 "Hook that is run whenever Org thinks TODO statistics should be updated.
12239 This hook runs even if there is no statistics cookie present, in which case
12240 `org-after-todo-statistics-hook' would not run.")
12242 (defun org-todo-trigger-tag-changes (state)
12243 "Apply the changes defined in `org-todo-state-tags-triggers'."
12244 (let ((l org-todo-state-tags-triggers)
12245 changes)
12246 (when (or (not state) (equal state ""))
12247 (setq changes (append changes (cdr (assoc "" l)))))
12248 (when (and (stringp state) (> (length state) 0))
12249 (setq changes (append changes (cdr (assoc state l)))))
12250 (when (member state org-not-done-keywords)
12251 (setq changes (append changes (cdr (assoc 'todo l)))))
12252 (when (member state org-done-keywords)
12253 (setq changes (append changes (cdr (assoc 'done l)))))
12254 (dolist (c changes)
12255 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12257 (defun org-local-logging (value)
12258 "Get logging settings from a property VALUE."
12259 (let* (words w a)
12260 ;; directly set the variables, they are already local.
12261 (setq org-log-done nil
12262 org-log-repeat nil
12263 org-todo-log-states nil)
12264 (setq words (org-split-string value))
12265 (while (setq w (pop words))
12266 (cond
12267 ((setq a (assoc w org-startup-options))
12268 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12269 (set (nth 1 a) (nth 2 a))))
12270 ((setq a (org-extract-log-state-settings w))
12271 (and (member (car a) org-todo-keywords-1)
12272 (push a org-todo-log-states)))))))
12274 (defun org-get-todo-sequence-head (kwd)
12275 "Return the head of the TODO sequence to which KWD belongs.
12276 If KWD is not set, check if there is a text property remembering the
12277 right sequence."
12278 (let (p)
12279 (cond
12280 ((not kwd)
12281 (or (get-text-property (point-at-bol) 'org-todo-head)
12282 (progn
12283 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12284 nil (point-at-eol)))
12285 (get-text-property p 'org-todo-head))))
12286 ((not (member kwd org-todo-keywords-1))
12287 (car org-todo-keywords-1))
12288 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12290 (defun org-fast-todo-selection ()
12291 "Fast TODO keyword selection with single keys.
12292 Returns the new TODO keyword, or nil if no state change should occur."
12293 (let* ((fulltable org-todo-key-alist)
12294 (done-keywords org-done-keywords) ;; needed for the faces.
12295 (maxlen (apply 'max (mapcar
12296 (lambda (x)
12297 (if (stringp (car x)) (string-width (car x)) 0))
12298 fulltable)))
12299 (expert nil)
12300 (fwidth (+ maxlen 3 1 3))
12301 (ncol (/ (- (window-width) 4) fwidth))
12302 tg cnt e c tbl
12303 groups ingroup)
12304 (save-excursion
12305 (save-window-excursion
12306 (if expert
12307 (set-buffer (get-buffer-create " *Org todo*"))
12308 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12309 (erase-buffer)
12310 (org-set-local 'org-done-keywords done-keywords)
12311 (setq tbl fulltable cnt 0)
12312 (while (setq e (pop tbl))
12313 (cond
12314 ((equal e '(:startgroup))
12315 (push '() groups) (setq ingroup t)
12316 (when (not (= cnt 0))
12317 (setq cnt 0)
12318 (insert "\n"))
12319 (insert "{ "))
12320 ((equal e '(:endgroup))
12321 (setq ingroup nil cnt 0)
12322 (insert "}\n"))
12323 ((equal e '(:newline))
12324 (when (not (= cnt 0))
12325 (setq cnt 0)
12326 (insert "\n")
12327 (setq e (car tbl))
12328 (while (equal (car tbl) '(:newline))
12329 (insert "\n")
12330 (setq tbl (cdr tbl)))))
12332 (setq tg (car e) c (cdr e))
12333 (if ingroup (push tg (car groups)))
12334 (setq tg (org-add-props tg nil 'face
12335 (org-get-todo-face tg)))
12336 (if (and (= cnt 0) (not ingroup)) (insert " "))
12337 (insert "[" c "] " tg (make-string
12338 (- fwidth 4 (length tg)) ?\ ))
12339 (when (= (setq cnt (1+ cnt)) ncol)
12340 (insert "\n")
12341 (if ingroup (insert " "))
12342 (setq cnt 0)))))
12343 (insert "\n")
12344 (goto-char (point-min))
12345 (if (not expert) (org-fit-window-to-buffer))
12346 (message "[a-z..]:Set [SPC]:clear")
12347 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12348 (cond
12349 ((or (= c ?\C-g)
12350 (and (= c ?q) (not (rassoc c fulltable))))
12351 (setq quit-flag t))
12352 ((= c ?\ ) nil)
12353 ((setq e (rassoc c fulltable) tg (car e))
12355 (t (setq quit-flag t)))))))
12357 (defun org-entry-is-todo-p ()
12358 (member (org-get-todo-state) org-not-done-keywords))
12360 (defun org-entry-is-done-p ()
12361 (member (org-get-todo-state) org-done-keywords))
12363 (defun org-get-todo-state ()
12364 (save-excursion
12365 (org-back-to-heading t)
12366 (and (looking-at org-todo-line-regexp)
12367 (match-end 2)
12368 (match-string 2))))
12370 (defun org-at-date-range-p (&optional inactive-ok)
12371 "Is the cursor inside a date range?"
12372 (interactive)
12373 (save-excursion
12374 (catch 'exit
12375 (let ((pos (point)))
12376 (skip-chars-backward "^[<\r\n")
12377 (skip-chars-backward "<[")
12378 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12379 (>= (match-end 0) pos)
12380 (throw 'exit t))
12381 (skip-chars-backward "^<[\r\n")
12382 (skip-chars-backward "<[")
12383 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12384 (>= (match-end 0) pos)
12385 (throw 'exit t)))
12386 nil)))
12388 (defun org-get-repeat (&optional tagline)
12389 "Check if there is a deadline/schedule with repeater in this entry."
12390 (save-match-data
12391 (save-excursion
12392 (org-back-to-heading t)
12393 (and (re-search-forward (if tagline
12394 (concat tagline "\\s-*" org-repeat-re)
12395 org-repeat-re)
12396 (org-entry-end-position) t)
12397 (match-string-no-properties 1)))))
12399 (defvar org-last-changed-timestamp)
12400 (defvar org-last-inserted-timestamp)
12401 (defvar org-log-post-message)
12402 (defvar org-log-note-purpose)
12403 (defvar org-log-note-how)
12404 (defvar org-log-note-extra)
12405 (defun org-auto-repeat-maybe (done-word)
12406 "Check if the current headline contains a repeated deadline/schedule.
12407 If yes, set TODO state back to what it was and change the base date
12408 of repeating deadline/scheduled time stamps to new date.
12409 This function is run automatically after each state change to a DONE state."
12410 ;; last-state is dynamically scoped into this function
12411 (let* ((repeat (org-get-repeat))
12412 (aa (assoc org-last-state org-todo-kwd-alist))
12413 (interpret (nth 1 aa))
12414 (head (nth 2 aa))
12415 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12416 (msg "Entry repeats: ")
12417 (org-log-done nil)
12418 (org-todo-log-states nil)
12419 re type n what ts time to-state)
12420 (when repeat
12421 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12422 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12423 org-todo-repeat-to-state))
12424 (unless (and to-state (member to-state org-todo-keywords-1))
12425 (setq to-state (if (eq interpret 'type) org-last-state head)))
12426 (org-todo to-state)
12427 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12428 (org-entry-put nil "LAST_REPEAT" (format-time-string
12429 (org-time-stamp-format t t))))
12430 (when org-log-repeat
12431 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12432 (memq 'org-add-log-note post-command-hook))
12433 ;; OK, we are already setup for some record
12434 (if (eq org-log-repeat 'note)
12435 ;; make sure we take a note, not only a time stamp
12436 (setq org-log-note-how 'note))
12437 ;; Set up for taking a record
12438 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12439 org-last-state
12440 'findpos org-log-repeat)))
12441 (org-back-to-heading t)
12442 (org-add-planning-info nil nil 'closed)
12443 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12444 org-deadline-time-regexp "\\)\\|\\("
12445 org-ts-regexp "\\)"))
12446 (while (re-search-forward
12447 re (save-excursion (outline-next-heading) (point)) t)
12448 (setq type (if (match-end 1) org-scheduled-string
12449 (if (match-end 3) org-deadline-string "Plain:"))
12450 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12451 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12452 (setq n (string-to-number (match-string 2 ts))
12453 what (match-string 3 ts))
12454 (if (equal what "w") (setq n (* n 7) what "d"))
12455 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12456 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12457 ;; Preparation, see if we need to modify the start date for the change
12458 (when (match-end 1)
12459 (setq time (save-match-data (org-time-string-to-time ts)))
12460 (cond
12461 ((equal (match-string 1 ts) ".")
12462 ;; Shift starting date to today
12463 (org-timestamp-change
12464 (- (org-today) (time-to-days time))
12465 'day))
12466 ((equal (match-string 1 ts) "+")
12467 (let ((nshiftmax 10) (nshift 0))
12468 (while (or (= nshift 0)
12469 (<= (time-to-days time)
12470 (time-to-days (current-time))))
12471 (when (= (incf nshift) nshiftmax)
12472 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12473 (error "Abort")))
12474 (org-timestamp-change n (cdr (assoc what whata)))
12475 (org-at-timestamp-p t)
12476 (setq ts (match-string 1))
12477 (setq time (save-match-data (org-time-string-to-time ts)))))
12478 (org-timestamp-change (- n) (cdr (assoc what whata)))
12479 ;; rematch, so that we have everything in place for the real shift
12480 (org-at-timestamp-p t)
12481 (setq ts (match-string 1))
12482 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12483 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12484 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12485 (setq org-log-post-message msg)
12486 (message "%s" msg))))
12488 (defun org-show-todo-tree (arg)
12489 "Make a compact tree which shows all headlines marked with TODO.
12490 The tree will show the lines where the regexp matches, and all higher
12491 headlines above the match.
12492 With a \\[universal-argument] prefix, prompt for a regexp to match.
12493 With a numeric prefix N, construct a sparse tree for the Nth element
12494 of `org-todo-keywords-1'."
12495 (interactive "P")
12496 (let ((case-fold-search nil)
12497 (kwd-re
12498 (cond ((null arg) org-not-done-regexp)
12499 ((equal arg '(4))
12500 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12501 (mapcar 'list org-todo-keywords-1))))
12502 (concat "\\("
12503 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12504 "\\)\\>")))
12505 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12506 (regexp-quote (nth (1- (prefix-numeric-value arg))
12507 org-todo-keywords-1)))
12508 (t (error "Invalid prefix argument: %s" arg)))))
12509 (message "%d TODO entries found"
12510 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12512 (defun org-deadline (&optional arg time)
12513 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12514 With one universal prefix argument, remove any deadline from the item.
12515 With two universal prefix arguments, prompt for a warning delay.
12516 With argument TIME, set the deadline at the corresponding date. TIME
12517 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12518 (interactive "P")
12519 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12520 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12521 'region-start-level 'region))
12522 org-loop-over-headlines-in-active-region)
12523 (org-map-entries
12524 `(org-deadline ',arg ,time)
12525 org-loop-over-headlines-in-active-region
12526 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12527 (let* ((old-date (org-entry-get nil "DEADLINE"))
12528 (repeater (and old-date
12529 (string-match
12530 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12531 old-date)
12532 (match-string 1 old-date))))
12533 (cond
12534 ((equal arg '(4))
12535 (when (and old-date org-log-redeadline)
12536 (org-add-log-setup 'deldeadline nil old-date 'findpos
12537 org-log-redeadline))
12538 (org-remove-timestamp-with-keyword org-deadline-string)
12539 (message "Item no longer has a deadline."))
12540 ((equal arg '(16))
12541 (save-excursion
12542 (if (re-search-forward
12543 org-deadline-time-regexp
12544 (save-excursion (outline-next-heading) (point)) t)
12545 (let* ((rpl0 (match-string 1))
12546 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12547 (replace-match
12548 (concat org-deadline-string
12549 " <" rpl
12550 (format " -%dd" (abs
12551 (- (time-to-days
12552 (save-match-data
12553 (org-read-date nil t nil "Warn starting from")))
12554 (time-to-days nil))))
12555 ">") t t))
12556 (user-error "No deadline information to update"))))
12558 (org-add-planning-info 'deadline time 'closed)
12559 (when (and old-date org-log-redeadline
12560 (not (equal old-date
12561 (substring org-last-inserted-timestamp 1 -1))))
12562 (org-add-log-setup 'redeadline nil old-date 'findpos
12563 org-log-redeadline))
12564 (when repeater
12565 (save-excursion
12566 (org-back-to-heading t)
12567 (when (re-search-forward (concat org-deadline-string " "
12568 org-last-inserted-timestamp)
12569 (save-excursion
12570 (outline-next-heading) (point)) t)
12571 (goto-char (1- (match-end 0)))
12572 (insert " " repeater)
12573 (setq org-last-inserted-timestamp
12574 (concat (substring org-last-inserted-timestamp 0 -1)
12575 " " repeater
12576 (substring org-last-inserted-timestamp -1))))))
12577 (message "Deadline on %s" org-last-inserted-timestamp))))))
12579 (defun org-schedule (&optional arg time)
12580 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12581 With one universal prefix argument, remove any scheduling date from the item.
12582 With two universal prefix arguments, prompt for a delay cookie.
12583 With argument TIME, scheduled at the corresponding date. TIME can
12584 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12585 (interactive "P")
12586 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12587 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12588 'region-start-level 'region))
12589 org-loop-over-headlines-in-active-region)
12590 (org-map-entries
12591 `(org-schedule ',arg ,time)
12592 org-loop-over-headlines-in-active-region
12593 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12594 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12595 (repeater (and old-date
12596 (string-match
12597 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12598 old-date)
12599 (match-string 1 old-date))))
12600 (cond
12601 ((equal arg '(4))
12602 (progn
12603 (when (and old-date org-log-reschedule)
12604 (org-add-log-setup 'delschedule nil old-date 'findpos
12605 org-log-reschedule))
12606 (org-remove-timestamp-with-keyword org-scheduled-string)
12607 (message "Item is no longer scheduled.")))
12608 ((equal arg '(16))
12609 (save-excursion
12610 (if (re-search-forward
12611 org-scheduled-time-regexp
12612 (save-excursion (outline-next-heading) (point)) t)
12613 (let* ((rpl0 (match-string 1))
12614 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12615 (replace-match
12616 (concat org-scheduled-string
12617 " <" rpl
12618 (format " -%dd" (abs
12619 (- (time-to-days
12620 (save-match-data
12621 (org-read-date nil t nil "Delay until")))
12622 (time-to-days nil))))
12623 ">") t t))
12624 (user-error "No scheduled information to update"))))
12626 (org-add-planning-info 'scheduled time 'closed)
12627 (when (and old-date org-log-reschedule
12628 (not (equal old-date
12629 (substring org-last-inserted-timestamp 1 -1))))
12630 (org-add-log-setup 'reschedule nil old-date 'findpos
12631 org-log-reschedule))
12632 (when repeater
12633 (save-excursion
12634 (org-back-to-heading t)
12635 (when (re-search-forward (concat org-scheduled-string " "
12636 org-last-inserted-timestamp)
12637 (save-excursion
12638 (outline-next-heading) (point)) t)
12639 (goto-char (1- (match-end 0)))
12640 (insert " " repeater)
12641 (setq org-last-inserted-timestamp
12642 (concat (substring org-last-inserted-timestamp 0 -1)
12643 " " repeater
12644 (substring org-last-inserted-timestamp -1))))))
12645 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12647 (defun org-get-scheduled-time (pom &optional inherit)
12648 "Get the scheduled time as a time tuple, of a format suitable
12649 for calling org-schedule with, or if there is no scheduling,
12650 returns nil."
12651 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12652 (when time
12653 (apply 'encode-time (org-parse-time-string time)))))
12655 (defun org-get-deadline-time (pom &optional inherit)
12656 "Get the deadline as a time tuple, of a format suitable for
12657 calling org-deadline with, or if there is no scheduling, returns
12658 nil."
12659 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12660 (when time
12661 (apply 'encode-time (org-parse-time-string time)))))
12663 (defun org-remove-timestamp-with-keyword (keyword)
12664 "Remove all time stamps with KEYWORD in the current entry."
12665 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12666 beg)
12667 (save-excursion
12668 (org-back-to-heading t)
12669 (setq beg (point))
12670 (outline-next-heading)
12671 (while (re-search-backward re beg t)
12672 (replace-match "")
12673 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12674 (equal (char-before) ?\ ))
12675 (backward-delete-char 1)
12676 (if (string-match "^[ \t]*$" (buffer-substring
12677 (point-at-bol) (point-at-eol)))
12678 (delete-region (point-at-bol)
12679 (min (point-max) (1+ (point-at-eol))))))))))
12681 (defun org-add-planning-info (what &optional time &rest remove)
12682 "Insert new timestamp with keyword in the line directly after the headline.
12683 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12684 If non is given, the user is prompted for a date.
12685 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12686 be removed."
12687 (interactive)
12688 (let (org-time-was-given org-end-time-was-given ts
12689 end default-time default-input)
12691 (catch 'exit
12692 (when (and (memq what '(scheduled deadline))
12693 (or (not time)
12694 (and (stringp time)
12695 (string-match "^[-+]+[0-9]" time))))
12696 ;; Try to get a default date/time from existing timestamp
12697 (save-excursion
12698 (org-back-to-heading t)
12699 (setq end (save-excursion (outline-next-heading) (point)))
12700 (when (re-search-forward (if (eq what 'scheduled)
12701 org-scheduled-time-regexp
12702 org-deadline-time-regexp)
12703 end t)
12704 (setq ts (match-string 1)
12705 default-time
12706 (apply 'encode-time (org-parse-time-string ts))
12707 default-input (and ts (org-get-compact-tod ts))))))
12708 (when what
12709 (setq time
12710 (if (stringp time)
12711 ;; This is a string (relative or absolute), set proper date
12712 (apply 'encode-time
12713 (org-read-date-analyze
12714 time default-time (decode-time default-time)))
12715 ;; If necessary, get the time from the user
12716 (or time (org-read-date nil 'to-time nil nil
12717 default-time default-input)))))
12719 (when (and org-insert-labeled-timestamps-at-point
12720 (member what '(scheduled deadline)))
12721 (insert
12722 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12723 (org-insert-time-stamp time org-time-was-given
12724 nil nil nil (list org-end-time-was-given))
12725 (setq what nil))
12726 (save-excursion
12727 (save-restriction
12728 (let (col list elt ts buffer-invisibility-spec)
12729 (org-back-to-heading t)
12730 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12731 (goto-char (match-end 1))
12732 (setq col (current-column))
12733 (goto-char (match-end 0))
12734 (if (eobp) (insert "\n") (forward-char 1))
12735 (when (and (not what)
12736 (not (looking-at
12737 (concat "[ \t]*"
12738 org-keyword-time-not-clock-regexp))))
12739 ;; Nothing to add, nothing to remove...... :-)
12740 (throw 'exit nil))
12741 (if (and (not (looking-at org-outline-regexp))
12742 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12743 "[^\r\n]*"))
12744 (not (equal (match-string 1) org-clock-string)))
12745 (narrow-to-region (match-beginning 0) (match-end 0))
12746 (insert-before-markers "\n")
12747 (backward-char 1)
12748 (narrow-to-region (point) (point))
12749 (and org-adapt-indentation (org-indent-to-column col)))
12750 ;; Check if we have to remove something.
12751 (setq list (cons what remove))
12752 (while list
12753 (setq elt (pop list))
12754 (when (or (and (eq elt 'scheduled)
12755 (re-search-forward org-scheduled-time-regexp nil t))
12756 (and (eq elt 'deadline)
12757 (re-search-forward org-deadline-time-regexp nil t))
12758 (and (eq elt 'closed)
12759 (re-search-forward org-closed-time-regexp nil t)))
12760 (replace-match "")
12761 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12762 (and (looking-at "[ \t]+") (replace-match ""))
12763 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12764 (when what
12765 (insert
12766 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12767 (cond ((eq what 'scheduled) org-scheduled-string)
12768 ((eq what 'deadline) org-deadline-string)
12769 ((eq what 'closed) org-closed-string))
12770 " ")
12771 (setq ts (org-insert-time-stamp
12772 time
12773 (or org-time-was-given
12774 (and (eq what 'closed) org-log-done-with-time))
12775 (eq what 'closed)
12776 nil nil (list org-end-time-was-given)))
12777 (insert
12778 (if (not (or (bolp) (eq (char-before) ?\ )
12779 (memq (char-after) '(32 10))
12780 (eobp))) " " ""))
12781 (end-of-line 1))
12782 (goto-char (point-min))
12783 (widen)
12784 (if (and (looking-at "[ \t]*\n")
12785 (equal (char-before) ?\n))
12786 (delete-region (1- (point)) (point-at-eol)))
12787 ts))))))
12789 (defvar org-log-note-marker (make-marker))
12790 (defvar org-log-note-purpose nil)
12791 (defvar org-log-note-state nil)
12792 (defvar org-log-note-previous-state nil)
12793 (defvar org-log-note-how nil)
12794 (defvar org-log-note-extra nil)
12795 (defvar org-log-note-window-configuration nil)
12796 (defvar org-log-note-return-to (make-marker))
12797 (defvar org-log-note-effective-time nil
12798 "Remembered current time so that dynamically scoped
12799 `org-extend-today-until' affects tha timestamps in state change
12800 log")
12802 (defvar org-log-post-message nil
12803 "Message to be displayed after a log note has been stored.
12804 The auto-repeater uses this.")
12806 (defun org-add-note ()
12807 "Add a note to the current entry.
12808 This is done in the same way as adding a state change note."
12809 (interactive)
12810 (org-add-log-setup 'note nil nil 'findpos nil))
12812 (defvar org-property-end-re)
12813 (defun org-add-log-setup (&optional purpose state prev-state
12814 findpos how extra)
12815 "Set up the post command hook to take a note.
12816 If this is about to TODO state change, the new state is expected in STATE.
12817 When FINDPOS is non-nil, find the correct position for the note in
12818 the current entry. If not, assume that it can be inserted at point.
12819 HOW is an indicator what kind of note should be created.
12820 EXTRA is additional text that will be inserted into the notes buffer."
12821 (let* ((org-log-into-drawer (org-log-into-drawer))
12822 (drawer (cond ((stringp org-log-into-drawer)
12823 org-log-into-drawer)
12824 (org-log-into-drawer "LOGBOOK"))))
12825 (save-restriction
12826 (save-excursion
12827 (when findpos
12828 (org-back-to-heading t)
12829 (narrow-to-region (point) (save-excursion
12830 (outline-next-heading) (point)))
12831 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12832 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12833 "[^\r\n]*\\)?"))
12834 (goto-char (match-end 0))
12835 (cond
12836 (drawer
12837 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12838 nil t)
12839 (progn
12840 (goto-char (match-end 0))
12841 (or org-log-states-order-reversed
12842 (and (re-search-forward org-property-end-re nil t)
12843 (goto-char (1- (match-beginning 0))))))
12844 (insert "\n:" drawer ":\n:END:")
12845 (beginning-of-line 0)
12846 (org-indent-line)
12847 (beginning-of-line 2)
12848 (org-indent-line)
12849 (end-of-line 0)))
12850 ((and org-log-state-notes-insert-after-drawers
12851 (save-excursion
12852 (forward-line) (looking-at org-drawer-regexp)))
12853 (forward-line)
12854 (while (looking-at org-drawer-regexp)
12855 (goto-char (match-end 0))
12856 (re-search-forward org-property-end-re (point-max) t)
12857 (forward-line))
12858 (forward-line -1)))
12859 (unless org-log-states-order-reversed
12860 (and (= (char-after) ?\n) (forward-char 1))
12861 (org-skip-over-state-notes)
12862 (skip-chars-backward " \t\n\r")))
12863 (move-marker org-log-note-marker (point))
12864 (setq org-log-note-purpose purpose
12865 org-log-note-state state
12866 org-log-note-previous-state prev-state
12867 org-log-note-how how
12868 org-log-note-extra extra
12869 org-log-note-effective-time (org-current-effective-time))
12870 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12872 (defun org-skip-over-state-notes ()
12873 "Skip past the list of State notes in an entry."
12874 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12875 (when (ignore-errors (goto-char (org-in-item-p)))
12876 (let* ((struct (org-list-struct))
12877 (prevs (org-list-prevs-alist struct)))
12878 (while (looking-at "[ \t]*- State")
12879 (goto-char (or (org-list-get-next-item (point) struct prevs)
12880 (org-list-get-item-end (point) struct)))))))
12882 (defun org-add-log-note (&optional purpose)
12883 "Pop up a window for taking a note, and add this note later at point."
12884 (remove-hook 'post-command-hook 'org-add-log-note)
12885 (setq org-log-note-window-configuration (current-window-configuration))
12886 (delete-other-windows)
12887 (move-marker org-log-note-return-to (point))
12888 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12889 (goto-char org-log-note-marker)
12890 (org-switch-to-buffer-other-window "*Org Note*")
12891 (erase-buffer)
12892 (if (memq org-log-note-how '(time state))
12893 (let (current-prefix-arg) (org-store-log-note))
12894 (let ((org-inhibit-startup t)) (org-mode))
12895 (insert (format "# Insert note for %s.
12896 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12897 (cond
12898 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12899 ((eq org-log-note-purpose 'done) "closed todo item")
12900 ((eq org-log-note-purpose 'state)
12901 (format "state change from \"%s\" to \"%s\""
12902 (or org-log-note-previous-state "")
12903 (or org-log-note-state "")))
12904 ((eq org-log-note-purpose 'reschedule)
12905 "rescheduling")
12906 ((eq org-log-note-purpose 'delschedule)
12907 "no longer scheduled")
12908 ((eq org-log-note-purpose 'redeadline)
12909 "changing deadline")
12910 ((eq org-log-note-purpose 'deldeadline)
12911 "removing deadline")
12912 ((eq org-log-note-purpose 'refile)
12913 "refiling")
12914 ((eq org-log-note-purpose 'note)
12915 "this entry")
12916 (t (error "This should not happen")))))
12917 (if org-log-note-extra (insert org-log-note-extra))
12918 (org-set-local 'org-finish-function 'org-store-log-note)
12919 (run-hooks 'org-log-buffer-setup-hook)))
12921 (defvar org-note-abort nil) ; dynamically scoped
12922 (defun org-store-log-note ()
12923 "Finish taking a log note, and insert it to where it belongs."
12924 (let ((txt (buffer-string)))
12925 (kill-buffer (current-buffer))
12926 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12927 lines ind bul)
12928 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12929 (setq txt (replace-match "" t t txt)))
12930 (if (string-match "\\s-+\\'" txt)
12931 (setq txt (replace-match "" t t txt)))
12932 (setq lines (org-split-string txt "\n"))
12933 (when (and note (string-match "\\S-" note))
12934 (setq note
12935 (org-replace-escapes
12936 note
12937 (list (cons "%u" (user-login-name))
12938 (cons "%U" user-full-name)
12939 (cons "%t" (format-time-string
12940 (org-time-stamp-format 'long 'inactive)
12941 org-log-note-effective-time))
12942 (cons "%T" (format-time-string
12943 (org-time-stamp-format 'long nil)
12944 org-log-note-effective-time))
12945 (cons "%d" (format-time-string
12946 (org-time-stamp-format nil 'inactive)
12947 org-log-note-effective-time))
12948 (cons "%D" (format-time-string
12949 (org-time-stamp-format nil nil)
12950 org-log-note-effective-time))
12951 (cons "%s" (if org-log-note-state
12952 (concat "\"" org-log-note-state "\"")
12953 ""))
12954 (cons "%S" (if org-log-note-previous-state
12955 (concat "\"" org-log-note-previous-state "\"")
12956 "\"\"")))))
12957 (if lines (setq note (concat note " \\\\")))
12958 (push note lines))
12959 (when (or current-prefix-arg org-note-abort)
12960 (when org-log-into-drawer
12961 (org-remove-empty-drawer-at
12962 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12963 org-log-note-marker))
12964 (setq lines nil))
12965 (when lines
12966 (with-current-buffer (marker-buffer org-log-note-marker)
12967 (save-excursion
12968 (goto-char org-log-note-marker)
12969 (move-marker org-log-note-marker nil)
12970 (end-of-line 1)
12971 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12972 (setq ind (save-excursion
12973 (if (ignore-errors (goto-char (org-in-item-p)))
12974 (let ((struct (org-list-struct)))
12975 (org-list-get-ind
12976 (org-list-get-top-point struct) struct))
12977 (skip-chars-backward " \r\t\n")
12978 (cond
12979 ((and (org-at-heading-p)
12980 org-adapt-indentation)
12981 (1+ (org-current-level)))
12982 ((org-at-heading-p) 0)
12983 (t (org-get-indentation))))))
12984 (setq bul (org-list-bullet-string "-"))
12985 (org-indent-line-to ind)
12986 (insert bul (pop lines))
12987 (let ((ind-body (+ (length bul) ind)))
12988 (while lines
12989 (insert "\n")
12990 (org-indent-line-to ind-body)
12991 (insert (pop lines))))
12992 (message "Note stored")
12993 (org-back-to-heading t)
12994 (org-cycle-hide-drawers 'children))))))
12995 (set-window-configuration org-log-note-window-configuration)
12996 (with-current-buffer (marker-buffer org-log-note-return-to)
12997 (goto-char org-log-note-return-to))
12998 (move-marker org-log-note-return-to nil)
12999 (and org-log-post-message (message "%s" org-log-post-message)))
13001 (defun org-remove-empty-drawer-at (drawer pos)
13002 "Remove an empty drawer DRAWER at position POS.
13003 POS may also be a marker."
13004 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13005 (save-excursion
13006 (save-restriction
13007 (widen)
13008 (goto-char pos)
13009 (if (org-in-regexp
13010 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13011 (replace-match ""))))))
13013 (defvar org-ts-type nil)
13014 (defun org-sparse-tree (&optional arg type)
13015 "Create a sparse tree, prompt for the details.
13016 This command can create sparse trees. You first need to select the type
13017 of match used to create the tree:
13019 t Show all TODO entries.
13020 T Show entries with a specific TODO keyword.
13021 m Show entries selected by a tags/property match.
13022 p Enter a property name and its value (both with completion on existing
13023 names/values) and show entries with that property.
13024 r Show entries matching a regular expression (`/' can be used as well).
13025 b Show deadlines and scheduled items before a date.
13026 a Show deadlines and scheduled items after a date.
13027 d Show deadlines due within `org-deadline-warning-days'.
13028 D Show deadlines and scheduled items between a date range."
13029 (interactive "P")
13030 (let (ans kwd value ts-type)
13031 (setq type (or type org-sparse-tree-default-date-type))
13032 (setq org-ts-type type)
13033 (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"
13034 (cond ((eq type 'all) "all timestamps")
13035 ((eq type 'scheduled) "only scheduled")
13036 ((eq type 'deadline) "only deadline")
13037 ((eq type 'active) "only active timestamps")
13038 ((eq type 'inactive) "only inactive timestamps")
13039 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13040 (t "scheduled/deadline")))
13041 (setq ans (read-char-exclusive))
13042 (cond
13043 ((equal ans ?c)
13044 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13045 ((equal ans ?d)
13046 (call-interactively 'org-check-deadlines))
13047 ((equal ans ?b)
13048 (call-interactively 'org-check-before-date))
13049 ((equal ans ?a)
13050 (call-interactively 'org-check-after-date))
13051 ((equal ans ?D)
13052 (call-interactively 'org-check-dates-range))
13053 ((equal ans ?t)
13054 (call-interactively 'org-show-todo-tree))
13055 ((equal ans ?T)
13056 (org-show-todo-tree '(4)))
13057 ((member ans '(?T ?m))
13058 (call-interactively 'org-match-sparse-tree))
13059 ((member ans '(?p ?P))
13060 (setq kwd (org-icompleting-read "Property: "
13061 (mapcar 'list (org-buffer-property-keys))))
13062 (setq value (org-icompleting-read "Value: "
13063 (mapcar 'list (org-property-values kwd))))
13064 (unless (string-match "\\`{.*}\\'" value)
13065 (setq value (concat "\"" value "\"")))
13066 (org-match-sparse-tree arg (concat kwd "=" value)))
13067 ((member ans '(?r ?R ?/))
13068 (call-interactively 'org-occur))
13069 (t (error "No such sparse tree command \"%c\"" ans)))))
13071 (defvar org-occur-highlights nil
13072 "List of overlays used for occur matches.")
13073 (make-variable-buffer-local 'org-occur-highlights)
13074 (defvar org-occur-parameters nil
13075 "Parameters of the active org-occur calls.
13076 This is a list, each call to org-occur pushes as cons cell,
13077 containing the regular expression and the callback, onto the list.
13078 The list can contain several entries if `org-occur' has been called
13079 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13080 will only contain one set of parameters. When the highlights are
13081 removed (for example with `C-c C-c', or with the next edit (depending
13082 on `org-remove-highlights-with-change'), this variable is emptied
13083 as well.")
13084 (make-variable-buffer-local 'org-occur-parameters)
13086 (defun org-occur (regexp &optional keep-previous callback)
13087 "Make a compact tree which shows all matches of REGEXP.
13088 The tree will show the lines where the regexp matches, and all higher
13089 headlines above the match. It will also show the heading after the match,
13090 to make sure editing the matching entry is easy.
13091 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13092 call to `org-occur' will be kept, to allow stacking of calls to this
13093 command.
13094 If CALLBACK is non-nil, it is a function which is called to confirm
13095 that the match should indeed be shown."
13096 (interactive "sRegexp: \nP")
13097 (when (equal regexp "")
13098 (error "Regexp cannot be empty"))
13099 (unless keep-previous
13100 (org-remove-occur-highlights nil nil t))
13101 (push (cons regexp callback) org-occur-parameters)
13102 (let ((cnt 0))
13103 (save-excursion
13104 (goto-char (point-min))
13105 (if (or (not keep-previous) ; do not want to keep
13106 (not org-occur-highlights)) ; no previous matches
13107 ;; hide everything
13108 (org-overview))
13109 (while (re-search-forward regexp nil t)
13110 (when (or (not callback)
13111 (save-match-data (funcall callback)))
13112 (setq cnt (1+ cnt))
13113 (when org-highlight-sparse-tree-matches
13114 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13115 (org-show-context 'occur-tree))))
13116 (when org-remove-highlights-with-change
13117 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13118 nil 'local))
13119 (unless org-sparse-tree-open-archived-trees
13120 (org-hide-archived-subtrees (point-min) (point-max)))
13121 (run-hooks 'org-occur-hook)
13122 (if (org-called-interactively-p 'interactive)
13123 (message "%d match(es) for regexp %s" cnt regexp))
13124 cnt))
13126 (defun org-occur-next-match (&optional n reset)
13127 "Function for `next-error-function' to find sparse tree matches.
13128 N is the number of matches to move, when negative move backwards.
13129 RESET is entirely ignored - this function always goes back to the
13130 starting point when no match is found."
13131 (let* ((limit (if (< n 0) (point-min) (point-max)))
13132 (search-func (if (< n 0)
13133 'previous-single-char-property-change
13134 'next-single-char-property-change))
13135 (n (abs n))
13136 (pos (point))
13138 (catch 'exit
13139 (while (setq p1 (funcall search-func (point) 'org-type))
13140 (when (equal p1 limit)
13141 (goto-char pos)
13142 (error "No more matches"))
13143 (when (equal (get-char-property p1 'org-type) 'org-occur)
13144 (setq n (1- n))
13145 (when (= n 0)
13146 (goto-char p1)
13147 (throw 'exit (point))))
13148 (goto-char p1))
13149 (goto-char p1)
13150 (error "No more matches"))))
13152 (defun org-show-context (&optional key)
13153 "Make sure point and context are visible.
13154 How much context is shown depends upon the variables
13155 `org-show-hierarchy-above', `org-show-following-heading',
13156 `org-show-entry-below' and `org-show-siblings'."
13157 (let ((heading-p (org-at-heading-p t))
13158 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13159 (following-p (org-get-alist-option org-show-following-heading key))
13160 (entry-p (org-get-alist-option org-show-entry-below key))
13161 (siblings-p (org-get-alist-option org-show-siblings key)))
13162 (catch 'exit
13163 ;; Show heading or entry text
13164 (if (and heading-p (not entry-p))
13165 (org-flag-heading nil) ; only show the heading
13166 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13167 (org-show-hidden-entry))) ; show entire entry
13168 (when following-p
13169 ;; Show next sibling, or heading below text
13170 (save-excursion
13171 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13172 (org-flag-heading nil))))
13173 (when siblings-p (org-show-siblings))
13174 (when hierarchy-p
13175 ;; show all higher headings, possibly with siblings
13176 (save-excursion
13177 (while (and (condition-case nil
13178 (progn (org-up-heading-all 1) t)
13179 (error nil))
13180 (not (bobp)))
13181 (org-flag-heading nil)
13182 (when siblings-p (org-show-siblings))))))))
13184 (defvar org-reveal-start-hook nil
13185 "Hook run before revealing a location.")
13187 (defun org-reveal (&optional siblings)
13188 "Show current entry, hierarchy above it, and the following headline.
13189 This can be used to show a consistent set of context around locations
13190 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13191 not t for the search context.
13193 With optional argument SIBLINGS, on each level of the hierarchy all
13194 siblings are shown. This repairs the tree structure to what it would
13195 look like when opened with hierarchical calls to `org-cycle'.
13196 With double optional argument \\[universal-argument] \\[universal-argument], \
13197 go to the parent and show the
13198 entire tree."
13199 (interactive "P")
13200 (run-hooks 'org-reveal-start-hook)
13201 (let ((org-show-hierarchy-above t)
13202 (org-show-following-heading t)
13203 (org-show-siblings (if siblings t org-show-siblings)))
13204 (org-show-context nil))
13205 (when (equal siblings '(16))
13206 (save-excursion
13207 (when (org-up-heading-safe)
13208 (org-show-subtree)
13209 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13211 (defun org-highlight-new-match (beg end)
13212 "Highlight from BEG to END and mark the highlight is an occur headline."
13213 (let ((ov (make-overlay beg end)))
13214 (overlay-put ov 'face 'secondary-selection)
13215 (overlay-put ov 'org-type 'org-occur)
13216 (push ov org-occur-highlights)))
13218 (defun org-remove-occur-highlights (&optional beg end noremove)
13219 "Remove the occur highlights from the buffer.
13220 BEG and END are ignored. If NOREMOVE is nil, remove this function
13221 from the `before-change-functions' in the current buffer."
13222 (interactive)
13223 (unless org-inhibit-highlight-removal
13224 (mapc 'delete-overlay org-occur-highlights)
13225 (setq org-occur-highlights nil)
13226 (setq org-occur-parameters nil)
13227 (unless noremove
13228 (remove-hook 'before-change-functions
13229 'org-remove-occur-highlights 'local))))
13231 ;;;; Priorities
13233 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13234 "Regular expression matching the priority indicator.")
13236 (defvar org-remove-priority-next-time nil)
13238 (defun org-priority-up ()
13239 "Increase the priority of the current item."
13240 (interactive)
13241 (org-priority 'up))
13243 (defun org-priority-down ()
13244 "Decrease the priority of the current item."
13245 (interactive)
13246 (org-priority 'down))
13248 (defun org-priority (&optional action show)
13249 "Change the priority of an item.
13250 ACTION can be `set', `up', `down', or a character."
13251 (interactive "P")
13252 (if (equal action '(4))
13253 (org-show-priority)
13254 (unless org-enable-priority-commands
13255 (error "Priority commands are disabled"))
13256 (setq action (or action 'set))
13257 (let (current new news have remove)
13258 (save-excursion
13259 (org-back-to-heading t)
13260 (if (looking-at org-priority-regexp)
13261 (setq current (string-to-char (match-string 2))
13262 have t))
13263 (cond
13264 ((eq action 'remove)
13265 (setq remove t new ?\ ))
13266 ((or (eq action 'set)
13267 (if (featurep 'xemacs) (characterp action) (integerp action)))
13268 (if (not (eq action 'set))
13269 (setq new action)
13270 (message "Priority %c-%c, SPC to remove: "
13271 org-highest-priority org-lowest-priority)
13272 (save-match-data
13273 (setq new (read-char-exclusive))))
13274 (if (and (= (upcase org-highest-priority) org-highest-priority)
13275 (= (upcase org-lowest-priority) org-lowest-priority))
13276 (setq new (upcase new)))
13277 (cond ((equal new ?\ ) (setq remove t))
13278 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13279 (error "Priority must be between `%c' and `%c'"
13280 org-highest-priority org-lowest-priority))))
13281 ((eq action 'up)
13282 (setq new (if have
13283 (1- current) ; normal cycling
13284 ;; last priority was empty
13285 (if (eq last-command this-command)
13286 org-lowest-priority ; wrap around empty to lowest
13287 ;; default
13288 (if org-priority-start-cycle-with-default
13289 org-default-priority
13290 (1- org-default-priority))))))
13291 ((eq action 'down)
13292 (setq new (if have
13293 (1+ current) ; normal cycling
13294 ;; last priority was empty
13295 (if (eq last-command this-command)
13296 org-highest-priority ; wrap around empty to highest
13297 ;; default
13298 (if org-priority-start-cycle-with-default
13299 org-default-priority
13300 (1+ org-default-priority))))))
13301 (t (error "Invalid action")))
13302 (if (or (< (upcase new) org-highest-priority)
13303 (> (upcase new) org-lowest-priority))
13304 (if (and (memq action '(up down))
13305 (not have) (not (eq last-command this-command)))
13306 ;; `new' is from default priority
13307 (error
13308 "The default can not be set, see `org-default-priority' why")
13309 ;; normal cycling: `new' is beyond highest/lowest priority
13310 ;; and is wrapped around to the empty priority
13311 (setq remove t)))
13312 (setq news (format "%c" new))
13313 (if have
13314 (if remove
13315 (replace-match "" t t nil 1)
13316 (replace-match news t t nil 2))
13317 (if remove
13318 (error "No priority cookie found in line")
13319 (let ((case-fold-search nil))
13320 (looking-at org-todo-line-regexp))
13321 (if (match-end 2)
13322 (progn
13323 (goto-char (match-end 2))
13324 (insert " [#" news "]"))
13325 (goto-char (match-beginning 3))
13326 (insert "[#" news "] "))))
13327 (org-preserve-lc (org-set-tags nil 'align)))
13328 (if remove
13329 (message "Priority removed")
13330 (message "Priority of current item set to %s" news)))))
13332 (defun org-show-priority ()
13333 "Show the priority of the current item.
13334 This priority is composed of the main priority given with the [#A] cookies,
13335 and by additional input from the age of a schedules or deadline entry."
13336 (interactive)
13337 (let ((pri (if (eq major-mode 'org-agenda-mode)
13338 (org-get-at-bol 'priority)
13339 (save-excursion
13340 (save-match-data
13341 (beginning-of-line)
13342 (and (looking-at org-heading-regexp)
13343 (org-get-priority (match-string 0))))))))
13344 (message "Priority is %d" (if pri pri -1000))))
13346 (defun org-get-priority (s)
13347 "Find priority cookie and return priority."
13348 (save-match-data
13349 (if (functionp org-get-priority-function)
13350 (funcall org-get-priority-function)
13351 (if (not (string-match org-priority-regexp s))
13352 (* 1000 (- org-lowest-priority org-default-priority))
13353 (* 1000 (- org-lowest-priority
13354 (string-to-char (match-string 2 s))))))))
13356 ;;;; Tags
13358 (defvar org-agenda-archives-mode)
13359 (defvar org-map-continue-from nil
13360 "Position from where mapping should continue.
13361 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13363 (defvar org-scanner-tags nil
13364 "The current tag list while the tags scanner is running.")
13365 (defvar org-trust-scanner-tags nil
13366 "Should `org-get-tags-at' use the tags for the scanner.
13367 This is for internal dynamical scoping only.
13368 When this is non-nil, the function `org-get-tags-at' will return the value
13369 of `org-scanner-tags' instead of building the list by itself. This
13370 can lead to large speed-ups when the tags scanner is used in a file with
13371 many entries, and when the list of tags is retrieved, for example to
13372 obtain a list of properties. Building the tags list for each entry in such
13373 a file becomes an N^2 operation - but with this variable set, it scales
13374 as N.")
13376 (defun org-scan-tags (action matcher todo-only &optional start-level)
13377 "Scan headline tags with inheritance and produce output ACTION.
13379 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13380 or `agenda' to produce an entry list for an agenda view. It can also be
13381 a Lisp form or a function that should be called at each matched headline, in
13382 this case the return value is a list of all return values from these calls.
13384 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13385 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13386 only lines with a not-done TODO keyword are included in the output.
13387 This should be the same variable that was scoped into
13388 and set by `org-make-tags-matcher' when it constructed MATCHER.
13390 START-LEVEL can be a string with asterisks, reducing the scope to
13391 headlines matching this string."
13392 (require 'org-agenda)
13393 (let* ((re (concat "^"
13394 (if start-level
13395 ;; Get the correct level to match
13396 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13397 org-outline-regexp)
13398 " *\\(\\<\\("
13399 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13400 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13401 (props (list 'face 'default
13402 'done-face 'org-agenda-done
13403 'undone-face 'default
13404 'mouse-face 'highlight
13405 'org-not-done-regexp org-not-done-regexp
13406 'org-todo-regexp org-todo-regexp
13407 'org-complex-heading-regexp org-complex-heading-regexp
13408 'help-echo
13409 (format "mouse-2 or RET jump to org file %s"
13410 (abbreviate-file-name
13411 (or (buffer-file-name (buffer-base-buffer))
13412 (buffer-name (buffer-base-buffer)))))))
13413 (case-fold-search nil)
13414 (org-map-continue-from nil)
13415 lspos tags tags-list
13416 (tags-alist (list (cons 0 org-file-tags)))
13417 (llast 0) rtn rtn1 level category i txt
13418 todo marker entry priority)
13419 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13420 (setq action (list 'lambda nil action)))
13421 (save-excursion
13422 (goto-char (point-min))
13423 (when (eq action 'sparse-tree)
13424 (org-overview)
13425 (org-remove-occur-highlights))
13426 (while (re-search-forward re nil t)
13427 (setq org-map-continue-from nil)
13428 (catch :skip
13429 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13430 tags (if (match-end 4) (org-match-string-no-properties 4)))
13431 (goto-char (setq lspos (match-beginning 0)))
13432 (setq level (org-reduced-level (org-outline-level))
13433 category (org-get-category))
13434 (setq i llast llast level)
13435 ;; remove tag lists from same and sublevels
13436 (while (>= i level)
13437 (when (setq entry (assoc i tags-alist))
13438 (setq tags-alist (delete entry tags-alist)))
13439 (setq i (1- i)))
13440 ;; add the next tags
13441 (when tags
13442 (setq tags (org-split-string tags ":")
13443 tags-alist
13444 (cons (cons level tags) tags-alist)))
13445 ;; compile tags for current headline
13446 (setq tags-list
13447 (if org-use-tag-inheritance
13448 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13449 tags)
13450 org-scanner-tags tags-list)
13451 (when org-use-tag-inheritance
13452 (setcdr (car tags-alist)
13453 (mapcar (lambda (x)
13454 (setq x (copy-sequence x))
13455 (org-add-prop-inherited x))
13456 (cdar tags-alist))))
13457 (when (and tags org-use-tag-inheritance
13458 (or (not (eq t org-use-tag-inheritance))
13459 org-tags-exclude-from-inheritance))
13460 ;; selective inheritance, remove uninherited ones
13461 (setcdr (car tags-alist)
13462 (org-remove-uninherited-tags (cdar tags-alist))))
13463 (when (and
13465 ;; eval matcher only when the todo condition is OK
13466 (and (or (not todo-only) (member todo org-not-done-keywords))
13467 (let ((case-fold-search t) (org-trust-scanner-tags t))
13468 (eval matcher)))
13470 ;; Call the skipper, but return t if it does not skip,
13471 ;; so that the `and' form continues evaluating
13472 (progn
13473 (unless (eq action 'sparse-tree) (org-agenda-skip))
13476 ;; Check if timestamps are deselecting this entry
13477 (or (not todo-only)
13478 (and (member todo org-not-done-keywords)
13479 (or (not org-agenda-tags-todo-honor-ignore-options)
13480 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13482 ;; select this headline
13483 (cond
13484 ((eq action 'sparse-tree)
13485 (and org-highlight-sparse-tree-matches
13486 (org-get-heading) (match-end 0)
13487 (org-highlight-new-match
13488 (match-beginning 1) (match-end 1)))
13489 (org-show-context 'tags-tree))
13490 ((eq action 'agenda)
13491 (setq txt (org-agenda-format-item
13493 (concat
13494 (if (eq org-tags-match-list-sublevels 'indented)
13495 (make-string (1- level) ?.) "")
13496 (org-get-heading))
13497 level category
13498 tags-list)
13499 priority (org-get-priority txt))
13500 (goto-char lspos)
13501 (setq marker (org-agenda-new-marker))
13502 (org-add-props txt props
13503 'org-marker marker 'org-hd-marker marker 'org-category category
13504 'todo-state todo
13505 'priority priority 'type "tagsmatch")
13506 (push txt rtn))
13507 ((functionp action)
13508 (setq org-map-continue-from nil)
13509 (save-excursion
13510 (setq rtn1 (funcall action))
13511 (push rtn1 rtn)))
13512 (t (error "Invalid action")))
13514 ;; if we are to skip sublevels, jump to end of subtree
13515 (unless org-tags-match-list-sublevels
13516 (org-end-of-subtree t)
13517 (backward-char 1))))
13518 ;; Get the correct position from where to continue
13519 (if org-map-continue-from
13520 (goto-char org-map-continue-from)
13521 (and (= (point) lspos) (end-of-line 1)))))
13522 (when (and (eq action 'sparse-tree)
13523 (not org-sparse-tree-open-archived-trees))
13524 (org-hide-archived-subtrees (point-min) (point-max)))
13525 (nreverse rtn)))
13527 (defun org-remove-uninherited-tags (tags)
13528 "Remove all tags that are not inherited from the list TAGS."
13529 (cond
13530 ((eq org-use-tag-inheritance t)
13531 (if org-tags-exclude-from-inheritance
13532 (org-delete-all org-tags-exclude-from-inheritance tags)
13533 tags))
13534 ((not org-use-tag-inheritance) nil)
13535 ((stringp org-use-tag-inheritance)
13536 (delq nil (mapcar
13537 (lambda (x)
13538 (if (and (string-match org-use-tag-inheritance x)
13539 (not (member x org-tags-exclude-from-inheritance)))
13540 x nil))
13541 tags)))
13542 ((listp org-use-tag-inheritance)
13543 (delq nil (mapcar
13544 (lambda (x)
13545 (if (member x org-use-tag-inheritance) x nil))
13546 tags)))))
13548 (defun org-match-sparse-tree (&optional todo-only match)
13549 "Create a sparse tree according to tags string MATCH.
13550 MATCH can contain positive and negative selection of tags, like
13551 \"+WORK+URGENT-WITHBOSS\".
13552 If optional argument TODO-ONLY is non-nil, only select lines that are
13553 also TODO lines."
13554 (interactive "P")
13555 (org-agenda-prepare-buffers (list (current-buffer)))
13556 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13558 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13560 (defvar org-cached-props nil)
13561 (defun org-cached-entry-get (pom property)
13562 (if (or (eq t org-use-property-inheritance)
13563 (and (stringp org-use-property-inheritance)
13564 (string-match org-use-property-inheritance property))
13565 (and (listp org-use-property-inheritance)
13566 (member property org-use-property-inheritance)))
13567 ;; Caching is not possible, check it directly
13568 (org-entry-get pom property 'inherit)
13569 ;; Get all properties, so that we can do complicated checks easily
13570 (cdr (assoc property (or org-cached-props
13571 (setq org-cached-props
13572 (org-entry-properties pom)))))))
13574 (defun org-global-tags-completion-table (&optional files)
13575 "Return the list of all tags in all agenda buffer/files.
13576 Optional FILES argument is a list of files which can be used
13577 instead of the agenda files."
13578 (save-excursion
13579 (org-uniquify
13580 (delq nil
13581 (apply 'append
13582 (mapcar
13583 (lambda (file)
13584 (set-buffer (find-file-noselect file))
13585 (append (org-get-buffer-tags)
13586 (mapcar (lambda (x) (if (stringp (car-safe x))
13587 (list (car-safe x)) nil))
13588 org-tag-alist)))
13589 (if (and files (car files))
13590 files
13591 (org-agenda-files))))))))
13593 (defun org-make-tags-matcher (match)
13594 "Create the TAGS/TODO matcher form for the selection string MATCH.
13596 The variable `todo-only' is scoped dynamically into this function.
13597 It will be set to t if the matcher restricts matching to TODO entries,
13598 otherwise will not be touched.
13600 Returns a cons of the selection string MATCH and the constructed
13601 lisp form implementing the matcher. The matcher is to be evaluated
13602 at an Org entry, with point on the headline, and returns t if the
13603 entry matches the selection string MATCH. The returned lisp form
13604 references two variables with information about the entry, which
13605 must be bound around the form's evaluation: todo, the TODO keyword
13606 at the entry (or nil of none); and tags-list, the list of all tags
13607 at the entry including inherited ones. Additionally, the category
13608 of the entry (if any) must be specified as the text property
13609 'org-category on the headline.
13611 See also `org-scan-tags'.
13613 (declare (special todo-only))
13614 (unless (boundp 'todo-only)
13615 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13616 (unless match
13617 ;; Get a new match request, with completion
13618 (let ((org-last-tags-completion-table
13619 (org-global-tags-completion-table)))
13620 (setq match (org-completing-read-no-i
13621 "Match: " 'org-tags-completion-function nil nil nil
13622 'org-tags-history))))
13624 ;; Parse the string and create a lisp form
13625 (let ((match0 match)
13626 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13627 minus tag mm
13628 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13629 orterms term orlist re-p str-p level-p level-op time-p
13630 prop-p pn pv po gv rest)
13631 (if (string-match "/+" match)
13632 ;; match contains also a todo-matching request
13633 (progn
13634 (setq tagsmatch (substring match 0 (match-beginning 0))
13635 todomatch (substring match (match-end 0)))
13636 (if (string-match "^!" todomatch)
13637 (setq todo-only t todomatch (substring todomatch 1)))
13638 (if (string-match "^\\s-*$" todomatch)
13639 (setq todomatch nil)))
13640 ;; only matching tags
13641 (setq tagsmatch match todomatch nil))
13643 ;; Make the tags matcher
13644 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13645 (setq tagsmatcher t)
13646 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13647 (while (setq term (pop orterms))
13648 (while (and (equal (substring term -1) "\\") orterms)
13649 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13650 (while (string-match re term)
13651 (setq rest (substring term (match-end 0))
13652 minus (and (match-end 1)
13653 (equal (match-string 1 term) "-"))
13654 tag (save-match-data (replace-regexp-in-string
13655 "\\\\-" "-"
13656 (match-string 2 term)))
13657 re-p (equal (string-to-char tag) ?{)
13658 level-p (match-end 4)
13659 prop-p (match-end 5)
13660 mm (cond
13661 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13662 (level-p
13663 (setq level-op (org-op-to-function (match-string 3 term)))
13664 `(,level-op level ,(string-to-number
13665 (match-string 4 term))))
13666 (prop-p
13667 (setq pn (match-string 5 term)
13668 po (match-string 6 term)
13669 pv (match-string 7 term)
13670 re-p (equal (string-to-char pv) ?{)
13671 str-p (equal (string-to-char pv) ?\")
13672 time-p (save-match-data
13673 (string-match "^\"[[<].*[]>]\"$" pv))
13674 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13675 (if time-p (setq pv (org-matcher-time pv)))
13676 (setq po (org-op-to-function po (if time-p 'time str-p)))
13677 (cond
13678 ((equal pn "CATEGORY")
13679 (setq gv '(get-text-property (point) 'org-category)))
13680 ((equal pn "TODO")
13681 (setq gv 'todo))
13683 (setq gv `(org-cached-entry-get nil ,pn))))
13684 (if re-p
13685 (if (eq po 'org<>)
13686 `(not (string-match ,pv (or ,gv "")))
13687 `(string-match ,pv (or ,gv "")))
13688 (if str-p
13689 `(,po (or ,gv "") ,pv)
13690 `(,po (string-to-number (or ,gv ""))
13691 ,(string-to-number pv) ))))
13692 (t `(member ,tag tags-list)))
13693 mm (if minus (list 'not mm) mm)
13694 term rest)
13695 (push mm tagsmatcher))
13696 (push (if (> (length tagsmatcher) 1)
13697 (cons 'and tagsmatcher)
13698 (car tagsmatcher))
13699 orlist)
13700 (setq tagsmatcher nil))
13701 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13702 (setq tagsmatcher
13703 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13704 ;; Make the todo matcher
13705 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13706 (setq todomatcher t)
13707 (setq orterms (org-split-string todomatch "|") orlist nil)
13708 (while (setq term (pop orterms))
13709 (while (string-match re term)
13710 (setq minus (and (match-end 1)
13711 (equal (match-string 1 term) "-"))
13712 kwd (match-string 2 term)
13713 re-p (equal (string-to-char kwd) ?{)
13714 term (substring term (match-end 0))
13715 mm (if re-p
13716 `(string-match ,(substring kwd 1 -1) todo)
13717 (list 'equal 'todo kwd))
13718 mm (if minus (list 'not mm) mm))
13719 (push mm todomatcher))
13720 (push (if (> (length todomatcher) 1)
13721 (cons 'and todomatcher)
13722 (car todomatcher))
13723 orlist)
13724 (setq todomatcher nil))
13725 (setq todomatcher (if (> (length orlist) 1)
13726 (cons 'or orlist) (car orlist))))
13728 ;; Return the string and lisp forms of the matcher
13729 (setq matcher (if todomatcher
13730 (list 'and tagsmatcher todomatcher)
13731 tagsmatcher))
13732 (when todo-only
13733 (setq matcher (list 'and '(member todo org-not-done-keywords)
13734 matcher)))
13735 (cons match0 matcher)))
13737 (defun org-op-to-function (op &optional stringp)
13738 "Turn an operator into the appropriate function."
13739 (setq op
13740 (cond
13741 ((equal op "<" ) '(< string< org-time<))
13742 ((equal op ">" ) '(> org-string> org-time>))
13743 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13744 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13745 ((member op '("=" "==")) '(= string= org-time=))
13746 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13747 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13749 (defun org<> (a b) (not (= a b)))
13750 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13751 (defun org-string>= (a b) (not (string< a b)))
13752 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13753 (defun org-string<> (a b) (not (string= a b)))
13754 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13755 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< 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) (org<> a b)))
13760 (defun org-2ft (s)
13761 "Convert S to a floating point time.
13762 If S is already a number, just return it. If it is a string, parse
13763 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13764 (cond
13765 ((numberp s) s)
13766 ((stringp s)
13767 (condition-case nil
13768 (float-time (apply 'encode-time (org-parse-time-string s)))
13769 (error 0.)))
13770 (t 0.)))
13772 (defun org-time-today ()
13773 "Time in seconds today at 0:00.
13774 Returns the float number of seconds since the beginning of the
13775 epoch to the beginning of today (00:00)."
13776 (float-time (apply 'encode-time
13777 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13779 (defun org-matcher-time (s)
13780 "Interpret a time comparison value."
13781 (save-match-data
13782 (cond
13783 ((string= s "<now>") (float-time))
13784 ((string= s "<today>") (org-time-today))
13785 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13786 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13787 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13788 (+ (org-time-today)
13789 (* (string-to-number (match-string 1 s))
13790 (cdr (assoc (match-string 2 s)
13791 '(("d" . 86400.0) ("w" . 604800.0)
13792 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13793 (t (org-2ft s)))))
13795 (defun org-match-any-p (re list)
13796 "Does re match any element of list?"
13797 (setq list (mapcar (lambda (x) (string-match re x)) list))
13798 (delq nil list))
13800 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13801 (defvar org-tags-overlay (make-overlay 1 1))
13802 (org-detach-overlay org-tags-overlay)
13804 (defun org-get-local-tags-at (&optional pos)
13805 "Get a list of tags defined in the current headline."
13806 (org-get-tags-at pos 'local))
13808 (defun org-get-local-tags ()
13809 "Get a list of tags defined in the current headline."
13810 (org-get-tags-at nil 'local))
13812 (defun org-get-tags-at (&optional pos local)
13813 "Get a list of all headline tags applicable at POS.
13814 POS defaults to point. If tags are inherited, the list contains
13815 the targets in the same sequence as the headlines appear, i.e.
13816 the tags of the current headline come last.
13817 When LOCAL is non-nil, only return tags from the current headline,
13818 ignore inherited ones."
13819 (interactive)
13820 (if (and org-trust-scanner-tags
13821 (or (not pos) (equal pos (point)))
13822 (not local))
13823 org-scanner-tags
13824 (let (tags ltags lastpos parent)
13825 (save-excursion
13826 (save-restriction
13827 (widen)
13828 (goto-char (or pos (point)))
13829 (save-match-data
13830 (catch 'done
13831 (condition-case nil
13832 (progn
13833 (org-back-to-heading t)
13834 (while (not (equal lastpos (point)))
13835 (setq lastpos (point))
13836 (when (looking-at
13837 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13838 (setq ltags (org-split-string
13839 (org-match-string-no-properties 1) ":"))
13840 (when parent
13841 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13842 (setq tags (append
13843 (if parent
13844 (org-remove-uninherited-tags ltags)
13845 ltags)
13846 tags)))
13847 (or org-use-tag-inheritance (throw 'done t))
13848 (if local (throw 'done t))
13849 (or (org-up-heading-safe) (error nil))
13850 (setq parent t)))
13851 (error nil)))))
13852 (if local
13853 tags
13854 (reverse (delete-dups
13855 (reverse (append
13856 (org-remove-uninherited-tags
13857 org-file-tags) tags)))))))))
13859 (defun org-add-prop-inherited (s)
13860 (add-text-properties 0 (length s) '(inherited t) s)
13863 (defun org-toggle-tag (tag &optional onoff)
13864 "Toggle the tag TAG for the current line.
13865 If ONOFF is `on' or `off', don't toggle but set to this state."
13866 (let (res current)
13867 (save-excursion
13868 (org-back-to-heading t)
13869 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13870 (point-at-eol) t)
13871 (progn
13872 (setq current (match-string 1))
13873 (replace-match ""))
13874 (setq current ""))
13875 (setq current (nreverse (org-split-string current ":")))
13876 (cond
13877 ((eq onoff 'on)
13878 (setq res t)
13879 (or (member tag current) (push tag current)))
13880 ((eq onoff 'off)
13881 (or (not (member tag current)) (setq current (delete tag current))))
13882 (t (if (member tag current)
13883 (setq current (delete tag current))
13884 (setq res t)
13885 (push tag current))))
13886 (end-of-line 1)
13887 (if current
13888 (progn
13889 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13890 (org-set-tags nil t))
13891 (delete-horizontal-space))
13892 (run-hooks 'org-after-tags-change-hook))
13893 res))
13895 (defun org-align-tags-here (to-col)
13896 ;; Assumes that this is a headline
13897 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13898 (beginning-of-line 1)
13899 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13900 (< pos (match-beginning 2)))
13901 (progn
13902 (setq tags-l (- (match-end 2) (match-beginning 2)))
13903 (goto-char (match-beginning 1))
13904 (insert " ")
13905 (delete-region (point) (1+ (match-beginning 2)))
13906 (setq ncol (max (current-column)
13907 (1+ col)
13908 (if (> to-col 0)
13909 to-col
13910 (- (abs to-col) tags-l))))
13911 (setq p (point))
13912 (insert (make-string (- ncol (current-column)) ?\ ))
13913 (setq ncol (current-column))
13914 (when indent-tabs-mode (tabify p (point-at-eol)))
13915 (org-move-to-column (min ncol col) t))
13916 (goto-char pos))))
13918 (defun org-set-tags-command (&optional arg just-align)
13919 "Call the set-tags command for the current entry."
13920 (interactive "P")
13921 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13922 (org-set-tags arg just-align)
13923 (save-excursion
13924 (org-back-to-heading t)
13925 (org-set-tags arg just-align))))
13927 (defun org-set-tags-to (data)
13928 "Set the tags of the current entry to DATA, replacing the current tags.
13929 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13930 If DATA is nil or the empty string, any tags will be removed."
13931 (interactive "sTags: ")
13932 (setq data
13933 (cond
13934 ((eq data nil) "")
13935 ((equal data "") "")
13936 ((stringp data)
13937 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13938 ":"))
13939 ((listp data)
13940 (concat ":" (mapconcat 'identity data ":") ":"))))
13941 (when data
13942 (save-excursion
13943 (org-back-to-heading t)
13944 (when (looking-at org-complex-heading-regexp)
13945 (if (match-end 5)
13946 (progn
13947 (goto-char (match-beginning 5))
13948 (insert data)
13949 (delete-region (point) (point-at-eol))
13950 (org-set-tags nil 'align))
13951 (goto-char (point-at-eol))
13952 (insert " " data)
13953 (org-set-tags nil 'align)))
13954 (beginning-of-line 1)
13955 (if (looking-at ".*?\\([ \t]+\\)$")
13956 (delete-region (match-beginning 1) (match-end 1))))))
13958 (defun org-align-all-tags ()
13959 "Align the tags i all headings."
13960 (interactive)
13961 (save-excursion
13962 (or (ignore-errors (org-back-to-heading t))
13963 (outline-next-heading))
13964 (if (org-at-heading-p)
13965 (org-set-tags t)
13966 (message "No headings"))))
13968 (defvar org-indent-indentation-per-level)
13969 (defun org-set-tags (&optional arg just-align)
13970 "Set the tags for the current headline.
13971 With prefix ARG, realign all tags in headings in the current buffer."
13972 (interactive "P")
13973 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13974 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13975 'region-start-level 'region))
13976 org-loop-over-headlines-in-active-region)
13977 (org-map-entries
13978 ;; We don't use ARG and JUST-ALIGN here these args are not
13979 ;; useful when looping over headlines
13980 `(org-set-tags)
13981 org-loop-over-headlines-in-active-region
13982 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13983 (let* ((re org-outline-regexp-bol)
13984 (current (unless arg (org-get-tags-string)))
13985 (col (current-column))
13986 (org-setting-tags t)
13987 table current-tags inherited-tags ; computed below when needed
13988 tags p0 c0 c1 rpl di tc level)
13989 (if arg
13990 (save-excursion
13991 (goto-char (point-min))
13992 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13993 (while (re-search-forward re nil t)
13994 (org-set-tags nil t)
13995 (end-of-line 1)))
13996 (message "All tags realigned to column %d" org-tags-column))
13997 (if just-align
13998 (setq tags current)
13999 ;; Get a new set of tags from the user
14000 (save-excursion
14001 (setq table (append org-tag-persistent-alist
14002 (or org-tag-alist (org-get-buffer-tags))
14003 (and
14004 org-complete-tags-always-offer-all-agenda-tags
14005 (org-global-tags-completion-table
14006 (org-agenda-files))))
14007 org-last-tags-completion-table table
14008 current-tags (org-split-string current ":")
14009 inherited-tags (nreverse
14010 (nthcdr (length current-tags)
14011 (nreverse (org-get-tags-at))))
14012 tags
14013 (if (or (eq t org-use-fast-tag-selection)
14014 (and org-use-fast-tag-selection
14015 (delq nil (mapcar 'cdr table))))
14016 (org-fast-tag-selection
14017 current-tags inherited-tags table
14018 (if org-fast-tag-selection-include-todo
14019 org-todo-key-alist))
14020 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14021 (org-trim
14022 (org-icompleting-read "Tags: "
14023 'org-tags-completion-function
14024 nil nil current 'org-tags-history))))))
14025 (while (string-match "[-+&]+" tags)
14026 ;; No boolean logic, just a list
14027 (setq tags (replace-match ":" t t tags))))
14029 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14031 (if org-tags-sort-function
14032 (setq tags (mapconcat 'identity
14033 (sort (org-split-string
14034 tags (org-re "[^[:alnum:]_@#%]+"))
14035 org-tags-sort-function) ":")))
14037 (if (string-match "\\`[\t ]*\\'" tags)
14038 (setq tags "")
14039 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14040 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14042 ;; Insert new tags at the correct column
14043 (beginning-of-line 1)
14044 (setq level (or (and (looking-at org-outline-regexp)
14045 (- (match-end 0) (point) 1))
14047 (cond
14048 ((and (equal current "") (equal tags "")))
14049 ((re-search-forward
14050 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14051 (point-at-eol) t)
14052 (if (equal tags "")
14053 (setq rpl "")
14054 (goto-char (match-beginning 0))
14055 (setq c0 (current-column)
14056 ;; compute offset for the case of org-indent-mode active
14057 di (if org-indent-mode
14058 (* (1- org-indent-indentation-per-level) (1- level))
14060 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14061 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14062 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14063 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14064 (replace-match rpl t t)
14065 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14066 tags)
14067 (t (error "Tags alignment failed")))
14068 (org-move-to-column col)
14069 (unless just-align
14070 (run-hooks 'org-after-tags-change-hook))))))
14072 (defun org-change-tag-in-region (beg end tag off)
14073 "Add or remove TAG for each entry in the region.
14074 This works in the agenda, and also in an org-mode buffer."
14075 (interactive
14076 (list (region-beginning) (region-end)
14077 (let ((org-last-tags-completion-table
14078 (if (derived-mode-p 'org-mode)
14079 (org-get-buffer-tags)
14080 (org-global-tags-completion-table))))
14081 (org-icompleting-read
14082 "Tag: " 'org-tags-completion-function nil nil nil
14083 'org-tags-history))
14084 (progn
14085 (message "[s]et or [r]emove? ")
14086 (equal (read-char-exclusive) ?r))))
14087 (if (fboundp 'deactivate-mark) (deactivate-mark))
14088 (let ((agendap (equal major-mode 'org-agenda-mode))
14089 l1 l2 m buf pos newhead (cnt 0))
14090 (goto-char end)
14091 (setq l2 (1- (org-current-line)))
14092 (goto-char beg)
14093 (setq l1 (org-current-line))
14094 (loop for l from l1 to l2 do
14095 (org-goto-line l)
14096 (setq m (get-text-property (point) 'org-hd-marker))
14097 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14098 (and agendap m))
14099 (setq buf (if agendap (marker-buffer m) (current-buffer))
14100 pos (if agendap m (point)))
14101 (with-current-buffer buf
14102 (save-excursion
14103 (save-restriction
14104 (goto-char pos)
14105 (setq cnt (1+ cnt))
14106 (org-toggle-tag tag (if off 'off 'on))
14107 (setq newhead (org-get-heading)))))
14108 (and agendap (org-agenda-change-all-lines newhead m))))
14109 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14111 (defun org-tags-completion-function (string predicate &optional flag)
14112 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14113 (confirm (lambda (x) (stringp (car x)))))
14114 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14115 (setq s1 (match-string 1 string)
14116 s2 (match-string 2 string))
14117 (setq s1 "" s2 string))
14118 (cond
14119 ((eq flag nil)
14120 ;; try completion
14121 (setq rtn (try-completion s2 ctable confirm))
14122 (if (stringp rtn)
14123 (setq rtn
14124 (concat s1 s2 (substring rtn (length s2))
14125 (if (and org-add-colon-after-tag-completion
14126 (assoc rtn ctable))
14127 ":" ""))))
14128 rtn)
14129 ((eq flag t)
14130 ;; all-completions
14131 (all-completions s2 ctable confirm)
14133 ((eq flag 'lambda)
14134 ;; exact match?
14135 (assoc s2 ctable)))
14138 (defun org-fast-tag-insert (kwd tags face &optional end)
14139 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14140 (insert (format "%-12s" (concat kwd ":"))
14141 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14142 (or end "")))
14144 (defun org-fast-tag-show-exit (flag)
14145 (save-excursion
14146 (org-goto-line 3)
14147 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14148 (replace-match ""))
14149 (when flag
14150 (end-of-line 1)
14151 (org-move-to-column (- (window-width) 19) t)
14152 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14154 (defun org-set-current-tags-overlay (current prefix)
14155 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14156 (if (featurep 'xemacs)
14157 (org-overlay-display org-tags-overlay (concat prefix s)
14158 'secondary-selection)
14159 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14160 (org-overlay-display org-tags-overlay (concat prefix s)))))
14162 (defvar org-last-tag-selection-key nil)
14163 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14164 "Fast tag selection with single keys.
14165 CURRENT is the current list of tags in the headline, INHERITED is the
14166 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14167 possibly with grouping information. TODO-TABLE is a similar table with
14168 TODO keywords, should these have keys assigned to them.
14169 If the keys are nil, a-z are automatically assigned.
14170 Returns the new tags string, or nil to not change the current settings."
14171 (let* ((fulltable (append table todo-table))
14172 (maxlen (apply 'max (mapcar
14173 (lambda (x)
14174 (if (stringp (car x)) (string-width (car x)) 0))
14175 fulltable)))
14176 (buf (current-buffer))
14177 (expert (eq org-fast-tag-selection-single-key 'expert))
14178 (buffer-tags nil)
14179 (fwidth (+ maxlen 3 1 3))
14180 (ncol (/ (- (window-width) 4) fwidth))
14181 (i-face 'org-done)
14182 (c-face 'org-todo)
14183 tg cnt e c char c1 c2 ntable tbl rtn
14184 ov-start ov-end ov-prefix
14185 (exit-after-next org-fast-tag-selection-single-key)
14186 (done-keywords org-done-keywords)
14187 groups ingroup)
14188 (save-excursion
14189 (beginning-of-line 1)
14190 (if (looking-at
14191 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14192 (setq ov-start (match-beginning 1)
14193 ov-end (match-end 1)
14194 ov-prefix "")
14195 (setq ov-start (1- (point-at-eol))
14196 ov-end (1+ ov-start))
14197 (skip-chars-forward "^\n\r")
14198 (setq ov-prefix
14199 (concat
14200 (buffer-substring (1- (point)) (point))
14201 (if (> (current-column) org-tags-column)
14203 (make-string (- org-tags-column (current-column)) ?\ ))))))
14204 (move-overlay org-tags-overlay ov-start ov-end)
14205 (save-window-excursion
14206 (if expert
14207 (set-buffer (get-buffer-create " *Org tags*"))
14208 (delete-other-windows)
14209 (split-window-vertically)
14210 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14211 (erase-buffer)
14212 (org-set-local 'org-done-keywords done-keywords)
14213 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14214 (org-fast-tag-insert "Current" current c-face "\n\n")
14215 (org-fast-tag-show-exit exit-after-next)
14216 (org-set-current-tags-overlay current ov-prefix)
14217 (setq tbl fulltable char ?a cnt 0)
14218 (while (setq e (pop tbl))
14219 (cond
14220 ((equal (car e) :startgroup)
14221 (push '() groups) (setq ingroup t)
14222 (when (not (= cnt 0))
14223 (setq cnt 0)
14224 (insert "\n"))
14225 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14226 ((equal (car e) :endgroup)
14227 (setq ingroup nil cnt 0)
14228 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14229 ((equal e '(:newline))
14230 (when (not (= cnt 0))
14231 (setq cnt 0)
14232 (insert "\n")
14233 (setq e (car tbl))
14234 (while (equal (car tbl) '(:newline))
14235 (insert "\n")
14236 (setq tbl (cdr tbl)))))
14238 (setq tg (copy-sequence (car e)) c2 nil)
14239 (if (cdr e)
14240 (setq c (cdr e))
14241 ;; automatically assign a character.
14242 (setq c1 (string-to-char
14243 (downcase (substring
14244 tg (if (= (string-to-char tg) ?@) 1 0)))))
14245 (if (or (rassoc c1 ntable) (rassoc c1 table))
14246 (while (or (rassoc char ntable) (rassoc char table))
14247 (setq char (1+ char)))
14248 (setq c2 c1))
14249 (setq c (or c2 char)))
14250 (if ingroup (push tg (car groups)))
14251 (setq tg (org-add-props tg nil 'face
14252 (cond
14253 ((not (assoc tg table))
14254 (org-get-todo-face tg))
14255 ((member tg current) c-face)
14256 ((member tg inherited) i-face))))
14257 (if (and (= cnt 0) (not ingroup)) (insert " "))
14258 (insert "[" c "] " tg (make-string
14259 (- fwidth 4 (length tg)) ?\ ))
14260 (push (cons tg c) ntable)
14261 (when (= (setq cnt (1+ cnt)) ncol)
14262 (insert "\n")
14263 (if ingroup (insert " "))
14264 (setq cnt 0)))))
14265 (setq ntable (nreverse ntable))
14266 (insert "\n")
14267 (goto-char (point-min))
14268 (if (not expert) (org-fit-window-to-buffer))
14269 (setq rtn
14270 (catch 'exit
14271 (while t
14272 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14273 (if (not groups) "no " "")
14274 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14275 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14276 (setq org-last-tag-selection-key c)
14277 (cond
14278 ((= c ?\r) (throw 'exit t))
14279 ((= c ?!)
14280 (setq groups (not groups))
14281 (goto-char (point-min))
14282 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14283 ((= c ?\C-c)
14284 (if (not expert)
14285 (org-fast-tag-show-exit
14286 (setq exit-after-next (not exit-after-next)))
14287 (setq expert nil)
14288 (delete-other-windows)
14289 (set-window-buffer (split-window-vertically) " *Org tags*")
14290 (org-switch-to-buffer-other-window " *Org tags*")
14291 (org-fit-window-to-buffer)))
14292 ((or (= c ?\C-g)
14293 (and (= c ?q) (not (rassoc c ntable))))
14294 (org-detach-overlay org-tags-overlay)
14295 (setq quit-flag t))
14296 ((= c ?\ )
14297 (setq current nil)
14298 (if exit-after-next (setq exit-after-next 'now)))
14299 ((= c ?\t)
14300 (condition-case nil
14301 (setq tg (org-icompleting-read
14302 "Tag: "
14303 (or buffer-tags
14304 (with-current-buffer buf
14305 (org-get-buffer-tags)))))
14306 (quit (setq tg "")))
14307 (when (string-match "\\S-" tg)
14308 (add-to-list 'buffer-tags (list tg))
14309 (if (member tg current)
14310 (setq current (delete tg current))
14311 (push tg current)))
14312 (if exit-after-next (setq exit-after-next 'now)))
14313 ((setq e (rassoc c todo-table) tg (car e))
14314 (with-current-buffer buf
14315 (save-excursion (org-todo tg)))
14316 (if exit-after-next (setq exit-after-next 'now)))
14317 ((setq e (rassoc c ntable) tg (car e))
14318 (if (member tg current)
14319 (setq current (delete tg current))
14320 (loop for g in groups do
14321 (if (member tg g)
14322 (mapc (lambda (x)
14323 (setq current (delete x current)))
14324 g)))
14325 (push tg current))
14326 (if exit-after-next (setq exit-after-next 'now))))
14328 ;; Create a sorted list
14329 (setq current
14330 (sort current
14331 (lambda (a b)
14332 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14333 (if (eq exit-after-next 'now) (throw 'exit t))
14334 (goto-char (point-min))
14335 (beginning-of-line 2)
14336 (delete-region (point) (point-at-eol))
14337 (org-fast-tag-insert "Current" current c-face)
14338 (org-set-current-tags-overlay current ov-prefix)
14339 (while (re-search-forward
14340 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14341 (setq tg (match-string 1))
14342 (add-text-properties
14343 (match-beginning 1) (match-end 1)
14344 (list 'face
14345 (cond
14346 ((member tg current) c-face)
14347 ((member tg inherited) i-face)
14348 (t (get-text-property (match-beginning 1) 'face))))))
14349 (goto-char (point-min)))))
14350 (org-detach-overlay org-tags-overlay)
14351 (if rtn
14352 (mapconcat 'identity current ":")
14353 nil))))
14355 (defun org-get-tags-string ()
14356 "Get the TAGS string in the current headline."
14357 (unless (org-at-heading-p t)
14358 (error "Not on a heading"))
14359 (save-excursion
14360 (beginning-of-line 1)
14361 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14362 (org-match-string-no-properties 1)
14363 "")))
14365 (defun org-get-tags ()
14366 "Get the list of tags specified in the current headline."
14367 (org-split-string (org-get-tags-string) ":"))
14369 (defun org-get-buffer-tags ()
14370 "Get a table of all tags used in the buffer, for completion."
14371 (let (tags)
14372 (save-excursion
14373 (goto-char (point-min))
14374 (while (re-search-forward
14375 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14376 (when (equal (char-after (point-at-bol 0)) ?*)
14377 (mapc (lambda (x) (add-to-list 'tags x))
14378 (org-split-string (org-match-string-no-properties 1) ":")))))
14379 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14380 (mapcar 'list tags)))
14382 ;;;; The mapping API
14384 (defun org-map-entries (func &optional match scope &rest skip)
14385 "Call FUNC at each headline selected by MATCH in SCOPE.
14387 FUNC is a function or a lisp form. The function will be called without
14388 arguments, with the cursor positioned at the beginning of the headline.
14389 The return values of all calls to the function will be collected and
14390 returned as a list.
14392 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14393 does not need to preserve point. After evaluation, the cursor will be
14394 moved to the end of the line (presumably of the headline of the
14395 processed entry) and search continues from there. Under some
14396 circumstances, this may not produce the wanted results. For example,
14397 if you have removed (e.g. archived) the current (sub)tree it could
14398 mean that the next entry will be skipped entirely. In such cases, you
14399 can specify the position from where search should continue by making
14400 FUNC set the variable `org-map-continue-from' to the desired buffer
14401 position.
14403 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14404 Only headlines that are matched by this query will be considered during
14405 the iteration. When MATCH is nil or t, all headlines will be
14406 visited by the iteration.
14408 SCOPE determines the scope of this command. It can be any of:
14410 nil The current buffer, respecting the restriction if any
14411 tree The subtree started with the entry at point
14412 region The entries within the active region, if any
14413 region-start-level
14414 The entries within the active region, but only those at
14415 the same level than the first one.
14416 file The current buffer, without restriction
14417 file-with-archives
14418 The current buffer, and any archives associated with it
14419 agenda All agenda files
14420 agenda-with-archives
14421 All agenda files with any archive files associated with them
14422 \(file1 file2 ...)
14423 If this is a list, all files in the list will be scanned
14425 The remaining args are treated as settings for the skipping facilities of
14426 the scanner. The following items can be given here:
14428 archive skip trees with the archive tag.
14429 comment skip trees with the COMMENT keyword
14430 function or Emacs Lisp form:
14431 will be used as value for `org-agenda-skip-function', so whenever
14432 the function returns t, FUNC will not be called for that
14433 entry and search will continue from the point where the
14434 function leaves it.
14436 If your function needs to retrieve the tags including inherited tags
14437 at the *current* entry, you can use the value of the variable
14438 `org-scanner-tags' which will be much faster than getting the value
14439 with `org-get-tags-at'. If your function gets properties with
14440 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14441 to t around the call to `org-entry-properties' to get the same speedup.
14442 Note that if your function moves around to retrieve tags and properties at
14443 a *different* entry, you cannot use these techniques."
14444 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14445 (not (org-region-active-p)))
14446 (let* ((org-agenda-archives-mode nil) ; just to make sure
14447 (org-agenda-skip-archived-trees (memq 'archive skip))
14448 (org-agenda-skip-comment-trees (memq 'comment skip))
14449 (org-agenda-skip-function
14450 (car (org-delete-all '(comment archive) skip)))
14451 (org-tags-match-list-sublevels t)
14452 (start-level (eq scope 'region-start-level))
14453 matcher file res
14454 org-todo-keywords-for-agenda
14455 org-done-keywords-for-agenda
14456 org-todo-keyword-alist-for-agenda
14457 org-drawers-for-agenda
14458 org-tag-alist-for-agenda
14459 todo-only)
14461 (cond
14462 ((eq match t) (setq matcher t))
14463 ((eq match nil) (setq matcher t))
14464 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14466 (save-excursion
14467 (save-restriction
14468 (cond ((eq scope 'tree)
14469 (org-back-to-heading t)
14470 (org-narrow-to-subtree)
14471 (setq scope nil))
14472 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14473 (org-region-active-p))
14474 ;; If needed, set start-level to a string like "2"
14475 (when start-level
14476 (save-excursion
14477 (goto-char (region-beginning))
14478 (unless (org-at-heading-p) (outline-next-heading))
14479 (setq start-level (org-current-level))))
14480 (narrow-to-region (region-beginning)
14481 (save-excursion
14482 (goto-char (region-end))
14483 (unless (and (bolp) (org-at-heading-p))
14484 (outline-next-heading))
14485 (point)))
14486 (setq scope nil)))
14488 (if (not scope)
14489 (progn
14490 (org-agenda-prepare-buffers
14491 (list (buffer-file-name (current-buffer))))
14492 (setq res (org-scan-tags func matcher todo-only start-level)))
14493 ;; Get the right scope
14494 (cond
14495 ((and scope (listp scope) (symbolp (car scope)))
14496 (setq scope (eval scope)))
14497 ((eq scope 'agenda)
14498 (setq scope (org-agenda-files t)))
14499 ((eq scope 'agenda-with-archives)
14500 (setq scope (org-agenda-files t))
14501 (setq scope (org-add-archive-files scope)))
14502 ((eq scope 'file)
14503 (setq scope (list (buffer-file-name))))
14504 ((eq scope 'file-with-archives)
14505 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14506 (org-agenda-prepare-buffers scope)
14507 (while (setq file (pop scope))
14508 (with-current-buffer (org-find-base-buffer-visiting file)
14509 (save-excursion
14510 (save-restriction
14511 (widen)
14512 (goto-char (point-min))
14513 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14514 res)))
14516 ;;;; Properties
14518 ;;; Setting and retrieving properties
14520 (defconst org-special-properties
14521 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14522 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14523 "The special properties valid in Org-mode.
14525 These are properties that are not defined in the property drawer,
14526 but in some other way.")
14528 (defconst org-default-properties
14529 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14530 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14531 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14532 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14533 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14534 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14535 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14536 "Some properties that are used by Org-mode for various purposes.
14537 Being in this list makes sure that they are offered for completion.")
14539 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14540 "Regular expression matching the first line of a property drawer.")
14542 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14543 "Regular expression matching the last line of a property drawer.")
14545 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14546 "Regular expression matching the first line of a property drawer.")
14548 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14549 "Regular expression matching the first line of a property drawer.")
14551 (defconst org-property-drawer-re
14552 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14553 org-property-end-re "\\)\n?")
14554 "Matches an entire property drawer.")
14556 (defconst org-clock-drawer-re
14557 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14558 org-property-end-re "\\)\n?")
14559 "Matches an entire clock drawer.")
14561 (defsubst org-re-property (property)
14562 "Return a regexp matching a PROPERTY line.
14563 Match group 1 will be set to the value."
14564 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14566 (defsubst org-re-property-keyword (property)
14567 "Return a regexp matching a PROPERTY line, possibly with no
14568 value for the property."
14569 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14571 (defun org-property-action ()
14572 "Do an action on properties."
14573 (interactive)
14574 (let (c)
14575 (org-at-property-p)
14576 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14577 (setq c (read-char-exclusive))
14578 (cond
14579 ((equal c ?s)
14580 (call-interactively 'org-set-property))
14581 ((equal c ?d)
14582 (call-interactively 'org-delete-property))
14583 ((equal c ?D)
14584 (call-interactively 'org-delete-property-globally))
14585 ((equal c ?c)
14586 (call-interactively 'org-compute-property-at-point))
14587 (t (error "No such property action %c" c)))))
14589 (defun org-inc-effort ()
14590 "Increment the value of the effort property in the current entry."
14591 (interactive)
14592 (org-set-effort nil t))
14594 (defun org-set-effort (&optional value increment)
14595 "Set the effort property of the current entry.
14596 With numerical prefix arg, use the nth allowed value, 0 stands for the
14597 10th allowed value.
14599 When INCREMENT is non-nil, set the property to the next allowed value."
14600 (interactive "P")
14601 (if (equal value 0) (setq value 10))
14602 (let* ((completion-ignore-case t)
14603 (prop org-effort-property)
14604 (cur (org-entry-get nil prop))
14605 (allowed (org-property-get-allowed-values nil prop 'table))
14606 (existing (mapcar 'list (org-property-values prop)))
14608 (val (cond
14609 ((stringp value) value)
14610 ((and allowed (integerp value))
14611 (or (car (nth (1- value) allowed))
14612 (car (org-last allowed))))
14613 ((and allowed increment)
14614 (or (caadr (member (list cur) allowed))
14615 (error "Allowed effort values are not set")))
14616 (allowed
14617 (message "Select 1-9,0, [RET%s]: %s"
14618 (if cur (concat "=" cur) "")
14619 (mapconcat 'car allowed " "))
14620 (setq rpl (read-char-exclusive))
14621 (if (equal rpl ?\r)
14623 (setq rpl (- rpl ?0))
14624 (if (equal rpl 0) (setq rpl 10))
14625 (if (and (> rpl 0) (<= rpl (length allowed)))
14626 (car (nth (1- rpl) allowed))
14627 (org-completing-read "Effort: " allowed nil))))
14629 (let (org-completion-use-ido org-completion-use-iswitchb)
14630 (org-completing-read
14631 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14632 (concat "[" cur "]") "")
14633 ": ")
14634 existing nil nil "" nil cur))))))
14635 (unless (equal (org-entry-get nil prop) val)
14636 (org-entry-put nil prop val))
14637 (save-excursion
14638 (org-back-to-heading t)
14639 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14640 (message "%s is now %s" prop val)))
14642 (defun org-at-property-p ()
14643 "Is cursor inside a property drawer?"
14644 (save-excursion
14645 (beginning-of-line 1)
14646 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14647 (save-match-data ;; Used by calling procedures
14648 (let ((p (point))
14649 (range (unless (org-before-first-heading-p)
14650 (org-get-property-block))))
14651 (and range (<= (car range) p) (< p (cdr range))))))))
14653 (defun org-get-property-block (&optional beg end force)
14654 "Return the (beg . end) range of the body of the property drawer.
14655 BEG and END are the beginning and end of the current subtree, or of
14656 the part before the first headline. If they are not given, they will
14657 be found. If the drawer does not exist and FORCE is non-nil, create
14658 the drawer."
14659 (catch 'exit
14660 (save-excursion
14661 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14662 (progn (org-back-to-heading t) (point))))
14663 (end (or end (and (not (outline-next-heading)) (point-max))
14664 (point))))
14665 (goto-char beg)
14666 (if (re-search-forward org-property-start-re end t)
14667 (setq beg (1+ (match-end 0)))
14668 (if force
14669 (save-excursion
14670 (org-insert-property-drawer)
14671 (setq end (progn (outline-next-heading) (point))))
14672 (throw 'exit nil))
14673 (goto-char beg)
14674 (if (re-search-forward org-property-start-re end t)
14675 (setq beg (1+ (match-end 0)))))
14676 (if (re-search-forward org-property-end-re end t)
14677 (setq end (match-beginning 0))
14678 (or force (throw 'exit nil))
14679 (goto-char beg)
14680 (setq end beg)
14681 (org-indent-line)
14682 (insert ":END:\n"))
14683 (cons beg end)))))
14685 (defun org-entry-properties (&optional pom which specific)
14686 "Get all properties of the entry at point-or-marker POM.
14687 This includes the TODO keyword, the tags, time strings for deadline,
14688 scheduled, and clocking, and any additional properties defined in the
14689 entry. The return value is an alist, keys may occur multiple times
14690 if the property key was used several times.
14691 POM may also be nil, in which case the current entry is used.
14692 If WHICH is nil or `all', get all properties. If WHICH is
14693 `special' or `standard', only get that subclass. If WHICH
14694 is a string only get exactly this property. SPECIFIC can be a string, the
14695 specific property we are interested in. Specifying it can speed
14696 things up because then unnecessary parsing is avoided."
14697 (setq which (or which 'all))
14698 (org-with-point-at pom
14699 (let ((clockstr (substring org-clock-string 0 -1))
14700 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14701 (case-fold-search nil)
14702 beg end range props sum-props key key1 value string clocksum clocksumt)
14703 (save-excursion
14704 (when (condition-case nil
14705 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14706 (error nil))
14707 (setq beg (point))
14708 (setq sum-props (get-text-property (point) 'org-summaries))
14709 (setq clocksum (get-text-property (point) :org-clock-minutes)
14710 clocksumt (get-text-property (point) :org-clock-minutes-today))
14711 (outline-next-heading)
14712 (setq end (point))
14713 (when (memq which '(all special))
14714 ;; Get the special properties, like TODO and tags
14715 (goto-char beg)
14716 (when (and (or (not specific) (string= specific "TODO"))
14717 (looking-at org-todo-line-regexp) (match-end 2))
14718 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14719 (when (and (or (not specific) (string= specific "PRIORITY"))
14720 (looking-at org-priority-regexp))
14721 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14722 (when (or (not specific) (string= specific "FILE"))
14723 (push (cons "FILE" buffer-file-name) props))
14724 (when (and (or (not specific) (string= specific "TAGS"))
14725 (setq value (org-get-tags-string))
14726 (string-match "\\S-" value))
14727 (push (cons "TAGS" value) props))
14728 (when (and (or (not specific) (string= specific "ALLTAGS"))
14729 (setq value (org-get-tags-at)))
14730 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14731 ":"))
14732 props))
14733 (when (or (not specific) (string= specific "BLOCKED"))
14734 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14735 (when (or (not specific)
14736 (member specific
14737 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14738 "TIMESTAMP" "TIMESTAMP_IA")))
14739 (catch 'match
14740 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14741 (setq key (if (match-end 1)
14742 (substring (org-match-string-no-properties 1)
14743 0 -1))
14744 string (if (equal key clockstr)
14745 (org-trim
14746 (buffer-substring-no-properties
14747 (match-beginning 3) (goto-char
14748 (point-at-eol))))
14749 (substring (org-match-string-no-properties 3)
14750 1 -1)))
14751 ;; Get the correct property name from the key. This is
14752 ;; necessary if the user has configured time keywords.
14753 (setq key1 (concat key ":"))
14754 (cond
14755 ((not key)
14756 (setq key
14757 (if (= (char-after (match-beginning 3)) ?\[)
14758 "TIMESTAMP_IA" "TIMESTAMP")))
14759 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14760 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14761 ((equal key1 org-closed-string) (setq key "CLOSED"))
14762 ((equal key1 org-clock-string) (setq key "CLOCK")))
14763 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14764 (progn
14765 (push (cons key string) props)
14766 ;; no need to search further if match is found
14767 (throw 'match t))
14768 (when (or (equal key "CLOCK") (not (assoc key props)))
14769 (push (cons key string) props)))))))
14771 (when (memq which '(all standard))
14772 ;; Get the standard properties, like :PROP: ...
14773 (setq range (org-get-property-block beg end))
14774 (when range
14775 (goto-char (car range))
14776 (while (re-search-forward
14777 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14778 (cdr range) t)
14779 (setq key (org-match-string-no-properties 1)
14780 value (org-trim (or (org-match-string-no-properties 2) "")))
14781 (unless (member key excluded)
14782 (push (cons key (or value "")) props)))))
14783 (if clocksum
14784 (push (cons "CLOCKSUM"
14785 (org-columns-number-to-string (/ (float clocksum) 60.)
14786 'add_times))
14787 props))
14788 (if clocksumt
14789 (push (cons "CLOCKSUM_T"
14790 (org-columns-number-to-string (/ (float clocksumt) 60.)
14791 'add_times))
14792 props))
14793 (unless (assoc "CATEGORY" props)
14794 (push (cons "CATEGORY" (org-get-category)) props))
14795 (append sum-props (nreverse props)))))))
14797 (defun org-entry-get (pom property &optional inherit literal-nil)
14798 "Get value of PROPERTY for entry or content at point-or-marker POM.
14799 If INHERIT is non-nil and the entry does not have the property,
14800 then also check higher levels of the hierarchy.
14801 If INHERIT is the symbol `selective', use inheritance only if the setting
14802 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14803 If the property is present but empty, the return value is the empty string.
14804 If the property is not present at all, nil is returned.
14806 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14807 do not interpret it as the list atom nil. This is used for inheritance
14808 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14809 (org-with-point-at pom
14810 (if (and inherit (if (eq inherit 'selective)
14811 (org-property-inherit-p property)
14813 (org-entry-get-with-inheritance property literal-nil)
14814 (if (member property org-special-properties)
14815 ;; We need a special property. Use `org-entry-properties' to
14816 ;; retrieve it, but specify the wanted property
14817 (cdr (assoc property (org-entry-properties nil 'special property)))
14818 (let ((range (org-get-property-block)))
14819 (when (and range (not (eq (car range) (cdr range))))
14820 (let* ((props (list (or (assoc property org-file-properties)
14821 (assoc property org-global-properties)
14822 (assoc property org-global-properties-fixed))))
14823 (ap (lambda (key)
14824 (when (re-search-forward
14825 (org-re-property key) (cdr range) t)
14826 (setq props
14827 (org-update-property-plist
14829 (if (match-end 1)
14830 (org-match-string-no-properties 1) "")
14831 props)))))
14832 val)
14833 (goto-char (car range))
14834 (funcall ap property)
14835 (goto-char (car range))
14836 (while (funcall ap (concat property "+")))
14837 (setq val (cdr (assoc property props)))
14838 (when val (if literal-nil val (org-not-nil val))))))))))
14840 (defun org-property-or-variable-value (var &optional inherit)
14841 "Check if there is a property fixing the value of VAR.
14842 If yes, return this value. If not, return the current value of the variable."
14843 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14844 (if (and prop (stringp prop) (string-match "\\S-" prop))
14845 (read prop)
14846 (symbol-value var))))
14848 (defun org-entry-delete (pom property)
14849 "Delete the property PROPERTY from entry at point-or-marker POM."
14850 (org-with-point-at pom
14851 (if (member property org-special-properties)
14852 nil ; cannot delete these properties.
14853 (let ((range (org-get-property-block)))
14854 (if (and range
14855 (goto-char (car range))
14856 (re-search-forward
14857 (org-re-property property)
14858 (cdr range) t))
14859 (progn
14860 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14862 nil)))))
14864 ;; Multi-values properties are properties that contain multiple values
14865 ;; These values are assumed to be single words, separated by whitespace.
14866 (defun org-entry-add-to-multivalued-property (pom property value)
14867 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14868 (let* ((old (org-entry-get pom property))
14869 (values (and old (org-split-string old "[ \t]"))))
14870 (setq value (org-entry-protect-space value))
14871 (unless (member value values)
14872 (setq values (cons value values))
14873 (org-entry-put pom property
14874 (mapconcat 'identity values " ")))))
14876 (defun org-entry-remove-from-multivalued-property (pom property value)
14877 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14878 (let* ((old (org-entry-get pom property))
14879 (values (and old (org-split-string old "[ \t]"))))
14880 (setq value (org-entry-protect-space value))
14881 (when (member value values)
14882 (setq values (delete value values))
14883 (org-entry-put pom property
14884 (mapconcat 'identity values " ")))))
14886 (defun org-entry-member-in-multivalued-property (pom property value)
14887 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14888 (let* ((old (org-entry-get pom property))
14889 (values (and old (org-split-string old "[ \t]"))))
14890 (setq value (org-entry-protect-space value))
14891 (member value values)))
14893 (defun org-entry-get-multivalued-property (pom property)
14894 "Return a list of values in a multivalued property."
14895 (let* ((value (org-entry-get pom property))
14896 (values (and value (org-split-string value "[ \t]"))))
14897 (mapcar 'org-entry-restore-space values)))
14899 (defun org-entry-put-multivalued-property (pom property &rest values)
14900 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14901 VALUES should be a list of strings. Spaces will be protected."
14902 (org-entry-put pom property
14903 (mapconcat 'org-entry-protect-space values " "))
14904 (let* ((value (org-entry-get pom property))
14905 (values (and value (org-split-string value "[ \t]"))))
14906 (mapcar 'org-entry-restore-space values)))
14908 (defun org-entry-protect-space (s)
14909 "Protect spaces and newline in string S."
14910 (while (string-match " " s)
14911 (setq s (replace-match "%20" t t s)))
14912 (while (string-match "\n" s)
14913 (setq s (replace-match "%0A" t t s)))
14916 (defun org-entry-restore-space (s)
14917 "Restore spaces and newline in string S."
14918 (while (string-match "%20" s)
14919 (setq s (replace-match " " t t s)))
14920 (while (string-match "%0A" s)
14921 (setq s (replace-match "\n" t t s)))
14924 (defvar org-entry-property-inherited-from (make-marker)
14925 "Marker pointing to the entry from where a property was inherited.
14926 Each call to `org-entry-get-with-inheritance' will set this marker to the
14927 location of the entry where the inheritance search matched. If there was
14928 no match, the marker will point nowhere.
14929 Note that also `org-entry-get' calls this function, if the INHERIT flag
14930 is set.")
14932 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14933 "Get PROPERTY of entry or content at point, search higher levels if needed.
14934 The search will stop at the first ancestor which has the property defined.
14935 If the value found is \"nil\", return nil to show that the property
14936 should be considered as undefined (this is the meaning of nil here).
14937 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14938 (move-marker org-entry-property-inherited-from nil)
14939 (let (tmp)
14940 (save-excursion
14941 (save-restriction
14942 (widen)
14943 (catch 'ex
14944 (while t
14945 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14946 (or (ignore-errors (org-back-to-heading t))
14947 (goto-char (point-min)))
14948 (move-marker org-entry-property-inherited-from (point))
14949 (throw 'ex tmp))
14950 (or (ignore-errors (org-up-heading-safe))
14951 (throw 'ex nil))))))
14952 (setq tmp (or tmp
14953 (cdr (assoc property org-file-properties))
14954 (cdr (assoc property org-global-properties))
14955 (cdr (assoc property org-global-properties-fixed))))
14956 (if literal-nil tmp (org-not-nil tmp))))
14958 (defvar org-property-changed-functions nil
14959 "Hook called when the value of a property has changed.
14960 Each hook function should accept two arguments, the name of the property
14961 and the new value.")
14963 (defun org-entry-put (pom property value)
14964 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14965 (org-with-point-at pom
14966 (org-back-to-heading t)
14967 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14968 range)
14969 (cond
14970 ((equal property "TODO")
14971 (when (and (stringp value) (string-match "\\S-" value)
14972 (not (member value org-todo-keywords-1)))
14973 (error "\"%s\" is not a valid TODO state" value))
14974 (if (or (not value)
14975 (not (string-match "\\S-" value)))
14976 (setq value 'none))
14977 (org-todo value)
14978 (org-set-tags nil 'align))
14979 ((equal property "PRIORITY")
14980 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14981 (string-to-char value) ?\ ))
14982 (org-set-tags nil 'align))
14983 ((equal property "CLOCKSUM")
14984 (if (not (re-search-forward
14985 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14986 (error "Cannot find a clock log")
14987 (goto-char (- (match-end 1) 2))
14988 (cond
14989 ((eq value 'earlier) (org-timestamp-down))
14990 ((eq value 'later) (org-timestamp-up)))
14991 (org-clock-sum-current-item)))
14992 ((equal property "SCHEDULED")
14993 (if (re-search-forward org-scheduled-time-regexp end t)
14994 (cond
14995 ((eq value 'earlier) (org-timestamp-change -1 'day))
14996 ((eq value 'later) (org-timestamp-change 1 'day))
14997 (t (call-interactively 'org-schedule)))
14998 (call-interactively 'org-schedule)))
14999 ((equal property "DEADLINE")
15000 (if (re-search-forward org-deadline-time-regexp end t)
15001 (cond
15002 ((eq value 'earlier) (org-timestamp-change -1 'day))
15003 ((eq value 'later) (org-timestamp-change 1 'day))
15004 (t (call-interactively 'org-deadline)))
15005 (call-interactively 'org-deadline)))
15006 ((member property org-special-properties)
15007 (error "The %s property can not yet be set with `org-entry-put'"
15008 property))
15009 (t ; a non-special property
15010 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15011 (setq range (org-get-property-block beg end 'force))
15012 (goto-char (car range))
15013 (if (re-search-forward
15014 (org-re-property-keyword property) (cdr range) t)
15015 (progn
15016 (delete-region (match-beginning 0) (match-end 0))
15017 (goto-char (match-beginning 0)))
15018 (goto-char (cdr range))
15019 (insert "\n")
15020 (backward-char 1)
15021 (org-indent-line))
15022 (insert ":" property ":")
15023 (and value (insert " " value))
15024 (org-indent-line)))))
15025 (run-hook-with-args 'org-property-changed-functions property value)))
15027 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15028 "Get all property keys in the current buffer.
15029 With INCLUDE-SPECIALS, also list the special properties that reflect things
15030 like tags and TODO state.
15031 With INCLUDE-DEFAULTS, also include properties that has special meaning
15032 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15033 and others.
15034 With INCLUDE-COLUMNS, also include property names given in COLUMN
15035 formats in the current buffer."
15036 (let (rtn range cfmt s p)
15037 (save-excursion
15038 (save-restriction
15039 (widen)
15040 (goto-char (point-min))
15041 (while (re-search-forward org-property-start-re nil t)
15042 (setq range (org-get-property-block))
15043 (goto-char (car range))
15044 (while (re-search-forward
15045 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15046 (cdr range) t)
15047 (add-to-list 'rtn (org-match-string-no-properties 1)))
15048 (outline-next-heading))))
15050 (when include-specials
15051 (setq rtn (append org-special-properties rtn)))
15053 (when include-defaults
15054 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15055 (add-to-list 'rtn org-effort-property))
15057 (when include-columns
15058 (save-excursion
15059 (save-restriction
15060 (widen)
15061 (goto-char (point-min))
15062 (while (re-search-forward
15063 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15064 nil t)
15065 (setq cfmt (match-string 2) s 0)
15066 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15067 cfmt s)
15068 (setq s (match-end 0)
15069 p (match-string 1 cfmt))
15070 (unless (or (equal p "ITEM")
15071 (member p org-special-properties))
15072 (add-to-list 'rtn (match-string 1 cfmt))))))))
15074 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15076 (defun org-property-values (key)
15077 "Return a list of all values of property KEY in the current buffer."
15078 (save-excursion
15079 (save-restriction
15080 (widen)
15081 (goto-char (point-min))
15082 (let ((re (org-re-property key))
15083 values)
15084 (while (re-search-forward re nil t)
15085 (add-to-list 'values (org-trim (match-string 1))))
15086 (delete "" values)))))
15088 (defun org-insert-property-drawer ()
15089 "Insert a property drawer into the current entry."
15090 (org-back-to-heading t)
15091 (looking-at org-outline-regexp)
15092 (let ((indent (if org-adapt-indentation
15093 (- (match-end 0) (match-beginning 0))
15095 (beg (point))
15096 (re (concat "^[ \t]*" org-keyword-time-regexp))
15097 end hiddenp)
15098 (outline-next-heading)
15099 (setq end (point))
15100 (goto-char beg)
15101 (while (re-search-forward re end t))
15102 (setq hiddenp (outline-invisible-p))
15103 (end-of-line 1)
15104 (and (equal (char-after) ?\n) (forward-char 1))
15105 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15106 (if (member (match-string 1) '("CLOCK:" ":END:"))
15107 ;; just skip this line
15108 (beginning-of-line 2)
15109 ;; Drawer start, find the end
15110 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15111 (beginning-of-line 1)))
15112 (org-skip-over-state-notes)
15113 (skip-chars-backward " \t\n\r")
15114 (if (eq (char-before) ?*) (forward-char 1))
15115 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15116 (beginning-of-line 0)
15117 (org-indent-to-column indent)
15118 (beginning-of-line 2)
15119 (org-indent-to-column indent)
15120 (beginning-of-line 0)
15121 (if hiddenp
15122 (save-excursion
15123 (org-back-to-heading t)
15124 (hide-entry))
15125 (org-flag-drawer t))))
15127 (defun org-insert-drawer (&optional arg drawer)
15128 "Insert a drawer at point.
15130 Optional argument DRAWER, when non-nil, is a string representing
15131 drawer's name. Otherwise, the user is prompted for a name.
15133 If a region is active, insert the drawer around that region
15134 instead.
15136 Point is left between drawer's boundaries."
15137 (interactive "P")
15138 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15139 "LOGBOOK"))
15140 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15141 ;; internally by Org. They are meant to be inserted
15142 ;; automatically.
15143 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15144 ;; Remove system drawers from list. Note: For some reason,
15145 ;; `org-completing-read' ignores the predicate while
15146 ;; `completing-read' handles it fine.
15147 (drawer (if arg "PROPERTIES"
15148 (or drawer
15149 (completing-read
15150 "Drawer: " org-drawers
15151 (lambda (d) (not (member d system-drawers))))))))
15152 (cond
15153 ;; With C-u, fall back on `org-insert-property-drawer'
15154 (arg (org-insert-property-drawer))
15155 ;; With an active region, insert a drawer at point.
15156 ((not (org-region-active-p))
15157 (progn
15158 (unless (bolp) (insert "\n"))
15159 (insert (format ":%s:\n\n:END:\n" drawer))
15160 (forward-line -2)))
15161 ;; Otherwise, insert the drawer at point
15163 (let ((rbeg (region-beginning))
15164 (rend (copy-marker (region-end))))
15165 (unwind-protect
15166 (progn
15167 (goto-char rbeg)
15168 (beginning-of-line)
15169 (when (save-excursion
15170 (re-search-forward org-outline-regexp-bol rend t))
15171 (error "Drawers cannot contain headlines"))
15172 ;; Position point at the beginning of the first
15173 ;; non-blank line in region. Insert drawer's opening
15174 ;; there, then indent it.
15175 (org-skip-whitespace)
15176 (beginning-of-line)
15177 (insert ":" drawer ":\n")
15178 (forward-line -1)
15179 (indent-for-tab-command)
15180 ;; Move point to the beginning of the first blank line
15181 ;; after the last non-blank line in region. Insert
15182 ;; drawer's closing, then indent it.
15183 (goto-char rend)
15184 (skip-chars-backward " \r\t\n")
15185 (insert "\n:END:")
15186 (deactivate-mark t)
15187 (indent-for-tab-command)
15188 (unless (eolp) (insert "\n")))
15189 ;; Clear marker, whatever the outcome of insertion is.
15190 (set-marker rend nil)))))))
15192 (defvar org-property-set-functions-alist nil
15193 "Property set function alist.
15194 Each entry should have the following format:
15196 (PROPERTY . READ-FUNCTION)
15198 The read function will be called with the same argument as
15199 `org-completing-read'.")
15201 (defun org-set-property-function (property)
15202 "Get the function that should be used to set PROPERTY.
15203 This is computed according to `org-property-set-functions-alist'."
15204 (or (cdr (assoc property org-property-set-functions-alist))
15205 'org-completing-read))
15207 (defun org-read-property-value (property)
15208 "Read PROPERTY value from user."
15209 (let* ((completion-ignore-case t)
15210 (allowed (org-property-get-allowed-values nil property 'table))
15211 (cur (org-entry-get nil property))
15212 (prompt (concat property " value"
15213 (if (and cur (string-match "\\S-" cur))
15214 (concat " [" cur "]") "") ": "))
15215 (set-function (org-set-property-function property))
15216 (val (if allowed
15217 (funcall set-function prompt allowed nil
15218 (not (get-text-property 0 'org-unrestricted
15219 (caar allowed))))
15220 (let (org-completion-use-ido org-completion-use-iswitchb)
15221 (funcall set-function prompt
15222 (mapcar 'list (org-property-values property))
15223 nil nil "" nil cur)))))
15224 (if (equal val "")
15226 val)))
15228 (defvar org-last-set-property nil)
15229 (defvar org-last-set-property-value nil)
15230 (defun org-read-property-name ()
15231 "Read a property name."
15232 (let* ((completion-ignore-case t)
15233 (keys (org-buffer-property-keys nil t t))
15234 (default-prop (or (save-excursion
15235 (save-match-data
15236 (beginning-of-line)
15237 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15238 (null (string= (match-string 1) "END"))
15239 (match-string 1))))
15240 org-last-set-property))
15241 (property (org-icompleting-read
15242 (concat "Property"
15243 (if default-prop (concat " [" default-prop "]") "")
15244 ": ")
15245 (mapcar 'list keys)
15246 nil nil nil nil
15247 default-prop)))
15248 (if (member property keys)
15249 property
15250 (or (cdr (assoc (downcase property)
15251 (mapcar (lambda (x) (cons (downcase x) x))
15252 keys)))
15253 property))))
15255 (defun org-set-property-and-value (use-last)
15256 "Allow to set [PROPERTY]: [value] direction from prompt.
15257 When use-default, don't even ask, just use the last
15258 \"[PROPERTY]: [value]\" string from the history."
15259 (interactive "P")
15260 (let* ((completion-ignore-case t)
15261 (pv (or (and use-last org-last-set-property-value)
15262 (org-completing-read
15263 "Enter a \"[Property]: [value]\" pair: "
15264 nil nil nil nil nil
15265 org-last-set-property-value)))
15266 prop val)
15267 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15268 (setq prop (match-string 1 pv)
15269 val (match-string 2 pv))
15270 (org-set-property prop val))))
15272 (defun org-set-property (property value)
15273 "In the current entry, set PROPERTY to VALUE.
15274 When called interactively, this will prompt for a property name, offering
15275 completion on existing and default properties. And then it will prompt
15276 for a value, offering completion either on allowed values (via an inherited
15277 xxx_ALL property) or on existing values in other instances of this property
15278 in the current file."
15279 (interactive (list nil nil))
15280 (let* ((property (or property (org-read-property-name)))
15281 (value (or value (org-read-property-value property)))
15282 (fn (cdr (assoc property org-properties-postprocess-alist))))
15283 (setq org-last-set-property property)
15284 (setq org-last-set-property-value (concat property ": " value))
15285 ;; Possibly postprocess the inserted value:
15286 (when fn (setq value (funcall fn value)))
15287 (unless (equal (org-entry-get nil property) value)
15288 (org-entry-put nil property value))))
15290 (defun org-delete-property (property)
15291 "In the current entry, delete PROPERTY."
15292 (interactive
15293 (let* ((completion-ignore-case t)
15294 (prop (org-icompleting-read "Property: "
15295 (org-entry-properties nil 'standard))))
15296 (list prop)))
15297 (message "Property %s %s" property
15298 (if (org-entry-delete nil property)
15299 "deleted"
15300 "was not present in the entry")))
15302 (defun org-delete-property-globally (property)
15303 "Remove PROPERTY globally, from all entries."
15304 (interactive
15305 (let* ((completion-ignore-case t)
15306 (prop (org-icompleting-read
15307 "Globally remove property: "
15308 (mapcar 'list (org-buffer-property-keys)))))
15309 (list prop)))
15310 (save-excursion
15311 (save-restriction
15312 (widen)
15313 (goto-char (point-min))
15314 (let ((cnt 0))
15315 (while (re-search-forward
15316 (org-re-property property)
15317 nil t)
15318 (setq cnt (1+ cnt))
15319 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15320 (message "Property \"%s\" removed from %d entries" property cnt)))))
15322 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15324 (defun org-compute-property-at-point ()
15325 "Compute the property at point.
15326 This looks for an enclosing column format, extracts the operator and
15327 then applies it to the property in the column format's scope."
15328 (interactive)
15329 (unless (org-at-property-p)
15330 (error "Not at a property"))
15331 (let ((prop (org-match-string-no-properties 2)))
15332 (org-columns-get-format-and-top-level)
15333 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15334 (error "No operator defined for property %s" prop))
15335 (org-columns-compute prop)))
15337 (defvar org-property-allowed-value-functions nil
15338 "Hook for functions supplying allowed values for a specific property.
15339 The functions must take a single argument, the name of the property, and
15340 return a flat list of allowed values. If \":ETC\" is one of
15341 the values, this means that these values are intended as defaults for
15342 completion, but that other values should be allowed too.
15343 The functions must return nil if they are not responsible for this
15344 property.")
15346 (defun org-property-get-allowed-values (pom property &optional table)
15347 "Get allowed values for the property PROPERTY.
15348 When TABLE is non-nil, return an alist that can directly be used for
15349 completion."
15350 (let (vals)
15351 (cond
15352 ((equal property "TODO")
15353 (setq vals (org-with-point-at pom
15354 (append org-todo-keywords-1 '("")))))
15355 ((equal property "PRIORITY")
15356 (let ((n org-lowest-priority))
15357 (while (>= n org-highest-priority)
15358 (push (char-to-string n) vals)
15359 (setq n (1- n)))))
15360 ((member property org-special-properties))
15361 ((setq vals (run-hook-with-args-until-success
15362 'org-property-allowed-value-functions property)))
15364 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15365 (when (and vals (string-match "\\S-" vals))
15366 (setq vals (car (read-from-string (concat "(" vals ")"))))
15367 (setq vals (mapcar (lambda (x)
15368 (cond ((stringp x) x)
15369 ((numberp x) (number-to-string x))
15370 ((symbolp x) (symbol-name x))
15371 (t "???")))
15372 vals)))))
15373 (when (member ":ETC" vals)
15374 (setq vals (remove ":ETC" vals))
15375 (org-add-props (car vals) '(org-unrestricted t)))
15376 (if table (mapcar 'list vals) vals)))
15378 (defun org-property-previous-allowed-value (&optional previous)
15379 "Switch to the next allowed value for this property."
15380 (interactive)
15381 (org-property-next-allowed-value t))
15383 (defun org-property-next-allowed-value (&optional previous)
15384 "Switch to the next allowed value for this property."
15385 (interactive)
15386 (unless (org-at-property-p)
15387 (error "Not at a property"))
15388 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15389 (key (match-string 2))
15390 (value (match-string 3))
15391 (allowed (or (org-property-get-allowed-values (point) key)
15392 (and (member value '("[ ]" "[-]" "[X]"))
15393 '("[ ]" "[X]"))))
15394 nval)
15395 (unless allowed
15396 (error "Allowed values for this property have not been defined"))
15397 (if previous (setq allowed (reverse allowed)))
15398 (if (member value allowed)
15399 (setq nval (car (cdr (member value allowed)))))
15400 (setq nval (or nval (car allowed)))
15401 (if (equal nval value)
15402 (error "Only one allowed value for this property"))
15403 (org-at-property-p)
15404 (replace-match (concat " :" key ": " nval) t t)
15405 (org-indent-line)
15406 (beginning-of-line 1)
15407 (skip-chars-forward " \t")
15408 (when (equal prop org-effort-property)
15409 (save-excursion
15410 (org-back-to-heading t)
15411 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15412 (run-hook-with-args 'org-property-changed-functions key nval)))
15414 (defun org-find-olp (path &optional this-buffer)
15415 "Return a marker pointing to the entry at outline path OLP.
15416 If anything goes wrong, throw an error.
15417 You can wrap this call to catch the error like this:
15419 (condition-case msg
15420 (org-mobile-locate-entry (match-string 4))
15421 (error (nth 1 msg)))
15423 The return value will then be either a string with the error message,
15424 or a marker if everything is OK.
15426 If THIS-BUFFER is set, the outline path does not contain a file,
15427 only headings."
15428 (let* ((file (if this-buffer buffer-file-name (pop path)))
15429 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15430 (level 1)
15431 (lmin 1)
15432 (lmax 1)
15433 limit re end found pos heading cnt flevel)
15434 (unless buffer (error "File not found :%s" file))
15435 (with-current-buffer buffer
15436 (save-excursion
15437 (save-restriction
15438 (widen)
15439 (setq limit (point-max))
15440 (goto-char (point-min))
15441 (while (setq heading (pop path))
15442 (setq re (format org-complex-heading-regexp-format
15443 (regexp-quote heading)))
15444 (setq cnt 0 pos (point))
15445 (while (re-search-forward re end t)
15446 (setq level (- (match-end 1) (match-beginning 1)))
15447 (if (and (>= level lmin) (<= level lmax))
15448 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15449 (when (= cnt 0) (error "Heading not found on level %d: %s"
15450 lmax heading))
15451 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15452 lmax heading))
15453 (goto-char found)
15454 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15455 (setq end (save-excursion (org-end-of-subtree t t))))
15456 (when (org-at-heading-p)
15457 (point-marker)))))))
15459 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15460 "Find node HEADING in BUFFER.
15461 Return a marker to the heading if it was found, or nil if not.
15462 If POS-ONLY is set, return just the position instead of a marker.
15464 The heading text must match exact, but it may have a TODO keyword,
15465 a priority cookie and tags in the standard locations."
15466 (with-current-buffer (or buffer (current-buffer))
15467 (save-excursion
15468 (save-restriction
15469 (widen)
15470 (goto-char (point-min))
15471 (let (case-fold-search)
15472 (if (re-search-forward
15473 (format org-complex-heading-regexp-format
15474 (regexp-quote heading)) nil t)
15475 (if pos-only
15476 (match-beginning 0)
15477 (move-marker (make-marker) (match-beginning 0)))))))))
15479 (defun org-find-exact-heading-in-directory (heading &optional dir)
15480 "Find Org node headline HEADING in all .org files in directory DIR.
15481 When the target headline is found, return a marker to this location."
15482 (let ((files (directory-files (or dir default-directory)
15483 nil "\\`[^.#].*\\.org\\'"))
15484 file visiting m buffer)
15485 (catch 'found
15486 (while (setq file (pop files))
15487 (message "trying %s" file)
15488 (setq visiting (org-find-base-buffer-visiting file))
15489 (setq buffer (or visiting (find-file-noselect file)))
15490 (setq m (org-find-exact-headline-in-buffer
15491 heading buffer))
15492 (when (and (not m) (not visiting)) (kill-buffer buffer))
15493 (and m (throw 'found m))))))
15495 (defun org-find-entry-with-id (ident)
15496 "Locate the entry that contains the ID property with exact value IDENT.
15497 IDENT can be a string, a symbol or a number, this function will search for
15498 the string representation of it.
15499 Return the position where this entry starts, or nil if there is no such entry."
15500 (interactive "sID: ")
15501 (let ((id (cond
15502 ((stringp ident) ident)
15503 ((symbol-name ident) (symbol-name ident))
15504 ((numberp ident) (number-to-string ident))
15505 (t (error "IDENT %s must be a string, symbol or number" ident))))
15506 (case-fold-search nil))
15507 (save-excursion
15508 (save-restriction
15509 (widen)
15510 (goto-char (point-min))
15511 (when (re-search-forward
15512 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15513 nil t)
15514 (org-back-to-heading t)
15515 (point))))))
15517 ;;;; Timestamps
15519 (defvar org-last-changed-timestamp nil)
15520 (defvar org-last-inserted-timestamp nil
15521 "The last time stamp inserted with `org-insert-time-stamp'.")
15522 (defvar org-time-was-given) ; dynamically scoped parameter
15523 (defvar org-end-time-was-given) ; dynamically scoped parameter
15524 (defvar org-ts-what) ; dynamically scoped parameter
15526 (defun org-time-stamp (arg &optional inactive)
15527 "Prompt for a date/time and insert a time stamp.
15528 If the user specifies a time like HH:MM or if this command is
15529 called with at least one prefix argument, the time stamp contains
15530 the date and the time. Otherwise, only the date is be included.
15532 All parts of a date not specified by the user is filled in from
15533 the current date/time. So if you just press return without
15534 typing anything, the time stamp will represent the current
15535 date/time.
15537 If there is already a timestamp at the cursor, it will be
15538 modified.
15540 With two universal prefix arguments, insert an active timestamp
15541 with the current time without prompting the user."
15542 (interactive "P")
15543 (let* ((ts nil)
15544 (default-time
15545 ;; Default time is either today, or, when entering a range,
15546 ;; the range start.
15547 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15548 (save-excursion
15549 (re-search-backward
15550 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15551 (- (point) 20) t)))
15552 (apply 'encode-time (org-parse-time-string (match-string 1)))
15553 (current-time)))
15554 (default-input (and ts (org-get-compact-tod ts)))
15555 (repeater (save-excursion
15556 (save-match-data
15557 (beginning-of-line)
15558 (when (re-search-forward
15559 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15560 (save-excursion (progn (end-of-line) (point))) t)
15561 (match-string 0)))))
15562 org-time-was-given org-end-time-was-given time)
15563 (cond
15564 ((and (org-at-timestamp-p t)
15565 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15566 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15567 (insert "--")
15568 (setq time (let ((this-command this-command))
15569 (org-read-date arg 'totime nil nil
15570 default-time default-input inactive)))
15571 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15572 ((org-at-timestamp-p t)
15573 (setq time (let ((this-command this-command))
15574 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15575 (when (org-at-timestamp-p t) ; just to get the match data
15576 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15577 (replace-match "")
15578 (setq org-last-changed-timestamp
15579 (org-insert-time-stamp
15580 time (or org-time-was-given arg)
15581 inactive nil nil (list org-end-time-was-given)))
15582 (when repeater (goto-char (1- (point))) (insert " " repeater)
15583 (setq org-last-changed-timestamp
15584 (concat (substring org-last-inserted-timestamp 0 -1)
15585 " " repeater ">"))))
15586 (message "Timestamp updated"))
15587 ((equal arg '(16))
15588 (org-insert-time-stamp (current-time) t))
15590 (setq time (let ((this-command this-command))
15591 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15592 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15593 nil nil (list org-end-time-was-given))))))
15595 ;; FIXME: can we use this for something else, like computing time differences?
15596 (defun org-get-compact-tod (s)
15597 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15598 (let* ((t1 (match-string 1 s))
15599 (h1 (string-to-number (match-string 2 s)))
15600 (m1 (string-to-number (match-string 3 s)))
15601 (t2 (and (match-end 4) (match-string 5 s)))
15602 (h2 (and t2 (string-to-number (match-string 6 s))))
15603 (m2 (and t2 (string-to-number (match-string 7 s))))
15604 dh dm)
15605 (if (not t2)
15607 (setq dh (- h2 h1) dm (- m2 m1))
15608 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15609 (concat t1 "+" (number-to-string dh)
15610 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15612 (defun org-time-stamp-inactive (&optional arg)
15613 "Insert an inactive time stamp.
15614 An inactive time stamp is enclosed in square brackets instead of angle
15615 brackets. It is inactive in the sense that it does not trigger agenda entries,
15616 does not link to the calendar and cannot be changed with the S-cursor keys.
15617 So these are more for recording a certain time/date."
15618 (interactive "P")
15619 (org-time-stamp arg 'inactive))
15621 (defvar org-date-ovl (make-overlay 1 1))
15622 (overlay-put org-date-ovl 'face 'org-date-selected)
15623 (org-detach-overlay org-date-ovl)
15625 (defvar org-ans1) ; dynamically scoped parameter
15626 (defvar org-ans2) ; dynamically scoped parameter
15628 (defvar org-plain-time-of-day-regexp) ; defined below
15630 (defvar org-overriding-default-time nil) ; dynamically scoped
15631 (defvar org-read-date-overlay nil)
15632 (defvar org-dcst nil) ; dynamically scoped
15633 (defvar org-read-date-history nil)
15634 (defvar org-read-date-final-answer nil)
15635 (defvar org-read-date-analyze-futurep nil)
15636 (defvar org-read-date-analyze-forced-year nil)
15637 (defvar org-read-date-inactive)
15639 (defvar org-read-date-minibuffer-local-map
15640 (let ((map (make-sparse-keymap)))
15641 (set-keymap-parent map minibuffer-local-map)
15642 (org-defkey map (kbd ".")
15643 (lambda () (interactive)
15644 (org-eval-in-calendar '(calendar-goto-today))))
15645 (org-defkey map [(meta shift left)]
15646 (lambda () (interactive)
15647 (org-eval-in-calendar '(calendar-backward-month 1))))
15648 (org-defkey map [(meta shift right)]
15649 (lambda () (interactive)
15650 (org-eval-in-calendar '(calendar-forward-month 1))))
15651 (org-defkey map [(meta shift up)]
15652 (lambda () (interactive)
15653 (org-eval-in-calendar '(calendar-backward-year 1))))
15654 (org-defkey map [(meta shift down)]
15655 (lambda () (interactive)
15656 (org-eval-in-calendar '(calendar-forward-year 1))))
15657 (org-defkey map [?\e (shift left)]
15658 (lambda () (interactive)
15659 (org-eval-in-calendar '(calendar-backward-month 1))))
15660 (org-defkey map [?\e (shift right)]
15661 (lambda () (interactive)
15662 (org-eval-in-calendar '(calendar-forward-month 1))))
15663 (org-defkey map [?\e (shift up)]
15664 (lambda () (interactive)
15665 (org-eval-in-calendar '(calendar-backward-year 1))))
15666 (org-defkey map [?\e (shift down)]
15667 (lambda () (interactive)
15668 (org-eval-in-calendar '(calendar-forward-year 1))))
15669 (org-defkey map [(shift up)]
15670 (lambda () (interactive)
15671 (org-eval-in-calendar '(calendar-backward-week 1))))
15672 (org-defkey map [(shift down)]
15673 (lambda () (interactive)
15674 (org-eval-in-calendar '(calendar-forward-week 1))))
15675 (org-defkey map [(shift left)]
15676 (lambda () (interactive)
15677 (org-eval-in-calendar '(calendar-backward-day 1))))
15678 (org-defkey map [(shift right)]
15679 (lambda () (interactive)
15680 (org-eval-in-calendar '(calendar-forward-day 1))))
15681 (org-defkey map "!"
15682 (lambda () (interactive)
15683 (org-eval-in-calendar '(diary-view-entries))
15684 (message "")))
15685 (org-defkey map ">"
15686 (lambda () (interactive)
15687 (org-eval-in-calendar '(scroll-calendar-left 1))))
15688 (org-defkey map "<"
15689 (lambda () (interactive)
15690 (org-eval-in-calendar '(scroll-calendar-right 1))))
15691 (org-defkey map "\C-v"
15692 (lambda () (interactive)
15693 (org-eval-in-calendar
15694 '(calendar-scroll-left-three-months 1))))
15695 (org-defkey map "\M-v"
15696 (lambda () (interactive)
15697 (org-eval-in-calendar
15698 '(calendar-scroll-right-three-months 1))))
15699 map)
15700 "Keymap for minibuffer commands when using `org-read-date'.")
15702 (defun org-read-date (&optional org-with-time to-time from-string prompt
15703 default-time default-input inactive)
15704 "Read a date, possibly a time, and make things smooth for the user.
15705 The prompt will suggest to enter an ISO date, but you can also enter anything
15706 which will at least partially be understood by `parse-time-string'.
15707 Unrecognized parts of the date will default to the current day, month, year,
15708 hour and minute. If this command is called to replace a timestamp at point,
15709 or to enter the second timestamp of a range, the default time is taken
15710 from the existing stamp. Furthermore, the command prefers the future,
15711 so if you are giving a date where the year is not given, and the day-month
15712 combination is already past in the current year, it will assume you
15713 mean next year. For details, see the manual. A few examples:
15715 3-2-5 --> 2003-02-05
15716 feb 15 --> currentyear-02-15
15717 2/15 --> currentyear-02-15
15718 sep 12 9 --> 2009-09-12
15719 12:45 --> today 12:45
15720 22 sept 0:34 --> currentyear-09-22 0:34
15721 12 --> currentyear-currentmonth-12
15722 Fri --> nearest Friday (today or later)
15723 etc.
15725 Furthermore you can specify a relative date by giving, as the *first* thing
15726 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15727 change in days weeks, months, years.
15728 With a single plus or minus, the date is relative to today. With a double
15729 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15730 +4d --> four days from today
15731 +4 --> same as above
15732 +2w --> two weeks from today
15733 ++5 --> five days from default date
15735 The function understands only English month and weekday abbreviations.
15737 While prompting, a calendar is popped up - you can also select the
15738 date with the mouse (button 1). The calendar shows a period of three
15739 months. To scroll it to other months, use the keys `>' and `<'.
15740 If you don't like the calendar, turn it off with
15741 \(setq org-read-date-popup-calendar nil)
15743 With optional argument TO-TIME, the date will immediately be converted
15744 to an internal time.
15745 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15746 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15747 still enter a time, and this function will inform the calling routine
15748 about this change. The calling routine may then choose to change the
15749 format used to insert the time stamp into the buffer to include the time.
15750 With optional argument FROM-STRING, read from this string instead from
15751 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15752 the time/date that is used for everything that is not specified by the
15753 user."
15754 (require 'parse-time)
15755 (let* ((org-time-stamp-rounding-minutes
15756 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15757 (org-dcst org-display-custom-times)
15758 (ct (org-current-time))
15759 (org-def (or org-overriding-default-time default-time ct))
15760 (org-defdecode (decode-time org-def))
15761 (dummy (progn
15762 (when (< (nth 2 org-defdecode) org-extend-today-until)
15763 (setcar (nthcdr 2 org-defdecode) -1)
15764 (setcar (nthcdr 1 org-defdecode) 59)
15765 (setq org-def (apply 'encode-time org-defdecode)
15766 org-defdecode (decode-time org-def)))))
15767 (mouse-autoselect-window nil) ; Don't let the mouse jump
15768 (calendar-frame-setup nil)
15769 (calendar-setup nil)
15770 (calendar-move-hook nil)
15771 (calendar-view-diary-initially-flag nil)
15772 (calendar-view-holidays-initially-flag nil)
15773 (timestr (format-time-string
15774 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15775 (prompt (concat (if prompt (concat prompt " ") "")
15776 (format "Date+time [%s]: " timestr)))
15777 ans (org-ans0 "") org-ans1 org-ans2 final)
15779 (cond
15780 (from-string (setq ans from-string))
15781 (org-read-date-popup-calendar
15782 (save-excursion
15783 (save-window-excursion
15784 (calendar)
15785 (org-eval-in-calendar '(setq cursor-type nil) t)
15786 (unwind-protect
15787 (progn
15788 (calendar-forward-day (- (time-to-days org-def)
15789 (calendar-absolute-from-gregorian
15790 (calendar-current-date))))
15791 (org-eval-in-calendar nil t)
15792 (let* ((old-map (current-local-map))
15793 (map (copy-keymap calendar-mode-map))
15794 (minibuffer-local-map
15795 (copy-keymap org-read-date-minibuffer-local-map)))
15796 (org-defkey map (kbd "RET") 'org-calendar-select)
15797 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15798 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15799 (unwind-protect
15800 (progn
15801 (use-local-map map)
15802 (setq org-read-date-inactive inactive)
15803 (add-hook 'post-command-hook 'org-read-date-display)
15804 (setq org-ans0 (read-string prompt default-input
15805 'org-read-date-history nil))
15806 ;; org-ans0: from prompt
15807 ;; org-ans1: from mouse click
15808 ;; org-ans2: from calendar motion
15809 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15810 (remove-hook 'post-command-hook 'org-read-date-display)
15811 (use-local-map old-map)
15812 (when org-read-date-overlay
15813 (delete-overlay org-read-date-overlay)
15814 (setq org-read-date-overlay nil)))))
15815 (bury-buffer "*Calendar*")))))
15817 (t ; Naked prompt only
15818 (unwind-protect
15819 (setq ans (read-string prompt default-input
15820 'org-read-date-history timestr))
15821 (when org-read-date-overlay
15822 (delete-overlay org-read-date-overlay)
15823 (setq org-read-date-overlay nil)))))
15825 (setq final (org-read-date-analyze ans org-def org-defdecode))
15827 (when org-read-date-analyze-forced-year
15828 (message "Year was forced into %s"
15829 (if org-read-date-force-compatible-dates
15830 "compatible range (1970-2037)"
15831 "range representable on this machine"))
15832 (ding))
15834 ;; One round trip to get rid of 34th of August and stuff like that....
15835 (setq final (decode-time (apply 'encode-time final)))
15837 (setq org-read-date-final-answer ans)
15839 (if to-time
15840 (apply 'encode-time final)
15841 (if (and (boundp 'org-time-was-given) org-time-was-given)
15842 (format "%04d-%02d-%02d %02d:%02d"
15843 (nth 5 final) (nth 4 final) (nth 3 final)
15844 (nth 2 final) (nth 1 final))
15845 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15847 (defvar org-def)
15848 (defvar org-defdecode)
15849 (defvar org-with-time)
15850 (defun org-read-date-display ()
15851 "Display the current date prompt interpretation in the minibuffer."
15852 (when org-read-date-display-live
15853 (when org-read-date-overlay
15854 (delete-overlay org-read-date-overlay))
15855 (when (minibufferp (current-buffer))
15856 (save-excursion
15857 (end-of-line 1)
15858 (while (not (equal (buffer-substring
15859 (max (point-min) (- (point) 4)) (point))
15860 " "))
15861 (insert " ")))
15862 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15863 " " (or org-ans1 org-ans2)))
15864 (org-end-time-was-given nil)
15865 (f (org-read-date-analyze ans org-def org-defdecode))
15866 (fmts (if org-dcst
15867 org-time-stamp-custom-formats
15868 org-time-stamp-formats))
15869 (fmt (if (or org-with-time
15870 (and (boundp 'org-time-was-given) org-time-was-given))
15871 (cdr fmts)
15872 (car fmts)))
15873 (txt (format-time-string fmt (apply 'encode-time f)))
15874 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15875 (txt (concat "=> " txt)))
15876 (when (and org-end-time-was-given
15877 (string-match org-plain-time-of-day-regexp txt))
15878 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15879 org-end-time-was-given
15880 (substring txt (match-end 0)))))
15881 (when org-read-date-analyze-futurep
15882 (setq txt (concat txt " (=>F)")))
15883 (setq org-read-date-overlay
15884 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15885 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15887 (defun org-read-date-analyze (ans org-def org-defdecode)
15888 "Analyze the combined answer of the date prompt."
15889 ;; FIXME: cleanup and comment
15890 (let ((nowdecode (decode-time (current-time)))
15891 delta deltan deltaw deltadef year month day
15892 hour minute second wday pm h2 m2 tl wday1
15893 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15894 (setq org-read-date-analyze-futurep nil
15895 org-read-date-analyze-forced-year nil)
15896 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15897 (setq ans "+0"))
15899 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15900 (setq ans (replace-match "" t t ans)
15901 deltan (car delta)
15902 deltaw (nth 1 delta)
15903 deltadef (nth 2 delta)))
15905 ;; Check if there is an iso week date in there. If yes, store the
15906 ;; info and postpone interpreting it until the rest of the parsing
15907 ;; is done.
15908 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15909 (setq iso-year (if (match-end 1)
15910 (org-small-year-to-year
15911 (string-to-number (match-string 1 ans))))
15912 iso-weekday (if (match-end 3)
15913 (string-to-number (match-string 3 ans)))
15914 iso-week (string-to-number (match-string 2 ans)))
15915 (setq ans (replace-match "" t t ans)))
15917 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15918 (when (string-match
15919 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15920 (setq year (if (match-end 2)
15921 (string-to-number (match-string 2 ans))
15922 (progn (setq kill-year t)
15923 (string-to-number (format-time-string "%Y"))))
15924 month (string-to-number (match-string 3 ans))
15925 day (string-to-number (match-string 4 ans)))
15926 (if (< year 100) (setq year (+ 2000 year)))
15927 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15928 t nil ans)))
15930 ;; Help matching dotted european dates
15931 (when (string-match
15932 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15933 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15934 (setq kill-year t)
15935 (string-to-number (format-time-string "%Y")))
15936 day (string-to-number (match-string 1 ans))
15937 month (string-to-number (match-string 2 ans))
15938 ans (replace-match (format "%04d-%02d-%02d" year month day)
15939 t nil ans)))
15941 ;; Help matching american dates, like 5/30 or 5/30/7
15942 (when (string-match
15943 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15944 (setq year (if (match-end 4)
15945 (string-to-number (match-string 4 ans))
15946 (progn (setq kill-year t)
15947 (string-to-number (format-time-string "%Y"))))
15948 month (string-to-number (match-string 1 ans))
15949 day (string-to-number (match-string 2 ans)))
15950 (if (< year 100) (setq year (+ 2000 year)))
15951 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15952 t nil ans)))
15953 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15954 ;; If there is a time with am/pm, and *no* time without it, we convert
15955 ;; so that matching will be successful.
15956 (loop for i from 1 to 2 do ; twice, for end time as well
15957 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15958 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15959 (setq hour (string-to-number (match-string 1 ans))
15960 minute (if (match-end 3)
15961 (string-to-number (match-string 3 ans))
15963 pm (equal ?p
15964 (string-to-char (downcase (match-string 4 ans)))))
15965 (if (and (= hour 12) (not pm))
15966 (setq hour 0)
15967 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15968 (setq ans (replace-match (format "%02d:%02d" hour minute)
15969 t t ans))))
15971 ;; Check if a time range is given as a duration
15972 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15973 (setq hour (string-to-number (match-string 1 ans))
15974 h2 (+ hour (string-to-number (match-string 3 ans)))
15975 minute (string-to-number (match-string 2 ans))
15976 m2 (+ minute (if (match-end 5) (string-to-number
15977 (match-string 5 ans))0)))
15978 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15979 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15980 t t ans)))
15982 ;; Check if there is a time range
15983 (when (boundp 'org-end-time-was-given)
15984 (setq org-time-was-given nil)
15985 (when (and (string-match org-plain-time-of-day-regexp ans)
15986 (match-end 8))
15987 (setq org-end-time-was-given (match-string 8 ans))
15988 (setq ans (concat (substring ans 0 (match-beginning 7))
15989 (substring ans (match-end 7))))))
15991 (setq tl (parse-time-string ans)
15992 day (or (nth 3 tl) (nth 3 org-defdecode))
15993 month (or (nth 4 tl)
15994 (if (and org-read-date-prefer-future
15995 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15996 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15997 (nth 4 org-defdecode)))
15998 year (or (and (not kill-year) (nth 5 tl))
15999 (if (and org-read-date-prefer-future
16000 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16001 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16002 (nth 5 org-defdecode)))
16003 hour (or (nth 2 tl) (nth 2 org-defdecode))
16004 minute (or (nth 1 tl) (nth 1 org-defdecode))
16005 second (or (nth 0 tl) 0)
16006 wday (nth 6 tl))
16008 (when (and (eq org-read-date-prefer-future 'time)
16009 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16010 (equal day (nth 3 nowdecode))
16011 (equal month (nth 4 nowdecode))
16012 (equal year (nth 5 nowdecode))
16013 (nth 2 tl)
16014 (or (< (nth 2 tl) (nth 2 nowdecode))
16015 (and (= (nth 2 tl) (nth 2 nowdecode))
16016 (nth 1 tl)
16017 (< (nth 1 tl) (nth 1 nowdecode)))))
16018 (setq day (1+ day)
16019 futurep t))
16021 ;; Special date definitions below
16022 (cond
16023 (iso-week
16024 ;; There was an iso week
16025 (require 'cal-iso)
16026 (setq futurep nil)
16027 (setq year (or iso-year year)
16028 day (or iso-weekday wday 1)
16029 wday nil ; to make sure that the trigger below does not match
16030 iso-date (calendar-gregorian-from-absolute
16031 (calendar-absolute-from-iso
16032 (list iso-week day year))))
16033 ; FIXME: Should we also push ISO weeks into the future?
16034 ; (when (and org-read-date-prefer-future
16035 ; (not iso-year)
16036 ; (< (calendar-absolute-from-gregorian iso-date)
16037 ; (time-to-days (current-time))))
16038 ; (setq year (1+ year)
16039 ; iso-date (calendar-gregorian-from-absolute
16040 ; (calendar-absolute-from-iso
16041 ; (list iso-week day year)))))
16042 (setq month (car iso-date)
16043 year (nth 2 iso-date)
16044 day (nth 1 iso-date)))
16045 (deltan
16046 (setq futurep nil)
16047 (unless deltadef
16048 (let ((now (decode-time (current-time))))
16049 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16050 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16051 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16052 ((equal deltaw "m") (setq month (+ month deltan)))
16053 ((equal deltaw "y") (setq year (+ year deltan)))))
16054 ((and wday (not (nth 3 tl)))
16055 ;; Weekday was given, but no day, so pick that day in the week
16056 ;; on or after the derived date.
16057 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16058 (unless (equal wday wday1)
16059 (setq day (+ day (% (- wday wday1 -7) 7))))))
16060 (if (and (boundp 'org-time-was-given)
16061 (nth 2 tl))
16062 (setq org-time-was-given t))
16063 (if (< year 100) (setq year (+ 2000 year)))
16064 ;; Check of the date is representable
16065 (if org-read-date-force-compatible-dates
16066 (progn
16067 (if (< year 1970)
16068 (setq year 1970 org-read-date-analyze-forced-year t))
16069 (if (> year 2037)
16070 (setq year 2037 org-read-date-analyze-forced-year t)))
16071 (condition-case nil
16072 (ignore (encode-time second minute hour day month year))
16073 (error
16074 (setq year (nth 5 org-defdecode))
16075 (setq org-read-date-analyze-forced-year t))))
16076 (setq org-read-date-analyze-futurep futurep)
16077 (list second minute hour day month year)))
16079 (defvar parse-time-weekdays)
16080 (defun org-read-date-get-relative (s today default)
16081 "Check string S for special relative date string.
16082 TODAY and DEFAULT are internal times, for today and for a default.
16083 Return shift list (N what def-flag)
16084 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16085 N is the number of WHATs to shift.
16086 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16087 the DEFAULT date rather than TODAY."
16088 (require 'parse-time)
16089 (when (and
16090 (string-match
16091 (concat
16092 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16093 "\\([0-9]+\\)?"
16094 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16095 "\\([ \t]\\|$\\)") s)
16096 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16097 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16098 (string-to-char (substring (match-string 1 s) -1))
16099 ?+))
16100 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16101 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16102 (what (if (match-end 3) (match-string 3 s) "d"))
16103 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16104 (date (if rel default today))
16105 (wday (nth 6 (decode-time date)))
16106 delta)
16107 (if wday1
16108 (progn
16109 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16110 (if (= dir ?-) (setq delta (- delta 7)))
16111 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16112 (list delta "d" rel))
16113 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16115 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16116 "Turn a user-specified date into the internal representation.
16117 The internal representation needed by the calendar is (month day year).
16118 This is a wrapper to handle the brain-dead convention in calendar that
16119 user function argument order change dependent on argument order."
16120 (if (boundp 'calendar-date-style)
16121 (cond
16122 ((eq calendar-date-style 'american)
16123 (list arg1 arg2 arg3))
16124 ((eq calendar-date-style 'european)
16125 (list arg2 arg1 arg3))
16126 ((eq calendar-date-style 'iso)
16127 (list arg2 arg3 arg1)))
16128 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16129 (if (org-bound-and-true-p european-calendar-style)
16130 (list arg2 arg1 arg3)
16131 (list arg1 arg2 arg3)))))
16133 (defun org-eval-in-calendar (form &optional keepdate)
16134 "Eval FORM in the calendar window and return to current window.
16135 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16136 otherwise stick to the current value of `org-ans2'."
16137 (let ((sf (selected-frame))
16138 (sw (selected-window)))
16139 (select-window (get-buffer-window "*Calendar*" t))
16140 (eval form)
16141 (when (and (not keepdate) (calendar-cursor-to-date))
16142 (let* ((date (calendar-cursor-to-date))
16143 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16144 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16145 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16146 (select-window sw)
16147 (org-select-frame-set-input-focus sf)))
16149 (defun org-calendar-select ()
16150 "Return to `org-read-date' with the date currently selected.
16151 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16152 (interactive)
16153 (when (calendar-cursor-to-date)
16154 (let* ((date (calendar-cursor-to-date))
16155 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16156 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16157 (if (active-minibuffer-window) (exit-minibuffer))))
16159 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16160 "Insert a date stamp for the date given by the internal TIME.
16161 WITH-HM means use the stamp format that includes the time of the day.
16162 INACTIVE means use square brackets instead of angular ones, so that the
16163 stamp will not contribute to the agenda.
16164 PRE and POST are optional strings to be inserted before and after the
16165 stamp.
16166 The command returns the inserted time stamp."
16167 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16168 stamp)
16169 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16170 (insert-before-markers (or pre ""))
16171 (when (listp extra)
16172 (setq extra (car extra))
16173 (if (and (stringp extra)
16174 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16175 (setq extra (format "-%02d:%02d"
16176 (string-to-number (match-string 1 extra))
16177 (string-to-number (match-string 2 extra))))
16178 (setq extra nil)))
16179 (when extra
16180 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16181 (insert-before-markers (setq stamp (format-time-string fmt time)))
16182 (insert-before-markers (or post ""))
16183 (setq org-last-inserted-timestamp stamp)))
16185 (defun org-toggle-time-stamp-overlays ()
16186 "Toggle the use of custom time stamp formats."
16187 (interactive)
16188 (setq org-display-custom-times (not org-display-custom-times))
16189 (unless org-display-custom-times
16190 (let ((p (point-min)) (bmp (buffer-modified-p)))
16191 (while (setq p (next-single-property-change p 'display))
16192 (if (and (get-text-property p 'display)
16193 (eq (get-text-property p 'face) 'org-date))
16194 (remove-text-properties
16195 p (setq p (next-single-property-change p 'display))
16196 '(display t))))
16197 (set-buffer-modified-p bmp)))
16198 (if (featurep 'xemacs)
16199 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16200 (org-restart-font-lock)
16201 (setq org-table-may-need-update t)
16202 (if org-display-custom-times
16203 (message "Time stamps are overlaid with custom format")
16204 (message "Time stamp overlays removed")))
16206 (defun org-display-custom-time (beg end)
16207 "Overlay modified time stamp format over timestamp between BEG and END."
16208 (let* ((ts (buffer-substring beg end))
16209 t1 w1 with-hm tf time str w2 (off 0))
16210 (save-match-data
16211 (setq t1 (org-parse-time-string ts t))
16212 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16213 (setq off (- (match-end 0) (match-beginning 0)))))
16214 (setq end (- end off))
16215 (setq w1 (- end beg)
16216 with-hm (and (nth 1 t1) (nth 2 t1))
16217 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16218 time (org-fix-decoded-time t1)
16219 str (org-add-props
16220 (format-time-string
16221 (substring tf 1 -1) (apply 'encode-time time))
16222 nil 'mouse-face 'highlight)
16223 w2 (length str))
16224 (if (not (= w2 w1))
16225 (add-text-properties (1+ beg) (+ 2 beg)
16226 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16227 (if (featurep 'xemacs)
16228 (progn
16229 (put-text-property beg end 'invisible t)
16230 (put-text-property beg end 'end-glyph (make-glyph str)))
16231 (put-text-property beg end 'display str))))
16233 (defun org-translate-time (string)
16234 "Translate all timestamps in STRING to custom format.
16235 But do this only if the variable `org-display-custom-times' is set."
16236 (when org-display-custom-times
16237 (save-match-data
16238 (let* ((start 0)
16239 (re org-ts-regexp-both)
16240 t1 with-hm inactive tf time str beg end)
16241 (while (setq start (string-match re string start))
16242 (setq beg (match-beginning 0)
16243 end (match-end 0)
16244 t1 (save-match-data
16245 (org-parse-time-string (substring string beg end) t))
16246 with-hm (and (nth 1 t1) (nth 2 t1))
16247 inactive (equal (substring string beg (1+ beg)) "[")
16248 tf (funcall (if with-hm 'cdr 'car)
16249 org-time-stamp-custom-formats)
16250 time (org-fix-decoded-time t1)
16251 str (format-time-string
16252 (concat
16253 (if inactive "[" "<") (substring tf 1 -1)
16254 (if inactive "]" ">"))
16255 (apply 'encode-time time))
16256 string (replace-match str t t string)
16257 start (+ start (length str)))))))
16258 string)
16260 (defun org-fix-decoded-time (time)
16261 "Set 0 instead of nil for the first 6 elements of time.
16262 Don't touch the rest."
16263 (let ((n 0))
16264 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16266 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16268 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16269 "Difference between TIMESTAMP-STRING and now in days.
16270 If SECONDS is non-nil, return the difference in seconds."
16271 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16272 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16273 (funcall fdiff (current-time)))))
16275 (defun org-deadline-close (timestamp-string &optional ndays)
16276 "Is the time in TIMESTAMP-STRING close to the current date?"
16277 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16278 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16279 (not (org-entry-is-done-p))))
16281 (defun org-get-wdays (ts &optional delay zero-delay)
16282 "Get the deadline lead time appropriate for timestring TS.
16283 When DELAY is non-nil, get the delay time for scheduled items
16284 instead of the deadline lead time. When ZERO-DELAY is non-nil
16285 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16286 don't try to find the delay cookie in the scheduled timestamp."
16287 (let ((tv (if delay org-scheduled-delay-days
16288 org-deadline-warning-days)))
16289 (cond
16290 ((or (and delay (< tv 0))
16291 (and delay zero-delay (<= tv 0))
16292 (and (not delay) (<= tv 0)))
16293 ;; Enforce this value no matter what
16294 (- tv))
16295 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16296 ;; lead time is specified.
16297 (floor (* (string-to-number (match-string 1 ts))
16298 (cdr (assoc (match-string 2 ts)
16299 '(("d" . 1) ("w" . 7)
16300 ("m" . 30.4) ("y" . 365.25)
16301 ("h" . 0.041667)))))))
16302 ;; go for the default.
16303 (t tv))))
16305 (defun org-calendar-select-mouse (ev)
16306 "Return to `org-read-date' with the date currently selected.
16307 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16308 (interactive "e")
16309 (mouse-set-point ev)
16310 (when (calendar-cursor-to-date)
16311 (let* ((date (calendar-cursor-to-date))
16312 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16313 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16314 (if (active-minibuffer-window) (exit-minibuffer))))
16316 (defun org-check-deadlines (ndays)
16317 "Check if there are any deadlines due or past due.
16318 A deadline is considered due if it happens within `org-deadline-warning-days'
16319 days from today's date. If the deadline appears in an entry marked DONE,
16320 it is not shown. The prefix arg NDAYS can be used to test that many
16321 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16322 (interactive "P")
16323 (let* ((org-warn-days
16324 (cond
16325 ((equal ndays '(4)) 100000)
16326 (ndays (prefix-numeric-value ndays))
16327 (t (abs org-deadline-warning-days))))
16328 (case-fold-search nil)
16329 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16330 (callback
16331 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16333 (message "%d deadlines past-due or due within %d days"
16334 (org-occur regexp nil callback)
16335 org-warn-days)))
16337 (defsubst org-re-timestamp (type)
16338 "Return a regexp for timestamp TYPE.
16339 Allowed values for TYPE are:
16341 all: all timestamps
16342 active: only active timestamps (<...>)
16343 inactive: only inactive timestamps ([...])
16344 scheduled: only scheduled timestamps
16345 deadline: only deadline timestamps
16347 When TYPE is nil, fall back on returning a regexp that matches
16348 both scheduled and deadline timestamps."
16349 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16350 ((eq type 'active) org-ts-regexp)
16351 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16352 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16353 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16354 ((eq type 'scheduled-or-deadline)
16355 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16357 (defun org-check-before-date (date)
16358 "Check if there are deadlines or scheduled entries before DATE."
16359 (interactive (list (org-read-date)))
16360 (let ((case-fold-search nil)
16361 (regexp (org-re-timestamp org-ts-type))
16362 (callback
16363 (lambda () (time-less-p
16364 (org-time-string-to-time (match-string 1))
16365 (org-time-string-to-time date)))))
16366 (message "%d entries before %s"
16367 (org-occur regexp nil callback) date)))
16369 (defun org-check-after-date (date)
16370 "Check if there are deadlines or scheduled entries after DATE."
16371 (interactive (list (org-read-date)))
16372 (let ((case-fold-search nil)
16373 (regexp (org-re-timestamp org-ts-type))
16374 (callback
16375 (lambda () (not
16376 (time-less-p
16377 (org-time-string-to-time (match-string 1))
16378 (org-time-string-to-time date))))))
16379 (message "%d entries after %s"
16380 (org-occur regexp nil callback) date)))
16382 (defun org-check-dates-range (start-date end-date)
16383 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16384 (interactive (list (org-read-date nil nil nil "Range starts")
16385 (org-read-date nil nil nil "Range end")))
16386 (let ((case-fold-search nil)
16387 (regexp (org-re-timestamp org-ts-type))
16388 (callback
16389 (lambda ()
16390 (let ((match (match-string 1)))
16391 (and
16392 (not (time-less-p
16393 (org-time-string-to-time match)
16394 (org-time-string-to-time start-date)))
16395 (time-less-p
16396 (org-time-string-to-time match)
16397 (org-time-string-to-time end-date)))))))
16398 (message "%d entries between %s and %s"
16399 (org-occur regexp nil callback) start-date end-date)))
16401 (defun org-evaluate-time-range (&optional to-buffer)
16402 "Evaluate a time range by computing the difference between start and end.
16403 Normally the result is just printed in the echo area, but with prefix arg
16404 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16405 If the time range is actually in a table, the result is inserted into the
16406 next column.
16407 For time difference computation, a year is assumed to be exactly 365
16408 days in order to avoid rounding problems."
16409 (interactive "P")
16411 (org-clock-update-time-maybe)
16412 (save-excursion
16413 (unless (org-at-date-range-p t)
16414 (goto-char (point-at-bol))
16415 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16416 (if (not (org-at-date-range-p t))
16417 (error "Not at a time-stamp range, and none found in current line")))
16418 (let* ((ts1 (match-string 1))
16419 (ts2 (match-string 2))
16420 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16421 (match-end (match-end 0))
16422 (time1 (org-time-string-to-time ts1))
16423 (time2 (org-time-string-to-time ts2))
16424 (t1 (org-float-time time1))
16425 (t2 (org-float-time time2))
16426 (diff (abs (- t2 t1)))
16427 (negative (< (- t2 t1) 0))
16428 ;; (ys (floor (* 365 24 60 60)))
16429 (ds (* 24 60 60))
16430 (hs (* 60 60))
16431 (fy "%dy %dd %02d:%02d")
16432 (fy1 "%dy %dd")
16433 (fd "%dd %02d:%02d")
16434 (fd1 "%dd")
16435 (fh "%02d:%02d")
16436 y d h m align)
16437 (if havetime
16438 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16440 d (floor (/ diff ds)) diff (mod diff ds)
16441 h (floor (/ diff hs)) diff (mod diff hs)
16442 m (floor (/ diff 60)))
16443 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16445 d (floor (+ (/ diff ds) 0.5))
16446 h 0 m 0))
16447 (if (not to-buffer)
16448 (message "%s" (org-make-tdiff-string y d h m))
16449 (if (org-at-table-p)
16450 (progn
16451 (goto-char match-end)
16452 (setq align t)
16453 (and (looking-at " *|") (goto-char (match-end 0))))
16454 (goto-char match-end))
16455 (if (looking-at
16456 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16457 (replace-match ""))
16458 (if negative (insert " -"))
16459 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16460 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16461 (insert " " (format fh h m))))
16462 (if align (org-table-align))
16463 (message "Time difference inserted")))))
16465 (defun org-make-tdiff-string (y d h m)
16466 (let ((fmt "")
16467 (l nil))
16468 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16469 l (push y l)))
16470 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16471 l (push d l)))
16472 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16473 l (push h l)))
16474 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16475 l (push m l)))
16476 (apply 'format fmt (nreverse l))))
16478 (defun org-time-string-to-time (s &optional buffer pos)
16479 "Convert a timestamp string into internal time."
16480 (condition-case errdata
16481 (apply 'encode-time (org-parse-time-string s))
16482 (error (error "Bad timestamp `%s'%s\nError was: %s"
16483 s (if (not (and buffer pos))
16485 (format " at %d in buffer `%s'" pos buffer))
16486 (cdr errdata)))))
16488 (defun org-time-string-to-seconds (s)
16489 "Convert a timestamp string to a number of seconds."
16490 (org-float-time (org-time-string-to-time s)))
16492 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16493 "Convert a time stamp to an absolute day number.
16494 If there is a specifier for a cyclic time stamp, get the closest
16495 date to DAYNR.
16496 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16497 The variable date is bound by the calendar when this is called."
16498 (cond
16499 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16500 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16501 daynr
16502 (+ daynr 1000)))
16503 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16504 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16505 (time-to-days (current-time))) (match-string 0 s)
16506 prefer show-all))
16507 (t (time-to-days
16508 (condition-case errdata
16509 (apply 'encode-time (org-parse-time-string s))
16510 (error (error "Bad timestamp `%s'%s\nError was: %s"
16511 s (if (not (and buffer pos))
16513 (format " at %d in buffer `%s'" pos buffer))
16514 (cdr errdata))))))))
16516 (defun org-days-to-iso-week (days)
16517 "Return the iso week number."
16518 (require 'cal-iso)
16519 (car (calendar-iso-from-absolute days)))
16521 (defun org-small-year-to-year (year)
16522 "Convert 2-digit years into 4-digit years.
16523 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16524 The year 2000 cannot be abbreviated. Any year larger than 99
16525 is returned unchanged."
16526 (if (< year 38)
16527 (setq year (+ 2000 year))
16528 (if (< year 100)
16529 (setq year (+ 1900 year))))
16530 year)
16532 (defun org-time-from-absolute (d)
16533 "Return the time corresponding to date D.
16534 D may be an absolute day number, or a calendar-type list (month day year)."
16535 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16536 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16538 (defun org-calendar-holiday ()
16539 "List of holidays, for Diary display in Org-mode."
16540 (require 'holidays)
16541 (let ((hl (funcall
16542 (if (fboundp 'calendar-check-holidays)
16543 'calendar-check-holidays 'check-calendar-holidays) date)))
16544 (if hl (mapconcat 'identity hl "; "))))
16546 (defun org-diary-sexp-entry (sexp entry date)
16547 "Process a SEXP diary ENTRY for DATE."
16548 (require 'diary-lib)
16549 (let ((result (if calendar-debug-sexp
16550 (let ((stack-trace-on-error t))
16551 (eval (car (read-from-string sexp))))
16552 (condition-case nil
16553 (eval (car (read-from-string sexp)))
16554 (error
16555 (beep)
16556 (message "Bad sexp at line %d in %s: %s"
16557 (org-current-line)
16558 (buffer-file-name) sexp)
16559 (sleep-for 2))))))
16560 (cond ((stringp result) (split-string result "; "))
16561 ((and (consp result)
16562 (not (consp (cdr result)))
16563 (stringp (cdr result))) (cdr result))
16564 ((and (consp result)
16565 (stringp (car result))) result)
16566 (result entry))))
16568 (defun org-diary-to-ical-string (frombuf)
16569 "Get iCalendar entries from diary entries in buffer FROMBUF.
16570 This uses the icalendar.el library."
16571 (let* ((tmpdir (if (featurep 'xemacs)
16572 (temp-directory)
16573 temporary-file-directory))
16574 (tmpfile (make-temp-name
16575 (expand-file-name "orgics" tmpdir)))
16576 buf rtn b e)
16577 (with-current-buffer frombuf
16578 (icalendar-export-region (point-min) (point-max) tmpfile)
16579 (setq buf (find-buffer-visiting tmpfile))
16580 (set-buffer buf)
16581 (goto-char (point-min))
16582 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16583 (setq b (match-beginning 0)))
16584 (goto-char (point-max))
16585 (if (re-search-backward "^END:VEVENT" nil t)
16586 (setq e (match-end 0)))
16587 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16588 (kill-buffer buf)
16589 (delete-file tmpfile)
16590 rtn))
16592 (defun org-closest-date (start current change prefer show-all)
16593 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16594 When PREFER is `past', return a date that is either CURRENT or past.
16595 When PREFER is `future', return a date that is either CURRENT or future.
16596 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16597 ;; Make the proper lists from the dates
16598 (catch 'exit
16599 (let ((a1 '(("h" . hour)
16600 ("d" . day)
16601 ("w" . week)
16602 ("m" . month)
16603 ("y" . year)))
16604 (shour (nth 2 (org-parse-time-string start)))
16605 dn dw sday cday n1 n2 n0
16606 d m y y1 y2 date1 date2 nmonths nm ny m2)
16608 (setq start (org-date-to-gregorian start)
16609 current (org-date-to-gregorian
16610 (if show-all
16611 current
16612 (time-to-days (current-time))))
16613 sday (calendar-absolute-from-gregorian start)
16614 cday (calendar-absolute-from-gregorian current))
16616 (if (<= cday sday) (throw 'exit sday))
16618 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16619 (setq dn (string-to-number (match-string 1 change))
16620 dw (cdr (assoc (match-string 2 change) a1)))
16621 (error "Invalid change specifier: %s" change))
16622 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16623 (cond
16624 ((eq dw 'hour)
16625 (let ((missing-hours
16626 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16627 dn)))
16628 (setq n1 (if (zerop missing-hours) cday
16629 (- cday (1+ (floor (/ missing-hours 24)))))
16630 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16631 ((eq dw 'day)
16632 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16633 n2 (+ n1 dn)))
16634 ((eq dw 'year)
16635 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16636 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16637 (setq date1 (list m d y1)
16638 n1 (calendar-absolute-from-gregorian date1)
16639 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16640 n2 (calendar-absolute-from-gregorian date2)))
16641 ((eq dw 'month)
16642 ;; approx number of month between the two dates
16643 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16644 ;; How often does dn fit in there?
16645 (setq d (nth 1 start) m (car start) y (nth 2 start)
16646 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16647 m (+ m nm)
16648 ny (floor (/ m 12))
16649 y (+ y ny)
16650 m (- m (* ny 12)))
16651 (while (> m 12) (setq m (- m 12) y (1+ y)))
16652 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16653 (setq m2 (+ m dn) y2 y)
16654 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16655 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16656 (while (<= n2 cday)
16657 (setq n1 n2 m m2 y y2)
16658 (setq m2 (+ m dn) y2 y)
16659 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16660 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16661 ;; Make sure n1 is the earlier date
16662 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16663 (if show-all
16664 (cond
16665 ((eq prefer 'past) (if (= cday n2) n2 n1))
16666 ((eq prefer 'future) (if (= cday n1) n1 n2))
16667 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16668 (cond
16669 ((eq prefer 'past) (if (= cday n2) n2 n1))
16670 ((eq prefer 'future) (if (= cday n1) n1 n2))
16671 (t (if (= cday n1) n1 n2)))))))
16673 (defun org-date-to-gregorian (date)
16674 "Turn any specification of DATE into a Gregorian date for the calendar."
16675 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16676 ((and (listp date) (= (length date) 3)) date)
16677 ((stringp date)
16678 (setq date (org-parse-time-string date))
16679 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16680 ((listp date)
16681 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16683 (defun org-parse-time-string (s &optional nodefault)
16684 "Parse the standard Org-mode time string.
16685 This should be a lot faster than the normal `parse-time-string'.
16686 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16687 hour and minute fields will be nil if not given."
16688 (cond ((string-match org-ts-regexp0 s)
16689 (list 0
16690 (if (or (match-beginning 8) (not nodefault))
16691 (string-to-number (or (match-string 8 s) "0")))
16692 (if (or (match-beginning 7) (not nodefault))
16693 (string-to-number (or (match-string 7 s) "0")))
16694 (string-to-number (match-string 4 s))
16695 (string-to-number (match-string 3 s))
16696 (string-to-number (match-string 2 s))
16697 nil nil nil))
16698 ((string-match "^<[^>]+>$" s)
16699 (decode-time (seconds-to-time (org-matcher-time s))))
16700 (t (error "Not a standard Org-mode time string: %s" s))))
16702 (defun org-timestamp-up (&optional arg)
16703 "Increase the date item at the cursor by one.
16704 If the cursor is on the year, change the year. If it is on the month,
16705 the day or the time, change that.
16706 With prefix ARG, change by that many units."
16707 (interactive "p")
16708 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16710 (defun org-timestamp-down (&optional arg)
16711 "Decrease the date item at the cursor by one.
16712 If the cursor is on the year, change the year. If it is on the month,
16713 the day or the time, change that.
16714 With prefix ARG, change by that many units."
16715 (interactive "p")
16716 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16718 (defun org-timestamp-up-day (&optional arg)
16719 "Increase the date in the time stamp by one day.
16720 With prefix ARG, change that many days."
16721 (interactive "p")
16722 (if (and (not (org-at-timestamp-p t))
16723 (org-at-heading-p))
16724 (org-todo 'up)
16725 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16727 (defun org-timestamp-down-day (&optional arg)
16728 "Decrease the date in the time stamp by one day.
16729 With prefix ARG, change that many days."
16730 (interactive "p")
16731 (if (and (not (org-at-timestamp-p t))
16732 (org-at-heading-p))
16733 (org-todo 'down)
16734 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16736 (defun org-at-timestamp-p (&optional inactive-ok)
16737 "Determine if the cursor is in or at a timestamp."
16738 (interactive)
16739 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16740 (pos (point))
16741 (ans (or (looking-at tsr)
16742 (save-excursion
16743 (skip-chars-backward "^[<\n\r\t")
16744 (if (> (point) (point-min)) (backward-char 1))
16745 (and (looking-at tsr)
16746 (> (- (match-end 0) pos) -1))))))
16747 (and ans
16748 (boundp 'org-ts-what)
16749 (setq org-ts-what
16750 (cond
16751 ((= pos (match-beginning 0)) 'bracket)
16752 ;; Point is considered to be "on the bracket" whether
16753 ;; it's really on it or right after it.
16754 ((= pos (1- (match-end 0))) 'bracket)
16755 ((= pos (match-end 0)) 'after)
16756 ((org-pos-in-match-range pos 2) 'year)
16757 ((org-pos-in-match-range pos 3) 'month)
16758 ((org-pos-in-match-range pos 7) 'hour)
16759 ((org-pos-in-match-range pos 8) 'minute)
16760 ((or (org-pos-in-match-range pos 4)
16761 (org-pos-in-match-range pos 5)) 'day)
16762 ((and (> pos (or (match-end 8) (match-end 5)))
16763 (< pos (match-end 0)))
16764 (- pos (or (match-end 8) (match-end 5))))
16765 (t 'day))))
16766 ans))
16768 (defun org-toggle-timestamp-type ()
16769 "Toggle the type (<active> or [inactive]) of a time stamp."
16770 (interactive)
16771 (when (org-at-timestamp-p t)
16772 (let ((beg (match-beginning 0)) (end (match-end 0))
16773 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16774 (save-excursion
16775 (goto-char beg)
16776 (while (re-search-forward "[][<>]" end t)
16777 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16778 t t)))
16779 (message "Timestamp is now %sactive"
16780 (if (equal (char-after beg) ?<) "" "in")))))
16782 (defvar org-clock-history) ; defined in org-clock.el
16783 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16784 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16785 "Change the date in the time stamp at point.
16786 The date will be changed by N times WHAT. WHAT can be `day', `month',
16787 `year', `minute', `second'. If WHAT is not given, the cursor position
16788 in the timestamp determines what will be changed.
16789 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16790 (let ((origin (point)) origin-cat
16791 with-hm inactive
16792 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16793 org-ts-what
16794 extra rem
16795 ts time time0 fixnext clrgx)
16796 (if (not (org-at-timestamp-p t))
16797 (error "Not at a timestamp"))
16798 (if (and (not what) (eq org-ts-what 'bracket))
16799 (org-toggle-timestamp-type)
16800 ;; Point isn't on brackets. Remember the part of the time-stamp
16801 ;; the point was in. Indeed, size of time-stamps may change,
16802 ;; but point must be kept in the same category nonetheless.
16803 (setq origin-cat org-ts-what)
16804 (if (and (not what) (not (eq org-ts-what 'day))
16805 org-display-custom-times
16806 (get-text-property (point) 'display)
16807 (not (get-text-property (1- (point)) 'display)))
16808 (setq org-ts-what 'day))
16809 (setq org-ts-what (or what org-ts-what)
16810 inactive (= (char-after (match-beginning 0)) ?\[)
16811 ts (match-string 0))
16812 (replace-match "")
16813 (when (string-match
16814 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16816 (setq extra (match-string 1 ts))
16817 (if suppress-tmp-delay
16818 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16819 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16820 (setq with-hm t))
16821 (setq time0 (org-parse-time-string ts))
16822 (when (and updown
16823 (eq org-ts-what 'minute)
16824 (not current-prefix-arg))
16825 ;; This looks like s-up and s-down. Change by one rounding step.
16826 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16827 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16828 (setcar (cdr time0) (+ (nth 1 time0)
16829 (if (> n 0) (- rem) (- dm rem))))))
16830 (setq time
16831 (encode-time (or (car time0) 0)
16832 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16833 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16834 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16835 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16836 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16837 (nthcdr 6 time0)))
16838 (when (and (member org-ts-what '(hour minute))
16839 extra
16840 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16841 (setq extra (org-modify-ts-extra
16842 extra
16843 (if (eq org-ts-what 'hour) 2 5)
16844 n dm)))
16845 (when (integerp org-ts-what)
16846 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16847 (if (eq what 'calendar)
16848 (let ((cal-date (org-get-date-from-calendar)))
16849 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16850 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16851 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16852 (setcar time0 (or (car time0) 0))
16853 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16854 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16855 (setq time (apply 'encode-time time0))))
16856 ;; Insert the new time-stamp, and ensure point stays in the same
16857 ;; category as before (i.e. not after the last position in that
16858 ;; category).
16859 (let ((pos (point)))
16860 ;; Stay before inserted string. `save-excursion' is of no use.
16861 (setq org-last-changed-timestamp
16862 (org-insert-time-stamp time with-hm inactive nil nil extra))
16863 (goto-char pos))
16864 (save-match-data
16865 (looking-at org-ts-regexp3)
16866 (goto-char (cond
16867 ;; `day' category ends before `hour' if any, or at
16868 ;; the end of the day name.
16869 ((eq origin-cat 'day)
16870 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16871 ((eq origin-cat 'hour) (min (match-end 7) origin))
16872 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16873 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16874 ;; `year' and `month' have both fixed size: point
16875 ;; couldn't have moved into another part.
16876 (t origin))))
16877 ;; Update clock if on a CLOCK line.
16878 (org-clock-update-time-maybe)
16879 ;; Maybe adjust the closest clock in `org-clock-history'
16880 (when org-clock-adjust-closest
16881 (if (not (and (org-at-clock-log-p)
16882 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16883 org-clock-history))))))
16884 (message "No clock to adjust")
16885 (cond ((save-excursion ; fix previous clock?
16886 (re-search-backward org-ts-regexp0 nil t)
16887 (org-looking-back (concat org-clock-string " \\[")))
16888 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16889 ((save-excursion ; fix next clock?
16890 (re-search-backward org-ts-regexp0 nil t)
16891 (looking-at (concat org-ts-regexp0 "\\] =>")))
16892 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16893 (save-window-excursion
16894 ;; Find closest clock to point, adjust the previous/next one in history
16895 (let* ((p (save-excursion (org-back-to-heading t)))
16896 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16897 (clfixnth
16898 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16899 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16900 (if (not clfixpos)
16901 (message "No clock to adjust")
16902 (save-excursion
16903 (org-goto-marker-or-bmk clfixpos)
16904 (org-show-subtree)
16905 (when (re-search-forward clrgx nil t)
16906 (goto-char (match-beginning 1))
16907 (let (org-clock-adjust-closest)
16908 (org-timestamp-change n org-ts-what updown))
16909 (message "Clock adjusted in %s for heading: %s"
16910 (file-name-nondirectory (buffer-file-name))
16911 (org-get-heading t t)))))))))
16912 ;; Try to recenter the calendar window, if any.
16913 (if (and org-calendar-follow-timestamp-change
16914 (get-buffer-window "*Calendar*" t)
16915 (memq org-ts-what '(day month year)))
16916 (org-recenter-calendar (time-to-days time))))))
16918 (defun org-modify-ts-extra (s pos n dm)
16919 "Change the different parts of the lead-time and repeat fields in timestamp."
16920 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16921 ng h m new rem)
16922 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16923 (cond
16924 ((or (org-pos-in-match-range pos 2)
16925 (org-pos-in-match-range pos 3))
16926 (setq m (string-to-number (match-string 3 s))
16927 h (string-to-number (match-string 2 s)))
16928 (if (org-pos-in-match-range pos 2)
16929 (setq h (+ h n))
16930 (setq n (* dm (org-no-warnings (signum n))))
16931 (when (not (= 0 (setq rem (% m dm))))
16932 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16933 (setq m (+ m n)))
16934 (if (< m 0) (setq m (+ m 60) h (1- h)))
16935 (if (> m 59) (setq m (- m 60) h (1+ h)))
16936 (setq h (min 24 (max 0 h)))
16937 (setq ng 1 new (format "-%02d:%02d" h m)))
16938 ((org-pos-in-match-range pos 6)
16939 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16940 ((org-pos-in-match-range pos 5)
16941 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16943 ((org-pos-in-match-range pos 9)
16944 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16945 ((org-pos-in-match-range pos 8)
16946 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16948 (when ng
16949 (setq s (concat
16950 (substring s 0 (match-beginning ng))
16952 (substring s (match-end ng))))))
16955 (defun org-recenter-calendar (date)
16956 "If the calendar is visible, recenter it to DATE."
16957 (let ((cwin (get-buffer-window "*Calendar*" t)))
16958 (when cwin
16959 (let ((calendar-move-hook nil))
16960 (with-selected-window cwin
16961 (calendar-goto-date (if (listp date) date
16962 (calendar-gregorian-from-absolute date))))))))
16964 (defun org-goto-calendar (&optional arg)
16965 "Go to the Emacs calendar at the current date.
16966 If there is a time stamp in the current line, go to that date.
16967 A prefix ARG can be used to force the current date."
16968 (interactive "P")
16969 (let ((tsr org-ts-regexp) diff
16970 (calendar-move-hook nil)
16971 (calendar-view-holidays-initially-flag nil)
16972 (calendar-view-diary-initially-flag nil))
16973 (if (or (org-at-timestamp-p)
16974 (save-excursion
16975 (beginning-of-line 1)
16976 (looking-at (concat ".*" tsr))))
16977 (let ((d1 (time-to-days (current-time)))
16978 (d2 (time-to-days
16979 (org-time-string-to-time (match-string 1)))))
16980 (setq diff (- d2 d1))))
16981 (calendar)
16982 (calendar-goto-today)
16983 (if (and diff (not arg)) (calendar-forward-day diff))))
16985 (defun org-get-date-from-calendar ()
16986 "Return a list (month day year) of date at point in calendar."
16987 (with-current-buffer "*Calendar*"
16988 (save-match-data
16989 (calendar-cursor-to-date))))
16991 (defun org-date-from-calendar ()
16992 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16993 If there is already a time stamp at the cursor position, update it."
16994 (interactive)
16995 (if (org-at-timestamp-p t)
16996 (org-timestamp-change 0 'calendar)
16997 (let ((cal-date (org-get-date-from-calendar)))
16998 (org-insert-time-stamp
16999 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17001 (defcustom org-effort-durations
17002 `(("h" . 60)
17003 ("d" . ,(* 60 8))
17004 ("w" . ,(* 60 8 5))
17005 ("m" . ,(* 60 8 5 4))
17006 ("y" . ,(* 60 8 5 40)))
17007 "Conversion factor to minutes for an effort modifier.
17009 Each entry has the form (MODIFIER . MINUTES).
17011 In an effort string, a number followed by MODIFIER is multiplied
17012 by the specified number of MINUTES to obtain an effort in
17013 minutes.
17015 For example, if the value of this variable is ((\"hours\" . 60)), then an
17016 effort string \"2hours\" is equivalent to 120 minutes."
17017 :group 'org-agenda
17018 :version "24.1"
17019 :type '(alist :key-type (string :tag "Modifier")
17020 :value-type (number :tag "Minutes")))
17022 (defun org-minutes-to-clocksum-string (m)
17023 "Format number of minutes as a clocksum string.
17024 The format is determined by `org-time-clocksum-format',
17025 `org-time-clocksum-use-fractional' and
17026 `org-time-clocksum-fractional-format' and
17027 `org-time-clocksum-use-effort-durations'."
17028 (let ((clocksum "") h d w mo y fmt n)
17029 (setq h (if org-time-clocksum-use-effort-durations
17030 (cdr (assoc "h" org-effort-durations)) 60)
17031 d (if org-time-clocksum-use-effort-durations
17032 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17033 w (if org-time-clocksum-use-effort-durations
17034 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17035 mo (if org-time-clocksum-use-effort-durations
17036 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17037 y (if org-time-clocksum-use-effort-durations
17038 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17039 ;; fractional format
17040 (if org-time-clocksum-use-fractional
17041 (cond
17042 ;; single format string
17043 ((stringp org-time-clocksum-fractional-format)
17044 (format org-time-clocksum-fractional-format (/ m (float h))))
17045 ;; choice of fractional formats for different time units
17046 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17047 (> (/ (truncate m) (* y d h)) 0))
17048 (format fmt (/ m (* y d (float h)))))
17049 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17050 (> (/ (truncate m) (* mo d h)) 0))
17051 (format fmt (/ m (* mo d (float h)))))
17052 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17053 (> (/ (truncate m) (* w d h)) 0))
17054 (format fmt (/ m (* w d (float h)))))
17055 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17056 (> (/ (truncate m) (* d h)) 0))
17057 (format fmt (/ m (* d (float h)))))
17058 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17059 (> (/ (truncate m) h) 0))
17060 (format fmt (/ m (float h))))
17061 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17062 (format fmt m))
17063 ;; fall back to smallest time unit with a format
17064 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17065 (format fmt (/ m (float h))))
17066 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17067 (format fmt (/ m (* d (float h)))))
17068 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17069 (format fmt (/ m (* w d (float h)))))
17070 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17071 (format fmt (/ m (* mo d (float h)))))
17072 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17073 (format fmt (/ m (* y d (float h))))))
17074 ;; standard (non-fractional) format, with single format string
17075 (if (stringp org-time-clocksum-format)
17076 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17077 ;; separate formats components
17078 (and (setq fmt (plist-get org-time-clocksum-format :years))
17079 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17080 (plist-get org-time-clocksum-format :require-years))
17081 (setq clocksum (concat clocksum (format fmt n))
17082 m (- m (* n y d h))))
17083 (and (setq fmt (plist-get org-time-clocksum-format :months))
17084 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17085 (plist-get org-time-clocksum-format :require-months))
17086 (setq clocksum (concat clocksum (format fmt n))
17087 m (- m (* n mo d h))))
17088 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17089 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17090 (plist-get org-time-clocksum-format :require-weeks))
17091 (setq clocksum (concat clocksum (format fmt n))
17092 m (- m (* n w d h))))
17093 (and (setq fmt (plist-get org-time-clocksum-format :days))
17094 (or (> (setq n (/ (truncate m) (* d h))) 0)
17095 (plist-get org-time-clocksum-format :require-days))
17096 (setq clocksum (concat clocksum (format fmt n))
17097 m (- m (* n d h))))
17098 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17099 (or (> (setq n (/ (truncate m) h)) 0)
17100 (plist-get org-time-clocksum-format :require-hours))
17101 (setq clocksum (concat clocksum (format fmt n))
17102 m (- m (* n h))))
17103 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17104 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17105 (setq clocksum (concat clocksum (format fmt m))))
17106 ;; return formatted time duration
17107 clocksum))))
17109 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17110 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17111 "Org mode version 8.0")
17113 (defun org-hours-to-clocksum-string (n)
17114 (org-minutes-to-clocksum-string (* n 60)))
17116 (defun org-hh:mm-string-to-minutes (s)
17117 "Convert a string H:MM to a number of minutes.
17118 If the string is just a number, interpret it as minutes.
17119 In fact, the first hh:mm or number in the string will be taken,
17120 there can be extra stuff in the string.
17121 If no number is found, the return value is 0."
17122 (cond
17123 ((integerp s) s)
17124 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17125 (+ (* (string-to-number (match-string 1 s)) 60)
17126 (string-to-number (match-string 2 s))))
17127 ((string-match "\\([0-9]+\\)" s)
17128 (string-to-number (match-string 1 s)))
17129 (t 0)))
17131 (defcustom org-image-actual-width t
17132 "Should we use the actual width of images when inlining them?
17134 When set to `t', always use the image width.
17136 When set to a number, use imagemagick (when available) to set
17137 the image's width to this value.
17139 When set to a number in a list, try to get the width from the
17140 #+ATTR.* keyword if it matches a width specification like
17141 width=\"[0-9]+\", and fall back on that number if none is found.
17143 When set to nil, try to get the width from an #+ATTR.* keyword
17144 and fall back on the original width if none is found.
17146 This requires Emacs >= 24.1, build with imagemagick support."
17147 :group 'org-appearance
17148 :version "24.3"
17149 :type '(choice
17150 (const :tag "Use the image width" t)
17151 (integer :tag "Use a number of pixels")
17152 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17153 (const :tag "Use #+ATTR* or don't resize" nil)))
17155 (defcustom org-agenda-inhibit-startup t
17156 "Inhibit startup when preparing agenda buffers.
17157 When this variable is `t' (the default), the initialization of
17158 the Org agenda buffers is inhibited: e.g. the visibility state
17159 is not set, the tables are not re-aligned, etc."
17160 :type 'boolean
17161 :version "24.3"
17162 :group 'org-agenda)
17164 (defun org-duration-string-to-minutes (s &optional output-to-string)
17165 "Convert a duration string S to minutes.
17167 A bare number is interpreted as minutes, modifiers can be set by
17168 customizing `org-effort-durations' (which see).
17170 Entries containing a colon are interpreted as H:MM by
17171 `org-hh:mm-string-to-minutes'."
17172 (let ((result 0)
17173 (re (concat "\\([0-9.]+\\) *\\("
17174 (regexp-opt (mapcar 'car org-effort-durations))
17175 "\\)")))
17176 (while (string-match re s)
17177 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17178 (string-to-number (match-string 1 s))))
17179 (setq s (replace-match "" nil t s)))
17180 (setq result (floor result))
17181 (incf result (org-hh:mm-string-to-minutes s))
17182 (if output-to-string (number-to-string result) result)))
17184 ;;;; Files
17186 (defun org-save-all-org-buffers ()
17187 "Save all Org-mode buffers without user confirmation."
17188 (interactive)
17189 (message "Saving all Org-mode buffers...")
17190 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17191 (when (featurep 'org-id) (org-id-locations-save))
17192 (message "Saving all Org-mode buffers... done"))
17194 (defun org-revert-all-org-buffers ()
17195 "Revert all Org-mode buffers.
17196 Prompt for confirmation when there are unsaved changes.
17197 Be sure you know what you are doing before letting this function
17198 overwrite your changes.
17200 This function is useful in a setup where one tracks org files
17201 with a version control system, to revert on one machine after pulling
17202 changes from another. I believe the procedure must be like this:
17204 1. M-x org-save-all-org-buffers
17205 2. Pull changes from the other machine, resolve conflicts
17206 3. M-x org-revert-all-org-buffers"
17207 (interactive)
17208 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17209 (error "Abort"))
17210 (save-excursion
17211 (save-window-excursion
17212 (mapc
17213 (lambda (b)
17214 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17215 (with-current-buffer b buffer-file-name))
17216 (org-pop-to-buffer-same-window b)
17217 (revert-buffer t 'no-confirm)))
17218 (buffer-list))
17219 (when (and (featurep 'org-id) org-id-track-globally)
17220 (org-id-locations-load)))))
17222 ;;;; Agenda files
17224 ;;;###autoload
17225 (defun org-switchb (&optional arg)
17226 "Switch between Org buffers.
17227 With one prefix argument, restrict available buffers to files.
17228 With two prefix arguments, restrict available buffers to agenda files.
17230 Defaults to `iswitchb' for buffer name completion.
17231 Set `org-completion-use-ido' to make it use ido instead."
17232 (interactive "P")
17233 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17234 ((equal arg '(16)) (org-buffer-list 'agenda))
17235 (t (org-buffer-list))))
17236 (org-completion-use-iswitchb org-completion-use-iswitchb)
17237 (org-completion-use-ido org-completion-use-ido))
17238 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17239 (setq org-completion-use-iswitchb t))
17240 (org-pop-to-buffer-same-window
17241 (org-icompleting-read "Org buffer: "
17242 (mapcar 'list (mapcar 'buffer-name blist))
17243 nil t))))
17245 ;;; Define some older names previously used for this functionality
17246 ;;;###autoload
17247 (defalias 'org-ido-switchb 'org-switchb)
17248 ;;;###autoload
17249 (defalias 'org-iswitchb 'org-switchb)
17251 (defun org-buffer-list (&optional predicate exclude-tmp)
17252 "Return a list of Org buffers.
17253 PREDICATE can be `export', `files' or `agenda'.
17255 export restrict the list to Export buffers.
17256 files restrict the list to buffers visiting Org files.
17257 agenda restrict the list to buffers visiting agenda files.
17259 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17260 (let* ((bfn nil)
17261 (agenda-files (and (eq predicate 'agenda)
17262 (mapcar 'file-truename (org-agenda-files t))))
17263 (filter
17264 (cond
17265 ((eq predicate 'files)
17266 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17267 ((eq predicate 'export)
17268 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17269 ((eq predicate 'agenda)
17270 (lambda (b)
17271 (with-current-buffer b
17272 (and (derived-mode-p 'org-mode)
17273 (setq bfn (buffer-file-name b))
17274 (member (file-truename bfn) agenda-files)))))
17275 (t (lambda (b) (with-current-buffer b
17276 (or (derived-mode-p 'org-mode)
17277 (string-match "\*Org .*Export"
17278 (buffer-name b)))))))))
17279 (delq nil
17280 (mapcar
17281 (lambda(b)
17282 (if (and (funcall filter b)
17283 (or (not exclude-tmp)
17284 (not (string-match "tmp" (buffer-name b)))))
17286 nil))
17287 (buffer-list)))))
17289 (defun org-agenda-files (&optional unrestricted archives)
17290 "Get the list of agenda files.
17291 Optional UNRESTRICTED means return the full list even if a restriction
17292 is currently in place.
17293 When ARCHIVES is t, include all archive files that are really being
17294 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17295 `org-agenda-archives-mode' is t."
17296 (let ((files
17297 (cond
17298 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17299 ((stringp org-agenda-files) (org-read-agenda-file-list))
17300 ((listp org-agenda-files) org-agenda-files)
17301 (t (error "Invalid value of `org-agenda-files'")))))
17302 (setq files (apply 'append
17303 (mapcar (lambda (f)
17304 (if (file-directory-p f)
17305 (directory-files
17306 f t org-agenda-file-regexp)
17307 (list f)))
17308 files)))
17309 (when org-agenda-skip-unavailable-files
17310 (setq files (delq nil
17311 (mapcar (function
17312 (lambda (file)
17313 (and (file-readable-p file) file)))
17314 files))))
17315 (when (or (eq archives t)
17316 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17317 (setq files (org-add-archive-files files)))
17318 files))
17320 (defun org-agenda-file-p (&optional file)
17321 "Return non-nil, if FILE is an agenda file.
17322 If FILE is omitted, use the file associated with the current
17323 buffer."
17324 (member (or file (buffer-file-name))
17325 (org-agenda-files t)))
17327 (defun org-edit-agenda-file-list ()
17328 "Edit the list of agenda files.
17329 Depending on setup, this either uses customize to edit the variable
17330 `org-agenda-files', or it visits the file that is holding the list. In the
17331 latter case, the buffer is set up in a way that saving it automatically kills
17332 the buffer and restores the previous window configuration."
17333 (interactive)
17334 (if (stringp org-agenda-files)
17335 (let ((cw (current-window-configuration)))
17336 (find-file org-agenda-files)
17337 (org-set-local 'org-window-configuration cw)
17338 (org-add-hook 'after-save-hook
17339 (lambda ()
17340 (set-window-configuration
17341 (prog1 org-window-configuration
17342 (kill-buffer (current-buffer))))
17343 (org-install-agenda-files-menu)
17344 (message "New agenda file list installed"))
17345 nil 'local)
17346 (message "%s" (substitute-command-keys
17347 "Edit list and finish with \\[save-buffer]")))
17348 (customize-variable 'org-agenda-files)))
17350 (defun org-store-new-agenda-file-list (list)
17351 "Set new value for the agenda file list and save it correctly."
17352 (if (stringp org-agenda-files)
17353 (let ((fe (org-read-agenda-file-list t)) b u)
17354 (while (setq b (find-buffer-visiting org-agenda-files))
17355 (kill-buffer b))
17356 (with-temp-file org-agenda-files
17357 (insert
17358 (mapconcat
17359 (lambda (f) ;; Keep un-expanded entries.
17360 (if (setq u (assoc f fe))
17361 (cdr u)
17363 list "\n")
17364 "\n")))
17365 (let ((org-mode-hook nil) (org-inhibit-startup t)
17366 (org-insert-mode-line-in-empty-file nil))
17367 (setq org-agenda-files list)
17368 (customize-save-variable 'org-agenda-files org-agenda-files))))
17370 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17371 "Read the list of agenda files from a file.
17372 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17373 filenames, used by `org-store-new-agenda-file-list' to write back
17374 un-expanded file names."
17375 (when (file-directory-p org-agenda-files)
17376 (error "`org-agenda-files' cannot be a single directory"))
17377 (when (stringp org-agenda-files)
17378 (with-temp-buffer
17379 (insert-file-contents org-agenda-files)
17380 (mapcar
17381 (lambda (f)
17382 (let ((e (expand-file-name (substitute-in-file-name f)
17383 org-directory)))
17384 (if pair-with-expansion
17385 (cons e f)
17386 e)))
17387 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17389 ;;;###autoload
17390 (defun org-cycle-agenda-files ()
17391 "Cycle through the files in `org-agenda-files'.
17392 If the current buffer visits an agenda file, find the next one in the list.
17393 If the current buffer does not, find the first agenda file."
17394 (interactive)
17395 (let* ((fs (org-agenda-files t))
17396 (files (append fs (list (car fs))))
17397 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17398 file)
17399 (unless files (error "No agenda files"))
17400 (catch 'exit
17401 (while (setq file (pop files))
17402 (if (equal (file-truename file) tcf)
17403 (when (car files)
17404 (find-file (car files))
17405 (throw 'exit t))))
17406 (find-file (car fs)))
17407 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17409 (defun org-agenda-file-to-front (&optional to-end)
17410 "Move/add the current file to the top of the agenda file list.
17411 If the file is not present in the list, it is added to the front. If it is
17412 present, it is moved there. With optional argument TO-END, add/move to the
17413 end of the list."
17414 (interactive "P")
17415 (let ((org-agenda-skip-unavailable-files nil)
17416 (file-alist (mapcar (lambda (x)
17417 (cons (file-truename x) x))
17418 (org-agenda-files t)))
17419 (ctf (file-truename
17420 (or buffer-file-name
17421 (error "Please save the current buffer to a file"))))
17422 x had)
17423 (setq x (assoc ctf file-alist) had x)
17425 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17426 (if to-end
17427 (setq file-alist (append (delq x file-alist) (list x)))
17428 (setq file-alist (cons x (delq x file-alist))))
17429 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17430 (org-install-agenda-files-menu)
17431 (message "File %s to %s of agenda file list"
17432 (if had "moved" "added") (if to-end "end" "front"))))
17434 (defun org-remove-file (&optional file)
17435 "Remove current file from the list of files in variable `org-agenda-files'.
17436 These are the files which are being checked for agenda entries.
17437 Optional argument FILE means use this file instead of the current."
17438 (interactive)
17439 (let* ((org-agenda-skip-unavailable-files nil)
17440 (file (or file buffer-file-name
17441 (error "Current buffer does not visit a file")))
17442 (true-file (file-truename file))
17443 (afile (abbreviate-file-name file))
17444 (files (delq nil (mapcar
17445 (lambda (x)
17446 (if (equal true-file
17447 (file-truename x))
17448 nil x))
17449 (org-agenda-files t)))))
17450 (if (not (= (length files) (length (org-agenda-files t))))
17451 (progn
17452 (org-store-new-agenda-file-list files)
17453 (org-install-agenda-files-menu)
17454 (message "Removed file: %s" afile))
17455 (message "File was not in list: %s (not removed)" afile))))
17457 (defun org-file-menu-entry (file)
17458 (vector file (list 'find-file file) t))
17460 (defun org-check-agenda-file (file)
17461 "Make sure FILE exists. If not, ask user what to do."
17462 (when (not (file-exists-p file))
17463 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17464 (abbreviate-file-name file))
17465 (let ((r (downcase (read-char-exclusive))))
17466 (cond
17467 ((equal r ?r)
17468 (org-remove-file file)
17469 (throw 'nextfile t))
17470 (t (error "Abort"))))))
17472 (defun org-get-agenda-file-buffer (file)
17473 "Get a buffer visiting FILE. If the buffer needs to be created, add
17474 it to the list of buffers which might be released later."
17475 (let ((buf (org-find-base-buffer-visiting file)))
17476 (if buf
17477 buf ; just return it
17478 ;; Make a new buffer and remember it
17479 (setq buf (find-file-noselect file))
17480 (if buf (push buf org-agenda-new-buffers))
17481 buf)))
17483 (defun org-release-buffers (blist)
17484 "Release all buffers in list, asking the user for confirmation when needed.
17485 When a buffer is unmodified, it is just killed. When modified, it is saved
17486 \(if the user agrees) and then killed."
17487 (let (buf file)
17488 (while (setq buf (pop blist))
17489 (setq file (buffer-file-name buf))
17490 (when (and (buffer-modified-p buf)
17491 file
17492 (y-or-n-p (format "Save file %s? " file)))
17493 (with-current-buffer buf (save-buffer)))
17494 (kill-buffer buf))))
17496 (defun org-agenda-prepare-buffers (files)
17497 "Create buffers for all agenda files, protect archived trees and comments."
17498 (interactive)
17499 (let ((pa '(:org-archived t))
17500 (pc '(:org-comment t))
17501 (pall '(:org-archived t :org-comment t))
17502 (inhibit-read-only t)
17503 (org-inhibit-startup org-agenda-inhibit-startup)
17504 (rea (concat ":" org-archive-tag ":"))
17505 file re)
17506 (save-excursion
17507 (save-restriction
17508 (while (setq file (pop files))
17509 (catch 'nextfile
17510 (if (bufferp file)
17511 (set-buffer file)
17512 (org-check-agenda-file file)
17513 (set-buffer (org-get-agenda-file-buffer file)))
17514 (widen)
17515 (org-unmodified
17516 (org-refresh-category-properties)
17517 (org-refresh-properties org-effort-property 'org-effort)
17518 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17519 (setq org-todo-keywords-for-agenda
17520 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17521 (setq org-done-keywords-for-agenda
17522 (append org-done-keywords-for-agenda org-done-keywords))
17523 (setq org-todo-keyword-alist-for-agenda
17524 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17525 (setq org-drawers-for-agenda
17526 (append org-drawers-for-agenda org-drawers))
17527 (setq org-tag-alist-for-agenda
17528 (append org-tag-alist-for-agenda org-tag-alist))
17530 (save-excursion
17531 (remove-text-properties (point-min) (point-max) pall)
17532 (when org-agenda-skip-archived-trees
17533 (goto-char (point-min))
17534 (while (re-search-forward rea nil t)
17535 (if (org-at-heading-p t)
17536 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17537 (goto-char (point-min))
17538 (setq re (format org-heading-keyword-regexp-format
17539 org-comment-string))
17540 (while (re-search-forward re nil t)
17541 (add-text-properties
17542 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17543 (setq org-todo-keywords-for-agenda
17544 (org-uniquify org-todo-keywords-for-agenda))
17545 (setq org-todo-keyword-alist-for-agenda
17546 (org-uniquify org-todo-keyword-alist-for-agenda)
17547 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17551 ;;;; CDLaTeX minor mode
17553 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17554 "Keymap for the minor `org-cdlatex-mode'.")
17556 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17557 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17558 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17559 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17560 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17562 (defvar org-cdlatex-texmathp-advice-is-done nil
17563 "Flag remembering if we have applied the advice to texmathp already.")
17565 (define-minor-mode org-cdlatex-mode
17566 "Toggle the minor `org-cdlatex-mode'.
17567 This mode supports entering LaTeX environment and math in LaTeX fragments
17568 in Org-mode.
17569 \\{org-cdlatex-mode-map}"
17570 nil " OCDL" nil
17571 (when org-cdlatex-mode
17572 (require 'cdlatex)
17573 (run-hooks 'cdlatex-mode-hook)
17574 (cdlatex-compute-tables))
17575 (unless org-cdlatex-texmathp-advice-is-done
17576 (setq org-cdlatex-texmathp-advice-is-done t)
17577 (defadvice texmathp (around org-math-always-on activate)
17578 "Always return t in org-mode buffers.
17579 This is because we want to insert math symbols without dollars even outside
17580 the LaTeX math segments. If Orgmode thinks that point is actually inside
17581 an embedded LaTeX fragment, let texmathp do its job.
17582 \\[org-cdlatex-mode-map]"
17583 (interactive)
17584 (let (p)
17585 (cond
17586 ((not (derived-mode-p 'org-mode)) ad-do-it)
17587 ((eq this-command 'cdlatex-math-symbol)
17588 (setq ad-return-value t
17589 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17591 (let ((p (org-inside-LaTeX-fragment-p)))
17592 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17593 (setq ad-return-value t
17594 texmathp-why '("Org-mode embedded math" . 0))
17595 (if p ad-do-it)))))))))
17597 (defun turn-on-org-cdlatex ()
17598 "Unconditionally turn on `org-cdlatex-mode'."
17599 (org-cdlatex-mode 1))
17601 (defun org-try-cdlatex-tab ()
17602 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17603 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17604 - inside a LaTeX fragment, or
17605 - after the first word in a line, where an abbreviation expansion could
17606 insert a LaTeX environment."
17607 (when org-cdlatex-mode
17608 (cond
17609 ;; Before any word on the line: No expansion possible.
17610 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17611 ;; Just after first word on the line: Expand it. Make sure it
17612 ;; cannot happen on headlines, though.
17613 ((save-excursion
17614 (skip-chars-backward "a-zA-Z0-9*")
17615 (skip-chars-backward " \t")
17616 (and (bolp) (not (org-at-heading-p))))
17617 (cdlatex-tab) t)
17618 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17620 (defun org-cdlatex-underscore-caret (&optional arg)
17621 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17622 Revert to the normal definition outside of these fragments."
17623 (interactive "P")
17624 (if (org-inside-LaTeX-fragment-p)
17625 (call-interactively 'cdlatex-sub-superscript)
17626 (let (org-cdlatex-mode)
17627 (call-interactively (key-binding (vector last-input-event))))))
17629 (defun org-cdlatex-math-modify (&optional arg)
17630 "Execute `cdlatex-math-modify' in LaTeX fragments.
17631 Revert to the normal definition outside of these fragments."
17632 (interactive "P")
17633 (if (org-inside-LaTeX-fragment-p)
17634 (call-interactively 'cdlatex-math-modify)
17635 (let (org-cdlatex-mode)
17636 (call-interactively (key-binding (vector last-input-event))))))
17640 ;;;; LaTeX fragments
17642 (defvar org-latex-regexps
17643 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17644 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17645 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17646 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17647 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17648 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17649 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17650 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17651 "Regular expressions for matching embedded LaTeX.")
17653 (defun org-inside-LaTeX-fragment-p ()
17654 "Test if point is inside a LaTeX fragment.
17655 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17656 sequence appearing also before point.
17657 Even though the matchers for math are configurable, this function assumes
17658 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17659 delimiters are skipped when they have been removed by customization.
17660 The return value is nil, or a cons cell with the delimiter and the
17661 position of this delimiter.
17663 This function does a reasonably good job, but can locally be fooled by
17664 for example currency specifications. For example it will assume being in
17665 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17666 fragments that are properly closed, but during editing, we have to live
17667 with the uncertainty caused by missing closing delimiters. This function
17668 looks only before point, not after."
17669 (catch 'exit
17670 (let ((pos (point))
17671 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17672 (lim (progn
17673 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17674 (point)))
17675 dd-on str (start 0) m re)
17676 (goto-char pos)
17677 (when dodollar
17678 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17679 re (nth 1 (assoc "$" org-latex-regexps)))
17680 (while (string-match re str start)
17681 (cond
17682 ((= (match-end 0) (length str))
17683 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17684 ((= (match-end 0) (- (length str) 5))
17685 (throw 'exit nil))
17686 (t (setq start (match-end 0))))))
17687 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17688 (goto-char pos)
17689 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17690 (and (match-beginning 2) (throw 'exit nil))
17691 ;; count $$
17692 (while (re-search-backward "\\$\\$" lim t)
17693 (setq dd-on (not dd-on)))
17694 (goto-char pos)
17695 (if dd-on (cons "$$" m))))))
17697 (defun org-inside-latex-macro-p ()
17698 "Is point inside a LaTeX macro or its arguments?"
17699 (save-match-data
17700 (org-in-regexp
17701 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17703 (defvar org-latex-fragment-image-overlays nil
17704 "List of overlays carrying the images of latex fragments.")
17705 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17707 (defun org-remove-latex-fragment-image-overlays ()
17708 "Remove all overlays with LaTeX fragment images in current buffer."
17709 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17710 (setq org-latex-fragment-image-overlays nil))
17712 (defun org-preview-latex-fragment (&optional subtree)
17713 "Preview the LaTeX fragment at point, or all locally or globally.
17714 If the cursor is in a LaTeX fragment, create the image and overlay
17715 it over the source code. If there is no fragment at point, display
17716 all fragments in the current text, from one headline to the next. With
17717 prefix SUBTREE, display all fragments in the current subtree. With a
17718 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17719 the cursor is before the first headline,
17720 display all fragments in the buffer.
17721 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17722 (interactive "P")
17723 (unless buffer-file-name
17724 (error "Can't preview LaTeX fragment in a non-file buffer"))
17725 (org-remove-latex-fragment-image-overlays)
17726 (save-excursion
17727 (save-restriction
17728 (let (beg end at msg)
17729 (cond
17730 ((or (equal subtree '(16))
17731 (not (save-excursion
17732 (re-search-backward org-outline-regexp-bol nil t))))
17733 (setq beg (point-min) end (point-max)
17734 msg "Creating images for buffer...%s"))
17735 ((equal subtree '(4))
17736 (org-back-to-heading)
17737 (setq beg (point) end (org-end-of-subtree t)
17738 msg "Creating images for subtree...%s"))
17740 (if (setq at (org-inside-LaTeX-fragment-p))
17741 (goto-char (max (point-min) (- (cdr at) 2)))
17742 (org-back-to-heading))
17743 (setq beg (point) end (progn (outline-next-heading) (point))
17744 msg (if at "Creating image...%s"
17745 "Creating images for entry...%s"))))
17746 (message msg "")
17747 (narrow-to-region beg end)
17748 (goto-char beg)
17749 (org-format-latex
17750 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17751 (file-name-nondirectory
17752 buffer-file-name)))
17753 default-directory 'overlays msg at 'forbuffer
17754 org-latex-create-formula-image-program)
17755 (message msg "done. Use `C-c C-c' to remove images.")))))
17757 (defun org-format-latex (prefix &optional dir overlays msg at
17758 forbuffer processing-type)
17759 "Replace LaTeX fragments with links to an image, and produce images.
17760 Some of the options can be changed using the variable
17761 `org-format-latex-options'."
17762 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17763 (let* ((prefixnodir (file-name-nondirectory prefix))
17764 (absprefix (expand-file-name prefix dir))
17765 (todir (file-name-directory absprefix))
17766 (opt org-format-latex-options)
17767 (optnew org-format-latex-options)
17768 (matchers (plist-get opt :matchers))
17769 (re-list org-latex-regexps)
17770 (cnt 0) txt hash link beg end re e checkdir
17771 string
17772 m n block-type block linkfile movefile ov)
17773 ;; Check the different regular expressions
17774 (while (setq e (pop re-list))
17775 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17776 block (if block-type "\n\n" ""))
17777 (when (member m matchers)
17778 (goto-char (point-min))
17779 (while (re-search-forward re nil t)
17780 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17781 (or (not overlays)
17782 (not (eq (get-char-property (match-beginning n)
17783 'org-overlay-type)
17784 'org-latex-overlay))))
17785 (cond
17786 ((eq processing-type 'verbatim))
17787 ((eq processing-type 'mathjax)
17788 ;; Prepare for MathJax processing.
17789 (setq string (match-string n))
17790 (when (member m '("$" "$1"))
17791 (save-excursion
17792 (delete-region (match-beginning n) (match-end n))
17793 (goto-char (match-beginning n))
17794 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17795 ((or (eq processing-type 'dvipng)
17796 (eq processing-type 'imagemagick))
17797 ;; Process to an image.
17798 (setq txt (match-string n)
17799 beg (match-beginning n) end (match-end n)
17800 cnt (1+ cnt))
17801 (let ((face (face-at-point))
17802 (fg (plist-get opt :foreground))
17803 (bg (plist-get opt :background))
17804 ;; Ensure full list is printed.
17805 print-length print-level)
17806 (when forbuffer
17807 ;; Get the colors from the face at point.
17808 (goto-char beg)
17809 (when (eq fg 'auto)
17810 (setq fg (face-attribute face :foreground nil 'default)))
17811 (when (eq bg 'auto)
17812 (setq bg (face-attribute face :background nil 'default)))
17813 (setq optnew (copy-sequence opt))
17814 (plist-put optnew :foreground fg)
17815 (plist-put optnew :background bg))
17816 (setq hash (sha1 (prin1-to-string
17817 (list org-format-latex-header
17818 org-latex-default-packages-alist
17819 org-latex-packages-alist
17820 org-format-latex-options
17821 forbuffer txt fg bg)))
17822 linkfile (format "%s_%s.png" prefix hash)
17823 movefile (format "%s_%s.png" absprefix hash)))
17824 (setq link (concat block "[[file:" linkfile "]]" block))
17825 (if msg (message msg cnt))
17826 (goto-char beg)
17827 (unless checkdir ; Ensure the directory exists.
17828 (setq checkdir t)
17829 (or (file-directory-p todir) (make-directory todir t)))
17830 (unless (file-exists-p movefile)
17831 (org-create-formula-image
17832 txt movefile optnew forbuffer processing-type))
17833 (if overlays
17834 (progn
17835 (mapc (lambda (o)
17836 (if (eq (overlay-get o 'org-overlay-type)
17837 'org-latex-overlay)
17838 (delete-overlay o)))
17839 (overlays-in beg end))
17840 (setq ov (make-overlay beg end))
17841 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17842 (if (featurep 'xemacs)
17843 (progn
17844 (overlay-put ov 'invisible t)
17845 (overlay-put
17846 ov 'end-glyph
17847 (make-glyph (vector 'png :file movefile))))
17848 (overlay-put
17849 ov 'display
17850 (list 'image :type 'png :file movefile :ascent 'center)))
17851 (push ov org-latex-fragment-image-overlays)
17852 (goto-char end))
17853 (delete-region beg end)
17854 (insert (org-add-props link
17855 (list 'org-latex-src
17856 (replace-regexp-in-string
17857 "\"" "" txt)
17858 'org-latex-src-embed-type
17859 (if block-type 'paragraph 'character))))))
17860 ((eq processing-type 'mathml)
17861 ;; Process to MathML
17862 (unless (save-match-data (org-format-latex-mathml-available-p))
17863 (error "LaTeX to MathML converter not configured"))
17864 (setq txt (match-string n)
17865 beg (match-beginning n) end (match-end n)
17866 cnt (1+ cnt))
17867 (if msg (message msg cnt))
17868 (goto-char beg)
17869 (delete-region beg end)
17870 (insert (org-format-latex-as-mathml
17871 txt block-type prefix dir)))
17873 (error "Unknown conversion type %s for latex fragments"
17874 processing-type)))))))))
17876 (defun org-create-math-formula (latex-frag &optional mathml-file)
17877 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17878 Use `org-latex-to-mathml-convert-command'. If the conversion is
17879 sucessful, return the portion between \"<math...> </math>\"
17880 elements otherwise return nil. When MATHML-FILE is specified,
17881 write the results in to that file. When invoked as an
17882 interactive command, prompt for LATEX-FRAG, with initial value
17883 set to the current active region and echo the results for user
17884 inspection."
17885 (interactive (list (let ((frag (when (org-region-active-p)
17886 (buffer-substring-no-properties
17887 (region-beginning) (region-end)))))
17888 (read-string "LaTeX Fragment: " frag nil frag))))
17889 (unless latex-frag (error "Invalid latex-frag"))
17890 (let* ((tmp-in-file (file-relative-name
17891 (make-temp-name (expand-file-name "ltxmathml-in"))))
17892 (ignore (write-region latex-frag nil tmp-in-file))
17893 (tmp-out-file (file-relative-name
17894 (make-temp-name (expand-file-name "ltxmathml-out"))))
17895 (cmd (format-spec
17896 org-latex-to-mathml-convert-command
17897 `((?j . ,(shell-quote-argument
17898 (expand-file-name org-latex-to-mathml-jar-file)))
17899 (?I . ,(shell-quote-argument tmp-in-file))
17900 (?o . ,(shell-quote-argument tmp-out-file)))))
17901 mathml shell-command-output)
17902 (when (org-called-interactively-p 'any)
17903 (unless (org-format-latex-mathml-available-p)
17904 (error "LaTeX to MathML converter not configured")))
17905 (message "Running %s" cmd)
17906 (setq shell-command-output (shell-command-to-string cmd))
17907 (setq mathml
17908 (when (file-readable-p tmp-out-file)
17909 (with-current-buffer (find-file-noselect tmp-out-file t)
17910 (goto-char (point-min))
17911 (when (re-search-forward
17912 (concat
17913 (regexp-quote
17914 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17915 "\\(.\\|\n\\)*"
17916 (regexp-quote "</math>")) nil t)
17917 (prog1 (match-string 0) (kill-buffer))))))
17918 (cond
17919 (mathml
17920 (setq mathml
17921 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17922 (when mathml-file
17923 (write-region mathml nil mathml-file))
17924 (when (org-called-interactively-p 'any)
17925 (message mathml)))
17926 ((message "LaTeX to MathML conversion failed")
17927 (message shell-command-output)))
17928 (delete-file tmp-in-file)
17929 (when (file-exists-p tmp-out-file)
17930 (delete-file tmp-out-file))
17931 mathml))
17933 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17934 prefix &optional dir)
17935 "Use `org-create-math-formula' but check local cache first."
17936 (let* ((absprefix (expand-file-name prefix dir))
17937 (print-length nil) (print-level nil)
17938 (formula-id (concat
17939 "formula-"
17940 (sha1
17941 (prin1-to-string
17942 (list latex-frag
17943 org-latex-to-mathml-convert-command)))))
17944 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17945 (formula-cache-dir (file-name-directory formula-cache)))
17947 (unless (file-directory-p formula-cache-dir)
17948 (make-directory formula-cache-dir t))
17950 (unless (file-exists-p formula-cache)
17951 (org-create-math-formula latex-frag formula-cache))
17953 (if (file-exists-p formula-cache)
17954 ;; Successful conversion. Return the link to MathML file.
17955 (org-add-props
17956 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17957 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17958 'org-latex-src-embed-type (if latex-frag-type
17959 'paragraph 'character)))
17960 ;; Failed conversion. Return the LaTeX fragment verbatim
17961 latex-frag)))
17963 (defun org-create-formula-image (string tofile options buffer &optional type)
17964 "Create an image from LaTeX source using dvipng or convert.
17965 This function calls either `org-create-formula-image-with-dvipng'
17966 or `org-create-formula-image-with-imagemagick' depending on the
17967 value of `org-latex-create-formula-image-program' or on the value
17968 of the optional TYPE variable.
17970 Note: ultimately these two function should be combined as they
17971 share a good deal of logic."
17972 (org-check-external-command
17973 "latex" "needed to convert LaTeX fragments to images")
17974 (funcall
17975 (case (or type org-latex-create-formula-image-program)
17976 ('dvipng
17977 (org-check-external-command
17978 "dvipng" "needed to convert LaTeX fragments to images")
17979 #'org-create-formula-image-with-dvipng)
17980 ('imagemagick
17981 (org-check-external-command
17982 "convert" "you need to install imagemagick")
17983 #'org-create-formula-image-with-imagemagick)
17984 (t (error
17985 "invalid value of `org-latex-create-formula-image-program'")))
17986 string tofile options buffer))
17988 ;; This function borrows from Ganesh Swami's latex2png.el
17989 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17990 "This calls dvipng."
17991 (let* ((tmpdir (if (featurep 'xemacs)
17992 (temp-directory)
17993 temporary-file-directory))
17994 (texfilebase (make-temp-name
17995 (expand-file-name "orgtex" tmpdir)))
17996 (texfile (concat texfilebase ".tex"))
17997 (dvifile (concat texfilebase ".dvi"))
17998 (pngfile (concat texfilebase ".png"))
17999 (fnh (if (featurep 'xemacs)
18000 (font-height (face-font 'default))
18001 (face-attribute 'default :height nil)))
18002 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18003 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18004 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18005 "Black"))
18006 (bg (or (plist-get options (if buffer :background :html-background))
18007 "Transparent")))
18008 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18009 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18010 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18011 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18012 (with-temp-file texfile
18013 (require 'ox-latex)
18014 (insert (org-latex-guess-inputenc
18015 (org-splice-latex-header
18016 org-format-latex-header
18017 org-latex-default-packages-alist
18018 org-latex-packages-alist t)))
18019 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18020 (let ((dir default-directory))
18021 (condition-case nil
18022 (progn
18023 (cd tmpdir)
18024 (call-process "latex" nil nil nil texfile))
18025 (error nil))
18026 (cd dir))
18027 (if (not (file-exists-p dvifile))
18028 (progn (message "Failed to create dvi file from %s" texfile) nil)
18029 (condition-case nil
18030 (if (featurep 'xemacs)
18031 (call-process "dvipng" nil nil nil
18032 "-fg" fg "-bg" bg
18033 "-T" "tight"
18034 "-o" pngfile
18035 dvifile)
18036 (call-process "dvipng" nil nil nil
18037 "-fg" fg "-bg" bg
18038 "-D" dpi
18039 ;;"-x" scale "-y" scale
18040 "-T" "tight"
18041 "-o" pngfile
18042 dvifile))
18043 (error nil))
18044 (if (not (file-exists-p pngfile))
18045 (if org-format-latex-signal-error
18046 (error "Failed to create png file from %s" texfile)
18047 (message "Failed to create png file from %s" texfile)
18048 nil)
18049 ;; Use the requested file name and clean up
18050 (copy-file pngfile tofile 'replace)
18051 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18052 (if (file-exists-p (concat texfilebase e))
18053 (delete-file (concat texfilebase e))))
18054 pngfile))))
18056 (defvar org-latex-pdf-process) ; From ox-latex.el
18057 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18058 "This calls convert, which is included into imagemagick."
18059 (let* ((tmpdir (if (featurep 'xemacs)
18060 (temp-directory)
18061 temporary-file-directory))
18062 (texfilebase (make-temp-name
18063 (expand-file-name "orgtex" tmpdir)))
18064 (texfile (concat texfilebase ".tex"))
18065 (pdffile (concat texfilebase ".pdf"))
18066 (pngfile (concat texfilebase ".png"))
18067 (fnh (if (featurep 'xemacs)
18068 (font-height (face-font 'default))
18069 (face-attribute 'default :height nil)))
18070 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18071 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18072 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18073 "black"))
18074 (bg (or (plist-get options (if buffer :background :html-background))
18075 "white")))
18076 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18077 (setq fg (org-latex-color-format fg)))
18078 (if (eq bg 'default) (setq bg (org-latex-color :background))
18079 (setq bg (org-latex-color-format
18080 (if (string= bg "Transparent") "white" bg))))
18081 (with-temp-file texfile
18082 (require 'ox-latex)
18083 (insert (org-latex-guess-inputenc
18084 (org-splice-latex-header
18085 org-format-latex-header
18086 org-latex-default-packages-alist
18087 org-latex-packages-alist t)))
18088 (insert "\n\\begin{document}\n"
18089 "\\definecolor{fg}{rgb}{" fg "}\n"
18090 "\\definecolor{bg}{rgb}{" bg "}\n"
18091 "\n\\pagecolor{bg}\n"
18092 "\n{\\color{fg}\n"
18093 string
18094 "\n}\n"
18095 "\n\\end{document}\n"))
18096 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18097 (condition-case nil
18098 (progn
18099 (cd tmpdir)
18100 (setq cmds org-latex-pdf-process)
18101 (while cmds
18102 (setq latex-frags-cmds (pop cmds))
18103 (if (listp latex-frags-cmds)
18104 (setq cmds nil)
18105 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18106 (while latex-frags-cmds
18107 (setq cmd (pop latex-frags-cmds))
18108 (while (string-match "%b" cmd)
18109 (setq cmd (replace-match
18110 (save-match-data
18111 (shell-quote-argument texfile))
18112 t t cmd)))
18113 (while (string-match "%f" cmd)
18114 (setq cmd (replace-match
18115 (save-match-data
18116 (shell-quote-argument
18117 (file-name-nondirectory texfile)))
18118 t t cmd)))
18119 (while (string-match "%o" cmd)
18120 (setq cmd (replace-match
18121 (save-match-data
18122 (shell-quote-argument
18123 (file-name-directory texfile)))
18124 t t cmd)))
18125 (setq cmd (split-string cmd))
18126 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18127 (error nil))
18128 (cd dir))
18129 (if (not (file-exists-p pdffile))
18130 (progn (message "Failed to create pdf file from %s" texfile) nil)
18131 (condition-case nil
18132 (if (featurep 'xemacs)
18133 (call-process "convert" nil nil nil
18134 "-density" "96"
18135 "-trim"
18136 "-antialias"
18137 pdffile
18138 "-quality" "100"
18139 ;; "-sharpen" "0x1.0"
18140 pngfile)
18141 (call-process "convert" nil nil nil
18142 "-density" dpi
18143 "-trim"
18144 "-antialias"
18145 pdffile
18146 "-quality" "100"
18147 ;; "-sharpen" "0x1.0"
18148 pngfile))
18149 (error nil))
18150 (if (not (file-exists-p pngfile))
18151 (if org-format-latex-signal-error
18152 (error "Failed to create png file from %s" texfile)
18153 (message "Failed to create png file from %s" texfile)
18154 nil)
18155 ;; Use the requested file name and clean up
18156 (copy-file pngfile tofile 'replace)
18157 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18158 (if (file-exists-p (concat texfilebase e))
18159 (delete-file (concat texfilebase e))))
18160 pngfile))))
18162 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18163 "Fill a LaTeX header template TPL.
18164 In the template, the following place holders will be recognized:
18166 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18167 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18168 [PACKAGES] \\usepackage statements for PKG
18169 [NO-PACKAGES] do not include PKG
18170 [EXTRA] the string EXTRA
18171 [NO-EXTRA] do not include EXTRA
18173 For backward compatibility, if both the positive and the negative place
18174 holder is missing, the positive one (without the \"NO-\") will be
18175 assumed to be present at the end of the template.
18176 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18177 EXTRA is a string.
18178 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18179 (let (rpl (end ""))
18180 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18181 (setq rpl (if (or (match-end 1) (not def-pkg))
18182 "" (org-latex-packages-to-string def-pkg snippets-p t))
18183 tpl (replace-match rpl t t tpl))
18184 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18186 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18187 (setq rpl (if (or (match-end 1) (not pkg))
18188 "" (org-latex-packages-to-string pkg snippets-p t))
18189 tpl (replace-match rpl t t tpl))
18190 (if pkg (setq end
18191 (concat end "\n"
18192 (org-latex-packages-to-string pkg snippets-p)))))
18194 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18195 (setq rpl (if (or (match-end 1) (not extra))
18196 "" (concat extra "\n"))
18197 tpl (replace-match rpl t t tpl))
18198 (if (and extra (string-match "\\S-" extra))
18199 (setq end (concat end "\n" extra))))
18201 (if (string-match "\\S-" end)
18202 (concat tpl "\n" end)
18203 tpl)))
18205 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18206 "Turn an alist of packages into a string with the \\usepackage macros."
18207 (setq pkg (mapconcat (lambda(p)
18208 (cond
18209 ((stringp p) p)
18210 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18211 (format "%% Package %s omitted" (cadr p)))
18212 ((equal "" (car p))
18213 (format "\\usepackage{%s}" (cadr p)))
18215 (format "\\usepackage[%s]{%s}"
18216 (car p) (cadr p)))))
18218 "\n"))
18219 (if newline (concat pkg "\n") pkg))
18221 (defun org-dvipng-color (attr)
18222 "Return a RGB color specification for dvipng."
18223 (apply 'format "rgb %s %s %s"
18224 (mapcar 'org-normalize-color
18225 (if (featurep 'xemacs)
18226 (color-rgb-components
18227 (face-property 'default
18228 (cond ((eq attr :foreground) 'foreground)
18229 ((eq attr :background) 'background))))
18230 (color-values (face-attribute 'default attr nil))))))
18232 (defun org-dvipng-color-format (color-name)
18233 "Convert COLOR-NAME to a RGB color value for dvipng."
18234 (apply 'format "rgb %s %s %s"
18235 (mapcar 'org-normalize-color
18236 (color-values color-name))))
18238 (defun org-latex-color (attr)
18239 "Return a RGB color for the LaTeX color package."
18240 (apply 'format "%s,%s,%s"
18241 (mapcar 'org-normalize-color
18242 (if (featurep 'xemacs)
18243 (color-rgb-components
18244 (face-property 'default
18245 (cond ((eq attr :foreground) 'foreground)
18246 ((eq attr :background) 'background))))
18247 (color-values (face-attribute 'default attr nil))))))
18249 (defun org-latex-color-format (color-name)
18250 "Convert COLOR-NAME to a RGB color value."
18251 (apply 'format "%s,%s,%s"
18252 (mapcar 'org-normalize-color
18253 (color-values color-name))))
18255 (defun org-normalize-color (value)
18256 "Return string to be used as color value for an RGB component."
18257 (format "%g" (/ value 65535.0)))
18261 ;; Image display
18263 (defvar org-inline-image-overlays nil)
18264 (make-variable-buffer-local 'org-inline-image-overlays)
18266 (defun org-toggle-inline-images (&optional include-linked)
18267 "Toggle the display of inline images.
18268 INCLUDE-LINKED is passed to `org-display-inline-images'."
18269 (interactive "P")
18270 (if org-inline-image-overlays
18271 (progn
18272 (org-remove-inline-images)
18273 (message "Inline image display turned off"))
18274 (org-display-inline-images include-linked)
18275 (if (and (org-called-interactively-p)
18276 org-inline-image-overlays)
18277 (message "%d images displayed inline"
18278 (length org-inline-image-overlays))
18279 (message "No images to display inline"))))
18281 (defun org-redisplay-inline-images ()
18282 "Refresh the display of inline images."
18283 (interactive)
18284 (if (not org-inline-image-overlays)
18285 (org-toggle-inline-images)
18286 (org-toggle-inline-images)
18287 (org-toggle-inline-images)))
18289 (defun org-display-inline-images (&optional include-linked refresh beg end)
18290 "Display inline images.
18291 Normally only links without a description part are inlined, because this
18292 is how it will work for export. When INCLUDE-LINKED is set, also links
18293 with a description part will be inlined. This can be nice for a quick
18294 look at those images, but it does not reflect what exported files will look
18295 like.
18296 When REFRESH is set, refresh existing images between BEG and END.
18297 This will create new image displays only if necessary.
18298 BEG and END default to the buffer boundaries."
18299 (interactive "P")
18300 (unless refresh
18301 (org-remove-inline-images)
18302 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18303 (save-excursion
18304 (save-restriction
18305 (widen)
18306 (setq beg (or beg (point-min)) end (or end (point-max)))
18307 (goto-char beg)
18308 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18309 (substring (org-image-file-name-regexp) 0 -2)
18310 "\\)\\]" (if include-linked "" "\\]")))
18311 old file ov img type attrwidth width)
18312 (while (re-search-forward re end t)
18313 (setq old (get-char-property-and-overlay (match-beginning 1)
18314 'org-image-overlay)
18315 file (expand-file-name
18316 (concat (or (match-string 3) "") (match-string 4))))
18317 (when (image-type-available-p 'imagemagick)
18318 (setq attrwidth (if (or (listp org-image-actual-width)
18319 (null org-image-actual-width))
18320 (save-excursion
18321 (save-match-data
18322 (when (re-search-backward
18323 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18324 (save-excursion
18325 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18326 (string-to-number (match-string 1))))))
18327 width (cond ((eq org-image-actual-width t) nil)
18328 ((null org-image-actual-width) attrwidth)
18329 ((numberp org-image-actual-width)
18330 org-image-actual-width)
18331 ((listp org-image-actual-width)
18332 (or attrwidth (car org-image-actual-width))))
18333 type (if width 'imagemagick)))
18334 (when (file-exists-p file)
18335 (if (and (car-safe old) refresh)
18336 (image-refresh (overlay-get (cdr old) 'display))
18337 (setq img (save-match-data (create-image file type nil :width width)))
18338 (when img
18339 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18340 (overlay-put ov 'display img)
18341 (overlay-put ov 'face 'default)
18342 (overlay-put ov 'org-image-overlay t)
18343 (overlay-put ov 'modification-hooks
18344 (list 'org-display-inline-remove-overlay))
18345 (push ov org-inline-image-overlays)))))))))
18347 (define-obsolete-function-alias
18348 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18350 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18351 "Remove inline-display overlay if a corresponding region is modified."
18352 (let ((inhibit-modification-hooks t))
18353 (when (and ov after)
18354 (delete ov org-inline-image-overlays)
18355 (delete-overlay ov))))
18357 (defun org-remove-inline-images ()
18358 "Remove inline display of images."
18359 (interactive)
18360 (mapc 'delete-overlay org-inline-image-overlays)
18361 (setq org-inline-image-overlays nil))
18363 ;;;; Key bindings
18365 ;; Outline functions from `outline-mode-prefix-map'
18366 ;; that can be remapped in Org:
18367 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18368 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18369 (define-key org-mode-map [remap outline-forward-same-level]
18370 'org-forward-heading-same-level)
18371 (define-key org-mode-map [remap outline-backward-same-level]
18372 'org-backward-heading-same-level)
18373 (define-key org-mode-map [remap show-branches]
18374 'org-kill-note-or-show-branches)
18375 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18376 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18377 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18379 ;; Outline functions from `outline-mode-prefix-map' that can not
18380 ;; be remapped in Org:
18382 ;; - the column "key binding" shows whether the Outline function is still
18383 ;; available in Org mode on the same key that it has been bound to in
18384 ;; Outline mode:
18385 ;; - "overridden": key used for a different functionality in Org mode
18386 ;; - else: key still bound to the same Outline function in Org mode
18388 ;; | Outline function | key binding | Org replacement |
18389 ;; |------------------------------------+-------------+-----------------------|
18390 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18391 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18392 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18393 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18394 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18395 ;; | `show-entry' | overridden | no replacement |
18396 ;; | `show-children' | `C-c C-i' | visibility cycling |
18397 ;; | `show-branches' | `C-c C-k' | still same function |
18398 ;; | `show-subtree' | overridden | visibility cycling |
18399 ;; | `show-all' | overridden | no replacement |
18400 ;; | `hide-subtree' | overridden | visibility cycling |
18401 ;; | `hide-body' | overridden | no replacement |
18402 ;; | `hide-entry' | overridden | visibility cycling |
18403 ;; | `hide-leaves' | overridden | no replacement |
18404 ;; | `hide-sublevels' | overridden | no replacement |
18405 ;; | `hide-other' | overridden | no replacement |
18407 ;; Make `C-c C-x' a prefix key
18408 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18410 ;; TAB key with modifiers
18411 (org-defkey org-mode-map "\C-i" 'org-cycle)
18412 (org-defkey org-mode-map [(tab)] 'org-cycle)
18413 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18414 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18415 ;; The following line is necessary under Suse GNU/Linux
18416 (unless (featurep 'xemacs)
18417 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18418 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18419 (define-key org-mode-map [backtab] 'org-shifttab)
18421 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18422 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18423 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18425 ;; Cursor keys with modifiers
18426 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18427 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18428 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18429 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18431 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18432 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18433 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18434 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18436 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18437 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18438 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18439 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18441 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18442 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18443 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18444 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18446 ;; Babel keys
18447 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18448 (mapc (lambda (pair)
18449 (define-key org-babel-map (car pair) (cdr pair)))
18450 org-babel-key-bindings)
18452 ;;; Extra keys for tty access.
18453 ;; We only set them when really needed because otherwise the
18454 ;; menus don't show the simple keys
18456 (when (or org-use-extra-keys
18457 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18458 (not window-system))
18459 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18460 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18461 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18462 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18463 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18464 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18465 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18466 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18467 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18468 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18469 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18470 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18471 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18472 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18473 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18474 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18475 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18476 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18477 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18478 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18479 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18480 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18481 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18482 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18483 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18484 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18485 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18486 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18488 ;; All the other keys
18490 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18491 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18492 (if (boundp 'narrow-map)
18493 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18494 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18495 (if (boundp 'narrow-map)
18496 (org-defkey narrow-map "b" 'org-narrow-to-block)
18497 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18498 (if (boundp 'narrow-map)
18499 (org-defkey narrow-map "e" 'org-narrow-to-element)
18500 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18501 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18502 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18503 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18504 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18505 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18506 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18507 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18508 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18509 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18510 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18511 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18512 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18513 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18514 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18515 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18516 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18517 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18518 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18519 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18520 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18521 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18522 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18523 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18524 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18525 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18526 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18527 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18528 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18529 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18530 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18531 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18532 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18533 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18534 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18535 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18536 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18537 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18538 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18539 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18540 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18541 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18542 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18543 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18544 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18545 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18546 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18547 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18548 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18549 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18550 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18551 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18552 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18553 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18554 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18555 (org-defkey org-mode-map "\C-c^" 'org-sort)
18556 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18557 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18558 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18559 (org-defkey org-mode-map "\C-m" 'org-return)
18560 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18561 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18562 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18563 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18564 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18565 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18566 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18567 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18568 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18569 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18570 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18571 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18572 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18573 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18574 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18575 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18576 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18577 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18578 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18579 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18580 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18581 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18582 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18584 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18585 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18586 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18588 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18589 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18590 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18591 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18592 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18593 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18594 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18595 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18596 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18597 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18598 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18599 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18600 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18601 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18602 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18603 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18604 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18605 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18606 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18607 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18608 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18609 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18610 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18612 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18613 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18614 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18615 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18616 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18618 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18620 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18622 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18623 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18625 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18628 (when (featurep 'xemacs)
18629 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18632 (defconst org-speed-commands-default
18634 ("Outline Navigation")
18635 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18636 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18637 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18638 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18639 ("F" . org-next-block)
18640 ("B" . org-previous-block)
18641 ("u" . (org-speed-move-safe 'outline-up-heading))
18642 ("j" . org-goto)
18643 ("g" . (org-refile t))
18644 ("Outline Visibility")
18645 ("c" . org-cycle)
18646 ("C" . org-shifttab)
18647 (" " . org-display-outline-path)
18648 ("=" . org-columns)
18649 ("Outline Structure Editing")
18650 ("U" . org-shiftmetaup)
18651 ("D" . org-shiftmetadown)
18652 ("r" . org-metaright)
18653 ("l" . org-metaleft)
18654 ("R" . org-shiftmetaright)
18655 ("L" . org-shiftmetaleft)
18656 ("i" . (progn (forward-char 1) (call-interactively
18657 'org-insert-heading-respect-content)))
18658 ("^" . org-sort)
18659 ("w" . org-refile)
18660 ("a" . org-archive-subtree-default-with-confirmation)
18661 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18662 ("#" . org-toggle-comment)
18663 ("Clock Commands")
18664 ("I" . org-clock-in)
18665 ("O" . org-clock-out)
18666 ("Meta Data Editing")
18667 ("t" . org-todo)
18668 ("," . (org-priority))
18669 ("0" . (org-priority ?\ ))
18670 ("1" . (org-priority ?A))
18671 ("2" . (org-priority ?B))
18672 ("3" . (org-priority ?C))
18673 (":" . org-set-tags-command)
18674 ("e" . org-set-effort)
18675 ("E" . org-inc-effort)
18676 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18677 (org-entry-put (point) "APPT_WARNTIME" m)))
18678 ("Agenda Views etc")
18679 ("v" . org-agenda)
18680 ("/" . org-sparse-tree)
18681 ("Misc")
18682 ("o" . org-open-at-point)
18683 ("?" . org-speed-command-help)
18684 ("<" . (org-agenda-set-restriction-lock 'subtree))
18685 (">" . (org-agenda-remove-restriction-lock))
18687 "The default speed commands.")
18689 (defun org-print-speed-command (e)
18690 (if (> (length (car e)) 1)
18691 (progn
18692 (princ "\n")
18693 (princ (car e))
18694 (princ "\n")
18695 (princ (make-string (length (car e)) ?-))
18696 (princ "\n"))
18697 (princ (car e))
18698 (princ " ")
18699 (if (symbolp (cdr e))
18700 (princ (symbol-name (cdr e)))
18701 (prin1 (cdr e)))
18702 (princ "\n")))
18704 (defun org-speed-command-help ()
18705 "Show the available speed commands."
18706 (interactive)
18707 (if (not org-use-speed-commands)
18708 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18709 (with-output-to-temp-buffer "*Help*"
18710 (princ "User-defined Speed commands\n===========================\n")
18711 (mapc 'org-print-speed-command org-speed-commands-user)
18712 (princ "\n")
18713 (princ "Built-in Speed commands\n=======================\n")
18714 (mapc 'org-print-speed-command org-speed-commands-default))
18715 (with-current-buffer "*Help*"
18716 (setq truncate-lines t))))
18718 (defun org-speed-move-safe (cmd)
18719 "Execute CMD, but make sure that the cursor always ends up in a headline.
18720 If not, return to the original position and throw an error."
18721 (interactive)
18722 (let ((pos (point)))
18723 (call-interactively cmd)
18724 (unless (and (bolp) (org-at-heading-p))
18725 (goto-char pos)
18726 (error "Boundary reached while executing %s" cmd))))
18728 (defvar org-self-insert-command-undo-counter 0)
18730 (defvar org-table-auto-blank-field) ; defined in org-table.el
18731 (defvar org-speed-command nil)
18733 (define-obsolete-function-alias
18734 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18736 (defun org-speed-command-activate (keys)
18737 "Hook for activating single-letter speed commands.
18738 `org-speed-commands-default' specifies a minimal command set.
18739 Use `org-speed-commands-user' for further customization."
18740 (when (or (and (bolp) (looking-at org-outline-regexp))
18741 (and (functionp org-use-speed-commands)
18742 (funcall org-use-speed-commands)))
18743 (cdr (assoc keys (append org-speed-commands-user
18744 org-speed-commands-default)))))
18746 (define-obsolete-function-alias
18747 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18749 (defun org-babel-speed-command-activate (keys)
18750 "Hook for activating single-letter code block commands."
18751 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18752 (cdr (assoc keys org-babel-key-bindings))))
18754 (defcustom org-speed-command-hook
18755 '(org-speed-command-default-hook org-babel-speed-command-hook)
18756 "Hook for activating speed commands at strategic locations.
18757 Hook functions are called in sequence until a valid handler is
18758 found.
18760 Each hook takes a single argument, a user-pressed command key
18761 which is also a `self-insert-command' from the global map.
18763 Within the hook, examine the cursor position and the command key
18764 and return nil or a valid handler as appropriate. Handler could
18765 be one of an interactive command, a function, or a form.
18767 Set `org-use-speed-commands' to non-nil value to enable this
18768 hook. The default setting is `org-speed-command-activate'."
18769 :group 'org-structure
18770 :version "24.1"
18771 :type 'hook)
18773 (defun org-self-insert-command (N)
18774 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18775 If the cursor is in a table looking at whitespace, the whitespace is
18776 overwritten, and the table is not marked as requiring realignment."
18777 (interactive "p")
18778 (org-check-before-invisible-edit 'insert)
18779 (cond
18780 ((and org-use-speed-commands
18781 (setq org-speed-command
18782 (run-hook-with-args-until-success
18783 'org-speed-command-hook (this-command-keys))))
18784 (cond
18785 ((commandp org-speed-command)
18786 (setq this-command org-speed-command)
18787 (call-interactively org-speed-command))
18788 ((functionp org-speed-command)
18789 (funcall org-speed-command))
18790 ((and org-speed-command (listp org-speed-command))
18791 (eval org-speed-command))
18792 (t (let (org-use-speed-commands)
18793 (call-interactively 'org-self-insert-command)))))
18794 ((and
18795 (org-table-p)
18796 (progn
18797 ;; check if we blank the field, and if that triggers align
18798 (and (featurep 'org-table) org-table-auto-blank-field
18799 (member last-command
18800 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18801 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18802 ;; got extra space, this field does not determine column width
18803 (let (org-table-may-need-update) (org-table-blank-field))
18804 ;; no extra space, this field may determine column width
18805 (org-table-blank-field)))
18807 (eq N 1)
18808 (looking-at "[^|\n]* |"))
18809 (let (org-table-may-need-update)
18810 (goto-char (1- (match-end 0)))
18811 (backward-delete-char 1)
18812 (goto-char (match-beginning 0))
18813 (self-insert-command N)))
18815 (setq org-table-may-need-update t)
18816 (self-insert-command N)
18817 (org-fix-tags-on-the-fly)
18818 (if org-self-insert-cluster-for-undo
18819 (if (not (eq last-command 'org-self-insert-command))
18820 (setq org-self-insert-command-undo-counter 1)
18821 (if (>= org-self-insert-command-undo-counter 20)
18822 (setq org-self-insert-command-undo-counter 1)
18823 (and (> org-self-insert-command-undo-counter 0)
18824 buffer-undo-list (listp buffer-undo-list)
18825 (not (cadr buffer-undo-list)) ; remove nil entry
18826 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18827 (setq org-self-insert-command-undo-counter
18828 (1+ org-self-insert-command-undo-counter))))))))
18830 (defun org-check-before-invisible-edit (kind)
18831 "Check is editing if kind KIND would be dangerous with invisible text around.
18832 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18833 ;; First, try to get out of here as quickly as possible, to reduce overhead
18834 (if (and org-catch-invisible-edits
18835 (or (not (boundp 'visible-mode)) (not visible-mode))
18836 (or (get-char-property (point) 'invisible)
18837 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18838 ;; OK, we need to take a closer look
18839 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18840 (invisible-before-point (if (bobp) nil (get-char-property
18841 (1- (point)) 'invisible)))
18842 (border-and-ok-direction
18844 ;; Check if we are acting predictably before invisible text
18845 (and invisible-at-point (not invisible-before-point)
18846 (memq kind '(insert delete-backward)))
18847 ;; Check if we are acting predictably after invisible text
18848 ;; This works not well, and I have turned it off. It seems
18849 ;; better to always show and stop after invisible text.
18850 ;; (and (not invisible-at-point) invisible-before-point
18851 ;; (memq kind '(insert delete)))
18853 (when (or (memq invisible-at-point '(outline org-hide-block t))
18854 (memq invisible-before-point '(outline org-hide-block t)))
18855 (if (eq org-catch-invisible-edits 'error)
18856 (error "Editing in invisible areas is prohibited - make visible first"))
18857 (if (and org-custom-properties-overlays
18858 (y-or-n-p "Display invisible properties in this buffer? "))
18859 (org-toggle-custom-properties-visibility)
18860 ;; Make the area visible
18861 (save-excursion
18862 (if invisible-before-point
18863 (goto-char (previous-single-char-property-change
18864 (point) 'invisible)))
18865 (org-cycle))
18866 (cond
18867 ((eq org-catch-invisible-edits 'show)
18868 ;; That's it, we do the edit after showing
18869 (message
18870 "Unfolding invisible region around point before editing")
18871 (sit-for 1))
18872 ((and (eq org-catch-invisible-edits 'smart)
18873 border-and-ok-direction)
18874 (message "Unfolding invisible region around point before editing"))
18876 ;; Don't do the edit, make the user repeat it in full visibility
18877 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18879 (defun org-fix-tags-on-the-fly ()
18880 (when (and (equal (char-after (point-at-bol)) ?*)
18881 (org-at-heading-p))
18882 (org-align-tags-here org-tags-column)))
18884 (defun org-delete-backward-char (N)
18885 "Like `delete-backward-char', insert whitespace at field end in tables.
18886 When deleting backwards, in tables this function will insert whitespace in
18887 front of the next \"|\" separator, to keep the table aligned. The table will
18888 still be marked for re-alignment if the field did fill the entire column,
18889 because, in this case the deletion might narrow the column."
18890 (interactive "p")
18891 (save-match-data
18892 (org-check-before-invisible-edit 'delete-backward)
18893 (if (and (org-table-p)
18894 (eq N 1)
18895 (string-match "|" (buffer-substring (point-at-bol) (point)))
18896 (looking-at ".*?|"))
18897 (let ((pos (point))
18898 (noalign (looking-at "[^|\n\r]* |"))
18899 (c org-table-may-need-update))
18900 (backward-delete-char N)
18901 (if (not overwrite-mode)
18902 (progn
18903 (skip-chars-forward "^|")
18904 (insert " ")
18905 (goto-char (1- pos))))
18906 ;; noalign: if there were two spaces at the end, this field
18907 ;; does not determine the width of the column.
18908 (if noalign (setq org-table-may-need-update c)))
18909 (backward-delete-char N)
18910 (org-fix-tags-on-the-fly))))
18912 (defun org-delete-char (N)
18913 "Like `delete-char', but insert whitespace at field end in tables.
18914 When deleting characters, in tables this function will insert whitespace in
18915 front of the next \"|\" separator, to keep the table aligned. The table will
18916 still be marked for re-alignment if the field did fill the entire column,
18917 because, in this case the deletion might narrow the column."
18918 (interactive "p")
18919 (save-match-data
18920 (org-check-before-invisible-edit 'delete)
18921 (if (and (org-table-p)
18922 (not (bolp))
18923 (not (= (char-after) ?|))
18924 (eq N 1))
18925 (if (looking-at ".*?|")
18926 (let ((pos (point))
18927 (noalign (looking-at "[^|\n\r]* |"))
18928 (c org-table-may-need-update))
18929 (replace-match (concat
18930 (substring (match-string 0) 1 -1)
18931 " |"))
18932 (goto-char pos)
18933 ;; noalign: if there were two spaces at the end, this field
18934 ;; does not determine the width of the column.
18935 (if noalign (setq org-table-may-need-update c)))
18936 (delete-char N))
18937 (delete-char N)
18938 (org-fix-tags-on-the-fly))))
18940 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18941 (put 'org-self-insert-command 'delete-selection t)
18942 (put 'orgtbl-self-insert-command 'delete-selection t)
18943 (put 'org-delete-char 'delete-selection 'supersede)
18944 (put 'org-delete-backward-char 'delete-selection 'supersede)
18945 (put 'org-yank 'delete-selection 'yank)
18947 ;; Make `flyspell-mode' delay after some commands
18948 (put 'org-self-insert-command 'flyspell-delayed t)
18949 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18950 (put 'org-delete-char 'flyspell-delayed t)
18951 (put 'org-delete-backward-char 'flyspell-delayed t)
18953 ;; Make pabbrev-mode expand after org-mode commands
18954 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18955 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18957 ;; How to do this: Measure non-white length of current string
18958 ;; If equal to column width, we should realign.
18960 (defun org-remap (map &rest commands)
18961 "In MAP, remap the functions given in COMMANDS.
18962 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18963 (let (new old)
18964 (while commands
18965 (setq old (pop commands) new (pop commands))
18966 (if (fboundp 'command-remapping)
18967 (org-defkey map (vector 'remap old) new)
18968 (substitute-key-definition old new map global-map)))))
18970 (when (eq org-enable-table-editor 'optimized)
18971 ;; If the user wants maximum table support, we need to hijack
18972 ;; some standard editing functions
18973 (org-remap org-mode-map
18974 'self-insert-command 'org-self-insert-command
18975 'delete-char 'org-delete-char
18976 'delete-backward-char 'org-delete-backward-char)
18977 (org-defkey org-mode-map "|" 'org-force-self-insert))
18979 (defvar org-ctrl-c-ctrl-c-hook nil
18980 "Hook for functions attaching themselves to `C-c C-c'.
18982 This can be used to add additional functionality to the C-c C-c
18983 key which executes context-dependent commands. This hook is run
18984 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18985 run after the last test.
18987 Each function will be called with no arguments. The function
18988 must check if the context is appropriate for it to act. If yes,
18989 it should do its thing and then return a non-nil value. If the
18990 context is wrong, just do nothing and return nil.")
18992 (defvar org-ctrl-c-ctrl-c-final-hook nil
18993 "Hook for functions attaching themselves to `C-c C-c'.
18995 This can be used to add additional functionality to the C-c C-c
18996 key which executes context-dependent commands. This hook is run
18997 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18998 before the first test.
19000 Each function will be called with no arguments. The function
19001 must check if the context is appropriate for it to act. If yes,
19002 it should do its thing and then return a non-nil value. If the
19003 context is wrong, just do nothing and return nil.")
19005 (defvar org-tab-first-hook nil
19006 "Hook for functions to attach themselves to TAB.
19007 See `org-ctrl-c-ctrl-c-hook' for more information.
19008 This hook runs as the first action when TAB is pressed, even before
19009 `org-cycle' messes around with the `outline-regexp' to cater for
19010 inline tasks and plain list item folding.
19011 If any function in this hook returns t, any other actions that
19012 would have been caused by TAB (such as table field motion or visibility
19013 cycling) will not occur.")
19015 (defvar org-tab-after-check-for-table-hook nil
19016 "Hook for functions to attach themselves to TAB.
19017 See `org-ctrl-c-ctrl-c-hook' for more information.
19018 This hook runs after it has been established that the cursor is not in a
19019 table, but before checking if the cursor is in a headline or if global cycling
19020 should be done.
19021 If any function in this hook returns t, not other actions like visibility
19022 cycling will be done.")
19024 (defvar org-tab-after-check-for-cycling-hook nil
19025 "Hook for functions to attach themselves to TAB.
19026 See `org-ctrl-c-ctrl-c-hook' for more information.
19027 This hook runs after it has been established that not table field motion and
19028 not visibility should be done because of current context. This is probably
19029 the place where a package like yasnippets can hook in.")
19031 (defvar org-tab-before-tab-emulation-hook nil
19032 "Hook for functions to attach themselves to TAB.
19033 See `org-ctrl-c-ctrl-c-hook' for more information.
19034 This hook runs after every other options for TAB have been exhausted, but
19035 before indentation and \t insertion takes place.")
19037 (defvar org-metaleft-hook nil
19038 "Hook for functions attaching themselves to `M-left'.
19039 See `org-ctrl-c-ctrl-c-hook' for more information.")
19040 (defvar org-metaright-hook nil
19041 "Hook for functions attaching themselves to `M-right'.
19042 See `org-ctrl-c-ctrl-c-hook' for more information.")
19043 (defvar org-metaup-hook nil
19044 "Hook for functions attaching themselves to `M-up'.
19045 See `org-ctrl-c-ctrl-c-hook' for more information.")
19046 (defvar org-metadown-hook nil
19047 "Hook for functions attaching themselves to `M-down'.
19048 See `org-ctrl-c-ctrl-c-hook' for more information.")
19049 (defvar org-shiftmetaleft-hook nil
19050 "Hook for functions attaching themselves to `M-S-left'.
19051 See `org-ctrl-c-ctrl-c-hook' for more information.")
19052 (defvar org-shiftmetaright-hook nil
19053 "Hook for functions attaching themselves to `M-S-right'.
19054 See `org-ctrl-c-ctrl-c-hook' for more information.")
19055 (defvar org-shiftmetaup-hook nil
19056 "Hook for functions attaching themselves to `M-S-up'.
19057 See `org-ctrl-c-ctrl-c-hook' for more information.")
19058 (defvar org-shiftmetadown-hook nil
19059 "Hook for functions attaching themselves to `M-S-down'.
19060 See `org-ctrl-c-ctrl-c-hook' for more information.")
19061 (defvar org-metareturn-hook nil
19062 "Hook for functions attaching themselves to `M-RET'.
19063 See `org-ctrl-c-ctrl-c-hook' for more information.")
19064 (defvar org-shiftup-hook nil
19065 "Hook for functions attaching themselves to `S-up'.
19066 See `org-ctrl-c-ctrl-c-hook' for more information.")
19067 (defvar org-shiftup-final-hook nil
19068 "Hook for functions attaching themselves to `S-up'.
19069 This one runs after all other options except shift-select have been excluded.
19070 See `org-ctrl-c-ctrl-c-hook' for more information.")
19071 (defvar org-shiftdown-hook nil
19072 "Hook for functions attaching themselves to `S-down'.
19073 See `org-ctrl-c-ctrl-c-hook' for more information.")
19074 (defvar org-shiftdown-final-hook nil
19075 "Hook for functions attaching themselves to `S-down'.
19076 This one runs after all other options except shift-select have been excluded.
19077 See `org-ctrl-c-ctrl-c-hook' for more information.")
19078 (defvar org-shiftleft-hook nil
19079 "Hook for functions attaching themselves to `S-left'.
19080 See `org-ctrl-c-ctrl-c-hook' for more information.")
19081 (defvar org-shiftleft-final-hook nil
19082 "Hook for functions attaching themselves to `S-left'.
19083 This one runs after all other options except shift-select have been excluded.
19084 See `org-ctrl-c-ctrl-c-hook' for more information.")
19085 (defvar org-shiftright-hook nil
19086 "Hook for functions attaching themselves to `S-right'.
19087 See `org-ctrl-c-ctrl-c-hook' for more information.")
19088 (defvar org-shiftright-final-hook nil
19089 "Hook for functions attaching themselves to `S-right'.
19090 This one runs after all other options except shift-select have been excluded.
19091 See `org-ctrl-c-ctrl-c-hook' for more information.")
19093 (defun org-modifier-cursor-error ()
19094 "Throw an error, a modified cursor command was applied in wrong context."
19095 (error "This command is active in special context like tables, headlines or items"))
19097 (defun org-shiftselect-error ()
19098 "Throw an error because Shift-Cursor command was applied in wrong context."
19099 (if (and (boundp 'shift-select-mode) shift-select-mode)
19100 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19101 (error "This command works only in special context like headlines or timestamps")))
19103 (defun org-call-for-shift-select (cmd)
19104 (let ((this-command-keys-shift-translated t))
19105 (call-interactively cmd)))
19107 (defun org-shifttab (&optional arg)
19108 "Global visibility cycling or move to previous table field.
19109 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19110 on context.
19111 See the individual commands for more information."
19112 (interactive "P")
19113 (cond
19114 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19115 ((integerp arg)
19116 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19117 (message "Content view to level: %d" arg)
19118 (org-content (prefix-numeric-value arg2))
19119 (setq org-cycle-global-status 'overview)))
19120 (t (call-interactively 'org-global-cycle))))
19122 (defun org-shiftmetaleft ()
19123 "Promote subtree or delete table column.
19124 Calls `org-promote-subtree', `org-outdent-item-tree', or
19125 `org-table-delete-column', depending on context. See the
19126 individual commands for more information."
19127 (interactive)
19128 (cond
19129 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19130 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19131 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19132 ((if (not (org-region-active-p)) (org-at-item-p)
19133 (save-excursion (goto-char (region-beginning))
19134 (org-at-item-p)))
19135 (call-interactively 'org-outdent-item-tree))
19136 (t (org-modifier-cursor-error))))
19138 (defun org-shiftmetaright ()
19139 "Demote subtree or insert table column.
19140 Calls `org-demote-subtree', `org-indent-item-tree', or
19141 `org-table-insert-column', depending on context. See the
19142 individual commands for more information."
19143 (interactive)
19144 (cond
19145 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19146 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19147 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19148 ((if (not (org-region-active-p)) (org-at-item-p)
19149 (save-excursion (goto-char (region-beginning))
19150 (org-at-item-p)))
19151 (call-interactively 'org-indent-item-tree))
19152 (t (org-modifier-cursor-error))))
19154 (defun org-shiftmetaup (&optional arg)
19155 "Move subtree up or kill table row.
19156 Calls `org-move-subtree-up' or `org-table-kill-row' or
19157 `org-move-item-up' or `org-timestamp-up', depending on context.
19158 See the individual commands for more information."
19159 (interactive "P")
19160 (cond
19161 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19162 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19163 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19164 ((org-at-item-p) (call-interactively 'org-move-item-up))
19165 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19166 (call-interactively 'org-timestamp-up)))
19167 (t (call-interactively 'org-drag-line-backward))))
19169 (defun org-shiftmetadown (&optional arg)
19170 "Move subtree down or insert table row.
19171 Calls `org-move-subtree-down' or `org-table-insert-row' or
19172 `org-move-item-down' or `org-timestamp-up', depending on context.
19173 See the individual commands for more information."
19174 (interactive "P")
19175 (cond
19176 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19177 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19178 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19179 ((org-at-item-p) (call-interactively 'org-move-item-down))
19180 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19181 (call-interactively 'org-timestamp-down)))
19182 (t (call-interactively 'org-drag-line-forward))))
19184 (defsubst org-hidden-tree-error ()
19185 (error
19186 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19188 (defun org-metaleft (&optional arg)
19189 "Promote heading or move table column to left.
19190 Calls `org-do-promote' or `org-table-move-column', depending on context.
19191 With no specific context, calls the Emacs default `backward-word'.
19192 See the individual commands for more information."
19193 (interactive "P")
19194 (cond
19195 ((run-hook-with-args-until-success 'org-metaleft-hook))
19196 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19197 ((org-with-limited-levels
19198 (or (org-at-heading-p)
19199 (and (org-region-active-p)
19200 (save-excursion
19201 (goto-char (region-beginning))
19202 (org-at-heading-p)))))
19203 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19204 (call-interactively 'org-do-promote))
19205 ;; At an inline task.
19206 ((org-at-heading-p)
19207 (call-interactively 'org-inlinetask-promote))
19208 ((or (org-at-item-p)
19209 (and (org-region-active-p)
19210 (save-excursion
19211 (goto-char (region-beginning))
19212 (org-at-item-p))))
19213 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19214 (call-interactively 'org-outdent-item))
19215 (t (call-interactively 'backward-word))))
19217 (defun org-metaright (&optional arg)
19218 "Demote a subtree, a list item or move table column to right.
19219 In front of a drawer or a block keyword, indent it correctly.
19220 With no specific context, calls the Emacs default `forward-word'.
19221 See the individual commands for more information."
19222 (interactive "P")
19223 (cond
19224 ((run-hook-with-args-until-success 'org-metaright-hook))
19225 ((org-at-table-p) (call-interactively 'org-table-move-column))
19226 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19227 ((org-at-block-p) (call-interactively 'org-indent-block))
19228 ((org-with-limited-levels
19229 (or (org-at-heading-p)
19230 (and (org-region-active-p)
19231 (save-excursion
19232 (goto-char (region-beginning))
19233 (org-at-heading-p)))))
19234 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19235 (call-interactively 'org-do-demote))
19236 ;; At an inline task.
19237 ((org-at-heading-p)
19238 (call-interactively 'org-inlinetask-demote))
19239 ((or (org-at-item-p)
19240 (and (org-region-active-p)
19241 (save-excursion
19242 (goto-char (region-beginning))
19243 (org-at-item-p))))
19244 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19245 (call-interactively 'org-indent-item))
19246 (t (call-interactively 'forward-word))))
19248 (defun org-check-for-hidden (what)
19249 "Check if there are hidden headlines/items in the current visual line.
19250 WHAT can be either `headlines' or `items'. If the current line is
19251 an outline or item heading and it has a folded subtree below it,
19252 this function returns t, nil otherwise."
19253 (let ((re (cond
19254 ((eq what 'headlines) org-outline-regexp-bol)
19255 ((eq what 'items) (org-item-beginning-re))
19256 (t (error "This should not happen"))))
19257 beg end)
19258 (save-excursion
19259 (catch 'exit
19260 (unless (org-region-active-p)
19261 (setq beg (point-at-bol))
19262 (beginning-of-line 2)
19263 (while (and (not (eobp)) ;; this is like `next-line'
19264 (get-char-property (1- (point)) 'invisible))
19265 (beginning-of-line 2))
19266 (setq end (point))
19267 (goto-char beg)
19268 (goto-char (point-at-eol))
19269 (setq end (max end (point)))
19270 (while (re-search-forward re end t)
19271 (if (get-char-property (match-beginning 0) 'invisible)
19272 (throw 'exit t))))
19273 nil))))
19275 (defun org-metaup (&optional arg)
19276 "Move subtree up or move table row up.
19277 Calls `org-move-subtree-up' or `org-table-move-row' or
19278 `org-move-item-up', depending on context. See the individual commands
19279 for more information."
19280 (interactive "P")
19281 (cond
19282 ((run-hook-with-args-until-success 'org-metaup-hook))
19283 ((org-region-active-p)
19284 (let* ((a (min (region-beginning) (region-end)))
19285 (b (1- (max (region-beginning) (region-end))))
19286 (c (save-excursion (goto-char a)
19287 (move-beginning-of-line 0)))
19288 (d (save-excursion (goto-char a)
19289 (move-end-of-line 0) (point))))
19290 (transpose-regions a b c d)
19291 (goto-char c)))
19292 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19293 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19294 ((org-at-item-p) (call-interactively 'org-move-item-up))
19295 (t (org-drag-element-backward))))
19297 (defun org-metadown (&optional arg)
19298 "Move subtree down or move table row down.
19299 Calls `org-move-subtree-down' or `org-table-move-row' or
19300 `org-move-item-down', depending on context. See the individual
19301 commands for more information."
19302 (interactive "P")
19303 (cond
19304 ((run-hook-with-args-until-success 'org-metadown-hook))
19305 ((org-region-active-p)
19306 (let* ((a (min (region-beginning) (region-end)))
19307 (b (max (region-beginning) (region-end)))
19308 (c (save-excursion (goto-char b)
19309 (move-beginning-of-line 1)))
19310 (d (save-excursion (goto-char b)
19311 (move-end-of-line 1) (1+ (point)))))
19312 (transpose-regions a b c d)
19313 (goto-char d)))
19314 ((org-at-table-p) (call-interactively 'org-table-move-row))
19315 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19316 ((org-at-item-p) (call-interactively 'org-move-item-down))
19317 (t (org-drag-element-forward))))
19319 (defun org-shiftup (&optional arg)
19320 "Increase item in timestamp or increase priority of current headline.
19321 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19322 depending on context. See the individual commands for more information."
19323 (interactive "P")
19324 (cond
19325 ((run-hook-with-args-until-success 'org-shiftup-hook))
19326 ((and org-support-shift-select (org-region-active-p))
19327 (org-call-for-shift-select 'previous-line))
19328 ((org-at-timestamp-p t)
19329 (call-interactively (if org-edit-timestamp-down-means-later
19330 'org-timestamp-down 'org-timestamp-up)))
19331 ((and (not (eq org-support-shift-select 'always))
19332 org-enable-priority-commands
19333 (org-at-heading-p))
19334 (call-interactively 'org-priority-up))
19335 ((and (not org-support-shift-select) (org-at-item-p))
19336 (call-interactively 'org-previous-item))
19337 ((org-clocktable-try-shift 'up arg))
19338 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19339 (org-support-shift-select
19340 (org-call-for-shift-select 'previous-line))
19341 (t (org-shiftselect-error))))
19343 (defun org-shiftdown (&optional arg)
19344 "Decrease item in timestamp or decrease priority of current headline.
19345 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19346 depending on context. See the individual commands for more information."
19347 (interactive "P")
19348 (cond
19349 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19350 ((and org-support-shift-select (org-region-active-p))
19351 (org-call-for-shift-select 'next-line))
19352 ((org-at-timestamp-p t)
19353 (call-interactively (if org-edit-timestamp-down-means-later
19354 'org-timestamp-up 'org-timestamp-down)))
19355 ((and (not (eq org-support-shift-select 'always))
19356 org-enable-priority-commands
19357 (org-at-heading-p))
19358 (call-interactively 'org-priority-down))
19359 ((and (not org-support-shift-select) (org-at-item-p))
19360 (call-interactively 'org-next-item))
19361 ((org-clocktable-try-shift 'down arg))
19362 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19363 (org-support-shift-select
19364 (org-call-for-shift-select 'next-line))
19365 (t (org-shiftselect-error))))
19367 (defun org-shiftright (&optional arg)
19368 "Cycle the thing at point or in the current line, depending on context.
19369 Depending on context, this does one of the following:
19371 - switch a timestamp at point one day into the future
19372 - on a headline, switch to the next TODO keyword.
19373 - on an item, switch entire list to the next bullet type
19374 - on a property line, switch to the next allowed value
19375 - on a clocktable definition line, move time block into the future"
19376 (interactive "P")
19377 (cond
19378 ((run-hook-with-args-until-success 'org-shiftright-hook))
19379 ((and org-support-shift-select (org-region-active-p))
19380 (org-call-for-shift-select 'forward-char))
19381 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19382 ((and (not (eq org-support-shift-select 'always))
19383 (org-at-heading-p))
19384 (let ((org-inhibit-logging
19385 (not org-treat-S-cursor-todo-selection-as-state-change))
19386 (org-inhibit-blocking
19387 (not org-treat-S-cursor-todo-selection-as-state-change)))
19388 (org-call-with-arg 'org-todo 'right)))
19389 ((or (and org-support-shift-select
19390 (not (eq org-support-shift-select 'always))
19391 (org-at-item-bullet-p))
19392 (and (not org-support-shift-select) (org-at-item-p)))
19393 (org-call-with-arg 'org-cycle-list-bullet nil))
19394 ((and (not (eq org-support-shift-select 'always))
19395 (org-at-property-p))
19396 (call-interactively 'org-property-next-allowed-value))
19397 ((org-clocktable-try-shift 'right arg))
19398 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19399 (org-support-shift-select
19400 (org-call-for-shift-select 'forward-char))
19401 (t (org-shiftselect-error))))
19403 (defun org-shiftleft (&optional arg)
19404 "Cycle the thing at point or in the current line, depending on context.
19405 Depending on context, this does one of the following:
19407 - switch a timestamp at point one day into the past
19408 - on a headline, switch to the previous TODO keyword.
19409 - on an item, switch entire list to the previous bullet type
19410 - on a property line, switch to the previous allowed value
19411 - on a clocktable definition line, move time block into the past"
19412 (interactive "P")
19413 (cond
19414 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19415 ((and org-support-shift-select (org-region-active-p))
19416 (org-call-for-shift-select 'backward-char))
19417 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19418 ((and (not (eq org-support-shift-select 'always))
19419 (org-at-heading-p))
19420 (let ((org-inhibit-logging
19421 (not org-treat-S-cursor-todo-selection-as-state-change))
19422 (org-inhibit-blocking
19423 (not org-treat-S-cursor-todo-selection-as-state-change)))
19424 (org-call-with-arg 'org-todo 'left)))
19425 ((or (and org-support-shift-select
19426 (not (eq org-support-shift-select 'always))
19427 (org-at-item-bullet-p))
19428 (and (not org-support-shift-select) (org-at-item-p)))
19429 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19430 ((and (not (eq org-support-shift-select 'always))
19431 (org-at-property-p))
19432 (call-interactively 'org-property-previous-allowed-value))
19433 ((org-clocktable-try-shift 'left arg))
19434 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19435 (org-support-shift-select
19436 (org-call-for-shift-select 'backward-char))
19437 (t (org-shiftselect-error))))
19439 (defun org-shiftcontrolright ()
19440 "Switch to next TODO set."
19441 (interactive)
19442 (cond
19443 ((and org-support-shift-select (org-region-active-p))
19444 (org-call-for-shift-select 'forward-word))
19445 ((and (not (eq org-support-shift-select 'always))
19446 (org-at-heading-p))
19447 (org-call-with-arg 'org-todo 'nextset))
19448 (org-support-shift-select
19449 (org-call-for-shift-select 'forward-word))
19450 (t (org-shiftselect-error))))
19452 (defun org-shiftcontrolleft ()
19453 "Switch to previous TODO set."
19454 (interactive)
19455 (cond
19456 ((and org-support-shift-select (org-region-active-p))
19457 (org-call-for-shift-select 'backward-word))
19458 ((and (not (eq org-support-shift-select 'always))
19459 (org-at-heading-p))
19460 (org-call-with-arg 'org-todo 'previousset))
19461 (org-support-shift-select
19462 (org-call-for-shift-select 'backward-word))
19463 (t (org-shiftselect-error))))
19465 (defun org-shiftcontrolup (&optional n)
19466 "Change timestamps synchronously up in CLOCK log lines.
19467 Optional argument N tells to change by that many units."
19468 (interactive "P")
19469 (cond ((and (not org-support-shift-select)
19470 (org-at-clock-log-p)
19471 (org-at-timestamp-p t))
19472 (org-clock-timestamps-up n))
19473 (t (org-shiftselect-error))))
19475 (defun org-shiftcontroldown (&optional n)
19476 "Change timestamps synchronously down in CLOCK log lines.
19477 Optional argument N tells to change by that many units."
19478 (interactive "P")
19479 (cond ((and (not org-support-shift-select)
19480 (org-at-clock-log-p)
19481 (org-at-timestamp-p t))
19482 (org-clock-timestamps-down n))
19483 (t (org-shiftselect-error))))
19485 (defun org-ctrl-c-ret ()
19486 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19487 (interactive)
19488 (cond
19489 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19490 (t (call-interactively 'org-insert-heading))))
19492 (defun org-find-visible ()
19493 (let ((s (point)))
19494 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19495 (get-char-property s 'invisible)))
19497 (defun org-find-invisible ()
19498 (let ((s (point)))
19499 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19500 (not (get-char-property s 'invisible))))
19503 (defun org-copy-visible (beg end)
19504 "Copy the visible parts of the region."
19505 (interactive "r")
19506 (let (snippets s)
19507 (save-excursion
19508 (save-restriction
19509 (narrow-to-region beg end)
19510 (setq s (goto-char (point-min)))
19511 (while (not (= (point) (point-max)))
19512 (goto-char (org-find-invisible))
19513 (push (buffer-substring s (point)) snippets)
19514 (setq s (goto-char (org-find-visible))))))
19515 (kill-new (apply 'concat (nreverse snippets)))))
19517 (defun org-copy-special ()
19518 "Copy region in table or copy current subtree.
19519 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19520 See the individual commands for more information."
19521 (interactive)
19522 (call-interactively
19523 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19525 (defun org-cut-special ()
19526 "Cut region in table or cut current subtree.
19527 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19528 See the individual commands for more information."
19529 (interactive)
19530 (call-interactively
19531 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19533 (defun org-paste-special (arg)
19534 "Paste rectangular region into table, or past subtree relative to level.
19535 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19536 See the individual commands for more information."
19537 (interactive "P")
19538 (if (org-at-table-p)
19539 (org-table-paste-rectangle)
19540 (org-paste-subtree arg)))
19542 (defsubst org-in-fixed-width-region-p ()
19543 "Is point in a fixed-width region?"
19544 (save-match-data
19545 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19547 (defun org-edit-special (&optional arg)
19548 "Call a special editor for the element at point.
19549 When at a table, call the formula editor with `org-table-edit-formulas'.
19550 When in a source code block, call `org-edit-src-code'.
19551 When in a fixed-width region, call `org-edit-fixed-width-region'.
19552 When at an #+INCLUDE keyword, visit the included file.
19553 On a link, call `ffap' to visit the link at point.
19554 Otherwise, return a user error."
19555 (interactive)
19556 (let ((element (org-element-at-point)))
19557 (assert (not buffer-read-only) nil
19558 "Buffer is read-only: %s" (buffer-name))
19559 (case (org-element-type element)
19560 (src-block
19561 (if (not arg) (org-edit-src-code)
19562 (let* ((info (org-babel-get-src-block-info))
19563 (lang (nth 0 info))
19564 (params (nth 2 info))
19565 (session (cdr (assq :session params))))
19566 (if (not session) (org-edit-src-code)
19567 ;; At a src-block with a session and function called with
19568 ;; an ARG: switch to the buffer related to the inferior
19569 ;; process.
19570 (funcall (intern (concat "org-babel-prep-session:" lang))
19571 session params)))))
19572 (keyword
19573 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19574 (find-file
19575 (org-remove-double-quotes
19576 (car (org-split-string (org-element-property :value element)))))
19577 (user-error "No special environment to edit here")))
19578 (table
19579 (if (eq (org-element-property :type element) 'table.el)
19580 (org-edit-src-code)
19581 (call-interactively 'org-table-edit-formulas)))
19582 ;; Only Org tables contain `table-row' type elements.
19583 (table-row (call-interactively 'org-table-edit-formulas))
19584 ((example-block export-block) (org-edit-src-code))
19585 (fixed-width (org-edit-fixed-width-region))
19586 (otherwise
19587 ;; No notable element at point. Though, we may be at a link,
19588 ;; which is an object. Thus, scan deeper.
19589 (if (eq (org-element-type (org-element-context element)) 'link)
19590 (call-interactively 'ffap)
19591 (user-error "No special environment to edit here"))))))
19593 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19594 (defun org-ctrl-c-ctrl-c (&optional arg)
19595 "Set tags in headline, or update according to changed information at point.
19597 This command does many different things, depending on context:
19599 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19600 this is what we do.
19602 - If the cursor is on a statistics cookie, update it.
19604 - If the cursor is in a headline, prompt for tags and insert them
19605 into the current line, aligned to `org-tags-column'. When called
19606 with prefix arg, realign all tags in the current buffer.
19608 - If the cursor is in one of the special #+KEYWORD lines, this
19609 triggers scanning the buffer for these lines and updating the
19610 information.
19612 - If the cursor is inside a table, realign the table. This command
19613 works even if the automatic table editor has been turned off.
19615 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19616 the entire table.
19618 - If the cursor is at a footnote reference or definition, jump to
19619 the corresponding definition or references, respectively.
19621 - If the cursor is a the beginning of a dynamic block, update it.
19623 - If the current buffer is a capture buffer, close note and file it.
19625 - If the cursor is on a <<<target>>>, update radio targets and
19626 corresponding links in this buffer.
19628 - If the cursor is on a numbered item in a plain list, renumber the
19629 ordered list.
19631 - If the cursor is on a checkbox, toggle it.
19633 - If the cursor is on a code block, evaluate it. The variable
19634 `org-confirm-babel-evaluate' can be used to control prompting
19635 before code block evaluation, by default every code block
19636 evaluation requires confirmation. Code block evaluation can be
19637 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19638 (interactive "P")
19639 (cond
19640 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19641 org-occur-highlights
19642 org-latex-fragment-image-overlays)
19643 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19644 (org-remove-occur-highlights)
19645 (org-remove-latex-fragment-image-overlays)
19646 (message "Temporary highlights/overlays removed from current buffer"))
19647 ((and (local-variable-p 'org-finish-function (current-buffer))
19648 (fboundp org-finish-function))
19649 (funcall org-finish-function))
19650 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19652 (let* ((context (org-element-context)) (type (org-element-type context)))
19653 ;; Test if point is within a blank line.
19654 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19655 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19656 (user-error "C-c C-c can do nothing useful at this location"))
19657 ;; For convenience: at the first line of a paragraph on the
19658 ;; same line as an item, apply function on that item instead.
19659 (when (eq type 'paragraph)
19660 (let ((parent (org-element-property :parent context)))
19661 (when (and (eq (org-element-type parent) 'item)
19662 (= (point-at-bol) (org-element-property :begin parent)))
19663 (setq context parent type 'item))))
19664 ;; Act according to type of element or object at point.
19665 (case type
19666 (clock (org-clock-update-time-maybe))
19667 (dynamic-block
19668 (save-excursion
19669 (goto-char (org-element-property :post-affiliated context))
19670 (org-update-dblock)))
19671 (footnote-definition
19672 (goto-char (org-element-property :post-affiliated context))
19673 (call-interactively 'org-footnote-action))
19674 (footnote-reference (call-interactively 'org-footnote-action))
19675 ((headline inlinetask)
19676 (save-excursion (goto-char (org-element-property :begin context))
19677 (call-interactively 'org-set-tags)))
19678 (item
19679 ;; At an item: a double C-u set checkbox to "[-]"
19680 ;; unconditionally, whereas a single one will toggle its
19681 ;; presence. Without an universal argument, if the item
19682 ;; has a checkbox, toggle it. Otherwise repair the list.
19683 (let* ((box (org-element-property :checkbox context))
19684 (struct (org-element-property :structure context))
19685 (old-struct (copy-tree struct))
19686 (parents (org-list-parents-alist struct))
19687 (prevs (org-list-prevs-alist struct))
19688 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19689 (org-list-set-checkbox
19690 (org-element-property :begin context) struct
19691 (cond ((equal arg '(16)) "[-]")
19692 ((and (not box) (equal arg '(4))) "[ ]")
19693 ((or (not box) (equal arg '(4))) nil)
19694 ((eq box 'on) "[ ]")
19695 (t "[X]")))
19696 ;; Mimic `org-list-write-struct' but with grabbing
19697 ;; a return value from `org-list-struct-fix-box'.
19698 (org-list-struct-fix-ind struct parents 2)
19699 (org-list-struct-fix-item-end struct)
19700 (org-list-struct-fix-bul struct prevs)
19701 (org-list-struct-fix-ind struct parents)
19702 (let ((block-item
19703 (org-list-struct-fix-box struct parents prevs orderedp)))
19704 (if (and box (equal struct old-struct))
19705 (if (equal arg '(16))
19706 (message "Checkboxes already reset")
19707 (user-error "Cannot toggle this checkbox: %s"
19708 (if (eq box 'on)
19709 "all subitems checked"
19710 "unchecked subitems")))
19711 (org-list-struct-apply-struct struct old-struct)
19712 (org-update-checkbox-count-maybe))
19713 (when block-item
19714 (message "Checkboxes were removed due to empty box at line %d"
19715 (org-current-line block-item))))))
19716 (keyword
19717 (let ((org-inhibit-startup-visibility-stuff t)
19718 (org-startup-align-all-tables nil))
19719 (when (boundp 'org-table-coordinate-overlays)
19720 (mapc 'delete-overlay org-table-coordinate-overlays)
19721 (setq org-table-coordinate-overlays nil))
19722 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19723 (message "Local setup has been refreshed"))
19724 (plain-list
19725 ;; At a plain list, with a double C-u argument, set
19726 ;; checkboxes of each item to "[-]", whereas a single one
19727 ;; will toggle their presence according to the state of the
19728 ;; first item in the list. Without an argument, repair the
19729 ;; list.
19730 (let* ((begin (org-element-property :contents-begin context))
19731 (struct (org-element-property :structure context))
19732 (old-struct (copy-tree struct))
19733 (first-box (save-excursion
19734 (goto-char begin)
19735 (looking-at org-list-full-item-re)
19736 (match-string-no-properties 3)))
19737 (new-box (cond ((equal arg '(16)) "[-]")
19738 ((equal arg '(4)) (unless first-box "[ ]"))
19739 ((equal first-box "[X]") "[ ]")
19740 (t "[X]"))))
19741 (cond
19742 (arg
19743 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19744 (org-list-get-all-items
19745 begin struct (org-list-prevs-alist struct))))
19746 ((and first-box (eq (point) begin))
19747 ;; For convenience, when point is at bol on the first
19748 ;; item of the list and no argument is provided, simply
19749 ;; toggle checkbox of that item, if any.
19750 (org-list-set-checkbox begin struct new-box)))
19751 (org-list-write-struct
19752 struct (org-list-parents-alist struct) old-struct)
19753 (org-update-checkbox-count-maybe)
19754 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19755 ((property-drawer node-property)
19756 (call-interactively 'org-property-action))
19757 ((radio-target target)
19758 (call-interactively 'org-update-radio-target-regexp))
19759 (statistics-cookie
19760 (call-interactively 'org-update-statistics-cookies))
19761 ((table table-cell table-row)
19762 ;; At a table, recalculate every field and align it. Also
19763 ;; send the table if necessary. If the table has
19764 ;; a `table.el' type, just give up. At a table row or
19765 ;; cell, maybe recalculate line but always align table.
19766 (if (eq (org-element-property :type context) 'table.el)
19767 (message "Use C-c ' to edit table.el tables")
19768 (let ((org-enable-table-editor t))
19769 (if (or (eq type 'table)
19770 ;; Check if point is at a TBLFM line.
19771 (and (eq type 'table-row)
19772 (= (point) (org-element-property :end context))))
19773 (save-excursion
19774 (goto-char (org-element-property :contents-begin context))
19775 (org-call-with-arg 'org-table-recalculate (or arg t))
19776 (orgtbl-send-table 'maybe))
19777 (org-table-maybe-eval-formula)
19778 (cond (arg (call-interactively 'org-table-recalculate))
19779 ((org-table-maybe-recalculate-line))
19780 (t (org-table-align)))))))
19781 (timestamp (org-timestamp-change 0 'day))
19782 (otherwise
19783 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19784 (user-error
19785 "C-c C-c can do nothing useful at this location")))))))))
19787 (defun org-mode-restart ()
19788 "Restart Org-mode, to scan again for special lines.
19789 Also updates the keyword regular expressions."
19790 (interactive)
19791 (org-mode)
19792 (message "Org-mode restarted"))
19794 (defun org-kill-note-or-show-branches ()
19795 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19796 (interactive)
19797 (if (not org-finish-function)
19798 (progn
19799 (hide-subtree)
19800 (call-interactively 'show-branches))
19801 (let ((org-note-abort t))
19802 (funcall org-finish-function))))
19804 (defun org-return (&optional indent)
19805 "Goto next table row or insert a newline.
19806 Calls `org-table-next-row' or `newline', depending on context.
19807 See the individual commands for more information."
19808 (interactive)
19809 (let (org-ts-what)
19810 (cond
19811 ((or (bobp) (org-in-src-block-p))
19812 (if indent (newline-and-indent) (newline)))
19813 ((org-at-table-p)
19814 (org-table-justify-field-maybe)
19815 (call-interactively 'org-table-next-row))
19816 ;; when `newline-and-indent' is called within a list, make sure
19817 ;; text moved stays inside the item.
19818 ((and (org-in-item-p) indent)
19819 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19820 (progn
19821 (save-match-data (newline))
19822 (org-indent-line-to (length (match-string 0))))
19823 (let ((ind (org-get-indentation)))
19824 (newline)
19825 (if (org-looking-back org-list-end-re)
19826 (org-indent-line)
19827 (org-indent-line-to ind)))))
19828 ((and org-return-follows-link
19829 (org-at-timestamp-p t)
19830 (not (eq org-ts-what 'after)))
19831 (org-follow-timestamp-link))
19832 ((and org-return-follows-link
19833 (let ((tprop (get-text-property (point) 'face)))
19834 (or (eq tprop 'org-link)
19835 (and (listp tprop) (memq 'org-link tprop)))))
19836 (call-interactively 'org-open-at-point))
19837 ((and (org-at-heading-p)
19838 (looking-at
19839 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19840 (org-show-entry)
19841 (end-of-line 1)
19842 (newline))
19843 (t (if indent (newline-and-indent) (newline))))))
19845 (defun org-return-indent ()
19846 "Goto next table row or insert a newline and indent.
19847 Calls `org-table-next-row' or `newline-and-indent', depending on
19848 context. See the individual commands for more information."
19849 (interactive)
19850 (org-return t))
19852 (defun org-ctrl-c-star ()
19853 "Compute table, or change heading status of lines.
19854 Calls `org-table-recalculate' or `org-toggle-heading',
19855 depending on context."
19856 (interactive)
19857 (cond
19858 ((org-at-table-p)
19859 (call-interactively 'org-table-recalculate))
19861 ;; Convert all lines in region to list items
19862 (call-interactively 'org-toggle-heading))))
19864 (defun org-ctrl-c-minus ()
19865 "Insert separator line in table or modify bullet status of line.
19866 Also turns a plain line or a region of lines into list items.
19867 Calls `org-table-insert-hline', `org-toggle-item', or
19868 `org-cycle-list-bullet', depending on context."
19869 (interactive)
19870 (cond
19871 ((org-at-table-p)
19872 (call-interactively 'org-table-insert-hline))
19873 ((org-region-active-p)
19874 (call-interactively 'org-toggle-item))
19875 ((org-in-item-p)
19876 (call-interactively 'org-cycle-list-bullet))
19878 (call-interactively 'org-toggle-item))))
19880 (defun org-toggle-item (arg)
19881 "Convert headings or normal lines to items, items to normal lines.
19882 If there is no active region, only the current line is considered.
19884 If the first non blank line in the region is an headline, convert
19885 all headlines to items, shifting text accordingly.
19887 If it is an item, convert all items to normal lines.
19889 If it is normal text, change region into an item. With a prefix
19890 argument ARG, change each line in region into an item."
19891 (interactive "P")
19892 (let ((shift-text
19893 (function
19894 ;; Shift text in current section to IND, from point to END.
19895 ;; The function leaves point to END line.
19896 (lambda (ind end)
19897 (let ((min-i 1000) (end (copy-marker end)))
19898 ;; First determine the minimum indentation (MIN-I) of
19899 ;; the text.
19900 (save-excursion
19901 (catch 'exit
19902 (while (< (point) end)
19903 (let ((i (org-get-indentation)))
19904 (cond
19905 ;; Skip blank lines and inline tasks.
19906 ((looking-at "^[ \t]*$"))
19907 ((looking-at org-outline-regexp-bol))
19908 ;; We can't find less than 0 indentation.
19909 ((zerop i) (throw 'exit (setq min-i 0)))
19910 ((< i min-i) (setq min-i i))))
19911 (forward-line))))
19912 ;; Then indent each line so that a line indented to
19913 ;; MIN-I becomes indented to IND. Ignore blank lines
19914 ;; and inline tasks in the process.
19915 (let ((delta (- ind min-i)))
19916 (while (< (point) end)
19917 (unless (or (looking-at "^[ \t]*$")
19918 (looking-at org-outline-regexp-bol))
19919 (org-indent-line-to (+ (org-get-indentation) delta)))
19920 (forward-line)))))))
19921 (skip-blanks
19922 (function
19923 ;; Return beginning of first non-blank line, starting from
19924 ;; line at POS.
19925 (lambda (pos)
19926 (save-excursion
19927 (goto-char pos)
19928 (skip-chars-forward " \r\t\n")
19929 (point-at-bol)))))
19930 beg end)
19931 ;; Determine boundaries of changes.
19932 (if (org-region-active-p)
19933 (setq beg (funcall skip-blanks (region-beginning))
19934 end (copy-marker (region-end)))
19935 (setq beg (funcall skip-blanks (point-at-bol))
19936 end (copy-marker (point-at-eol))))
19937 ;; Depending on the starting line, choose an action on the text
19938 ;; between BEG and END.
19939 (org-with-limited-levels
19940 (save-excursion
19941 (goto-char beg)
19942 (cond
19943 ;; Case 1. Start at an item: de-itemize. Note that it only
19944 ;; happens when a region is active: `org-ctrl-c-minus'
19945 ;; would call `org-cycle-list-bullet' otherwise.
19946 ((org-at-item-p)
19947 (while (< (point) end)
19948 (when (org-at-item-p)
19949 (skip-chars-forward " \t")
19950 (delete-region (point) (match-end 0)))
19951 (forward-line)))
19952 ;; Case 2. Start at an heading: convert to items.
19953 ((org-at-heading-p)
19954 (let* ((bul (org-list-bullet-string "-"))
19955 (bul-len (length bul))
19956 ;; Indentation of the first heading. It should be
19957 ;; relative to the indentation of its parent, if any.
19958 (start-ind (save-excursion
19959 (cond
19960 ((not org-adapt-indentation) 0)
19961 ((not (outline-previous-heading)) 0)
19962 (t (length (match-string 0))))))
19963 ;; Level of first heading. Further headings will be
19964 ;; compared to it to determine hierarchy in the list.
19965 (ref-level (org-reduced-level (org-outline-level))))
19966 (while (< (point) end)
19967 (let* ((level (org-reduced-level (org-outline-level)))
19968 (delta (max 0 (- level ref-level))))
19969 ;; If current headline is less indented than the first
19970 ;; one, set it as reference, in order to preserve
19971 ;; subtrees.
19972 (when (< level ref-level) (setq ref-level level))
19973 (replace-match bul t t)
19974 (org-indent-line-to (+ start-ind (* delta bul-len)))
19975 ;; Ensure all text down to END (or SECTION-END) belongs
19976 ;; to the newly created item.
19977 (let ((section-end (save-excursion
19978 (or (outline-next-heading) (point)))))
19979 (forward-line)
19980 (funcall shift-text
19981 (+ start-ind (* (1+ delta) bul-len))
19982 (min end section-end)))))))
19983 ;; Case 3. Normal line with ARG: turn each non-item line into
19984 ;; an item.
19985 (arg
19986 (while (< (point) end)
19987 (unless (or (org-at-heading-p) (org-at-item-p))
19988 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19989 (replace-match
19990 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19991 (forward-line)))
19992 ;; Case 4. Normal line without ARG: make the first line of
19993 ;; region an item, and shift indentation of others
19994 ;; lines to set them as item's body.
19995 (t (let* ((bul (org-list-bullet-string "-"))
19996 (bul-len (length bul))
19997 (ref-ind (org-get-indentation)))
19998 (skip-chars-forward " \t")
19999 (insert bul)
20000 (forward-line)
20001 (while (< (point) end)
20002 ;; Ensure that lines less indented than first one
20003 ;; still get included in item body.
20004 (funcall shift-text
20005 (+ ref-ind bul-len)
20006 (min end (save-excursion (or (outline-next-heading)
20007 (point)))))
20008 (forward-line)))))))))
20010 (defun org-toggle-heading (&optional nstars)
20011 "Convert headings to normal text, or items or text to headings.
20012 If there is no active region, only the current line is considered.
20014 With a \\[universal-argument] prefix, convert the whole list at
20015 point into heading.
20017 In a region:
20019 - If the first non blank line is an headline, remove the stars
20020 from all headlines in the region.
20022 - If it is a normal line turn each and every normal line (i.e. not an
20023 heading or an item) in the region into a heading.
20025 - If it is a plain list item, turn all plain list items into headings.
20027 When converting a line into a heading, the number of stars is chosen
20028 such that the lines become children of the current entry. However,
20029 when a prefix argument is given, its value determines the number of
20030 stars to add."
20031 (interactive "P")
20032 (let ((skip-blanks
20033 (function
20034 ;; Return beginning of first non-blank line, starting from
20035 ;; line at POS.
20036 (lambda (pos)
20037 (save-excursion
20038 (goto-char pos)
20039 (while (org-at-comment-p) (forward-line))
20040 (skip-chars-forward " \r\t\n")
20041 (point-at-bol)))))
20042 beg end toggled)
20043 ;; Determine boundaries of changes. If a universal prefix has
20044 ;; been given, put the list in a region. If region ends at a bol,
20045 ;; do not consider the last line to be in the region.
20047 (when (and current-prefix-arg (org-at-item-p))
20048 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20049 (org-mark-element))
20051 (if (org-region-active-p)
20052 (setq beg (funcall skip-blanks (region-beginning))
20053 end (copy-marker (save-excursion
20054 (goto-char (region-end))
20055 (if (bolp) (point) (point-at-eol)))))
20056 (setq beg (funcall skip-blanks (point-at-bol))
20057 end (copy-marker (point-at-eol))))
20058 ;; Ensure inline tasks don't count as headings.
20059 (org-with-limited-levels
20060 (save-excursion
20061 (goto-char beg)
20062 (cond
20063 ;; Case 1. Started at an heading: de-star headings.
20064 ((org-at-heading-p)
20065 (while (< (point) end)
20066 (when (org-at-heading-p t)
20067 (looking-at org-outline-regexp) (replace-match "")
20068 (setq toggled t))
20069 (forward-line)))
20070 ;; Case 2. Started at an item: change items into headlines.
20071 ;; One star will be added by `org-list-to-subtree'.
20072 ((org-at-item-p)
20073 (let* ((stars (make-string
20074 (if nstars
20075 ;; subtract the star that will be added again by
20076 ;; `org-list-to-subtree'
20077 (1- (prefix-numeric-value current-prefix-arg))
20078 (or (org-current-level) 0))
20079 ?*))
20080 (add-stars
20081 (cond (nstars "") ; stars from prefix only
20082 ((equal stars "") "") ; before first heading
20083 (org-odd-levels-only "*") ; inside heading, odd
20084 (t "")))) ; inside heading, oddeven
20085 (while (< (point) end)
20086 (when (org-at-item-p)
20087 ;; Pay attention to cases when region ends before list.
20088 (let* ((struct (org-list-struct))
20089 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20090 (save-restriction
20091 (narrow-to-region (point) list-end)
20092 (insert
20093 (org-list-to-subtree
20094 (org-list-parse-list t)
20095 '(:istart (concat stars add-stars (funcall get-stars depth))
20096 :icount (concat stars add-stars (funcall get-stars depth)))))))
20097 (setq toggled t))
20098 (forward-line))))
20099 ;; Case 3. Started at normal text: make every line an heading,
20100 ;; skipping headlines and items.
20101 (t (let* ((stars (make-string
20102 (if nstars
20103 (prefix-numeric-value current-prefix-arg)
20104 (or (org-current-level) 0))
20105 ?*))
20106 (add-stars
20107 (cond (nstars "") ; stars from prefix only
20108 ((equal stars "") "*") ; before first heading
20109 (org-odd-levels-only "**") ; inside heading, odd
20110 (t "*"))) ; inside heading, oddeven
20111 (rpl (concat stars add-stars " ")))
20112 (while (< (point) end)
20113 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20114 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20115 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20116 (forward-line)))))))
20117 (unless toggled (message "Cannot toggle heading from here"))))
20119 (defun org-meta-return (&optional arg)
20120 "Insert a new heading or wrap a region in a table.
20121 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20122 See the individual commands for more information."
20123 (interactive "P")
20124 (cond
20125 ((run-hook-with-args-until-success 'org-metareturn-hook))
20126 ((or (org-at-drawer-p) (org-at-property-p))
20127 (newline-and-indent))
20128 ((org-at-table-p)
20129 (call-interactively 'org-table-wrap-region))
20130 (t (call-interactively 'org-insert-heading))))
20132 ;;; Menu entries
20134 (defsubst org-in-subtree-not-table-p ()
20135 "Are we in a subtree and not in a table?"
20136 (and (not (org-before-first-heading-p))
20137 (not (org-at-table-p))))
20139 ;; Define the Org-mode menus
20140 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20141 '("Tbl"
20142 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20143 ["Next Field" org-cycle (org-at-table-p)]
20144 ["Previous Field" org-shifttab (org-at-table-p)]
20145 ["Next Row" org-return (org-at-table-p)]
20146 "--"
20147 ["Blank Field" org-table-blank-field (org-at-table-p)]
20148 ["Edit Field" org-table-edit-field (org-at-table-p)]
20149 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20150 "--"
20151 ("Column"
20152 ["Move Column Left" org-metaleft (org-at-table-p)]
20153 ["Move Column Right" org-metaright (org-at-table-p)]
20154 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20155 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20156 ("Row"
20157 ["Move Row Up" org-metaup (org-at-table-p)]
20158 ["Move Row Down" org-metadown (org-at-table-p)]
20159 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20160 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20161 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20162 "--"
20163 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20164 ("Rectangle"
20165 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20166 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20167 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20168 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20169 "--"
20170 ("Calculate"
20171 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20172 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20173 ["Edit Formulas" org-edit-special (org-at-table-p)]
20174 "--"
20175 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20176 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20177 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20178 "--"
20179 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20180 "--"
20181 ["Sum Column/Rectangle" org-table-sum
20182 (or (org-at-table-p) (org-region-active-p))]
20183 ["Which Column?" org-table-current-column (org-at-table-p)])
20184 ["Debug Formulas"
20185 org-table-toggle-formula-debugger
20186 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20187 ["Show Col/Row Numbers"
20188 org-table-toggle-coordinate-overlays
20189 :style toggle
20190 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20191 "--"
20192 ["Create" org-table-create (and (not (org-at-table-p))
20193 org-enable-table-editor)]
20194 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20195 ["Import from File" org-table-import (not (org-at-table-p))]
20196 ["Export to File" org-table-export (org-at-table-p)]
20197 "--"
20198 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20200 (easy-menu-define org-org-menu org-mode-map "Org menu"
20201 '("Org"
20202 ("Show/Hide"
20203 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20204 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20205 ["Sparse Tree..." org-sparse-tree t]
20206 ["Reveal Context" org-reveal t]
20207 ["Show All" show-all t]
20208 "--"
20209 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20210 "--"
20211 ["New Heading" org-insert-heading t]
20212 ("Navigate Headings"
20213 ["Up" outline-up-heading t]
20214 ["Next" outline-next-visible-heading t]
20215 ["Previous" outline-previous-visible-heading t]
20216 ["Next Same Level" outline-forward-same-level t]
20217 ["Previous Same Level" outline-backward-same-level t]
20218 "--"
20219 ["Jump" org-goto t])
20220 ("Edit Structure"
20221 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20222 "--"
20223 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20224 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20225 "--"
20226 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20227 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20228 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20229 "--"
20230 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20231 "--"
20232 ["Copy visible text" org-copy-visible t]
20233 "--"
20234 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20235 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20236 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20237 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20238 "--"
20239 ["Sort Region/Children" org-sort t]
20240 "--"
20241 ["Convert to odd levels" org-convert-to-odd-levels t]
20242 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20243 ("Editing"
20244 ["Emphasis..." org-emphasize t]
20245 ["Edit Source Example" org-edit-special t]
20246 "--"
20247 ["Footnote new/jump" org-footnote-action t]
20248 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20249 ("Archive"
20250 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20251 "--"
20252 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20253 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20254 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20256 "--"
20257 ("Hyperlinks"
20258 ["Store Link (Global)" org-store-link t]
20259 ["Find existing link to here" org-occur-link-in-agenda-files t]
20260 ["Insert Link" org-insert-link t]
20261 ["Follow Link" org-open-at-point t]
20262 "--"
20263 ["Next link" org-next-link t]
20264 ["Previous link" org-previous-link t]
20265 "--"
20266 ["Descriptive Links"
20267 org-toggle-link-display
20268 :style radio
20269 :selected org-descriptive-links
20271 ["Literal Links"
20272 org-toggle-link-display
20273 :style radio
20274 :selected (not org-descriptive-links)])
20275 "--"
20276 ("TODO Lists"
20277 ["TODO/DONE/-" org-todo t]
20278 ("Select keyword"
20279 ["Next keyword" org-shiftright (org-at-heading-p)]
20280 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20281 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20282 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20283 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20284 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20285 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20286 "--"
20287 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20288 :selected org-enforce-todo-dependencies :style toggle :active t]
20289 "Settings for tree at point"
20290 ["Do Children sequentially" org-toggle-ordered-property :style radio
20291 :selected (org-entry-get nil "ORDERED")
20292 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20293 ["Do Children parallel" org-toggle-ordered-property :style radio
20294 :selected (not (org-entry-get nil "ORDERED"))
20295 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20296 "--"
20297 ["Set Priority" org-priority t]
20298 ["Priority Up" org-shiftup t]
20299 ["Priority Down" org-shiftdown t]
20300 "--"
20301 ["Get news from all feeds" org-feed-update-all t]
20302 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20303 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20304 ("TAGS and Properties"
20305 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20306 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20307 "--"
20308 ["Set property" org-set-property (not (org-before-first-heading-p))]
20309 ["Column view of properties" org-columns t]
20310 ["Insert Column View DBlock" org-insert-columns-dblock t])
20311 ("Dates and Scheduling"
20312 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20313 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20314 ("Change Date"
20315 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20316 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20317 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20318 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20319 ["Compute Time Range" org-evaluate-time-range t]
20320 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20321 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20322 "--"
20323 ["Custom time format" org-toggle-time-stamp-overlays
20324 :style radio :selected org-display-custom-times]
20325 "--"
20326 ["Goto Calendar" org-goto-calendar t]
20327 ["Date from Calendar" org-date-from-calendar t]
20328 "--"
20329 ["Start/Restart Timer" org-timer-start t]
20330 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20331 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20332 ["Insert Timer String" org-timer t]
20333 ["Insert Timer Item" org-timer-item t])
20334 ("Logging work"
20335 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20336 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20337 ["Clock out" org-clock-out t]
20338 ["Clock cancel" org-clock-cancel t]
20339 "--"
20340 ["Mark as default task" org-clock-mark-default-task t]
20341 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20342 ["Goto running clock" org-clock-goto t]
20343 "--"
20344 ["Display times" org-clock-display t]
20345 ["Create clock table" org-clock-report t]
20346 "--"
20347 ["Record DONE time"
20348 (progn (setq org-log-done (not org-log-done))
20349 (message "Switching to %s will %s record a timestamp"
20350 (car org-done-keywords)
20351 (if org-log-done "automatically" "not")))
20352 :style toggle :selected org-log-done])
20353 "--"
20354 ["Agenda Command..." org-agenda t]
20355 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20356 ("File List for Agenda")
20357 ("Special views current file"
20358 ["TODO Tree" org-show-todo-tree t]
20359 ["Check Deadlines" org-check-deadlines t]
20360 ["Timeline" org-timeline t]
20361 ["Tags/Property tree" org-match-sparse-tree t])
20362 "--"
20363 ["Export/Publish..." org-export-dispatch t]
20364 ("LaTeX"
20365 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20366 :selected org-cdlatex-mode]
20367 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20368 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20369 ["Modify math symbol" org-cdlatex-math-modify
20370 (org-inside-LaTeX-fragment-p)]
20371 ["Insert citation" org-reftex-citation t]
20372 "--"
20373 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20374 "--"
20375 ("MobileOrg"
20376 ["Push Files and Views" org-mobile-push t]
20377 ["Get Captured and Flagged" org-mobile-pull t]
20378 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20379 "--"
20380 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20381 "--"
20382 ("Documentation"
20383 ["Show Version" org-version t]
20384 ["Info Documentation" org-info t])
20385 ("Customize"
20386 ["Browse Org Group" org-customize t]
20387 "--"
20388 ["Expand This Menu" org-create-customize-menu
20389 (fboundp 'customize-menu-create)])
20390 ["Send bug report" org-submit-bug-report t]
20391 "--"
20392 ("Refresh/Reload"
20393 ["Refresh setup current buffer" org-mode-restart t]
20394 ["Reload Org (after update)" org-reload t]
20395 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20398 (defun org-info (&optional node)
20399 "Read documentation for Org-mode in the info system.
20400 With optional NODE, go directly to that node."
20401 (interactive)
20402 (info (format "(org)%s" (or node ""))))
20404 ;;;###autoload
20405 (defun org-submit-bug-report ()
20406 "Submit a bug report on Org-mode via mail.
20408 Don't hesitate to report any problems or inaccurate documentation.
20410 If you don't have setup sending mail from (X)Emacs, please copy the
20411 output buffer into your mail program, as it gives us important
20412 information about your Org-mode version and configuration."
20413 (interactive)
20414 (require 'reporter)
20415 (org-load-modules-maybe)
20416 (org-require-autoloaded-modules)
20417 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20418 (reporter-submit-bug-report
20419 "emacs-orgmode@gnu.org"
20420 (org-version nil 'full)
20421 (let (list)
20422 (save-window-excursion
20423 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20424 (delete-other-windows)
20425 (erase-buffer)
20426 (insert "You are about to submit a bug report to the Org-mode mailing list.
20428 We would like to add your full Org-mode and Outline configuration to the
20429 bug report. This greatly simplifies the work of the maintainer and
20430 other experts on the mailing list.
20432 HOWEVER, some variables you have customized may contain private
20433 information. The names of customers, colleagues, or friends, might
20434 appear in the form of file names, tags, todo states, or search strings.
20435 If you answer yes to the prompt, you might want to check and remove
20436 such private information before sending the email.")
20437 (add-text-properties (point-min) (point-max) '(face org-warning))
20438 (when (yes-or-no-p "Include your Org-mode configuration ")
20439 (mapatoms
20440 (lambda (v)
20441 (and (boundp v)
20442 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20443 (or (and (symbol-value v)
20444 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20445 (and
20446 (get v 'custom-type) (get v 'standard-value)
20447 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20448 (push v list)))))
20449 (kill-buffer (get-buffer "*Warn about privacy*"))
20450 list))
20451 nil nil
20452 "Remember to cover the basics, that is, what you expected to happen and
20453 what in fact did happen. You don't know how to make a good report? See
20455 http://orgmode.org/manual/Feedback.html#Feedback
20457 Your bug report will be posted to the Org-mode mailing list.
20458 ------------------------------------------------------------------------")
20459 (save-excursion
20460 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20461 (replace-match "\\1Bug: \\3 [\\2]")))))
20464 (defun org-install-agenda-files-menu ()
20465 (let ((bl (buffer-list)))
20466 (save-excursion
20467 (while bl
20468 (set-buffer (pop bl))
20469 (if (derived-mode-p 'org-mode) (setq bl nil)))
20470 (when (derived-mode-p 'org-mode)
20471 (easy-menu-change
20472 '("Org") "File List for Agenda"
20473 (append
20474 (list
20475 ["Edit File List" (org-edit-agenda-file-list) t]
20476 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20477 ["Remove Current File from List" org-remove-file t]
20478 ["Cycle through agenda files" org-cycle-agenda-files t]
20479 ["Occur in all agenda files" org-occur-in-agenda-files t]
20480 "--")
20481 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20483 ;;;; Documentation
20485 (defun org-require-autoloaded-modules ()
20486 (interactive)
20487 (mapc 'require
20488 '(org-agenda org-archive org-attach org-clock org-colview org-id
20489 org-remember org-table org-timer)))
20491 ;;;###autoload
20492 (defun org-reload (&optional uncompiled)
20493 "Reload all org lisp files.
20494 With prefix arg UNCOMPILED, load the uncompiled versions."
20495 (interactive "P")
20496 (require 'loadhist)
20497 (let* ((org-dir (org-find-library-dir "org"))
20498 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20499 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20500 (remove-re (mapconcat 'identity
20501 (mapcar (lambda (f) (concat "^" f "$"))
20502 (list (if (featurep 'xemacs)
20503 "org-colview"
20504 "org-colview-xemacs")
20505 "org" "org-loaddefs" "org-version"))
20506 "\\|"))
20507 (feats (delete-dups
20508 (mapcar 'file-name-sans-extension
20509 (mapcar 'file-name-nondirectory
20510 (delq nil
20511 (mapcar 'feature-file
20512 features))))))
20513 (lfeat (append
20514 (sort
20515 (setq feats
20516 (delq nil (mapcar
20517 (lambda (f)
20518 (if (and (string-match feature-re f)
20519 (not (string-match remove-re f)))
20520 f nil))
20521 feats)))
20522 'string-lessp)
20523 (list "org-version" "org")))
20524 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20525 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20526 load-uncore load-misses)
20527 (setq load-misses
20528 (delq 't
20529 (mapcar (lambda (f)
20530 (or (org-load-noerror-mustsuffix (concat org-dir f))
20531 (and (string= org-dir contrib-dir)
20532 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20533 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20534 (add-to-list 'load-uncore f 'append)
20537 lfeat)))
20538 (if load-uncore
20539 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20540 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20541 (if load-misses
20542 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20543 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20544 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20546 ;;;###autoload
20547 (defun org-customize ()
20548 "Call the customize function with org as argument."
20549 (interactive)
20550 (org-load-modules-maybe)
20551 (org-require-autoloaded-modules)
20552 (customize-browse 'org))
20554 (defun org-create-customize-menu ()
20555 "Create a full customization menu for Org-mode, insert it into the menu."
20556 (interactive)
20557 (org-load-modules-maybe)
20558 (org-require-autoloaded-modules)
20559 (if (fboundp 'customize-menu-create)
20560 (progn
20561 (easy-menu-change
20562 '("Org") "Customize"
20563 `(["Browse Org group" org-customize t]
20564 "--"
20565 ,(customize-menu-create 'org)
20566 ["Set" Custom-set t]
20567 ["Save" Custom-save t]
20568 ["Reset to Current" Custom-reset-current t]
20569 ["Reset to Saved" Custom-reset-saved t]
20570 ["Reset to Standard Settings" Custom-reset-standard t]))
20571 (message "\"Org\"-menu now contains full customization menu"))
20572 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20574 ;;;; Miscellaneous stuff
20576 ;;; Generally useful functions
20578 (defun org-get-at-bol (property)
20579 "Get text property PROPERTY at beginning of line."
20580 (get-text-property (point-at-bol) property))
20582 (defun org-find-text-property-in-string (prop s)
20583 "Return the first non-nil value of property PROP in string S."
20584 (or (get-text-property 0 prop s)
20585 (get-text-property (or (next-single-property-change 0 prop s) 0)
20586 prop s)))
20588 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20589 "Display the given MESSAGE as a warning."
20590 (if (fboundp 'display-warning)
20591 (display-warning 'org message
20592 (if (featurep 'xemacs) 'warning :warning))
20593 (let ((buf (get-buffer-create "*Org warnings*")))
20594 (with-current-buffer buf
20595 (goto-char (point-max))
20596 (insert "Warning (Org): " message)
20597 (unless (bolp)
20598 (newline)))
20599 (display-buffer buf)
20600 (sit-for 0))))
20602 (defun org-eval (form)
20603 "Eval FORM and return result."
20604 (condition-case error
20605 (eval form)
20606 (error (format "%%![Error: %s]" error))))
20608 (defun org-in-clocktable-p ()
20609 "Check if the cursor is in a clocktable."
20610 (let ((pos (point)) start)
20611 (save-excursion
20612 (end-of-line 1)
20613 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20614 (setq start (match-beginning 0))
20615 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20616 (>= (match-end 0) pos)
20617 start))))
20619 (defun org-in-commented-line ()
20620 "Is point in a line starting with `#'?"
20621 (equal (char-after (point-at-bol)) ?#))
20623 (defun org-in-indented-comment-line ()
20624 "Is point in a line starting with `#' after some white space?"
20625 (save-excursion
20626 (save-match-data
20627 (goto-char (point-at-bol))
20628 (looking-at "[ \t]*#"))))
20630 (defun org-in-verbatim-emphasis ()
20631 (save-match-data
20632 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20634 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20635 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20636 (if (and marker (marker-buffer marker)
20637 (buffer-live-p (marker-buffer marker)))
20638 (progn
20639 (org-pop-to-buffer-same-window (marker-buffer marker))
20640 (if (or (> marker (point-max)) (< marker (point-min)))
20641 (widen))
20642 (goto-char marker)
20643 (org-show-context 'org-goto))
20644 (if bookmark
20645 (bookmark-jump bookmark)
20646 (error "Cannot find location"))))
20648 (defun org-quote-csv-field (s)
20649 "Quote field for inclusion in CSV material."
20650 (if (string-match "[\",]" s)
20651 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20654 (defun org-force-self-insert (N)
20655 "Needed to enforce self-insert under remapping."
20656 (interactive "p")
20657 (self-insert-command N))
20659 (defun org-string-width (s)
20660 "Compute width of string, ignoring invisible characters.
20661 This ignores character with invisibility property `org-link', and also
20662 characters with property `org-cwidth', because these will become invisible
20663 upon the next fontification round."
20664 (let (b l)
20665 (when (or (eq t buffer-invisibility-spec)
20666 (assq 'org-link buffer-invisibility-spec))
20667 (while (setq b (text-property-any 0 (length s)
20668 'invisible 'org-link s))
20669 (setq s (concat (substring s 0 b)
20670 (substring s (or (next-single-property-change
20671 b 'invisible s) (length s)))))))
20672 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20673 (setq s (concat (substring s 0 b)
20674 (substring s (or (next-single-property-change
20675 b 'org-cwidth s) (length s))))))
20676 (setq l (string-width s) b -1)
20677 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20678 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20681 (defun org-shorten-string (s maxlength)
20682 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20683 If the string is shorter or has length MAXLENGTH, just return the
20684 original string. If it is longer, the functions finds a space in the
20685 string, breaks this string off at that locations and adds three dots
20686 as ellipsis. Including the ellipsis, the string will not be longer
20687 than MAXLENGTH. If finding a good breaking point in the string does
20688 not work, the string is just chopped off in the middle of a word
20689 if necessary."
20690 (if (<= (length s) maxlength)
20692 (let* ((n (max (- maxlength 4) 1))
20693 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20694 (if (string-match re s)
20695 (concat (match-string 1 s) "...")
20696 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20698 (defun org-get-indentation (&optional line)
20699 "Get the indentation of the current line, interpreting tabs.
20700 When LINE is given, assume it represents a line and compute its indentation."
20701 (if line
20702 (if (string-match "^ *" (org-remove-tabs line))
20703 (match-end 0))
20704 (save-excursion
20705 (beginning-of-line 1)
20706 (skip-chars-forward " \t")
20707 (current-column))))
20709 (defun org-get-string-indentation (s)
20710 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20711 (let ((n -1) (i 0) (w tab-width) c)
20712 (catch 'exit
20713 (while (< (setq n (1+ n)) (length s))
20714 (setq c (aref s n))
20715 (cond ((= c ?\ ) (setq i (1+ i)))
20716 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20717 (t (throw 'exit t)))))
20720 (defun org-remove-tabs (s &optional width)
20721 "Replace tabulators in S with spaces.
20722 Assumes that s is a single line, starting in column 0."
20723 (setq width (or width tab-width))
20724 (while (string-match "\t" s)
20725 (setq s (replace-match
20726 (make-string
20727 (- (* width (/ (+ (match-beginning 0) width) width))
20728 (match-beginning 0)) ?\ )
20729 t t s)))
20732 (defun org-fix-indentation (line ind)
20733 "Fix indentation in LINE.
20734 IND is a cons cell with target and minimum indentation.
20735 If the current indentation in LINE is smaller than the minimum,
20736 leave it alone. If it is larger than ind, set it to the target."
20737 (let* ((l (org-remove-tabs line))
20738 (i (org-get-indentation l))
20739 (i1 (car ind)) (i2 (cdr ind)))
20740 (if (>= i i2) (setq l (substring line i2)))
20741 (if (> i1 0)
20742 (concat (make-string i1 ?\ ) l)
20743 l)))
20745 (defun org-remove-indentation (code &optional n)
20746 "Remove the maximum common indentation from the lines in CODE.
20747 N may optionally be the number of spaces to remove."
20748 (with-temp-buffer
20749 (insert code)
20750 (org-do-remove-indentation n)
20751 (buffer-string)))
20753 (defun org-do-remove-indentation (&optional n)
20754 "Remove the maximum common indentation from the buffer."
20755 (untabify (point-min) (point-max))
20756 (let ((min 10000) re)
20757 (if n
20758 (setq min n)
20759 (goto-char (point-min))
20760 (while (re-search-forward "^ *[^ \n]" nil t)
20761 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20762 (unless (or (= min 0) (= min 10000))
20763 (setq re (format "^ \\{%d\\}" min))
20764 (goto-char (point-min))
20765 (while (re-search-forward re nil t)
20766 (replace-match "")
20767 (end-of-line 1))
20768 min)))
20770 (defun org-fill-template (template alist)
20771 "Find each %key of ALIST in TEMPLATE and replace it."
20772 (let ((case-fold-search nil)
20773 entry key value)
20774 (setq alist (sort (copy-sequence alist)
20775 (lambda (a b) (< (length (car a)) (length (car b))))))
20776 (while (setq entry (pop alist))
20777 (setq template
20778 (replace-regexp-in-string
20779 (concat "%" (regexp-quote (car entry)))
20780 (or (cdr entry) "") template t t)))
20781 template))
20783 (defun org-base-buffer (buffer)
20784 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20785 (if (not buffer)
20786 buffer
20787 (or (buffer-base-buffer buffer)
20788 buffer)))
20790 (defun org-trim (s)
20791 "Remove whitespace at beginning and end of string."
20792 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20793 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20796 (defun org-wrap (string &optional width lines)
20797 "Wrap string to either a number of lines, or a width in characters.
20798 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20799 that costs. If there is a word longer than WIDTH, the text is actually
20800 wrapped to the length of that word.
20801 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20802 many lines, whatever width that takes.
20803 The return value is a list of lines, without newlines at the end."
20804 (let* ((words (org-split-string string "[ \t\n]+"))
20805 (maxword (apply 'max (mapcar 'org-string-width words)))
20806 w ll)
20807 (cond (width
20808 (org-do-wrap words (max maxword width)))
20809 (lines
20810 (setq w maxword)
20811 (setq ll (org-do-wrap words maxword))
20812 (if (<= (length ll) lines)
20814 (setq ll words)
20815 (while (> (length ll) lines)
20816 (setq w (1+ w))
20817 (setq ll (org-do-wrap words w)))
20818 ll))
20819 (t (error "Cannot wrap this")))))
20821 (defun org-do-wrap (words width)
20822 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20823 (let (lines line)
20824 (while words
20825 (setq line (pop words))
20826 (while (and words (< (+ (length line) (length (car words))) width))
20827 (setq line (concat line " " (pop words))))
20828 (setq lines (push line lines)))
20829 (nreverse lines)))
20831 (defun org-split-string (string &optional separators)
20832 "Splits STRING into substrings at SEPARATORS.
20833 No empty strings are returned if there are matches at the beginning
20834 and end of string."
20835 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20836 (start 0)
20837 notfirst
20838 (list nil))
20839 (while (and (string-match rexp string
20840 (if (and notfirst
20841 (= start (match-beginning 0))
20842 (< start (length string)))
20843 (1+ start) start))
20844 (< (match-beginning 0) (length string)))
20845 (setq notfirst t)
20846 (or (eq (match-beginning 0) 0)
20847 (and (eq (match-beginning 0) (match-end 0))
20848 (eq (match-beginning 0) start))
20849 (setq list
20850 (cons (substring string start (match-beginning 0))
20851 list)))
20852 (setq start (match-end 0)))
20853 (or (eq start (length string))
20854 (setq list
20855 (cons (substring string start)
20856 list)))
20857 (nreverse list)))
20859 (defun org-quote-vert (s)
20860 "Replace \"|\" with \"\\vert\"."
20861 (while (string-match "|" s)
20862 (setq s (replace-match "\\vert" t t s)))
20865 (defun org-uuidgen-p (s)
20866 "Is S an ID created by UUIDGEN?"
20867 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20869 (defun org-in-src-block-p (&optional inside)
20870 "Whether point is in a code source block.
20871 When INSIDE is non-nil, don't consider we are within a src block
20872 when point is at #+BEGIN_SRC or #+END_SRC."
20873 (let ((case-fold-search t) ov)
20874 (or (and (setq ov (overlays-at (point)))
20875 (memq 'org-block-background
20876 (overlay-properties (car ov))))
20877 (and (not inside)
20878 (save-match-data
20879 (save-excursion
20880 (beginning-of-line)
20881 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20883 (defun org-context ()
20884 "Return a list of contexts of the current cursor position.
20885 If several contexts apply, all are returned.
20886 Each context entry is a list with a symbol naming the context, and
20887 two positions indicating start and end of the context. Possible
20888 contexts are:
20890 :headline anywhere in a headline
20891 :headline-stars on the leading stars in a headline
20892 :todo-keyword on a TODO keyword (including DONE) in a headline
20893 :tags on the TAGS in a headline
20894 :priority on the priority cookie in a headline
20895 :item on the first line of a plain list item
20896 :item-bullet on the bullet/number of a plain list item
20897 :checkbox on the checkbox in a plain list item
20898 :table in an org-mode table
20899 :table-special on a special filed in a table
20900 :table-table in a table.el table
20901 :clocktable in a clocktable
20902 :src-block in a source block
20903 :link on a hyperlink
20904 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20905 :target on a <<target>>
20906 :radio-target on a <<<radio-target>>>
20907 :latex-fragment on a LaTeX fragment
20908 :latex-preview on a LaTeX fragment with overlaid preview image
20910 This function expects the position to be visible because it uses font-lock
20911 faces as a help to recognize the following contexts: :table-special, :link,
20912 and :keyword."
20913 (let* ((f (get-text-property (point) 'face))
20914 (faces (if (listp f) f (list f)))
20915 (case-fold-search t)
20916 (p (point)) clist o)
20917 ;; First the large context
20918 (cond
20919 ((org-at-heading-p t)
20920 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20921 (when (progn
20922 (beginning-of-line 1)
20923 (looking-at org-todo-line-tags-regexp))
20924 (push (org-point-in-group p 1 :headline-stars) clist)
20925 (push (org-point-in-group p 2 :todo-keyword) clist)
20926 (push (org-point-in-group p 4 :tags) clist))
20927 (goto-char p)
20928 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20929 (if (looking-at "\\[#[A-Z0-9]\\]")
20930 (push (org-point-in-group p 0 :priority) clist)))
20932 ((org-at-item-p)
20933 (push (org-point-in-group p 2 :item-bullet) clist)
20934 (push (list :item (point-at-bol)
20935 (save-excursion (org-end-of-item) (point)))
20936 clist)
20937 (and (org-at-item-checkbox-p)
20938 (push (org-point-in-group p 0 :checkbox) clist)))
20940 ((org-at-table-p)
20941 (push (list :table (org-table-begin) (org-table-end)) clist)
20942 (if (memq 'org-formula faces)
20943 (push (list :table-special
20944 (previous-single-property-change p 'face)
20945 (next-single-property-change p 'face)) clist)))
20946 ((org-at-table-p 'any)
20947 (push (list :table-table) clist)))
20948 (goto-char p)
20950 (let ((case-fold-search t))
20951 ;; New the "medium" contexts: clocktables, source blocks
20952 (cond ((org-in-clocktable-p)
20953 (push (list :clocktable
20954 (and (or (looking-at "#\\+BEGIN: clocktable")
20955 (search-backward "#+BEGIN: clocktable" nil t))
20956 (match-beginning 0))
20957 (and (re-search-forward "#\\+END:?" nil t)
20958 (match-end 0))) clist))
20959 ((org-in-src-block-p)
20960 (push (list :src-block
20961 (and (or (looking-at "#\\+BEGIN_SRC")
20962 (search-backward "#+BEGIN_SRC" nil t))
20963 (match-beginning 0))
20964 (and (search-forward "#+END_SRC" nil t)
20965 (match-beginning 0))) clist))))
20966 (goto-char p)
20968 ;; Now the small context
20969 (cond
20970 ((org-at-timestamp-p)
20971 (push (org-point-in-group p 0 :timestamp) clist))
20972 ((memq 'org-link faces)
20973 (push (list :link
20974 (previous-single-property-change p 'face)
20975 (next-single-property-change p 'face)) clist))
20976 ((memq 'org-special-keyword faces)
20977 (push (list :keyword
20978 (previous-single-property-change p 'face)
20979 (next-single-property-change p 'face)) clist))
20980 ((org-at-target-p)
20981 (push (org-point-in-group p 0 :target) clist)
20982 (goto-char (1- (match-beginning 0)))
20983 (if (looking-at org-radio-target-regexp)
20984 (push (org-point-in-group p 0 :radio-target) clist))
20985 (goto-char p))
20986 ((setq o (car (delq nil
20987 (mapcar
20988 (lambda (x)
20989 (if (memq x org-latex-fragment-image-overlays) x))
20990 (overlays-at (point))))))
20991 (push (list :latex-fragment
20992 (overlay-start o) (overlay-end o)) clist)
20993 (push (list :latex-preview
20994 (overlay-start o) (overlay-end o)) clist))
20995 ((org-inside-LaTeX-fragment-p)
20996 ;; FIXME: positions wrong.
20997 (push (list :latex-fragment (point) (point)) clist)))
20999 (setq clist (nreverse (delq nil clist)))
21000 clist))
21002 ;; FIXME: Compare with at-regexp-p Do we need both?
21003 (defun org-in-regexp (re &optional nlines visually)
21004 "Check if point is inside a match of regexp.
21005 Normally only the current line is checked, but you can include NLINES extra
21006 lines both before and after point into the search.
21007 If VISUALLY is set, require that the cursor is not after the match but
21008 really on, so that the block visually is on the match."
21009 (catch 'exit
21010 (let ((pos (point))
21011 (eol (point-at-eol (+ 1 (or nlines 0))))
21012 (inc (if visually 1 0)))
21013 (save-excursion
21014 (beginning-of-line (- 1 (or nlines 0)))
21015 (while (re-search-forward re eol t)
21016 (if (and (<= (match-beginning 0) pos)
21017 (>= (+ inc (match-end 0)) pos))
21018 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21020 (defun org-at-regexp-p (regexp)
21021 "Is point inside a match of REGEXP in the current line?"
21022 (catch 'exit
21023 (save-excursion
21024 (let ((pos (point)) (end (point-at-eol)))
21025 (beginning-of-line 1)
21026 (while (re-search-forward regexp end t)
21027 (if (and (<= (match-beginning 0) pos)
21028 (>= (match-end 0) pos))
21029 (throw 'exit t)))
21030 nil))))
21032 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21033 "Non-nil when point is between matches of START-RE and END-RE.
21035 Also return a non-nil value when point is on one of the matches.
21037 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21038 buffer positions. Default values are the positions of headlines
21039 surrounding the point.
21041 The functions returns a cons cell whose car (resp. cdr) is the
21042 position before START-RE (resp. after END-RE)."
21043 (save-match-data
21044 (let ((pos (point))
21045 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21046 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21047 beg end)
21048 (save-excursion
21049 ;; Point is on a block when on START-RE or if START-RE can be
21050 ;; found before it...
21051 (and (or (org-at-regexp-p start-re)
21052 (re-search-backward start-re limit-up t))
21053 (setq beg (match-beginning 0))
21054 ;; ... and END-RE after it...
21055 (goto-char (match-end 0))
21056 (re-search-forward end-re limit-down t)
21057 (> (setq end (match-end 0)) pos)
21058 ;; ... without another START-RE in-between.
21059 (goto-char (match-beginning 0))
21060 (not (re-search-backward start-re (1+ beg) t))
21061 ;; Return value.
21062 (cons beg end))))))
21064 (defun org-in-block-p (names)
21065 "Non-nil when point belongs to a block whose name belongs to NAMES.
21067 NAMES is a list of strings containing names of blocks.
21069 Return first block name matched, or nil. Beware that in case of
21070 nested blocks, the returned name may not belong to the closest
21071 block from point."
21072 (save-match-data
21073 (catch 'exit
21074 (let ((case-fold-search t)
21075 (lim-up (save-excursion (outline-previous-heading)))
21076 (lim-down (save-excursion (outline-next-heading))))
21077 (mapc (lambda (name)
21078 (let ((n (regexp-quote name)))
21079 (when (org-between-regexps-p
21080 (concat "^[ \t]*#\\+begin_" n)
21081 (concat "^[ \t]*#\\+end_" n)
21082 lim-up lim-down)
21083 (throw 'exit n))))
21084 names))
21085 nil)))
21087 (defun org-occur-in-agenda-files (regexp &optional nlines)
21088 "Call `multi-occur' with buffers for all agenda files."
21089 (interactive "sOrg-files matching: \np")
21090 (let* ((files (org-agenda-files))
21091 (tnames (mapcar 'file-truename files))
21092 (extra org-agenda-text-search-extra-files)
21094 (when (eq (car extra) 'agenda-archives)
21095 (setq extra (cdr extra))
21096 (setq files (org-add-archive-files files)))
21097 (while (setq f (pop extra))
21098 (unless (member (file-truename f) tnames)
21099 (add-to-list 'files f 'append)
21100 (add-to-list 'tnames (file-truename f) 'append)))
21101 (multi-occur
21102 (mapcar (lambda (x)
21103 (with-current-buffer
21104 (or (get-file-buffer x) (find-file-noselect x))
21105 (widen)
21106 (current-buffer)))
21107 files)
21108 regexp)))
21110 (if (boundp 'occur-mode-find-occurrence-hook)
21111 ;; Emacs 23
21112 (add-hook 'occur-mode-find-occurrence-hook
21113 (lambda ()
21114 (when (derived-mode-p 'org-mode)
21115 (org-reveal))))
21116 ;; Emacs 22
21117 (defadvice occur-mode-goto-occurrence
21118 (after org-occur-reveal activate)
21119 (and (derived-mode-p 'org-mode) (org-reveal)))
21120 (defadvice occur-mode-goto-occurrence-other-window
21121 (after org-occur-reveal activate)
21122 (and (derived-mode-p 'org-mode) (org-reveal)))
21123 (defadvice occur-mode-display-occurrence
21124 (after org-occur-reveal activate)
21125 (when (derived-mode-p 'org-mode)
21126 (let ((pos (occur-mode-find-occurrence)))
21127 (with-current-buffer (marker-buffer pos)
21128 (save-excursion
21129 (goto-char pos)
21130 (org-reveal)))))))
21132 (defun org-occur-link-in-agenda-files ()
21133 "Create a link and search for it in the agendas.
21134 The link is not stored in `org-stored-links', it is just created
21135 for the search purpose."
21136 (interactive)
21137 (let ((link (condition-case nil
21138 (org-store-link nil)
21139 (error "Unable to create a link to here"))))
21140 (org-occur-in-agenda-files (regexp-quote link))))
21142 (defun org-reverse-string (string)
21143 "Return the reverse of STRING."
21144 (apply 'string (reverse (string-to-list string))))
21146 (defun org-uniquify (list)
21147 "Remove duplicate elements from LIST."
21148 (let (res)
21149 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21150 res))
21152 (defun org-delete-all (elts list)
21153 "Remove all elements in ELTS from LIST."
21154 (while elts
21155 (setq list (delete (pop elts) list)))
21156 list)
21158 (defun org-count (cl-item cl-seq)
21159 "Count the number of occurrences of ITEM in SEQ.
21160 Taken from `count' in cl-seq.el with all keyword arguments removed."
21161 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21162 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21163 (while (< cl-start cl-end)
21164 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21165 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21166 (setq cl-start (1+ cl-start)))
21167 cl-count))
21169 (defun org-remove-if (predicate seq)
21170 "Remove everything from SEQ that fulfills PREDICATE."
21171 (let (res e)
21172 (while seq
21173 (setq e (pop seq))
21174 (if (not (funcall predicate e)) (push e res)))
21175 (nreverse res)))
21177 (defun org-remove-if-not (predicate seq)
21178 "Remove everything from SEQ that does not fulfill PREDICATE."
21179 (let (res e)
21180 (while seq
21181 (setq e (pop seq))
21182 (if (funcall predicate e) (push e res)))
21183 (nreverse res)))
21185 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21186 "Reduce two-argument FUNCTION across SEQ.
21187 Taken from `reduce' in cl-seq.el with all keyword arguments but
21188 \":initial-value\" removed."
21189 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21190 (cadr (memq :initial-value cl-keys)))
21191 (cl-seq (pop cl-seq))
21192 (t (funcall cl-func)))))
21193 (while cl-seq
21194 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21195 cl-accum))
21197 (defun org-back-over-empty-lines ()
21198 "Move backwards over whitespace, to the beginning of the first empty line.
21199 Returns the number of empty lines passed."
21200 (let ((pos (point)))
21201 (if (cdr (assoc 'heading org-blank-before-new-entry))
21202 (skip-chars-backward " \t\n\r")
21203 (unless (eobp)
21204 (forward-line -1)))
21205 (beginning-of-line 2)
21206 (goto-char (min (point) pos))
21207 (count-lines (point) pos)))
21209 (defun org-skip-whitespace ()
21210 (skip-chars-forward " \t\n\r"))
21212 (defun org-point-in-group (point group &optional context)
21213 "Check if POINT is in match-group GROUP.
21214 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21215 match. If the match group does not exist or point is not inside it,
21216 return nil."
21217 (and (match-beginning group)
21218 (>= point (match-beginning group))
21219 (<= point (match-end group))
21220 (if context
21221 (list context (match-beginning group) (match-end group))
21222 t)))
21224 (defun org-switch-to-buffer-other-window (&rest args)
21225 "Switch to buffer in a second window on the current frame.
21226 In particular, do not allow pop-up frames.
21227 Returns the newly created buffer."
21228 (org-no-popups
21229 (apply 'switch-to-buffer-other-window args)))
21231 (defun org-combine-plists (&rest plists)
21232 "Create a single property list from all plists in PLISTS.
21233 The process starts by copying the first list, and then setting properties
21234 from the other lists. Settings in the last list are the most significant
21235 ones and overrule settings in the other lists."
21236 (let ((rtn (copy-sequence (pop plists)))
21237 p v ls)
21238 (while plists
21239 (setq ls (pop plists))
21240 (while ls
21241 (setq p (pop ls) v (pop ls))
21242 (setq rtn (plist-put rtn p v))))
21243 rtn))
21245 (defun org-replace-escapes (string table)
21246 "Replace %-escapes in STRING with values in TABLE.
21247 TABLE is an association list with keys like \"%a\" and string values.
21248 The sequences in STRING may contain normal field width and padding information,
21249 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21250 so values can contain further %-escapes if they are define later in TABLE."
21251 (let ((tbl (copy-alist table))
21252 (case-fold-search nil)
21253 (pchg 0)
21254 e re rpl)
21255 (while (setq e (pop tbl))
21256 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21257 (when (and (cdr e) (string-match re (cdr e)))
21258 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21259 (safe "SREF"))
21260 (add-text-properties 0 3 (list 'sref sref) safe)
21261 (setcdr e (replace-match safe t t (cdr e)))))
21262 (while (string-match re string)
21263 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21264 (cdr e)))
21265 (setq string (replace-match rpl t t string))))
21266 (while (setq pchg (next-property-change pchg string))
21267 (let ((sref (get-text-property pchg 'sref string)))
21268 (when (and sref (string-match "SREF" string pchg))
21269 (setq string (replace-match sref t t string)))))
21270 string))
21272 (defun org-sublist (list start end)
21273 "Return a section of LIST, from START to END.
21274 Counting starts at 1."
21275 (let (rtn (c start))
21276 (setq list (nthcdr (1- start) list))
21277 (while (and list (<= c end))
21278 (push (pop list) rtn)
21279 (setq c (1+ c)))
21280 (nreverse rtn)))
21282 (defun org-find-base-buffer-visiting (file)
21283 "Like `find-buffer-visiting' but always return the base buffer and
21284 not an indirect buffer."
21285 (let ((buf (or (get-file-buffer file)
21286 (find-buffer-visiting file))))
21287 (if buf
21288 (or (buffer-base-buffer buf) buf)
21289 nil)))
21291 (defun org-image-file-name-regexp (&optional extensions)
21292 "Return regexp matching the file names of images.
21293 If EXTENSIONS is given, only match these."
21294 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21295 (image-file-name-regexp)
21296 (let ((image-file-name-extensions
21297 (or extensions
21298 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21299 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21300 (concat "\\."
21301 (regexp-opt (nconc (mapcar 'upcase
21302 image-file-name-extensions)
21303 image-file-name-extensions)
21305 "\\'"))))
21307 (defun org-file-image-p (file &optional extensions)
21308 "Return non-nil if FILE is an image."
21309 (save-match-data
21310 (string-match (org-image-file-name-regexp extensions) file)))
21312 (defun org-get-cursor-date (&optional with-time)
21313 "Return the date at cursor in as a time.
21314 This works in the calendar and in the agenda, anywhere else it just
21315 returns the current time.
21316 If WITH-TIME is non-nil, returns the time of the event at point (in
21317 the agenda) or the current time of the day."
21318 (let (date day defd tp tm hod mod)
21319 (when with-time
21320 (setq tp (get-text-property (point) 'time))
21321 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21322 (setq hod (string-to-number (match-string 1 tp))
21323 mod (string-to-number (match-string 2 tp))))
21324 (or tp (setq hod (nth 2 (decode-time (current-time)))
21325 mod (nth 1 (decode-time (current-time))))))
21326 (cond
21327 ((eq major-mode 'calendar-mode)
21328 (setq date (calendar-cursor-to-date)
21329 defd (encode-time 0 (or mod 0) (or hod 0)
21330 (nth 1 date) (nth 0 date) (nth 2 date))))
21331 ((eq major-mode 'org-agenda-mode)
21332 (setq day (get-text-property (point) 'day))
21333 (if day
21334 (setq date (calendar-gregorian-from-absolute day)
21335 defd (encode-time 0 (or mod 0) (or hod 0)
21336 (nth 1 date) (nth 0 date) (nth 2 date))))))
21337 (or defd (current-time))))
21339 (defun org-mark-subtree (&optional up)
21340 "Mark the current subtree.
21341 This puts point at the start of the current subtree, and mark at
21342 the end. If a numeric prefix UP is given, move up into the
21343 hierarchy of headlines by UP levels before marking the subtree."
21344 (interactive "P")
21345 (org-with-limited-levels
21346 (cond ((org-at-heading-p) (beginning-of-line))
21347 ((org-before-first-heading-p) (error "Not in a subtree"))
21348 (t (outline-previous-visible-heading 1))))
21349 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21350 (if (org-called-interactively-p 'any)
21351 (call-interactively 'org-mark-element)
21352 (org-mark-element)))
21355 ;;; Indentation
21357 (defun org-indent-line ()
21358 "Indent line depending on context."
21359 (interactive)
21360 (let* ((pos (point))
21361 (itemp (org-at-item-p))
21362 (case-fold-search t)
21363 (org-drawer-regexp (or org-drawer-regexp "\000"))
21364 (inline-task-p (and (featurep 'org-inlinetask)
21365 (org-inlinetask-in-task-p)))
21366 (inline-re (and inline-task-p
21367 (org-inlinetask-outline-regexp)))
21368 column)
21369 (if (and orgstruct-is-++ (eq pos (point)))
21370 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21371 (indent-according-to-mode))
21372 (beginning-of-line 1)
21373 (cond
21374 ;; Headings
21375 ((looking-at org-outline-regexp) (setq column 0))
21376 ;; Footnote definition
21377 ((looking-at org-footnote-definition-re) (setq column 0))
21378 ;; Literal examples
21379 ((looking-at "[ \t]*:\\( \\|$\\)")
21380 (setq column (org-get-indentation))) ; do nothing
21381 ;; Lists
21382 ((ignore-errors (goto-char (org-in-item-p)))
21383 (setq column (if itemp
21384 (org-get-indentation)
21385 (org-list-item-body-column (point))))
21386 (goto-char pos))
21387 ;; Drawers
21388 ((and (looking-at "[ \t]*:END:")
21389 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21390 (save-excursion
21391 (goto-char (1- (match-beginning 1)))
21392 (setq column (current-column))))
21393 ;; Special blocks
21394 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21395 (save-excursion
21396 (re-search-backward
21397 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21398 (setq column (org-get-indentation (match-string 0))))
21399 ((and (not (looking-at "[ \t]*#\\+begin_"))
21400 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21401 (save-excursion
21402 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21403 (setq column
21404 (cond ((equal (downcase (match-string 1)) "src")
21405 ;; src blocks: let `org-edit-src-exit' handle them
21406 (org-get-indentation))
21407 ((equal (downcase (match-string 1)) "example")
21408 (max (org-get-indentation)
21409 (org-get-indentation (match-string 0))))
21411 (org-get-indentation (match-string 0))))))
21412 ;; This line has nothing special, look at the previous relevant
21413 ;; line to compute indentation
21415 (beginning-of-line 0)
21416 (while (and (not (bobp))
21417 (not (looking-at org-table-line-regexp))
21418 (not (looking-at org-drawer-regexp))
21419 ;; When point started in an inline task, do not move
21420 ;; above task starting line.
21421 (not (and inline-task-p (looking-at inline-re)))
21422 ;; Skip drawers, blocks, empty lines, verbatim,
21423 ;; comments, tables, footnotes definitions, lists,
21424 ;; inline tasks.
21425 (or (and (looking-at "[ \t]*:END:")
21426 (re-search-backward org-drawer-regexp nil t))
21427 (and (looking-at "[ \t]*#\\+end_")
21428 (re-search-backward "[ \t]*#\\+begin_"nil t))
21429 (looking-at "[ \t]*[\n:#|]")
21430 (looking-at org-footnote-definition-re)
21431 (and (ignore-errors (goto-char (org-in-item-p)))
21432 (goto-char
21433 (org-list-get-top-point (org-list-struct))))
21434 (and (not inline-task-p)
21435 (featurep 'org-inlinetask)
21436 (org-inlinetask-in-task-p)
21437 (or (org-inlinetask-goto-beginning) t))))
21438 (beginning-of-line 0))
21439 (cond
21440 ;; There was an heading above.
21441 ((looking-at "\\*+[ \t]+")
21442 (if (not org-adapt-indentation)
21443 (setq column 0)
21444 (goto-char (match-end 0))
21445 (setq column (current-column))))
21446 ;; A drawer had started and is unfinished
21447 ((looking-at org-drawer-regexp)
21448 (goto-char (1- (match-beginning 1)))
21449 (setq column (current-column)))
21450 ;; Else, nothing noticeable found: get indentation and go on.
21451 (t (setq column (org-get-indentation))))))
21452 ;; Now apply indentation and move cursor accordingly
21453 (goto-char pos)
21454 (if (<= (current-column) (current-indentation))
21455 (org-indent-line-to column)
21456 (save-excursion (org-indent-line-to column)))
21457 ;; Special polishing for properties, see `org-property-format'
21458 (setq column (current-column))
21459 (beginning-of-line 1)
21460 (if (looking-at
21461 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21462 (replace-match (concat (match-string 1)
21463 (format org-property-format
21464 (match-string 2) (match-string 3)))
21465 t t))
21466 (org-move-to-column column))))
21468 (defun org-indent-drawer ()
21469 "Indent the drawer at point."
21470 (interactive)
21471 (let ((p (point))
21472 (e (and (save-excursion (re-search-forward ":END:" nil t))
21473 (match-end 0)))
21474 (folded
21475 (save-excursion
21476 (end-of-line)
21477 (when (overlays-at (point))
21478 (member 'invisible (overlay-properties
21479 (car (overlays-at (point)))))))))
21480 (when folded (org-cycle))
21481 (indent-for-tab-command)
21482 (while (and (move-beginning-of-line 2) (< (point) e))
21483 (indent-for-tab-command))
21484 (goto-char p)
21485 (when folded (org-cycle)))
21486 (message "Drawer at point indented"))
21488 (defun org-indent-block ()
21489 "Indent the block at point."
21490 (interactive)
21491 (let ((p (point))
21492 (case-fold-search t)
21493 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21494 (match-end 0)))
21495 (folded
21496 (save-excursion
21497 (end-of-line)
21498 (when (overlays-at (point))
21499 (member 'invisible (overlay-properties
21500 (car (overlays-at (point)))))))))
21501 (when folded (org-cycle))
21502 (indent-for-tab-command)
21503 (while (and (move-beginning-of-line 2) (< (point) e))
21504 (indent-for-tab-command))
21505 (goto-char p)
21506 (when folded (org-cycle)))
21507 (message "Block at point indented"))
21509 (defun org-indent-region (start end)
21510 "Indent region."
21511 (interactive "r")
21512 (save-excursion
21513 (let ((line-end (org-current-line end)))
21514 (goto-char start)
21515 (while (< (org-current-line) line-end)
21516 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21517 (t (call-interactively 'org-indent-line)))
21518 (move-beginning-of-line 2)))))
21521 ;;; Filling
21523 ;; We use our own fill-paragraph and auto-fill functions.
21525 ;; `org-fill-paragraph' relies on adaptive filling and context
21526 ;; checking. Appropriate `fill-prefix' is computed with
21527 ;; `org-adaptive-fill-function'.
21529 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21530 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21531 ;; `org-adaptive-fill-function' value. Internally,
21532 ;; `org-comment-line-break-function' breaks the line.
21534 ;; `org-setup-filling' installs filling and auto-filling related
21535 ;; variables during `org-mode' initialization.
21537 (defun org-setup-filling ()
21538 (interactive)
21539 ;; Prevent auto-fill from inserting unwanted new items.
21540 (when (boundp 'fill-nobreak-predicate)
21541 (org-set-local
21542 'fill-nobreak-predicate
21543 (org-uniquify
21544 (append fill-nobreak-predicate
21545 '(org-fill-paragraph-separate-nobreak-p
21546 org-fill-line-break-nobreak-p
21547 org-fill-paragraph-with-timestamp-nobreak-p)))))
21548 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21549 (org-set-local 'auto-fill-inhibit-regexp nil)
21550 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21551 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21552 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21554 (defvar org-element-paragraph-separate) ; org-element.el
21555 (defun org-fill-paragraph-separate-nobreak-p ()
21556 "Non-nil when a line break at point would insert a new item."
21557 (looking-at (substring org-element-paragraph-separate 1)))
21559 (defun org-fill-line-break-nobreak-p ()
21560 "Non-nil when a line break at point would create an Org line break."
21561 (save-excursion
21562 (skip-chars-backward "[ \t]")
21563 (skip-chars-backward "\\\\")
21564 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21566 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21567 "Non-nil when a line break at point would insert a new item."
21568 (and (org-at-timestamp-p t)
21569 (not (looking-at org-ts-regexp-both))))
21571 (declare-function message-in-body-p "message" ())
21572 (defvar orgtbl-line-start-regexp) ; From org-table.el
21573 (defun org-adaptive-fill-function ()
21574 "Compute a fill prefix for the current line.
21575 Return fill prefix, as a string, or nil if current line isn't
21576 meant to be filled."
21577 (let (prefix)
21578 (catch 'exit
21579 (when (derived-mode-p 'message-mode)
21580 (save-excursion
21581 (beginning-of-line)
21582 (cond ((or (not (message-in-body-p))
21583 (looking-at orgtbl-line-start-regexp))
21584 (throw 'exit nil))
21585 ((looking-at message-cite-prefix-regexp)
21586 (throw 'exit (match-string-no-properties 0)))
21587 ((looking-at org-outline-regexp)
21588 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21589 (org-with-wide-buffer
21590 (let* ((p (line-beginning-position))
21591 (element (save-excursion (beginning-of-line)
21592 (org-element-at-point)))
21593 (type (org-element-type element))
21594 (post-affiliated (org-element-property :post-affiliated element)))
21595 (unless (and post-affiliated (< p post-affiliated))
21596 (case type
21597 (comment (looking-at "[ \t]*# ?") (match-string 0))
21598 (footnote-definition "")
21599 ((item plain-list)
21600 (make-string (org-list-item-body-column
21601 (or post-affiliated
21602 (org-element-property :begin element)))
21603 ? ))
21604 (paragraph
21605 ;; Fill prefix is usually the same as the current line,
21606 ;; except if the paragraph is at the beginning of an item.
21607 (let ((parent (org-element-property :parent element)))
21608 (cond ((eq (org-element-type parent) 'item)
21609 (make-string (org-list-item-body-column
21610 (org-element-property :begin parent))
21611 ? ))
21612 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21613 (match-string 0))
21614 (t ""))))
21615 (comment-block
21616 ;; Only fill contents if P is within block boundaries.
21617 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21618 (forward-line)
21619 (point)))
21620 (cend (save-excursion
21621 (goto-char (org-element-property :end element))
21622 (skip-chars-backward " \r\t\n")
21623 (line-beginning-position))))
21624 (when (and (>= p cbeg) (< p cend))
21625 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21626 (match-string 0)
21627 "")))))))))))
21629 (declare-function message-goto-body "message" ())
21630 (defvar message-cite-prefix-regexp) ; From message.el
21631 (defvar org-element-all-objects) ; From org-element.el
21632 (defun org-fill-paragraph (&optional justify)
21633 "Fill element at point, when applicable.
21635 This function only applies to comment blocks, comments, example
21636 blocks and paragraphs. Also, as a special case, re-align table
21637 when point is at one.
21639 If JUSTIFY is non-nil (interactively, with prefix argument),
21640 justify as well. If `sentence-end-double-space' is non-nil, then
21641 period followed by one space does not end a sentence, so don't
21642 break a line there. The variable `fill-column' controls the
21643 width for filling.
21645 For convenience, when point is at a plain list, an item or
21646 a footnote definition, try to fill the first paragraph within."
21647 (interactive)
21648 (if (and (derived-mode-p 'message-mode)
21649 (or (not (message-in-body-p))
21650 (save-excursion (move-beginning-of-line 1)
21651 (looking-at message-cite-prefix-regexp))))
21652 ;; First ensure filling is correct in message-mode.
21653 (let ((fill-paragraph-function
21654 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21655 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21656 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21657 (paragraph-separate
21658 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21659 (fill-paragraph nil))
21660 (save-excursion
21661 ;; Move to end of line in order to get the first paragraph
21662 ;; within a plain list or a footnote definition.
21663 (end-of-line)
21664 (let ((element (org-element-at-point)))
21665 ;; First check if point is in a blank line at the beginning of
21666 ;; the buffer. In that case, ignore filling.
21667 (if (< (point) (org-element-property :begin element)) t
21668 (case (org-element-type element)
21669 ;; Use major mode filling function is src blocks.
21670 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21671 ;; Align Org tables, leave table.el tables as-is.
21672 (table-row (org-table-align) t)
21673 (table
21674 (when (eq (org-element-property :type element) 'org)
21675 (org-table-align))
21677 (paragraph
21678 ;; Paragraphs may contain `line-break' type objects.
21679 (let ((beg (max (point-min)
21680 (org-element-property :contents-begin element)))
21681 (end (min (point-max)
21682 (org-element-property :contents-end element))))
21683 ;; Do nothing if point is at an affiliated keyword.
21684 (if (< (point) beg) t
21685 (when (derived-mode-p 'message-mode)
21686 ;; In `message-mode', do not fill following
21687 ;; citation in current paragraph nor text before
21688 ;; message body.
21689 (let ((body-start (save-excursion (message-goto-body))))
21690 (when body-start (setq beg (max body-start beg))))
21691 (when (save-excursion
21692 (re-search-forward
21693 (concat "^" message-cite-prefix-regexp) end t))
21694 (setq end (match-beginning 0))))
21695 ;; Fill paragraph, taking line breaks into
21696 ;; consideration. For that, slice the paragraph
21697 ;; using line breaks as separators, and fill the
21698 ;; parts in reverse order to avoid messing with
21699 ;; markers.
21700 (save-excursion
21701 (goto-char end)
21702 (mapc
21703 (lambda (pos)
21704 (fill-region-as-paragraph pos (point) justify)
21705 (goto-char pos))
21706 ;; Find the list of ending positions for line
21707 ;; breaks in the current paragraph. Add paragraph
21708 ;; beginning to include first slice.
21709 (nreverse
21710 (cons
21712 (org-element-map
21713 (org-element--parse-objects
21714 beg end nil org-element-all-objects)
21715 'line-break
21716 (lambda (lb) (org-element-property :end lb)))))))
21717 t)))
21718 ;; Contents of `comment-block' type elements should be
21719 ;; filled as plain text, but only if point is within block
21720 ;; markers.
21721 (comment-block
21722 (let* ((case-fold-search t)
21723 (beg (save-excursion
21724 (goto-char (org-element-property :begin element))
21725 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21726 (forward-line)
21727 (point)))
21728 (end (save-excursion
21729 (goto-char (org-element-property :end element))
21730 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21731 (line-beginning-position))))
21732 (when (and (>= (point) beg) (< (point) end))
21733 (fill-region-as-paragraph
21734 (save-excursion
21735 (end-of-line)
21736 (re-search-backward "^[ \t]*$" beg 'move)
21737 (line-beginning-position))
21738 (save-excursion
21739 (beginning-of-line)
21740 (re-search-forward "^[ \t]*$" end 'move)
21741 (line-beginning-position))
21742 justify)))
21744 ;; Fill comments.
21745 (comment (fill-comment-paragraph justify))
21746 ;; Ignore every other element.
21747 (otherwise t)))))))
21749 (defun org-auto-fill-function ()
21750 "Auto-fill function."
21751 ;; Check if auto-filling is meaningful.
21752 (let ((fc (current-fill-column)))
21753 (when (and fc (> (current-column) fc))
21754 (let* ((fill-prefix (org-adaptive-fill-function))
21755 ;; Enforce empty fill prefix, if required. Otherwise, it
21756 ;; will be computed again.
21757 (adaptive-fill-mode (not (equal fill-prefix ""))))
21758 (when fill-prefix (do-auto-fill))))))
21760 (defun org-comment-line-break-function (&optional soft)
21761 "Break line at point and indent, continuing comment if within one.
21762 The inserted newline is marked hard if variable
21763 `use-hard-newlines' is true, unless optional argument SOFT is
21764 non-nil."
21765 (if soft (insert-and-inherit ?\n) (newline 1))
21766 (save-excursion (forward-char -1) (delete-horizontal-space))
21767 (delete-horizontal-space)
21768 (indent-to-left-margin)
21769 (insert-before-markers-and-inherit fill-prefix))
21772 ;;; Comments
21774 ;; Org comments syntax is quite complex. It requires the entire line
21775 ;; to be just a comment. Also, even with the right syntax at the
21776 ;; beginning of line, some some elements (i.e. verse-block or
21777 ;; example-block) don't accept comments. Usual Emacs comment commands
21778 ;; cannot cope with those requirements. Therefore, Org replaces them.
21780 ;; Org still relies on `comment-dwim', but cannot trust
21781 ;; `comment-only-p'. So, `comment-region-function' and
21782 ;; `uncomment-region-function' both point
21783 ;; to`org-comment-or-uncomment-region'. Eventually,
21784 ;; `org-insert-comment' takes care of insertion of comments at the
21785 ;; beginning of line.
21787 ;; `org-setup-comments-handling' install comments related variables
21788 ;; during `org-mode' initialization.
21790 (defun org-setup-comments-handling ()
21791 (interactive)
21792 (org-set-local 'comment-use-syntax nil)
21793 (org-set-local 'comment-start "# ")
21794 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21795 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21796 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21797 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21799 (defun org-insert-comment ()
21800 "Insert an empty comment above current line.
21801 If the line is empty, insert comment at its beginning."
21802 (beginning-of-line)
21803 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21804 (org-indent-line)
21805 (insert "# "))
21807 (defvar comment-empty-lines) ; From newcomment.el.
21808 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21809 "Comment or uncomment each non-blank line in the region.
21810 Uncomment each non-blank line between BEG and END if it only
21811 contains commented lines. Otherwise, comment them."
21812 (save-restriction
21813 ;; Restrict region
21814 (narrow-to-region (save-excursion (goto-char beg)
21815 (skip-chars-forward " \r\t\n" end)
21816 (line-beginning-position))
21817 (save-excursion (goto-char end)
21818 (skip-chars-backward " \r\t\n" beg)
21819 (line-end-position)))
21820 (let ((uncommentp
21821 ;; UNCOMMENTP is non-nil when every non blank line between
21822 ;; BEG and END is a comment.
21823 (save-excursion
21824 (goto-char (point-min))
21825 (while (and (not (eobp))
21826 (let ((element (org-element-at-point)))
21827 (and (eq (org-element-type element) 'comment)
21828 (goto-char (min (point-max)
21829 (org-element-property
21830 :end element)))))))
21831 (eobp))))
21832 (if uncommentp
21833 ;; Only blank lines and comments in region: uncomment it.
21834 (save-excursion
21835 (goto-char (point-min))
21836 (while (not (eobp))
21837 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21838 (replace-match "" nil nil nil 1))
21839 (forward-line)))
21840 ;; Comment each line in region.
21841 (let ((min-indent (point-max)))
21842 ;; First find the minimum indentation across all lines.
21843 (save-excursion
21844 (goto-char (point-min))
21845 (while (and (not (eobp)) (not (zerop min-indent)))
21846 (unless (looking-at "[ \t]*$")
21847 (setq min-indent (min min-indent (current-indentation))))
21848 (forward-line)))
21849 ;; Then loop over all lines.
21850 (save-excursion
21851 (goto-char (point-min))
21852 (while (not (eobp))
21853 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21854 (org-move-to-column min-indent t)
21855 (insert comment-start))
21856 (forward-line))))))))
21859 ;;; Planning
21861 ;; This section contains tools to operate on timestamp objects, as
21862 ;; returned by, e.g. `org-element-context'.
21864 (defun org-timestamp-has-time-p (timestamp)
21865 "Non-nil when TIMESTAMP has a time specified."
21866 (org-element-property :hour-start timestamp))
21868 (defun org-timestamp-format (timestamp format &optional end utc)
21869 "Format a TIMESTAMP element into a string.
21871 FORMAT is a format specifier to be passed to
21872 `format-time-string'.
21874 When optional argument END is non-nil, use end of date-range or
21875 time-range, if possible.
21877 When optional argument UTC is non-nil, time will be expressed as
21878 Universal Time."
21879 (format-time-string
21880 format
21881 (apply 'encode-time
21882 (cons 0
21883 (mapcar
21884 (lambda (prop) (or (org-element-property prop timestamp) 0))
21885 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21886 '(:minute-start :hour-start :day-start :month-start
21887 :year-start)))))
21888 utc))
21890 (defun org-timestamp-split-range (timestamp &optional end)
21891 "Extract a timestamp object from a date or time range.
21893 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21894 the end of the range. Otherwise, extract its start.
21896 Return a new timestamp object sharing the same parent as
21897 TIMESTAMP."
21898 (let ((type (org-element-property :type timestamp)))
21899 (if (memq type '(active inactive diary)) timestamp
21900 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21901 ;; Set new type.
21902 (org-element-put-property
21903 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21904 ;; Copy start properties over end properties if END is
21905 ;; non-nil. Otherwise, copy end properties over `start' ones.
21906 (let ((p-alist '((:minute-start . :minute-end)
21907 (:hour-start . :hour-end)
21908 (:day-start . :day-end)
21909 (:month-start . :month-end)
21910 (:year-start . :year-end))))
21911 (dolist (p-cell p-alist)
21912 (org-element-put-property
21913 split-ts
21914 (funcall (if end 'car 'cdr) p-cell)
21915 (org-element-property
21916 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21917 ;; Eventually refresh `:raw-value'.
21918 (org-element-put-property split-ts :raw-value nil)
21919 (org-element-put-property
21920 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21922 (defun org-timestamp-translate (timestamp &optional boundary)
21923 "Apply `org-translate-time' on a TIMESTAMP object.
21924 When optional argument BOUNDARY is non-nil, it is either the
21925 symbol `start' or `end'. In this case, only translate the
21926 starting or ending part of TIMESTAMP if it is a date or time
21927 range. Otherwise, translate both parts."
21928 (if (and (not boundary)
21929 (memq (org-element-property :type timestamp)
21930 '(active-range inactive-range)))
21931 (concat
21932 (org-translate-time
21933 (org-element-property :raw-value
21934 (org-timestamp-split-range timestamp)))
21935 "--"
21936 (org-translate-time
21937 (org-element-property :raw-value
21938 (org-timestamp-split-range timestamp t))))
21939 (org-translate-time
21940 (org-element-property
21941 :raw-value
21942 (if (not boundary) timestamp
21943 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
21947 ;;; Other stuff.
21949 (defun org-toggle-fixed-width-section (arg)
21950 "Toggle the fixed-width export.
21951 If there is no active region, the QUOTE keyword at the current headline is
21952 inserted or removed. When present, it causes the text between this headline
21953 and the next to be exported as fixed-width text, and unmodified.
21954 If there is an active region, this command adds or removes a colon as the
21955 first character of this line. If the first character of a line is a colon,
21956 this line is also exported in fixed-width font."
21957 (interactive "P")
21958 (let* ((cc 0)
21959 (regionp (org-region-active-p))
21960 (beg (if regionp (region-beginning) (point)))
21961 (end (if regionp (region-end)))
21962 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21963 (case-fold-search nil)
21964 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21965 off)
21966 (if regionp
21967 (save-excursion
21968 (goto-char beg)
21969 (setq cc (current-column))
21970 (beginning-of-line 1)
21971 (setq off (looking-at re))
21972 (while (> nlines 0)
21973 (setq nlines (1- nlines))
21974 (beginning-of-line 1)
21975 (cond
21976 (arg
21977 (org-move-to-column cc t)
21978 (insert ": \n")
21979 (forward-line -1))
21980 ((and off (looking-at re))
21981 (replace-match "" t t nil 1))
21982 ((not off) (org-move-to-column cc t) (insert ": ")))
21983 (forward-line 1)))
21984 (save-excursion
21985 (org-back-to-heading)
21986 (cond
21987 ((looking-at (format org-heading-keyword-regexp-format
21988 org-quote-string))
21989 (goto-char (match-end 1))
21990 (looking-at (concat " +" org-quote-string))
21991 (replace-match "" t t)
21992 (when (eolp) (insert " ")))
21993 ((looking-at org-outline-regexp)
21994 (goto-char (match-end 0))
21995 (insert org-quote-string " ")))))))
21997 (defun org-reftex-citation ()
21998 "Use reftex-citation to insert a citation into the buffer.
21999 This looks for a line like
22001 #+BIBLIOGRAPHY: foo plain option:-d
22003 and derives from it that foo.bib is the bibliography file relevant
22004 for this document. It then installs the necessary environment for RefTeX
22005 to work in this buffer and calls `reftex-citation' to insert a citation
22006 into the buffer.
22008 Export of such citations to both LaTeX and HTML is handled by the contributed
22009 package org-exp-bibtex by Taru Karttunen."
22010 (interactive)
22011 (let ((reftex-docstruct-symbol 'rds)
22012 (reftex-cite-format "\\cite{%l}")
22013 rds bib)
22014 (save-excursion
22015 (save-restriction
22016 (widen)
22017 (let ((case-fold-search t)
22018 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22019 (if (not (save-excursion
22020 (or (re-search-forward re nil t)
22021 (re-search-backward re nil t))))
22022 (error "No bibliography defined in file")
22023 (setq bib (concat (match-string 1) ".bib")
22024 rds (list (list 'bib bib)))))))
22025 (call-interactively 'reftex-citation)))
22027 ;;;; Functions extending outline functionality
22029 (defun org-beginning-of-line (&optional arg)
22030 "Go to the beginning of the current line. If that is invisible, continue
22031 to a visible line beginning. This makes the function of C-a more intuitive.
22032 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22033 first attempt, and only move to after the tags when the cursor is already
22034 beyond the end of the headline."
22035 (interactive "P")
22036 (let ((pos (point))
22037 (special (if (consp org-special-ctrl-a/e)
22038 (car org-special-ctrl-a/e)
22039 org-special-ctrl-a/e))
22040 refpos)
22041 (if (org-bound-and-true-p visual-line-mode)
22042 (beginning-of-visual-line 1)
22043 (beginning-of-line 1))
22044 (if (and arg (fboundp 'move-beginning-of-line))
22045 (call-interactively 'move-beginning-of-line)
22046 (if (bobp)
22048 (backward-char 1)
22049 (if (org-truely-invisible-p)
22050 (while (and (not (bobp)) (org-truely-invisible-p))
22051 (backward-char 1)
22052 (beginning-of-line 1))
22053 (forward-char 1))))
22054 (when special
22055 (cond
22056 ((and (looking-at org-complex-heading-regexp)
22057 (= (char-after (match-end 1)) ?\ ))
22058 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22059 (point-at-eol)))
22060 (goto-char
22061 (if (eq special t)
22062 (cond ((> pos refpos) refpos)
22063 ((= pos (point)) refpos)
22064 (t (point)))
22065 (cond ((> pos (point)) (point))
22066 ((not (eq last-command this-command)) (point))
22067 (t refpos)))))
22068 ((org-at-item-p)
22069 ;; Being at an item and not looking at an the item means point
22070 ;; was previously moved to beginning of a visual line, which
22071 ;; doesn't contain the item. Therefore, do nothing special,
22072 ;; just stay here.
22073 (when (looking-at org-list-full-item-re)
22074 ;; Set special position at first white space character after
22075 ;; bullet, and check-box, if any.
22076 (let ((after-bullet
22077 (let ((box (match-end 3)))
22078 (if (not box) (match-end 1)
22079 (let ((after (char-after box)))
22080 (if (and after (= after ? )) (1+ box) box))))))
22081 ;; Special case: Move point to special position when
22082 ;; currently after it or at beginning of line.
22083 (if (eq special t)
22084 (when (or (> pos after-bullet) (= (point) pos))
22085 (goto-char after-bullet))
22086 ;; Reversed case: Move point to special position when
22087 ;; point was already at beginning of line and command is
22088 ;; repeated.
22089 (when (and (= (point) pos) (eq last-command this-command))
22090 (goto-char after-bullet))))))))
22091 (org-no-warnings
22092 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22094 (defun org-end-of-line (&optional arg)
22095 "Go to the end of the line.
22096 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22097 tags on the first attempt, and only move to after the tags when
22098 the cursor is already beyond the end of the headline."
22099 (interactive "P")
22100 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22101 org-special-ctrl-a/e))
22102 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22103 'end-of-visual-line)
22104 ((fboundp 'move-end-of-line) 'move-end-of-line)
22105 (t 'end-of-line))))
22106 (if (or (not special) arg) (call-interactively move-fun)
22107 (let* ((element (save-excursion (beginning-of-line)
22108 (org-element-at-point)))
22109 (type (org-element-type element)))
22110 (cond
22111 ((memq type '(headline inlinetask))
22112 (let ((pos (point)))
22113 (beginning-of-line 1)
22114 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22115 (if (eq special t)
22116 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22117 (goto-char (match-beginning 1))
22118 (goto-char (match-end 0)))
22119 (if (or (< pos (match-end 0))
22120 (not (eq this-command last-command)))
22121 (goto-char (match-end 0))
22122 (goto-char (match-beginning 1))))
22123 (call-interactively move-fun))))
22124 ((org-element-property :hiddenp element)
22125 ;; If element is hidden, `move-end-of-line' would put point
22126 ;; after it. Use `end-of-line' to stay on current line.
22127 (call-interactively 'end-of-line))
22128 (t (call-interactively move-fun)))))
22129 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22131 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22132 (define-key org-mode-map "\C-e" 'org-end-of-line)
22134 (defun org-backward-sentence (&optional arg)
22135 "Go to beginning of sentence, or beginning of table field.
22136 This will call `backward-sentence' or `org-table-beginning-of-field',
22137 depending on context."
22138 (interactive "P")
22139 (cond
22140 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22141 (t (call-interactively 'backward-sentence))))
22143 (defun org-forward-sentence (&optional arg)
22144 "Go to end of sentence, or end of table field.
22145 This will call `forward-sentence' or `org-table-end-of-field',
22146 depending on context."
22147 (interactive "P")
22148 (cond
22149 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22150 (t (call-interactively 'forward-sentence))))
22152 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22153 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22155 (defun org-kill-line (&optional arg)
22156 "Kill line, to tags or end of line."
22157 (interactive "P")
22158 (cond
22159 ((or (not org-special-ctrl-k)
22160 (bolp)
22161 (not (org-at-heading-p)))
22162 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22163 org-ctrl-k-protect-subtree)
22164 (if (or (eq org-ctrl-k-protect-subtree 'error)
22165 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22166 (error "C-k aborted - would kill hidden subtree")))
22167 (call-interactively
22168 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22169 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22170 (kill-region (point) (match-beginning 1))
22171 (org-set-tags nil t))
22172 (t (kill-region (point) (point-at-eol)))))
22174 (define-key org-mode-map "\C-k" 'org-kill-line)
22176 (defun org-yank (&optional arg)
22177 "Yank. If the kill is a subtree, treat it specially.
22178 This command will look at the current kill and check if is a single
22179 subtree, or a series of subtrees[1]. If it passes the test, and if the
22180 cursor is at the beginning of a line or after the stars of a currently
22181 empty headline, then the yank is handled specially. How exactly depends
22182 on the value of the following variables, both set by default.
22184 org-yank-folded-subtrees
22185 When set, the subtree(s) will be folded after insertion, but only
22186 if doing so would now swallow text after the yanked text.
22188 org-yank-adjusted-subtrees
22189 When set, the subtree will be promoted or demoted in order to
22190 fit into the local outline tree structure, which means that the level
22191 will be adjusted so that it becomes the smaller one of the two
22192 *visible* surrounding headings.
22194 Any prefix to this command will cause `yank' to be called directly with
22195 no special treatment. In particular, a simple \\[universal-argument] prefix \
22196 will just
22197 plainly yank the text as it is.
22199 \[1] The test checks if the first non-white line is a heading
22200 and if there are no other headings with fewer stars."
22201 (interactive "P")
22202 (org-yank-generic 'yank arg))
22204 (defun org-yank-generic (command arg)
22205 "Perform some yank-like command.
22207 This function implements the behavior described in the `org-yank'
22208 documentation. However, it has been generalized to work for any
22209 interactive command with similar behavior."
22211 ;; pretend to be command COMMAND
22212 (setq this-command command)
22214 (if arg
22215 (call-interactively command)
22217 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22218 (and (org-kill-is-subtree-p)
22219 (or (bolp)
22220 (and (looking-at "[ \t]*$")
22221 (string-match
22222 "\\`\\*+\\'"
22223 (buffer-substring (point-at-bol) (point)))))))
22224 swallowp)
22225 (cond
22226 ((and subtreep org-yank-folded-subtrees)
22227 (let ((beg (point))
22228 end)
22229 (if (and subtreep org-yank-adjusted-subtrees)
22230 (org-paste-subtree nil nil 'for-yank)
22231 (call-interactively command))
22233 (setq end (point))
22234 (goto-char beg)
22235 (when (and (bolp) subtreep
22236 (not (setq swallowp
22237 (org-yank-folding-would-swallow-text beg end))))
22238 (org-with-limited-levels
22239 (or (looking-at org-outline-regexp)
22240 (re-search-forward org-outline-regexp-bol end t))
22241 (while (and (< (point) end) (looking-at org-outline-regexp))
22242 (hide-subtree)
22243 (org-cycle-show-empty-lines 'folded)
22244 (condition-case nil
22245 (outline-forward-same-level 1)
22246 (error (goto-char end))))))
22247 (when swallowp
22248 (message
22249 "Inserted text not folded because that would swallow text"))
22251 (goto-char end)
22252 (skip-chars-forward " \t\n\r")
22253 (beginning-of-line 1)
22254 (push-mark beg 'nomsg)))
22255 ((and subtreep org-yank-adjusted-subtrees)
22256 (let ((beg (point-at-bol)))
22257 (org-paste-subtree nil nil 'for-yank)
22258 (push-mark beg 'nomsg)))
22260 (call-interactively command))))))
22262 (defun org-yank-folding-would-swallow-text (beg end)
22263 "Would hide-subtree at BEG swallow any text after END?"
22264 (let (level)
22265 (org-with-limited-levels
22266 (save-excursion
22267 (goto-char beg)
22268 (when (or (looking-at org-outline-regexp)
22269 (re-search-forward org-outline-regexp-bol end t))
22270 (setq level (org-outline-level)))
22271 (goto-char end)
22272 (skip-chars-forward " \t\r\n\v\f")
22273 (if (or (eobp)
22274 (and (bolp) (looking-at org-outline-regexp)
22275 (<= (org-outline-level) level)))
22276 nil ; Nothing would be swallowed
22277 t))))) ; something would swallow
22279 (define-key org-mode-map "\C-y" 'org-yank)
22281 (defun org-truely-invisible-p ()
22282 "Check if point is at a character currently not visible.
22283 This version does not only check the character property, but also
22284 `visible-mode'."
22285 ;; Early versions of noutline don't have `outline-invisible-p'.
22286 (if (org-bound-and-true-p visible-mode)
22288 (outline-invisible-p)))
22290 (defun org-invisible-p2 ()
22291 "Check if point is at a character currently not visible."
22292 (save-excursion
22293 (if (and (eolp) (not (bobp))) (backward-char 1))
22294 ;; Early versions of noutline don't have `outline-invisible-p'.
22295 (outline-invisible-p)))
22297 (defun org-back-to-heading (&optional invisible-ok)
22298 "Call `outline-back-to-heading', but provide a better error message."
22299 (condition-case nil
22300 (outline-back-to-heading invisible-ok)
22301 (error (error "Before first headline at position %d in buffer %s"
22302 (point) (current-buffer)))))
22304 (defun org-before-first-heading-p ()
22305 "Before first heading?"
22306 (save-excursion
22307 (end-of-line)
22308 (null (re-search-backward org-outline-regexp-bol nil t))))
22310 (defun org-at-heading-p (&optional ignored)
22311 (outline-on-heading-p t))
22312 ;; Compatibility alias with Org versions < 7.8.03
22313 (defalias 'org-on-heading-p 'org-at-heading-p)
22315 (defun org-at-comment-p nil
22316 "Is cursor in a line starting with a # character?"
22317 (save-excursion
22318 (beginning-of-line)
22319 (looking-at "^#")))
22321 (defun org-at-drawer-p nil
22322 "Is cursor at a drawer keyword?"
22323 (save-excursion
22324 (move-beginning-of-line 1)
22325 (looking-at org-drawer-regexp)))
22327 (defun org-at-block-p nil
22328 "Is cursor at a block keyword?"
22329 (save-excursion
22330 (move-beginning-of-line 1)
22331 (looking-at org-block-regexp)))
22333 (defun org-point-at-end-of-empty-headline ()
22334 "If point is at the end of an empty headline, return t, else nil.
22335 If the heading only contains a TODO keyword, it is still still considered
22336 empty."
22337 (and (looking-at "[ \t]*$")
22338 (when org-todo-line-regexp
22339 (save-excursion
22340 (beginning-of-line 1)
22341 (let ((case-fold-search nil))
22342 (looking-at org-todo-line-regexp)
22343 (string= (match-string 3) ""))))))
22345 (defun org-at-heading-or-item-p ()
22346 (or (org-at-heading-p) (org-at-item-p)))
22348 (defun org-at-target-p ()
22349 (or (org-in-regexp org-radio-target-regexp)
22350 (org-in-regexp org-target-regexp)))
22351 ;; Compatibility alias with Org versions < 7.8.03
22352 (defalias 'org-on-target-p 'org-at-target-p)
22354 (defun org-up-heading-all (arg)
22355 "Move to the heading line of which the present line is a subheading.
22356 This function considers both visible and invisible heading lines.
22357 With argument, move up ARG levels."
22358 (if (fboundp 'outline-up-heading-all)
22359 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22360 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22362 (defun org-up-heading-safe ()
22363 "Move to the heading line of which the present line is a subheading.
22364 This version will not throw an error. It will return the level of the
22365 headline found, or nil if no higher level is found.
22367 Also, this function will be a lot faster than `outline-up-heading',
22368 because it relies on stars being the outline starters. This can really
22369 make a significant difference in outlines with very many siblings."
22370 (let (start-level re)
22371 (org-back-to-heading t)
22372 (setq start-level (funcall outline-level))
22373 (if (equal start-level 1)
22375 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22376 (if (re-search-backward re nil t)
22377 (funcall outline-level)))))
22379 (defun org-first-sibling-p ()
22380 "Is this heading the first child of its parents?"
22381 (interactive)
22382 (let ((re org-outline-regexp-bol)
22383 level l)
22384 (unless (org-at-heading-p t)
22385 (error "Not at a heading"))
22386 (setq level (funcall outline-level))
22387 (save-excursion
22388 (if (not (re-search-backward re nil t))
22390 (setq l (funcall outline-level))
22391 (< l level)))))
22393 (defun org-goto-sibling (&optional previous)
22394 "Goto the next sibling, even if it is invisible.
22395 When PREVIOUS is set, go to the previous sibling instead. Returns t
22396 when a sibling was found. When none is found, return nil and don't
22397 move point."
22398 (let ((fun (if previous 're-search-backward 're-search-forward))
22399 (pos (point))
22400 (re org-outline-regexp-bol)
22401 level l)
22402 (when (condition-case nil (org-back-to-heading t) (error nil))
22403 (setq level (funcall outline-level))
22404 (catch 'exit
22405 (or previous (forward-char 1))
22406 (while (funcall fun re nil t)
22407 (setq l (funcall outline-level))
22408 (when (< l level) (goto-char pos) (throw 'exit nil))
22409 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22410 (goto-char pos)
22411 nil))))
22413 (defun org-show-siblings ()
22414 "Show all siblings of the current headline."
22415 (save-excursion
22416 (while (org-goto-sibling) (org-flag-heading nil)))
22417 (save-excursion
22418 (while (org-goto-sibling 'previous)
22419 (org-flag-heading nil))))
22421 (defun org-goto-first-child ()
22422 "Goto the first child, even if it is invisible.
22423 Return t when a child was found. Otherwise don't move point and
22424 return nil."
22425 (let (level (pos (point)) (re org-outline-regexp-bol))
22426 (when (condition-case nil (org-back-to-heading t) (error nil))
22427 (setq level (outline-level))
22428 (forward-char 1)
22429 (if (and (re-search-forward re nil t) (> (outline-level) level))
22430 (progn (goto-char (match-beginning 0)) t)
22431 (goto-char pos) nil))))
22433 (defun org-show-hidden-entry ()
22434 "Show an entry where even the heading is hidden."
22435 (save-excursion
22436 (org-show-entry)))
22438 (defun org-flag-heading (flag &optional entry)
22439 "Flag the current heading. FLAG non-nil means make invisible.
22440 When ENTRY is non-nil, show the entire entry."
22441 (save-excursion
22442 (org-back-to-heading t)
22443 ;; Check if we should show the entire entry
22444 (if entry
22445 (progn
22446 (org-show-entry)
22447 (save-excursion
22448 (and (outline-next-heading)
22449 (org-flag-heading nil))))
22450 (outline-flag-region (max (point-min) (1- (point)))
22451 (save-excursion (outline-end-of-heading) (point))
22452 flag))))
22454 (defun org-get-next-sibling ()
22455 "Move to next heading of the same level, and return point.
22456 If there is no such heading, return nil.
22457 This is like outline-next-sibling, but invisible headings are ok."
22458 (let ((level (funcall outline-level)))
22459 (outline-next-heading)
22460 (while (and (not (eobp)) (> (funcall outline-level) level))
22461 (outline-next-heading))
22462 (if (or (eobp) (< (funcall outline-level) level))
22464 (point))))
22466 (defun org-get-last-sibling ()
22467 "Move to previous heading of the same level, and return point.
22468 If there is no such heading, return nil."
22469 (let ((opoint (point))
22470 (level (funcall outline-level)))
22471 (outline-previous-heading)
22472 (when (and (/= (point) opoint) (outline-on-heading-p t))
22473 (while (and (> (funcall outline-level) level)
22474 (not (bobp)))
22475 (outline-previous-heading))
22476 (if (< (funcall outline-level) level)
22478 (point)))))
22480 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22481 "Goto to the end of a subtree."
22482 ;; This contains an exact copy of the original function, but it uses
22483 ;; `org-back-to-heading', to make it work also in invisible
22484 ;; trees. And is uses an invisible-ok argument.
22485 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22486 ;; Furthermore, when used inside Org, finding the end of a large subtree
22487 ;; with many children and grandchildren etc, this can be much faster
22488 ;; than the outline version.
22489 (org-back-to-heading invisible-ok)
22490 (let ((first t)
22491 (level (funcall outline-level)))
22492 (if (and (derived-mode-p 'org-mode) (< level 1000))
22493 ;; A true heading (not a plain list item), in Org-mode
22494 ;; This means we can easily find the end by looking
22495 ;; only for the right number of stars. Using a regexp to do
22496 ;; this is so much faster than using a Lisp loop.
22497 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22498 (forward-char 1)
22499 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22500 ;; something else, do it the slow way
22501 (while (and (not (eobp))
22502 (or first (> (funcall outline-level) level)))
22503 (setq first nil)
22504 (outline-next-heading)))
22505 (unless to-heading
22506 (if (memq (preceding-char) '(?\n ?\^M))
22507 (progn
22508 ;; Go to end of line before heading
22509 (forward-char -1)
22510 (if (memq (preceding-char) '(?\n ?\^M))
22511 ;; leave blank line before heading
22512 (forward-char -1))))))
22513 (point))
22515 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22516 "Use Org version in org-mode, for dramatic speed-up."
22517 (if (derived-mode-p 'org-mode)
22518 (progn
22519 (org-end-of-subtree nil t)
22520 (unless (eobp) (backward-char 1)))
22521 ad-do-it))
22523 (defun org-end-of-meta-data-and-drawers ()
22524 "Jump to the first text after meta data and drawers in the current entry.
22525 This will move over empty lines, lines with planning time stamps,
22526 clocking lines, and drawers."
22527 (org-back-to-heading t)
22528 (let ((end (save-excursion (outline-next-heading) (point)))
22529 (re (concat "\\(" org-drawer-regexp "\\)"
22530 "\\|" "[ \t]*" org-keyword-time-regexp)))
22531 (forward-line 1)
22532 (while (re-search-forward re end t)
22533 (if (not (match-end 1))
22534 ;; empty or planning line
22535 (forward-line 1)
22536 ;; a drawer, find the end
22537 (re-search-forward "^[ \t]*:END:" end 'move)
22538 (forward-line 1)))
22539 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22540 (point)))
22542 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22543 "Move forward to the ARG'th subheading at same level as this one.
22544 Stop at the first and last subheadings of a superior heading.
22545 Normally this only looks at visible headings, but when INVISIBLE-OK is
22546 non-nil it will also look at invisible ones."
22547 (interactive "p")
22548 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22549 (if (and arg (< arg 0))
22550 (goto-char (point-min))
22551 (outline-next-heading))
22552 (org-at-heading-p)
22553 (let ((level (- (match-end 0) (match-beginning 0) 1))
22554 (f (if (and arg (< arg 0))
22555 're-search-backward
22556 're-search-forward))
22557 (count (if arg (abs arg) 1))
22558 (result (point)))
22559 (forward-char (if (and arg (< arg 0)) -1 1))
22560 (while (and (> count 0)
22561 (funcall f org-outline-regexp-bol nil 'move))
22562 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22563 (cond ((< l level) (setq count 0))
22564 ((and (= l level)
22565 (or invisible-ok
22566 (progn
22567 (goto-char (line-beginning-position))
22568 (not (outline-invisible-p)))))
22569 (setq count (1- count))
22570 (when (eq l level)
22571 (setq result (point)))))))
22572 (goto-char result))
22573 (beginning-of-line 1)))
22575 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22576 "Move backward to the ARG'th subheading at same level as this one.
22577 Stop at the first and last subheadings of a superior heading."
22578 (interactive "p")
22579 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22581 (defun org-next-block (arg &optional backward block-regexp)
22582 "Jump to the next block.
22583 With a prefix argument ARG, jump forward ARG many source blocks.
22584 When BACKWARD is non-nil, jump to the previous block.
22585 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22586 (interactive "p")
22587 (let ((re (or block-regexp org-block-regexp))
22588 (re-search-fn (or (and backward 're-search-backward)
22589 're-search-forward)))
22590 (if (looking-at re) (forward-char 1))
22591 (condition-case nil
22592 (funcall re-search-fn re nil nil arg)
22593 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22594 (goto-char (match-beginning 0)) (org-show-context)))
22596 (defun org-previous-block (arg &optional block-regexp)
22597 "Jump to the previous block.
22598 With a prefix argument ARG, jump backward ARG many source blocks.
22599 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22600 (interactive "p")
22601 (org-next-block arg t block-regexp))
22603 (defun org-forward-element ()
22604 "Move forward by one element.
22605 Move to the next element at the same level, when possible."
22606 (interactive)
22607 (cond ((eobp) (error "Cannot move further down"))
22608 ((org-with-limited-levels (org-at-heading-p))
22609 (let ((origin (point)))
22610 (goto-char (org-end-of-subtree nil t))
22611 (unless (org-with-limited-levels (org-at-heading-p))
22612 (goto-char origin)
22613 (error "Cannot move further down"))))
22615 (let* ((elem (org-element-at-point))
22616 (end (org-element-property :end elem))
22617 (parent (org-element-property :parent elem)))
22618 (if (and parent (= (org-element-property :contents-end parent) end))
22619 (goto-char (org-element-property :end parent))
22620 (goto-char end))))))
22622 (defun org-backward-element ()
22623 "Move backward by one element.
22624 Move to the previous element at the same level, when possible."
22625 (interactive)
22626 (cond ((bobp) (error "Cannot move further up"))
22627 ((org-with-limited-levels (org-at-heading-p))
22628 ;; At an headline, move to the previous one, if any, or stay
22629 ;; here.
22630 (let ((origin (point)))
22631 (org-with-limited-levels (org-backward-heading-same-level 1))
22632 ;; When current headline has no sibling above, move to its
22633 ;; parent.
22634 (when (= (point) origin)
22635 (or (org-with-limited-levels (org-up-heading-safe))
22636 (progn (goto-char origin)
22637 (error "Cannot move further up"))))))
22639 (let* ((trail (org-element-at-point 'keep-trail))
22640 (elem (car trail))
22641 (prev-elem (nth 1 trail))
22642 (beg (org-element-property :begin elem)))
22643 (cond
22644 ;; Move to beginning of current element if point isn't
22645 ;; there already.
22646 ((/= (point) beg) (goto-char beg))
22647 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22648 ((org-before-first-heading-p) (goto-char (point-min)))
22649 (t (org-back-to-heading)))))))
22651 (defun org-up-element ()
22652 "Move to upper element."
22653 (interactive)
22654 (if (org-with-limited-levels (org-at-heading-p))
22655 (unless (org-up-heading-safe) (error "No surrounding element"))
22656 (let* ((elem (org-element-at-point))
22657 (parent (org-element-property :parent elem)))
22658 (if parent (goto-char (org-element-property :begin parent))
22659 (if (org-with-limited-levels (org-before-first-heading-p))
22660 (error "No surrounding element")
22661 (org-with-limited-levels (org-back-to-heading)))))))
22663 (defvar org-element-greater-elements)
22664 (defun org-down-element ()
22665 "Move to inner element."
22666 (interactive)
22667 (let ((element (org-element-at-point)))
22668 (cond
22669 ((memq (org-element-type element) '(plain-list table))
22670 (goto-char (org-element-property :contents-begin element))
22671 (forward-char))
22672 ((memq (org-element-type element) org-element-greater-elements)
22673 ;; If contents are hidden, first disclose them.
22674 (when (org-element-property :hiddenp element) (org-cycle))
22675 (goto-char (or (org-element-property :contents-begin element)
22676 (error "No content for this element"))))
22677 (t (error "No inner element")))))
22679 (defun org-drag-element-backward ()
22680 "Move backward element at point."
22681 (interactive)
22682 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22683 (let* ((trail (org-element-at-point 'keep-trail))
22684 (elem (car trail))
22685 (prev-elem (nth 1 trail)))
22686 ;; Error out if no previous element or previous element is
22687 ;; a parent of the current one.
22688 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22689 (error "Cannot drag element backward")
22690 (let ((pos (point)))
22691 (org-element-swap-A-B prev-elem elem)
22692 (goto-char (+ (org-element-property :begin prev-elem)
22693 (- pos (org-element-property :begin elem)))))))))
22695 (defun org-drag-element-forward ()
22696 "Move forward element at point."
22697 (interactive)
22698 (let* ((pos (point))
22699 (elem (org-element-at-point)))
22700 (when (= (point-max) (org-element-property :end elem))
22701 (error "Cannot drag element forward"))
22702 (goto-char (org-element-property :end elem))
22703 (let ((next-elem (org-element-at-point)))
22704 (when (or (org-element-nested-p elem next-elem)
22705 (and (eq (org-element-type next-elem) 'headline)
22706 (not (eq (org-element-type elem) 'headline))))
22707 (goto-char pos)
22708 (error "Cannot drag element forward"))
22709 ;; Compute new position of point: it's shifted by NEXT-ELEM
22710 ;; body's length (without final blanks) and by the length of
22711 ;; blanks between ELEM and NEXT-ELEM.
22712 (let ((size-next (- (save-excursion
22713 (goto-char (org-element-property :end next-elem))
22714 (skip-chars-backward " \r\t\n")
22715 (forward-line)
22716 ;; Small correction if buffer doesn't end
22717 ;; with a newline character.
22718 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22719 (org-element-property :begin next-elem)))
22720 (size-blank (- (org-element-property :end elem)
22721 (save-excursion
22722 (goto-char (org-element-property :end elem))
22723 (skip-chars-backward " \r\t\n")
22724 (forward-line)
22725 (point)))))
22726 (org-element-swap-A-B elem next-elem)
22727 (goto-char (+ pos size-next size-blank))))))
22729 (defun org-drag-line-forward (arg)
22730 "Drag the line at point ARG lines forward."
22731 (interactive "p")
22732 (dotimes (n (abs arg))
22733 (let ((c (current-column)))
22734 (if (< 0 arg)
22735 (progn
22736 (beginning-of-line 2)
22737 (transpose-lines 1)
22738 (beginning-of-line 0))
22739 (transpose-lines 1)
22740 (beginning-of-line -1))
22741 (org-move-to-column c))))
22743 (defun org-drag-line-backward (arg)
22744 "Drag the line at point ARG lines backward."
22745 (interactive "p")
22746 (org-drag-line-forward (- arg)))
22748 (defun org-mark-element ()
22749 "Put point at beginning of this element, mark at end.
22751 Interactively, if this command is repeated or (in Transient Mark
22752 mode) if the mark is active, it marks the next element after the
22753 ones already marked."
22754 (interactive)
22755 (let (deactivate-mark)
22756 (if (and (org-called-interactively-p 'any)
22757 (or (and (eq last-command this-command) (mark t))
22758 (and transient-mark-mode mark-active)))
22759 (set-mark
22760 (save-excursion
22761 (goto-char (mark))
22762 (goto-char (org-element-property :end (org-element-at-point)))))
22763 (let ((element (org-element-at-point)))
22764 (end-of-line)
22765 (push-mark (org-element-property :end element) t t)
22766 (goto-char (org-element-property :begin element))))))
22768 (defun org-narrow-to-element ()
22769 "Narrow buffer to current element."
22770 (interactive)
22771 (let ((elem (org-element-at-point)))
22772 (cond
22773 ((eq (car elem) 'headline)
22774 (narrow-to-region
22775 (org-element-property :begin elem)
22776 (org-element-property :end elem)))
22777 ((memq (car elem) org-element-greater-elements)
22778 (narrow-to-region
22779 (org-element-property :contents-begin elem)
22780 (org-element-property :contents-end elem)))
22782 (narrow-to-region
22783 (org-element-property :begin elem)
22784 (org-element-property :end elem))))))
22786 (defun org-transpose-element ()
22787 "Transpose current and previous elements, keeping blank lines between.
22788 Point is moved after both elements."
22789 (interactive)
22790 (org-skip-whitespace)
22791 (let ((end (org-element-property :end (org-element-at-point))))
22792 (org-drag-element-backward)
22793 (goto-char end)))
22795 (defun org-unindent-buffer ()
22796 "Un-indent the visible part of the buffer.
22797 Relative indentation (between items, inside blocks, etc.) isn't
22798 modified."
22799 (interactive)
22800 (unless (eq major-mode 'org-mode)
22801 (error "Cannot un-indent a buffer not in Org mode"))
22802 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22803 unindent-tree ; For byte-compiler.
22804 (unindent-tree
22805 (function
22806 (lambda (contents)
22807 (mapc
22808 (lambda (element)
22809 (if (memq (org-element-type element) '(headline section))
22810 (funcall unindent-tree (org-element-contents element))
22811 (save-excursion
22812 (save-restriction
22813 (narrow-to-region
22814 (org-element-property :begin element)
22815 (org-element-property :end element))
22816 (org-do-remove-indentation)))))
22817 (reverse contents))))))
22818 (funcall unindent-tree (org-element-contents parse-tree))))
22820 (defun org-show-subtree ()
22821 "Show everything after this heading at deeper levels."
22822 (interactive)
22823 (outline-flag-region
22824 (point)
22825 (save-excursion
22826 (org-end-of-subtree t t))
22827 nil))
22829 (defun org-show-entry ()
22830 "Show the body directly following this heading.
22831 Show the heading too, if it is currently invisible."
22832 (interactive)
22833 (save-excursion
22834 (condition-case nil
22835 (progn
22836 (org-back-to-heading t)
22837 (outline-flag-region
22838 (max (point-min) (1- (point)))
22839 (save-excursion
22840 (if (re-search-forward
22841 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22842 (match-beginning 1)
22843 (point-max)))
22844 nil)
22845 (org-cycle-hide-drawers 'children))
22846 (error nil))))
22848 (defun org-make-options-regexp (kwds &optional extra)
22849 "Make a regular expression for keyword lines."
22850 (concat
22851 "^#\\+\\("
22852 (mapconcat 'regexp-quote kwds "\\|")
22853 (if extra (concat "\\|" extra))
22854 "\\):[ \t]*\\(.*\\)"))
22856 ;; Make isearch reveal the necessary context
22857 (defun org-isearch-end ()
22858 "Reveal context after isearch exits."
22859 (when isearch-success ; only if search was successful
22860 (if (featurep 'xemacs)
22861 ;; Under XEmacs, the hook is run in the correct place,
22862 ;; we directly show the context.
22863 (org-show-context 'isearch)
22864 ;; In Emacs the hook runs *before* restoring the overlays.
22865 ;; So we have to use a one-time post-command-hook to do this.
22866 ;; (Emacs 22 has a special variable, see function `org-mode')
22867 (unless (and (boundp 'isearch-mode-end-hook-quit)
22868 isearch-mode-end-hook-quit)
22869 ;; Only when the isearch was not quitted.
22870 (org-add-hook 'post-command-hook 'org-isearch-post-command
22871 'append 'local)))))
22873 (defun org-isearch-post-command ()
22874 "Remove self from hook, and show context."
22875 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22876 (org-show-context 'isearch))
22879 ;;;; Integration with and fixes for other packages
22881 ;;; Imenu support
22883 (defvar org-imenu-markers nil
22884 "All markers currently used by Imenu.")
22885 (make-variable-buffer-local 'org-imenu-markers)
22887 (defun org-imenu-new-marker (&optional pos)
22888 "Return a new marker for use by Imenu, and remember the marker."
22889 (let ((m (make-marker)))
22890 (move-marker m (or pos (point)))
22891 (push m org-imenu-markers)
22894 (defun org-imenu-get-tree ()
22895 "Produce the index for Imenu."
22896 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22897 (setq org-imenu-markers nil)
22898 (let* ((n org-imenu-depth)
22899 (re (concat "^" (org-get-limited-outline-regexp)))
22900 (subs (make-vector (1+ n) nil))
22901 (last-level 0)
22902 m level head)
22903 (save-excursion
22904 (save-restriction
22905 (widen)
22906 (goto-char (point-max))
22907 (while (re-search-backward re nil t)
22908 (setq level (org-reduced-level (funcall outline-level)))
22909 (when (and (<= level n)
22910 (looking-at org-complex-heading-regexp))
22911 (setq head (org-link-display-format
22912 (org-match-string-no-properties 4))
22913 m (org-imenu-new-marker))
22914 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22915 (if (>= level last-level)
22916 (push (cons head m) (aref subs level))
22917 (push (cons head (aref subs (1+ level))) (aref subs level))
22918 (loop for i from (1+ level) to n do (aset subs i nil)))
22919 (setq last-level level)))))
22920 (aref subs 1)))
22922 (eval-after-load "imenu"
22923 '(progn
22924 (add-hook 'imenu-after-jump-hook
22925 (lambda ()
22926 (if (derived-mode-p 'org-mode)
22927 (org-show-context 'org-goto))))))
22929 (defun org-link-display-format (link)
22930 "Replace a link with either the description, or the link target
22931 if no description is present"
22932 (save-match-data
22933 (if (string-match org-bracket-link-analytic-regexp link)
22934 (replace-match (if (match-end 5)
22935 (match-string 5 link)
22936 (concat (match-string 1 link)
22937 (match-string 3 link)))
22938 nil t link)
22939 link)))
22941 (defun org-toggle-link-display ()
22942 "Toggle the literal or descriptive display of links."
22943 (interactive)
22944 (if org-descriptive-links
22945 (progn (org-remove-from-invisibility-spec '(org-link))
22946 (org-restart-font-lock)
22947 (setq org-descriptive-links nil))
22948 (progn (add-to-invisibility-spec '(org-link))
22949 (org-restart-font-lock)
22950 (setq org-descriptive-links t))))
22952 ;; Speedbar support
22954 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22955 "Overlay marking the agenda restriction line in speedbar.")
22956 (overlay-put org-speedbar-restriction-lock-overlay
22957 'face 'org-agenda-restriction-lock)
22958 (overlay-put org-speedbar-restriction-lock-overlay
22959 'help-echo "Agendas are currently limited to this item.")
22960 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22962 (defun org-speedbar-set-agenda-restriction ()
22963 "Restrict future agenda commands to the location at point in speedbar.
22964 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22965 (interactive)
22966 (require 'org-agenda)
22967 (let (p m tp np dir txt)
22968 (cond
22969 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22970 'org-imenu t))
22971 (setq m (get-text-property p 'org-imenu-marker))
22972 (with-current-buffer (marker-buffer m)
22973 (goto-char m)
22974 (org-agenda-set-restriction-lock 'subtree)))
22975 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22976 'speedbar-function 'speedbar-find-file))
22977 (setq tp (previous-single-property-change
22978 (1+ p) 'speedbar-function)
22979 np (next-single-property-change
22980 tp 'speedbar-function)
22981 dir (speedbar-line-directory)
22982 txt (buffer-substring-no-properties (or tp (point-min))
22983 (or np (point-max))))
22984 (with-current-buffer (find-file-noselect
22985 (let ((default-directory dir))
22986 (expand-file-name txt)))
22987 (unless (derived-mode-p 'org-mode)
22988 (error "Cannot restrict to non-Org-mode file"))
22989 (org-agenda-set-restriction-lock 'file)))
22990 (t (error "Don't know how to restrict Org-mode's agenda")))
22991 (move-overlay org-speedbar-restriction-lock-overlay
22992 (point-at-bol) (point-at-eol))
22993 (setq current-prefix-arg nil)
22994 (org-agenda-maybe-redo)))
22996 (eval-after-load "speedbar"
22997 '(progn
22998 (speedbar-add-supported-extension ".org")
22999 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23000 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23001 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23002 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23003 (add-hook 'speedbar-visiting-tag-hook
23004 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23006 ;;; Fixes and Hacks for problems with other packages
23008 ;; Make flyspell not check words in links, to not mess up our keymap
23009 (defvar org-element-affiliated-keywords) ; From org-element.el
23010 (defvar org-element-block-name-alist) ; From org-element.el
23011 (defun org-mode-flyspell-verify ()
23012 "Don't let flyspell put overlays at active buttons, or on
23013 {todo,all-time,additional-option-like}-keywords."
23014 (let ((pos (max (1- (point)) (point-min)))
23015 (word (thing-at-point 'word)))
23016 (and (not (get-text-property pos 'keymap))
23017 (not (get-text-property pos 'org-no-flyspell))
23018 (not (member word org-todo-keywords-1))
23019 (not (member word org-all-time-keywords))
23020 (not (member word org-options-keywords))
23021 (not (member word (mapcar 'car org-startup-options)))
23022 (not (member-ignore-case word org-element-affiliated-keywords))
23023 (not (member-ignore-case word (org-get-export-keywords)))
23024 (not (member-ignore-case
23025 word (mapcar 'car org-element-block-name-alist)))
23026 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23028 (defun org-remove-flyspell-overlays-in (beg end)
23029 "Remove flyspell overlays in region."
23030 (and (org-bound-and-true-p flyspell-mode)
23031 (fboundp 'flyspell-delete-region-overlays)
23032 (flyspell-delete-region-overlays beg end))
23033 (add-text-properties beg end '(org-no-flyspell t)))
23035 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23036 (eval-after-load "bookmark"
23037 '(if (boundp 'bookmark-after-jump-hook)
23038 ;; We can use the hook
23039 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23040 ;; Hook not available, use advice
23041 (defadvice bookmark-jump (after org-make-visible activate)
23042 "Make the position visible."
23043 (org-bookmark-jump-unhide))))
23045 ;; Make sure saveplace shows the location if it was hidden
23046 (eval-after-load "saveplace"
23047 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23048 "Make the position visible."
23049 (org-bookmark-jump-unhide)))
23051 ;; Make sure ecb shows the location if it was hidden
23052 (eval-after-load "ecb"
23053 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23054 "Make hierarchy visible when jumping into location from ECB tree buffer."
23055 (if (derived-mode-p 'org-mode)
23056 (org-show-context))))
23058 (defun org-bookmark-jump-unhide ()
23059 "Unhide the current position, to show the bookmark location."
23060 (and (derived-mode-p 'org-mode)
23061 (or (outline-invisible-p)
23062 (save-excursion (goto-char (max (point-min) (1- (point))))
23063 (outline-invisible-p)))
23064 (org-show-context 'bookmark-jump)))
23066 ;; Make session.el ignore our circular variable
23067 (eval-after-load "session"
23068 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23070 ;;;; Experimental code
23072 (defun org-closed-in-range ()
23073 "Sparse tree of items closed in a certain time range.
23074 Still experimental, may disappear in the future."
23075 (interactive)
23076 ;; Get the time interval from the user.
23077 (let* ((time1 (org-float-time
23078 (org-read-date nil 'to-time nil "Starting date: ")))
23079 (time2 (org-float-time
23080 (org-read-date nil 'to-time nil "End date:")))
23081 ;; callback function
23082 (callback (lambda ()
23083 (let ((time
23084 (org-float-time
23085 (apply 'encode-time
23086 (org-parse-time-string
23087 (match-string 1))))))
23088 ;; check if time in interval
23089 (and (>= time time1) (<= time time2))))))
23090 ;; make tree, check each match with the callback
23091 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23093 ;;;; Finish up
23095 (provide 'org)
23097 (run-hooks 'org-load-hook)
23099 ;;; org.el ends here