org.el (org-startup-with-latex-preview): New option
[org-mode/org-tableheadings.git] / lisp / org.el
blobfcf394d23cdf95a8742c9ed2fb6f59566e5c401c
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (load "org-loaddefs.el" t t t)
83 (require 'org-macs)
84 (require 'org-compat)
86 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
87 ;; some places -- e.g. see the macro org-with-limited-levels.
89 ;; In Org buffers, the value of `outline-regexp' is that of
90 ;; `org-outline-regexp'. The only function still directly relying on
91 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
92 ;; job when `orgstruct-mode' is active.
93 (defvar org-outline-regexp "\\*+ "
94 "Regexp to match Org headlines.")
96 (defvar org-outline-regexp-bol "^\\*+ "
97 "Regexp to match Org headlines.
98 This is similar to `org-outline-regexp' but additionally makes
99 sure that we are at the beginning of the line.")
101 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
102 "Matches an headline, putting stars and text into groups.
103 Stars are put in group 1 and the trimmed body in group 2.")
105 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
106 (when (fboundp 'defvaralias)
107 (unless (boundp 'calendar-view-holidays-initially-flag)
108 (defvaralias 'calendar-view-holidays-initially-flag
109 'view-calendar-holidays-initially))
110 (unless (boundp 'calendar-view-diary-initially-flag)
111 (defvaralias 'calendar-view-diary-initially-flag
112 'view-diary-entries-initially))
113 (unless (boundp 'diary-fancy-buffer)
114 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
116 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
117 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
118 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
119 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
120 (declare-function org-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything"
590 :group 'org-startup
591 :type '(choice
592 (const :tag "nofold: show all" nil)
593 (const :tag "fold: overview" t)
594 (const :tag "content: all headlines" content)
595 (const :tag "show everything, even drawers" showeverything)))
597 (defcustom org-startup-truncated t
598 "Non-nil means entering Org-mode will set `truncate-lines'.
599 This is useful since some lines containing links can be very long and
600 uninteresting. Also tables look terrible when wrapped."
601 :group 'org-startup
602 :type 'boolean)
604 (defcustom org-startup-indented nil
605 "Non-nil means turn on `org-indent-mode' on startup.
606 This can also be configured on a per-file basis by adding one of
607 the following lines anywhere in the buffer:
609 #+STARTUP: indent
610 #+STARTUP: noindent"
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Not" nil)
614 (const :tag "Globally (slow on startup in large files)" t)))
616 (defcustom org-use-sub-superscripts t
617 "Non-nil means interpret \"_\" and \"^\" for display.
618 When this option is turned on, you can use TeX-like syntax for sub- and
619 superscripts. Several characters after \"_\" or \"^\" will be
620 considered as a single item - so grouping with {} is normally not
621 needed. For example, the following things will be parsed as single
622 sub- or superscripts.
624 10^24 or 10^tau several digits will be considered 1 item.
625 10^-12 or 10^-tau a leading sign with digits or a word
626 x^2-y^3 will be read as x^2 - y^3, because items are
627 terminated by almost any nonword/nondigit char.
628 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
630 Still, ambiguity is possible - so when in doubt use {} to enclose
631 the sub/superscript. If you set this variable to the symbol
632 `{}', the braces are *required* in order to trigger
633 interpretations as sub/superscript. This can be helpful in
634 documents that need \"_\" frequently in plain text."
635 :group 'org-startup
636 :version "24.1"
637 :type '(choice
638 (const :tag "Always interpret" t)
639 (const :tag "Only with braces" {})
640 (const :tag "Never interpret" nil)))
642 (defcustom org-startup-with-beamer-mode nil
643 "Non-nil means turn on `org-beamer-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: beamer"
648 :group 'org-startup
649 :version "24.1"
650 :type 'boolean)
652 (defcustom org-startup-align-all-tables nil
653 "Non-nil means align all tables when visiting a file.
654 This is useful when the column width in tables is forced with <N> cookies
655 in table fields. Such tables will look correct only after the first re-align.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
658 #+STARTUP: align
659 #+STARTUP: noalign"
660 :group 'org-startup
661 :type 'boolean)
663 (defcustom org-startup-with-inline-images nil
664 "Non-nil means show inline images when loading a new Org file.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: inlineimages
668 #+STARTUP: noinlineimages"
669 :group 'org-startup
670 :version "24.1"
671 :type 'boolean)
673 (defcustom org-startup-with-latex-preview nil
674 "Non-nil means preview LaTeX fragments when loading a new Org file.
676 This can also be configured on a per-file basis by adding one of
677 the followinglines anywhere in the buffer:
678 #+STARTUP: latexpreview
679 #+STARTUP: nolatexpreview"
680 :group 'org-startup
681 :version "24.3"
682 :type 'boolean)
684 (defcustom org-insert-mode-line-in-empty-file nil
685 "Non-nil means insert the first line setting Org-mode in empty files.
686 When the function `org-mode' is called interactively in an empty file, this
687 normally means that the file name does not automatically trigger Org-mode.
688 To ensure that the file will always be in Org-mode in the future, a
689 line enforcing Org-mode will be inserted into the buffer, if this option
690 has been set."
691 :group 'org-startup
692 :type 'boolean)
694 (defcustom org-replace-disputed-keys nil
695 "Non-nil means use alternative key bindings for some keys.
696 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
697 These keys are also used by other packages like shift-selection-mode'
698 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
699 If you want to use Org-mode together with one of these other modes,
700 or more generally if you would like to move some Org-mode commands to
701 other keys, set this variable and configure the keys with the variable
702 `org-disputed-keys'.
704 This option is only relevant at load-time of Org-mode, and must be set
705 *before* org.el is loaded. Changing it requires a restart of Emacs to
706 become effective."
707 :group 'org-startup
708 :type 'boolean)
710 (defcustom org-use-extra-keys nil
711 "Non-nil means use extra key sequence definitions for certain commands.
712 This happens automatically if you run XEmacs or if `window-system'
713 is nil. This variable lets you do the same manually. You must
714 set it before loading org.
716 Example: on Carbon Emacs 22 running graphically, with an external
717 keyboard on a Powerbook, the default way of setting M-left might
718 not work for either Alt or ESC. Setting this variable will make
719 it work for ESC."
720 :group 'org-startup
721 :type 'boolean)
723 (if (fboundp 'defvaralias)
724 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
726 (defcustom org-disputed-keys
727 '(([(shift up)] . [(meta p)])
728 ([(shift down)] . [(meta n)])
729 ([(shift left)] . [(meta -)])
730 ([(shift right)] . [(meta +)])
731 ([(control shift right)] . [(meta shift +)])
732 ([(control shift left)] . [(meta shift -)]))
733 "Keys for which Org-mode and other modes compete.
734 This is an alist, cars are the default keys, second element specifies
735 the alternative to use when `org-replace-disputed-keys' is t.
737 Keys can be specified in any syntax supported by `define-key'.
738 The value of this option takes effect only at Org-mode's startup,
739 therefore you'll have to restart Emacs to apply it after changing."
740 :group 'org-startup
741 :type 'alist)
743 (defun org-key (key)
744 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
745 Or return the original if not disputed.
746 Also apply the translations defined in `org-xemacs-key-equivalents'."
747 (when org-replace-disputed-keys
748 (let* ((nkey (key-description key))
749 (x (org-find-if (lambda (x)
750 (equal (key-description (car x)) nkey))
751 org-disputed-keys)))
752 (setq key (if x (cdr x) key))))
753 (when (featurep 'xemacs)
754 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
755 key)
757 (defun org-find-if (predicate seq)
758 (catch 'exit
759 (while seq
760 (if (funcall predicate (car seq))
761 (throw 'exit (car seq))
762 (pop seq)))))
764 (defun org-defkey (keymap key def)
765 "Define a key, possibly translated, as returned by `org-key'."
766 (define-key keymap (org-key key) def))
768 (defcustom org-ellipsis nil
769 "The ellipsis to use in the Org-mode outline.
770 When nil, just use the standard three dots. When a string, use that instead,
771 When a face, use the standard 3 dots, but with the specified face.
772 The change affects only Org-mode (which will then use its own display table).
773 Changing this requires executing `M-x org-mode' in a buffer to become
774 effective."
775 :group 'org-startup
776 :type '(choice (const :tag "Default" nil)
777 (face :tag "Face" :value org-warning)
778 (string :tag "String" :value "...#")))
780 (defvar org-display-table nil
781 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
783 (defgroup org-keywords nil
784 "Keywords in Org-mode."
785 :tag "Org Keywords"
786 :group 'org)
788 (defcustom org-deadline-string "DEADLINE:"
789 "String to mark deadline entries.
790 A deadline is this string, followed by a time stamp. Should be a word,
791 terminated by a colon. You can insert a schedule keyword and
792 a timestamp with \\[org-deadline].
793 Changes become only effective after restarting Emacs."
794 :group 'org-keywords
795 :type 'string)
797 (defcustom org-scheduled-string "SCHEDULED:"
798 "String to mark scheduled TODO entries.
799 A schedule is this string, followed by a time stamp. Should be a word,
800 terminated by a colon. You can insert a schedule keyword and
801 a timestamp with \\[org-schedule].
802 Changes become only effective after restarting Emacs."
803 :group 'org-keywords
804 :type 'string)
806 (defcustom org-closed-string "CLOSED:"
807 "String used as the prefix for timestamps logging closing a TODO entry."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-clock-string "CLOCK:"
812 "String used as prefix for timestamps clocking work hours on an item."
813 :group 'org-keywords
814 :type 'string)
816 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
817 org-scheduled-string "\\|"
818 org-deadline-string "\\|"
819 org-closed-string "\\|"
820 org-clock-string "\\)")
821 "Matches a line with planning or clock info.")
823 (defcustom org-comment-string "COMMENT"
824 "Entries starting with this keyword will never be exported.
825 An entry can be toggled between COMMENT and normal with
826 \\[org-toggle-comment].
827 Changes become only effective after restarting Emacs."
828 :group 'org-keywords
829 :type 'string)
831 (defcustom org-quote-string "QUOTE"
832 "Entries starting with this keyword will be exported in fixed-width font.
833 Quoting applies only to the text in the entry following the headline, and does
834 not extend beyond the next headline, even if that is lower level.
835 An entry can be toggled between QUOTE and normal with
836 \\[org-toggle-fixed-width-section]."
837 :group 'org-keywords
838 :type 'string)
840 (defconst org-repeat-re
841 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
842 "Regular expression for specifying repeated events.
843 After a match, group 1 contains the repeat expression.")
845 (defgroup org-structure nil
846 "Options concerning the general structure of Org-mode files."
847 :tag "Org Structure"
848 :group 'org)
850 (defgroup org-reveal-location nil
851 "Options about how to make context of a location visible."
852 :tag "Org Reveal Location"
853 :group 'org-structure)
855 (defconst org-context-choice
856 '(choice
857 (const :tag "Always" t)
858 (const :tag "Never" nil)
859 (repeat :greedy t :tag "Individual contexts"
860 (cons
861 (choice :tag "Context"
862 (const agenda)
863 (const org-goto)
864 (const occur-tree)
865 (const tags-tree)
866 (const link-search)
867 (const mark-goto)
868 (const bookmark-jump)
869 (const isearch)
870 (const default))
871 (boolean))))
872 "Contexts for the reveal options.")
874 (defcustom org-show-hierarchy-above '((default . t))
875 "Non-nil means show full hierarchy when revealing a location.
876 Org-mode often shows locations in an org-mode file which might have
877 been invisible before. When this is set, the hierarchy of headings
878 above the exposed location is shown.
879 Turning this off for example for sparse trees makes them very compact.
880 Instead of t, this can also be an alist specifying this option for different
881 contexts. Valid contexts are
882 agenda when exposing an entry from the agenda
883 org-goto when using the command `org-goto' on key C-c C-j
884 occur-tree when using the command `org-occur' on key C-c /
885 tags-tree when constructing a sparse tree based on tags matches
886 link-search when exposing search matches associated with a link
887 mark-goto when exposing the jump goal of a mark
888 bookmark-jump when exposing a bookmark location
889 isearch when exiting from an incremental search
890 default default for all contexts not set explicitly"
891 :group 'org-reveal-location
892 :type org-context-choice)
894 (defcustom org-show-following-heading '((default . nil))
895 "Non-nil means show following heading when revealing a location.
896 Org-mode often shows locations in an org-mode file which might have
897 been invisible before. When this is set, the heading following the
898 match is shown.
899 Turning this off for example for sparse trees makes them very compact,
900 but makes it harder to edit the location of the match. In such a case,
901 use the command \\[org-reveal] to show more context.
902 Instead of t, this can also be an alist specifying this option for different
903 contexts. See `org-show-hierarchy-above' for valid contexts."
904 :group 'org-reveal-location
905 :type org-context-choice)
907 (defcustom org-show-siblings '((default . nil) (isearch t))
908 "Non-nil means show all sibling heading when revealing a location.
909 Org-mode often shows locations in an org-mode file which might have
910 been invisible before. When this is set, the sibling of the current entry
911 heading are all made visible. If `org-show-hierarchy-above' is t,
912 the same happens on each level of the hierarchy above the current entry.
914 By default this is on for the isearch context, off for all other contexts.
915 Turning this off for example for sparse trees makes them very compact,
916 but makes it harder to edit the location of the match. In such a case,
917 use the command \\[org-reveal] to show more context.
918 Instead of t, this can also be an alist specifying this option for different
919 contexts. See `org-show-hierarchy-above' for valid contexts."
920 :group 'org-reveal-location
921 :type org-context-choice)
923 (defcustom org-show-entry-below '((default . nil))
924 "Non-nil means show the entry below a headline when revealing a location.
925 Org-mode often shows locations in an org-mode file which might have
926 been invisible before. When this is set, the text below the headline that is
927 exposed is also shown.
929 By default this is off for all contexts.
930 Instead of t, this can also be an alist specifying this option for different
931 contexts. See `org-show-hierarchy-above' for valid contexts."
932 :group 'org-reveal-location
933 :type org-context-choice)
935 (defcustom org-indirect-buffer-display 'other-window
936 "How should indirect tree buffers be displayed?
937 This applies to indirect buffers created with the commands
938 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
939 Valid values are:
940 current-window Display in the current window
941 other-window Just display in another window.
942 dedicated-frame Create one new frame, and re-use it each time.
943 new-frame Make a new frame each time. Note that in this case
944 previously-made indirect buffers are kept, and you need to
945 kill these buffers yourself."
946 :group 'org-structure
947 :group 'org-agenda-windows
948 :type '(choice
949 (const :tag "In current window" current-window)
950 (const :tag "In current frame, other window" other-window)
951 (const :tag "Each time a new frame" new-frame)
952 (const :tag "One dedicated frame" dedicated-frame)))
954 (defcustom org-use-speed-commands nil
955 "Non-nil means activate single letter commands at beginning of a headline.
956 This may also be a function to test for appropriate locations where speed
957 commands should be active."
958 :group 'org-structure
959 :type '(choice
960 (const :tag "Never" nil)
961 (const :tag "At beginning of headline stars" t)
962 (function)))
964 (defcustom org-speed-commands-user nil
965 "Alist of additional speed commands.
966 This list will be checked before `org-speed-commands-default'
967 when the variable `org-use-speed-commands' is non-nil
968 and when the cursor is at the beginning of a headline.
969 The car if each entry is a string with a single letter, which must
970 be assigned to `self-insert-command' in the global map.
971 The cdr is either a command to be called interactively, a function
972 to be called, or a form to be evaluated.
973 An entry that is just a list with a single string will be interpreted
974 as a descriptive headline that will be added when listing the speed
975 commands in the Help buffer using the `?' speed command."
976 :group 'org-structure
977 :type '(repeat :value ("k" . ignore)
978 (choice :value ("k" . ignore)
979 (list :tag "Descriptive Headline" (string :tag "Headline"))
980 (cons :tag "Letter and Command"
981 (string :tag "Command letter")
982 (choice
983 (function)
984 (sexp))))))
986 (defgroup org-cycle nil
987 "Options concerning visibility cycling in Org-mode."
988 :tag "Org Cycle"
989 :group 'org-structure)
991 (defcustom org-cycle-skip-children-state-if-no-children t
992 "Non-nil means skip CHILDREN state in entries that don't have any."
993 :group 'org-cycle
994 :type 'boolean)
996 (defcustom org-cycle-max-level nil
997 "Maximum level which should still be subject to visibility cycling.
998 Levels higher than this will, for cycling, be treated as text, not a headline.
999 When `org-odd-levels-only' is set, a value of N in this variable actually
1000 means 2N-1 stars as the limiting headline.
1001 When nil, cycle all levels.
1002 Note that the limiting level of cycling is also influenced by
1003 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1004 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1005 than its value."
1006 :group 'org-cycle
1007 :type '(choice
1008 (const :tag "No limit" nil)
1009 (integer :tag "Maximum level")))
1011 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1012 "Names of drawers. Drawers are not opened by cycling on the headline above.
1013 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1014 this:
1015 :DRAWERNAME:
1016 .....
1017 :END:
1018 The drawer \"PROPERTIES\" is special for capturing properties through
1019 the property API.
1021 Drawers can be defined on the per-file basis with a line like:
1023 #+DRAWERS: HIDDEN STATE PROPERTIES"
1024 :group 'org-structure
1025 :group 'org-cycle
1026 :type '(repeat (string :tag "Drawer Name")))
1028 (defcustom org-hide-block-startup nil
1029 "Non-nil means entering Org-mode will fold all blocks.
1030 This can also be set in on a per-file basis with
1032 #+STARTUP: hideblocks
1033 #+STARTUP: showblocks"
1034 :group 'org-startup
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-global-at-bob nil
1039 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1040 This makes it possible to do global cycling without having to use S-TAB or
1041 \\[universal-argument] TAB. For this special case to work, the first line
1042 of the buffer must not be a headline -- it may be empty or some other text.
1043 When used in this way, `org-cycle-hook' is disabled temporarily to make
1044 sure the cursor stays at the beginning of the buffer. When this option is
1045 nil, don't do anything special at the beginning of the buffer."
1046 :group 'org-cycle
1047 :type 'boolean)
1049 (defcustom org-cycle-level-after-item/entry-creation t
1050 "Non-nil means cycle entry level or item indentation in new empty entries.
1052 When the cursor is at the end of an empty headline, i.e., with only stars
1053 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1054 and then all possible ancestor states, before returning to the original state.
1055 This makes data entry extremely fast: M-RET to create a new headline,
1056 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1058 When the cursor is at the end of an empty plain list item, one TAB will
1059 make it a subitem, two or more tabs will back up to make this an item
1060 higher up in the item hierarchy."
1061 :group 'org-cycle
1062 :type 'boolean)
1064 (defcustom org-cycle-emulate-tab t
1065 "Where should `org-cycle' emulate TAB.
1066 nil Never
1067 white Only in completely white lines
1068 whitestart Only at the beginning of lines, before the first non-white char
1069 t Everywhere except in headlines
1070 exc-hl-bol Everywhere except at the start of a headline
1071 If TAB is used in a place where it does not emulate TAB, the current subtree
1072 visibility is cycled."
1073 :group 'org-cycle
1074 :type '(choice (const :tag "Never" nil)
1075 (const :tag "Only in completely white lines" white)
1076 (const :tag "Before first char in a line" whitestart)
1077 (const :tag "Everywhere except in headlines" t)
1078 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1081 (defcustom org-cycle-separator-lines 2
1082 "Number of empty lines needed to keep an empty line between collapsed trees.
1083 If you leave an empty line between the end of a subtree and the following
1084 headline, this empty line is hidden when the subtree is folded.
1085 Org-mode will leave (exactly) one empty line visible if the number of
1086 empty lines is equal or larger to the number given in this variable.
1087 So the default 2 means at least 2 empty lines after the end of a subtree
1088 are needed to produce free space between a collapsed subtree and the
1089 following headline.
1091 If the number is negative, and the number of empty lines is at least -N,
1092 all empty lines are shown.
1094 Special case: when 0, never leave empty lines in collapsed view."
1095 :group 'org-cycle
1096 :type 'integer)
1097 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1099 (defcustom org-pre-cycle-hook nil
1100 "Hook that is run before visibility cycling is happening.
1101 The function(s) in this hook must accept a single argument which indicates
1102 the new state that will be set right after running this hook. The
1103 argument is a symbol. Before a global state change, it can have the values
1104 `overview', `content', or `all'. Before a local state change, it can have
1105 the values `folded', `children', or `subtree'."
1106 :group 'org-cycle
1107 :type 'hook)
1109 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1110 org-cycle-hide-drawers
1111 org-cycle-hide-inline-tasks
1112 org-cycle-show-empty-lines
1113 org-optimize-window-after-visibility-change)
1114 "Hook that is run after `org-cycle' has changed the buffer visibility.
1115 The function(s) in this hook must accept a single argument which indicates
1116 the new state that was set by the most recent `org-cycle' command. The
1117 argument is a symbol. After a global state change, it can have the values
1118 `overview', `contents', or `all'. After a local state change, it can have
1119 the values `folded', `children', or `subtree'."
1120 :group 'org-cycle
1121 :type 'hook)
1123 (defgroup org-edit-structure nil
1124 "Options concerning structure editing in Org-mode."
1125 :tag "Org Edit Structure"
1126 :group 'org-structure)
1128 (defcustom org-odd-levels-only nil
1129 "Non-nil means skip even levels and only use odd levels for the outline.
1130 This has the effect that two stars are being added/taken away in
1131 promotion/demotion commands. It also influences how levels are
1132 handled by the exporters.
1133 Changing it requires restart of `font-lock-mode' to become effective
1134 for fontification also in regions already fontified.
1135 You may also set this on a per-file basis by adding one of the following
1136 lines to the buffer:
1138 #+STARTUP: odd
1139 #+STARTUP: oddeven"
1140 :group 'org-edit-structure
1141 :group 'org-appearance
1142 :type 'boolean)
1144 (defcustom org-adapt-indentation t
1145 "Non-nil means adapt indentation to outline node level.
1147 When this variable is set, Org assumes that you write outlines by
1148 indenting text in each node to align with the headline (after the stars).
1149 The following issues are influenced by this variable:
1151 - When this is set and the *entire* text in an entry is indented, the
1152 indentation is increased by one space in a demotion command, and
1153 decreased by one in a promotion command. If any line in the entry
1154 body starts with text at column 0, indentation is not changed at all.
1156 - Property drawers and planning information is inserted indented when
1157 this variable s set. When nil, they will not be indented.
1159 - TAB indents a line relative to context. The lines below a headline
1160 will be indented when this variable is set.
1162 Note that this is all about true indentation, by adding and removing
1163 space characters. See also `org-indent.el' which does level-dependent
1164 indentation in a virtual way, i.e. at display time in Emacs."
1165 :group 'org-edit-structure
1166 :type 'boolean)
1168 (defcustom org-special-ctrl-a/e nil
1169 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1171 When t, `C-a' will bring back the cursor to the beginning of the
1172 headline text, i.e. after the stars and after a possible TODO
1173 keyword. In an item, this will be the position after bullet and
1174 check-box, if any. When the cursor is already at that position,
1175 another `C-a' will bring it to the beginning of the line.
1177 `C-e' will jump to the end of the headline, ignoring the presence
1178 of tags in the headline. A second `C-e' will then jump to the
1179 true end of the line, after any tags. This also means that, when
1180 this variable is non-nil, `C-e' also will never jump beyond the
1181 end of the heading of a folded section, i.e. not after the
1182 ellipses.
1184 When set to the symbol `reversed', the first `C-a' or `C-e' works
1185 normally, going to the true line boundary first. Only a directly
1186 following, identical keypress will bring the cursor to the
1187 special positions.
1189 This may also be a cons cell where the behavior for `C-a' and
1190 `C-e' is set separately."
1191 :group 'org-edit-structure
1192 :type '(choice
1193 (const :tag "off" nil)
1194 (const :tag "on: after stars/bullet and before tags first" t)
1195 (const :tag "reversed: true line boundary first" reversed)
1196 (cons :tag "Set C-a and C-e separately"
1197 (choice :tag "Special C-a"
1198 (const :tag "off" nil)
1199 (const :tag "on: after stars/bullet first" t)
1200 (const :tag "reversed: before stars/bullet first" reversed))
1201 (choice :tag "Special C-e"
1202 (const :tag "off" nil)
1203 (const :tag "on: before tags first" t)
1204 (const :tag "reversed: after tags first" reversed)))))
1205 (if (fboundp 'defvaralias)
1206 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1208 (defcustom org-special-ctrl-k nil
1209 "Non-nil means `C-k' will behave specially in headlines.
1210 When nil, `C-k' will call the default `kill-line' command.
1211 When t, the following will happen while the cursor is in the headline:
1213 - When the cursor is at the beginning of a headline, kill the entire
1214 line and possible the folded subtree below the line.
1215 - When in the middle of the headline text, kill the headline up to the tags.
1216 - When after the headline text, kill the tags."
1217 :group 'org-edit-structure
1218 :type 'boolean)
1220 (defcustom org-ctrl-k-protect-subtree nil
1221 "Non-nil means, do not delete a hidden subtree with C-k.
1222 When set to the symbol `error', simply throw an error when C-k is
1223 used to kill (part-of) a headline that has hidden text behind it.
1224 Any other non-nil value will result in a query to the user, if it is
1225 OK to kill that hidden subtree. When nil, kill without remorse."
1226 :group 'org-edit-structure
1227 :version "24.1"
1228 :type '(choice
1229 (const :tag "Do not protect hidden subtrees" nil)
1230 (const :tag "Protect hidden subtrees with a security query" t)
1231 (const :tag "Never kill a hidden subtree with C-k" error)))
1233 (defcustom org-catch-invisible-edits nil
1234 "Check if in invisible region before inserting or deleting a character.
1235 Valid values are:
1237 nil Do not check, so just do invisible edits.
1238 error Throw an error and do nothing.
1239 show Make point visible, and do the requested edit.
1240 show-and-error Make point visible, then throw an error and abort the edit.
1241 smart Make point visible, and do insertion/deletion if it is
1242 adjacent to visible text and the change feels predictable.
1243 Never delete a previously invisible character or add in the
1244 middle or right after an invisible region. Basically, this
1245 allows insertion and backward-delete right before ellipses.
1246 FIXME: maybe in this case we should not even show?"
1247 :group 'org-edit-structure
1248 :version "24.1"
1249 :type '(choice
1250 (const :tag "Do not check" nil)
1251 (const :tag "Throw error when trying to edit" error)
1252 (const :tag "Unhide, but do not do the edit" show-and-error)
1253 (const :tag "Show invisible part and do the edit" show)
1254 (const :tag "Be smart and do the right thing" smart)))
1256 (defcustom org-yank-folded-subtrees t
1257 "Non-nil means when yanking subtrees, fold them.
1258 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1259 it starts with a heading and all other headings in it are either children
1260 or siblings, then fold all the subtrees. However, do this only if no
1261 text after the yank would be swallowed into a folded tree by this action."
1262 :group 'org-edit-structure
1263 :type 'boolean)
1265 (defcustom org-yank-adjusted-subtrees nil
1266 "Non-nil means when yanking subtrees, adjust the level.
1267 With this setting, `org-paste-subtree' is used to insert the subtree, see
1268 this function for details."
1269 :group 'org-edit-structure
1270 :type 'boolean)
1272 (defcustom org-M-RET-may-split-line '((default . t))
1273 "Non-nil means M-RET will split the line at the cursor position.
1274 When nil, it will go to the end of the line before making a
1275 new line.
1276 You may also set this option in a different way for different
1277 contexts. Valid contexts are:
1279 headline when creating a new headline
1280 item when creating a new item
1281 table in a table field
1282 default the value to be used for all contexts not explicitly
1283 customized"
1284 :group 'org-structure
1285 :group 'org-table
1286 :type '(choice
1287 (const :tag "Always" t)
1288 (const :tag "Never" nil)
1289 (repeat :greedy t :tag "Individual contexts"
1290 (cons
1291 (choice :tag "Context"
1292 (const headline)
1293 (const item)
1294 (const table)
1295 (const default))
1296 (boolean)))))
1299 (defcustom org-insert-heading-respect-content nil
1300 "Non-nil means insert new headings after the current subtree.
1301 When nil, the new heading is created directly after the current line.
1302 The commands \\[org-insert-heading-respect-content] and
1303 \\[org-insert-todo-heading-respect-content] turn this variable on
1304 for the duration of the command."
1305 :group 'org-structure
1306 :type 'boolean)
1308 (defcustom org-blank-before-new-entry '((heading . auto)
1309 (plain-list-item . auto))
1310 "Should `org-insert-heading' leave a blank line before new heading/item?
1311 The value is an alist, with `heading' and `plain-list-item' as CAR,
1312 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1313 which case Org will look at the surrounding headings/items and try to
1314 make an intelligent decision whether to insert a blank line or not.
1316 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1317 set, the setting here is ignored and no empty line is inserted, to avoid
1318 breaking the list structure."
1319 :group 'org-edit-structure
1320 :type '(list
1321 (cons (const heading)
1322 (choice (const :tag "Never" nil)
1323 (const :tag "Always" t)
1324 (const :tag "Auto" auto)))
1325 (cons (const plain-list-item)
1326 (choice (const :tag "Never" nil)
1327 (const :tag "Always" t)
1328 (const :tag "Auto" auto)))))
1330 (defcustom org-insert-heading-hook nil
1331 "Hook being run after inserting a new heading."
1332 :group 'org-edit-structure
1333 :type 'hook)
1335 (defcustom org-enable-fixed-width-editor t
1336 "Non-nil means lines starting with \":\" are treated as fixed-width.
1337 This currently only means they are never auto-wrapped.
1338 When nil, such lines will be treated like ordinary lines.
1339 See also the QUOTE keyword."
1340 :group 'org-edit-structure
1341 :type 'boolean)
1343 (defcustom org-goto-auto-isearch t
1344 "Non-nil means typing characters in `org-goto' starts incremental search.
1345 When nil, you can use these keybindings to navigate the buffer:
1347 q Quit the org-goto interface
1348 n Go to the next visible heading
1349 p Go to the previous visible heading
1350 f Go one heading forward on same level
1351 b Go one heading backward on same level
1352 u Go one heading up"
1353 :group 'org-edit-structure
1354 :type 'boolean)
1356 (defgroup org-sparse-trees nil
1357 "Options concerning sparse trees in Org-mode."
1358 :tag "Org Sparse Trees"
1359 :group 'org-structure)
1361 (defcustom org-highlight-sparse-tree-matches t
1362 "Non-nil means highlight all matches that define a sparse tree.
1363 The highlights will automatically disappear the next time the buffer is
1364 changed by an edit command."
1365 :group 'org-sparse-trees
1366 :type 'boolean)
1368 (defcustom org-remove-highlights-with-change t
1369 "Non-nil means any change to the buffer will remove temporary highlights.
1370 Such highlights are created by `org-occur' and `org-clock-display'.
1371 When nil, `C-c C-c needs to be used to get rid of the highlights.
1372 The highlights created by `org-preview-latex-fragment' always need
1373 `C-c C-c' to be removed."
1374 :group 'org-sparse-trees
1375 :group 'org-time
1376 :type 'boolean)
1379 (defcustom org-occur-hook '(org-first-headline-recenter)
1380 "Hook that is run after `org-occur' has constructed a sparse tree.
1381 This can be used to recenter the window to show as much of the structure
1382 as possible."
1383 :group 'org-sparse-trees
1384 :type 'hook)
1386 (defgroup org-imenu-and-speedbar nil
1387 "Options concerning imenu and speedbar in Org-mode."
1388 :tag "Org Imenu and Speedbar"
1389 :group 'org-structure)
1391 (defcustom org-imenu-depth 2
1392 "The maximum level for Imenu access to Org-mode headlines.
1393 This also applied for speedbar access."
1394 :group 'org-imenu-and-speedbar
1395 :type 'integer)
1397 (defgroup org-table nil
1398 "Options concerning tables in Org-mode."
1399 :tag "Org Table"
1400 :group 'org)
1402 (defcustom org-enable-table-editor 'optimized
1403 "Non-nil means lines starting with \"|\" are handled by the table editor.
1404 When nil, such lines will be treated like ordinary lines.
1406 When equal to the symbol `optimized', the table editor will be optimized to
1407 do the following:
1408 - Automatic overwrite mode in front of whitespace in table fields.
1409 This makes the structure of the table stay in tact as long as the edited
1410 field does not exceed the column width.
1411 - Minimize the number of realigns. Normally, the table is aligned each time
1412 TAB or RET are pressed to move to another field. With optimization this
1413 happens only if changes to a field might have changed the column width.
1414 Optimization requires replacing the functions `self-insert-command',
1415 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1416 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1417 very good at guessing when a re-align will be necessary, but you can always
1418 force one with \\[org-ctrl-c-ctrl-c].
1420 If you would like to use the optimized version in Org-mode, but the
1421 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1423 This variable can be used to turn on and off the table editor during a session,
1424 but in order to toggle optimization, a restart is required.
1426 See also the variable `org-table-auto-blank-field'."
1427 :group 'org-table
1428 :type '(choice
1429 (const :tag "off" nil)
1430 (const :tag "on" t)
1431 (const :tag "on, optimized" optimized)))
1433 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1434 (version<= emacs-version "24.1"))
1435 "Non-nil means cluster self-insert commands for undo when possible.
1436 If this is set, then, like in the Emacs command loop, 20 consecutive
1437 characters will be undone together.
1438 This is configurable, because there is some impact on typing performance."
1439 :group 'org-table
1440 :type 'boolean)
1442 (defcustom org-table-tab-recognizes-table.el t
1443 "Non-nil means TAB will automatically notice a table.el table.
1444 When it sees such a table, it moves point into it and - if necessary -
1445 calls `table-recognize-table'."
1446 :group 'org-table-editing
1447 :type 'boolean)
1449 (defgroup org-link nil
1450 "Options concerning links in Org-mode."
1451 :tag "Org Link"
1452 :group 'org)
1454 (defvar org-link-abbrev-alist-local nil
1455 "Buffer-local version of `org-link-abbrev-alist', which see.
1456 The value of this is taken from the #+LINK lines.")
1457 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1459 (defcustom org-link-abbrev-alist nil
1460 "Alist of link abbreviations.
1461 The car of each element is a string, to be replaced at the start of a link.
1462 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1463 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1465 [[linkkey:tag][description]]
1467 The 'linkkey' must be a word word, starting with a letter, followed
1468 by letters, numbers, '-' or '_'.
1470 If REPLACE is a string, the tag will simply be appended to create the link.
1471 If the string contains \"%s\", the tag will be inserted there. If the string
1472 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1473 at that point (see the function `url-hexify-string'). If the string contains
1474 the specifier \"%(my-function)\", then the custom function `my-function' will
1475 be invoked: this function takes the tag as its only argument and must return
1476 a string.
1478 REPLACE may also be a function that will be called with the tag as the
1479 only argument to create the link, which should be returned as a string.
1481 See the manual for examples."
1482 :group 'org-link
1483 :type '(repeat
1484 (cons
1485 (string :tag "Protocol")
1486 (choice
1487 (string :tag "Format")
1488 (function)))))
1490 (defcustom org-descriptive-links t
1491 "Non-nil means Org will display descriptive links.
1492 E.g. [[http://orgmode.org][Org website]] will be displayed as
1493 \"Org Website\", hiding the link itself and just displaying its
1494 description. When set to `nil', Org will display the full links
1495 literally.
1497 You can interactively set the value of this variable by calling
1498 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1499 :group 'org-link
1500 :type 'boolean)
1502 (defcustom org-link-file-path-type 'adaptive
1503 "How the path name in file links should be stored.
1504 Valid values are:
1506 relative Relative to the current directory, i.e. the directory of the file
1507 into which the link is being inserted.
1508 absolute Absolute path, if possible with ~ for home directory.
1509 noabbrev Absolute path, no abbreviation of home directory.
1510 adaptive Use relative path for files in the current directory and sub-
1511 directories of it. For other files, use an absolute path."
1512 :group 'org-link
1513 :type '(choice
1514 (const relative)
1515 (const absolute)
1516 (const noabbrev)
1517 (const adaptive)))
1519 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1520 "Types of links that should be activated in Org-mode files.
1521 This is a list of symbols, each leading to the activation of a certain link
1522 type. In principle, it does not hurt to turn on most link types - there may
1523 be a small gain when turning off unused link types. The types are:
1525 bracket The recommended [[link][description]] or [[link]] links with hiding.
1526 angle Links in angular brackets that may contain whitespace like
1527 <bbdb:Carsten Dominik>.
1528 plain Plain links in normal text, no whitespace, like http://google.com.
1529 radio Text that is matched by a radio target, see manual for details.
1530 tag Tag settings in a headline (link to tag search).
1531 date Time stamps (link to calendar).
1532 footnote Footnote labels.
1534 Changing this variable requires a restart of Emacs to become effective."
1535 :group 'org-link
1536 :type '(set :greedy t
1537 (const :tag "Double bracket links" bracket)
1538 (const :tag "Angular bracket links" angle)
1539 (const :tag "Plain text links" plain)
1540 (const :tag "Radio target matches" radio)
1541 (const :tag "Tags" tag)
1542 (const :tag "Timestamps" date)
1543 (const :tag "Footnotes" footnote)))
1545 (defcustom org-make-link-description-function nil
1546 "Function to use for generating link descriptions from links.
1547 When nil, the link location will be used. This function must take
1548 two parameters: the first one is the link, the second one is the
1549 description generated by `org-insert-link'. The function should
1550 return the description to use."
1551 :group 'org-link
1552 :type 'function)
1554 (defgroup org-link-store nil
1555 "Options concerning storing links in Org-mode."
1556 :tag "Org Store Link"
1557 :group 'org-link)
1559 (defcustom org-url-hexify-p t
1560 "When non-nil, hexify URL when creating a link."
1561 :type 'boolean
1562 :version "24.3"
1563 :group 'org-link-store)
1565 (defcustom org-email-link-description-format "Email %c: %.30s"
1566 "Format of the description part of a link to an email or usenet message.
1567 The following %-escapes will be replaced by corresponding information:
1569 %F full \"From\" field
1570 %f name, taken from \"From\" field, address if no name
1571 %T full \"To\" field
1572 %t first name in \"To\" field, address if no name
1573 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1574 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1575 %s subject
1576 %d date
1577 %m message-id.
1579 You may use normal field width specification between the % and the letter.
1580 This is for example useful to limit the length of the subject.
1582 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1583 :group 'org-link-store
1584 :type 'string)
1586 (defcustom org-from-is-user-regexp
1587 (let (r1 r2)
1588 (when (and user-mail-address (not (string= user-mail-address "")))
1589 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1590 (when (and user-full-name (not (string= user-full-name "")))
1591 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1592 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1593 "Regexp matched against the \"From:\" header of an email or usenet message.
1594 It should match if the message is from the user him/herself."
1595 :group 'org-link-store
1596 :type 'regexp)
1598 (defcustom org-context-in-file-links t
1599 "Non-nil means file links from `org-store-link' contain context.
1600 A search string will be added to the file name with :: as separator and
1601 used to find the context when the link is activated by the command
1602 `org-open-at-point'. When this option is t, the entire active region
1603 will be placed in the search string of the file link. If set to a
1604 positive integer, only the first n lines of context will be stored.
1606 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1607 negates this setting for the duration of the command."
1608 :group 'org-link-store
1609 :type '(choice boolean integer))
1611 (defcustom org-keep-stored-link-after-insertion nil
1612 "Non-nil means keep link in list for entire session.
1614 The command `org-store-link' adds a link pointing to the current
1615 location to an internal list. These links accumulate during a session.
1616 The command `org-insert-link' can be used to insert links into any
1617 Org-mode file (offering completion for all stored links). When this
1618 option is nil, every link which has been inserted once using \\[org-insert-link]
1619 will be removed from the list, to make completing the unused links
1620 more efficient."
1621 :group 'org-link-store
1622 :type 'boolean)
1624 (defgroup org-link-follow nil
1625 "Options concerning following links in Org-mode."
1626 :tag "Org Follow Link"
1627 :group 'org-link)
1629 (defcustom org-link-translation-function nil
1630 "Function to translate links with different syntax to Org syntax.
1631 This can be used to translate links created for example by the Planner
1632 or emacs-wiki packages to Org syntax.
1633 The function must accept two parameters, a TYPE containing the link
1634 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1635 which is everything after the link protocol. It should return a cons
1636 with possibly modified values of type and path.
1637 Org contains a function for this, so if you set this variable to
1638 `org-translate-link-from-planner', you should be able follow many
1639 links created by planner."
1640 :group 'org-link-follow
1641 :type 'function)
1643 (defcustom org-follow-link-hook nil
1644 "Hook that is run after a link has been followed."
1645 :group 'org-link-follow
1646 :type 'hook)
1648 (defcustom org-tab-follows-link nil
1649 "Non-nil means on links TAB will follow the link.
1650 Needs to be set before org.el is loaded.
1651 This really should not be used, it does not make sense, and the
1652 implementation is bad."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-return-follows-link nil
1657 "Non-nil means on links RET will follow the link."
1658 :group 'org-link-follow
1659 :type 'boolean)
1661 (defcustom org-mouse-1-follows-link
1662 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1663 "Non-nil means mouse-1 on a link will follow the link.
1664 A longer mouse click will still set point. Does not work on XEmacs.
1665 Needs to be set before org.el is loaded."
1666 :group 'org-link-follow
1667 :type 'boolean)
1669 (defcustom org-mark-ring-length 4
1670 "Number of different positions to be recorded in the ring.
1671 Changing this requires a restart of Emacs to work correctly."
1672 :group 'org-link-follow
1673 :type 'integer)
1675 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1676 "Non-nil means internal links in Org files must exactly match a headline.
1677 When nil, the link search tries to match a phrase with all words
1678 in the search text."
1679 :group 'org-link-follow
1680 :version "24.1"
1681 :type '(choice
1682 (const :tag "Use fuzzy text search" nil)
1683 (const :tag "Match only exact headline" t)
1684 (const :tag "Match exact headline or query to create it"
1685 query-to-create)))
1687 (defcustom org-link-frame-setup
1688 '((vm . vm-visit-folder-other-frame)
1689 (vm-imap . vm-visit-imap-folder-other-frame)
1690 (gnus . org-gnus-no-new-news)
1691 (file . find-file-other-window)
1692 (wl . wl-other-frame))
1693 "Setup the frame configuration for following links.
1694 When following a link with Emacs, it may often be useful to display
1695 this link in another window or frame. This variable can be used to
1696 set this up for the different types of links.
1697 For VM, use any of
1698 `vm-visit-folder'
1699 `vm-visit-folder-other-window'
1700 `vm-visit-folder-other-frame'
1701 For Gnus, use any of
1702 `gnus'
1703 `gnus-other-frame'
1704 `org-gnus-no-new-news'
1705 For FILE, use any of
1706 `find-file'
1707 `find-file-other-window'
1708 `find-file-other-frame'
1709 For Wanderlust use any of
1710 `wl'
1711 `wl-other-frame'
1712 For the calendar, use the variable `calendar-setup'.
1713 For BBDB, it is currently only possible to display the matches in
1714 another window."
1715 :group 'org-link-follow
1716 :type '(list
1717 (cons (const vm)
1718 (choice
1719 (const vm-visit-folder)
1720 (const vm-visit-folder-other-window)
1721 (const vm-visit-folder-other-frame)))
1722 (cons (const gnus)
1723 (choice
1724 (const gnus)
1725 (const gnus-other-frame)
1726 (const org-gnus-no-new-news)))
1727 (cons (const file)
1728 (choice
1729 (const find-file)
1730 (const find-file-other-window)
1731 (const find-file-other-frame)))
1732 (cons (const wl)
1733 (choice
1734 (const wl)
1735 (const wl-other-frame)))))
1737 (defcustom org-display-internal-link-with-indirect-buffer nil
1738 "Non-nil means use indirect buffer to display infile links.
1739 Activating internal links (from one location in a file to another location
1740 in the same file) normally just jumps to the location. When the link is
1741 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1742 is displayed in
1743 another window. When this option is set, the other window actually displays
1744 an indirect buffer clone of the current buffer, to avoid any visibility
1745 changes to the current buffer."
1746 :group 'org-link-follow
1747 :type 'boolean)
1749 (defcustom org-open-non-existing-files nil
1750 "Non-nil means `org-open-file' will open non-existing files.
1751 When nil, an error will be generated.
1752 This variable applies only to external applications because they
1753 might choke on non-existing files. If the link is to a file that
1754 will be opened in Emacs, the variable is ignored."
1755 :group 'org-link-follow
1756 :type 'boolean)
1758 (defcustom org-open-directory-means-index-dot-org nil
1759 "Non-nil means a link to a directory really means to index.org.
1760 When nil, following a directory link will run dired or open a finder/explorer
1761 window on that directory."
1762 :group 'org-link-follow
1763 :type 'boolean)
1765 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1766 "Function and arguments to call for following mailto links.
1767 This is a list with the first element being a Lisp function, and the
1768 remaining elements being arguments to the function. In string arguments,
1769 %a will be replaced by the address, and %s will be replaced by the subject
1770 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1771 :group 'org-link-follow
1772 :type '(choice
1773 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1774 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1775 (const :tag "message-mail" (message-mail "%a" "%s"))
1776 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1778 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1779 "Non-nil means ask for confirmation before executing shell links.
1780 Shell links can be dangerous: just think about a link
1782 [[shell:rm -rf ~/*][Google Search]]
1784 This link would show up in your Org-mode document as \"Google Search\",
1785 but really it would remove your entire home directory.
1786 Therefore we advise against setting this variable to nil.
1787 Just change it to `y-or-n-p' if you want to confirm with a
1788 single keystroke rather than having to type \"yes\"."
1789 :group 'org-link-follow
1790 :type '(choice
1791 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1792 (const :tag "with y-or-n (faster)" y-or-n-p)
1793 (const :tag "no confirmation (dangerous)" nil)))
1794 (put 'org-confirm-shell-link-function
1795 'safe-local-variable
1796 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1798 (defcustom org-confirm-shell-link-not-regexp ""
1799 "A regexp to skip confirmation for shell links."
1800 :group 'org-link-follow
1801 :version "24.1"
1802 :type 'regexp)
1804 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1805 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1806 Elisp links can be dangerous: just think about a link
1808 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1810 This link would show up in your Org-mode document as \"Google Search\",
1811 but really it would remove your entire home directory.
1812 Therefore we advise against setting this variable to nil.
1813 Just change it to `y-or-n-p' if you want to confirm with a
1814 single keystroke rather than having to type \"yes\"."
1815 :group 'org-link-follow
1816 :type '(choice
1817 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1818 (const :tag "with y-or-n (faster)" y-or-n-p)
1819 (const :tag "no confirmation (dangerous)" nil)))
1820 (put 'org-confirm-shell-link-function
1821 'safe-local-variable
1822 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1824 (defcustom org-confirm-elisp-link-not-regexp ""
1825 "A regexp to skip confirmation for Elisp links."
1826 :group 'org-link-follow
1827 :version "24.1"
1828 :type 'regexp)
1830 (defconst org-file-apps-defaults-gnu
1831 '((remote . emacs)
1832 (system . mailcap)
1833 (t . mailcap))
1834 "Default file applications on a UNIX or GNU/Linux system.
1835 See `org-file-apps'.")
1837 (defconst org-file-apps-defaults-macosx
1838 '((remote . emacs)
1839 (t . "open %s")
1840 (system . "open %s")
1841 ("ps.gz" . "gv %s")
1842 ("eps.gz" . "gv %s")
1843 ("dvi" . "xdvi %s")
1844 ("fig" . "xfig %s"))
1845 "Default file applications on a MacOS X system.
1846 The system \"open\" is known as a default, but we use X11 applications
1847 for some files for which the OS does not have a good default.
1848 See `org-file-apps'.")
1850 (defconst org-file-apps-defaults-windowsnt
1851 (list
1852 '(remote . emacs)
1853 (cons t
1854 (list (if (featurep 'xemacs)
1855 'mswindows-shell-execute
1856 'w32-shell-execute)
1857 "open" 'file))
1858 (cons 'system
1859 (list (if (featurep 'xemacs)
1860 'mswindows-shell-execute
1861 'w32-shell-execute)
1862 "open" 'file)))
1863 "Default file applications on a Windows NT system.
1864 The system \"open\" is used for most files.
1865 See `org-file-apps'.")
1867 (defcustom org-file-apps
1869 (auto-mode . emacs)
1870 ("\\.mm\\'" . default)
1871 ("\\.x?html?\\'" . default)
1872 ("\\.pdf\\'" . default)
1874 "External applications for opening `file:path' items in a document.
1875 Org-mode uses system defaults for different file types, but
1876 you can use this variable to set the application for a given file
1877 extension. The entries in this list are cons cells where the car identifies
1878 files and the cdr the corresponding command. Possible values for the
1879 file identifier are
1880 \"string\" A string as a file identifier can be interpreted in different
1881 ways, depending on its contents:
1883 - Alphanumeric characters only:
1884 Match links with this file extension.
1885 Example: (\"pdf\" . \"evince %s\")
1886 to open PDFs with evince.
1888 - Regular expression: Match links where the
1889 filename matches the regexp. If you want to
1890 use groups here, use shy groups.
1892 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1893 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1894 to open *.html and *.xhtml with firefox.
1896 - Regular expression which contains (non-shy) groups:
1897 Match links where the whole link, including \"::\", and
1898 anything after that, matches the regexp.
1899 In a custom command string, %1, %2, etc. are replaced with
1900 the parts of the link that were matched by the groups.
1901 For backwards compatibility, if a command string is given
1902 that does not use any of the group matches, this case is
1903 handled identically to the second one (i.e. match against
1904 file name only).
1905 In a custom lisp form, you can access the group matches with
1906 (match-string n link).
1908 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1909 to open [[file:document.pdf::5]] with evince at page 5.
1911 `directory' Matches a directory
1912 `remote' Matches a remote file, accessible through tramp or efs.
1913 Remote files most likely should be visited through Emacs
1914 because external applications cannot handle such paths.
1915 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1916 so all files Emacs knows how to handle. Using this with
1917 command `emacs' will open most files in Emacs. Beware that this
1918 will also open html files inside Emacs, unless you add
1919 (\"html\" . default) to the list as well.
1920 t Default for files not matched by any of the other options.
1921 `system' The system command to open files, like `open' on Windows
1922 and Mac OS X, and mailcap under GNU/Linux. This is the command
1923 that will be selected if you call `C-c C-o' with a double
1924 \\[universal-argument] \\[universal-argument] prefix.
1926 Possible values for the command are:
1927 `emacs' The file will be visited by the current Emacs process.
1928 `default' Use the default application for this file type, which is the
1929 association for t in the list, most likely in the system-specific
1930 part.
1931 This can be used to overrule an unwanted setting in the
1932 system-specific variable.
1933 `system' Use the system command for opening files, like \"open\".
1934 This command is specified by the entry whose car is `system'.
1935 Most likely, the system-specific version of this variable
1936 does define this command, but you can overrule/replace it
1937 here.
1938 string A command to be executed by a shell; %s will be replaced
1939 by the path to the file.
1940 sexp A Lisp form which will be evaluated. The file path will
1941 be available in the Lisp variable `file'.
1942 For more examples, see the system specific constants
1943 `org-file-apps-defaults-macosx'
1944 `org-file-apps-defaults-windowsnt'
1945 `org-file-apps-defaults-gnu'."
1946 :group 'org-link-follow
1947 :type '(repeat
1948 (cons (choice :value ""
1949 (string :tag "Extension")
1950 (const :tag "System command to open files" system)
1951 (const :tag "Default for unrecognized files" t)
1952 (const :tag "Remote file" remote)
1953 (const :tag "Links to a directory" directory)
1954 (const :tag "Any files that have Emacs modes"
1955 auto-mode))
1956 (choice :value ""
1957 (const :tag "Visit with Emacs" emacs)
1958 (const :tag "Use default" default)
1959 (const :tag "Use the system command" system)
1960 (string :tag "Command")
1961 (sexp :tag "Lisp form")))))
1963 (defcustom org-doi-server-url "http://dx.doi.org/"
1964 "The URL of the DOI server."
1965 :type 'string
1966 :version "24.3"
1967 :group 'org-link-follow)
1969 (defgroup org-refile nil
1970 "Options concerning refiling entries in Org-mode."
1971 :tag "Org Refile"
1972 :group 'org)
1974 (defcustom org-directory "~/org"
1975 "Directory with org files.
1976 This is just a default location to look for Org files. There is no need
1977 at all to put your files into this directory. It is only used in the
1978 following situations:
1980 1. When a capture template specifies a target file that is not an
1981 absolute path. The path will then be interpreted relative to
1982 `org-directory'
1983 2. When a capture note is filed away in an interactive way (when exiting the
1984 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1985 with `org-directory' as the default path."
1986 :group 'org-refile
1987 :group 'org-remember
1988 :group 'org-capture
1989 :type 'directory)
1991 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1992 "Default target for storing notes.
1993 Used as a fall back file for org-remember.el and org-capture.el, for
1994 templates that do not specify a target file."
1995 :group 'org-refile
1996 :group 'org-remember
1997 :group 'org-capture
1998 :type '(choice
1999 (const :tag "Default from remember-data-file" nil)
2000 file))
2002 (defcustom org-goto-interface 'outline
2003 "The default interface to be used for `org-goto'.
2004 Allowed values are:
2005 outline The interface shows an outline of the relevant file
2006 and the correct heading is found by moving through
2007 the outline or by searching with incremental search.
2008 outline-path-completion Headlines in the current buffer are offered via
2009 completion. This is the interface also used by
2010 the refile command."
2011 :group 'org-refile
2012 :type '(choice
2013 (const :tag "Outline" outline)
2014 (const :tag "Outline-path-completion" outline-path-completion)))
2016 (defcustom org-goto-max-level 5
2017 "Maximum target level when running `org-goto' with refile interface."
2018 :group 'org-refile
2019 :type 'integer)
2021 (defcustom org-reverse-note-order nil
2022 "Non-nil means store new notes at the beginning of a file or entry.
2023 When nil, new notes will be filed to the end of a file or entry.
2024 This can also be a list with cons cells of regular expressions that
2025 are matched against file names, and values."
2026 :group 'org-remember
2027 :group 'org-capture
2028 :group 'org-refile
2029 :type '(choice
2030 (const :tag "Reverse always" t)
2031 (const :tag "Reverse never" nil)
2032 (repeat :tag "By file name regexp"
2033 (cons regexp boolean))))
2035 (defcustom org-log-refile nil
2036 "Information to record when a task is refiled.
2038 Possible values are:
2040 nil Don't add anything
2041 time Add a time stamp to the task
2042 note Prompt for a note and add it with template `org-log-note-headings'
2044 This option can also be set with on a per-file-basis with
2046 #+STARTUP: nologrefile
2047 #+STARTUP: logrefile
2048 #+STARTUP: lognoterefile
2050 You can have local logging settings for a subtree by setting the LOGGING
2051 property to one or more of these keywords.
2053 When bulk-refiling from the agenda, the value `note' is forbidden and
2054 will temporarily be changed to `time'."
2055 :group 'org-refile
2056 :group 'org-progress
2057 :version "24.1"
2058 :type '(choice
2059 (const :tag "No logging" nil)
2060 (const :tag "Record timestamp" time)
2061 (const :tag "Record timestamp with note." note)))
2063 (defcustom org-refile-targets nil
2064 "Targets for refiling entries with \\[org-refile].
2065 This is a list of cons cells. Each cell contains:
2066 - a specification of the files to be considered, either a list of files,
2067 or a symbol whose function or variable value will be used to retrieve
2068 a file name or a list of file names. If you use `org-agenda-files' for
2069 that, all agenda files will be scanned for targets. Nil means consider
2070 headings in the current buffer.
2071 - A specification of how to find candidate refile targets. This may be
2072 any of:
2073 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2074 This tag has to be present in all target headlines, inheritance will
2075 not be considered.
2076 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2077 todo keyword.
2078 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2079 headlines that are refiling targets.
2080 - a cons cell (:level . N). Any headline of level N is considered a target.
2081 Note that, when `org-odd-levels-only' is set, level corresponds to
2082 order in hierarchy, not to the number of stars.
2083 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2084 Note that, when `org-odd-levels-only' is set, level corresponds to
2085 order in hierarchy, not to the number of stars.
2087 Each element of this list generates a set of possible targets.
2088 The union of these sets is presented (with completion) to
2089 the user by `org-refile'.
2091 You can set the variable `org-refile-target-verify-function' to a function
2092 to verify each headline found by the simple criteria above.
2094 When this variable is nil, all top-level headlines in the current buffer
2095 are used, equivalent to the value `((nil . (:level . 1))'."
2096 :group 'org-refile
2097 :type '(repeat
2098 (cons
2099 (choice :value org-agenda-files
2100 (const :tag "All agenda files" org-agenda-files)
2101 (const :tag "Current buffer" nil)
2102 (function) (variable) (file))
2103 (choice :tag "Identify target headline by"
2104 (cons :tag "Specific tag" (const :value :tag) (string))
2105 (cons :tag "TODO keyword" (const :value :todo) (string))
2106 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2107 (cons :tag "Level number" (const :value :level) (integer))
2108 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2110 (defcustom org-refile-target-verify-function nil
2111 "Function to verify if the headline at point should be a refile target.
2112 The function will be called without arguments, with point at the
2113 beginning of the headline. It should return t and leave point
2114 where it is if the headline is a valid target for refiling.
2116 If the target should not be selected, the function must return nil.
2117 In addition to this, it may move point to a place from where the search
2118 should be continued. For example, the function may decide that the entire
2119 subtree of the current entry should be excluded and move point to the end
2120 of the subtree."
2121 :group 'org-refile
2122 :type 'function)
2124 (defcustom org-refile-use-cache nil
2125 "Non-nil means cache refile targets to speed up the process.
2126 The cache for a particular file will be updated automatically when
2127 the buffer has been killed, or when any of the marker used for flagging
2128 refile targets no longer points at a live buffer.
2129 If you have added new entries to a buffer that might themselves be targets,
2130 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2131 find that easier, `C-u C-u C-u C-c C-w'."
2132 :group 'org-refile
2133 :version "24.1"
2134 :type 'boolean)
2136 (defcustom org-refile-use-outline-path nil
2137 "Non-nil means provide refile targets as paths.
2138 So a level 3 headline will be available as level1/level2/level3.
2140 When the value is `file', also include the file name (without directory)
2141 into the path. In this case, you can also stop the completion after
2142 the file name, to get entries inserted as top level in the file.
2144 When `full-file-path', include the full file path."
2145 :group 'org-refile
2146 :type '(choice
2147 (const :tag "Not" nil)
2148 (const :tag "Yes" t)
2149 (const :tag "Start with file name" file)
2150 (const :tag "Start with full file path" full-file-path)))
2152 (defcustom org-outline-path-complete-in-steps t
2153 "Non-nil means complete the outline path in hierarchical steps.
2154 When Org-mode uses the refile interface to select an outline path
2155 \(see variable `org-refile-use-outline-path'), the completion of
2156 the path can be done is a single go, or if can be done in steps down
2157 the headline hierarchy. Going in steps is probably the best if you
2158 do not use a special completion package like `ido' or `icicles'.
2159 However, when using these packages, going in one step can be very
2160 fast, while still showing the whole path to the entry."
2161 :group 'org-refile
2162 :type 'boolean)
2164 (defcustom org-refile-allow-creating-parent-nodes nil
2165 "Non-nil means allow to create new nodes as refile targets.
2166 New nodes are then created by adding \"/new node name\" to the completion
2167 of an existing node. When the value of this variable is `confirm',
2168 new node creation must be confirmed by the user (recommended)
2169 When nil, the completion must match an existing entry.
2171 Note that, if the new heading is not seen by the criteria
2172 listed in `org-refile-targets', multiple instances of the same
2173 heading would be created by trying again to file under the new
2174 heading."
2175 :group 'org-refile
2176 :type '(choice
2177 (const :tag "Never" nil)
2178 (const :tag "Always" t)
2179 (const :tag "Prompt for confirmation" confirm)))
2181 (defcustom org-refile-active-region-within-subtree nil
2182 "Non-nil means also refile active region within a subtree.
2184 By default `org-refile' doesn't allow refiling regions if they
2185 don't contain a set of subtrees, but it might be convenient to
2186 do so sometimes: in that case, the first line of the region is
2187 converted to a headline before refiling."
2188 :group 'org-refile
2189 :version "24.1"
2190 :type 'boolean)
2192 (defgroup org-todo nil
2193 "Options concerning TODO items in Org-mode."
2194 :tag "Org TODO"
2195 :group 'org)
2197 (defgroup org-progress nil
2198 "Options concerning Progress logging in Org-mode."
2199 :tag "Org Progress"
2200 :group 'org-time)
2202 (defvar org-todo-interpretation-widgets
2203 '((:tag "Sequence (cycling hits every state)" sequence)
2204 (:tag "Type (cycling directly to DONE)" type))
2205 "The available interpretation symbols for customizing `org-todo-keywords'.
2206 Interested libraries should add to this list.")
2208 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2209 "List of TODO entry keyword sequences and their interpretation.
2210 \\<org-mode-map>This is a list of sequences.
2212 Each sequence starts with a symbol, either `sequence' or `type',
2213 indicating if the keywords should be interpreted as a sequence of
2214 action steps, or as different types of TODO items. The first
2215 keywords are states requiring action - these states will select a headline
2216 for inclusion into the global TODO list Org-mode produces. If one of
2217 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2218 signify that no further action is necessary. If \"|\" is not found,
2219 the last keyword is treated as the only DONE state of the sequence.
2221 The command \\[org-todo] cycles an entry through these states, and one
2222 additional state where no keyword is present. For details about this
2223 cycling, see the manual.
2225 TODO keywords and interpretation can also be set on a per-file basis with
2226 the special #+SEQ_TODO and #+TYP_TODO lines.
2228 Each keyword can optionally specify a character for fast state selection
2229 \(in combination with the variable `org-use-fast-todo-selection')
2230 and specifiers for state change logging, using the same syntax that
2231 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2232 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2233 indicates to record a time stamp each time this state is selected.
2235 Each keyword may also specify if a timestamp or a note should be
2236 recorded when entering or leaving the state, by adding additional
2237 characters in the parenthesis after the keyword. This looks like this:
2238 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2239 record only the time of the state change. With X and Y being either
2240 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2241 Y when leaving the state if and only if the *target* state does not
2242 define X. You may omit any of the fast-selection key or X or /Y,
2243 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2245 For backward compatibility, this variable may also be just a list
2246 of keywords. In this case the interpretation (sequence or type) will be
2247 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2248 :group 'org-todo
2249 :group 'org-keywords
2250 :type '(choice
2251 (repeat :tag "Old syntax, just keywords"
2252 (string :tag "Keyword"))
2253 (repeat :tag "New syntax"
2254 (cons
2255 (choice
2256 :tag "Interpretation"
2257 ;;Quick and dirty way to see
2258 ;;`org-todo-interpretations'. This takes the
2259 ;;place of item arguments
2260 :convert-widget
2261 (lambda (widget)
2262 (widget-put widget
2263 :args (mapcar
2264 #'(lambda (x)
2265 (widget-convert
2266 (cons 'const x)))
2267 org-todo-interpretation-widgets))
2268 widget))
2269 (repeat
2270 (string :tag "Keyword"))))))
2272 (defvar org-todo-keywords-1 nil
2273 "All TODO and DONE keywords active in a buffer.")
2274 (make-variable-buffer-local 'org-todo-keywords-1)
2275 (defvar org-todo-keywords-for-agenda nil)
2276 (defvar org-done-keywords-for-agenda nil)
2277 (defvar org-drawers-for-agenda nil)
2278 (defvar org-todo-keyword-alist-for-agenda nil)
2279 (defvar org-tag-alist-for-agenda nil)
2280 (defvar org-agenda-contributing-files nil)
2281 (defvar org-not-done-keywords nil)
2282 (make-variable-buffer-local 'org-not-done-keywords)
2283 (defvar org-done-keywords nil)
2284 (make-variable-buffer-local 'org-done-keywords)
2285 (defvar org-todo-heads nil)
2286 (make-variable-buffer-local 'org-todo-heads)
2287 (defvar org-todo-sets nil)
2288 (make-variable-buffer-local 'org-todo-sets)
2289 (defvar org-todo-log-states nil)
2290 (make-variable-buffer-local 'org-todo-log-states)
2291 (defvar org-todo-kwd-alist nil)
2292 (make-variable-buffer-local 'org-todo-kwd-alist)
2293 (defvar org-todo-key-alist nil)
2294 (make-variable-buffer-local 'org-todo-key-alist)
2295 (defvar org-todo-key-trigger nil)
2296 (make-variable-buffer-local 'org-todo-key-trigger)
2298 (defcustom org-todo-interpretation 'sequence
2299 "Controls how TODO keywords are interpreted.
2300 This variable is in principle obsolete and is only used for
2301 backward compatibility, if the interpretation of todo keywords is
2302 not given already in `org-todo-keywords'. See that variable for
2303 more information."
2304 :group 'org-todo
2305 :group 'org-keywords
2306 :type '(choice (const sequence)
2307 (const type)))
2309 (defcustom org-use-fast-todo-selection t
2310 "Non-nil means use the fast todo selection scheme with C-c C-t.
2311 This variable describes if and under what circumstances the cycling
2312 mechanism for TODO keywords will be replaced by a single-key, direct
2313 selection scheme.
2315 When nil, fast selection is never used.
2317 When the symbol `prefix', it will be used when `org-todo' is called
2318 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2319 `C-u t' in an agenda buffer.
2321 When t, fast selection is used by default. In this case, the prefix
2322 argument forces cycling instead.
2324 In all cases, the special interface is only used if access keys have
2325 actually been assigned by the user, i.e. if keywords in the configuration
2326 are followed by a letter in parenthesis, like TODO(t)."
2327 :group 'org-todo
2328 :type '(choice
2329 (const :tag "Never" nil)
2330 (const :tag "By default" t)
2331 (const :tag "Only with C-u C-c C-t" prefix)))
2333 (defcustom org-provide-todo-statistics t
2334 "Non-nil means update todo statistics after insert and toggle.
2335 ALL-HEADLINES means update todo statistics by including headlines
2336 with no TODO keyword as well, counting them as not done.
2337 A list of TODO keywords means the same, but skip keywords that are
2338 not in this list.
2340 When this is set, todo statistics is updated in the parent of the
2341 current entry each time a todo state is changed."
2342 :group 'org-todo
2343 :type '(choice
2344 (const :tag "Yes, only for TODO entries" t)
2345 (const :tag "Yes, including all entries" 'all-headlines)
2346 (repeat :tag "Yes, for TODOs in this list"
2347 (string :tag "TODO keyword"))
2348 (other :tag "No TODO statistics" nil)))
2350 (defcustom org-hierarchical-todo-statistics t
2351 "Non-nil means TODO statistics covers just direct children.
2352 When nil, all entries in the subtree are considered.
2353 This has only an effect if `org-provide-todo-statistics' is set.
2354 To set this to nil for only a single subtree, use a COOKIE_DATA
2355 property and include the word \"recursive\" into the value."
2356 :group 'org-todo
2357 :type 'boolean)
2359 (defcustom org-after-todo-state-change-hook nil
2360 "Hook which is run after the state of a TODO item was changed.
2361 The new state (a string with a TODO keyword, or nil) is available in the
2362 Lisp variable `org-state'."
2363 :group 'org-todo
2364 :type 'hook)
2366 (defvar org-blocker-hook nil
2367 "Hook for functions that are allowed to block a state change.
2369 Functions in this hook should not modify the buffer.
2370 Each function gets as its single argument a property list,
2371 see `org-trigger-hook' for more information about this list.
2373 If any of the functions in this hook returns nil, the state change
2374 is blocked.")
2376 (defvar org-trigger-hook nil
2377 "Hook for functions that are triggered by a state change.
2379 Each function gets as its single argument a property list with at
2380 least the following elements:
2382 (:type type-of-change :position pos-at-entry-start
2383 :from old-state :to new-state)
2385 Depending on the type, more properties may be present.
2387 This mechanism is currently implemented for:
2389 TODO state changes
2390 ------------------
2391 :type todo-state-change
2392 :from previous state (keyword as a string), or nil, or a symbol
2393 'todo' or 'done', to indicate the general type of state.
2394 :to new state, like in :from")
2396 (defcustom org-enforce-todo-dependencies nil
2397 "Non-nil means undone TODO entries will block switching the parent to DONE.
2398 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2399 be blocked if any prior sibling is not yet done.
2400 Finally, if the parent is blocked because of ordered siblings of its own,
2401 the child will also be blocked."
2402 :set (lambda (var val)
2403 (set var val)
2404 (if val
2405 (add-hook 'org-blocker-hook
2406 'org-block-todo-from-children-or-siblings-or-parent)
2407 (remove-hook 'org-blocker-hook
2408 'org-block-todo-from-children-or-siblings-or-parent)))
2409 :group 'org-todo
2410 :type 'boolean)
2412 (defcustom org-enforce-todo-checkbox-dependencies nil
2413 "Non-nil means unchecked boxes will block switching the parent to DONE.
2414 When this is nil, checkboxes have no influence on switching TODO states.
2415 When non-nil, you first need to check off all check boxes before the TODO
2416 entry can be switched to DONE.
2417 This variable needs to be set before org.el is loaded, and you need to
2418 restart Emacs after a change to make the change effective. The only way
2419 to change is while Emacs is running is through the customize interface."
2420 :set (lambda (var val)
2421 (set var val)
2422 (if val
2423 (add-hook 'org-blocker-hook
2424 'org-block-todo-from-checkboxes)
2425 (remove-hook 'org-blocker-hook
2426 'org-block-todo-from-checkboxes)))
2427 :group 'org-todo
2428 :type 'boolean)
2430 (defcustom org-treat-insert-todo-heading-as-state-change nil
2431 "Non-nil means inserting a TODO heading is treated as state change.
2432 So when the command \\[org-insert-todo-heading] is used, state change
2433 logging will apply if appropriate. When nil, the new TODO item will
2434 be inserted directly, and no logging will take place."
2435 :group 'org-todo
2436 :type 'boolean)
2438 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2439 "Non-nil means switching TODO states with S-cursor counts as state change.
2440 This is the default behavior. However, setting this to nil allows a
2441 convenient way to select a TODO state and bypass any logging associated
2442 with that."
2443 :group 'org-todo
2444 :type 'boolean)
2446 (defcustom org-todo-state-tags-triggers nil
2447 "Tag changes that should be triggered by TODO state changes.
2448 This is a list. Each entry is
2450 (state-change (tag . flag) .......)
2452 State-change can be a string with a state, and empty string to indicate the
2453 state that has no TODO keyword, or it can be one of the symbols `todo'
2454 or `done', meaning any not-done or done state, respectively."
2455 :group 'org-todo
2456 :group 'org-tags
2457 :type '(repeat
2458 (cons (choice :tag "When changing to"
2459 (const :tag "Not-done state" todo)
2460 (const :tag "Done state" done)
2461 (string :tag "State"))
2462 (repeat
2463 (cons :tag "Tag action"
2464 (string :tag "Tag")
2465 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2467 (defcustom org-log-done nil
2468 "Information to record when a task moves to the DONE state.
2470 Possible values are:
2472 nil Don't add anything, just change the keyword
2473 time Add a time stamp to the task
2474 note Prompt for a note and add it with template `org-log-note-headings'
2476 This option can also be set with on a per-file-basis with
2478 #+STARTUP: nologdone
2479 #+STARTUP: logdone
2480 #+STARTUP: lognotedone
2482 You can have local logging settings for a subtree by setting the LOGGING
2483 property to one or more of these keywords."
2484 :group 'org-todo
2485 :group 'org-progress
2486 :type '(choice
2487 (const :tag "No logging" nil)
2488 (const :tag "Record CLOSED timestamp" time)
2489 (const :tag "Record CLOSED timestamp with note." note)))
2491 ;; Normalize old uses of org-log-done.
2492 (cond
2493 ((eq org-log-done t) (setq org-log-done 'time))
2494 ((and (listp org-log-done) (memq 'done org-log-done))
2495 (setq org-log-done 'note)))
2497 (defcustom org-log-reschedule nil
2498 "Information to record when the scheduling date of a tasks is modified.
2500 Possible values are:
2502 nil Don't add anything, just change the date
2503 time Add a time stamp to the task
2504 note Prompt for a note and add it with template `org-log-note-headings'
2506 This option can also be set with on a per-file-basis with
2508 #+STARTUP: nologreschedule
2509 #+STARTUP: logreschedule
2510 #+STARTUP: lognotereschedule"
2511 :group 'org-todo
2512 :group 'org-progress
2513 :type '(choice
2514 (const :tag "No logging" nil)
2515 (const :tag "Record timestamp" time)
2516 (const :tag "Record timestamp with note." note)))
2518 (defcustom org-log-redeadline nil
2519 "Information to record when the deadline date of a tasks is modified.
2521 Possible values are:
2523 nil Don't add anything, just change the date
2524 time Add a time stamp to the task
2525 note Prompt for a note and add it with template `org-log-note-headings'
2527 This option can also be set with on a per-file-basis with
2529 #+STARTUP: nologredeadline
2530 #+STARTUP: logredeadline
2531 #+STARTUP: lognoteredeadline
2533 You can have local logging settings for a subtree by setting the LOGGING
2534 property to one or more of these keywords."
2535 :group 'org-todo
2536 :group 'org-progress
2537 :type '(choice
2538 (const :tag "No logging" nil)
2539 (const :tag "Record timestamp" time)
2540 (const :tag "Record timestamp with note." note)))
2542 (defcustom org-log-note-clock-out nil
2543 "Non-nil means record a note when clocking out of an item.
2544 This can also be configured on a per-file basis by adding one of
2545 the following lines anywhere in the buffer:
2547 #+STARTUP: lognoteclock-out
2548 #+STARTUP: nolognoteclock-out"
2549 :group 'org-todo
2550 :group 'org-progress
2551 :type 'boolean)
2553 (defcustom org-log-done-with-time t
2554 "Non-nil means the CLOSED time stamp will contain date and time.
2555 When nil, only the date will be recorded."
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-note-headings
2560 '((done . "CLOSING NOTE %t")
2561 (state . "State %-12s from %-12S %t")
2562 (note . "Note taken on %t")
2563 (reschedule . "Rescheduled from %S on %t")
2564 (delschedule . "Not scheduled, was %S on %t")
2565 (redeadline . "New deadline from %S on %t")
2566 (deldeadline . "Removed deadline, was %S on %t")
2567 (refile . "Refiled on %t")
2568 (clock-out . ""))
2569 "Headings for notes added to entries.
2570 The value is an alist, with the car being a symbol indicating the note
2571 context, and the cdr is the heading to be used. The heading may also be the
2572 empty string.
2573 %t in the heading will be replaced by a time stamp.
2574 %T will be an active time stamp instead the default inactive one
2575 %d will be replaced by a short-format time stamp.
2576 %D will be replaced by an active short-format time stamp.
2577 %s will be replaced by the new TODO state, in double quotes.
2578 %S will be replaced by the old TODO state, in double quotes.
2579 %u will be replaced by the user name.
2580 %U will be replaced by the full user name.
2582 In fact, it is not a good idea to change the `state' entry, because
2583 agenda log mode depends on the format of these entries."
2584 :group 'org-todo
2585 :group 'org-progress
2586 :type '(list :greedy t
2587 (cons (const :tag "Heading when closing an item" done) string)
2588 (cons (const :tag
2589 "Heading when changing todo state (todo sequence only)"
2590 state) string)
2591 (cons (const :tag "Heading when just taking a note" note) string)
2592 (cons (const :tag "Heading when clocking out" clock-out) string)
2593 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2594 (cons (const :tag "Heading when rescheduling" reschedule) string)
2595 (cons (const :tag "Heading when changing deadline" redeadline) string)
2596 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2597 (cons (const :tag "Heading when refiling" refile) string)))
2599 (unless (assq 'note org-log-note-headings)
2600 (push '(note . "%t") org-log-note-headings))
2602 (defcustom org-log-into-drawer nil
2603 "Non-nil means insert state change notes and time stamps into a drawer.
2604 When nil, state changes notes will be inserted after the headline and
2605 any scheduling and clock lines, but not inside a drawer.
2607 The value of this variable should be the name of the drawer to use.
2608 LOGBOOK is proposed as the default drawer for this purpose, you can
2609 also set this to a string to define the drawer of your choice.
2611 A value of t is also allowed, representing \"LOGBOOK\".
2613 A value of t or nil can also be set with on a per-file-basis with
2615 #+STARTUP: logdrawer
2616 #+STARTUP: nologdrawer
2618 If this variable is set, `org-log-state-notes-insert-after-drawers'
2619 will be ignored.
2621 You can set the property LOG_INTO_DRAWER to overrule this setting for
2622 a subtree."
2623 :group 'org-todo
2624 :group 'org-progress
2625 :type '(choice
2626 (const :tag "Not into a drawer" nil)
2627 (const :tag "LOGBOOK" t)
2628 (string :tag "Other")))
2630 (if (fboundp 'defvaralias)
2631 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2633 (defun org-log-into-drawer ()
2634 "Return the value of `org-log-into-drawer', but let properties overrule.
2635 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2636 used instead of the default value."
2637 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2638 (cond
2639 ((not p) org-log-into-drawer)
2640 ((equal p "nil") nil)
2641 ((equal p "t") "LOGBOOK")
2642 (t p))))
2644 (defcustom org-log-state-notes-insert-after-drawers nil
2645 "Non-nil means insert state change notes after any drawers in entry.
2646 Only the drawers that *immediately* follow the headline and the
2647 deadline/scheduled line are skipped.
2648 When nil, insert notes right after the heading and perhaps the line
2649 with deadline/scheduling if present.
2651 This variable will have no effect if `org-log-into-drawer' is
2652 set."
2653 :group 'org-todo
2654 :group 'org-progress
2655 :type 'boolean)
2657 (defcustom org-log-states-order-reversed t
2658 "Non-nil means the latest state note will be directly after heading.
2659 When nil, the state change notes will be ordered according to time.
2661 This option can also be set with on a per-file-basis with
2663 #+STARTUP: logstatesreversed
2664 #+STARTUP: nologstatesreversed"
2665 :group 'org-todo
2666 :group 'org-progress
2667 :type 'boolean)
2669 (defcustom org-todo-repeat-to-state nil
2670 "The TODO state to which a repeater should return the repeating task.
2671 By default this is the first task in a TODO sequence, or the previous state
2672 in a TODO_TYP set. But you can specify another task here.
2673 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2674 :group 'org-todo
2675 :version "24.1"
2676 :type '(choice (const :tag "Head of sequence" nil)
2677 (string :tag "Specific state")))
2679 (defcustom org-log-repeat 'time
2680 "Non-nil means record moving through the DONE state when triggering repeat.
2681 An auto-repeating task is immediately switched back to TODO when
2682 marked DONE. If you are not logging state changes (by adding \"@\"
2683 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2684 record a closing note, there will be no record of the task moving
2685 through DONE. This variable forces taking a note anyway.
2687 nil Don't force a record
2688 time Record a time stamp
2689 note Prompt for a note and add it with template `org-log-note-headings'
2691 This option can also be set with on a per-file-basis with
2693 #+STARTUP: nologrepeat
2694 #+STARTUP: logrepeat
2695 #+STARTUP: lognoterepeat
2697 You can have local logging settings for a subtree by setting the LOGGING
2698 property to one or more of these keywords."
2699 :group 'org-todo
2700 :group 'org-progress
2701 :type '(choice
2702 (const :tag "Don't force a record" nil)
2703 (const :tag "Force recording the DONE state" time)
2704 (const :tag "Force recording a note with the DONE state" note)))
2707 (defgroup org-priorities nil
2708 "Priorities in Org-mode."
2709 :tag "Org Priorities"
2710 :group 'org-todo)
2712 (defcustom org-enable-priority-commands t
2713 "Non-nil means priority commands are active.
2714 When nil, these commands will be disabled, so that you never accidentally
2715 set a priority."
2716 :group 'org-priorities
2717 :type 'boolean)
2719 (defcustom org-highest-priority ?A
2720 "The highest priority of TODO items. A character like ?A, ?B etc.
2721 Must have a smaller ASCII number than `org-lowest-priority'."
2722 :group 'org-priorities
2723 :type 'character)
2725 (defcustom org-lowest-priority ?C
2726 "The lowest priority of TODO items. A character like ?A, ?B etc.
2727 Must have a larger ASCII number than `org-highest-priority'."
2728 :group 'org-priorities
2729 :type 'character)
2731 (defcustom org-default-priority ?B
2732 "The default priority of TODO items.
2733 This is the priority an item gets if no explicit priority is given.
2734 When starting to cycle on an empty priority the first step in the cycle
2735 depends on `org-priority-start-cycle-with-default'. The resulting first
2736 step priority must not exceed the range from `org-highest-priority' to
2737 `org-lowest-priority' which means that `org-default-priority' has to be
2738 in this range exclusive or inclusive the range boundaries. Else the
2739 first step refuses to set the default and the second will fall back
2740 to (depending on the command used) the highest or lowest priority."
2741 :group 'org-priorities
2742 :type 'character)
2744 (defcustom org-priority-start-cycle-with-default t
2745 "Non-nil means start with default priority when starting to cycle.
2746 When this is nil, the first step in the cycle will be (depending on the
2747 command used) one higher or lower than the default priority.
2748 See also `org-default-priority'."
2749 :group 'org-priorities
2750 :type 'boolean)
2752 (defcustom org-get-priority-function nil
2753 "Function to extract the priority from a string.
2754 The string is normally the headline. If this is nil Org computes the
2755 priority from the priority cookie like [#A] in the headline. It returns
2756 an integer, increasing by 1000 for each priority level.
2757 The user can set a different function here, which should take a string
2758 as an argument and return the numeric priority."
2759 :group 'org-priorities
2760 :version "24.1"
2761 :type 'function)
2763 (defgroup org-time nil
2764 "Options concerning time stamps and deadlines in Org-mode."
2765 :tag "Org Time"
2766 :group 'org)
2768 (defcustom org-insert-labeled-timestamps-at-point nil
2769 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2770 When nil, these labeled time stamps are forces into the second line of an
2771 entry, just after the headline. When scheduling from the global TODO list,
2772 the time stamp will always be forced into the second line."
2773 :group 'org-time
2774 :type 'boolean)
2776 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2777 "Formats for `format-time-string' which are used for time stamps.
2778 It is not recommended to change this constant.")
2780 (defcustom org-time-stamp-rounding-minutes '(0 5)
2781 "Number of minutes to round time stamps to.
2782 These are two values, the first applies when first creating a time stamp.
2783 The second applies when changing it with the commands `S-up' and `S-down'.
2784 When changing the time stamp, this means that it will change in steps
2785 of N minutes, as given by the second value.
2787 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2788 numbers should be factors of 60, so for example 5, 10, 15.
2790 When this is larger than 1, you can still force an exact time stamp by using
2791 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2792 and by using a prefix arg to `S-up/down' to specify the exact number
2793 of minutes to shift."
2794 :group 'org-time
2795 :get #'(lambda (var) ; Make sure both elements are there
2796 (if (integerp (default-value var))
2797 (list (default-value var) 5)
2798 (default-value var)))
2799 :type '(list
2800 (integer :tag "when inserting times")
2801 (integer :tag "when modifying times")))
2803 ;; Normalize old customizations of this variable.
2804 (when (integerp org-time-stamp-rounding-minutes)
2805 (setq org-time-stamp-rounding-minutes
2806 (list org-time-stamp-rounding-minutes
2807 org-time-stamp-rounding-minutes)))
2809 (defcustom org-display-custom-times nil
2810 "Non-nil means overlay custom formats over all time stamps.
2811 The formats are defined through the variable `org-time-stamp-custom-formats'.
2812 To turn this on on a per-file basis, insert anywhere in the file:
2813 #+STARTUP: customtime"
2814 :group 'org-time
2815 :set 'set-default
2816 :type 'sexp)
2817 (make-variable-buffer-local 'org-display-custom-times)
2819 (defcustom org-time-stamp-custom-formats
2820 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2821 "Custom formats for time stamps. See `format-time-string' for the syntax.
2822 These are overlaid over the default ISO format if the variable
2823 `org-display-custom-times' is set. Time like %H:%M should be at the
2824 end of the second format. The custom formats are also honored by export
2825 commands, if custom time display is turned on at the time of export."
2826 :group 'org-time
2827 :type 'sexp)
2829 (defun org-time-stamp-format (&optional long inactive)
2830 "Get the right format for a time string."
2831 (let ((f (if long (cdr org-time-stamp-formats)
2832 (car org-time-stamp-formats))))
2833 (if inactive
2834 (concat "[" (substring f 1 -1) "]")
2835 f)))
2837 (defcustom org-time-clocksum-format
2838 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2839 "The format string used when creating CLOCKSUM lines.
2840 This is also used when Org mode generates a time duration.
2842 The value can be a single format string containing two
2843 %-sequences, which will be filled with the number of hours and
2844 minutes in that order.
2846 Alternatively, the value can be a plist associating any of the
2847 keys :years, :months, :weeks, :days, :hours or :minutes with
2848 format strings. The time duration is formatted using only the
2849 time components that are needed and concatenating the results.
2850 If a time unit in absent, it falls back to the next smallest
2851 unit.
2853 The keys :require-years, :require-months, :require-days,
2854 :require-weeks, :require-hours, :require-minutes are also
2855 meaningful. A non-nil value for these keys indicates that the
2856 corresponding time component should always be included, even if
2857 its value is 0.
2860 For example,
2862 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2863 :require-minutes t)
2865 means durations longer than a day will be expressed in days,
2866 hours and minutes, and durations less than a day will always be
2867 expressed in hours and minutes (even for durations less than an
2868 hour).
2870 The value
2872 \(:days \"%dd\" :minutes \"%dm\")
2874 means durations longer than a day will be expressed in days and
2875 minutes, and durations less than a day will be expressed entirely
2876 in minutes (even for durations longer than an hour)."
2877 :group 'org-time
2878 :group 'org-clock
2879 :version "24.3"
2880 :type '(choice (string :tag "Format string")
2881 (set :tag "Plist"
2882 (group :inline t (const :tag "Years" :years)
2883 (string :tag "Format string"))
2884 (group :inline t
2885 (const :tag "Always show years" :require-years)
2886 (const t))
2887 (group :inline t (const :tag "Months" :months)
2888 (string :tag "Format string"))
2889 (group :inline t
2890 (const :tag "Always show months" :require-months)
2891 (const t))
2892 (group :inline t (const :tag "Weeks" :weeks)
2893 (string :tag "Format string"))
2894 (group :inline t
2895 (const :tag "Always show weeks" :require-weeks)
2896 (const t))
2897 (group :inline t (const :tag "Days" :days)
2898 (string :tag "Format string"))
2899 (group :inline t
2900 (const :tag "Always show days" :require-days)
2901 (const t))
2902 (group :inline t (const :tag "Hours" :hours)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show hours" :require-hours)
2906 (const t))
2907 (group :inline t (const :tag "Minutes" :minutes)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show minutes" :require-minutes)
2911 (const t)))))
2913 (defcustom org-time-clocksum-use-fractional nil
2914 "When non-nil, \\[org-clock-display] uses fractional times.
2915 See `org-time-clocksum-format' for more on time clock formats."
2916 :group 'org-time
2917 :group 'org-clock
2918 :version "24.3"
2919 :type 'boolean)
2921 (defcustom org-time-clocksum-use-effort-durations t
2922 "When non-nil, \\[org-clock-display] uses effort durations.
2923 E.g. by default, one day is considered to be a 8 hours effort,
2924 so a task that has been clocked for 16 hours will be displayed
2925 as during 2 days in the clock display or in the clocktable.
2927 See `org-effort-durations' on how to set effort durations
2928 and `org-time-clocksum-format' for more on time clock formats."
2929 :group 'org-time
2930 :group 'org-clock
2931 :version "24.3"
2932 :type 'boolean)
2934 (defcustom org-time-clocksum-fractional-format "%.2f"
2935 "The format string used when creating CLOCKSUM lines,
2936 or when Org mode generates a time duration, if
2937 `org-time-clocksum-use-fractional' is enabled.
2939 The value can be a single format string containing one
2940 %-sequence, which will be filled with the number of hours as
2941 a float.
2943 Alternatively, the value can be a plist associating any of the
2944 keys :years, :months, :weeks, :days, :hours or :minutes with
2945 a format string. The time duration is formatted using the
2946 largest time unit which gives a non-zero integer part. If all
2947 specified formats have zero integer part, the smallest time unit
2948 is used."
2949 :group 'org-time
2950 :type '(choice (string :tag "Format string")
2951 (set (group :inline t (const :tag "Years" :years)
2952 (string :tag "Format string"))
2953 (group :inline t (const :tag "Months" :months)
2954 (string :tag "Format string"))
2955 (group :inline t (const :tag "Weeks" :weeks)
2956 (string :tag "Format string"))
2957 (group :inline t (const :tag "Days" :days)
2958 (string :tag "Format string"))
2959 (group :inline t (const :tag "Hours" :hours)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Minutes" :minutes)
2962 (string :tag "Format string")))))
2964 (defcustom org-deadline-warning-days 14
2965 "Number of days before expiration during which a deadline becomes active.
2966 This variable governs the display in sparse trees and in the agenda.
2967 When 0 or negative, it means use this number (the absolute value of it)
2968 even if a deadline has a different individual lead time specified.
2970 Custom commands can set this variable in the options section."
2971 :group 'org-time
2972 :group 'org-agenda-daily/weekly
2973 :type 'integer)
2975 (defcustom org-scheduled-delay-days 0
2976 "Number of days before a scheduled item becomes active.
2977 This variable governs the display in sparse trees and in the agenda.
2978 The default value (i.e. 0) means: don't delay scheduled item.
2979 When negative, it means use this number (the absolute value of it)
2980 even if a scheduled item has a different individual delay time
2981 specified.
2983 Custom commands can set this variable in the options section."
2984 :group 'org-time
2985 :group 'org-agenda-daily/weekly
2986 :version "24.3"
2987 :type 'integer)
2989 (defcustom org-read-date-prefer-future t
2990 "Non-nil means assume future for incomplete date input from user.
2991 This affects the following situations:
2992 1. The user gives a month but not a year.
2993 For example, if it is April and you enter \"feb 2\", this will be read
2994 as Feb 2, *next* year. \"May 5\", however, will be this year.
2995 2. The user gives a day, but no month.
2996 For example, if today is the 15th, and you enter \"3\", Org-mode will
2997 read this as the third of *next* month. However, if you enter \"17\",
2998 it will be considered as *this* month.
3000 If you set this variable to the symbol `time', then also the following
3001 will work:
3003 3. If the user gives a time.
3004 If the time is before now, it will be interpreted as tomorrow.
3006 Currently none of this works for ISO week specifications.
3008 When this option is nil, the current day, month and year will always be
3009 used as defaults.
3011 See also `org-agenda-jump-prefer-future'."
3012 :group 'org-time
3013 :type '(choice
3014 (const :tag "Never" nil)
3015 (const :tag "Check month and day" t)
3016 (const :tag "Check month, day, and time" time)))
3018 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3019 "Should the agenda jump command prefer the future for incomplete dates?
3020 The default is to do the same as configured in `org-read-date-prefer-future'.
3021 But you can also set a deviating value here.
3022 This may t or nil, or the symbol `org-read-date-prefer-future'."
3023 :group 'org-agenda
3024 :group 'org-time
3025 :version "24.1"
3026 :type '(choice
3027 (const :tag "Use org-read-date-prefer-future"
3028 org-read-date-prefer-future)
3029 (const :tag "Never" nil)
3030 (const :tag "Always" t)))
3032 (defcustom org-read-date-force-compatible-dates t
3033 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3035 Depending on the system Emacs is running on, certain dates cannot
3036 be represented with the type used internally to represent time.
3037 Dates between 1970-1-1 and 2038-1-1 can always be represented
3038 correctly. Some systems allow for earlier dates, some for later,
3039 some for both. One way to find out it to insert any date into an
3040 Org buffer, putting the cursor on the year and hitting S-up and
3041 S-down to test the range.
3043 When this variable is set to t, the date/time prompt will not let
3044 you specify dates outside the 1970-2037 range, so it is certain that
3045 these dates will work in whatever version of Emacs you are
3046 running, and also that you can move a file from one Emacs implementation
3047 to another. WHenever Org is forcing the year for you, it will display
3048 a message and beep.
3050 When this variable is nil, Org will check if the date is
3051 representable in the specific Emacs implementation you are using.
3052 If not, it will force a year, usually the current year, and beep
3053 to remind you. Currently this setting is not recommended because
3054 the likelihood that you will open your Org files in an Emacs that
3055 has limited date range is not negligible.
3057 A workaround for this problem is to use diary sexp dates for time
3058 stamps outside of this range."
3059 :group 'org-time
3060 :version "24.1"
3061 :type 'boolean)
3063 (defcustom org-read-date-display-live t
3064 "Non-nil means display current interpretation of date prompt live.
3065 This display will be in an overlay, in the minibuffer."
3066 :group 'org-time
3067 :type 'boolean)
3069 (defcustom org-read-date-popup-calendar t
3070 "Non-nil means pop up a calendar when prompting for a date.
3071 In the calendar, the date can be selected with mouse-1. However, the
3072 minibuffer will also be active, and you can simply enter the date as well.
3073 When nil, only the minibuffer will be available."
3074 :group 'org-time
3075 :type 'boolean)
3076 (if (fboundp 'defvaralias)
3077 (defvaralias 'org-popup-calendar-for-date-prompt
3078 'org-read-date-popup-calendar))
3080 (make-obsolete-variable
3081 'org-read-date-minibuffer-setup-hook
3082 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3083 (defcustom org-read-date-minibuffer-setup-hook nil
3084 "Hook to be used to set up keys for the date/time interface.
3085 Add key definitions to `minibuffer-local-map', which will be a
3086 temporary copy.
3088 WARNING: This option is obsolete, you should use
3089 `org-read-date-minibuffer-local-map' to set up keys."
3090 :group 'org-time
3091 :type 'hook)
3093 (defcustom org-extend-today-until 0
3094 "The hour when your day really ends. Must be an integer.
3095 This has influence for the following applications:
3096 - When switching the agenda to \"today\". It it is still earlier than
3097 the time given here, the day recognized as TODAY is actually yesterday.
3098 - When a date is read from the user and it is still before the time given
3099 here, the current date and time will be assumed to be yesterday, 23:59.
3100 Also, timestamps inserted in capture templates follow this rule.
3102 IMPORTANT: This is a feature whose implementation is and likely will
3103 remain incomplete. Really, it is only here because past midnight seems to
3104 be the favorite working time of John Wiegley :-)"
3105 :group 'org-time
3106 :type 'integer)
3108 (defcustom org-use-effective-time nil
3109 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3110 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3111 \"effective time\" of any timestamps between midnight and 8am will be
3112 23:59 of the previous day."
3113 :group 'org-time
3114 :version "24.1"
3115 :type 'boolean)
3117 (defcustom org-use-last-clock-out-time-as-effective-time nil
3118 "When non-nil, use the last clock out time for `org-todo'.
3119 Note that this option has precedence over the combined use of
3120 `org-use-effective-time' and `org-extend-today-until'."
3121 :group 'org-time
3122 ;; :version "24.3"
3123 :type 'boolean)
3125 (defcustom org-edit-timestamp-down-means-later nil
3126 "Non-nil means S-down will increase the time in a time stamp.
3127 When nil, S-up will increase."
3128 :group 'org-time
3129 :type 'boolean)
3131 (defcustom org-calendar-follow-timestamp-change t
3132 "Non-nil means make the calendar window follow timestamp changes.
3133 When a timestamp is modified and the calendar window is visible, it will be
3134 moved to the new date."
3135 :group 'org-time
3136 :type 'boolean)
3138 (defgroup org-tags nil
3139 "Options concerning tags in Org-mode."
3140 :tag "Org Tags"
3141 :group 'org)
3143 (defcustom org-tag-alist nil
3144 "List of tags allowed in Org-mode files.
3145 When this list is nil, Org-mode will base TAG input on what is already in the
3146 buffer.
3147 The value of this variable is an alist, the car of each entry must be a
3148 keyword as a string, the cdr may be a character that is used to select
3149 that tag through the fast-tag-selection interface.
3150 See the manual for details."
3151 :group 'org-tags
3152 :type '(repeat
3153 (choice
3154 (cons (string :tag "Tag name")
3155 (character :tag "Access char"))
3156 (list :tag "Start radio group"
3157 (const :startgroup)
3158 (option (string :tag "Group description")))
3159 (list :tag "End radio group"
3160 (const :endgroup)
3161 (option (string :tag "Group description")))
3162 (const :tag "New line" (:newline)))))
3164 (defcustom org-tag-persistent-alist nil
3165 "List of tags that will always appear in all Org-mode files.
3166 This is in addition to any in buffer settings or customizations
3167 of `org-tag-alist'.
3168 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3169 The value of this variable is an alist, the car of each entry must be a
3170 keyword as a string, the cdr may be a character that is used to select
3171 that tag through the fast-tag-selection interface.
3172 See the manual for details.
3173 To disable these tags on a per-file basis, insert anywhere in the file:
3174 #+STARTUP: noptag"
3175 :group 'org-tags
3176 :type '(repeat
3177 (choice
3178 (cons (string :tag "Tag name")
3179 (character :tag "Access char"))
3180 (const :tag "Start radio group" (:startgroup))
3181 (const :tag "End radio group" (:endgroup))
3182 (const :tag "New line" (:newline)))))
3184 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3185 "If non-nil, always offer completion for all tags of all agenda files.
3186 Instead of customizing this variable directly, you might want to
3187 set it locally for capture buffers, because there no list of
3188 tags in that file can be created dynamically (there are none).
3190 (add-hook 'org-capture-mode-hook
3191 (lambda ()
3192 (set (make-local-variable
3193 'org-complete-tags-always-offer-all-agenda-tags)
3194 t)))"
3195 :group 'org-tags
3196 :version "24.1"
3197 :type 'boolean)
3199 (defvar org-file-tags nil
3200 "List of tags that can be inherited by all entries in the file.
3201 The tags will be inherited if the variable `org-use-tag-inheritance'
3202 says they should be.
3203 This variable is populated from #+FILETAGS lines.")
3205 (defcustom org-use-fast-tag-selection 'auto
3206 "Non-nil means use fast tag selection scheme.
3207 This is a special interface to select and deselect tags with single keys.
3208 When nil, fast selection is never used.
3209 When the symbol `auto', fast selection is used if and only if selection
3210 characters for tags have been configured, either through the variable
3211 `org-tag-alist' or through a #+TAGS line in the buffer.
3212 When t, fast selection is always used and selection keys are assigned
3213 automatically if necessary."
3214 :group 'org-tags
3215 :type '(choice
3216 (const :tag "Always" t)
3217 (const :tag "Never" nil)
3218 (const :tag "When selection characters are configured" 'auto)))
3220 (defcustom org-fast-tag-selection-single-key nil
3221 "Non-nil means fast tag selection exits after first change.
3222 When nil, you have to press RET to exit it.
3223 During fast tag selection, you can toggle this flag with `C-c'.
3224 This variable can also have the value `expert'. In this case, the window
3225 displaying the tags menu is not even shown, until you press C-c again."
3226 :group 'org-tags
3227 :type '(choice
3228 (const :tag "No" nil)
3229 (const :tag "Yes" t)
3230 (const :tag "Expert" expert)))
3232 (defvar org-fast-tag-selection-include-todo nil
3233 "Non-nil means fast tags selection interface will also offer TODO states.
3234 This is an undocumented feature, you should not rely on it.")
3236 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3237 "The column to which tags should be indented in a headline.
3238 If this number is positive, it specifies the column. If it is negative,
3239 it means that the tags should be flushright to that column. For example,
3240 -80 works well for a normal 80 character screen.
3241 When 0, place tags directly after headline text, with only one space in
3242 between."
3243 :group 'org-tags
3244 :type 'integer)
3246 (defcustom org-auto-align-tags t
3247 "Non-nil keeps tags aligned when modifying headlines.
3248 Some operations (i.e. demoting) change the length of a headline and
3249 therefore shift the tags around. With this option turned on, after
3250 each such operation the tags are again aligned to `org-tags-column'."
3251 :group 'org-tags
3252 :type 'boolean)
3254 (defcustom org-use-tag-inheritance t
3255 "Non-nil means tags in levels apply also for sublevels.
3256 When nil, only the tags directly given in a specific line apply there.
3257 This may also be a list of tags that should be inherited, or a regexp that
3258 matches tags that should be inherited. Additional control is possible
3259 with the variable `org-tags-exclude-from-inheritance' which gives an
3260 explicit list of tags to be excluded from inheritance, even if the value of
3261 `org-use-tag-inheritance' would select it for inheritance.
3263 If this option is t, a match early-on in a tree can lead to a large
3264 number of matches in the subtree when constructing the agenda or creating
3265 a sparse tree. If you only want to see the first match in a tree during
3266 a search, check out the variable `org-tags-match-list-sublevels'."
3267 :group 'org-tags
3268 :type '(choice
3269 (const :tag "Not" nil)
3270 (const :tag "Always" t)
3271 (repeat :tag "Specific tags" (string :tag "Tag"))
3272 (regexp :tag "Tags matched by regexp")))
3274 (defcustom org-tags-exclude-from-inheritance nil
3275 "List of tags that should never be inherited.
3276 This is a way to exclude a few tags from inheritance. For way to do
3277 the opposite, to actively allow inheritance for selected tags,
3278 see the variable `org-use-tag-inheritance'."
3279 :group 'org-tags
3280 :type '(repeat (string :tag "Tag")))
3282 (defun org-tag-inherit-p (tag)
3283 "Check if TAG is one that should be inherited."
3284 (cond
3285 ((member tag org-tags-exclude-from-inheritance) nil)
3286 ((eq org-use-tag-inheritance t) t)
3287 ((not org-use-tag-inheritance) nil)
3288 ((stringp org-use-tag-inheritance)
3289 (string-match org-use-tag-inheritance tag))
3290 ((listp org-use-tag-inheritance)
3291 (member tag org-use-tag-inheritance))
3292 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3294 (defcustom org-tags-match-list-sublevels t
3295 "Non-nil means list also sublevels of headlines matching a search.
3296 This variable applies to tags/property searches, and also to stuck
3297 projects because this search is based on a tags match as well.
3299 When set to the symbol `indented', sublevels are indented with
3300 leading dots.
3302 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3303 the sublevels of a headline matching a tag search often also match
3304 the same search. Listing all of them can create very long lists.
3305 Setting this variable to nil causes subtrees of a match to be skipped.
3307 This variable is semi-obsolete and probably should always be true. It
3308 is better to limit inheritance to certain tags using the variables
3309 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3310 :group 'org-tags
3311 :type '(choice
3312 (const :tag "No, don't list them" nil)
3313 (const :tag "Yes, do list them" t)
3314 (const :tag "List them, indented with leading dots" indented)))
3316 (defcustom org-tags-sort-function nil
3317 "When set, tags are sorted using this function as a comparator."
3318 :group 'org-tags
3319 :type '(choice
3320 (const :tag "No sorting" nil)
3321 (const :tag "Alphabetical" string<)
3322 (const :tag "Reverse alphabetical" string>)
3323 (function :tag "Custom function" nil)))
3325 (defvar org-tags-history nil
3326 "History of minibuffer reads for tags.")
3327 (defvar org-last-tags-completion-table nil
3328 "The last used completion table for tags.")
3329 (defvar org-after-tags-change-hook nil
3330 "Hook that is run after the tags in a line have changed.")
3332 (defgroup org-properties nil
3333 "Options concerning properties in Org-mode."
3334 :tag "Org Properties"
3335 :group 'org)
3337 (defcustom org-property-format "%-10s %s"
3338 "How property key/value pairs should be formatted by `indent-line'.
3339 When `indent-line' hits a property definition, it will format the line
3340 according to this format, mainly to make sure that the values are
3341 lined-up with respect to each other."
3342 :group 'org-properties
3343 :type 'string)
3345 (defcustom org-properties-postprocess-alist nil
3346 "Alist of properties and functions to adjust inserted values.
3347 Elements of this alist must be of the form
3349 ([string] [function])
3351 where [string] must be a property name and [function] must be a
3352 lambda expression: this lambda expression must take one argument,
3353 the value to adjust, and return the new value as a string.
3355 For example, this element will allow the property \"Remaining\"
3356 to be updated wrt the relation between the \"Effort\" property
3357 and the clock summary:
3359 ((\"Remaining\" (lambda(value)
3360 (let ((clocksum (org-clock-sum-current-item))
3361 (effort (org-duration-string-to-minutes
3362 (org-entry-get (point) \"Effort\"))))
3363 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3364 :group 'org-properties
3365 :version "24.1"
3366 :type '(alist :key-type (string :tag "Property")
3367 :value-type (function :tag "Function")))
3369 (defcustom org-use-property-inheritance nil
3370 "Non-nil means properties apply also for sublevels.
3372 This setting is chiefly used during property searches. Turning it on can
3373 cause significant overhead when doing a search, which is why it is not
3374 on by default.
3376 When nil, only the properties directly given in the current entry count.
3377 When t, every property is inherited. The value may also be a list of
3378 properties that should have inheritance, or a regular expression matching
3379 properties that should be inherited.
3381 However, note that some special properties use inheritance under special
3382 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3383 and the properties ending in \"_ALL\" when they are used as descriptor
3384 for valid values of a property.
3386 Note for programmers:
3387 When querying an entry with `org-entry-get', you can control if inheritance
3388 should be used. By default, `org-entry-get' looks only at the local
3389 properties. You can request inheritance by setting the inherit argument
3390 to t (to force inheritance) or to `selective' (to respect the setting
3391 in this variable)."
3392 :group 'org-properties
3393 :type '(choice
3394 (const :tag "Not" nil)
3395 (const :tag "Always" t)
3396 (repeat :tag "Specific properties" (string :tag "Property"))
3397 (regexp :tag "Properties matched by regexp")))
3399 (defun org-property-inherit-p (property)
3400 "Check if PROPERTY is one that should be inherited."
3401 (cond
3402 ((eq org-use-property-inheritance t) t)
3403 ((not org-use-property-inheritance) nil)
3404 ((stringp org-use-property-inheritance)
3405 (string-match org-use-property-inheritance property))
3406 ((listp org-use-property-inheritance)
3407 (member property org-use-property-inheritance))
3408 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3410 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3411 "The default column format, if no other format has been defined.
3412 This variable can be set on the per-file basis by inserting a line
3414 #+COLUMNS: %25ITEM ....."
3415 :group 'org-properties
3416 :type 'string)
3418 (defcustom org-columns-ellipses ".."
3419 "The ellipses to be used when a field in column view is truncated.
3420 When this is the empty string, as many characters as possible are shown,
3421 but then there will be no visual indication that the field has been truncated.
3422 When this is a string of length N, the last N characters of a truncated
3423 field are replaced by this string. If the column is narrower than the
3424 ellipses string, only part of the ellipses string will be shown."
3425 :group 'org-properties
3426 :type 'string)
3428 (defcustom org-columns-modify-value-for-display-function nil
3429 "Function that modifies values for display in column view.
3430 For example, it can be used to cut out a certain part from a time stamp.
3431 The function must take 2 arguments:
3433 column-title The title of the column (*not* the property name)
3434 value The value that should be modified.
3436 The function should return the value that should be displayed,
3437 or nil if the normal value should be used."
3438 :group 'org-properties
3439 :type 'function)
3441 (defcustom org-effort-property "Effort"
3442 "The property that is being used to keep track of effort estimates.
3443 Effort estimates given in this property need to have the format H:MM."
3444 :group 'org-properties
3445 :group 'org-progress
3446 :type '(string :tag "Property"))
3448 (defconst org-global-properties-fixed
3449 '(("VISIBILITY_ALL" . "folded children content all")
3450 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3451 "List of property/value pairs that can be inherited by any entry.
3453 These are fixed values, for the preset properties. The user variable
3454 that can be used to add to this list is `org-global-properties'.
3456 The entries in this list are cons cells where the car is a property
3457 name and cdr is a string with the value. If the value represents
3458 multiple items like an \"_ALL\" property, separate the items by
3459 spaces.")
3461 (defcustom org-global-properties nil
3462 "List of property/value pairs that can be inherited by any entry.
3464 This list will be combined with the constant `org-global-properties-fixed'.
3466 The entries in this list are cons cells where the car is a property
3467 name and cdr is a string with the value.
3469 You can set buffer-local values for the same purpose in the variable
3470 `org-file-properties' this by adding lines like
3472 #+PROPERTY: NAME VALUE"
3473 :group 'org-properties
3474 :type '(repeat
3475 (cons (string :tag "Property")
3476 (string :tag "Value"))))
3478 (defvar org-file-properties nil
3479 "List of property/value pairs that can be inherited by any entry.
3480 Valid for the current buffer.
3481 This variable is populated from #+PROPERTY lines.")
3482 (make-variable-buffer-local 'org-file-properties)
3484 (defgroup org-agenda nil
3485 "Options concerning agenda views in Org-mode."
3486 :tag "Org Agenda"
3487 :group 'org)
3489 (defvar org-category nil
3490 "Variable used by org files to set a category for agenda display.
3491 Such files should use a file variable to set it, for example
3493 # -*- mode: org; org-category: \"ELisp\"
3495 or contain a special line
3497 #+CATEGORY: ELisp
3499 If the file does not specify a category, then file's base name
3500 is used instead.")
3501 (make-variable-buffer-local 'org-category)
3502 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3504 (defcustom org-agenda-files nil
3505 "The files to be used for agenda display.
3506 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3507 \\[org-remove-file]. You can also use customize to edit the list.
3509 If an entry is a directory, all files in that directory that are matched by
3510 `org-agenda-file-regexp' will be part of the file list.
3512 If the value of the variable is not a list but a single file name, then
3513 the list of agenda files is actually stored and maintained in that file, one
3514 agenda file per line. In this file paths can be given relative to
3515 `org-directory'. Tilde expansion and environment variable substitution
3516 are also made."
3517 :group 'org-agenda
3518 :type '(choice
3519 (repeat :tag "List of files and directories" file)
3520 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3522 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3523 "Regular expression to match files for `org-agenda-files'.
3524 If any element in the list in that variable contains a directory instead
3525 of a normal file, all files in that directory that are matched by this
3526 regular expression will be included."
3527 :group 'org-agenda
3528 :type 'regexp)
3530 (defcustom org-agenda-text-search-extra-files nil
3531 "List of extra files to be searched by text search commands.
3532 These files will be search in addition to the agenda files by the
3533 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3534 Note that these files will only be searched for text search commands,
3535 not for the other agenda views like todo lists, tag searches or the weekly
3536 agenda. This variable is intended to list notes and possibly archive files
3537 that should also be searched by these two commands.
3538 In fact, if the first element in the list is the symbol `agenda-archives',
3539 than all archive files of all agenda files will be added to the search
3540 scope."
3541 :group 'org-agenda
3542 :type '(set :greedy t
3543 (const :tag "Agenda Archives" agenda-archives)
3544 (repeat :inline t (file))))
3546 (if (fboundp 'defvaralias)
3547 (defvaralias 'org-agenda-multi-occur-extra-files
3548 'org-agenda-text-search-extra-files))
3550 (defcustom org-agenda-skip-unavailable-files nil
3551 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3552 A nil value means to remove them, after a query, from the list."
3553 :group 'org-agenda
3554 :type 'boolean)
3556 (defcustom org-calendar-to-agenda-key [?c]
3557 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3558 The command `org-calendar-goto-agenda' will be bound to this key. The
3559 default is the character `c' because then `c' can be used to switch back and
3560 forth between agenda and calendar."
3561 :group 'org-agenda
3562 :type 'sexp)
3564 (defcustom org-calendar-insert-diary-entry-key [?i]
3565 "The key to be installed in `calendar-mode-map' for adding diary entries.
3566 This option is irrelevant until `org-agenda-diary-file' has been configured
3567 to point to an Org-mode file. When that is the case, the command
3568 `org-agenda-diary-entry' will be bound to the key given here, by default
3569 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3570 if you want to continue doing this, you need to change this to a different
3571 key."
3572 :group 'org-agenda
3573 :type 'sexp)
3575 (defcustom org-agenda-diary-file 'diary-file
3576 "File to which to add new entries with the `i' key in agenda and calendar.
3577 When this is the symbol `diary-file', the functionality in the Emacs
3578 calendar will be used to add entries to the `diary-file'. But when this
3579 points to a file, `org-agenda-diary-entry' will be used instead."
3580 :group 'org-agenda
3581 :type '(choice
3582 (const :tag "The standard Emacs diary file" diary-file)
3583 (file :tag "Special Org file diary entries")))
3585 (eval-after-load "calendar"
3586 '(progn
3587 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3588 'org-calendar-goto-agenda)
3589 (add-hook 'calendar-mode-hook
3590 (lambda ()
3591 (unless (eq org-agenda-diary-file 'diary-file)
3592 (define-key calendar-mode-map
3593 org-calendar-insert-diary-entry-key
3594 'org-agenda-diary-entry))))))
3596 (defgroup org-latex nil
3597 "Options for embedding LaTeX code into Org-mode."
3598 :tag "Org LaTeX"
3599 :group 'org)
3601 (defcustom org-format-latex-options
3602 '(:foreground default :background default :scale 1.0
3603 :html-foreground "Black" :html-background "Transparent"
3604 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3605 "Options for creating images from LaTeX fragments.
3606 This is a property list with the following properties:
3607 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3608 `default' means use the foreground of the default face.
3609 `auto' means use the foreground from the text face.
3610 :background the background color, or \"Transparent\".
3611 `default' means use the background of the default face.
3612 `auto' means use the background from the text face.
3613 :scale a scaling factor for the size of the images, to get more pixels
3614 :html-foreground, :html-background, :html-scale
3615 the same numbers for HTML export.
3616 :matchers a list indicating which matchers should be used to
3617 find LaTeX fragments. Valid members of this list are:
3618 \"begin\" find environments
3619 \"$1\" find single characters surrounded by $.$
3620 \"$\" find math expressions surrounded by $...$
3621 \"$$\" find math expressions surrounded by $$....$$
3622 \"\\(\" find math expressions surrounded by \\(...\\)
3623 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3624 :group 'org-latex
3625 :type 'plist)
3627 (defcustom org-format-latex-signal-error t
3628 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3629 When nil, just push out a message."
3630 :group 'org-latex
3631 :version "24.1"
3632 :type 'boolean)
3634 (defcustom org-latex-to-mathml-jar-file nil
3635 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3636 Use this to specify additional executable file say a jar file.
3638 When using MathToWeb as the converter, specify the full-path to
3639 your mathtoweb.jar file."
3640 :group 'org-latex
3641 :version "24.1"
3642 :type '(choice
3643 (const :tag "None" nil)
3644 (file :tag "JAR file" :must-match t)))
3646 (defcustom org-latex-to-mathml-convert-command nil
3647 "Command to convert LaTeX fragments to MathML.
3648 Replace format-specifiers in the command as noted below and use
3649 `shell-command' to convert LaTeX to MathML.
3650 %j: Executable file in fully expanded form as specified by
3651 `org-latex-to-mathml-jar-file'.
3652 %I: Input LaTeX file in fully expanded form
3653 %o: Output MathML file
3654 This command is used by `org-create-math-formula'.
3656 When using MathToWeb as the converter, set this to
3657 \"java -jar %j -unicode -force -df %o %I\"."
3658 :group 'org-latex
3659 :version "24.1"
3660 :type '(choice
3661 (const :tag "None" nil)
3662 (string :tag "\nShell command")))
3664 (defcustom org-latex-create-formula-image-program 'dvipng
3665 "Program to convert LaTeX fragments with.
3667 dvipng Process the LaTeX fragments to dvi file, then convert
3668 dvi files to png files using dvipng.
3669 This will also include processing of non-math environments.
3670 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3671 to convert pdf files to png files"
3672 :group 'org-latex
3673 :version "24.1"
3674 :type '(choice
3675 (const :tag "dvipng" dvipng)
3676 (const :tag "imagemagick" imagemagick)))
3678 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3679 "Path to store latex preview images.
3680 A relative path here creates many directories relative to the
3681 processed org files paths. An absolute path puts all preview
3682 images at the same place."
3683 :group 'org-latex
3684 :version "24.3"
3685 :type 'string)
3687 (defun org-format-latex-mathml-available-p ()
3688 "Return t if `org-latex-to-mathml-convert-command' is usable."
3689 (save-match-data
3690 (when (and (boundp 'org-latex-to-mathml-convert-command)
3691 org-latex-to-mathml-convert-command)
3692 (let ((executable (car (split-string
3693 org-latex-to-mathml-convert-command))))
3694 (when (executable-find executable)
3695 (if (string-match
3696 "%j" org-latex-to-mathml-convert-command)
3697 (file-readable-p org-latex-to-mathml-jar-file)
3698 t))))))
3700 (defcustom org-format-latex-header "\\documentclass{article}
3701 \\usepackage[usenames]{color}
3702 \\usepackage{amsmath}
3703 \\usepackage[mathscr]{eucal}
3704 \\pagestyle{empty} % do not remove
3705 \[PACKAGES]
3706 \[DEFAULT-PACKAGES]
3707 % The settings below are copied from fullpage.sty
3708 \\setlength{\\textwidth}{\\paperwidth}
3709 \\addtolength{\\textwidth}{-3cm}
3710 \\setlength{\\oddsidemargin}{1.5cm}
3711 \\addtolength{\\oddsidemargin}{-2.54cm}
3712 \\setlength{\\evensidemargin}{\\oddsidemargin}
3713 \\setlength{\\textheight}{\\paperheight}
3714 \\addtolength{\\textheight}{-\\headheight}
3715 \\addtolength{\\textheight}{-\\headsep}
3716 \\addtolength{\\textheight}{-\\footskip}
3717 \\addtolength{\\textheight}{-3cm}
3718 \\setlength{\\topmargin}{1.5cm}
3719 \\addtolength{\\topmargin}{-2.54cm}"
3720 "The document header used for processing LaTeX fragments.
3721 It is imperative that this header make sure that no page number
3722 appears on the page. The package defined in the variables
3723 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3724 will either replace the placeholder \"[PACKAGES]\" in this
3725 header, or they will be appended."
3726 :group 'org-latex
3727 :type 'string)
3729 (defun org-set-packages-alist (var val)
3730 "Set the packages alist and make sure it has 3 elements per entry."
3731 (set var (mapcar (lambda (x)
3732 (if (and (consp x) (= (length x) 2))
3733 (list (car x) (nth 1 x) t)
3735 val)))
3737 (defun org-get-packages-alist (var)
3738 "Get the packages alist and make sure it has 3 elements per entry."
3739 (mapcar (lambda (x)
3740 (if (and (consp x) (= (length x) 2))
3741 (list (car x) (nth 1 x) t)
3743 (default-value var)))
3745 (defcustom org-latex-default-packages-alist
3746 '(("AUTO" "inputenc" t)
3747 ("T1" "fontenc" t)
3748 ("" "fixltx2e" nil)
3749 ("" "graphicx" t)
3750 ("" "longtable" nil)
3751 ("" "float" nil)
3752 ("" "wrapfig" nil)
3753 ("" "soul" t)
3754 ("" "textcomp" t)
3755 ("" "marvosym" t)
3756 ("" "wasysym" t)
3757 ("" "latexsym" t)
3758 ("" "amssymb" t)
3759 ("" "hyperref" nil)
3760 "\\tolerance=1000")
3761 "Alist of default packages to be inserted in the header.
3763 Change this only if one of the packages here causes an
3764 incompatibility with another package you are using.
3766 The packages in this list are needed by one part or another of
3767 Org mode to function properly:
3769 - inputenc, fontenc: for basic font and character selection
3770 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3771 symbols used for interpreting the entities in `org-entities'.
3772 You can skip some of these packages if you don't use any of the
3773 symbols in it.
3774 - graphicx: for including images
3775 - float, wrapfig: for figure placement
3776 - longtable: for long tables
3777 - hyperref: for cross references
3779 Therefore you should not modify this variable unless you know
3780 what you are doing. The one reason to change it anyway is that
3781 you might be loading some other package that conflicts with one
3782 of the default packages. Each cell is of the format
3783 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3784 the package also needs to be included when compiling LaTeX
3785 snippets into images for inclusion into non-LaTeX output."
3786 :group 'org-latex
3787 :group 'org-export-latex
3788 :set 'org-set-packages-alist
3789 :get 'org-get-packages-alist
3790 :version "24.1"
3791 :type '(repeat
3792 (choice
3793 (list :tag "options/package pair"
3794 (string :tag "options")
3795 (string :tag "package")
3796 (boolean :tag "Snippet"))
3797 (string :tag "A line of LaTeX"))))
3799 (defcustom org-latex-packages-alist nil
3800 "Alist of packages to be inserted in every LaTeX header.
3802 These will be inserted after `org-latex-default-packages-alist'.
3803 Each cell is of the format:
3805 \(\"options\" \"package\" snippet-flag)
3807 SNIPPET-FLAG, when t, indicates that this package is also needed
3808 when turning LaTeX snippets into images for inclusion into
3809 non-LaTeX output.
3811 Make sure that you only list packages here which:
3813 - you want in every file
3814 - do not conflict with the setup in `org-format-latex-header'.
3815 - do not conflict with the default packages in
3816 `org-latex-default-packages-alist'."
3817 :group 'org-latex
3818 :group 'org-export-latex
3819 :set 'org-set-packages-alist
3820 :get 'org-get-packages-alist
3821 :type '(repeat
3822 (choice
3823 (list :tag "options/package pair"
3824 (string :tag "options")
3825 (string :tag "package")
3826 (boolean :tag "Snippet"))
3827 (string :tag "A line of LaTeX"))))
3829 (defgroup org-appearance nil
3830 "Settings for Org-mode appearance."
3831 :tag "Org Appearance"
3832 :group 'org)
3834 (defcustom org-level-color-stars-only nil
3835 "Non-nil means fontify only the stars in each headline.
3836 When nil, the entire headline is fontified.
3837 Changing it requires restart of `font-lock-mode' to become effective
3838 also in regions already fontified."
3839 :group 'org-appearance
3840 :type 'boolean)
3842 (defcustom org-hide-leading-stars nil
3843 "Non-nil means hide the first N-1 stars in a headline.
3844 This works by using the face `org-hide' for these stars. This
3845 face is white for a light background, and black for a dark
3846 background. You may have to customize the face `org-hide' to
3847 make this work.
3848 Changing it requires restart of `font-lock-mode' to become effective
3849 also in regions already fontified.
3850 You may also set this on a per-file basis by adding one of the following
3851 lines to the buffer:
3853 #+STARTUP: hidestars
3854 #+STARTUP: showstars"
3855 :group 'org-appearance
3856 :type 'boolean)
3858 (defcustom org-hidden-keywords nil
3859 "List of symbols corresponding to keywords to be hidden the org buffer.
3860 For example, a value '(title) for this list will make the document's title
3861 appear in the buffer without the initial #+TITLE: keyword."
3862 :group 'org-appearance
3863 :version "24.1"
3864 :type '(set (const :tag "#+AUTHOR" author)
3865 (const :tag "#+DATE" date)
3866 (const :tag "#+EMAIL" email)
3867 (const :tag "#+TITLE" title)))
3869 (defcustom org-custom-properties nil
3870 "List of properties (as strings) with a special meaning.
3871 The default use of these custom properties is to let the user
3872 hide them with `org-toggle-custom-properties-visibility'."
3873 :group 'org-properties
3874 :group 'org-appearance
3875 :version "24.3"
3876 :type '(repeat (string :tag "Property Name")))
3878 (defcustom org-fontify-done-headline nil
3879 "Non-nil means change the face of a headline if it is marked DONE.
3880 Normally, only the TODO/DONE keyword indicates the state of a headline.
3881 When this is non-nil, the headline after the keyword is set to the
3882 `org-headline-done' as an additional indication."
3883 :group 'org-appearance
3884 :type 'boolean)
3886 (defcustom org-fontify-emphasized-text t
3887 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3888 Changing this variable requires a restart of Emacs to take effect."
3889 :group 'org-appearance
3890 :type 'boolean)
3892 (defcustom org-fontify-whole-heading-line nil
3893 "Non-nil means fontify the whole line for headings.
3894 This is useful when setting a background color for the
3895 org-level-* faces."
3896 :group 'org-appearance
3897 :type 'boolean)
3899 (defcustom org-hide-emphasis-markers nil
3900 "Non-nil mean font-lock should hide the emphasis marker characters."
3901 :group 'org-appearance
3902 :type 'boolean)
3904 (defcustom org-pretty-entities nil
3905 "Non-nil means show entities as UTF8 characters.
3906 When nil, the \\name form remains in the buffer."
3907 :group 'org-appearance
3908 :version "24.1"
3909 :type 'boolean)
3911 (defcustom org-pretty-entities-include-sub-superscripts t
3912 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3913 :group 'org-appearance
3914 :version "24.1"
3915 :type 'boolean)
3917 (defvar org-emph-re nil
3918 "Regular expression for matching emphasis.
3919 After a match, the match groups contain these elements:
3920 0 The match of the full regular expression, including the characters
3921 before and after the proper match
3922 1 The character before the proper match, or empty at beginning of line
3923 2 The proper match, including the leading and trailing markers
3924 3 The leading marker like * or /, indicating the type of highlighting
3925 4 The text between the emphasis markers, not including the markers
3926 5 The character after the match, empty at the end of a line")
3927 (defvar org-verbatim-re nil
3928 "Regular expression for matching verbatim text.")
3929 (defvar org-emphasis-regexp-components) ; defined just below
3930 (defvar org-emphasis-alist) ; defined just below
3931 (defun org-set-emph-re (var val)
3932 "Set variable and compute the emphasis regular expression."
3933 (set var val)
3934 (when (and (boundp 'org-emphasis-alist)
3935 (boundp 'org-emphasis-regexp-components)
3936 org-emphasis-alist org-emphasis-regexp-components)
3937 (let* ((e org-emphasis-regexp-components)
3938 (pre (car e))
3939 (post (nth 1 e))
3940 (border (nth 2 e))
3941 (body (nth 3 e))
3942 (nl (nth 4 e))
3943 (body1 (concat body "*?"))
3944 (markers (mapconcat 'car org-emphasis-alist ""))
3945 (vmarkers (mapconcat
3946 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3947 org-emphasis-alist "")))
3948 ;; make sure special characters appear at the right position in the class
3949 (if (string-match "\\^" markers)
3950 (setq markers (concat (replace-match "" t t markers) "^")))
3951 (if (string-match "-" markers)
3952 (setq markers (concat (replace-match "" t t markers) "-")))
3953 (if (string-match "\\^" vmarkers)
3954 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3955 (if (string-match "-" vmarkers)
3956 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3957 (if (> nl 0)
3958 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3959 (int-to-string nl) "\\}")))
3960 ;; Make the regexp
3961 (setq org-emph-re
3962 (concat "\\([" pre "]\\|^\\)"
3963 "\\("
3964 "\\([" markers "]\\)"
3965 "\\("
3966 "[^" border "]\\|"
3967 "[^" border "]"
3968 body1
3969 "[^" border "]"
3970 "\\)"
3971 "\\3\\)"
3972 "\\([" post "]\\|$\\)"))
3973 (setq org-verbatim-re
3974 (concat "\\([" pre "]\\|^\\)"
3975 "\\("
3976 "\\([" vmarkers "]\\)"
3977 "\\("
3978 "[^" border "]\\|"
3979 "[^" border "]"
3980 body1
3981 "[^" border "]"
3982 "\\)"
3983 "\\3\\)"
3984 "\\([" post "]\\|$\\)")))))
3986 (defcustom org-emphasis-regexp-components
3987 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3988 "Components used to build the regular expression for emphasis.
3989 This is a list with five entries. Terminology: In an emphasis string
3990 like \" *strong word* \", we call the initial space PREMATCH, the final
3991 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3992 and \"trong wor\" is the body. The different components in this variable
3993 specify what is allowed/forbidden in each part:
3995 pre Chars allowed as prematch. Beginning of line will be allowed too.
3996 post Chars allowed as postmatch. End of line will be allowed too.
3997 border The chars *forbidden* as border characters.
3998 body-regexp A regexp like \".\" to match a body character. Don't use
3999 non-shy groups here, and don't allow newline here.
4000 newline The maximum number of newlines allowed in an emphasis exp.
4002 Use customize to modify this, or restart Emacs after changing it."
4003 :group 'org-appearance
4004 :set 'org-set-emph-re
4005 :type '(list
4006 (sexp :tag "Allowed chars in pre ")
4007 (sexp :tag "Allowed chars in post ")
4008 (sexp :tag "Forbidden chars in border ")
4009 (sexp :tag "Regexp for body ")
4010 (integer :tag "number of newlines allowed")
4011 (option (boolean :tag "Please ignore this button"))))
4013 (defcustom org-emphasis-alist
4014 `(("*" bold "<b>" "</b>")
4015 ("/" italic "<i>" "</i>")
4016 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4017 ("=" org-code "<code>" "</code>" verbatim)
4018 ("~" org-verbatim "<code>" "</code>" verbatim)
4019 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4020 "<del>" "</del>")
4022 "Special syntax for emphasized text.
4023 Text starting and ending with a special character will be emphasized, for
4024 example *bold*, _underlined_ and /italic/. This variable sets the marker
4025 characters, the face to be used by font-lock for highlighting in Org-mode
4026 Emacs buffers, and the HTML tags to be used for this.
4027 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4028 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4029 Use customize to modify this, or restart Emacs after changing it."
4030 :group 'org-appearance
4031 :set 'org-set-emph-re
4032 :type '(repeat
4033 (list
4034 (string :tag "Marker character")
4035 (choice
4036 (face :tag "Font-lock-face")
4037 (plist :tag "Face property list"))
4038 (string :tag "HTML start tag")
4039 (string :tag "HTML end tag")
4040 (option (const verbatim)))))
4042 (defvar org-syntax-table
4043 (let ((st (make-syntax-table)))
4044 (mapc (lambda(c) (modify-syntax-entry
4045 (string-to-char (car c)) "w p" st))
4046 org-emphasis-alist)
4047 st))
4049 (defvar org-protecting-blocks
4050 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4051 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4052 This is needed for font-lock setup.")
4054 ;;; Miscellaneous options
4056 (defgroup org-completion nil
4057 "Completion in Org-mode."
4058 :tag "Org Completion"
4059 :group 'org)
4061 (defcustom org-completion-use-ido nil
4062 "Non-nil means use ido completion wherever possible.
4063 Note that `ido-mode' must be active for this variable to be relevant.
4064 If you decide to turn this variable on, you might well want to turn off
4065 `org-outline-path-complete-in-steps'.
4066 See also `org-completion-use-iswitchb'."
4067 :group 'org-completion
4068 :type 'boolean)
4070 (defcustom org-completion-use-iswitchb nil
4071 "Non-nil means use iswitchb completion wherever possible.
4072 Note that `iswitchb-mode' must be active for this variable to be relevant.
4073 If you decide to turn this variable on, you might well want to turn off
4074 `org-outline-path-complete-in-steps'.
4075 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4076 :group 'org-completion
4077 :type 'boolean)
4079 (defcustom org-completion-fallback-command 'hippie-expand
4080 "The expansion command called by \\[pcomplete] in normal context.
4081 Normal means, no org-mode-specific context."
4082 :group 'org-completion
4083 :type 'function)
4085 ;;; Functions and variables from their packages
4086 ;; Declared here to avoid compiler warnings
4088 ;; XEmacs only
4089 (defvar outline-mode-menu-heading)
4090 (defvar outline-mode-menu-show)
4091 (defvar outline-mode-menu-hide)
4092 (defvar zmacs-regions) ; XEmacs regions
4094 ;; Emacs only
4095 (defvar mark-active)
4097 ;; Various packages
4098 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4099 (declare-function calendar-forward-day "cal-move" (arg))
4100 (declare-function calendar-goto-date "cal-move" (date))
4101 (declare-function calendar-goto-today "cal-move" ())
4102 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4103 (defvar calc-embedded-close-formula)
4104 (defvar calc-embedded-open-formula)
4105 (declare-function cdlatex-tab "ext:cdlatex" ())
4106 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4107 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4108 (defvar font-lock-unfontify-region-function)
4109 (declare-function iswitchb-read-buffer "iswitchb"
4110 (prompt &optional default require-match start matches-set))
4111 (defvar iswitchb-temp-buflist)
4112 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4113 (defvar org-agenda-tags-todo-honor-ignore-options)
4114 (declare-function org-agenda-skip "org-agenda" ())
4115 (declare-function
4116 org-agenda-format-item "org-agenda"
4117 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4118 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4119 (declare-function org-agenda-change-all-lines "org-agenda"
4120 (newhead hdmarker &optional fixface just-this))
4121 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4122 (declare-function org-agenda-maybe-redo "org-agenda" ())
4123 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4124 (beg end))
4125 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4126 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4127 "org-agenda" (&optional end))
4128 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4129 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4130 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4131 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4132 (declare-function org-indent-mode "org-indent" (&optional arg))
4133 (declare-function parse-time-string "parse-time" (string))
4134 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4135 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4136 (defvar remember-data-file)
4137 (defvar texmathp-why)
4138 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4139 (declare-function table--at-cell-p "table" (position &optional object at-column))
4141 (defvar org-latex-regexps)
4143 ;;; Autoload and prepare some org modules
4145 ;; Some table stuff that needs to be defined here, because it is used
4146 ;; by the functions setting up org-mode or checking for table context.
4148 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4149 "Detect an org-type or table-type table.")
4150 (defconst org-table-line-regexp "^[ \t]*|"
4151 "Detect an org-type table line.")
4152 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4153 "Detect an org-type table line.")
4154 (defconst org-table-hline-regexp "^[ \t]*|-"
4155 "Detect an org-type table hline.")
4156 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4157 "Detect a table-type table hline.")
4158 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4159 "Detect the first line outside a table when searching from within it.
4160 This works for both table types.")
4162 ;; Autoload the functions in org-table.el that are needed by functions here.
4164 (eval-and-compile
4165 (org-autoload "org-table"
4166 '(org-table-begin org-table-blank-field org-table-end)))
4168 ;;;###autoload
4169 (defun turn-on-orgtbl ()
4170 "Unconditionally turn on `orgtbl-mode'."
4171 (require 'org-table)
4172 (orgtbl-mode 1))
4174 (defun org-at-table-p (&optional table-type)
4175 "Return t if the cursor is inside an org-type table.
4176 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4177 (if org-enable-table-editor
4178 (save-excursion
4179 (beginning-of-line 1)
4180 (looking-at (if table-type org-table-any-line-regexp
4181 org-table-line-regexp)))
4182 nil))
4183 (defsubst org-table-p () (org-at-table-p))
4185 (defun org-at-table.el-p ()
4186 "Return t if and only if we are at a table.el table."
4187 (and (org-at-table-p 'any)
4188 (save-excursion
4189 (goto-char (org-table-begin 'any))
4190 (looking-at org-table1-hline-regexp))))
4191 (defun org-table-recognize-table.el ()
4192 "If there is a table.el table nearby, recognize it and move into it."
4193 (if org-table-tab-recognizes-table.el
4194 (if (org-at-table.el-p)
4195 (progn
4196 (beginning-of-line 1)
4197 (if (looking-at org-table-dataline-regexp)
4199 (if (looking-at org-table1-hline-regexp)
4200 (progn
4201 (beginning-of-line 2)
4202 (if (looking-at org-table-any-border-regexp)
4203 (beginning-of-line -1)))))
4204 (if (re-search-forward "|" (org-table-end t) t)
4205 (progn
4206 (require 'table)
4207 (if (table--at-cell-p (point))
4209 (message "recognizing table.el table...")
4210 (table-recognize-table)
4211 (message "recognizing table.el table...done")))
4212 (error "This should not happen"))
4214 nil)
4215 nil))
4217 (defun org-at-table-hline-p ()
4218 "Return t if the cursor is inside a hline in a table."
4219 (if org-enable-table-editor
4220 (save-excursion
4221 (beginning-of-line 1)
4222 (looking-at org-table-hline-regexp))
4223 nil))
4225 (defvar org-table-clean-did-remove-column nil)
4227 (defun org-table-map-tables (function &optional quietly)
4228 "Apply FUNCTION to the start of all tables in the buffer."
4229 (save-excursion
4230 (save-restriction
4231 (widen)
4232 (goto-char (point-min))
4233 (while (re-search-forward org-table-any-line-regexp nil t)
4234 (unless quietly
4235 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4236 (beginning-of-line 1)
4237 (when (and (looking-at org-table-line-regexp)
4238 ;; Exclude tables in src/example/verbatim/clocktable blocks
4239 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4240 (save-excursion (funcall function))
4241 (or (looking-at org-table-line-regexp)
4242 (forward-char 1)))
4243 (re-search-forward org-table-any-border-regexp nil 1))))
4244 (unless quietly (message "Mapping tables: done")))
4246 ;; Declare and autoload functions from ox.el and al.
4248 (declare-function org-export-get-environment "ox"
4249 (&optional backend subtreep ext-plist))
4250 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4252 ;; Declare and autoload functions from org-agenda.el
4254 (eval-and-compile
4255 (org-autoload "org-agenda"
4256 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4258 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4259 (declare-function org-clock-update-mode-line "org-clock" ())
4260 (declare-function org-resolve-clocks "org-clock"
4261 (&optional also-non-dangling-p prompt last-valid))
4262 (defvar org-clock-start-time)
4263 (defvar org-clock-marker (make-marker)
4264 "Marker recording the last clock-in.")
4265 (defvar org-clock-hd-marker (make-marker)
4266 "Marker recording the last clock-in, but the headline position.")
4267 (defvar org-clock-heading ""
4268 "The heading of the current clock entry.")
4269 (defun org-clock-is-active ()
4270 "Return non-nil if clock is currently running.
4271 The return value is actually the clock marker."
4272 (marker-buffer org-clock-marker))
4274 (eval-and-compile
4275 (org-autoload "org-clock" '(org-clock-remove-overlays
4276 org-clock-update-time-maybe
4277 org-clocktable-shift)))
4279 (defun org-check-running-clock ()
4280 "Check if the current buffer contains the running clock.
4281 If yes, offer to stop it and to save the buffer with the changes."
4282 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4283 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4284 (buffer-name))))
4285 (org-clock-out)
4286 (when (y-or-n-p "Save changed buffer?")
4287 (save-buffer))))
4289 (defun org-clocktable-try-shift (dir n)
4290 "Check if this line starts a clock table, if yes, shift the time block."
4291 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4292 (org-clocktable-shift dir n)))
4294 ;;;###autoload
4295 (defun org-clock-persistence-insinuate ()
4296 "Set up hooks for clock persistence."
4297 (require 'org-clock)
4298 (add-hook 'org-mode-hook 'org-clock-load)
4299 (add-hook 'kill-emacs-hook 'org-clock-save))
4301 ;; Define the variable already here, to make sure we have it.
4302 (defvar org-indent-mode nil
4303 "Non-nil if Org-Indent mode is enabled.
4304 Use the command `org-indent-mode' to change this variable.")
4306 ;; Autoload archiving code
4307 ;; The stuff that is needed for cycling and tags has to be defined here.
4309 (defgroup org-archive nil
4310 "Options concerning archiving in Org-mode."
4311 :tag "Org Archive"
4312 :group 'org-structure)
4314 (defcustom org-archive-location "%s_archive::"
4315 "The location where subtrees should be archived.
4317 The value of this variable is a string, consisting of two parts,
4318 separated by a double-colon. The first part is a filename and
4319 the second part is a headline.
4321 When the filename is omitted, archiving happens in the same file.
4322 %s in the filename will be replaced by the current file
4323 name (without the directory part). Archiving to a different file
4324 is useful to keep archived entries from contributing to the
4325 Org-mode Agenda.
4327 The archived entries will be filed as subtrees of the specified
4328 headline. When the headline is omitted, the subtrees are simply
4329 filed away at the end of the file, as top-level entries. Also in
4330 the heading you can use %s to represent the file name, this can be
4331 useful when using the same archive for a number of different files.
4333 Here are a few examples:
4334 \"%s_archive::\"
4335 If the current file is Projects.org, archive in file
4336 Projects.org_archive, as top-level trees. This is the default.
4338 \"::* Archived Tasks\"
4339 Archive in the current file, under the top-level headline
4340 \"* Archived Tasks\".
4342 \"~/org/archive.org::\"
4343 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4345 \"~/org/archive.org::* From %s\"
4346 Archive in file ~/org/archive.org (absolute path), under headlines
4347 \"From FILENAME\" where file name is the current file name.
4349 \"~/org/datetree.org::datetree/* Finished Tasks\"
4350 The \"datetree/\" string is special, signifying to archive
4351 items to the datetree. Items are placed in either the CLOSED
4352 date of the item, or the current date if there is no CLOSED date.
4353 The heading will be a subentry to the current date. There doesn't
4354 need to be a heading, but there always needs to be a slash after
4355 datetree. For example, to store archived items directly in the
4356 datetree, use \"~/org/datetree.org::datetree/\".
4358 \"basement::** Finished Tasks\"
4359 Archive in file ./basement (relative path), as level 3 trees
4360 below the level 2 heading \"** Finished Tasks\".
4362 You may set this option on a per-file basis by adding to the buffer a
4363 line like
4365 #+ARCHIVE: basement::** Finished Tasks
4367 You may also define it locally for a subtree by setting an ARCHIVE property
4368 in the entry. If such a property is found in an entry, or anywhere up
4369 the hierarchy, it will be used."
4370 :group 'org-archive
4371 :type 'string)
4373 (defcustom org-archive-tag "ARCHIVE"
4374 "The tag that marks a subtree as archived.
4375 An archived subtree does not open during visibility cycling, and does
4376 not contribute to the agenda listings.
4377 After changing this, font-lock must be restarted in the relevant buffers to
4378 get the proper fontification."
4379 :group 'org-archive
4380 :group 'org-keywords
4381 :type 'string)
4383 (defcustom org-agenda-skip-archived-trees t
4384 "Non-nil means the agenda will skip any items located in archived trees.
4385 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4386 variable is no longer recommended, you should leave it at the value t.
4387 Instead, use the key `v' to cycle the archives-mode in the agenda."
4388 :group 'org-archive
4389 :group 'org-agenda-skip
4390 :type 'boolean)
4392 (defcustom org-columns-skip-archived-trees t
4393 "Non-nil means ignore archived trees when creating column view."
4394 :group 'org-archive
4395 :group 'org-properties
4396 :type 'boolean)
4398 (defcustom org-cycle-open-archived-trees nil
4399 "Non-nil means `org-cycle' will open archived trees.
4400 An archived tree is a tree marked with the tag ARCHIVE.
4401 When nil, archived trees will stay folded. You can still open them with
4402 normal outline commands like `show-all', but not with the cycling commands."
4403 :group 'org-archive
4404 :group 'org-cycle
4405 :type 'boolean)
4407 (defcustom org-sparse-tree-open-archived-trees nil
4408 "Non-nil means sparse tree construction shows matches in archived trees.
4409 When nil, matches in these trees are highlighted, but the trees are kept in
4410 collapsed state."
4411 :group 'org-archive
4412 :group 'org-sparse-trees
4413 :type 'boolean)
4415 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4416 "The default date type when building a sparse tree.
4417 When this is nil, a date is a scheduled or a deadline timestamp.
4418 Otherwise, these types are allowed:
4420 all: all timestamps
4421 active: only active timestamps (<...>)
4422 inactive: only inactive timestamps (<...)
4423 scheduled: only scheduled timestamps
4424 deadline: only deadline timestamps"
4425 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4426 (const :tag "All timestamps" all)
4427 (const :tag "Only active timestamps" active)
4428 (const :tag "Only inactive timestamps" inactive)
4429 (const :tag "Only scheduled timestamps" scheduled)
4430 (const :tag "Only deadline timestamps" deadline))
4431 :version "24.3"
4432 :group 'org-sparse-trees)
4434 (defun org-cycle-hide-archived-subtrees (state)
4435 "Re-hide all archived subtrees after a visibility state change."
4436 (when (and (not org-cycle-open-archived-trees)
4437 (not (memq state '(overview folded))))
4438 (save-excursion
4439 (let* ((globalp (memq state '(contents all)))
4440 (beg (if globalp (point-min) (point)))
4441 (end (if globalp (point-max) (org-end-of-subtree t))))
4442 (org-hide-archived-subtrees beg end)
4443 (goto-char beg)
4444 (if (looking-at (concat ".*:" org-archive-tag ":"))
4445 (message "%s" (substitute-command-keys
4446 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4448 (defun org-force-cycle-archived ()
4449 "Cycle subtree even if it is archived."
4450 (interactive)
4451 (setq this-command 'org-cycle)
4452 (let ((org-cycle-open-archived-trees t))
4453 (call-interactively 'org-cycle)))
4455 (defun org-hide-archived-subtrees (beg end)
4456 "Re-hide all archived subtrees after a visibility state change."
4457 (save-excursion
4458 (let* ((re (concat ":" org-archive-tag ":")))
4459 (goto-char beg)
4460 (while (re-search-forward re end t)
4461 (when (org-at-heading-p)
4462 (org-flag-subtree t)
4463 (org-end-of-subtree t))))))
4465 (declare-function outline-end-of-heading "outline" ())
4466 (declare-function outline-flag-region "outline" (from to flag))
4467 (defun org-flag-subtree (flag)
4468 (save-excursion
4469 (org-back-to-heading t)
4470 (outline-end-of-heading)
4471 (outline-flag-region (point)
4472 (progn (org-end-of-subtree t) (point))
4473 flag)))
4475 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4477 (eval-and-compile
4478 (org-autoload "org-archive"
4479 '(org-add-archive-files)))
4481 ;; Autoload Column View Code
4483 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4484 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4485 (declare-function org-columns-compute "org-colview" (property))
4487 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4488 '(org-columns-number-to-string
4489 org-columns-get-format-and-top-level
4490 org-columns-compute
4491 org-columns-remove-overlays))
4493 ;; Autoload ID code
4495 (declare-function org-id-store-link "org-id")
4496 (declare-function org-id-locations-load "org-id")
4497 (declare-function org-id-locations-save "org-id")
4498 (defvar org-id-track-globally)
4499 (org-autoload "org-id"
4500 '(org-id-new
4501 org-id-copy
4502 org-id-get-with-outline-path-completion
4503 org-id-get-with-outline-drilling))
4505 ;;; Variables for pre-computed regular expressions, all buffer local
4507 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4508 "Matches first line of a hidden block.")
4509 (make-variable-buffer-local 'org-drawer-regexp)
4510 (defvar org-todo-regexp nil
4511 "Matches any of the TODO state keywords.")
4512 (make-variable-buffer-local 'org-todo-regexp)
4513 (defvar org-not-done-regexp nil
4514 "Matches any of the TODO state keywords except the last one.")
4515 (make-variable-buffer-local 'org-not-done-regexp)
4516 (defvar org-not-done-heading-regexp nil
4517 "Matches a TODO headline that is not done.")
4518 (make-variable-buffer-local 'org-not-done-regexp)
4519 (defvar org-todo-line-regexp nil
4520 "Matches a headline and puts TODO state into group 2 if present.")
4521 (make-variable-buffer-local 'org-todo-line-regexp)
4522 (defvar org-complex-heading-regexp nil
4523 "Matches a headline and puts everything into groups:
4524 group 1: the stars
4525 group 2: The todo keyword, maybe
4526 group 3: Priority cookie
4527 group 4: True headline
4528 group 5: Tags")
4529 (make-variable-buffer-local 'org-complex-heading-regexp)
4530 (defvar org-complex-heading-regexp-format nil
4531 "Printf format to make regexp to match an exact headline.
4532 This regexp will match the headline of any node which has the
4533 exact headline text that is put into the format, but may have any
4534 TODO state, priority and tags.")
4535 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4536 (defvar org-todo-line-tags-regexp nil
4537 "Matches a headline and puts TODO state into group 2 if present.
4538 Also put tags into group 4 if tags are present.")
4539 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4540 (defvar org-ds-keyword-length 12
4541 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4542 (make-variable-buffer-local 'org-ds-keyword-length)
4543 (defvar org-deadline-regexp nil
4544 "Matches the DEADLINE keyword.")
4545 (make-variable-buffer-local 'org-deadline-regexp)
4546 (defvar org-deadline-time-regexp nil
4547 "Matches the DEADLINE keyword together with a time stamp.")
4548 (make-variable-buffer-local 'org-deadline-time-regexp)
4549 (defvar org-deadline-line-regexp nil
4550 "Matches the DEADLINE keyword and the rest of the line.")
4551 (make-variable-buffer-local 'org-deadline-line-regexp)
4552 (defvar org-scheduled-regexp nil
4553 "Matches the SCHEDULED keyword.")
4554 (make-variable-buffer-local 'org-scheduled-regexp)
4555 (defvar org-scheduled-time-regexp nil
4556 "Matches the SCHEDULED keyword together with a time stamp.")
4557 (make-variable-buffer-local 'org-scheduled-time-regexp)
4558 (defvar org-closed-time-regexp nil
4559 "Matches the CLOSED keyword together with a time stamp.")
4560 (make-variable-buffer-local 'org-closed-time-regexp)
4562 (defvar org-keyword-time-regexp nil
4563 "Matches any of the 4 keywords, together with the time stamp.")
4564 (make-variable-buffer-local 'org-keyword-time-regexp)
4565 (defvar org-keyword-time-not-clock-regexp nil
4566 "Matches any of the 3 keywords, together with the time stamp.")
4567 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4568 (defvar org-maybe-keyword-time-regexp nil
4569 "Matches a timestamp, possibly preceded by a keyword.")
4570 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4571 (defvar org-all-time-keywords nil
4572 "List of time keywords.")
4573 (make-variable-buffer-local 'org-all-time-keywords)
4575 (defconst org-plain-time-of-day-regexp
4576 (concat
4577 "\\(\\<[012]?[0-9]"
4578 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4579 "\\(--?"
4580 "\\(\\<[012]?[0-9]"
4581 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4582 "\\)?")
4583 "Regular expression to match a plain time or time range.
4584 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4585 groups carry important information:
4586 0 the full match
4587 1 the first time, range or not
4588 8 the second time, if it is a range.")
4590 (defconst org-plain-time-extension-regexp
4591 (concat
4592 "\\(\\<[012]?[0-9]"
4593 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4594 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4595 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4596 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4597 groups carry important information:
4598 0 the full match
4599 7 hours of duration
4600 9 minutes of duration")
4602 (defconst org-stamp-time-of-day-regexp
4603 (concat
4604 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4605 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4606 "\\(--?"
4607 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4608 "Regular expression to match a timestamp time or time range.
4609 After a match, the following groups carry important information:
4610 0 the full match
4611 1 date plus weekday, for back referencing to make sure both times are on the same day
4612 2 the first time, range or not
4613 4 the second time, if it is a range.")
4615 (defconst org-startup-options
4616 '(("fold" org-startup-folded t)
4617 ("overview" org-startup-folded t)
4618 ("nofold" org-startup-folded nil)
4619 ("showall" org-startup-folded nil)
4620 ("showeverything" org-startup-folded showeverything)
4621 ("content" org-startup-folded content)
4622 ("indent" org-startup-indented t)
4623 ("noindent" org-startup-indented nil)
4624 ("hidestars" org-hide-leading-stars t)
4625 ("showstars" org-hide-leading-stars nil)
4626 ("odd" org-odd-levels-only t)
4627 ("oddeven" org-odd-levels-only nil)
4628 ("align" org-startup-align-all-tables t)
4629 ("noalign" org-startup-align-all-tables nil)
4630 ("inlineimages" org-startup-with-inline-images t)
4631 ("noinlineimages" org-startup-with-inline-images nil)
4632 ("latexpreview" org-startup-with-latex-preview t)
4633 ("nolatexpreview" org-startup-with-latex-preview nil)
4634 ("customtime" org-display-custom-times t)
4635 ("logdone" org-log-done time)
4636 ("lognotedone" org-log-done note)
4637 ("nologdone" org-log-done nil)
4638 ("lognoteclock-out" org-log-note-clock-out t)
4639 ("nolognoteclock-out" org-log-note-clock-out nil)
4640 ("logrepeat" org-log-repeat state)
4641 ("lognoterepeat" org-log-repeat note)
4642 ("logdrawer" org-log-into-drawer t)
4643 ("nologdrawer" org-log-into-drawer nil)
4644 ("logstatesreversed" org-log-states-order-reversed t)
4645 ("nologstatesreversed" org-log-states-order-reversed nil)
4646 ("nologrepeat" org-log-repeat nil)
4647 ("logreschedule" org-log-reschedule time)
4648 ("lognotereschedule" org-log-reschedule note)
4649 ("nologreschedule" org-log-reschedule nil)
4650 ("logredeadline" org-log-redeadline time)
4651 ("lognoteredeadline" org-log-redeadline note)
4652 ("nologredeadline" org-log-redeadline nil)
4653 ("logrefile" org-log-refile time)
4654 ("lognoterefile" org-log-refile note)
4655 ("nologrefile" org-log-refile nil)
4656 ("fninline" org-footnote-define-inline t)
4657 ("nofninline" org-footnote-define-inline nil)
4658 ("fnlocal" org-footnote-section nil)
4659 ("fnauto" org-footnote-auto-label t)
4660 ("fnprompt" org-footnote-auto-label nil)
4661 ("fnconfirm" org-footnote-auto-label confirm)
4662 ("fnplain" org-footnote-auto-label plain)
4663 ("fnadjust" org-footnote-auto-adjust t)
4664 ("nofnadjust" org-footnote-auto-adjust nil)
4665 ("constcgs" constants-unit-system cgs)
4666 ("constSI" constants-unit-system SI)
4667 ("noptag" org-tag-persistent-alist nil)
4668 ("hideblocks" org-hide-block-startup t)
4669 ("nohideblocks" org-hide-block-startup nil)
4670 ("beamer" org-startup-with-beamer-mode t)
4671 ("entitiespretty" org-pretty-entities t)
4672 ("entitiesplain" org-pretty-entities nil))
4673 "Variable associated with STARTUP options for org-mode.
4674 Each element is a list of three items: the startup options (as written
4675 in the #+STARTUP line), the corresponding variable, and the value to set
4676 this variable to if the option is found. An optional forth element PUSH
4677 means to push this value onto the list in the variable.")
4679 (defun org-update-property-plist (key val props)
4680 "Update PROPS with KEY and VAL."
4681 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4682 (key (if appending (substring key 0 (- (length key) 1)) key))
4683 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4684 (previous (cdr (assoc key props))))
4685 (if appending
4686 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4687 (cons (cons key val) remainder))))
4689 (defconst org-block-regexp
4690 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4691 "Regular expression for hiding blocks.")
4692 (defconst org-heading-keyword-regexp-format
4693 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4694 "Printf format for a regexp matching an headline with some keyword.
4695 This regexp will match the headline of any node which has the
4696 exact keyword that is put into the format. The keyword isn't in
4697 any group by default, but the stars and the body are.")
4698 (defconst org-heading-keyword-maybe-regexp-format
4699 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4700 "Printf format for a regexp matching an headline, possibly with some keyword.
4701 This regexp can match any headline with the specified keyword, or
4702 without a keyword. The keyword isn't in any group by default,
4703 but the stars and the body are.")
4705 (defun org-set-regexps-and-options ()
4706 "Precompute regular expressions for current buffer."
4707 (when (derived-mode-p 'org-mode)
4708 (org-set-local 'org-todo-kwd-alist nil)
4709 (org-set-local 'org-todo-key-alist nil)
4710 (org-set-local 'org-todo-key-trigger nil)
4711 (org-set-local 'org-todo-keywords-1 nil)
4712 (org-set-local 'org-done-keywords nil)
4713 (org-set-local 'org-todo-heads nil)
4714 (org-set-local 'org-todo-sets nil)
4715 (org-set-local 'org-todo-log-states nil)
4716 (org-set-local 'org-file-properties nil)
4717 (org-set-local 'org-file-tags nil)
4718 (let ((re (org-make-options-regexp
4719 '("CATEGORY" "TODO" "COLUMNS"
4720 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4721 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4722 "OPTIONS")
4723 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4724 (splitre "[ \t]+")
4725 (scripts org-use-sub-superscripts)
4726 kwds kws0 kwsa key log value cat arch tags const links hw dws
4727 tail sep kws1 prio props ftags drawers beamer-p
4728 ext-setup-or-nil setup-contents (start 0))
4729 (save-excursion
4730 (save-restriction
4731 (widen)
4732 (goto-char (point-min))
4733 (while (or (and ext-setup-or-nil
4734 (string-match re ext-setup-or-nil start)
4735 (setq start (match-end 0)))
4736 (and (setq ext-setup-or-nil nil start 0)
4737 (re-search-forward re nil t)))
4738 (setq key (upcase (match-string 1 ext-setup-or-nil))
4739 value (org-match-string-no-properties 2 ext-setup-or-nil))
4740 (if (stringp value) (setq value (org-trim value)))
4741 (cond
4742 ((equal key "CATEGORY")
4743 (setq cat value))
4744 ((member key '("SEQ_TODO" "TODO"))
4745 (push (cons 'sequence (org-split-string value splitre)) kwds))
4746 ((equal key "TYP_TODO")
4747 (push (cons 'type (org-split-string value splitre)) kwds))
4748 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4749 ;; general TODO-like setup
4750 (push (cons (intern (downcase (match-string 1 key)))
4751 (org-split-string value splitre)) kwds))
4752 ((equal key "TAGS")
4753 (setq tags (append tags (if tags '("\\n") nil)
4754 (org-split-string value splitre))))
4755 ((equal key "COLUMNS")
4756 (org-set-local 'org-columns-default-format value))
4757 ((equal key "LINK")
4758 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4759 (push (cons (match-string 1 value)
4760 (org-trim (match-string 2 value)))
4761 links)))
4762 ((equal key "PRIORITIES")
4763 (setq prio (org-split-string value " +")))
4764 ((equal key "PROPERTY")
4765 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4766 (setq props (org-update-property-plist (match-string 1 value)
4767 (match-string 2 value)
4768 props))))
4769 ((equal key "FILETAGS")
4770 (when (string-match "\\S-" value)
4771 (setq ftags
4772 (append
4773 ftags
4774 (apply 'append
4775 (mapcar (lambda (x) (org-split-string x ":"))
4776 (org-split-string value)))))))
4777 ((equal key "DRAWERS")
4778 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4779 ((equal key "CONSTANTS")
4780 (setq const (append const (org-split-string value splitre))))
4781 ((equal key "STARTUP")
4782 (let ((opts (org-split-string value splitre))
4783 l var val)
4784 (while (setq l (pop opts))
4785 (when (setq l (assoc l org-startup-options))
4786 (setq var (nth 1 l) val (nth 2 l))
4787 (if (not (nth 3 l))
4788 (set (make-local-variable var) val)
4789 (if (not (listp (symbol-value var)))
4790 (set (make-local-variable var) nil))
4791 (set (make-local-variable var) (symbol-value var))
4792 (add-to-list var val))))))
4793 ((equal key "ARCHIVE")
4794 (setq arch value)
4795 (remove-text-properties 0 (length arch)
4796 '(face t fontified t) arch))
4797 ((equal key "LATEX_CLASS")
4798 (setq beamer-p (equal value "beamer")))
4799 ((equal key "OPTIONS")
4800 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4801 (setq scripts (read (match-string 2 value)))))
4802 ((equal key "SETUPFILE")
4803 (setq setup-contents (org-file-contents
4804 (expand-file-name
4805 (org-remove-double-quotes value))
4806 'noerror))
4807 (if (not ext-setup-or-nil)
4808 (setq ext-setup-or-nil setup-contents start 0)
4809 (setq ext-setup-or-nil
4810 (concat (substring ext-setup-or-nil 0 start)
4811 "\n" setup-contents "\n"
4812 (substring ext-setup-or-nil start)))))))
4813 ;; search for property blocks
4814 (goto-char (point-min))
4815 (while (re-search-forward org-block-regexp nil t)
4816 (when (equal "PROPERTY" (upcase (match-string 1)))
4817 (setq value (replace-regexp-in-string
4818 "[\n\r]" " " (match-string 4)))
4819 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4820 (setq props (org-update-property-plist (match-string 1 value)
4821 (match-string 2 value)
4822 props)))))))
4823 (org-set-local 'org-use-sub-superscripts scripts)
4824 (when cat
4825 (org-set-local 'org-category (intern cat))
4826 (push (cons "CATEGORY" cat) props))
4827 (when prio
4828 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4829 (setq prio (mapcar 'string-to-char prio))
4830 (org-set-local 'org-highest-priority (nth 0 prio))
4831 (org-set-local 'org-lowest-priority (nth 1 prio))
4832 (org-set-local 'org-default-priority (nth 2 prio)))
4833 (and props (org-set-local 'org-file-properties (nreverse props)))
4834 (and ftags (org-set-local 'org-file-tags
4835 (mapcar 'org-add-prop-inherited ftags)))
4836 (and drawers (org-set-local 'org-drawers drawers))
4837 (and arch (org-set-local 'org-archive-location arch))
4838 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4839 ;; Process the TODO keywords
4840 (unless kwds
4841 ;; Use the global values as if they had been given locally.
4842 (setq kwds (default-value 'org-todo-keywords))
4843 (if (stringp (car kwds))
4844 (setq kwds (list (cons org-todo-interpretation
4845 (default-value 'org-todo-keywords)))))
4846 (setq kwds (reverse kwds)))
4847 (setq kwds (nreverse kwds))
4848 (let (inter kws kw)
4849 (while (setq kws (pop kwds))
4850 (let ((kws (or
4851 (run-hook-with-args-until-success
4852 'org-todo-setup-filter-hook kws)
4853 kws)))
4854 (setq inter (pop kws) sep (member "|" kws)
4855 kws0 (delete "|" (copy-sequence kws))
4856 kwsa nil
4857 kws1 (mapcar
4858 (lambda (x)
4859 ;; 1 2
4860 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4861 (progn
4862 (setq kw (match-string 1 x)
4863 key (and (match-end 2) (match-string 2 x))
4864 log (org-extract-log-state-settings x))
4865 (push (cons kw (and key (string-to-char key))) kwsa)
4866 (and log (push log org-todo-log-states))
4868 (error "Invalid TODO keyword %s" x)))
4869 kws0)
4870 kwsa (if kwsa (append '((:startgroup))
4871 (nreverse kwsa)
4872 '((:endgroup))))
4873 hw (car kws1)
4874 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4875 tail (list inter hw (car dws) (org-last dws))))
4876 (add-to-list 'org-todo-heads hw 'append)
4877 (push kws1 org-todo-sets)
4878 (setq org-done-keywords (append org-done-keywords dws nil))
4879 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4880 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4881 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4882 (setq org-todo-sets (nreverse org-todo-sets)
4883 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4884 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4885 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4886 ;; Process the constants
4887 (when const
4888 (let (e cst)
4889 (while (setq e (pop const))
4890 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4891 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4892 (setq org-table-formula-constants-local cst)))
4894 ;; Process the tags.
4895 (when tags
4896 (let (e tgs)
4897 (while (setq e (pop tags))
4898 (cond
4899 ((equal e "{") (push '(:startgroup) tgs))
4900 ((equal e "}") (push '(:endgroup) tgs))
4901 ((equal e "\\n") (push '(:newline) tgs))
4902 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4903 (push (cons (match-string 1 e)
4904 (string-to-char (match-string 2 e)))
4905 tgs))
4906 (t (push (list e) tgs))))
4907 (org-set-local 'org-tag-alist nil)
4908 (while (setq e (pop tgs))
4909 (or (and (stringp (car e))
4910 (assoc (car e) org-tag-alist))
4911 (push e org-tag-alist)))))
4913 ;; Compute the regular expressions and other local variables.
4914 ;; Using `org-outline-regexp-bol' would complicate them much,
4915 ;; because of the fixed white space at the end of that string.
4916 (if (not org-done-keywords)
4917 (setq org-done-keywords (and org-todo-keywords-1
4918 (list (org-last org-todo-keywords-1)))))
4919 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4920 (length org-scheduled-string)
4921 (length org-clock-string)
4922 (length org-closed-string)))
4923 org-drawer-regexp
4924 (concat "^[ \t]*:\\("
4925 (mapconcat 'regexp-quote org-drawers "\\|")
4926 "\\):[ \t]*$")
4927 org-not-done-keywords
4928 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4929 org-todo-regexp
4930 (concat "\\("
4931 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4932 "\\)")
4933 org-not-done-regexp
4934 (concat "\\("
4935 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4936 "\\)")
4937 org-not-done-heading-regexp
4938 (format org-heading-keyword-regexp-format org-not-done-regexp)
4939 org-todo-line-regexp
4940 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4941 org-complex-heading-regexp
4942 (concat "^\\(\\*+\\)"
4943 "\\(?: +" org-todo-regexp "\\)?"
4944 "\\(?: +\\(\\[#.\\]\\)\\)?"
4945 "\\(?: +\\(.*?\\)\\)??"
4946 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4947 "[ \t]*$")
4948 org-complex-heading-regexp-format
4949 (concat "^\\(\\*+\\)"
4950 "\\(?: +" org-todo-regexp "\\)?"
4951 "\\(?: +\\(\\[#.\\]\\)\\)?"
4952 "\\(?: +"
4953 ;; Stats cookies can be stuck to body.
4954 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4955 "\\(%s\\)"
4956 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4957 "\\)"
4958 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4959 "[ \t]*$")
4960 org-todo-line-tags-regexp
4961 (concat "^\\(\\*+\\)"
4962 "\\(?: +" org-todo-regexp "\\)?"
4963 "\\(?: +\\(.*?\\)\\)??"
4964 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4965 "[ \t]*$")
4966 org-deadline-regexp (concat "\\<" org-deadline-string)
4967 org-deadline-time-regexp
4968 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4969 org-deadline-line-regexp
4970 (concat "\\<\\(" org-deadline-string "\\).*")
4971 org-scheduled-regexp
4972 (concat "\\<" org-scheduled-string)
4973 org-scheduled-time-regexp
4974 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4975 org-closed-time-regexp
4976 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4977 org-keyword-time-regexp
4978 (concat "\\<\\(" org-scheduled-string
4979 "\\|" org-deadline-string
4980 "\\|" org-closed-string
4981 "\\|" org-clock-string "\\)"
4982 " *[[<]\\([^]>]+\\)[]>]")
4983 org-keyword-time-not-clock-regexp
4984 (concat "\\<\\(" org-scheduled-string
4985 "\\|" org-deadline-string
4986 "\\|" org-closed-string
4987 "\\)"
4988 " *[[<]\\([^]>]+\\)[]>]")
4989 org-maybe-keyword-time-regexp
4990 (concat "\\(\\<\\(" org-scheduled-string
4991 "\\|" org-deadline-string
4992 "\\|" org-closed-string
4993 "\\|" org-clock-string "\\)\\)?"
4994 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4995 org-all-time-keywords
4996 (mapcar (lambda (w) (substring w 0 -1))
4997 (list org-scheduled-string org-deadline-string
4998 org-clock-string org-closed-string)))
4999 (org-set-font-lock-defaults))))
5001 (defun org-file-contents (file &optional noerror)
5002 "Return the contents of FILE, as a string."
5003 (if (or (not file)
5004 (not (file-readable-p file)))
5005 (if noerror
5006 (progn
5007 (message "Cannot read file \"%s\"" file)
5008 (ding) (sit-for 2)
5010 (error "Cannot read file \"%s\"" file))
5011 (with-temp-buffer
5012 (insert-file-contents file)
5013 (buffer-string))))
5015 (defun org-extract-log-state-settings (x)
5016 "Extract the log state setting from a TODO keyword string.
5017 This will extract info from a string like \"WAIT(w@/!)\"."
5018 (let (kw key log1 log2)
5019 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5020 (setq kw (match-string 1 x)
5021 key (and (match-end 2) (match-string 2 x))
5022 log1 (and (match-end 3) (match-string 3 x))
5023 log2 (and (match-end 4) (match-string 4 x)))
5024 (and (or log1 log2)
5025 (list kw
5026 (and log1 (if (equal log1 "!") 'time 'note))
5027 (and log2 (if (equal log2 "!") 'time 'note)))))))
5029 (defun org-remove-keyword-keys (list)
5030 "Remove a pair of parenthesis at the end of each string in LIST."
5031 (mapcar (lambda (x)
5032 (if (string-match "(.*)$" x)
5033 (substring x 0 (match-beginning 0))
5035 list))
5037 (defun org-assign-fast-keys (alist)
5038 "Assign fast keys to a keyword-key alist.
5039 Respect keys that are already there."
5040 (let (new e (alt ?0))
5041 (while (setq e (pop alist))
5042 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5043 (cdr e)) ;; Key already assigned.
5044 (push e new)
5045 (let ((clist (string-to-list (downcase (car e))))
5046 (used (append new alist)))
5047 (when (= (car clist) ?@)
5048 (pop clist))
5049 (while (and clist (rassoc (car clist) used))
5050 (pop clist))
5051 (unless clist
5052 (while (rassoc alt used)
5053 (incf alt)))
5054 (push (cons (car e) (or (car clist) alt)) new))))
5055 (nreverse new)))
5057 ;;; Some variables used in various places
5059 (defvar org-window-configuration nil
5060 "Used in various places to store a window configuration.")
5061 (defvar org-selected-window nil
5062 "Used in various places to store a window configuration.")
5063 (defvar org-finish-function nil
5064 "Function to be called when `C-c C-c' is used.
5065 This is for getting out of special buffers like capture.")
5068 ;; FIXME: Occasionally check by commenting these, to make sure
5069 ;; no other functions uses these, forgetting to let-bind them.
5070 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5071 (defvar org-last-state)
5072 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5074 ;; Defined somewhere in this file, but used before definition.
5075 (defvar org-entities) ;; defined in org-entities.el
5076 (defvar org-struct-menu)
5077 (defvar org-org-menu)
5078 (defvar org-tbl-menu)
5080 ;;;; Define the Org-mode
5082 ;; We use a before-change function to check if a table might need
5083 ;; an update.
5084 (defvar org-table-may-need-update t
5085 "Indicates that a table might need an update.
5086 This variable is set by `org-before-change-function'.
5087 `org-table-align' sets it back to nil.")
5088 (defun org-before-change-function (beg end)
5089 "Every change indicates that a table might need an update."
5090 (setq org-table-may-need-update t))
5091 (defvar org-mode-map)
5092 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5093 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5094 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5095 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5096 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5097 (defvar org-table-buffer-is-an nil)
5099 (defvar bidi-paragraph-direction)
5100 (defvar buffer-face-mode-face)
5102 (require 'outline)
5103 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5104 (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"))
5105 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5107 ;; Other stuff we need.
5108 (require 'time-date)
5109 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5110 (require 'easymenu)
5111 (require 'overlay)
5113 ;; (require 'org-macs) moved higher up in the file before it is first used
5114 (require 'org-entities)
5115 ;; (require 'org-compat) moved higher up in the file before it is first used
5116 (require 'org-faces)
5117 (require 'org-list)
5118 (require 'org-pcomplete)
5119 (require 'org-src)
5120 (require 'org-footnote)
5122 ;; babel
5123 (require 'ob)
5125 ;;;###autoload
5126 (define-derived-mode org-mode outline-mode "Org"
5127 "Outline-based notes management and organizer, alias
5128 \"Carsten's outline-mode for keeping track of everything.\"
5130 Org-mode develops organizational tasks around a NOTES file which
5131 contains information about projects as plain text. Org-mode is
5132 implemented on top of outline-mode, which is ideal to keep the content
5133 of large files well structured. It supports ToDo items, deadlines and
5134 time stamps, which magically appear in the diary listing of the Emacs
5135 calendar. Tables are easily created with a built-in table editor.
5136 Plain text URL-like links connect to websites, emails (VM), Usenet
5137 messages (Gnus), BBDB entries, and any files related to the project.
5138 For printing and sharing of notes, an Org-mode file (or a part of it)
5139 can be exported as a structured ASCII or HTML file.
5141 The following commands are available:
5143 \\{org-mode-map}"
5145 ;; Get rid of Outline menus, they are not needed
5146 ;; Need to do this here because define-derived-mode sets up
5147 ;; the keymap so late. Still, it is a waste to call this each time
5148 ;; we switch another buffer into org-mode.
5149 (if (featurep 'xemacs)
5150 (when (boundp 'outline-mode-menu-heading)
5151 ;; Assume this is Greg's port, it uses easymenu
5152 (easy-menu-remove outline-mode-menu-heading)
5153 (easy-menu-remove outline-mode-menu-show)
5154 (easy-menu-remove outline-mode-menu-hide))
5155 (define-key org-mode-map [menu-bar headings] 'undefined)
5156 (define-key org-mode-map [menu-bar hide] 'undefined)
5157 (define-key org-mode-map [menu-bar show] 'undefined))
5159 (org-load-modules-maybe)
5160 (easy-menu-add org-org-menu)
5161 (easy-menu-add org-tbl-menu)
5162 (org-install-agenda-files-menu)
5163 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5164 (add-to-invisibility-spec '(org-cwidth))
5165 (add-to-invisibility-spec '(org-hide-block . t))
5166 (when (featurep 'xemacs)
5167 (org-set-local 'line-move-ignore-invisible t))
5168 (org-set-local 'outline-regexp org-outline-regexp)
5169 (org-set-local 'outline-level 'org-outline-level)
5170 (setq bidi-paragraph-direction 'left-to-right)
5171 (when (and org-ellipsis
5172 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5173 (fboundp 'make-glyph-code))
5174 (unless org-display-table
5175 (setq org-display-table (make-display-table)))
5176 (set-display-table-slot
5177 org-display-table 4
5178 (vconcat (mapcar
5179 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5180 org-ellipsis)))
5181 (if (stringp org-ellipsis) org-ellipsis "..."))))
5182 (setq buffer-display-table org-display-table))
5183 (org-set-regexps-and-options)
5184 (when (and org-tag-faces (not org-tags-special-faces-re))
5185 ;; tag faces set outside customize.... force initialization.
5186 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5187 ;; Calc embedded
5188 (org-set-local 'calc-embedded-open-mode "# ")
5189 (modify-syntax-entry ?@ "w")
5190 (modify-syntax-entry ?\" "\"")
5191 (if org-startup-truncated (setq truncate-lines t))
5192 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5193 (org-set-local 'font-lock-unfontify-region-function
5194 'org-unfontify-region)
5195 ;; Activate before-change-function
5196 (org-set-local 'org-table-may-need-update t)
5197 (org-add-hook 'before-change-functions 'org-before-change-function nil
5198 'local)
5199 ;; Check for running clock before killing a buffer
5200 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5201 ;; Initialize macros templates.
5202 (org-macro-initialize-templates)
5203 ;; Initialize radio targets.
5204 (org-update-radio-target-regexp)
5205 ;; Indentation.
5206 (org-set-local 'indent-line-function 'org-indent-line)
5207 (org-set-local 'indent-region-function 'org-indent-region)
5208 ;; Filling and auto-filling.
5209 (org-setup-filling)
5210 ;; Comments.
5211 (org-setup-comments-handling)
5212 ;; Beginning/end of defun
5213 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5214 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5215 ;; Next error for sparse trees
5216 (org-set-local 'next-error-function 'org-occur-next-match)
5217 ;; Make sure dependence stuff works reliably, even for users who set it
5218 ;; too late :-(
5219 (if org-enforce-todo-dependencies
5220 (add-hook 'org-blocker-hook
5221 'org-block-todo-from-children-or-siblings-or-parent)
5222 (remove-hook 'org-blocker-hook
5223 'org-block-todo-from-children-or-siblings-or-parent))
5224 (if org-enforce-todo-checkbox-dependencies
5225 (add-hook 'org-blocker-hook
5226 'org-block-todo-from-checkboxes)
5227 (remove-hook 'org-blocker-hook
5228 'org-block-todo-from-checkboxes))
5230 ;; Align options lines
5231 (org-set-local
5232 'align-mode-rules-list
5233 '((org-in-buffer-settings
5234 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5235 (modes . '(org-mode)))))
5237 ;; Imenu
5238 (org-set-local 'imenu-create-index-function
5239 'org-imenu-get-tree)
5241 ;; Make isearch reveal context
5242 (if (or (featurep 'xemacs)
5243 (not (boundp 'outline-isearch-open-invisible-function)))
5244 ;; Emacs 21 and XEmacs make use of the hook
5245 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5246 ;; Emacs 22 deals with this through a special variable
5247 (org-set-local 'outline-isearch-open-invisible-function
5248 (lambda (&rest ignore) (org-show-context 'isearch))))
5250 ;; Setup the pcomplete hooks
5251 (set (make-local-variable 'pcomplete-command-completion-function)
5252 'org-pcomplete-initial)
5253 (set (make-local-variable 'pcomplete-command-name-function)
5254 'org-command-at-point)
5255 (set (make-local-variable 'pcomplete-default-completion-function)
5256 'ignore)
5257 (set (make-local-variable 'pcomplete-parse-arguments-function)
5258 'org-parse-arguments)
5259 (set (make-local-variable 'pcomplete-termination-string) "")
5260 (when (>= emacs-major-version 23)
5261 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5263 ;; If empty file that did not turn on org-mode automatically, make it to.
5264 (if (and org-insert-mode-line-in-empty-file
5265 (org-called-interactively-p 'any)
5266 (= (point-min) (point-max)))
5267 (insert "# -*- mode: org -*-\n\n"))
5268 (unless org-inhibit-startup
5269 (and org-startup-with-beamer-mode (org-beamer-mode))
5270 (when org-startup-align-all-tables
5271 (let ((bmp (buffer-modified-p)))
5272 (org-table-map-tables 'org-table-align 'quietly)
5273 (set-buffer-modified-p bmp)))
5274 (when org-startup-with-inline-images
5275 (org-display-inline-images))
5276 (when org-startup-with-latex-preview
5277 (org-preview-latex-fragment))
5278 (unless org-inhibit-startup-visibility-stuff
5279 (org-set-startup-visibility)))
5280 ;; Try to set org-hide correctly
5281 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5283 (when (fboundp 'abbrev-table-put)
5284 (abbrev-table-put org-mode-abbrev-table
5285 :parents (list text-mode-abbrev-table)))
5287 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5290 (defun org-find-invisible-foreground ()
5291 (let ((candidates (remove
5292 "unspecified-bg"
5293 (nconc
5294 (list (face-background 'default)
5295 (face-background 'org-default))
5296 (mapcar
5297 (lambda (alist)
5298 (when (boundp alist)
5299 (cdr (assoc 'background-color (symbol-value alist)))))
5300 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5301 (list (face-foreground 'org-hide))))))
5302 (car (remove nil candidates))))
5304 (defun org-current-time (&optional rounding-minutes)
5305 "Current time, possibly rounded to ROUNDING-MINUTES.
5306 When ROUNDING-MINUTES is not an integer, fall back on the car of
5307 `org-time-stamp-rounding-minutes'."
5308 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5309 (car org-time-stamp-rounding-minutes)))
5310 (time (decode-time)))
5311 (if (> r 1)
5312 (apply 'encode-time
5313 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5314 (nthcdr 2 time)))
5315 (current-time))))
5317 (defun org-today ()
5318 "Return today date, considering `org-extend-today-until'."
5319 (time-to-days
5320 (time-subtract (current-time)
5321 (list 0 (* 3600 org-extend-today-until) 0))))
5323 ;;;; Font-Lock stuff, including the activators
5325 (defvar org-mouse-map (make-sparse-keymap))
5326 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5327 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5328 (when org-mouse-1-follows-link
5329 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5330 (when org-tab-follows-link
5331 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5332 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5334 (require 'font-lock)
5336 (defconst org-non-link-chars "]\t\n\r<>")
5337 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5338 "shell" "elisp" "doi" "message"))
5339 (defvar org-link-types-re nil
5340 "Matches a link that has a url-like prefix like \"http:\"")
5341 (defvar org-link-re-with-space nil
5342 "Matches a link with spaces, optional angular brackets around it.")
5343 (defvar org-link-re-with-space2 nil
5344 "Matches a link with spaces, optional angular brackets around it.")
5345 (defvar org-link-re-with-space3 nil
5346 "Matches a link with spaces, only for internal part in bracket links.")
5347 (defvar org-angle-link-re nil
5348 "Matches link with angular brackets, spaces are allowed.")
5349 (defvar org-plain-link-re nil
5350 "Matches plain link, without spaces.")
5351 (defvar org-bracket-link-regexp nil
5352 "Matches a link in double brackets.")
5353 (defvar org-bracket-link-analytic-regexp nil
5354 "Regular expression used to analyze links.
5355 Here is what the match groups contain after a match:
5356 1: http:
5357 2: http
5358 3: path
5359 4: [desc]
5360 5: desc")
5361 (defvar org-bracket-link-analytic-regexp++ nil
5362 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5363 (defvar org-any-link-re nil
5364 "Regular expression matching any link.")
5366 (defconst org-match-sexp-depth 3
5367 "Number of stacked braces for sub/superscript matching.")
5369 (defun org-create-multibrace-regexp (left right n)
5370 "Create a regular expression which will match a balanced sexp.
5371 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5372 as single character strings.
5373 The regexp returned will match the entire expression including the
5374 delimiters. It will also define a single group which contains the
5375 match except for the outermost delimiters. The maximum depth of
5376 stacked delimiters is N. Escaping delimiters is not possible."
5377 (let* ((nothing (concat "[^" left right "]*?"))
5378 (or "\\|")
5379 (re nothing)
5380 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5381 (while (> n 1)
5382 (setq n (1- n)
5383 re (concat re or next)
5384 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5385 (concat left "\\(" re "\\)" right)))
5387 (defvar org-match-substring-regexp
5388 (concat
5389 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5390 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5391 "\\|"
5392 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5393 "\\|"
5394 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5395 "The regular expression matching a sub- or superscript.")
5397 (defvar org-match-substring-with-braces-regexp
5398 (concat
5399 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5400 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5401 "\\)")
5402 "The regular expression matching a sub- or superscript, forcing braces.")
5404 (defun org-make-link-regexps ()
5405 "Update the link regular expressions.
5406 This should be called after the variable `org-link-types' has changed."
5407 (setq org-link-types-re
5408 (concat
5409 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5410 org-link-re-with-space
5411 (concat
5412 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5413 "\\([^" org-non-link-chars " ]"
5414 "[^" org-non-link-chars "]*"
5415 "[^" org-non-link-chars " ]\\)>?")
5416 org-link-re-with-space2
5417 (concat
5418 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5419 "\\([^" org-non-link-chars " ]"
5420 "[^\t\n\r]*"
5421 "[^" org-non-link-chars " ]\\)>?")
5422 org-link-re-with-space3
5423 (concat
5424 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5425 "\\([^" org-non-link-chars " ]"
5426 "[^\t\n\r]*\\)")
5427 org-angle-link-re
5428 (concat
5429 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5430 "\\([^" org-non-link-chars " ]"
5431 "[^" org-non-link-chars "]*"
5432 "\\)>")
5433 org-plain-link-re
5434 (concat
5435 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5436 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5437 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5438 org-bracket-link-regexp
5439 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5440 org-bracket-link-analytic-regexp
5441 (concat
5442 "\\[\\["
5443 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5444 "\\([^]]+\\)"
5445 "\\]"
5446 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5447 "\\]")
5448 org-bracket-link-analytic-regexp++
5449 (concat
5450 "\\[\\["
5451 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5452 "\\([^]]+\\)"
5453 "\\]"
5454 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5455 "\\]")
5456 org-any-link-re
5457 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5458 org-angle-link-re "\\)\\|\\("
5459 org-plain-link-re "\\)")))
5461 (org-make-link-regexps)
5463 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5464 "Regular expression for fast time stamp matching.")
5465 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5466 "Regular expression for fast time stamp matching.")
5467 (defconst org-ts-regexp0
5468 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5469 "Regular expression matching time strings for analysis.
5470 This one does not require the space after the date, so it can be used
5471 on a string that terminates immediately after the date.")
5472 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5473 "Regular expression matching time strings for analysis.")
5474 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5475 "Regular expression matching time stamps, with groups.")
5476 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5477 "Regular expression matching time stamps (also [..]), with groups.")
5478 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5479 "Regular expression matching a time stamp range.")
5480 (defconst org-tr-regexp-both
5481 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5482 "Regular expression matching a time stamp range.")
5483 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5484 org-ts-regexp "\\)?")
5485 "Regular expression matching a time stamp or time stamp range.")
5486 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5487 org-ts-regexp-both "\\)?")
5488 "Regular expression matching a time stamp or time stamp range.
5489 The time stamps may be either active or inactive.")
5491 (defvar org-emph-face nil)
5493 (defun org-do-emphasis-faces (limit)
5494 "Run through the buffer and add overlays to emphasized strings."
5495 (let (rtn a)
5496 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5497 (if (not (= (char-after (match-beginning 3))
5498 (char-after (match-beginning 4))))
5499 (progn
5500 (setq rtn t)
5501 (setq a (assoc (match-string 3) org-emphasis-alist))
5502 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5503 'face
5504 (nth 1 a))
5505 (and (nth 4 a)
5506 (org-remove-flyspell-overlays-in
5507 (match-beginning 0) (match-end 0)))
5508 (add-text-properties (match-beginning 2) (match-end 2)
5509 '(font-lock-multiline t org-emphasis t))
5510 (when org-hide-emphasis-markers
5511 (add-text-properties (match-end 4) (match-beginning 5)
5512 '(invisible org-link))
5513 (add-text-properties (match-beginning 3) (match-end 3)
5514 '(invisible org-link)))))
5515 (backward-char 1))
5516 rtn))
5518 (defun org-emphasize (&optional char)
5519 "Insert or change an emphasis, i.e. a font like bold or italic.
5520 If there is an active region, change that region to a new emphasis.
5521 If there is no region, just insert the marker characters and position
5522 the cursor between them.
5523 CHAR should be either the marker character, or the first character of the
5524 HTML tag associated with that emphasis. If CHAR is a space, the means
5525 to remove the emphasis of the selected region.
5526 If char is not given (for example in an interactive call) it
5527 will be prompted for."
5528 (interactive)
5529 (let ((eal org-emphasis-alist) e det
5530 (erc org-emphasis-regexp-components)
5531 (prompt "")
5532 (string "") beg end move tag c s)
5533 (if (org-region-active-p)
5534 (setq beg (region-beginning) end (region-end)
5535 string (buffer-substring beg end))
5536 (setq move t))
5538 (while (setq e (pop eal))
5539 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5540 c (aref tag 0))
5541 (push (cons c (string-to-char (car e))) det)
5542 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5543 (substring tag 1)))))
5544 (setq det (nreverse det))
5545 (unless char
5546 (message "%s" (concat "Emphasis marker or tag:" prompt))
5547 (setq char (read-char-exclusive)))
5548 (setq char (or (cdr (assoc char det)) char))
5549 (if (equal char ?\ )
5550 (setq s "" move nil)
5551 (unless (assoc (char-to-string char) org-emphasis-alist)
5552 (error "No such emphasis marker: \"%c\"" char))
5553 (setq s (char-to-string char)))
5554 (while (and (> (length string) 1)
5555 (equal (substring string 0 1) (substring string -1))
5556 (assoc (substring string 0 1) org-emphasis-alist))
5557 (setq string (substring string 1 -1)))
5558 (setq string (concat s string s))
5559 (if beg (delete-region beg end))
5560 (unless (or (bolp)
5561 (string-match (concat "[" (nth 0 erc) "\n]")
5562 (char-to-string (char-before (point)))))
5563 (insert " "))
5564 (unless (or (eobp)
5565 (string-match (concat "[" (nth 1 erc) "\n]")
5566 (char-to-string (char-after (point)))))
5567 (insert " ") (backward-char 1))
5568 (insert string)
5569 (and move (backward-char 1))))
5571 (defconst org-nonsticky-props
5572 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5574 (defsubst org-rear-nonsticky-at (pos)
5575 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5577 (defun org-activate-plain-links (limit)
5578 "Run through the buffer and add overlays to links."
5579 (catch 'exit
5580 (let (f hl)
5581 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5582 (not (org-in-src-block-p)))
5583 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5584 (setq f (get-text-property (match-beginning 0) 'face))
5585 (setq hl (org-match-string-no-properties 0))
5586 (if (or (eq f 'org-tag)
5587 (and (listp f) (memq 'org-tag f)))
5589 (add-text-properties (match-beginning 0) (match-end 0)
5590 (list 'mouse-face 'highlight
5591 'face 'org-link
5592 'htmlize-link `(:uri ,hl)
5593 'keymap org-mouse-map))
5594 (org-rear-nonsticky-at (match-end 0)))
5595 t))))
5597 (defun org-activate-code (limit)
5598 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5599 (progn
5600 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5601 (remove-text-properties (match-beginning 0) (match-end 0)
5602 '(display t invisible t intangible t))
5603 t)))
5605 (defcustom org-src-fontify-natively nil
5606 "When non-nil, fontify code in code blocks."
5607 :type 'boolean
5608 :version "24.1"
5609 :group 'org-appearance
5610 :group 'org-babel)
5612 (defcustom org-allow-promoting-top-level-subtree nil
5613 "When non-nil, allow promoting a top level subtree.
5614 The leading star of the top level headline will be replaced
5615 by a #."
5616 :type 'boolean
5617 :version "24.1"
5618 :group 'org-appearance)
5620 (defun org-fontify-meta-lines-and-blocks (limit)
5621 (condition-case nil
5622 (org-fontify-meta-lines-and-blocks-1 limit)
5623 (error (message "org-mode fontification error"))))
5625 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5626 "Fontify #+ lines and blocks, in the correct ways."
5627 (let ((case-fold-search t))
5628 (if (re-search-forward
5629 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5630 limit t)
5631 (let ((beg (match-beginning 0))
5632 (block-start (match-end 0))
5633 (block-end nil)
5634 (lang (match-string 7))
5635 (beg1 (line-beginning-position 2))
5636 (dc1 (downcase (match-string 2)))
5637 (dc3 (downcase (match-string 3)))
5638 end end1 quoting block-type ovl)
5639 (cond
5640 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5641 ;; a single line of backend-specific content
5642 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5643 (remove-text-properties (match-beginning 0) (match-end 0)
5644 '(display t invisible t intangible t))
5645 (add-text-properties (match-beginning 1) (match-end 3)
5646 '(font-lock-fontified t face org-meta-line))
5647 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5648 '(font-lock-fontified t face org-block))
5649 ; for backend-specific code
5651 ((and (match-end 4) (equal dc3 "+begin"))
5652 ;; Truly a block
5653 (setq block-type (downcase (match-string 5))
5654 quoting (member block-type org-protecting-blocks))
5655 (when (re-search-forward
5656 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5657 nil t) ;; on purpose, we look further than LIMIT
5658 (setq end (min (point-max) (match-end 0))
5659 end1 (min (point-max) (1- (match-beginning 0))))
5660 (setq block-end (match-beginning 0))
5661 (when quoting
5662 (remove-text-properties beg end
5663 '(display t invisible t intangible t)))
5664 (add-text-properties
5665 beg end
5666 '(font-lock-fontified t font-lock-multiline t))
5667 (add-text-properties beg beg1 '(face org-meta-line))
5668 (add-text-properties end1 (min (point-max) (1+ end))
5669 '(face org-meta-line)) ; for end_src
5670 (cond
5671 ((and lang (not (string= lang "")) org-src-fontify-natively)
5672 (org-src-font-lock-fontify-block lang block-start block-end)
5673 ;; remove old background overlays
5674 (mapc (lambda (ov)
5675 (if (eq (overlay-get ov 'face) 'org-block-background)
5676 (delete-overlay ov)))
5677 (overlays-at (/ (+ beg1 block-end) 2)))
5678 ;; add a background overlay
5679 (setq ovl (make-overlay beg1 block-end))
5680 (overlay-put ovl 'face 'org-block-background)
5681 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5682 (quoting
5683 (add-text-properties beg1 (min (point-max) (1+ end1))
5684 '(face org-block))) ; end of source block
5685 ((not org-fontify-quote-and-verse-blocks))
5686 ((string= block-type "quote")
5687 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5688 ((string= block-type "verse")
5689 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5690 (add-text-properties beg beg1 '(face org-block-begin-line))
5691 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5692 '(face org-block-end-line))
5694 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5695 (add-text-properties
5696 beg (match-end 3)
5697 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5698 '(font-lock-fontified t invisible t)
5699 '(font-lock-fontified t face org-document-info-keyword)))
5700 (add-text-properties
5701 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5702 (if (string-equal dc1 "+title:")
5703 '(font-lock-fontified t face org-document-title)
5704 '(font-lock-fontified t face org-document-info))))
5705 ((or (equal dc1 "+results")
5706 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5707 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5708 "+call:" "+header:" "+headers:" "+name:"))
5709 (and (match-end 4) (equal dc3 "+attr")))
5710 (add-text-properties
5711 beg (match-end 0)
5712 '(font-lock-fontified t face org-meta-line))
5714 ((member dc3 '(" " ""))
5715 (add-text-properties
5716 beg (match-end 0)
5717 '(font-lock-fontified t face font-lock-comment-face)))
5718 ((not (member (char-after beg) '(?\ ?\t)))
5719 ;; just any other in-buffer setting, but not indented
5720 (add-text-properties
5721 beg (match-end 0)
5722 '(font-lock-fontified t face org-meta-line))
5724 (t nil))))))
5726 (defun org-activate-angle-links (limit)
5727 "Run through the buffer and add overlays to links."
5728 (if (and (re-search-forward org-angle-link-re limit t)
5729 (not (org-in-src-block-p)))
5730 (progn
5731 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5732 (add-text-properties (match-beginning 0) (match-end 0)
5733 (list 'mouse-face 'highlight
5734 'keymap org-mouse-map))
5735 (org-rear-nonsticky-at (match-end 0))
5736 t)))
5738 (defun org-activate-footnote-links (limit)
5739 "Run through the buffer and add overlays to footnotes."
5740 (let ((fn (org-footnote-next-reference-or-definition limit)))
5741 (when fn
5742 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5743 (org-remove-flyspell-overlays-in beg end)
5744 (add-text-properties beg end
5745 (list 'mouse-face 'highlight
5746 'keymap org-mouse-map
5747 'help-echo
5748 (if (= (point-at-bol) beg)
5749 "Footnote definition"
5750 "Footnote reference")
5751 'font-lock-fontified t
5752 'font-lock-multiline t
5753 'face 'org-footnote))))))
5755 (defun org-activate-bracket-links (limit)
5756 "Run through the buffer and add overlays to bracketed links."
5757 (if (and (re-search-forward org-bracket-link-regexp limit t)
5758 (not (org-in-src-block-p)))
5759 (let* ((hl (org-match-string-no-properties 1))
5760 (help (concat "LINK: " hl))
5761 ;; FIXME: Above we should remove the escapes. But that
5762 ;; requires another match, protecting match data, a lot
5763 ;; of overhead for font-lock.
5764 (ip (org-maybe-intangible
5765 (list 'invisible 'org-link
5766 'keymap org-mouse-map 'mouse-face 'highlight
5767 'font-lock-multiline t 'help-echo help
5768 'htmlize-link `(:uri ,hl))))
5769 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5770 'font-lock-multiline t 'help-echo help
5771 'htmlize-link `(:uri ,hl))))
5772 ;; We need to remove the invisible property here. Table narrowing
5773 ;; may have made some of this invisible.
5774 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5775 (remove-text-properties (match-beginning 0) (match-end 0)
5776 '(invisible nil))
5777 (if (match-end 3)
5778 (progn
5779 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5780 (org-rear-nonsticky-at (match-beginning 3))
5781 (add-text-properties (match-beginning 3) (match-end 3) vp)
5782 (org-rear-nonsticky-at (match-end 3))
5783 (add-text-properties (match-end 3) (match-end 0) ip)
5784 (org-rear-nonsticky-at (match-end 0)))
5785 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5786 (org-rear-nonsticky-at (match-beginning 1))
5787 (add-text-properties (match-beginning 1) (match-end 1) vp)
5788 (org-rear-nonsticky-at (match-end 1))
5789 (add-text-properties (match-end 1) (match-end 0) ip)
5790 (org-rear-nonsticky-at (match-end 0)))
5791 t)))
5793 (defun org-activate-dates (limit)
5794 "Run through the buffer and add overlays to dates."
5795 (if (re-search-forward org-tsr-regexp-both limit t)
5796 (progn
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (add-text-properties (match-beginning 0) (match-end 0)
5799 (list 'mouse-face 'highlight
5800 'keymap org-mouse-map))
5801 (org-rear-nonsticky-at (match-end 0))
5802 (when org-display-custom-times
5803 (if (match-end 3)
5804 (org-display-custom-time (match-beginning 3) (match-end 3)))
5805 (org-display-custom-time (match-beginning 1) (match-end 1)))
5806 t)))
5808 (defvar org-target-link-regexp nil
5809 "Regular expression matching radio targets in plain text.")
5810 (make-variable-buffer-local 'org-target-link-regexp)
5811 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5812 "Regular expression matching a link target.")
5813 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5814 "Regular expression matching a radio target.")
5815 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5816 "Regular expression matching any target.")
5818 (defun org-activate-target-links (limit)
5819 "Run through the buffer and add overlays to target matches."
5820 (when org-target-link-regexp
5821 (let ((case-fold-search t))
5822 (if (re-search-forward org-target-link-regexp limit t)
5823 (progn
5824 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5825 (add-text-properties (match-beginning 0) (match-end 0)
5826 (list 'mouse-face 'highlight
5827 'keymap org-mouse-map
5828 'help-echo "Radio target link"
5829 'org-linked-text t))
5830 (org-rear-nonsticky-at (match-end 0))
5831 t)))))
5833 (defun org-update-radio-target-regexp ()
5834 "Find all radio targets in this file and update the regular expression."
5835 (interactive)
5836 (when (memq 'radio org-activate-links)
5837 (setq org-target-link-regexp
5838 (org-make-target-link-regexp (org-all-targets 'radio)))
5839 (org-restart-font-lock)))
5841 (defun org-hide-wide-columns (limit)
5842 (let (s e)
5843 (setq s (text-property-any (point) (or limit (point-max))
5844 'org-cwidth t))
5845 (when s
5846 (setq e (next-single-property-change s 'org-cwidth))
5847 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5848 (goto-char e)
5849 t)))
5851 (defvar org-match-substring-regexp)
5852 (defvar org-match-substring-with-braces-regexp)
5854 (defun org-restart-font-lock ()
5855 "Restart `font-lock-mode', to force refontification."
5856 (when (and (boundp 'font-lock-mode) font-lock-mode)
5857 (font-lock-mode -1)
5858 (font-lock-mode 1)))
5860 (defun org-all-targets (&optional radio)
5861 "Return a list of all targets in this file.
5862 When optional argument RADIO is non-nil, only find radio
5863 targets."
5864 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5865 (save-excursion
5866 (goto-char (point-min))
5867 (while (re-search-forward re nil t)
5868 ;; Make sure point is really within the object.
5869 (backward-char)
5870 (let ((obj (org-element-context)))
5871 (when (memq (org-element-type obj) '(radio-target target))
5872 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5873 rtn)))
5875 (defun org-make-target-link-regexp (targets)
5876 "Make regular expression matching all strings in TARGETS.
5877 The regular expression finds the targets also if there is a line break
5878 between words."
5879 (and targets
5880 (concat
5881 "\\<\\("
5882 (mapconcat
5883 (lambda (x)
5884 (setq x (regexp-quote x))
5885 (while (string-match " +" x)
5886 (setq x (replace-match "\\s-+" t t x)))
5888 targets
5889 "\\|")
5890 "\\)\\>")))
5892 (defun org-activate-tags (limit)
5893 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5894 (progn
5895 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5896 (add-text-properties (match-beginning 1) (match-end 1)
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map))
5899 (org-rear-nonsticky-at (match-end 1))
5900 t)))
5902 (defun org-outline-level ()
5903 "Compute the outline level of the heading at point.
5904 If this is called at a normal headline, the level is the number of stars.
5905 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5906 (save-excursion
5907 (if (not (condition-case nil
5908 (org-back-to-heading t)
5909 (error nil)))
5911 (looking-at org-outline-regexp)
5912 (1- (- (match-end 0) (match-beginning 0))))))
5914 (defvar org-font-lock-keywords nil)
5916 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5917 "Regular expression matching a property line.")
5919 (defvar org-font-lock-hook nil
5920 "Functions to be called for special font lock stuff.")
5922 (defvar org-font-lock-set-keywords-hook nil
5923 "Functions that can manipulate `org-font-lock-extra-keywords'.
5924 This is called after `org-font-lock-extra-keywords' is defined, but before
5925 it is installed to be used by font lock. This can be useful if something
5926 needs to be inserted at a specific position in the font-lock sequence.")
5928 (defun org-font-lock-hook (limit)
5929 "Run `org-font-lock-hook' within LIMIT."
5930 (run-hook-with-args 'org-font-lock-hook limit))
5932 (defun org-set-font-lock-defaults ()
5933 "Set font lock defaults for the current buffer."
5934 (let* ((em org-fontify-emphasized-text)
5935 (lk org-activate-links)
5936 (org-font-lock-extra-keywords
5937 (list
5938 ;; Call the hook
5939 '(org-font-lock-hook)
5940 ;; Headlines
5941 `(,(if org-fontify-whole-heading-line
5942 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5943 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5944 (1 (org-get-level-face 1))
5945 (2 (org-get-level-face 2))
5946 (3 (org-get-level-face 3)))
5947 ;; Table lines
5948 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5949 (1 'org-table t))
5950 ;; Table internals
5951 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5952 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5953 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5954 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5955 ;; Drawers
5956 (list org-drawer-regexp '(0 'org-special-keyword t))
5957 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5958 ;; Properties
5959 (list org-property-re
5960 '(1 'org-special-keyword t)
5961 '(3 'org-property-value t))
5962 ;; Links
5963 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5964 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5965 (if (memq 'plain lk) '(org-activate-plain-links))
5966 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5967 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5968 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5969 (if (memq 'footnote lk) '(org-activate-footnote-links))
5970 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5971 '(org-hide-wide-columns (0 nil append))
5972 ;; TODO keyword
5973 (list (format org-heading-keyword-regexp-format
5974 org-todo-regexp)
5975 '(2 (org-get-todo-face 2) t))
5976 ;; DONE
5977 (if org-fontify-done-headline
5978 (list (format org-heading-keyword-regexp-format
5979 (concat
5980 "\\(?:"
5981 (mapconcat 'regexp-quote org-done-keywords "\\|")
5982 "\\)"))
5983 '(2 'org-headline-done t))
5984 nil)
5985 ;; Priorities
5986 '(org-font-lock-add-priority-faces)
5987 ;; Tags
5988 '(org-font-lock-add-tag-faces)
5989 ;; Special keywords
5990 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5991 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5992 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5993 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5994 ;; Emphasis
5995 (if em
5996 (if (featurep 'xemacs)
5997 '(org-do-emphasis-faces (0 nil append))
5998 '(org-do-emphasis-faces)))
5999 ;; Checkboxes
6000 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6001 1 'org-checkbox prepend)
6002 (if (cdr (assq 'checkbox org-list-automatic-rules))
6003 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6004 (0 (org-get-checkbox-statistics-face) t)))
6005 ;; Description list items
6006 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6007 1 'org-list-dt prepend)
6008 ;; ARCHIVEd headings
6009 (list (concat
6010 org-outline-regexp-bol
6011 "\\(.*:" org-archive-tag ":.*\\)")
6012 '(1 'org-archived prepend))
6013 ;; Specials
6014 '(org-fontify-entities)
6015 '(org-raise-scripts)
6016 ;; Code
6017 '(org-activate-code (1 'org-code t))
6018 ;; COMMENT
6019 (list (format org-heading-keyword-regexp-format
6020 (concat "\\("
6021 org-comment-string "\\|" org-quote-string
6022 "\\)"))
6023 '(2 'org-special-keyword t))
6024 ;; Blocks and meta lines
6025 '(org-fontify-meta-lines-and-blocks)
6027 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6028 (run-hooks 'org-font-lock-set-keywords-hook)
6029 ;; Now set the full font-lock-keywords
6030 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6031 (org-set-local 'font-lock-defaults
6032 '(org-font-lock-keywords t nil nil backward-paragraph))
6033 (kill-local-variable 'font-lock-keywords) nil))
6035 (defun org-toggle-pretty-entities ()
6036 "Toggle the composition display of entities as UTF8 characters."
6037 (interactive)
6038 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6039 (org-restart-font-lock)
6040 (if org-pretty-entities
6041 (message "Entities are displayed as UTF8 characters")
6042 (save-restriction
6043 (widen)
6044 (org-decompose-region (point-min) (point-max))
6045 (message "Entities are displayed plain"))))
6047 (defvar org-custom-properties-overlays nil
6048 "List of overlays used for custom properties.")
6049 (make-variable-buffer-local 'org-custom-properties-overlays)
6051 (defun org-toggle-custom-properties-visibility ()
6052 "Display or hide properties in `org-custom-properties'."
6053 (interactive)
6054 (if org-custom-properties-overlays
6055 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6056 (setq org-custom-properties-overlays nil))
6057 (unless (not org-custom-properties)
6058 (save-excursion
6059 (save-restriction
6060 (widen)
6061 (goto-char (point-min))
6062 (while (re-search-forward org-property-re nil t)
6063 (mapc (lambda(p)
6064 (when (equal p (substring (match-string 1) 1 -1))
6065 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6066 (overlay-put o 'invisible t)
6067 (overlay-put o 'org-custom-property t)
6068 (push o org-custom-properties-overlays))))
6069 org-custom-properties)))))))
6071 (defun org-fontify-entities (limit)
6072 "Find an entity to fontify."
6073 (let (ee)
6074 (when org-pretty-entities
6075 (catch 'match
6076 (while (re-search-forward
6077 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6078 limit t)
6079 (if (and (not (org-in-indented-comment-line))
6080 (setq ee (org-entity-get (match-string 1)))
6081 (= (length (nth 6 ee)) 1))
6082 (let*
6083 ((end (if (equal (match-string 2) "{}")
6084 (match-end 2)
6085 (match-end 1))))
6086 (add-text-properties
6087 (match-beginning 0) end
6088 (list 'font-lock-fontified t))
6089 (compose-region (match-beginning 0) end
6090 (nth 6 ee) nil)
6091 (backward-char 1)
6092 (throw 'match t))))
6093 nil))))
6095 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6096 "Fontify string S like in Org-mode."
6097 (with-temp-buffer
6098 (insert s)
6099 (let ((org-odd-levels-only odd-levels))
6100 (org-mode)
6101 (font-lock-fontify-buffer)
6102 (buffer-string))))
6104 (defvar org-m nil)
6105 (defvar org-l nil)
6106 (defvar org-f nil)
6107 (defun org-get-level-face (n)
6108 "Get the right face for match N in font-lock matching of headlines."
6109 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6110 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6111 (if org-cycle-level-faces
6112 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6113 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6114 (cond
6115 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6116 ((eq n 2) org-f)
6117 (t (if org-level-color-stars-only nil org-f))))
6120 (defun org-get-todo-face (kwd)
6121 "Get the right face for a TODO keyword KWD.
6122 If KWD is a number, get the corresponding match group."
6123 (if (numberp kwd) (setq kwd (match-string kwd)))
6124 (or (org-face-from-face-or-color
6125 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6126 (and (member kwd org-done-keywords) 'org-done)
6127 'org-todo))
6129 (defun org-face-from-face-or-color (context inherit face-or-color)
6130 "Create a face list that inherits INHERIT, but sets the foreground color.
6131 When FACE-OR-COLOR is not a string, just return it."
6132 (if (stringp face-or-color)
6133 (list :inherit inherit
6134 (cdr (assoc context org-faces-easy-properties))
6135 face-or-color)
6136 face-or-color))
6138 (defun org-font-lock-add-tag-faces (limit)
6139 "Add the special tag faces."
6140 (when (and org-tag-faces org-tags-special-faces-re)
6141 (while (re-search-forward org-tags-special-faces-re limit t)
6142 (add-text-properties (match-beginning 1) (match-end 1)
6143 (list 'face (org-get-tag-face 1)
6144 'font-lock-fontified t))
6145 (backward-char 1))))
6147 (defun org-font-lock-add-priority-faces (limit)
6148 "Add the special priority faces."
6149 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6150 (when (save-match-data (org-at-heading-p))
6151 (add-text-properties
6152 (match-beginning 0) (match-end 0)
6153 (list 'face (or (org-face-from-face-or-color
6154 'priority 'org-priority
6155 (cdr (assoc (char-after (match-beginning 1))
6156 org-priority-faces)))
6157 'org-priority)
6158 'font-lock-fontified t)))))
6160 (defun org-get-tag-face (kwd)
6161 "Get the right face for a TODO keyword KWD.
6162 If KWD is a number, get the corresponding match group."
6163 (if (numberp kwd) (setq kwd (match-string kwd)))
6164 (or (org-face-from-face-or-color
6165 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6166 'org-tag))
6168 (defun org-unfontify-region (beg end &optional maybe_loudly)
6169 "Remove fontification and activation overlays from links."
6170 (font-lock-default-unfontify-region beg end)
6171 (let* ((buffer-undo-list t)
6172 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6173 (inhibit-modification-hooks t)
6174 deactivate-mark buffer-file-name buffer-file-truename)
6175 (org-decompose-region beg end)
6176 (remove-text-properties beg end
6177 '(mouse-face t keymap t org-linked-text t
6178 invisible t intangible t
6179 org-no-flyspell t org-emphasis t))
6180 (org-remove-font-lock-display-properties beg end)))
6182 (defconst org-script-display '(((raise -0.3) (height 0.7))
6183 ((raise 0.3) (height 0.7))
6184 ((raise -0.5))
6185 ((raise 0.5)))
6186 "Display properties for showing superscripts and subscripts.")
6188 (defun org-remove-font-lock-display-properties (beg end)
6189 "Remove specific display properties that have been added by font lock.
6190 The will remove the raise properties that are used to show superscripts
6191 and subscripts."
6192 (let (next prop)
6193 (while (< beg end)
6194 (setq next (next-single-property-change beg 'display nil end)
6195 prop (get-text-property beg 'display))
6196 (if (member prop org-script-display)
6197 (put-text-property beg next 'display nil))
6198 (setq beg next))))
6200 (defun org-raise-scripts (limit)
6201 "Add raise properties to sub/superscripts."
6202 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6203 (if (re-search-forward
6204 (if (eq org-use-sub-superscripts t)
6205 org-match-substring-regexp
6206 org-match-substring-with-braces-regexp)
6207 limit t)
6208 (let* ((pos (point)) table-p comment-p
6209 (mpos (match-beginning 3))
6210 (emph-p (get-text-property mpos 'org-emphasis))
6211 (link-p (get-text-property mpos 'mouse-face))
6212 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6213 (goto-char (point-at-bol))
6214 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6215 comment-p (org-looking-at-p "[ \t]*#"))
6216 (goto-char pos)
6217 ;; FIXME: Should we go back one character here, for a_b^c
6218 ;; (goto-char (1- pos)) ;????????????????????
6219 (if (or comment-p emph-p link-p keyw-p)
6221 (put-text-property (match-beginning 3) (match-end 0)
6222 'display
6223 (if (equal (char-after (match-beginning 2)) ?^)
6224 (nth (if table-p 3 1) org-script-display)
6225 (nth (if table-p 2 0) org-script-display)))
6226 (add-text-properties (match-beginning 2) (match-end 2)
6227 (list 'invisible t
6228 'org-dwidth t 'org-dwidth-n 1))
6229 (if (and (eq (char-after (match-beginning 3)) ?{)
6230 (eq (char-before (match-end 3)) ?}))
6231 (progn
6232 (add-text-properties
6233 (match-beginning 3) (1+ (match-beginning 3))
6234 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6235 (add-text-properties
6236 (1- (match-end 3)) (match-end 3)
6237 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6238 t)))))
6240 ;;;; Visibility cycling, including org-goto and indirect buffer
6242 ;;; Cycling
6244 (defvar org-cycle-global-status nil)
6245 (make-variable-buffer-local 'org-cycle-global-status)
6246 (put 'org-cycle-global-status 'org-state t)
6247 (defvar org-cycle-subtree-status nil)
6248 (make-variable-buffer-local 'org-cycle-subtree-status)
6249 (put 'org-cycle-subtree-status 'org-state t)
6251 (defvar org-inlinetask-min-level)
6253 ;;;###autoload
6254 (defun org-cycle (&optional arg)
6255 "TAB-action and visibility cycling for Org-mode.
6257 This is the command invoked in Org-mode by the TAB key. Its main purpose
6258 is outline visibility cycling, but it also invokes other actions
6259 in special contexts.
6261 - When this function is called with a prefix argument, rotate the entire
6262 buffer through 3 states (global cycling)
6263 1. OVERVIEW: Show only top-level headlines.
6264 2. CONTENTS: Show all headlines of all levels, but no body text.
6265 3. SHOW ALL: Show everything.
6266 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6267 determined by the variable `org-startup-folded', and by any VISIBILITY
6268 properties in the buffer.
6269 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6270 including any drawers.
6272 - When inside a table, re-align the table and move to the next field.
6274 - When point is at the beginning of a headline, rotate the subtree started
6275 by this line through 3 different states (local cycling)
6276 1. FOLDED: Only the main headline is shown.
6277 2. CHILDREN: The main headline and the direct children are shown.
6278 From this state, you can move to one of the children
6279 and zoom in further.
6280 3. SUBTREE: Show the entire subtree, including body text.
6281 If there is no subtree, switch directly from CHILDREN to FOLDED.
6283 - When point is at the beginning of an empty headline and the variable
6284 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6285 of the headline by demoting and promoting it to likely levels. This
6286 speeds up creation document structure by pressing TAB once or several
6287 times right after creating a new headline.
6289 - When there is a numeric prefix, go up to a heading with level ARG, do
6290 a `show-subtree' and return to the previous cursor position. If ARG
6291 is negative, go up that many levels.
6293 - When point is not at the beginning of a headline, execute the global
6294 binding for TAB, which is re-indenting the line. See the option
6295 `org-cycle-emulate-tab' for details.
6297 - Special case: if point is at the beginning of the buffer and there is
6298 no headline in line 1, this function will act as if called with prefix arg
6299 (C-u TAB, same as S-TAB) also when called without prefix arg.
6300 But only if also the variable `org-cycle-global-at-bob' is t."
6301 (interactive "P")
6302 (org-load-modules-maybe)
6303 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6304 (and org-cycle-level-after-item/entry-creation
6305 (or (org-cycle-level)
6306 (org-cycle-item-indentation))))
6307 (let* (message-log-max ; Don't populate the *Messages* buffer
6308 (limit-level
6309 (or org-cycle-max-level
6310 (and (boundp 'org-inlinetask-min-level)
6311 org-inlinetask-min-level
6312 (1- org-inlinetask-min-level))))
6313 (nstars (and limit-level
6314 (if org-odd-levels-only
6315 (and limit-level (1- (* limit-level 2)))
6316 limit-level)))
6317 (org-outline-regexp
6318 (if (not (derived-mode-p 'org-mode))
6319 outline-regexp
6320 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6321 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6322 (not (looking-at org-outline-regexp))))
6323 (org-cycle-hook
6324 (if bob-special
6325 (delq 'org-optimize-window-after-visibility-change
6326 (copy-sequence org-cycle-hook))
6327 org-cycle-hook))
6328 (pos (point)))
6330 (if (or bob-special (equal arg '(4)))
6331 ;; special case: use global cycling
6332 (setq arg t))
6334 (cond
6336 ((equal arg '(16))
6337 (setq last-command 'dummy)
6338 (org-set-startup-visibility)
6339 (message "Startup visibility, plus VISIBILITY properties"))
6341 ((equal arg '(64))
6342 (show-all)
6343 (message "Entire buffer visible, including drawers"))
6345 ;; Table: enter it or move to the next field.
6346 ((org-at-table-p 'any)
6347 (if (org-at-table.el-p)
6348 (message "Use C-c ' to edit table.el tables")
6349 (if arg (org-table-edit-field t)
6350 (org-table-justify-field-maybe)
6351 (call-interactively 'org-table-next-field))))
6353 ((run-hook-with-args-until-success
6354 'org-tab-after-check-for-table-hook))
6356 ;; Global cycling: delegate to `org-cycle-internal-global'.
6357 ((eq arg t) (org-cycle-internal-global))
6359 ;; Drawers: delegate to `org-flag-drawer'.
6360 ((and org-drawers org-drawer-regexp
6361 (save-excursion
6362 (beginning-of-line 1)
6363 (looking-at org-drawer-regexp)))
6364 (org-flag-drawer ; toggle block visibility
6365 (not (get-char-property (match-end 0) 'invisible))))
6367 ;; Show-subtree, ARG levels up from here.
6368 ((integerp arg)
6369 (save-excursion
6370 (org-back-to-heading)
6371 (outline-up-heading (if (< arg 0) (- arg)
6372 (- (funcall outline-level) arg)))
6373 (org-show-subtree)))
6375 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6376 ((and (featurep 'org-inlinetask)
6377 (org-inlinetask-at-task-p)
6378 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6379 (org-inlinetask-toggle-visibility))
6381 ((org-try-cdlatex-tab))
6383 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6384 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6385 (save-excursion (beginning-of-line 1)
6386 (looking-at org-outline-regexp)))
6387 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6388 (org-cycle-internal-local))
6390 ;; From there: TAB emulation and template completion.
6391 (buffer-read-only (org-back-to-heading))
6393 ((run-hook-with-args-until-success
6394 'org-tab-after-check-for-cycling-hook))
6396 ((org-try-structure-completion))
6398 ((run-hook-with-args-until-success
6399 'org-tab-before-tab-emulation-hook))
6401 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6402 (or (not (bolp))
6403 (not (looking-at org-outline-regexp))))
6404 (call-interactively (global-key-binding "\t")))
6406 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6407 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6408 (or (and (eq org-cycle-emulate-tab 'white)
6409 (= (match-end 0) (point-at-eol)))
6410 (and (eq org-cycle-emulate-tab 'whitestart)
6411 (>= (match-end 0) pos))))
6413 (eq org-cycle-emulate-tab t))
6414 (call-interactively (global-key-binding "\t")))
6416 (t (save-excursion
6417 (org-back-to-heading)
6418 (org-cycle)))))))
6420 (defun org-cycle-internal-global ()
6421 "Do the global cycling action."
6422 ;; Hack to avoid display of messages for .org attachments in Gnus
6423 (let (message-log-max ; Don't populate the *Messages* buffer
6424 (ga (string-match "\\*fontification" (buffer-name))))
6425 (cond
6426 ((and (eq last-command this-command)
6427 (eq org-cycle-global-status 'overview))
6428 ;; We just created the overview - now do table of contents
6429 ;; This can be slow in very large buffers, so indicate action
6430 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6431 (unless ga (message "CONTENTS..."))
6432 (org-content)
6433 (unless ga (message "CONTENTS...done"))
6434 (setq org-cycle-global-status 'contents)
6435 (run-hook-with-args 'org-cycle-hook 'contents))
6437 ((and (eq last-command this-command)
6438 (eq org-cycle-global-status 'contents))
6439 ;; We just showed the table of contents - now show everything
6440 (run-hook-with-args 'org-pre-cycle-hook 'all)
6441 (show-all)
6442 (unless ga (message "SHOW ALL"))
6443 (setq org-cycle-global-status 'all)
6444 (run-hook-with-args 'org-cycle-hook 'all))
6447 ;; Default action: go to overview
6448 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6449 (org-overview)
6450 (unless ga (message "OVERVIEW"))
6451 (setq org-cycle-global-status 'overview)
6452 (run-hook-with-args 'org-cycle-hook 'overview)))))
6454 (defun org-cycle-internal-local ()
6455 "Do the local cycling action."
6456 (let (message-log-max ; Don't populate the *Messages* buffer
6457 (goal-column 0) eoh eol eos has-children children-skipped struct)
6458 ;; First, determine end of headline (EOH), end of subtree or item
6459 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6460 (save-excursion
6461 (if (org-at-item-p)
6462 (progn
6463 (beginning-of-line)
6464 (setq struct (org-list-struct))
6465 (setq eoh (point-at-eol))
6466 (setq eos (org-list-get-item-end-before-blank (point) struct))
6467 (setq has-children (org-list-has-child-p (point) struct)))
6468 (org-back-to-heading)
6469 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6470 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6471 (setq has-children
6472 (or (save-excursion
6473 (let ((level (funcall outline-level)))
6474 (outline-next-heading)
6475 (and (org-at-heading-p t)
6476 (> (funcall outline-level) level))))
6477 (save-excursion
6478 (org-list-search-forward (org-item-beginning-re) eos t)))))
6479 ;; Determine end invisible part of buffer (EOL)
6480 (beginning-of-line 2)
6481 ;; XEmacs doesn't have `next-single-char-property-change'
6482 (if (featurep 'xemacs)
6483 (while (and (not (eobp)) ;; this is like `next-line'
6484 (get-char-property (1- (point)) 'invisible))
6485 (beginning-of-line 2))
6486 (while (and (not (eobp)) ;; this is like `next-line'
6487 (get-char-property (1- (point)) 'invisible))
6488 (goto-char (next-single-char-property-change (point) 'invisible))
6489 (and (eolp) (beginning-of-line 2))))
6490 (setq eol (point)))
6491 ;; Find out what to do next and set `this-command'
6492 (cond
6493 ((= eos eoh)
6494 ;; Nothing is hidden behind this heading
6495 (unless (org-before-first-heading-p)
6496 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6497 (message "EMPTY ENTRY")
6498 (setq org-cycle-subtree-status nil)
6499 (save-excursion
6500 (goto-char eos)
6501 (outline-next-heading)
6502 (if (outline-invisible-p) (org-flag-heading nil))))
6503 ((and (or (>= eol eos)
6504 (not (string-match "\\S-" (buffer-substring eol eos))))
6505 (or has-children
6506 (not (setq children-skipped
6507 org-cycle-skip-children-state-if-no-children))))
6508 ;; Entire subtree is hidden in one line: children view
6509 (unless (org-before-first-heading-p)
6510 (run-hook-with-args 'org-pre-cycle-hook 'children))
6511 (if (org-at-item-p)
6512 (org-list-set-item-visibility (point-at-bol) struct 'children)
6513 (org-show-entry)
6514 (org-with-limited-levels (show-children))
6515 ;; FIXME: This slows down the func way too much.
6516 ;; How keep drawers hidden in subtree anyway?
6517 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6518 ;; (org-cycle-hide-drawers 'subtree))
6520 ;; Fold every list in subtree to top-level items.
6521 (when (eq org-cycle-include-plain-lists 'integrate)
6522 (save-excursion
6523 (org-back-to-heading)
6524 (while (org-list-search-forward (org-item-beginning-re) eos t)
6525 (beginning-of-line 1)
6526 (let* ((struct (org-list-struct))
6527 (prevs (org-list-prevs-alist struct))
6528 (end (org-list-get-bottom-point struct)))
6529 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6530 (org-list-get-all-items (point) struct prevs))
6531 (goto-char end))))))
6532 (message "CHILDREN")
6533 (save-excursion
6534 (goto-char eos)
6535 (outline-next-heading)
6536 (if (outline-invisible-p) (org-flag-heading nil)))
6537 (setq org-cycle-subtree-status 'children)
6538 (unless (org-before-first-heading-p)
6539 (run-hook-with-args 'org-cycle-hook 'children)))
6540 ((or children-skipped
6541 (and (eq last-command this-command)
6542 (eq org-cycle-subtree-status 'children)))
6543 ;; We just showed the children, or no children are there,
6544 ;; now show everything.
6545 (unless (org-before-first-heading-p)
6546 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6547 (outline-flag-region eoh eos nil)
6548 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6549 (setq org-cycle-subtree-status 'subtree)
6550 (unless (org-before-first-heading-p)
6551 (run-hook-with-args 'org-cycle-hook 'subtree)))
6553 ;; Default action: hide the subtree.
6554 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6555 (outline-flag-region eoh eos t)
6556 (message "FOLDED")
6557 (setq org-cycle-subtree-status 'folded)
6558 (unless (org-before-first-heading-p)
6559 (run-hook-with-args 'org-cycle-hook 'folded))))))
6561 ;;;###autoload
6562 (defun org-global-cycle (&optional arg)
6563 "Cycle the global visibility. For details see `org-cycle'.
6564 With \\[universal-argument] prefix arg, switch to startup visibility.
6565 With a numeric prefix, show all headlines up to that level."
6566 (interactive "P")
6567 (let ((org-cycle-include-plain-lists
6568 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6569 (cond
6570 ((integerp arg)
6571 (show-all)
6572 (hide-sublevels arg)
6573 (setq org-cycle-global-status 'contents))
6574 ((equal arg '(4))
6575 (org-set-startup-visibility)
6576 (message "Startup visibility, plus VISIBILITY properties."))
6578 (org-cycle '(4))))))
6580 (defun org-set-startup-visibility ()
6581 "Set the visibility required by startup options and properties."
6582 (cond
6583 ((eq org-startup-folded t)
6584 (org-cycle '(4)))
6585 ((eq org-startup-folded 'content)
6586 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6587 (org-cycle '(4)) (org-cycle '(4)))))
6588 (unless (eq org-startup-folded 'showeverything)
6589 (if org-hide-block-startup (org-hide-block-all))
6590 (org-set-visibility-according-to-property 'no-cleanup)
6591 (org-cycle-hide-archived-subtrees 'all)
6592 (org-cycle-hide-drawers 'all)
6593 (org-cycle-show-empty-lines t)))
6595 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6596 "Switch subtree visibilities according to :VISIBILITY: property."
6597 (interactive)
6598 (let (org-show-entry-below state)
6599 (save-excursion
6600 (goto-char (point-min))
6601 (while (re-search-forward
6602 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6603 nil t)
6604 (setq state (match-string 1))
6605 (save-excursion
6606 (org-back-to-heading t)
6607 (hide-subtree)
6608 (org-reveal)
6609 (cond
6610 ((equal state '("fold" "folded"))
6611 (hide-subtree))
6612 ((equal state "children")
6613 (org-show-hidden-entry)
6614 (show-children))
6615 ((equal state "content")
6616 (save-excursion
6617 (save-restriction
6618 (org-narrow-to-subtree)
6619 (org-content))))
6620 ((member state '("all" "showall"))
6621 (show-subtree)))))
6622 (unless no-cleanup
6623 (org-cycle-hide-archived-subtrees 'all)
6624 (org-cycle-hide-drawers 'all)
6625 (org-cycle-show-empty-lines 'all)))))
6627 ;; This function uses outline-regexp instead of the more fundamental
6628 ;; org-outline-regexp so that org-cycle-global works outside of Org
6629 ;; buffers, where outline-regexp is needed.
6630 (defun org-overview ()
6631 "Switch to overview mode, showing only top-level headlines.
6632 Really, this shows all headlines with level equal or greater than the level
6633 of the first headline in the buffer. This is important, because if the
6634 first headline is not level one, then (hide-sublevels 1) gives confusing
6635 results."
6636 (interactive)
6637 (let ((level (save-excursion
6638 (goto-char (point-min))
6639 (if (re-search-forward (concat "^" outline-regexp) nil t)
6640 (progn
6641 (goto-char (match-beginning 0))
6642 (funcall outline-level))))))
6643 (and level (hide-sublevels level))))
6645 (defun org-content (&optional arg)
6646 "Show all headlines in the buffer, like a table of contents.
6647 With numerical argument N, show content up to level N."
6648 (interactive "P")
6649 (save-excursion
6650 ;; Visit all headings and show their offspring
6651 (and (integerp arg) (org-overview))
6652 (goto-char (point-max))
6653 (catch 'exit
6654 (while (and (progn (condition-case nil
6655 (outline-previous-visible-heading 1)
6656 (error (goto-char (point-min))))
6658 (looking-at org-outline-regexp))
6659 (if (integerp arg)
6660 (show-children (1- arg))
6661 (show-branches))
6662 (if (bobp) (throw 'exit nil))))))
6665 (defun org-optimize-window-after-visibility-change (state)
6666 "Adjust the window after a change in outline visibility.
6667 This function is the default value of the hook `org-cycle-hook'."
6668 (when (get-buffer-window (current-buffer))
6669 (cond
6670 ((eq state 'content) nil)
6671 ((eq state 'all) nil)
6672 ((eq state 'folded) nil)
6673 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6674 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6676 (defun org-remove-empty-overlays-at (pos)
6677 "Remove outline overlays that do not contain non-white stuff."
6678 (mapc
6679 (lambda (o)
6680 (and (eq 'outline (overlay-get o 'invisible))
6681 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6682 (overlay-end o))))
6683 (delete-overlay o)))
6684 (overlays-at pos)))
6686 (defun org-clean-visibility-after-subtree-move ()
6687 "Fix visibility issues after moving a subtree."
6688 ;; First, find a reasonable region to look at:
6689 ;; Start two siblings above, end three below
6690 (let* ((beg (save-excursion
6691 (and (org-get-last-sibling)
6692 (org-get-last-sibling))
6693 (point)))
6694 (end (save-excursion
6695 (and (org-get-next-sibling)
6696 (org-get-next-sibling)
6697 (org-get-next-sibling))
6698 (if (org-at-heading-p)
6699 (point-at-eol)
6700 (point))))
6701 (level (looking-at "\\*+"))
6702 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6703 (save-excursion
6704 (save-restriction
6705 (narrow-to-region beg end)
6706 (when re
6707 ;; Properly fold already folded siblings
6708 (goto-char (point-min))
6709 (while (re-search-forward re nil t)
6710 (if (and (not (outline-invisible-p))
6711 (save-excursion
6712 (goto-char (point-at-eol)) (outline-invisible-p)))
6713 (hide-entry))))
6714 (org-cycle-show-empty-lines 'overview)
6715 (org-cycle-hide-drawers 'overview)))))
6717 (defun org-cycle-show-empty-lines (state)
6718 "Show empty lines above all visible headlines.
6719 The region to be covered depends on STATE when called through
6720 `org-cycle-hook'. Lisp program can use t for STATE to get the
6721 entire buffer covered. Note that an empty line is only shown if there
6722 are at least `org-cycle-separator-lines' empty lines before the headline."
6723 (when (not (= org-cycle-separator-lines 0))
6724 (save-excursion
6725 (let* ((n (abs org-cycle-separator-lines))
6726 (re (cond
6727 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6728 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6729 (t (let ((ns (number-to-string (- n 2))))
6730 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6731 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6732 beg end b e)
6733 (cond
6734 ((memq state '(overview contents t))
6735 (setq beg (point-min) end (point-max)))
6736 ((memq state '(children folded))
6737 (setq beg (point) end (progn (org-end-of-subtree t t)
6738 (beginning-of-line 2)
6739 (point)))))
6740 (when beg
6741 (goto-char beg)
6742 (while (re-search-forward re end t)
6743 (unless (get-char-property (match-end 1) 'invisible)
6744 (setq e (match-end 1))
6745 (if (< org-cycle-separator-lines 0)
6746 (setq b (save-excursion
6747 (goto-char (match-beginning 0))
6748 (org-back-over-empty-lines)
6749 (if (save-excursion
6750 (goto-char (max (point-min) (1- (point))))
6751 (org-at-heading-p))
6752 (1- (point))
6753 (point))))
6754 (setq b (match-beginning 1)))
6755 (outline-flag-region b e nil)))))))
6756 ;; Never hide empty lines at the end of the file.
6757 (save-excursion
6758 (goto-char (point-max))
6759 (outline-previous-heading)
6760 (outline-end-of-heading)
6761 (if (and (looking-at "[ \t\n]+")
6762 (= (match-end 0) (point-max)))
6763 (outline-flag-region (point) (match-end 0) nil))))
6765 (defun org-show-empty-lines-in-parent ()
6766 "Move to the parent and re-show empty lines before visible headlines."
6767 (save-excursion
6768 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6769 (org-cycle-show-empty-lines context))))
6771 (defun org-files-list ()
6772 "Return `org-agenda-files' list, plus all open org-mode files.
6773 This is useful for operations that need to scan all of a user's
6774 open and agenda-wise Org files."
6775 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6776 (dolist (buf (buffer-list))
6777 (with-current-buffer buf
6778 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6779 (let ((file (expand-file-name (buffer-file-name))))
6780 (unless (member file files)
6781 (push file files))))))
6782 files))
6784 (defsubst org-entry-beginning-position ()
6785 "Return the beginning position of the current entry."
6786 (save-excursion (outline-back-to-heading t) (point)))
6788 (defsubst org-entry-end-position ()
6789 "Return the end position of the current entry."
6790 (save-excursion (outline-next-heading) (point)))
6792 (defun org-cycle-hide-drawers (state)
6793 "Re-hide all drawers after a visibility state change."
6794 (when (and (derived-mode-p 'org-mode)
6795 (not (memq state '(overview folded contents))))
6796 (save-excursion
6797 (let* ((globalp (memq state '(contents all)))
6798 (beg (if globalp (point-min) (point)))
6799 (end (if globalp (point-max)
6800 (if (eq state 'children)
6801 (save-excursion (outline-next-heading) (point))
6802 (org-end-of-subtree t)))))
6803 (goto-char beg)
6804 (while (re-search-forward org-drawer-regexp end t)
6805 (org-flag-drawer t))))))
6807 (defun org-cycle-hide-inline-tasks (state)
6808 "Re-hide inline task when switching to 'contents visibility state."
6809 (when (and (eq state 'contents)
6810 (boundp 'org-inlinetask-min-level)
6811 org-inlinetask-min-level)
6812 (hide-sublevels (1- org-inlinetask-min-level))))
6814 (defun org-flag-drawer (flag)
6815 "When FLAG is non-nil, hide the drawer we are within.
6816 Otherwise make it visible."
6817 (save-excursion
6818 (beginning-of-line 1)
6819 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6820 (let ((b (match-end 0)))
6821 (if (re-search-forward
6822 "^[ \t]*:END:"
6823 (save-excursion (outline-next-heading) (point)) t)
6824 (outline-flag-region b (point-at-eol) flag)
6825 (error ":END: line missing at position %s" b))))))
6827 (defun org-subtree-end-visible-p ()
6828 "Is the end of the current subtree visible?"
6829 (pos-visible-in-window-p
6830 (save-excursion (org-end-of-subtree t) (point))))
6832 (defun org-first-headline-recenter (&optional N)
6833 "Move cursor to the first headline and recenter the headline.
6834 Optional argument N means put the headline into the Nth line of the window."
6835 (goto-char (point-min))
6836 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6837 (beginning-of-line)
6838 (recenter (prefix-numeric-value N))))
6840 ;;; Saving and restoring visibility
6842 (defun org-outline-overlay-data (&optional use-markers)
6843 "Return a list of the locations of all outline overlays.
6844 These are overlays with the `invisible' property value `outline'.
6845 The return value is a list of cons cells, with start and stop
6846 positions for each overlay.
6847 If USE-MARKERS is set, return the positions as markers."
6848 (let (beg end)
6849 (save-excursion
6850 (save-restriction
6851 (widen)
6852 (delq nil
6853 (mapcar (lambda (o)
6854 (when (eq (overlay-get o 'invisible) 'outline)
6855 (setq beg (overlay-start o)
6856 end (overlay-end o))
6857 (and beg end (> end beg)
6858 (if use-markers
6859 (cons (move-marker (make-marker) beg)
6860 (move-marker (make-marker) end))
6861 (cons beg end)))))
6862 (overlays-in (point-min) (point-max))))))))
6864 (defun org-set-outline-overlay-data (data)
6865 "Create visibility overlays for all positions in DATA.
6866 DATA should have been made by `org-outline-overlay-data'."
6867 (let (o)
6868 (save-excursion
6869 (save-restriction
6870 (widen)
6871 (show-all)
6872 (mapc (lambda (c)
6873 (outline-flag-region (car c) (cdr c) t))
6874 data)))))
6876 ;;; Folding of blocks
6878 (defvar org-hide-block-overlays nil
6879 "Overlays hiding blocks.")
6880 (make-variable-buffer-local 'org-hide-block-overlays)
6882 (defun org-block-map (function &optional start end)
6883 "Call FUNCTION at the head of all source blocks in the current buffer.
6884 Optional arguments START and END can be used to limit the range."
6885 (let ((start (or start (point-min)))
6886 (end (or end (point-max))))
6887 (save-excursion
6888 (goto-char start)
6889 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6890 (save-excursion
6891 (save-match-data
6892 (goto-char (match-beginning 0))
6893 (funcall function)))))))
6895 (defun org-hide-block-toggle-all ()
6896 "Toggle the visibility of all blocks in the current buffer."
6897 (org-block-map #'org-hide-block-toggle))
6899 (defun org-hide-block-all ()
6900 "Fold all blocks in the current buffer."
6901 (interactive)
6902 (org-show-block-all)
6903 (org-block-map #'org-hide-block-toggle-maybe))
6905 (defun org-show-block-all ()
6906 "Unfold all blocks in the current buffer."
6907 (interactive)
6908 (mapc 'delete-overlay org-hide-block-overlays)
6909 (setq org-hide-block-overlays nil))
6911 (defun org-hide-block-toggle-maybe ()
6912 "Toggle visibility of block at point."
6913 (interactive)
6914 (let ((case-fold-search t))
6915 (if (save-excursion
6916 (beginning-of-line 1)
6917 (looking-at org-block-regexp))
6918 (progn (org-hide-block-toggle)
6919 t) ;; to signal that we took action
6920 nil))) ;; to signal that we did not
6922 (defun org-hide-block-toggle (&optional force)
6923 "Toggle the visibility of the current block."
6924 (interactive)
6925 (save-excursion
6926 (beginning-of-line)
6927 (if (re-search-forward org-block-regexp nil t)
6928 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6929 (end (match-end 0)) ;; end of entire body
6931 (if (memq t (mapcar (lambda (overlay)
6932 (eq (overlay-get overlay 'invisible)
6933 'org-hide-block))
6934 (overlays-at start)))
6935 (if (or (not force) (eq force 'off))
6936 (mapc (lambda (ov)
6937 (when (member ov org-hide-block-overlays)
6938 (setq org-hide-block-overlays
6939 (delq ov org-hide-block-overlays)))
6940 (when (eq (overlay-get ov 'invisible)
6941 'org-hide-block)
6942 (delete-overlay ov)))
6943 (overlays-at start)))
6944 (setq ov (make-overlay start end))
6945 (overlay-put ov 'invisible 'org-hide-block)
6946 ;; make the block accessible to isearch
6947 (overlay-put
6948 ov 'isearch-open-invisible
6949 (lambda (ov)
6950 (when (member ov org-hide-block-overlays)
6951 (setq org-hide-block-overlays
6952 (delq ov org-hide-block-overlays)))
6953 (when (eq (overlay-get ov 'invisible)
6954 'org-hide-block)
6955 (delete-overlay ov))))
6956 (push ov org-hide-block-overlays)))
6957 (error "Not looking at a source block"))))
6959 ;; org-tab-after-check-for-cycling-hook
6960 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6961 ;; Remove overlays when changing major mode
6962 (add-hook 'org-mode-hook
6963 (lambda () (org-add-hook 'change-major-mode-hook
6964 'org-show-block-all 'append 'local)))
6966 ;;; Org-goto
6968 (defvar org-goto-window-configuration nil)
6969 (defvar org-goto-marker nil)
6970 (defvar org-goto-map)
6971 (defun org-goto-map ()
6972 "Set the keymap `org-goto'."
6973 (setq org-goto-map
6974 (let ((map (make-sparse-keymap)))
6975 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6976 mouse-drag-region universal-argument org-occur))
6977 cmd)
6978 (while (setq cmd (pop cmds))
6979 (substitute-key-definition cmd cmd map global-map)))
6980 (suppress-keymap map)
6981 (org-defkey map "\C-m" 'org-goto-ret)
6982 (org-defkey map [(return)] 'org-goto-ret)
6983 (org-defkey map [(left)] 'org-goto-left)
6984 (org-defkey map [(right)] 'org-goto-right)
6985 (org-defkey map [(control ?g)] 'org-goto-quit)
6986 (org-defkey map "\C-i" 'org-cycle)
6987 (org-defkey map [(tab)] 'org-cycle)
6988 (org-defkey map [(down)] 'outline-next-visible-heading)
6989 (org-defkey map [(up)] 'outline-previous-visible-heading)
6990 (if org-goto-auto-isearch
6991 (if (fboundp 'define-key-after)
6992 (define-key-after map [t] 'org-goto-local-auto-isearch)
6993 nil)
6994 (org-defkey map "q" 'org-goto-quit)
6995 (org-defkey map "n" 'outline-next-visible-heading)
6996 (org-defkey map "p" 'outline-previous-visible-heading)
6997 (org-defkey map "f" 'outline-forward-same-level)
6998 (org-defkey map "b" 'outline-backward-same-level)
6999 (org-defkey map "u" 'outline-up-heading))
7000 (org-defkey map "/" 'org-occur)
7001 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7002 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7003 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7004 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7005 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7006 map)))
7008 (defconst org-goto-help
7009 "Browse buffer copy, to find location or copy text.%s
7010 RET=jump to location C-g=quit and return to previous location
7011 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7013 (defvar org-goto-start-pos) ; dynamically scoped parameter
7015 ;; FIXME: Docstring does not mention both interfaces
7016 (defun org-goto (&optional alternative-interface)
7017 "Look up a different location in the current file, keeping current visibility.
7019 When you want look-up or go to a different location in a
7020 document, the fastest way is often to fold the entire buffer and
7021 then dive into the tree. This method has the disadvantage, that
7022 the previous location will be folded, which may not be what you
7023 want.
7025 This command works around this by showing a copy of the current
7026 buffer in an indirect buffer, in overview mode. You can dive
7027 into the tree in that copy, use org-occur and incremental search
7028 to find a location. When pressing RET or `Q', the command
7029 returns to the original buffer in which the visibility is still
7030 unchanged. After RET it will also jump to the location selected
7031 in the indirect buffer and expose the headline hierarchy above.
7033 With a prefix argument, use the alternative interface: e.g. if
7034 `org-goto-interface' is 'outline use 'outline-path-completion."
7035 (interactive "P")
7036 (org-goto-map)
7037 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7038 (org-refile-use-outline-path t)
7039 (org-refile-target-verify-function nil)
7040 (interface
7041 (if (not alternative-interface)
7042 org-goto-interface
7043 (if (eq org-goto-interface 'outline)
7044 'outline-path-completion
7045 'outline)))
7046 (org-goto-start-pos (point))
7047 (selected-point
7048 (if (eq interface 'outline)
7049 (car (org-get-location (current-buffer) org-goto-help))
7050 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7051 (org-refile-check-position pa)
7052 (nth 3 pa)))))
7053 (if selected-point
7054 (progn
7055 (org-mark-ring-push org-goto-start-pos)
7056 (goto-char selected-point)
7057 (if (or (outline-invisible-p) (org-invisible-p2))
7058 (org-show-context 'org-goto)))
7059 (message "Quit"))))
7061 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7062 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7063 (defvar org-goto-local-auto-isearch-map) ; defined below
7065 (defun org-get-location (buf help)
7066 "Let the user select a location in the Org-mode buffer BUF.
7067 This function uses a recursive edit. It returns the selected position
7068 or nil."
7069 (org-no-popups
7070 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7071 (isearch-hide-immediately nil)
7072 (isearch-search-fun-function
7073 (lambda () 'org-goto-local-search-headings))
7074 (org-goto-selected-point org-goto-exit-command))
7075 (save-excursion
7076 (save-window-excursion
7077 (delete-other-windows)
7078 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7079 (org-pop-to-buffer-same-window
7080 (condition-case nil
7081 (make-indirect-buffer (current-buffer) "*org-goto*")
7082 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7083 (with-output-to-temp-buffer "*Org Help*"
7084 (princ (format help (if org-goto-auto-isearch
7085 " Just type for auto-isearch."
7086 " n/p/f/b/u to navigate, q to quit."))))
7087 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7088 (setq buffer-read-only nil)
7089 (let ((org-startup-truncated t)
7090 (org-startup-folded nil)
7091 (org-startup-align-all-tables nil))
7092 (org-mode)
7093 (org-overview))
7094 (setq buffer-read-only t)
7095 (if (and (boundp 'org-goto-start-pos)
7096 (integer-or-marker-p org-goto-start-pos))
7097 (let ((org-show-hierarchy-above t)
7098 (org-show-siblings t)
7099 (org-show-following-heading t))
7100 (goto-char org-goto-start-pos)
7101 (and (outline-invisible-p) (org-show-context)))
7102 (goto-char (point-min)))
7103 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7104 (message "Select location and press RET")
7105 (use-local-map org-goto-map)
7106 (recursive-edit)))
7107 (kill-buffer "*org-goto*")
7108 (cons org-goto-selected-point org-goto-exit-command))))
7110 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7111 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7112 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7113 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7115 (defun org-goto-local-search-headings (string bound noerror)
7116 "Search and make sure that any matches are in headlines."
7117 (catch 'return
7118 (while (if isearch-forward
7119 (search-forward string bound noerror)
7120 (search-backward string bound noerror))
7121 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7122 (and (member :headline context)
7123 (not (member :tags context))))
7124 (throw 'return (point))))))
7126 (defun org-goto-local-auto-isearch ()
7127 "Start isearch."
7128 (interactive)
7129 (goto-char (point-min))
7130 (let ((keys (this-command-keys)))
7131 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7132 (isearch-mode t)
7133 (isearch-process-search-char (string-to-char keys)))))
7135 (defun org-goto-ret (&optional arg)
7136 "Finish `org-goto' by going to the new location."
7137 (interactive "P")
7138 (setq org-goto-selected-point (point)
7139 org-goto-exit-command 'return)
7140 (throw 'exit nil))
7142 (defun org-goto-left ()
7143 "Finish `org-goto' by going to the new location."
7144 (interactive)
7145 (if (org-at-heading-p)
7146 (progn
7147 (beginning-of-line 1)
7148 (setq org-goto-selected-point (point)
7149 org-goto-exit-command 'left)
7150 (throw 'exit nil))
7151 (error "Not on a heading")))
7153 (defun org-goto-right ()
7154 "Finish `org-goto' by going to the new location."
7155 (interactive)
7156 (if (org-at-heading-p)
7157 (progn
7158 (setq org-goto-selected-point (point)
7159 org-goto-exit-command 'right)
7160 (throw 'exit nil))
7161 (error "Not on a heading")))
7163 (defun org-goto-quit ()
7164 "Finish `org-goto' without cursor motion."
7165 (interactive)
7166 (setq org-goto-selected-point nil)
7167 (setq org-goto-exit-command 'quit)
7168 (throw 'exit nil))
7170 ;;; Indirect buffer display of subtrees
7172 (defvar org-indirect-dedicated-frame nil
7173 "This is the frame being used for indirect tree display.")
7174 (defvar org-last-indirect-buffer nil)
7176 (defun org-tree-to-indirect-buffer (&optional arg)
7177 "Create indirect buffer and narrow it to current subtree.
7178 With a numerical prefix ARG, go up to this level and then take that tree.
7179 If ARG is negative, go up that many levels.
7181 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7182 indirect buffer previously made with this command, to avoid proliferation of
7183 indirect buffers. However, when you call the command with a \
7184 \\[universal-argument] prefix, or
7185 when `org-indirect-buffer-display' is `new-frame', the last buffer
7186 is kept so that you can work with several indirect buffers at the same time.
7187 If `org-indirect-buffer-display' is `dedicated-frame', the \
7188 \\[universal-argument] prefix also
7189 requests that a new frame be made for the new buffer, so that the dedicated
7190 frame is not changed."
7191 (interactive "P")
7192 (let ((cbuf (current-buffer))
7193 (cwin (selected-window))
7194 (pos (point))
7195 beg end level heading ibuf)
7196 (save-excursion
7197 (org-back-to-heading t)
7198 (when (numberp arg)
7199 (setq level (org-outline-level))
7200 (if (< arg 0) (setq arg (+ level arg)))
7201 (while (> (setq level (org-outline-level)) arg)
7202 (org-up-heading-safe)))
7203 (setq beg (point)
7204 heading (org-get-heading))
7205 (org-end-of-subtree t t)
7206 (if (org-at-heading-p) (backward-char 1))
7207 (setq end (point)))
7208 (if (and (buffer-live-p org-last-indirect-buffer)
7209 (not (eq org-indirect-buffer-display 'new-frame))
7210 (not arg))
7211 (kill-buffer org-last-indirect-buffer))
7212 (setq ibuf (org-get-indirect-buffer cbuf)
7213 org-last-indirect-buffer ibuf)
7214 (cond
7215 ((or (eq org-indirect-buffer-display 'new-frame)
7216 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7217 (select-frame (make-frame))
7218 (delete-other-windows)
7219 (org-pop-to-buffer-same-window ibuf)
7220 (org-set-frame-title heading))
7221 ((eq org-indirect-buffer-display 'dedicated-frame)
7222 (raise-frame
7223 (select-frame (or (and org-indirect-dedicated-frame
7224 (frame-live-p org-indirect-dedicated-frame)
7225 org-indirect-dedicated-frame)
7226 (setq org-indirect-dedicated-frame (make-frame)))))
7227 (delete-other-windows)
7228 (org-pop-to-buffer-same-window ibuf)
7229 (org-set-frame-title (concat "Indirect: " heading)))
7230 ((eq org-indirect-buffer-display 'current-window)
7231 (org-pop-to-buffer-same-window ibuf))
7232 ((eq org-indirect-buffer-display 'other-window)
7233 (pop-to-buffer ibuf))
7234 (t (error "Invalid value")))
7235 (if (featurep 'xemacs)
7236 (save-excursion (org-mode) (turn-on-font-lock)))
7237 (narrow-to-region beg end)
7238 (show-all)
7239 (goto-char pos)
7240 (run-hook-with-args 'org-cycle-hook 'all)
7241 (and (window-live-p cwin) (select-window cwin))))
7243 (defun org-get-indirect-buffer (&optional buffer)
7244 (setq buffer (or buffer (current-buffer)))
7245 (let ((n 1) (base (buffer-name buffer)) bname)
7246 (while (buffer-live-p
7247 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7248 (setq n (1+ n)))
7249 (condition-case nil
7250 (make-indirect-buffer buffer bname 'clone)
7251 (error (make-indirect-buffer buffer bname)))))
7253 (defun org-set-frame-title (title)
7254 "Set the title of the current frame to the string TITLE."
7255 ;; FIXME: how to name a single frame in XEmacs???
7256 (unless (featurep 'xemacs)
7257 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7259 ;;;; Structure editing
7261 ;;; Inserting headlines
7263 (defun org-previous-line-empty-p ()
7264 (save-excursion
7265 (and (not (bobp))
7266 (or (beginning-of-line 0) t)
7267 (save-match-data
7268 (looking-at "[ \t]*$")))))
7270 (defun org-insert-heading (&optional force-heading invisible-ok)
7271 "Insert a new heading or item with same depth at point.
7272 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7273 If point is at the beginning of a headline, insert a sibling before the
7274 current headline. If point is not at the beginning, split the line,
7275 create the new headline with the text in the current line after point
7276 \(but see also the variable `org-M-RET-may-split-line').
7278 With a double prefix arg, force the heading to be inserted at the
7279 end of the parent subtree.
7281 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7282 This is important for non-interactive uses of the command."
7283 (interactive "P")
7284 (if (or (= (buffer-size) 0)
7285 (and (not (save-excursion
7286 (and (ignore-errors (org-back-to-heading invisible-ok))
7287 (org-at-heading-p))))
7288 (or force-heading (not (org-in-item-p)))))
7289 (progn
7290 (insert "\n* ")
7291 (run-hooks 'org-insert-heading-hook))
7292 (when (or force-heading (not (org-insert-item)))
7293 (let* ((empty-line-p nil)
7294 (level nil)
7295 (on-heading (org-at-heading-p))
7296 (head (save-excursion
7297 (condition-case nil
7298 (progn
7299 (org-back-to-heading invisible-ok)
7300 (when (and (not on-heading)
7301 (featurep 'org-inlinetask)
7302 (integerp org-inlinetask-min-level)
7303 (>= (length (match-string 0))
7304 org-inlinetask-min-level))
7305 ;; Find a heading level before the inline task
7306 (while (and (setq level (org-up-heading-safe))
7307 (>= level org-inlinetask-min-level)))
7308 (if (org-at-heading-p)
7309 (org-back-to-heading invisible-ok)
7310 (error "This should not happen")))
7311 (setq empty-line-p (org-previous-line-empty-p))
7312 (match-string 0))
7313 (error "*"))))
7314 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7315 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7316 pos hide-previous previous-pos)
7317 (cond
7318 ((and (org-at-heading-p) (bolp)
7319 (or (bobp)
7320 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7321 ;; insert before the current line
7322 (open-line (if blank 2 1)))
7323 ((and (bolp)
7324 (not org-insert-heading-respect-content)
7325 (or (bobp)
7326 (save-excursion
7327 (backward-char 1) (not (outline-invisible-p)))))
7328 ;; insert right here
7329 nil)
7331 ;; somewhere in the line
7332 (save-excursion
7333 (setq previous-pos (point-at-bol))
7334 (end-of-line)
7335 (setq hide-previous (outline-invisible-p)))
7336 (and org-insert-heading-respect-content (org-show-subtree))
7337 (let ((split
7338 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7339 (save-excursion
7340 (let ((p (point)))
7341 (goto-char (point-at-bol))
7342 (and (looking-at org-complex-heading-regexp)
7343 (match-beginning 4)
7344 (> p (match-beginning 4)))))))
7345 tags pos)
7346 (cond
7347 (org-insert-heading-respect-content
7348 (if (not (equal force-heading '(16)))
7349 (org-end-of-subtree nil t)
7350 (org-up-heading-safe)
7351 (org-end-of-subtree nil t))
7352 (when (featurep 'org-inlinetask)
7353 (while (and (not (eobp))
7354 (looking-at "\\(\\*+\\)[ \t]+")
7355 (>= (length (match-string 1))
7356 org-inlinetask-min-level))
7357 (org-end-of-subtree nil t)))
7358 (or (bolp) (newline))
7359 (or (org-previous-line-empty-p)
7360 (and blank (newline)))
7361 (open-line 1))
7362 ((org-at-heading-p)
7363 (when hide-previous
7364 (show-children)
7365 (org-show-entry))
7366 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7367 (setq tags (and (match-end 2) (match-string 2)))
7368 (and (match-end 1)
7369 (delete-region (match-beginning 1) (match-end 1)))
7370 (setq pos (point-at-bol))
7371 (or split (end-of-line 1))
7372 (delete-horizontal-space)
7373 (if (string-match "\\`\\*+\\'"
7374 (buffer-substring (point-at-bol) (point)))
7375 (insert " "))
7376 (newline (if blank 2 1))
7377 (when tags
7378 (save-excursion
7379 (goto-char pos)
7380 (end-of-line 1)
7381 (insert " " tags)
7382 (org-set-tags nil 'align))))
7384 (or split (end-of-line 1))
7385 (newline (if blank 2 1)))))))
7386 (insert head) (just-one-space)
7387 (setq pos (point))
7388 (end-of-line 1)
7389 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7390 (when (and org-insert-heading-respect-content hide-previous)
7391 (save-excursion
7392 (goto-char previous-pos)
7393 (hide-subtree)))
7394 (run-hooks 'org-insert-heading-hook)))))
7396 (defun org-get-heading (&optional no-tags no-todo)
7397 "Return the heading of the current entry, without the stars.
7398 When NO-TAGS is non-nil, don't include tags.
7399 When NO-TODO is non-nil, don't include TODO keywords."
7400 (save-excursion
7401 (org-back-to-heading t)
7402 (cond
7403 ((and no-tags no-todo)
7404 (looking-at org-complex-heading-regexp)
7405 (match-string 4))
7406 (no-tags
7407 (looking-at (concat org-outline-regexp
7408 "\\(.*?\\)"
7409 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7410 (match-string 1))
7411 (no-todo
7412 (looking-at org-todo-line-regexp)
7413 (match-string 3))
7414 (t (looking-at org-heading-regexp)
7415 (match-string 2)))))
7417 (defvar orgstruct-mode) ; defined below
7419 (defun org-heading-components ()
7420 "Return the components of the current heading.
7421 This is a list with the following elements:
7422 - the level as an integer
7423 - the reduced level, different if `org-odd-levels-only' is set.
7424 - the TODO keyword, or nil
7425 - the priority character, like ?A, or nil if no priority is given
7426 - the headline text itself, or the tags string if no headline text
7427 - the tags string, or nil."
7428 (save-excursion
7429 (org-back-to-heading t)
7430 (if (let (case-fold-search)
7431 (looking-at
7432 (if orgstruct-mode
7433 org-heading-regexp
7434 org-complex-heading-regexp)))
7435 (if orgstruct-mode
7436 (list (length (match-string 1))
7437 (org-reduced-level (length (match-string 1)))
7440 (match-string 2)
7441 nil)
7442 (list (length (match-string 1))
7443 (org-reduced-level (length (match-string 1)))
7444 (org-match-string-no-properties 2)
7445 (and (match-end 3) (aref (match-string 3) 2))
7446 (org-match-string-no-properties 4)
7447 (org-match-string-no-properties 5))))))
7449 (defun org-get-entry ()
7450 "Get the entry text, after heading, entire subtree."
7451 (save-excursion
7452 (org-back-to-heading t)
7453 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7455 (defun org-insert-heading-after-current ()
7456 "Insert a new heading with same level as current, after current subtree."
7457 (interactive)
7458 (org-back-to-heading)
7459 (org-insert-heading)
7460 (org-move-subtree-down)
7461 (end-of-line 1))
7463 (defun org-insert-heading-respect-content (invisible-ok)
7464 "Insert heading with `org-insert-heading-respect-content' set to t."
7465 (interactive "P")
7466 (let ((org-insert-heading-respect-content t))
7467 (org-insert-heading t invisible-ok)))
7469 (defun org-insert-todo-heading-respect-content (&optional force-state)
7470 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7471 (interactive "P")
7472 (let ((org-insert-heading-respect-content t))
7473 (org-insert-todo-heading force-state t)))
7475 (defun org-insert-todo-heading (arg &optional force-heading)
7476 "Insert a new heading with the same level and TODO state as current heading.
7477 If the heading has no TODO state, or if the state is DONE, use the first
7478 state (TODO by default). Also one prefix arg, force first state. With two
7479 prefix args, force inserting at the end of the parent subtree."
7480 (interactive "P")
7481 (when (or force-heading (not (org-insert-item 'checkbox)))
7482 (org-insert-heading (or (and (equal arg '(16)) '(16))
7483 force-heading))
7484 (save-excursion
7485 (org-back-to-heading)
7486 (outline-previous-heading)
7487 (looking-at org-todo-line-regexp))
7488 (let*
7489 ((new-mark-x
7490 (if (or arg
7491 (not (match-beginning 2))
7492 (member (match-string 2) org-done-keywords))
7493 (car org-todo-keywords-1)
7494 (match-string 2)))
7495 (new-mark
7497 (run-hook-with-args-until-success
7498 'org-todo-get-default-hook new-mark-x nil)
7499 new-mark-x)))
7500 (beginning-of-line 1)
7501 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7502 (if org-treat-insert-todo-heading-as-state-change
7503 (org-todo new-mark)
7504 (insert new-mark " "))))
7505 (when org-provide-todo-statistics
7506 (org-update-parent-todo-statistics))))
7508 (defun org-insert-subheading (arg)
7509 "Insert a new subheading and demote it.
7510 Works for outline headings and for plain lists alike."
7511 (interactive "P")
7512 (org-insert-heading arg)
7513 (cond
7514 ((org-at-heading-p) (org-do-demote))
7515 ((org-at-item-p) (org-indent-item))))
7517 (defun org-insert-todo-subheading (arg)
7518 "Insert a new subheading with TODO keyword or checkbox and demote it.
7519 Works for outline headings and for plain lists alike."
7520 (interactive "P")
7521 (org-insert-todo-heading arg)
7522 (cond
7523 ((org-at-heading-p) (org-do-demote))
7524 ((org-at-item-p) (org-indent-item))))
7526 ;;; Promotion and Demotion
7528 (defvar org-after-demote-entry-hook nil
7529 "Hook run after an entry has been demoted.
7530 The cursor will be at the beginning of the entry.
7531 When a subtree is being demoted, the hook will be called for each node.")
7533 (defvar org-after-promote-entry-hook nil
7534 "Hook run after an entry has been promoted.
7535 The cursor will be at the beginning of the entry.
7536 When a subtree is being promoted, the hook will be called for each node.")
7538 (defun org-promote-subtree ()
7539 "Promote the entire subtree.
7540 See also `org-promote'."
7541 (interactive)
7542 (save-excursion
7543 (org-with-limited-levels (org-map-tree 'org-promote)))
7544 (org-fix-position-after-promote))
7546 (defun org-demote-subtree ()
7547 "Demote the entire subtree. See `org-demote'.
7548 See also `org-promote'."
7549 (interactive)
7550 (save-excursion
7551 (org-with-limited-levels (org-map-tree 'org-demote)))
7552 (org-fix-position-after-promote))
7555 (defun org-do-promote ()
7556 "Promote the current heading higher up the tree.
7557 If the region is active in `transient-mark-mode', promote all headings
7558 in the region."
7559 (interactive)
7560 (save-excursion
7561 (if (org-region-active-p)
7562 (org-map-region 'org-promote (region-beginning) (region-end))
7563 (org-promote)))
7564 (org-fix-position-after-promote))
7566 (defun org-do-demote ()
7567 "Demote the current heading lower down the tree.
7568 If the region is active in `transient-mark-mode', demote all headings
7569 in the region."
7570 (interactive)
7571 (save-excursion
7572 (if (org-region-active-p)
7573 (org-map-region 'org-demote (region-beginning) (region-end))
7574 (org-demote)))
7575 (org-fix-position-after-promote))
7577 (defun org-fix-position-after-promote ()
7578 "Make sure that after pro/demotion cursor position is right."
7579 (let ((pos (point)))
7580 (when (save-excursion
7581 (beginning-of-line 1)
7582 (looking-at org-todo-line-regexp)
7583 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7584 (cond ((eobp) (insert " "))
7585 ((eolp) (insert " "))
7586 ((equal (char-after) ?\ ) (forward-char 1))))))
7588 (defun org-current-level ()
7589 "Return the level of the current entry, or nil if before the first headline.
7590 The level is the number of stars at the beginning of the headline."
7591 (save-excursion
7592 (org-with-limited-levels
7593 (if (ignore-errors (org-back-to-heading t))
7594 (funcall outline-level)))))
7596 (defun org-get-previous-line-level ()
7597 "Return the outline depth of the last headline before the current line.
7598 Returns 0 for the first headline in the buffer, and nil if before the
7599 first headline."
7600 (let ((current-level (org-current-level))
7601 (prev-level (when (> (line-number-at-pos) 1)
7602 (save-excursion
7603 (beginning-of-line 0)
7604 (org-current-level)))))
7605 (cond ((null current-level) nil) ; Before first headline
7606 ((null prev-level) 0) ; At first headline
7607 (prev-level))))
7609 (defun org-reduced-level (l)
7610 "Compute the effective level of a heading.
7611 This takes into account the setting of `org-odd-levels-only'."
7612 (cond
7613 ((zerop l) 0)
7614 (org-odd-levels-only (1+ (floor (/ l 2))))
7615 (t l)))
7617 (defun org-level-increment ()
7618 "Return the number of stars that will be added or removed at a
7619 time to headlines when structure editing, based on the value of
7620 `org-odd-levels-only'."
7621 (if org-odd-levels-only 2 1))
7623 (defun org-get-valid-level (level &optional change)
7624 "Rectify a level change under the influence of `org-odd-levels-only'
7625 LEVEL is a current level, CHANGE is by how much the level should be
7626 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7627 even level numbers will become the next higher odd number."
7628 (if org-odd-levels-only
7629 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7630 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7631 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7632 (max 1 (+ level (or change 0)))))
7634 (if (boundp 'define-obsolete-function-alias)
7635 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7636 (define-obsolete-function-alias 'org-get-legal-level
7637 'org-get-valid-level)
7638 (define-obsolete-function-alias 'org-get-legal-level
7639 'org-get-valid-level "23.1")))
7641 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7642 ;; ̀org-with-limited-levels'
7643 (defun org-promote ()
7644 "Promote the current heading higher up the tree.
7645 If the region is active in `transient-mark-mode', promote all headings
7646 in the region."
7647 (org-back-to-heading t)
7648 (let* ((level (save-match-data (funcall outline-level)))
7649 (after-change-functions (remove 'flyspell-after-change-function
7650 after-change-functions))
7651 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7652 (diff (abs (- level (length up-head) -1))))
7653 (cond ((and (= level 1) org-called-with-limited-levels
7654 org-allow-promoting-top-level-subtree)
7655 (replace-match "# " nil t))
7656 ((= level 1)
7657 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7658 (t (replace-match up-head nil t)))
7659 ;; Fixup tag positioning
7660 (unless (= level 1)
7661 (and org-auto-align-tags (org-set-tags nil t))
7662 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7663 (run-hooks 'org-after-promote-entry-hook)))
7665 (defun org-demote ()
7666 "Demote the current heading lower down the tree.
7667 If the region is active in `transient-mark-mode', demote all headings
7668 in the region."
7669 (org-back-to-heading t)
7670 (let* ((level (save-match-data (funcall outline-level)))
7671 (after-change-functions (remove 'flyspell-after-change-function
7672 after-change-functions))
7673 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7674 (diff (abs (- level (length down-head) -1))))
7675 (replace-match down-head nil t)
7676 ;; Fixup tag positioning
7677 (and org-auto-align-tags (org-set-tags nil t))
7678 (if org-adapt-indentation (org-fixup-indentation diff))
7679 (run-hooks 'org-after-demote-entry-hook)))
7681 (defun org-cycle-level ()
7682 "Cycle the level of an empty headline through possible states.
7683 This goes first to child, then to parent, level, then up the hierarchy.
7684 After top level, it switches back to sibling level."
7685 (interactive)
7686 (let ((org-adapt-indentation nil))
7687 (when (org-point-at-end-of-empty-headline)
7688 (setq this-command 'org-cycle-level) ; Only needed for caching
7689 (let ((cur-level (org-current-level))
7690 (prev-level (org-get-previous-line-level)))
7691 (cond
7692 ;; If first headline in file, promote to top-level.
7693 ((= prev-level 0)
7694 (loop repeat (/ (- cur-level 1) (org-level-increment))
7695 do (org-do-promote)))
7696 ;; If same level as prev, demote one.
7697 ((= prev-level cur-level)
7698 (org-do-demote))
7699 ;; If parent is top-level, promote to top level if not already.
7700 ((= prev-level 1)
7701 (loop repeat (/ (- cur-level 1) (org-level-increment))
7702 do (org-do-promote)))
7703 ;; If top-level, return to prev-level.
7704 ((= cur-level 1)
7705 (loop repeat (/ (- prev-level 1) (org-level-increment))
7706 do (org-do-demote)))
7707 ;; If less than prev-level, promote one.
7708 ((< cur-level prev-level)
7709 (org-do-promote))
7710 ;; If deeper than prev-level, promote until higher than
7711 ;; prev-level.
7712 ((> cur-level prev-level)
7713 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7714 do (org-do-promote))))
7715 t))))
7717 (defun org-map-tree (fun)
7718 "Call FUN for every heading underneath the current one."
7719 (org-back-to-heading)
7720 (let ((level (funcall outline-level)))
7721 (save-excursion
7722 (funcall fun)
7723 (while (and (progn
7724 (outline-next-heading)
7725 (> (funcall outline-level) level))
7726 (not (eobp)))
7727 (funcall fun)))))
7729 (defun org-map-region (fun beg end)
7730 "Call FUN for every heading between BEG and END."
7731 (let ((org-ignore-region t))
7732 (save-excursion
7733 (setq end (copy-marker end))
7734 (goto-char beg)
7735 (if (and (re-search-forward org-outline-regexp-bol nil t)
7736 (< (point) end))
7737 (funcall fun))
7738 (while (and (progn
7739 (outline-next-heading)
7740 (< (point) end))
7741 (not (eobp)))
7742 (funcall fun)))))
7744 (defvar org-property-end-re) ; silence byte-compiler
7745 (defun org-fixup-indentation (diff)
7746 "Change the indentation in the current entry by DIFF.
7747 However, if any line in the current entry has no indentation, or if it
7748 would end up with no indentation after the change, nothing at all is done."
7749 (save-excursion
7750 (let ((end (save-excursion (outline-next-heading)
7751 (point-marker)))
7752 (prohibit (if (> diff 0)
7753 "^\\S-"
7754 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7755 col)
7756 (unless (save-excursion (end-of-line 1)
7757 (re-search-forward prohibit end t))
7758 (while (and (< (point) end)
7759 (re-search-forward "^[ \t]+" end t))
7760 (goto-char (match-end 0))
7761 (setq col (current-column))
7762 (if (< diff 0) (replace-match ""))
7763 (org-indent-to-column (+ diff col))))
7764 (move-marker end nil))))
7766 (defun org-convert-to-odd-levels ()
7767 "Convert an org-mode file with all levels allowed to one with odd levels.
7768 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7769 level 5 etc."
7770 (interactive)
7771 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7772 (let ((outline-level 'org-outline-level)
7773 (org-odd-levels-only nil) n)
7774 (save-excursion
7775 (goto-char (point-min))
7776 (while (re-search-forward "^\\*\\*+ " nil t)
7777 (setq n (- (length (match-string 0)) 2))
7778 (while (>= (setq n (1- n)) 0)
7779 (org-demote))
7780 (end-of-line 1))))))
7782 (defun org-convert-to-oddeven-levels ()
7783 "Convert an org-mode file with only odd levels to one with odd/even levels.
7784 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7785 file contains a section with an even level, conversion would
7786 destroy the structure of the file. An error is signaled in this
7787 case."
7788 (interactive)
7789 (goto-char (point-min))
7790 ;; First check if there are no even levels
7791 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7792 (org-show-context t)
7793 (error "Not all levels are odd in this file. Conversion not possible"))
7794 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7795 (let ((outline-regexp org-outline-regexp)
7796 (outline-level 'org-outline-level)
7797 (org-odd-levels-only nil) n)
7798 (save-excursion
7799 (goto-char (point-min))
7800 (while (re-search-forward "^\\*\\*+ " nil t)
7801 (setq n (/ (1- (length (match-string 0))) 2))
7802 (while (>= (setq n (1- n)) 0)
7803 (org-promote))
7804 (end-of-line 1))))))
7806 (defun org-tr-level (n)
7807 "Make N odd if required."
7808 (if org-odd-levels-only (1+ (/ n 2)) n))
7810 ;;; Vertical tree motion, cutting and pasting of subtrees
7812 (defun org-move-subtree-up (&optional arg)
7813 "Move the current subtree up past ARG headlines of the same level."
7814 (interactive "p")
7815 (org-move-subtree-down (- (prefix-numeric-value arg))))
7817 (defun org-move-subtree-down (&optional arg)
7818 "Move the current subtree down past ARG headlines of the same level."
7819 (interactive "p")
7820 (setq arg (prefix-numeric-value arg))
7821 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7822 'org-get-last-sibling))
7823 (ins-point (make-marker))
7824 (cnt (abs arg))
7825 (col (current-column))
7826 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7827 ;; Select the tree
7828 (org-back-to-heading)
7829 (setq beg0 (point))
7830 (save-excursion
7831 (setq ne-beg (org-back-over-empty-lines))
7832 (setq beg (point)))
7833 (save-match-data
7834 (save-excursion (outline-end-of-heading)
7835 (setq folded (outline-invisible-p)))
7836 (outline-end-of-subtree))
7837 (outline-next-heading)
7838 (setq ne-end (org-back-over-empty-lines))
7839 (setq end (point))
7840 (goto-char beg0)
7841 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7842 ;; include less whitespace
7843 (save-excursion
7844 (goto-char beg)
7845 (forward-line (- ne-beg ne-end))
7846 (setq beg (point))))
7847 ;; Find insertion point, with error handling
7848 (while (> cnt 0)
7849 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7850 (progn (goto-char beg0)
7851 (error "Cannot move past superior level or buffer limit")))
7852 (setq cnt (1- cnt)))
7853 (if (> arg 0)
7854 ;; Moving forward - still need to move over subtree
7855 (progn (org-end-of-subtree t t)
7856 (save-excursion
7857 (org-back-over-empty-lines)
7858 (or (bolp) (newline)))))
7859 (setq ne-ins (org-back-over-empty-lines))
7860 (move-marker ins-point (point))
7861 (setq txt (buffer-substring beg end))
7862 (org-save-markers-in-region beg end)
7863 (delete-region beg end)
7864 (org-remove-empty-overlays-at beg)
7865 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7866 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7867 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7868 (let ((bbb (point)))
7869 (insert-before-markers txt)
7870 (org-reinstall-markers-in-region bbb)
7871 (move-marker ins-point bbb))
7872 (or (bolp) (insert "\n"))
7873 (setq ins-end (point))
7874 (goto-char ins-point)
7875 (org-skip-whitespace)
7876 (when (and (< arg 0)
7877 (org-first-sibling-p)
7878 (> ne-ins ne-beg))
7879 ;; Move whitespace back to beginning
7880 (save-excursion
7881 (goto-char ins-end)
7882 (let ((kill-whole-line t))
7883 (kill-line (- ne-ins ne-beg)) (point)))
7884 (insert (make-string (- ne-ins ne-beg) ?\n)))
7885 (move-marker ins-point nil)
7886 (if folded
7887 (hide-subtree)
7888 (org-show-entry)
7889 (show-children)
7890 (org-cycle-hide-drawers 'children))
7891 (org-clean-visibility-after-subtree-move)
7892 ;; move back to the initial column we were at
7893 (move-to-column col)))
7895 (defvar org-subtree-clip ""
7896 "Clipboard for cut and paste of subtrees.
7897 This is actually only a copy of the kill, because we use the normal kill
7898 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7900 (defvar org-subtree-clip-folded nil
7901 "Was the last copied subtree folded?
7902 This is used to fold the tree back after pasting.")
7904 (defun org-cut-subtree (&optional n)
7905 "Cut the current subtree into the clipboard.
7906 With prefix arg N, cut this many sequential subtrees.
7907 This is a short-hand for marking the subtree and then cutting it."
7908 (interactive "p")
7909 (org-copy-subtree n 'cut))
7911 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7912 "Cut the current subtree into the clipboard.
7913 With prefix arg N, cut this many sequential subtrees.
7914 This is a short-hand for marking the subtree and then copying it.
7915 If CUT is non-nil, actually cut the subtree.
7916 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7917 of some markers in the region, even if CUT is non-nil. This is
7918 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7919 (interactive "p")
7920 (let (beg end folded (beg0 (point)))
7921 (if (org-called-interactively-p 'any)
7922 (org-back-to-heading nil) ; take what looks like a subtree
7923 (org-back-to-heading t)) ; take what is really there
7924 (setq beg (point))
7925 (skip-chars-forward " \t\r\n")
7926 (save-match-data
7927 (if nosubtrees
7928 (outline-next-heading)
7929 (save-excursion (outline-end-of-heading)
7930 (setq folded (outline-invisible-p)))
7931 (condition-case nil
7932 (org-forward-heading-same-level (1- n) t)
7933 (error nil))
7934 (org-end-of-subtree t t)))
7935 (setq end (point))
7936 (goto-char beg0)
7937 (when (> end beg)
7938 (setq org-subtree-clip-folded folded)
7939 (when (or cut force-store-markers)
7940 (org-save-markers-in-region beg end))
7941 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7942 (setq org-subtree-clip (current-kill 0))
7943 (message "%s: Subtree(s) with %d characters"
7944 (if cut "Cut" "Copied")
7945 (length org-subtree-clip)))))
7947 (defun org-paste-subtree (&optional level tree for-yank)
7948 "Paste the clipboard as a subtree, with modification of headline level.
7949 The entire subtree is promoted or demoted in order to match a new headline
7950 level.
7952 If the cursor is at the beginning of a headline, the same level as
7953 that headline is used to paste the tree.
7955 If not, the new level is derived from the *visible* headings
7956 before and after the insertion point, and taken to be the inferior headline
7957 level of the two. So if the previous visible heading is level 3 and the
7958 next is level 4 (or vice versa), level 4 will be used for insertion.
7959 This makes sure that the subtree remains an independent subtree and does
7960 not swallow low level entries.
7962 You can also force a different level, either by using a numeric prefix
7963 argument, or by inserting the heading marker by hand. For example, if the
7964 cursor is after \"*****\", then the tree will be shifted to level 5.
7966 If optional TREE is given, use this text instead of the kill ring.
7968 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7969 move back over whitespace before inserting, and move point to the end of
7970 the inserted text when done."
7971 (interactive "P")
7972 (setq tree (or tree (and kill-ring (current-kill 0))))
7973 (unless (org-kill-is-subtree-p tree)
7974 (error "%s"
7975 (substitute-command-keys
7976 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7977 (org-with-limited-levels
7978 (let* ((visp (not (outline-invisible-p)))
7979 (txt tree)
7980 (^re_ "\\(\\*+\\)[ \t]*")
7981 (old-level (if (string-match org-outline-regexp-bol txt)
7982 (- (match-end 0) (match-beginning 0) 1)
7983 -1))
7984 (force-level (cond (level (prefix-numeric-value level))
7985 ((and (looking-at "[ \t]*$")
7986 (string-match
7987 "^\\*+$" (buffer-substring
7988 (point-at-bol) (point))))
7989 (- (match-end 1) (match-beginning 1)))
7990 ((and (bolp)
7991 (looking-at org-outline-regexp))
7992 (- (match-end 0) (point) 1))))
7993 (previous-level (save-excursion
7994 (condition-case nil
7995 (progn
7996 (outline-previous-visible-heading 1)
7997 (if (looking-at ^re_)
7998 (- (match-end 0) (match-beginning 0) 1)
8000 (error 1))))
8001 (next-level (save-excursion
8002 (condition-case nil
8003 (progn
8004 (or (looking-at org-outline-regexp)
8005 (outline-next-visible-heading 1))
8006 (if (looking-at ^re_)
8007 (- (match-end 0) (match-beginning 0) 1)
8009 (error 1))))
8010 (new-level (or force-level (max previous-level next-level)))
8011 (shift (if (or (= old-level -1)
8012 (= new-level -1)
8013 (= old-level new-level))
8015 (- new-level old-level)))
8016 (delta (if (> shift 0) -1 1))
8017 (func (if (> shift 0) 'org-demote 'org-promote))
8018 (org-odd-levels-only nil)
8019 beg end newend)
8020 ;; Remove the forced level indicator
8021 (if force-level
8022 (delete-region (point-at-bol) (point)))
8023 ;; Paste
8024 (beginning-of-line (if (bolp) 1 2))
8025 (setq beg (point))
8026 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8027 (insert-before-markers txt)
8028 (unless (string-match "\n\\'" txt) (insert "\n"))
8029 (setq newend (point))
8030 (org-reinstall-markers-in-region beg)
8031 (setq end (point))
8032 (goto-char beg)
8033 (skip-chars-forward " \t\n\r")
8034 (setq beg (point))
8035 (if (and (outline-invisible-p) visp)
8036 (save-excursion (outline-show-heading)))
8037 ;; Shift if necessary
8038 (unless (= shift 0)
8039 (save-restriction
8040 (narrow-to-region beg end)
8041 (while (not (= shift 0))
8042 (org-map-region func (point-min) (point-max))
8043 (setq shift (+ delta shift)))
8044 (goto-char (point-min))
8045 (setq newend (point-max))))
8046 (when (or (org-called-interactively-p 'interactive) for-yank)
8047 (message "Clipboard pasted as level %d subtree" new-level))
8048 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8049 kill-ring
8050 (eq org-subtree-clip (current-kill 0))
8051 org-subtree-clip-folded)
8052 ;; The tree was folded before it was killed/copied
8053 (hide-subtree))
8054 (and for-yank (goto-char newend)))))
8056 (defun org-kill-is-subtree-p (&optional txt)
8057 "Check if the current kill is an outline subtree, or a set of trees.
8058 Returns nil if kill does not start with a headline, or if the first
8059 headline level is not the largest headline level in the tree.
8060 So this will actually accept several entries of equal levels as well,
8061 which is OK for `org-paste-subtree'.
8062 If optional TXT is given, check this string instead of the current kill."
8063 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8064 (re (org-get-limited-outline-regexp))
8065 (^re (concat "^" re))
8066 (start-level (and kill
8067 (string-match
8068 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8069 kill)
8070 (- (match-end 2) (match-beginning 2) 1)))
8071 (start (1+ (or (match-beginning 2) -1))))
8072 (if (not start-level)
8073 (progn
8074 nil) ;; does not even start with a heading
8075 (catch 'exit
8076 (while (setq start (string-match ^re kill (1+ start)))
8077 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8078 (throw 'exit nil)))
8079 t))))
8081 (defvar org-markers-to-move nil
8082 "Markers that should be moved with a cut-and-paste operation.
8083 Those markers are stored together with their positions relative to
8084 the start of the region.")
8086 (defun org-save-markers-in-region (beg end)
8087 "Check markers in region.
8088 If these markers are between BEG and END, record their position relative
8089 to BEG, so that after moving the block of text, we can put the markers back
8090 into place.
8091 This function gets called just before an entry or tree gets cut from the
8092 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8093 called immediately, to move the markers with the entries."
8094 (setq org-markers-to-move nil)
8095 (when (featurep 'org-clock)
8096 (org-clock-save-markers-for-cut-and-paste beg end))
8097 (when (featurep 'org-agenda)
8098 (org-agenda-save-markers-for-cut-and-paste beg end)))
8100 (defun org-check-and-save-marker (marker beg end)
8101 "Check if MARKER is between BEG and END.
8102 If yes, remember the marker and the distance to BEG."
8103 (when (and (marker-buffer marker)
8104 (equal (marker-buffer marker) (current-buffer)))
8105 (if (and (>= marker beg) (< marker end))
8106 (push (cons marker (- marker beg)) org-markers-to-move))))
8108 (defun org-reinstall-markers-in-region (beg)
8109 "Move all remembered markers to their position relative to BEG."
8110 (mapc (lambda (x)
8111 (move-marker (car x) (+ beg (cdr x))))
8112 org-markers-to-move)
8113 (setq org-markers-to-move nil))
8115 (defun org-narrow-to-subtree ()
8116 "Narrow buffer to the current subtree."
8117 (interactive)
8118 (save-excursion
8119 (save-match-data
8120 (org-with-limited-levels
8121 (narrow-to-region
8122 (progn (org-back-to-heading t) (point))
8123 (progn (org-end-of-subtree t t)
8124 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8125 (point)))))))
8127 (defun org-narrow-to-block ()
8128 "Narrow buffer to the current block."
8129 (interactive)
8130 (let* ((case-fold-search t)
8131 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8132 "^[ \t]*#\\+end_.*")))
8133 (if blockp
8134 (narrow-to-region (car blockp) (cdr blockp))
8135 (error "Not in a block"))))
8137 (eval-when-compile
8138 (defvar org-property-drawer-re))
8140 (defvar org-property-start-re) ;; defined below
8141 (defun org-clone-subtree-with-time-shift (n &optional shift)
8142 "Clone the task (subtree) at point N times.
8143 The clones will be inserted as siblings.
8145 In interactive use, the user will be prompted for the number of
8146 clones to be produced, and for a time SHIFT, which may be a
8147 repeater as used in time stamps, for example `+3d'.
8149 When a valid repeater is given and the entry contains any time
8150 stamps, the clones will become a sequence in time, with time
8151 stamps in the subtree shifted for each clone produced. If SHIFT
8152 is nil or the empty string, time stamps will be left alone. The
8153 ID property of the original subtree is removed.
8155 If the original subtree did contain time stamps with a repeater,
8156 the following will happen:
8157 - the repeater will be removed in each clone
8158 - an additional clone will be produced, with the current, unshifted
8159 date(s) in the entry.
8160 - the original entry will be placed *after* all the clones, with
8161 repeater intact.
8162 - the start days in the repeater in the original entry will be shifted
8163 to past the last clone.
8164 In this way you can spell out a number of instances of a repeating task,
8165 and still retain the repeater to cover future instances of the task."
8166 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8167 (let (beg end template task idprop
8168 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8169 (drawer-re org-drawer-regexp))
8170 (if (not (and (integerp n) (> n 0)))
8171 (error "Invalid number of replications %s" n))
8172 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8173 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8174 shift)))
8175 (error "Invalid shift specification %s" shift))
8176 (when doshift
8177 (setq shift-n (string-to-number (match-string 1 shift))
8178 shift-what (cdr (assoc (match-string 2 shift)
8179 '(("d" . day) ("w" . week)
8180 ("m" . month) ("y" . year))))))
8181 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8182 (setq nmin 1 nmax n)
8183 (org-back-to-heading t)
8184 (setq beg (point))
8185 (setq idprop (org-entry-get nil "ID"))
8186 (org-end-of-subtree t t)
8187 (or (bolp) (insert "\n"))
8188 (setq end (point))
8189 (setq template (buffer-substring beg end))
8190 (when (and doshift
8191 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8192 (delete-region beg end)
8193 (setq end beg)
8194 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8195 (goto-char end)
8196 (loop for n from nmin to nmax do
8197 ;; prepare clone
8198 (with-temp-buffer
8199 (insert template)
8200 (org-mode)
8201 (goto-char (point-min))
8202 (org-show-subtree)
8203 (and idprop (if org-clone-delete-id
8204 (org-entry-delete nil "ID")
8205 (org-id-get-create t)))
8206 (unless (= n 0)
8207 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8208 (kill-whole-line))
8209 (goto-char (point-min))
8210 (while (re-search-forward drawer-re nil t)
8211 (mapc (lambda (d)
8212 (org-remove-empty-drawer-at d (point))) org-drawers)))
8213 (goto-char (point-min))
8214 (when doshift
8215 (while (re-search-forward org-ts-regexp-both nil t)
8216 (org-timestamp-change (* n shift-n) shift-what))
8217 (unless (= n n-no-remove)
8218 (goto-char (point-min))
8219 (while (re-search-forward org-ts-regexp nil t)
8220 (save-excursion
8221 (goto-char (match-beginning 0))
8222 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8223 (delete-region (match-beginning 1) (match-end 1)))))))
8224 (setq task (buffer-string)))
8225 (insert task))
8226 (goto-char beg)))
8228 ;;; Outline Sorting
8230 (defun org-sort (with-case)
8231 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8232 Optional argument WITH-CASE means sort case-sensitively."
8233 (interactive "P")
8234 (cond
8235 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8236 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8238 (org-call-with-arg 'org-sort-entries with-case))))
8240 (defun org-sort-remove-invisible (s)
8241 (remove-text-properties 0 (length s) org-rm-props s)
8242 (while (string-match org-bracket-link-regexp s)
8243 (setq s (replace-match (if (match-end 2)
8244 (match-string 3 s)
8245 (match-string 1 s)) t t s)))
8248 (defvar org-priority-regexp) ; defined later in the file
8250 (defvar org-after-sorting-entries-or-items-hook nil
8251 "Hook that is run after a bunch of entries or items have been sorted.
8252 When children are sorted, the cursor is in the parent line when this
8253 hook gets called. When a region or a plain list is sorted, the cursor
8254 will be in the first entry of the sorted region/list.")
8256 (defun org-sort-entries
8257 (&optional with-case sorting-type getkey-func compare-func property)
8258 "Sort entries on a certain level of an outline tree.
8259 If there is an active region, the entries in the region are sorted.
8260 Else, if the cursor is before the first entry, sort the top-level items.
8261 Else, the children of the entry at point are sorted.
8263 Sorting can be alphabetically, numerically, by date/time as given by
8264 a time stamp, by a property or by priority.
8266 The command prompts for the sorting type unless it has been given to the
8267 function through the SORTING-TYPE argument, which needs to be a character,
8268 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8269 precise meaning of each character:
8271 n Numerically, by converting the beginning of the entry/item to a number.
8272 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8273 o By order of TODO keywords.
8274 t By date/time, either the first active time stamp in the entry, or, if
8275 none exist, by the first inactive one.
8276 s By the scheduled date/time.
8277 d By deadline date/time.
8278 c By creation time, which is assumed to be the first inactive time stamp
8279 at the beginning of a line.
8280 p By priority according to the cookie.
8281 r By the value of a property.
8283 Capital letters will reverse the sort order.
8285 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8286 called with point at the beginning of the record. It must return either
8287 a string or a number that should serve as the sorting key for that record.
8289 Comparing entries ignores case by default. However, with an optional argument
8290 WITH-CASE, the sorting considers case as well."
8291 (interactive "P")
8292 (let ((case-func (if with-case 'identity 'downcase))
8293 (cmstr
8294 ;; The clock marker is lost when using `sort-subr', let's
8295 ;; store the clocking string.
8296 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8297 (save-excursion
8298 (goto-char org-clock-marker)
8299 (looking-back "^.*") (match-string-no-properties 0))))
8300 start beg end stars re re2
8301 txt what tmp)
8302 ;; Find beginning and end of region to sort
8303 (cond
8304 ((org-region-active-p)
8305 ;; we will sort the region
8306 (setq end (region-end)
8307 what "region")
8308 (goto-char (region-beginning))
8309 (if (not (org-at-heading-p)) (outline-next-heading))
8310 (setq start (point)))
8311 ((or (org-at-heading-p)
8312 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8313 ;; we will sort the children of the current headline
8314 (org-back-to-heading)
8315 (setq start (point)
8316 end (progn (org-end-of-subtree t t)
8317 (or (bolp) (insert "\n"))
8318 (org-back-over-empty-lines)
8319 (point))
8320 what "children")
8321 (goto-char start)
8322 (show-subtree)
8323 (outline-next-heading))
8325 ;; we will sort the top-level entries in this file
8326 (goto-char (point-min))
8327 (or (org-at-heading-p) (outline-next-heading))
8328 (setq start (point))
8329 (goto-char (point-max))
8330 (beginning-of-line 1)
8331 (when (looking-at ".*?\\S-")
8332 ;; File ends in a non-white line
8333 (end-of-line 1)
8334 (insert "\n"))
8335 (setq end (point-max))
8336 (setq what "top-level")
8337 (goto-char start)
8338 (show-all)))
8340 (setq beg (point))
8341 (if (>= beg end) (error "Nothing to sort"))
8343 (looking-at "\\(\\*+\\)")
8344 (setq stars (match-string 1)
8345 re (concat "^" (regexp-quote stars) " +")
8346 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8347 txt (buffer-substring beg end))
8348 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8349 (if (and (not (equal stars "*")) (string-match re2 txt))
8350 (error "Region to sort contains a level above the first entry"))
8352 (unless sorting-type
8353 (message
8354 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8355 [t]ime [s]cheduled [d]eadline [c]reated
8356 A/N/P/R/O/F/T/S/D/C means reversed:"
8357 what)
8358 (setq sorting-type (read-char-exclusive))
8360 (unless getkey-func
8361 (and (= (downcase sorting-type) ?f)
8362 (setq getkey-func
8363 (org-icompleting-read "Sort using function: "
8364 obarray 'fboundp t nil nil))
8365 (setq getkey-func (intern getkey-func))))
8367 (and (= (downcase sorting-type) ?r)
8368 (not property)
8369 (setq property
8370 (org-icompleting-read "Property: "
8371 (mapcar 'list (org-buffer-property-keys t))
8372 nil t))))
8374 (message "Sorting entries...")
8376 (save-restriction
8377 (narrow-to-region start end)
8378 (let ((dcst (downcase sorting-type))
8379 (case-fold-search nil)
8380 (now (current-time)))
8381 (sort-subr
8382 (/= dcst sorting-type)
8383 ;; This function moves to the beginning character of the "record" to
8384 ;; be sorted.
8385 (lambda nil
8386 (if (re-search-forward re nil t)
8387 (goto-char (match-beginning 0))
8388 (goto-char (point-max))))
8389 ;; This function moves to the last character of the "record" being
8390 ;; sorted.
8391 (lambda nil
8392 (save-match-data
8393 (condition-case nil
8394 (outline-forward-same-level 1)
8395 (error
8396 (goto-char (point-max))))))
8397 ;; This function returns the value that gets sorted against.
8398 (lambda nil
8399 (cond
8400 ((= dcst ?n)
8401 (if (looking-at org-complex-heading-regexp)
8402 (string-to-number (match-string 4))
8403 nil))
8404 ((= dcst ?a)
8405 (if (looking-at org-complex-heading-regexp)
8406 (funcall case-func (match-string 4))
8407 nil))
8408 ((= dcst ?t)
8409 (let ((end (save-excursion (outline-next-heading) (point))))
8410 (if (or (re-search-forward org-ts-regexp end t)
8411 (re-search-forward org-ts-regexp-both end t))
8412 (org-time-string-to-seconds (match-string 0))
8413 (org-float-time now))))
8414 ((= dcst ?c)
8415 (let ((end (save-excursion (outline-next-heading) (point))))
8416 (if (re-search-forward
8417 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8418 end t)
8419 (org-time-string-to-seconds (match-string 0))
8420 (org-float-time now))))
8421 ((= dcst ?s)
8422 (let ((end (save-excursion (outline-next-heading) (point))))
8423 (if (re-search-forward org-scheduled-time-regexp end t)
8424 (org-time-string-to-seconds (match-string 1))
8425 (org-float-time now))))
8426 ((= dcst ?d)
8427 (let ((end (save-excursion (outline-next-heading) (point))))
8428 (if (re-search-forward org-deadline-time-regexp end t)
8429 (org-time-string-to-seconds (match-string 1))
8430 (org-float-time now))))
8431 ((= dcst ?p)
8432 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8433 (string-to-char (match-string 2))
8434 org-default-priority))
8435 ((= dcst ?r)
8436 (or (org-entry-get nil property) ""))
8437 ((= dcst ?o)
8438 (if (looking-at org-complex-heading-regexp)
8439 (- 9999 (length (member (match-string 2)
8440 org-todo-keywords-1)))))
8441 ((= dcst ?f)
8442 (if getkey-func
8443 (progn
8444 (setq tmp (funcall getkey-func))
8445 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8446 tmp)
8447 (error "Invalid key function `%s'" getkey-func)))
8448 (t (error "Invalid sorting type `%c'" sorting-type))))
8450 (cond
8451 ((= dcst ?a) 'string<)
8452 ((= dcst ?f) compare-func)
8453 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8454 (run-hooks 'org-after-sorting-entries-or-items-hook)
8455 ;; Reset the clock marker if needed
8456 (when cmstr
8457 (save-excursion
8458 (goto-char start)
8459 (search-forward cmstr nil t)
8460 (move-marker org-clock-marker (point))))
8461 (message "Sorting entries...done")))
8463 (defun org-do-sort (table what &optional with-case sorting-type)
8464 "Sort TABLE of WHAT according to SORTING-TYPE.
8465 The user will be prompted for the SORTING-TYPE if the call to this
8466 function does not specify it. WHAT is only for the prompt, to indicate
8467 what is being sorted. The sorting key will be extracted from
8468 the car of the elements of the table.
8469 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8470 (unless sorting-type
8471 (message
8472 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8473 what)
8474 (setq sorting-type (read-char-exclusive)))
8475 (let ((dcst (downcase sorting-type))
8476 extractfun comparefun)
8477 ;; Define the appropriate functions
8478 (cond
8479 ((= dcst ?n)
8480 (setq extractfun 'string-to-number
8481 comparefun (if (= dcst sorting-type) '< '>)))
8482 ((= dcst ?a)
8483 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8484 (lambda(x) (downcase (org-sort-remove-invisible x))))
8485 comparefun (if (= dcst sorting-type)
8486 'string<
8487 (lambda (a b) (and (not (string< a b))
8488 (not (string= a b)))))))
8489 ((= dcst ?t)
8490 (setq extractfun
8491 (lambda (x)
8492 (if (or (string-match org-ts-regexp x)
8493 (string-match org-ts-regexp-both x))
8494 (org-float-time
8495 (org-time-string-to-time (match-string 0 x)))
8497 comparefun (if (= dcst sorting-type) '< '>)))
8498 (t (error "Invalid sorting type `%c'" sorting-type)))
8500 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8501 table)
8502 (lambda (a b) (funcall comparefun (car a) (car b))))))
8505 ;;; The orgstruct minor mode
8507 ;; Define a minor mode which can be used in other modes in order to
8508 ;; integrate the org-mode structure editing commands.
8510 ;; This is really a hack, because the org-mode structure commands use
8511 ;; keys which normally belong to the major mode. Here is how it
8512 ;; works: The minor mode defines all the keys necessary to operate the
8513 ;; structure commands, but wraps the commands into a function which
8514 ;; tests if the cursor is currently at a headline or a plain list
8515 ;; item. If that is the case, the structure command is used,
8516 ;; temporarily setting many Org-mode variables like regular
8517 ;; expressions for filling etc. However, when any of those keys is
8518 ;; used at a different location, function uses `key-binding' to look
8519 ;; up if the key has an associated command in another currently active
8520 ;; keymap (minor modes, major mode, global), and executes that
8521 ;; command. There might be problems if any of the keys is otherwise
8522 ;; used as a prefix key.
8524 (defcustom orgstruct-heading-prefix-regexp ""
8525 "Regexp that matches the custom prefix of Org headlines in
8526 orgstruct(++)-mode."
8527 :group 'org
8528 :type 'string)
8529 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8531 (defcustom orgstruct-setup-hook nil
8532 "Hook run after orgstruct-mode-map is filled."
8533 :group 'org
8534 :type 'hook)
8536 (defvar orgstruct-initialized nil)
8538 (defvar org-local-vars nil
8539 "List of local variables, for use by `orgstruct-mode'.")
8541 ;;;###autoload
8542 (define-minor-mode orgstruct-mode
8543 "Toggle the minor mode `orgstruct-mode'.
8544 This mode is for using Org-mode structure commands in other
8545 modes. The following keys behave as if Org-mode were active, if
8546 the cursor is on a headline, or on a plain list item (both as
8547 defined by Org-mode)."
8548 nil " OrgStruct" (make-sparse-keymap)
8549 (when orgstruct-mode
8550 (org-load-modules-maybe)
8551 (unless orgstruct-initialized
8552 (orgstruct-setup)
8553 (setq orgstruct-initialized t))))
8555 ;;;###autoload
8556 (defun turn-on-orgstruct ()
8557 "Unconditionally turn on `orgstruct-mode'."
8558 (orgstruct-mode 1))
8560 (defvar org-fb-vars nil)
8561 (make-variable-buffer-local 'org-fb-vars)
8562 (defun orgstruct++-mode (&optional arg)
8563 "Toggle `orgstruct-mode', the enhanced version of it.
8564 In addition to setting orgstruct-mode, this also exports all
8565 indentation and autofilling variables from org-mode into the
8566 buffer. It will also recognize item context in multiline items."
8567 (interactive "P")
8568 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8569 (if (< arg 1)
8570 (progn (orgstruct-mode -1)
8571 (mapc (lambda(v)
8572 (org-set-local (car v)
8573 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8574 org-fb-vars))
8575 (orgstruct-mode 1)
8576 (setq org-fb-vars nil)
8577 (let (var val)
8578 (mapc
8579 (lambda (x)
8580 (when (string-match
8581 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8582 (symbol-name (car x)))
8583 (setq var (car x) val (nth 1 x))
8584 (push (list var `(quote ,(eval var))) org-fb-vars)
8585 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8586 org-local-vars)
8587 (org-set-local 'orgstruct-is-++ t))))
8589 (defvar orgstruct-is-++ nil
8590 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8591 (make-variable-buffer-local 'orgstruct-is-++)
8593 ;;;###autoload
8594 (defun turn-on-orgstruct++ ()
8595 "Unconditionally turn on `orgstruct++-mode'."
8596 (orgstruct++-mode 1))
8598 (defun orgstruct-error ()
8599 "Error when there is no default binding for a structure key."
8600 (interactive)
8601 (error "This key has no function outside structure elements"))
8603 (defun orgstruct-setup ()
8604 "Setup orgstruct keymap."
8605 (dolist (f
8606 '("org-meta"
8607 "org-shiftmeta"
8608 org-shifttab
8609 org-backward-element
8610 org-backward-heading-same-level
8611 org-ctrl-c-ret
8612 org-cycle
8613 org-forward-heading-same-level
8614 org-insert-heading
8615 org-insert-heading-respect-content
8616 org-kill-note-or-show-branches
8617 org-mark-subtree
8618 org-narrow-to-subtree
8619 org-promote-subtree
8620 org-reveal
8621 org-show-subtree
8622 org-sort
8623 org-up-element
8624 outline-demote
8625 outline-next-visible-heading
8626 outline-previous-visible-heading
8627 outline-promote
8628 outline-up-heading
8629 show-children))
8630 (dolist (f (if (stringp f)
8631 (let ((flist))
8632 (dolist (postfix
8633 '("-return" "tab" "left" "right" "up" "down")
8634 flist)
8635 (let ((f (intern (concat f postfix))))
8636 (when (fboundp f)
8637 (push f flist)))))
8638 (list f)))
8639 (dolist (binding (nconc (where-is-internal f org-mode-map)
8640 (where-is-internal f outline-mode-map)))
8641 ;; TODO use local-function-key-map
8642 (dolist (rep '(("<tab>" . "TAB")
8643 ("<ret>" . "RET")
8644 ("<esc>" . "ESC")
8645 ("<del>" . "DEL")))
8646 (setq binding (read-kbd-macro (replace-regexp-in-string
8647 (regexp-quote (car rep))
8648 (cdr rep)
8649 (key-description binding)))))
8650 (let ((key (lookup-key orgstruct-mode-map binding)))
8651 (when (or (not key) (numberp key))
8652 (condition-case nil
8653 (org-defkey orgstruct-mode-map
8654 binding
8655 (orgstruct-make-binding f binding))
8656 (error nil)))))))
8657 (run-hooks 'orgstruct-setup-hook))
8659 (defun orgstruct-make-binding (fun key)
8660 "Create a function for binding in the structure minor mode.
8661 FUN is the command to call inside a table. KEY is the key that
8662 should be checked in for a command to execute outside of tables."
8663 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8664 (let ((nname name)
8665 (i 0))
8666 (while (fboundp (intern nname))
8667 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8668 (setq name (intern nname)))
8669 (eval
8670 `(defun ,name (arg)
8671 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8672 "Outside of structure, run the binding of `"
8673 (key-description key) "'.")
8674 (interactive "p")
8675 (unless
8676 (let* ((org-heading-regexp
8677 (concat "^"
8678 orgstruct-heading-prefix-regexp
8679 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8680 (org-outline-regexp
8681 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8682 (org-outline-regexp-bol
8683 (concat "^" org-outline-regexp))
8684 (outline-regexp org-outline-regexp)
8685 (outline-heading-end-regexp "\n")
8686 (outline-level 'outline-level)
8687 (outline-heading-alist))
8688 (when (org-context-p 'headline 'item
8689 ,(when (memq fun '(org-insert-heading))
8690 '(when orgstruct-is-++
8691 'item-body)))
8692 (org-run-like-in-org-mode ',fun)
8694 (let* ((orgstruct-mode)
8695 (binding (key-binding ,key)))
8696 (if (keymapp binding)
8697 (set-temporary-overlay-map binding)
8698 (call-interactively
8699 (or binding 'orgstruct-error)))))))
8700 name))
8702 (defun org-contextualize-keys (alist contexts)
8703 "Return valid elements in ALIST depending on CONTEXTS.
8705 `org-agenda-custom-commands' or `org-capture-templates' are the
8706 values used for ALIST, and `org-agenda-custom-commands-contexts'
8707 or `org-capture-templates-contexts' are the associated contexts
8708 definitions."
8709 (let ((contexts
8710 ;; normalize contexts
8711 (mapcar
8712 (lambda(c) (cond ((listp (cadr c))
8713 (list (car c) (car c) (cadr c)))
8714 ((string= "" (cadr c))
8715 (list (car c) (car c) (caddr c)))
8716 (t c))) contexts))
8717 (a alist) c r s)
8718 ;; loop over all commands or templates
8719 (while (setq c (pop a))
8720 (let (vrules repl)
8721 (cond
8722 ((not (assoc (car c) contexts))
8723 (push c r))
8724 ((and (assoc (car c) contexts)
8725 (setq vrules (org-contextualize-validate-key
8726 (car c) contexts)))
8727 (mapc (lambda (vr)
8728 (when (not (equal (car vr) (cadr vr)))
8729 (setq repl vr))) vrules)
8730 (if (not repl) (push c r)
8731 (push (cadr repl) s)
8732 (push
8733 (cons (car c)
8734 (cdr (or (assoc (cadr repl) alist)
8735 (error "Undefined key `%s' as contextual replacement for `%s'"
8736 (cadr repl) (car c)))))
8737 r))))))
8738 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8739 (delq
8741 (delete-dups
8742 (mapcar (lambda (x)
8743 (let ((tpl (car x)))
8744 (when (not (delq
8746 (mapcar (lambda(y)
8747 (equal y tpl)) s))) x)))
8748 (reverse r))))))
8750 (defun org-contextualize-validate-key (key contexts)
8751 "Check CONTEXTS for agenda or capture KEY."
8752 (let (r rr res)
8753 (while (setq r (pop contexts))
8754 (mapc
8755 (lambda (rr)
8756 (when
8757 (and (equal key (car r))
8758 (if (functionp rr) (funcall rr)
8759 (or (and (eq (car rr) 'in-file)
8760 (buffer-file-name)
8761 (string-match (cdr rr) (buffer-file-name)))
8762 (and (eq (car rr) 'in-mode)
8763 (string-match (cdr rr) (symbol-name major-mode)))
8764 (and (eq (car rr) 'in-buffer)
8765 (string-match (cdr rr) (buffer-name)))
8766 (when (and (eq (car rr) 'not-in-file)
8767 (buffer-file-name))
8768 (not (string-match (cdr rr) (buffer-file-name))))
8769 (when (eq (car rr) 'not-in-mode)
8770 (not (string-match (cdr rr) (symbol-name major-mode))))
8771 (when (eq (car rr) 'not-in-buffer)
8772 (not (string-match (cdr rr) (buffer-name)))))))
8773 (push r res)))
8774 (car (last r))))
8775 (delete-dups (delq nil res))))
8777 (defun org-context-p (&rest contexts)
8778 "Check if local context is any of CONTEXTS.
8779 Possible values in the list of contexts are `table', `headline', and `item'."
8780 (let ((pos (point)))
8781 (goto-char (point-at-bol))
8782 (prog1 (or (and (memq 'table contexts)
8783 (looking-at "[ \t]*|"))
8784 (and (memq 'headline contexts)
8785 (looking-at org-outline-regexp))
8786 (and (memq 'item contexts)
8787 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8788 (and (memq 'item-body contexts)
8789 (org-in-item-p)))
8790 (goto-char pos))))
8792 (defun org-get-local-variables ()
8793 "Return a list of all local variables in an Org mode buffer."
8794 (let (varlist)
8795 (with-current-buffer (get-buffer-create "*Org tmp*")
8796 (erase-buffer)
8797 (org-mode)
8798 (setq varlist (buffer-local-variables)))
8799 (kill-buffer "*Org tmp*")
8800 (delq nil
8801 (mapcar
8802 (lambda (x)
8803 (setq x
8804 (if (symbolp x)
8805 (list x)
8806 (list (car x) (cdr x))))
8807 (if (and (not (get (car x) 'org-state))
8808 (string-match
8809 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8810 (symbol-name (car x))))
8811 x nil))
8812 varlist))))
8814 (defun org-clone-local-variables (from-buffer &optional regexp)
8815 "Clone local variables from FROM-BUFFER.
8816 Optional argument REGEXP selects variables to clone."
8817 (mapc
8818 (lambda (pair)
8819 (and (symbolp (car pair))
8820 (or (null regexp)
8821 (string-match regexp (symbol-name (car pair))))
8822 (set (make-local-variable (car pair))
8823 (cdr pair))))
8824 (buffer-local-variables from-buffer)))
8826 ;;;###autoload
8827 (defun org-run-like-in-org-mode (cmd)
8828 "Run a command, pretending that the current buffer is in Org-mode.
8829 This will temporarily bind local variables that are typically bound in
8830 Org-mode to the values they have in Org-mode, and then interactively
8831 call CMD."
8832 (org-load-modules-maybe)
8833 (unless org-local-vars
8834 (setq org-local-vars (org-get-local-variables)))
8835 (let (binds)
8836 (dolist (var org-local-vars)
8837 (when (or (not (boundp (car var)))
8838 (eq (symbol-value (car var))
8839 (default-value (car var))))
8840 (push (list (car var) `(quote ,(cadr var))) binds)))
8841 (eval `(let ,binds
8842 (call-interactively (quote ,cmd))))))
8844 ;;;; Archiving
8846 (defun org-get-category (&optional pos force-refresh)
8847 "Get the category applying to position POS."
8848 (save-match-data
8849 (if force-refresh (org-refresh-category-properties))
8850 (let ((pos (or pos (point))))
8851 (or (get-text-property pos 'org-category)
8852 (progn (org-refresh-category-properties)
8853 (get-text-property pos 'org-category))))))
8855 (defun org-refresh-category-properties ()
8856 "Refresh category text properties in the buffer."
8857 (let ((case-fold-search t)
8858 (inhibit-read-only t)
8859 (def-cat (cond
8860 ((null org-category)
8861 (if buffer-file-name
8862 (file-name-sans-extension
8863 (file-name-nondirectory buffer-file-name))
8864 "???"))
8865 ((symbolp org-category) (symbol-name org-category))
8866 (t org-category)))
8867 beg end cat pos optionp)
8868 (org-unmodified
8869 (save-excursion
8870 (save-restriction
8871 (widen)
8872 (goto-char (point-min))
8873 (put-text-property (point) (point-max) 'org-category def-cat)
8874 (while (re-search-forward
8875 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8876 (setq pos (match-end 0)
8877 optionp (equal (char-after (match-beginning 0)) ?#)
8878 cat (org-trim (match-string 2)))
8879 (if optionp
8880 (setq beg (point-at-bol) end (point-max))
8881 (org-back-to-heading t)
8882 (setq beg (point) end (org-end-of-subtree t t)))
8883 (put-text-property beg end 'org-category cat)
8884 (put-text-property beg end 'org-category-position beg)
8885 (goto-char pos)))))))
8887 (defun org-refresh-properties (dprop tprop)
8888 "Refresh buffer text properties.
8889 DPROP is the drawer property and TPROP is the corresponding text
8890 property to set."
8891 (let ((case-fold-search t)
8892 (inhibit-read-only t) p)
8893 (org-unmodified
8894 (save-excursion
8895 (save-restriction
8896 (widen)
8897 (goto-char (point-min))
8898 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8899 (setq p (org-match-string-no-properties 1))
8900 (save-excursion
8901 (org-back-to-heading t)
8902 (put-text-property
8903 (point-at-bol) (point-at-eol) tprop p))))))))
8906 ;;;; Link Stuff
8908 ;;; Link abbreviations
8910 (defun org-link-expand-abbrev (link)
8911 "Apply replacements as defined in `org-link-abbrev-alist'."
8912 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8913 (let* ((key (match-string 1 link))
8914 (as (or (assoc key org-link-abbrev-alist-local)
8915 (assoc key org-link-abbrev-alist)))
8916 (tag (and (match-end 2) (match-string 3 link)))
8917 rpl)
8918 (if (not as)
8919 link
8920 (setq rpl (cdr as))
8921 (cond
8922 ((symbolp rpl) (funcall rpl tag))
8923 ((string-match "%(\\([^)]+\\))" rpl)
8924 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8925 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8926 ((string-match "%h" rpl)
8927 (replace-match (url-hexify-string (or tag "")) t t rpl))
8928 (t (concat rpl tag)))))
8929 link))
8931 ;;; Storing and inserting links
8933 (defvar org-insert-link-history nil
8934 "Minibuffer history for links inserted with `org-insert-link'.")
8936 (defvar org-stored-links nil
8937 "Contains the links stored with `org-store-link'.")
8939 (defvar org-store-link-plist nil
8940 "Plist with info about the most recently link created with `org-store-link'.")
8942 (defvar org-link-protocols nil
8943 "Link protocols added to Org-mode using `org-add-link-type'.")
8945 (defvar org-store-link-functions nil
8946 "List of functions that are called to create and store a link.
8947 Each function will be called in turn until one returns a non-nil
8948 value. Each function should check if it is responsible for creating
8949 this link (for example by looking at the major mode).
8950 If not, it must exit and return nil.
8951 If yes, it should return a non-nil value after a calling
8952 `org-store-link-props' with a list of properties and values.
8953 Special properties are:
8955 :type The link prefix, like \"http\". This must be given.
8956 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8957 This is obligatory as well.
8958 :description Optional default description for the second pair
8959 of brackets in an Org-mode link. The user can still change
8960 this when inserting this link into an Org-mode buffer.
8962 In addition to these, any additional properties can be specified
8963 and then used in capture templates.")
8965 (defun org-add-link-type (type &optional follow export)
8966 "Add TYPE to the list of `org-link-types'.
8967 Re-compute all regular expressions depending on `org-link-types'
8969 FOLLOW and EXPORT are two functions.
8971 FOLLOW should take the link path as the single argument and do whatever
8972 is necessary to follow the link, for example find a file or display
8973 a mail message.
8975 EXPORT should format the link path for export to one of the export formats.
8976 It should be a function accepting three arguments:
8978 path the path of the link, the text after the prefix (like \"http:\")
8979 desc the description of the link, if any, or a description added by
8980 org-export-normalize-links if there is none
8981 format the export format, a symbol like `html' or `latex' or `ascii'..
8983 The function may use the FORMAT information to return different values
8984 depending on the format. The return value will be put literally into
8985 the exported file. If the return value is nil, this means Org should
8986 do what it normally does with links which do not have EXPORT defined.
8988 Org-mode has a built-in default for exporting links. If you are happy with
8989 this default, there is no need to define an export function for the link
8990 type. For a simple example of an export function, see `org-bbdb.el'."
8991 (add-to-list 'org-link-types type t)
8992 (org-make-link-regexps)
8993 (if (assoc type org-link-protocols)
8994 (setcdr (assoc type org-link-protocols) (list follow export))
8995 (push (list type follow export) org-link-protocols)))
8997 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8998 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9000 ;;;###autoload
9001 (defun org-store-link (arg)
9002 "\\<org-mode-map>Store an org-link to the current location.
9003 This link is added to `org-stored-links' and can later be inserted
9004 into an org-buffer with \\[org-insert-link].
9006 For some link types, a prefix arg is interpreted.
9007 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9008 For file links, arg negates `org-context-in-file-links'.
9010 A double prefix arg force skipping storing functions that are not
9011 part of Org's core."
9012 (interactive "P")
9013 (org-load-modules-maybe)
9014 (setq org-store-link-plist nil) ; reset
9015 (org-with-limited-levels
9016 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9017 (cond
9018 ((and (not (equal arg '(16)))
9019 (setq sfuns
9020 (delq
9021 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9022 org-store-link-functions))
9023 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9024 (or (and (cdr sfuns)
9025 (funcall (intern
9026 (completing-read "Which function for creating the link? "
9027 sfunsn t (car sfunsn)))))
9028 (funcall (caar sfuns)))
9029 (setq link (plist-get org-store-link-plist :link)
9030 desc (or (plist-get org-store-link-plist :description) link))))
9031 ((org-src-edit-buffer-p)
9032 (let (label gc)
9033 (while (or (not label)
9034 (save-excursion
9035 (save-restriction
9036 (widen)
9037 (goto-char (point-min))
9038 (re-search-forward
9039 (regexp-quote (format org-coderef-label-format label))
9040 nil t))))
9041 (when label (message "Label exists already") (sit-for 2))
9042 (setq label (read-string "Code line label: " label)))
9043 (end-of-line 1)
9044 (setq link (format org-coderef-label-format label))
9045 (setq gc (- 79 (length link)))
9046 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9047 (insert link)
9048 (setq link (concat "(" label ")") desc nil)))
9050 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9051 ;; We are in the agenda, link to referenced location
9052 (let ((m (or (get-text-property (point) 'org-hd-marker)
9053 (get-text-property (point) 'org-marker))))
9054 (when m
9055 (org-with-point-at m
9056 (setq agenda-link
9057 (if (org-called-interactively-p 'any)
9058 (call-interactively 'org-store-link)
9059 (org-store-link nil)))))))
9061 ((eq major-mode 'calendar-mode)
9062 (let ((cd (calendar-cursor-to-date)))
9063 (setq link
9064 (format-time-string
9065 (car org-time-stamp-formats)
9066 (apply 'encode-time
9067 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9068 nil nil nil))))
9069 (org-store-link-props :type "calendar" :date cd)))
9071 ((eq major-mode 'help-mode)
9072 (setq link (concat "help:" (save-excursion
9073 (goto-char (point-min))
9074 (looking-at "^[^ ]+")
9075 (match-string 0))))
9076 (org-store-link-props :type "help"))
9078 ((eq major-mode 'w3-mode)
9079 (setq cpltxt (if (and (buffer-name)
9080 (not (string-match "Untitled" (buffer-name))))
9081 (buffer-name)
9082 (url-view-url t))
9083 link (url-view-url t))
9084 (org-store-link-props :type "w3" :url (url-view-url t)))
9086 ((setq search (run-hook-with-args-until-success
9087 'org-create-file-search-functions))
9088 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9089 "::" search))
9090 (setq cpltxt (or description link)))
9092 ((eq major-mode 'image-mode)
9093 (setq cpltxt (concat "file:"
9094 (abbreviate-file-name buffer-file-name))
9095 link cpltxt)
9096 (org-store-link-props :type "image" :file buffer-file-name))
9098 ((eq major-mode 'dired-mode)
9099 ;; link to the file in the current line
9100 (let ((file (dired-get-filename nil t)))
9101 (setq file (if file
9102 (abbreviate-file-name
9103 (expand-file-name (dired-get-filename nil t)))
9104 ;; otherwise, no file so use current directory.
9105 default-directory))
9106 (setq cpltxt (concat "file:" file)
9107 link cpltxt)))
9109 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9110 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9111 (cond
9112 ((org-in-regexp "<<\\(.*?\\)>>")
9113 (setq cpltxt
9114 (concat "file:"
9115 (abbreviate-file-name
9116 (buffer-file-name (buffer-base-buffer)))
9117 "::" (match-string 1))
9118 link cpltxt))
9119 ((and (featurep 'org-id)
9120 (or (eq org-id-link-to-org-use-id t)
9121 (and (org-called-interactively-p 'any)
9122 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9123 (and (eq org-id-link-to-org-use-id
9124 'create-if-interactive-and-no-custom-id)
9125 (not custom-id))))
9126 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9127 ;; We can make a link using the ID.
9128 (setq link (condition-case nil
9129 (prog1 (org-id-store-link)
9130 (setq desc (plist-get org-store-link-plist :description)))
9131 (error
9132 ;; probably before first headline, link to file only
9133 (concat "file:"
9134 (abbreviate-file-name
9135 (buffer-file-name (buffer-base-buffer))))))))
9137 ;; Just link to current headline
9138 (setq cpltxt (concat "file:"
9139 (abbreviate-file-name
9140 (buffer-file-name (buffer-base-buffer)))))
9141 ;; Add a context search string
9142 (when (org-xor org-context-in-file-links arg)
9143 (let* ((ee (org-element-at-point))
9144 (et (org-element-type ee))
9145 (ev (plist-get (cadr ee) :value)))
9146 (setq txt (cond
9147 ((org-at-heading-p) nil)
9148 ((eq et 'keyword) ev)
9149 ((org-region-active-p)
9150 (buffer-substring (region-beginning) (region-end)))))
9151 (when (or (null txt) (string-match "\\S-" txt))
9152 (setq cpltxt
9153 (concat cpltxt "::"
9154 (condition-case nil
9155 (org-make-org-heading-search-string txt)
9156 (error "")))
9157 desc (or (and (eq et 'keyword) ev)
9158 (nth 4 (ignore-errors (org-heading-components)))
9159 "NONE")))))
9160 (if (string-match "::\\'" cpltxt)
9161 (setq cpltxt (substring cpltxt 0 -2)))
9162 (setq link cpltxt))))
9164 ((buffer-file-name (buffer-base-buffer))
9165 ;; Just link to this file here.
9166 (setq cpltxt (concat "file:"
9167 (abbreviate-file-name
9168 (buffer-file-name (buffer-base-buffer)))))
9169 ;; Add a context string
9170 (when (org-xor org-context-in-file-links arg)
9171 (setq txt (if (org-region-active-p)
9172 (buffer-substring (region-beginning) (region-end))
9173 (buffer-substring (point-at-bol) (point-at-eol))))
9174 ;; Only use search option if there is some text.
9175 (when (string-match "\\S-" txt)
9176 (setq cpltxt
9177 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9178 desc "NONE")))
9179 (setq link cpltxt))
9181 ((org-called-interactively-p 'interactive)
9182 (user-error "No method for storing a link from this buffer"))
9184 (t (setq link nil)))
9186 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9187 (setq link (or link cpltxt)
9188 desc (or desc cpltxt))
9189 (cond ((equal desc "NONE") (setq desc nil))
9190 ((string-match org-bracket-link-regexp desc)
9191 (setq desc (replace-regexp-in-string
9192 org-bracket-link-regexp
9193 (concat "\\3" (if (equal (length (match-string 0 desc))
9194 (length desc)) "*" "")) desc))))
9196 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9197 (progn
9198 (setq org-stored-links
9199 (cons (list link desc) org-stored-links))
9200 (message "Stored: %s" (or desc link))
9201 (when custom-id
9202 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9203 "::#" custom-id))
9204 (setq org-stored-links
9205 (cons (list link desc) org-stored-links))))
9206 (or agenda-link (and link (org-make-link-string link desc)))))))
9208 (defun org-store-link-props (&rest plist)
9209 "Store link properties, extract names and addresses."
9210 (let (x adr)
9211 (when (setq x (plist-get plist :from))
9212 (setq adr (mail-extract-address-components x))
9213 (setq plist (plist-put plist :fromname (car adr)))
9214 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9215 (when (setq x (plist-get plist :to))
9216 (setq adr (mail-extract-address-components x))
9217 (setq plist (plist-put plist :toname (car adr)))
9218 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9219 (let ((from (plist-get plist :from))
9220 (to (plist-get plist :to)))
9221 (when (and from to org-from-is-user-regexp)
9222 (setq plist
9223 (plist-put plist :fromto
9224 (if (string-match org-from-is-user-regexp from)
9225 (concat "to %t")
9226 (concat "from %f"))))))
9227 (setq org-store-link-plist plist))
9229 (defun org-add-link-props (&rest plist)
9230 "Add these properties to the link property list."
9231 (let (key value)
9232 (while plist
9233 (setq key (pop plist) value (pop plist))
9234 (setq org-store-link-plist
9235 (plist-put org-store-link-plist key value)))))
9237 (defun org-email-link-description (&optional fmt)
9238 "Return the description part of an email link.
9239 This takes information from `org-store-link-plist' and formats it
9240 according to FMT (default from `org-email-link-description-format')."
9241 (setq fmt (or fmt org-email-link-description-format))
9242 (let* ((p org-store-link-plist)
9243 (to (plist-get p :toaddress))
9244 (from (plist-get p :fromaddress))
9245 (table
9246 (list
9247 (cons "%c" (plist-get p :fromto))
9248 (cons "%F" (plist-get p :from))
9249 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9250 (cons "%T" (plist-get p :to))
9251 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9252 (cons "%s" (plist-get p :subject))
9253 (cons "%d" (plist-get p :date))
9254 (cons "%m" (plist-get p :message-id)))))
9255 (when (string-match "%c" fmt)
9256 ;; Check if the user wrote this message
9257 (if (and org-from-is-user-regexp from to
9258 (save-match-data (string-match org-from-is-user-regexp from)))
9259 (setq fmt (replace-match "to %t" t t fmt))
9260 (setq fmt (replace-match "from %f" t t fmt))))
9261 (org-replace-escapes fmt table)))
9263 (defun org-make-org-heading-search-string (&optional string)
9264 "Make search string for the current headline or STRING."
9265 (let ((s (or string
9266 (and (derived-mode-p 'org-mode)
9267 (save-excursion
9268 (org-back-to-heading t)
9269 (plist-get (cadr (org-element-at-point))
9270 :raw-value)))))
9271 (lines org-context-in-file-links))
9272 (or string (setq s (concat "*" s))) ; Add * for headlines
9273 (when (and string (integerp lines) (> lines 0))
9274 (let ((slines (org-split-string s "\n")))
9275 (when (< lines (length slines))
9276 (setq s (mapconcat
9277 'identity
9278 (reverse (nthcdr (- (length slines) lines)
9279 (reverse slines))) "\n")))))
9280 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9282 (defun org-make-link-string (link &optional description)
9283 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9284 (unless (string-match "\\S-" link)
9285 (error "Empty link"))
9286 (when (and description
9287 (stringp description)
9288 (not (string-match "\\S-" description)))
9289 (setq description nil))
9290 (when (stringp description)
9291 ;; Remove brackets from the description, they are fatal.
9292 (while (string-match "\\[" description)
9293 (setq description (replace-match "{" t t description)))
9294 (while (string-match "\\]" description)
9295 (setq description (replace-match "}" t t description))))
9296 (when (equal link description)
9297 ;; No description needed, it is identical
9298 (setq description nil))
9299 (when (and (not description)
9300 (not (string-match (org-image-file-name-regexp) link))
9301 (not (equal link (org-link-escape link))))
9302 (setq description (org-extract-attributes link)))
9303 (setq link
9304 (cond ((string-match (org-image-file-name-regexp) link) link)
9305 ((string-match org-link-types-re link)
9306 (concat (match-string 1 link)
9307 (org-link-escape (substring link (match-end 1)))))
9308 (t (org-link-escape link))))
9309 (concat "[[" link "]"
9310 (if description (concat "[" description "]") "")
9311 "]"))
9313 (defconst org-link-escape-chars
9314 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9315 "List of characters that should be escaped in link.
9316 This is the list that is used for internal purposes.")
9318 (defconst org-link-escape-chars-browser
9319 '(?\ )
9320 "List of escapes for characters that are problematic in links.
9321 This is the list that is used before handing over to the browser.")
9323 (defun org-link-escape (text &optional table merge)
9324 "Return percent escaped representation of TEXT.
9325 TEXT is a string with the text to escape.
9326 Optional argument TABLE is a list with characters that should be
9327 escaped. When nil, `org-link-escape-chars' is used.
9328 If optional argument MERGE is set, merge TABLE into
9329 `org-link-escape-chars'."
9330 (cond
9331 ((and table merge)
9332 (mapc (lambda (defchr)
9333 (unless (member defchr table)
9334 (setq table (cons defchr table)))) org-link-escape-chars))
9335 ((null table)
9336 (setq table org-link-escape-chars)))
9337 (mapconcat
9338 (lambda (char)
9339 (if (or (member char table)
9340 (and (or (< char 32) (= char 37) (> char 126))
9341 org-url-hexify-p))
9342 (mapconcat (lambda (sequence-element)
9343 (format "%%%.2X" sequence-element))
9344 (or (encode-coding-char char 'utf-8)
9345 (error "Unable to percent escape character: %s"
9346 (char-to-string char))) "")
9347 (char-to-string char))) text ""))
9349 (defun org-link-unescape (str)
9350 "Unhex hexified Unicode strings as returned from the JavaScript function
9351 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9352 (unless (and (null str) (string= "" str))
9353 (let ((pos 0) (case-fold-search t) unhexed)
9354 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9355 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9356 (setq str (replace-match unhexed t t str))
9357 (setq pos (+ pos (length unhexed))))))
9358 str)
9360 (defun org-link-unescape-compound (hex)
9361 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9362 Note: this function also decodes single byte encodings like
9363 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9364 (save-match-data
9365 (let* ((bytes (cdr (split-string hex "%")))
9366 (ret "")
9367 (eat 0)
9368 (sum 0))
9369 (while bytes
9370 (let* ((val (string-to-number (pop bytes) 16))
9371 (shift-xor
9372 (if (= 0 eat)
9373 (cond
9374 ((>= val 252) (cons 6 252))
9375 ((>= val 248) (cons 5 248))
9376 ((>= val 240) (cons 4 240))
9377 ((>= val 224) (cons 3 224))
9378 ((>= val 192) (cons 2 192))
9379 (t (cons 0 0)))
9380 (cons 6 128))))
9381 (if (>= val 192) (setq eat (car shift-xor)))
9382 (setq val (logxor val (cdr shift-xor)))
9383 (setq sum (+ (lsh sum (car shift-xor)) val))
9384 (if (> eat 0) (setq eat (- eat 1)))
9385 (cond
9386 ((= 0 eat) ;multi byte
9387 (setq ret (concat ret (org-char-to-string sum)))
9388 (setq sum 0))
9389 ((not bytes) ; single byte(s)
9390 (setq ret (org-link-unescape-single-byte-sequence hex))))
9391 )) ;; end (while bytes
9392 ret )))
9394 (defun org-link-unescape-single-byte-sequence (hex)
9395 "Unhexify hex-encoded single byte character sequences."
9396 (mapconcat (lambda (byte)
9397 (char-to-string (string-to-number byte 16)))
9398 (cdr (split-string hex "%")) ""))
9400 (defun org-xor (a b)
9401 "Exclusive or."
9402 (if a (not b) b))
9404 (defun org-fixup-message-id-for-http (s)
9405 "Replace special characters in a message id, so it can be used in an http query."
9406 (when (string-match "%" s)
9407 (setq s (mapconcat (lambda (c)
9408 (if (eq c ?%)
9409 "%25"
9410 (char-to-string c)))
9411 s "")))
9412 (while (string-match "<" s)
9413 (setq s (replace-match "%3C" t t s)))
9414 (while (string-match ">" s)
9415 (setq s (replace-match "%3E" t t s)))
9416 (while (string-match "@" s)
9417 (setq s (replace-match "%40" t t s)))
9420 (defun org-link-prettify (link)
9421 "Return a human-readable representation of LINK.
9422 The car of LINK must be a raw link the cdr of LINK must be either
9423 a link description or nil."
9424 (let ((desc (or (cadr link) "<no description>")))
9425 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9426 "<" (car link) ">")))
9428 ;;;###autoload
9429 (defun org-insert-link-global ()
9430 "Insert a link like Org-mode does.
9431 This command can be called in any mode to insert a link in Org-mode syntax."
9432 (interactive)
9433 (org-load-modules-maybe)
9434 (org-run-like-in-org-mode 'org-insert-link))
9436 (defun org-insert-all-links (&optional keep)
9437 "Insert all links in `org-stored-links'."
9438 (interactive "P")
9439 (let ((links (copy-sequence org-stored-links)) l)
9440 (while (setq l (if keep (pop links) (pop org-stored-links)))
9441 (insert "- ")
9442 (org-insert-link nil (car l) (cadr l))
9443 (insert "\n"))))
9445 (defun org-link-fontify-links-to-this-file ()
9446 "Fontify links to the current file in `org-stored-links'."
9447 (let ((f (buffer-file-name)) a b)
9448 (setq a (mapcar (lambda(l)
9449 (let ((ll (car l)))
9450 (when (and (string-match "^file:\\(.+\\)::" ll)
9451 (equal f (expand-file-name (match-string 1 ll))))
9452 ll)))
9453 org-stored-links))
9454 (when (featurep 'org-id)
9455 (setq b (mapcar (lambda(l)
9456 (let ((ll (car l)))
9457 (when (and (string-match "^id:\\(.+\\)$" ll)
9458 (equal f (expand-file-name
9459 (or (org-id-find-id-file
9460 (match-string 1 ll)) ""))))
9461 ll)))
9462 org-stored-links)))
9463 (mapcar (lambda(l)
9464 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9465 (delq nil (append a b)))))
9467 (defvar org-link-links-in-this-file nil)
9468 (defun org-insert-link (&optional complete-file link-location default-description)
9469 "Insert a link. At the prompt, enter the link.
9471 Completion can be used to insert any of the link protocol prefixes like
9472 http or ftp in use.
9474 The history can be used to select a link previously stored with
9475 `org-store-link'. When the empty string is entered (i.e. if you just
9476 press RET at the prompt), the link defaults to the most recently
9477 stored link. As SPC triggers completion in the minibuffer, you need to
9478 use M-SPC or C-q SPC to force the insertion of a space character.
9480 You will also be prompted for a description, and if one is given, it will
9481 be displayed in the buffer instead of the link.
9483 If there is already a link at point, this command will allow you to edit link
9484 and description parts.
9486 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9487 be selected using completion. The path to the file will be relative to the
9488 current directory if the file is in the current directory or a subdirectory.
9489 Otherwise, the link will be the absolute path as completed in the minibuffer
9490 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9491 option `org-link-file-path-type'.
9493 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9494 the current directory or below.
9496 With three \\[universal-argument] prefixes, negate the meaning of
9497 `org-keep-stored-link-after-insertion'.
9499 If `org-make-link-description-function' is non-nil, this function will be
9500 called with the link target, and the result will be the default
9501 link description.
9503 If the LINK-LOCATION parameter is non-nil, this value will be
9504 used as the link location instead of reading one interactively.
9506 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9507 be used as the default description."
9508 (interactive "P")
9509 (let* ((wcf (current-window-configuration))
9510 (origbuf (current-buffer))
9511 (region (if (org-region-active-p)
9512 (buffer-substring (region-beginning) (region-end))))
9513 (remove (and region (list (region-beginning) (region-end))))
9514 (desc region)
9515 tmphist ; byte-compile incorrectly complains about this
9516 (link link-location)
9517 (abbrevs org-link-abbrev-alist-local)
9518 entry file all-prefixes auto-desc)
9519 (cond
9520 (link-location) ; specified by arg, just use it.
9521 ((org-in-regexp org-bracket-link-regexp 1)
9522 ;; We do have a link at point, and we are going to edit it.
9523 (setq remove (list (match-beginning 0) (match-end 0)))
9524 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9525 (setq link (read-string "Link: "
9526 (org-link-unescape
9527 (org-match-string-no-properties 1)))))
9528 ((or (org-in-regexp org-angle-link-re)
9529 (org-in-regexp org-plain-link-re))
9530 ;; Convert to bracket link
9531 (setq remove (list (match-beginning 0) (match-end 0))
9532 link (read-string "Link: "
9533 (org-remove-angle-brackets (match-string 0)))))
9534 ((member complete-file '((4) (16)))
9535 ;; Completing read for file names.
9536 (setq link (org-file-complete-link complete-file)))
9538 ;; Read link, with completion for stored links.
9539 (org-link-fontify-links-to-this-file)
9540 (org-switch-to-buffer-other-window "*Org Links*")
9541 (with-current-buffer "*Org Links*"
9542 (erase-buffer)
9543 (insert "Insert a link.
9544 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9545 (when org-stored-links
9546 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9547 (insert (mapconcat 'org-link-prettify
9548 (reverse org-stored-links) "\n")))
9549 (goto-char (point-min)))
9550 (let ((cw (selected-window)))
9551 (select-window (get-buffer-window "*Org Links*" 'visible))
9552 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9553 (unless (pos-visible-in-window-p (point-max))
9554 (org-fit-window-to-buffer))
9555 (and (window-live-p cw) (select-window cw)))
9556 ;; Fake a link history, containing the stored links.
9557 (setq tmphist (append (mapcar 'car org-stored-links)
9558 org-insert-link-history))
9559 (setq all-prefixes (append (mapcar 'car abbrevs)
9560 (mapcar 'car org-link-abbrev-alist)
9561 org-link-types))
9562 (unwind-protect
9563 (progn
9564 (setq link
9565 (org-completing-read
9566 "Link: "
9567 (append
9568 (mapcar (lambda (x) (concat x ":"))
9569 all-prefixes)
9570 (mapcar 'car org-stored-links))
9571 nil nil nil
9572 'tmphist
9573 (caar org-stored-links)))
9574 (if (not (string-match "\\S-" link))
9575 (error "No link selected"))
9576 (mapc (lambda(l)
9577 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9578 org-stored-links)
9579 (if (or (member link all-prefixes)
9580 (and (equal ":" (substring link -1))
9581 (member (substring link 0 -1) all-prefixes)
9582 (setq link (substring link 0 -1))))
9583 (setq link (with-current-buffer origbuf
9584 (org-link-try-special-completion link)))))
9585 (set-window-configuration wcf)
9586 (kill-buffer "*Org Links*"))
9587 (setq entry (assoc link org-stored-links))
9588 (or entry (push link org-insert-link-history))
9589 (setq desc (or desc (nth 1 entry)))))
9591 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9592 (not org-keep-stored-link-after-insertion))
9593 (setq org-stored-links (delq (assoc link org-stored-links)
9594 org-stored-links)))
9596 (if (string-match org-plain-link-re link)
9597 ;; URL-like link, normalize the use of angular brackets.
9598 (setq link (org-remove-angle-brackets link)))
9600 ;; Check if we are linking to the current file with a search
9601 ;; option If yes, simplify the link by using only the search
9602 ;; option.
9603 (when (and buffer-file-name
9604 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9605 (let* ((path (match-string 1 link))
9606 (case-fold-search nil)
9607 (search (match-string 2 link)))
9608 (save-match-data
9609 (if (equal (file-truename buffer-file-name) (file-truename path))
9610 ;; We are linking to this same file, with a search option
9611 (setq link search)))))
9613 ;; Check if we can/should use a relative path. If yes, simplify the link
9614 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9615 (let* ((type (match-string 1 link))
9616 (path (match-string 2 link))
9617 (origpath path)
9618 (case-fold-search nil))
9619 (cond
9620 ((or (eq org-link-file-path-type 'absolute)
9621 (equal complete-file '(16)))
9622 (setq path (abbreviate-file-name (expand-file-name path))))
9623 ((eq org-link-file-path-type 'noabbrev)
9624 (setq path (expand-file-name path)))
9625 ((eq org-link-file-path-type 'relative)
9626 (setq path (file-relative-name path)))
9628 (save-match-data
9629 (if (string-match (concat "^" (regexp-quote
9630 (expand-file-name
9631 (file-name-as-directory
9632 default-directory))))
9633 (expand-file-name path))
9634 ;; We are linking a file with relative path name.
9635 (setq path (substring (expand-file-name path)
9636 (match-end 0)))
9637 (setq path (abbreviate-file-name (expand-file-name path)))))))
9638 (setq link (concat type path))
9639 (if (equal desc origpath)
9640 (setq desc path))))
9642 (if org-make-link-description-function
9643 (setq desc
9644 (or (condition-case nil
9645 (funcall org-make-link-description-function link desc)
9646 (error (progn (message "Can't get link description from `%s'"
9647 (symbol-name org-make-link-description-function))
9648 (sit-for 2) nil)))
9649 (read-string "Description: " default-description)))
9650 (if default-description (setq desc default-description)
9651 (setq desc (or (and auto-desc desc)
9652 (read-string "Description: " desc)))))
9654 (unless (string-match "\\S-" desc) (setq desc nil))
9655 (if remove (apply 'delete-region remove))
9656 (insert (org-make-link-string link desc))))
9658 (defun org-link-try-special-completion (type)
9659 "If there is completion support for link type TYPE, offer it."
9660 (let ((fun (intern (concat "org-" type "-complete-link"))))
9661 (if (functionp fun)
9662 (funcall fun)
9663 (read-string "Link (no completion support): " (concat type ":")))))
9665 (defun org-file-complete-link (&optional arg)
9666 "Create a file link using completion."
9667 (let (file link)
9668 (setq file (org-iread-file-name "File: "))
9669 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9670 (pwd1 (file-name-as-directory (abbreviate-file-name
9671 (expand-file-name ".")))))
9672 (cond
9673 ((equal arg '(16))
9674 (setq link (concat
9675 "file:"
9676 (abbreviate-file-name (expand-file-name file)))))
9677 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9678 (setq link (concat "file:" (match-string 1 file))))
9679 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9680 (expand-file-name file))
9681 (setq link (concat
9682 "file:" (match-string 1 (expand-file-name file)))))
9683 (t (setq link (concat "file:" file)))))
9684 link))
9686 (defun org-iread-file-name (&rest args)
9687 "Read-file-name using `ido-mode' speedup if available.
9688 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9689 See `read-file-name' for a description of parameters."
9690 (org-without-partial-completion
9691 (if (and org-completion-use-ido
9692 (fboundp 'ido-read-file-name)
9693 (boundp 'ido-mode) ido-mode
9694 (listp (second args)))
9695 (let ((ido-enter-matching-directory nil))
9696 (apply 'ido-read-file-name args))
9697 (apply 'read-file-name args))))
9699 (defun org-completing-read (&rest args)
9700 "Completing-read with SPACE being a normal character."
9701 (let ((enable-recursive-minibuffers t)
9702 (minibuffer-local-completion-map
9703 (copy-keymap minibuffer-local-completion-map)))
9704 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9705 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9706 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9707 (apply 'org-icompleting-read args)))
9709 (defun org-completing-read-no-i (&rest args)
9710 (let (org-completion-use-ido org-completion-use-iswitchb)
9711 (apply 'org-completing-read args)))
9713 (defun org-iswitchb-completing-read (prompt choices &rest args)
9714 "Use iswitch as a completing-read replacement to choose from choices.
9715 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9716 from."
9717 (let* ((iswitchb-use-virtual-buffers nil)
9718 (iswitchb-make-buflist-hook
9719 (lambda ()
9720 (setq iswitchb-temp-buflist choices))))
9721 (iswitchb-read-buffer prompt)))
9723 (defun org-icompleting-read (&rest args)
9724 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9725 (org-without-partial-completion
9726 (if (and org-completion-use-ido
9727 (fboundp 'ido-completing-read)
9728 (boundp 'ido-mode) ido-mode
9729 (listp (second args)))
9730 (let ((ido-enter-matching-directory nil))
9731 (apply 'ido-completing-read (concat (car args))
9732 (if (consp (car (nth 1 args)))
9733 (mapcar 'car (nth 1 args))
9734 (nth 1 args))
9735 (cddr args)))
9736 (if (and org-completion-use-iswitchb
9737 (boundp 'iswitchb-mode) iswitchb-mode
9738 (listp (second args)))
9739 (apply 'org-iswitchb-completing-read (concat (car args))
9740 (if (consp (car (nth 1 args)))
9741 (mapcar 'car (nth 1 args))
9742 (nth 1 args))
9743 (cddr args))
9744 (apply 'completing-read args)))))
9746 (defun org-extract-attributes (s)
9747 "Extract the attributes cookie from a string and set as text property."
9748 (let (a attr (start 0) key value)
9749 (save-match-data
9750 (when (string-match "{{\\([^}]+\\)}}$" s)
9751 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9752 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9753 (setq key (match-string 1 a) value (match-string 2 a)
9754 start (match-end 0)
9755 attr (plist-put attr (intern key) value))))
9756 (org-add-props s nil 'org-attr attr))
9759 (defun org-extract-attributes-from-string (tag)
9760 (let (key value attr)
9761 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9762 (setq key (match-string 1 tag) value (match-string 2 tag)
9763 tag (replace-match "" t t tag)
9764 attr (plist-put attr (intern key) value)))
9765 (cons tag attr)))
9767 (defun org-attributes-to-string (plist)
9768 "Format a property list into an HTML attribute list."
9769 (let ((s "") key value)
9770 (while plist
9771 (setq key (pop plist) value (pop plist))
9772 (and value
9773 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9776 ;;; Opening/following a link
9778 (defvar org-link-search-failed nil)
9780 (defvar org-open-link-functions nil
9781 "Hook for functions finding a plain text link.
9782 These functions must take a single argument, the link content.
9783 They will be called for links that look like [[link text][description]]
9784 when LINK TEXT does not have a protocol like \"http:\" and does not look
9785 like a filename (e.g. \"./blue.png\").
9787 These functions will be called *before* Org attempts to resolve the
9788 link by doing text searches in the current buffer - so if you want a
9789 link \"[[target]]\" to still find \"<<target>>\", your function should
9790 handle this as a special case.
9792 When the function does handle the link, it must return a non-nil value.
9793 If it decides that it is not responsible for this link, it must return
9794 nil to indicate that that Org-mode can continue with other options
9795 like exact and fuzzy text search.")
9797 (defun org-next-link ()
9798 "Move forward to the next link.
9799 If the link is in hidden text, expose it."
9800 (interactive)
9801 (when (and org-link-search-failed (eq this-command last-command))
9802 (goto-char (point-min))
9803 (message "Link search wrapped back to beginning of buffer"))
9804 (setq org-link-search-failed nil)
9805 (let* ((pos (point))
9806 (ct (org-context))
9807 (a (assoc :link ct)))
9808 (if a (goto-char (nth 2 a)))
9809 (if (re-search-forward org-any-link-re nil t)
9810 (progn
9811 (goto-char (match-beginning 0))
9812 (if (outline-invisible-p) (org-show-context)))
9813 (goto-char pos)
9814 (setq org-link-search-failed t)
9815 (error "No further link found"))))
9817 (defun org-previous-link ()
9818 "Move backward to the previous link.
9819 If the link is in hidden text, expose it."
9820 (interactive)
9821 (when (and org-link-search-failed (eq this-command last-command))
9822 (goto-char (point-max))
9823 (message "Link search wrapped back to end of buffer"))
9824 (setq org-link-search-failed nil)
9825 (let* ((pos (point))
9826 (ct (org-context))
9827 (a (assoc :link ct)))
9828 (if a (goto-char (nth 1 a)))
9829 (if (re-search-backward org-any-link-re nil t)
9830 (progn
9831 (goto-char (match-beginning 0))
9832 (if (outline-invisible-p) (org-show-context)))
9833 (goto-char pos)
9834 (setq org-link-search-failed t)
9835 (error "No further link found"))))
9837 (defun org-translate-link (s)
9838 "Translate a link string if a translation function has been defined."
9839 (if (and org-link-translation-function
9840 (fboundp org-link-translation-function)
9841 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9842 (progn
9843 (setq s (funcall org-link-translation-function
9844 (match-string 1 s) (match-string 2 s)))
9845 (concat (car s) ":" (cdr s)))
9848 (defun org-translate-link-from-planner (type path)
9849 "Translate a link from Emacs Planner syntax so that Org can follow it.
9850 This is still an experimental function, your mileage may vary."
9851 (cond
9852 ((member type '("http" "https" "news" "ftp"))
9853 ;; standard Internet links are the same.
9854 nil)
9855 ((and (equal type "irc") (string-match "^//" path))
9856 ;; Planner has two / at the beginning of an irc link, we have 1.
9857 ;; We should have zero, actually....
9858 (setq path (substring path 1)))
9859 ((and (equal type "lisp") (string-match "^/" path))
9860 ;; Planner has a slash, we do not.
9861 (setq type "elisp" path (substring path 1)))
9862 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9863 ;; A typical message link. Planner has the id after the final slash,
9864 ;; we separate it with a hash mark
9865 (setq path (concat (match-string 1 path) "#"
9866 (org-remove-angle-brackets (match-string 2 path)))))
9868 (cons type path))
9870 (defun org-find-file-at-mouse (ev)
9871 "Open file link or URL at mouse."
9872 (interactive "e")
9873 (mouse-set-point ev)
9874 (org-open-at-point 'in-emacs))
9876 (defun org-open-at-mouse (ev)
9877 "Open file link or URL at mouse.
9878 See the docstring of `org-open-file' for details."
9879 (interactive "e")
9880 (mouse-set-point ev)
9881 (if (eq major-mode 'org-agenda-mode)
9882 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9883 (org-open-at-point))
9885 (defvar org-window-config-before-follow-link nil
9886 "The window configuration before following a link.
9887 This is saved in case the need arises to restore it.")
9889 (defvar org-open-link-marker (make-marker)
9890 "Marker pointing to the location where `org-open-at-point; was called.")
9892 ;;;###autoload
9893 (defun org-open-at-point-global ()
9894 "Follow a link like Org-mode does.
9895 This command can be called in any mode to follow a link that has
9896 Org-mode syntax."
9897 (interactive)
9898 (org-run-like-in-org-mode 'org-open-at-point))
9900 ;;;###autoload
9901 (defun org-open-link-from-string (s &optional arg reference-buffer)
9902 "Open a link in the string S, as if it was in Org-mode."
9903 (interactive "sLink: \nP")
9904 (let ((reference-buffer (or reference-buffer (current-buffer))))
9905 (with-temp-buffer
9906 (let ((org-inhibit-startup (not reference-buffer)))
9907 (org-mode)
9908 (insert s)
9909 (goto-char (point-min))
9910 (when reference-buffer
9911 (setq org-link-abbrev-alist-local
9912 (with-current-buffer reference-buffer
9913 org-link-abbrev-alist-local)))
9914 (org-open-at-point arg reference-buffer)))))
9916 (defvar org-open-at-point-functions nil
9917 "Hook that is run when following a link at point.
9919 Functions in this hook must return t if they identify and follow
9920 a link at point. If they don't find anything interesting at point,
9921 they must return nil.")
9923 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9924 (defun org-open-at-point (&optional arg reference-buffer)
9925 "Open link at or after point.
9926 If there is no link at point, this function will search forward up to
9927 the end of the current line.
9928 Normally, files will be opened by an appropriate application. If the
9929 optional prefix argument ARG is non-nil, Emacs will visit the file.
9930 With a double prefix argument, try to open outside of Emacs, in the
9931 application the system uses for this file type."
9932 (interactive "P")
9933 ;; if in a code block, then open the block's results
9934 (unless (call-interactively #'org-babel-open-src-block-result)
9935 (org-load-modules-maybe)
9936 (move-marker org-open-link-marker (point))
9937 (setq org-window-config-before-follow-link (current-window-configuration))
9938 (org-remove-occur-highlights nil nil t)
9939 (cond
9940 ((and (org-at-heading-p)
9941 (not (org-at-timestamp-p t))
9942 (not (org-in-regexp
9943 (concat org-plain-link-re "\\|"
9944 org-bracket-link-regexp "\\|"
9945 org-angle-link-re "\\|"
9946 "[ \t]:[^ \t\n]+:[ \t]*$")))
9947 (not (get-text-property (point) 'org-linked-text)))
9948 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9949 (lk0 (car lkall))
9950 (lk (if (stringp lk0) (list lk0) lk0))
9951 (lkend (cdr lkall)))
9952 (mapcar (lambda(l)
9953 (search-forward l nil lkend)
9954 (goto-char (match-beginning 0))
9955 (org-open-at-point))
9956 lk))
9957 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9958 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9959 ((and (org-at-timestamp-p t)
9960 (not (org-in-regexp org-bracket-link-regexp)))
9961 (org-follow-timestamp-link))
9962 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9963 (not (org-in-regexp org-any-link-re)))
9964 (org-footnote-action))
9966 (let (type path link line search (pos (point)))
9967 (catch 'match
9968 (save-excursion
9969 (skip-chars-forward "^]\n\r")
9970 (when (org-in-regexp org-bracket-link-regexp 1)
9971 (setq link (org-extract-attributes
9972 (org-link-unescape (org-match-string-no-properties 1))))
9973 (while (string-match " *\n *" link)
9974 (setq link (replace-match " " t t link)))
9975 (setq link (org-link-expand-abbrev link))
9976 (cond
9977 ((or (file-name-absolute-p link)
9978 (string-match "^\\.\\.?/" link))
9979 (setq type "file" path link))
9980 ((string-match org-link-re-with-space3 link)
9981 (setq type (match-string 1 link) path (match-string 2 link)))
9982 ((string-match "^help:+\\(.+\\)" link)
9983 (setq type "help" path (match-string 1 link)))
9984 (t (setq type "thisfile" path link)))
9985 (throw 'match t)))
9987 (when (get-text-property (point) 'org-linked-text)
9988 (setq type "thisfile"
9989 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9990 (1+ (point)) (point))
9991 path (buffer-substring
9992 (or (previous-single-property-change pos 'org-linked-text)
9993 (point-min))
9994 (or (next-single-property-change pos 'org-linked-text)
9995 (point-max))))
9996 (throw 'match t))
9998 (save-excursion
9999 (when (or (org-in-regexp org-angle-link-re)
10000 (let ((match (org-in-regexp org-plain-link-re)))
10001 ;; Check a plain link is not within a bracket link
10002 (and match
10003 (save-excursion
10004 (progn
10005 (goto-char (car match))
10006 (not (org-in-regexp org-bracket-link-regexp))))))
10007 (let ((line_ending (save-excursion (end-of-line) (point))))
10008 ;; We are in a line before a plain or bracket link
10009 (or (re-search-forward org-plain-link-re line_ending t)
10010 (re-search-forward org-bracket-link-regexp line_ending t))))
10011 (setq type (match-string 1)
10012 path (org-link-unescape (match-string 2)))
10013 (throw 'match t)))
10014 (save-excursion
10015 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10016 (setq type "tags"
10017 path (match-string 1))
10018 (while (string-match ":" path)
10019 (setq path (replace-match "+" t t path)))
10020 (throw 'match t)))
10021 (when (org-in-regexp "<\\([^><\n]+\\)>")
10022 (setq type "tree-match"
10023 path (match-string 1))
10024 (throw 'match t)))
10025 (unless path
10026 (user-error "No link found"))
10028 ;; switch back to reference buffer
10029 ;; needed when if called in a temporary buffer through
10030 ;; org-open-link-from-string
10031 (with-current-buffer (or reference-buffer (current-buffer))
10033 ;; Remove any trailing spaces in path
10034 (if (string-match " +\\'" path)
10035 (setq path (replace-match "" t t path)))
10036 (if (and org-link-translation-function
10037 (fboundp org-link-translation-function))
10038 ;; Check if we need to translate the link
10039 (let ((tmp (funcall org-link-translation-function type path)))
10040 (setq type (car tmp) path (cdr tmp))))
10042 (cond
10044 ((assoc type org-link-protocols)
10045 (funcall (nth 1 (assoc type org-link-protocols)) path))
10047 ((equal type "help")
10048 (let ((f-or-v (intern path)))
10049 (cond ((fboundp f-or-v)
10050 (describe-function f-or-v))
10051 ((boundp f-or-v)
10052 (describe-variable f-or-v))
10053 (t (error "Not a known function or variable")))))
10055 ((equal type "mailto")
10056 (let ((cmd (car org-link-mailto-program))
10057 (args (cdr org-link-mailto-program)) args1
10058 (address path) (subject "") a)
10059 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10060 (setq address (match-string 1 path)
10061 subject (org-link-escape (match-string 2 path))))
10062 (while args
10063 (cond
10064 ((not (stringp (car args))) (push (pop args) args1))
10065 (t (setq a (pop args))
10066 (if (string-match "%a" a)
10067 (setq a (replace-match address t t a)))
10068 (if (string-match "%s" a)
10069 (setq a (replace-match subject t t a)))
10070 (push a args1))))
10071 (apply cmd (nreverse args1))))
10073 ((member type '("http" "https" "ftp" "news"))
10074 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10075 (org-link-escape
10076 path org-link-escape-chars-browser)
10077 path))))
10079 ((string= type "doi")
10080 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10081 (org-link-escape
10082 path org-link-escape-chars-browser)
10083 path))))
10085 ((member type '("message"))
10086 (browse-url (concat type ":" path)))
10088 ((string= type "tags")
10089 (org-tags-view arg path))
10091 ((string= type "tree-match")
10092 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10094 ((string= type "file")
10095 (if (string-match "::\\([0-9]+\\)\\'" path)
10096 (setq line (string-to-number (match-string 1 path))
10097 path (substring path 0 (match-beginning 0)))
10098 (if (string-match "::\\(.+\\)\\'" path)
10099 (setq search (match-string 1 path)
10100 path (substring path 0 (match-beginning 0)))))
10101 (if (string-match "[*?{]" (file-name-nondirectory path))
10102 (dired path)
10103 (org-open-file path arg line search)))
10105 ((string= type "shell")
10106 (let ((buf (generate-new-buffer "*Org Shell Output"))
10107 (cmd path))
10108 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10109 (string-match org-confirm-shell-link-not-regexp cmd))
10110 (not org-confirm-shell-link-function)
10111 (funcall org-confirm-shell-link-function
10112 (format "Execute \"%s\" in shell? "
10113 (org-add-props cmd nil
10114 'face 'org-warning))))
10115 (progn
10116 (message "Executing %s" cmd)
10117 (shell-command cmd buf)
10118 (if (featurep 'midnight)
10119 (setq clean-buffer-list-kill-buffer-names
10120 (cons buf clean-buffer-list-kill-buffer-names))))
10121 (error "Abort"))))
10123 ((string= type "elisp")
10124 (let ((cmd path))
10125 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10126 (string-match org-confirm-elisp-link-not-regexp cmd))
10127 (not org-confirm-elisp-link-function)
10128 (funcall org-confirm-elisp-link-function
10129 (format "Execute \"%s\" as elisp? "
10130 (org-add-props cmd nil
10131 'face 'org-warning))))
10132 (message "%s => %s" cmd
10133 (if (equal (string-to-char cmd) ?\()
10134 (eval (read cmd))
10135 (call-interactively (read cmd))))
10136 (error "Abort"))))
10138 ((and (string= type "thisfile")
10139 (run-hook-with-args-until-success
10140 'org-open-link-functions path)))
10142 ((string= type "thisfile")
10143 (if arg
10144 (switch-to-buffer-other-window
10145 (org-get-buffer-for-internal-link (current-buffer)))
10146 (org-mark-ring-push))
10147 (let ((cmd `(org-link-search
10148 ,path
10149 ,(cond ((equal arg '(4)) ''occur)
10150 ((equal arg '(16)) ''org-occur))
10151 ,pos)))
10152 (condition-case nil (let ((org-link-search-inhibit-query t))
10153 (eval cmd))
10154 (error (progn (widen) (eval cmd))))))
10156 (t (browse-url-at-point)))))))
10157 (move-marker org-open-link-marker nil)
10158 (run-hook-with-args 'org-follow-link-hook)))
10160 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10161 "Offer links in the current entry and return the selected link.
10162 If there is only one link, return it.
10163 If NTH is an integer, return the NTH link found.
10164 If ZERO is a string, check also this string for a link, and if
10165 there is one, return it."
10166 (with-current-buffer buffer
10167 (save-excursion
10168 (save-restriction
10169 (widen)
10170 (goto-char marker)
10171 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10172 "\\(" org-angle-link-re "\\)\\|"
10173 "\\(" org-plain-link-re "\\)"))
10174 (cnt ?0)
10175 (in-emacs (if (integerp nth) nil nth))
10176 have-zero end links link c)
10177 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10178 (push (match-string 0 zero) links)
10179 (setq cnt (1- cnt) have-zero t))
10180 (save-excursion
10181 (org-back-to-heading t)
10182 (setq end (save-excursion (outline-next-heading) (point)))
10183 (while (re-search-forward re end t)
10184 (push (match-string 0) links))
10185 (setq links (org-uniquify (reverse links))))
10186 (cond
10187 ((null links)
10188 (message "No links"))
10189 ((equal (length links) 1)
10190 (setq link (car links)))
10191 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10192 (setq link (nth (if have-zero nth (1- nth)) links)))
10193 (t ; we have to select a link
10194 (save-excursion
10195 (save-window-excursion
10196 (delete-other-windows)
10197 (with-output-to-temp-buffer "*Select Link*"
10198 (mapc (lambda (l)
10199 (if (not (string-match org-bracket-link-regexp l))
10200 (princ (format "[%c] %s\n" (incf cnt)
10201 (org-remove-angle-brackets l)))
10202 (if (match-end 3)
10203 (princ (format "[%c] %s (%s)\n" (incf cnt)
10204 (match-string 3 l) (match-string 1 l)))
10205 (princ (format "[%c] %s\n" (incf cnt)
10206 (match-string 1 l))))))
10207 links))
10208 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10209 (message "Select link to open, RET to open all:")
10210 (setq c (read-char-exclusive))
10211 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10212 (when (equal c ?q) (error "Abort"))
10213 (if (equal c ?\C-m)
10214 (setq link links)
10215 (setq nth (- c ?0))
10216 (if have-zero (setq nth (1+ nth)))
10217 (unless (and (integerp nth) (>= (length links) nth))
10218 (error "Invalid link selection"))
10219 (setq link (nth (1- nth) links)))))
10220 (cons link end))))))
10222 ;; Add special file links that specify the way of opening
10224 (org-add-link-type "file+sys" 'org-open-file-with-system)
10225 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10226 (defun org-open-file-with-system (path)
10227 "Open file at PATH using the system way of opening it."
10228 (org-open-file path 'system))
10229 (defun org-open-file-with-emacs (path)
10230 "Open file at PATH in Emacs."
10231 (org-open-file path 'emacs))
10234 ;;; File search
10236 (defvar org-create-file-search-functions nil
10237 "List of functions to construct the right search string for a file link.
10238 These functions are called in turn with point at the location to
10239 which the link should point.
10241 A function in the hook should first test if it would like to
10242 handle this file type, for example by checking the `major-mode'
10243 or the file extension. If it decides not to handle this file, it
10244 should just return nil to give other functions a chance. If it
10245 does handle the file, it must return the search string to be used
10246 when following the link. The search string will be part of the
10247 file link, given after a double colon, and `org-open-at-point'
10248 will automatically search for it. If special measures must be
10249 taken to make the search successful, another function should be
10250 added to the companion hook `org-execute-file-search-functions',
10251 which see.
10253 A function in this hook may also use `setq' to set the variable
10254 `description' to provide a suggestion for the descriptive text to
10255 be used for this link when it gets inserted into an Org-mode
10256 buffer with \\[org-insert-link].")
10258 (defvar org-execute-file-search-functions nil
10259 "List of functions to execute a file search triggered by a link.
10261 Functions added to this hook must accept a single argument, the
10262 search string that was part of the file link, the part after the
10263 double colon. The function must first check if it would like to
10264 handle this search, for example by checking the `major-mode' or
10265 the file extension. If it decides not to handle this search, it
10266 should just return nil to give other functions a chance. If it
10267 does handle the search, it must return a non-nil value to keep
10268 other functions from trying.
10270 Each function can access the current prefix argument through the
10271 variable `current-prefix-argument'. Note that a single prefix is
10272 used to force opening a link in Emacs, so it may be good to only
10273 use a numeric or double prefix to guide the search function.
10275 In case this is needed, a function in this hook can also restore
10276 the window configuration before `org-open-at-point' was called using:
10278 (set-window-configuration org-window-config-before-follow-link)")
10280 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10281 (defun org-link-search (s &optional type avoid-pos stealth)
10282 "Search for a link search option.
10283 If S is surrounded by forward slashes, it is interpreted as a
10284 regular expression. In org-mode files, this will create an `org-occur'
10285 sparse tree. In ordinary files, `occur' will be used to list matches.
10286 If the current buffer is in `dired-mode', grep will be used to search
10287 in all files. If AVOID-POS is given, ignore matches near that position.
10289 When optional argument STEALTH is non-nil, do not modify
10290 visibility around point, thus ignoring
10291 `org-show-hierarchy-above', `org-show-following-heading' and
10292 `org-show-siblings' variables."
10293 (let ((case-fold-search t)
10294 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10295 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10296 (append '(("") (" ") ("\t") ("\n"))
10297 org-emphasis-alist)
10298 "\\|") "\\)"))
10299 (pos (point))
10300 (pre nil) (post nil)
10301 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10302 (cond
10303 ;; First check if there are any special search functions
10304 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10305 ;; Now try the builtin stuff
10306 ((and (equal (string-to-char s0) ?#)
10307 (> (length s0) 1)
10308 (save-excursion
10309 (goto-char (point-min))
10310 (and
10311 (re-search-forward
10312 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10313 (setq type 'dedicated
10314 pos (match-beginning 0))))
10315 ;; There is an exact target for this
10316 (goto-char pos)
10317 (org-back-to-heading t)))
10318 ((save-excursion
10319 (goto-char (point-min))
10320 (and
10321 (re-search-forward
10322 (concat "<<" (regexp-quote s0) ">>") nil t)
10323 (setq type 'dedicated
10324 pos (match-beginning 0))))
10325 ;; There is an exact target for this
10326 (goto-char pos))
10327 ((save-excursion
10328 (goto-char (point-min))
10329 (and
10330 (re-search-forward
10331 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10332 (setq type 'dedicated pos (match-beginning 0))))
10333 ;; Found an invisible target.
10334 (goto-char pos))
10335 ((save-excursion
10336 (goto-char (point-min))
10337 (and
10338 (re-search-forward
10339 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10340 (setq type 'dedicated pos (match-beginning 0))))
10341 ;; Found an element with a matching #+name affiliated keyword.
10342 (goto-char pos))
10343 ((and (string-match "^(\\(.*\\))$" s0)
10344 (save-excursion
10345 (goto-char (point-min))
10346 (and
10347 (re-search-forward
10348 (concat "[^[]" (regexp-quote
10349 (format org-coderef-label-format
10350 (match-string 1 s0))))
10351 nil t)
10352 (setq type 'dedicated
10353 pos (1+ (match-beginning 0))))))
10354 ;; There is a coderef target for this
10355 (goto-char pos))
10356 ((string-match "^/\\(.*\\)/$" s)
10357 ;; A regular expression
10358 (cond
10359 ((derived-mode-p 'org-mode)
10360 (org-occur (match-string 1 s)))
10361 ;;((eq major-mode 'dired-mode)
10362 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10363 (t (org-do-occur (match-string 1 s)))))
10364 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10365 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10366 (goto-char (point-min))
10367 (cond
10368 ((let (case-fold-search)
10369 (re-search-forward (format org-complex-heading-regexp-format
10370 (regexp-quote s))
10371 nil t))
10372 ;; OK, found a match
10373 (setq type 'dedicated)
10374 (goto-char (match-beginning 0)))
10375 ((and (not org-link-search-inhibit-query)
10376 (eq org-link-search-must-match-exact-headline 'query-to-create)
10377 (y-or-n-p "No match - create this as a new heading? "))
10378 (goto-char (point-max))
10379 (or (bolp) (newline))
10380 (insert "* " s "\n")
10381 (beginning-of-line 0))
10383 (goto-char pos)
10384 (error "No match"))))
10386 ;; A normal search string
10387 (when (equal (string-to-char s) ?*)
10388 ;; Anchor on headlines, post may include tags.
10389 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10390 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10391 s (substring s 1)))
10392 (remove-text-properties
10393 0 (length s)
10394 '(face nil mouse-face nil keymap nil fontified nil) s)
10395 ;; Make a series of regular expressions to find a match
10396 (setq words (org-split-string s "[ \n\r\t]+")
10398 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10399 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10400 "\\)" markers)
10401 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10402 re2a (concat "[ \t\r\n]" re2a_)
10403 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10404 re4 (concat "[^a-zA-Z_]" re4_)
10406 re1 (concat pre re2 post)
10407 re3 (concat pre (if pre re4_ re4) post)
10408 re5 (concat pre ".*" re4)
10409 re2 (concat pre re2)
10410 re2a (concat pre (if pre re2a_ re2a))
10411 re4 (concat pre (if pre re4_ re4))
10412 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10413 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10414 re5 "\\)"
10416 (cond
10417 ((eq type 'org-occur) (org-occur reall))
10418 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10419 (t (goto-char (point-min))
10420 (setq type 'fuzzy)
10421 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10422 (org-search-not-self 1 re1 nil t)
10423 (org-search-not-self 1 re2 nil t)
10424 (org-search-not-self 1 re2a nil t)
10425 (org-search-not-self 1 re3 nil t)
10426 (org-search-not-self 1 re4 nil t)
10427 (org-search-not-self 1 re5 nil t)
10429 (goto-char (match-beginning 1))
10430 (goto-char pos)
10431 (error "No match"))))))
10432 (and (derived-mode-p 'org-mode)
10433 (not stealth)
10434 (org-show-context 'link-search))
10435 type))
10437 (defun org-search-not-self (group &rest args)
10438 "Execute `re-search-forward', but only accept matches that do not
10439 enclose the position of `org-open-link-marker'."
10440 (let ((m org-open-link-marker))
10441 (catch 'exit
10442 (while (apply 're-search-forward args)
10443 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10444 (goto-char (match-end group))
10445 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10446 (> (match-beginning 0) (marker-position m))
10447 (< (match-end 0) (marker-position m)))
10448 (save-match-data
10449 (or (not (org-in-regexp
10450 org-bracket-link-analytic-regexp 1))
10451 (not (match-end 4)) ; no description
10452 (and (<= (match-beginning 4) (point))
10453 (>= (match-end 4) (point))))))
10454 (throw 'exit (point))))))))
10456 (defun org-get-buffer-for-internal-link (buffer)
10457 "Return a buffer to be used for displaying the link target of internal links."
10458 (cond
10459 ((not org-display-internal-link-with-indirect-buffer)
10460 buffer)
10461 ((string-match "(Clone)$" (buffer-name buffer))
10462 (message "Buffer is already a clone, not making another one")
10463 ;; we also do not modify visibility in this case
10464 buffer)
10465 (t ; make a new indirect buffer for displaying the link
10466 (let* ((bn (buffer-name buffer))
10467 (ibn (concat bn "(Clone)"))
10468 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10469 (with-current-buffer ib (org-overview))
10470 ib))))
10472 (defun org-do-occur (regexp &optional cleanup)
10473 "Call the Emacs command `occur'.
10474 If CLEANUP is non-nil, remove the printout of the regular expression
10475 in the *Occur* buffer. This is useful if the regex is long and not useful
10476 to read."
10477 (occur regexp)
10478 (when cleanup
10479 (let ((cwin (selected-window)) win beg end)
10480 (when (setq win (get-buffer-window "*Occur*"))
10481 (select-window win))
10482 (goto-char (point-min))
10483 (when (re-search-forward "match[a-z]+" nil t)
10484 (setq beg (match-end 0))
10485 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10486 (setq end (1- (match-beginning 0)))))
10487 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10488 (goto-char (point-min))
10489 (select-window cwin))))
10491 ;;; The mark ring for links jumps
10493 (defvar org-mark-ring nil
10494 "Mark ring for positions before jumps in Org-mode.")
10495 (defvar org-mark-ring-last-goto nil
10496 "Last position in the mark ring used to go back.")
10497 ;; Fill and close the ring
10498 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10499 (loop for i from 1 to org-mark-ring-length do
10500 (push (make-marker) org-mark-ring))
10501 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10502 org-mark-ring)
10504 (defun org-mark-ring-push (&optional pos buffer)
10505 "Put the current position or POS into the mark ring and rotate it."
10506 (interactive)
10507 (setq pos (or pos (point)))
10508 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10509 (move-marker (car org-mark-ring)
10510 (or pos (point))
10511 (or buffer (current-buffer)))
10512 (message "%s"
10513 (substitute-command-keys
10514 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10516 (defun org-mark-ring-goto (&optional n)
10517 "Jump to the previous position in the mark ring.
10518 With prefix arg N, jump back that many stored positions. When
10519 called several times in succession, walk through the entire ring.
10520 Org-mode commands jumping to a different position in the current file,
10521 or to another Org-mode file, automatically push the old position
10522 onto the ring."
10523 (interactive "p")
10524 (let (p m)
10525 (if (eq last-command this-command)
10526 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10527 (setq p org-mark-ring))
10528 (setq org-mark-ring-last-goto p)
10529 (setq m (car p))
10530 (org-pop-to-buffer-same-window (marker-buffer m))
10531 (goto-char m)
10532 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10534 (defun org-remove-angle-brackets (s)
10535 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10536 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10538 (defun org-add-angle-brackets (s)
10539 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10540 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10542 (defun org-remove-double-quotes (s)
10543 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10544 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10547 ;;; Following specific links
10549 (defun org-follow-timestamp-link ()
10550 "Open an agenda view for the time-stamp date/range at point."
10551 (cond
10552 ((org-at-date-range-p t)
10553 (let ((org-agenda-start-on-weekday)
10554 (t1 (match-string 1))
10555 (t2 (match-string 2)) tt1 tt2)
10556 (setq tt1 (time-to-days (org-time-string-to-time t1))
10557 tt2 (time-to-days (org-time-string-to-time t2)))
10558 (let ((org-agenda-buffer-tmp-name
10559 (format "*Org Agenda(a:%s)"
10560 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10561 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10562 ((org-at-timestamp-p t)
10563 (let ((org-agenda-buffer-tmp-name
10564 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10565 (org-agenda-list nil (time-to-days (org-time-string-to-time
10566 (substring (match-string 1) 0 10)))
10567 1)))
10568 (t (error "This should not happen"))))
10571 ;;; Following file links
10572 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10573 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10574 (declare-function mailcap-mime-info
10575 "mailcap" (string &optional request no-decode))
10576 (defvar org-wait nil)
10577 (defun org-open-file (path &optional in-emacs line search)
10578 "Open the file at PATH.
10579 First, this expands any special file name abbreviations. Then the
10580 configuration variable `org-file-apps' is checked if it contains an
10581 entry for this file type, and if yes, the corresponding command is launched.
10583 If no application is found, Emacs simply visits the file.
10585 With optional prefix argument IN-EMACS, Emacs will visit the file.
10586 With a double \\[universal-argument] \\[universal-argument] \
10587 prefix arg, Org tries to avoid opening in Emacs
10588 and to use an external application to visit the file.
10590 Optional LINE specifies a line to go to, optional SEARCH a string
10591 to search for. If LINE or SEARCH is given, the file will be
10592 opened in Emacs, unless an entry from org-file-apps that makes
10593 use of groups in a regexp matches.
10595 If you want to change the way frames are used when following a
10596 link, please customize `org-link-frame-setup'.
10598 If the file does not exist, an error is thrown."
10599 (let* ((file (if (equal path "")
10600 buffer-file-name
10601 (substitute-in-file-name (expand-file-name path))))
10602 (file-apps (append org-file-apps (org-default-apps)))
10603 (apps (org-remove-if
10604 'org-file-apps-entry-match-against-dlink-p file-apps))
10605 (apps-dlink (org-remove-if-not
10606 'org-file-apps-entry-match-against-dlink-p file-apps))
10607 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10608 (dirp (if remp nil (file-directory-p file)))
10609 (file (if (and dirp org-open-directory-means-index-dot-org)
10610 (concat (file-name-as-directory file) "index.org")
10611 file))
10612 (a-m-a-p (assq 'auto-mode apps))
10613 (dfile (downcase file))
10614 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10615 (link (cond ((and (eq line nil)
10616 (eq search nil))
10617 file)
10618 (line
10619 (concat file "::" (number-to-string line)))
10620 (search
10621 (concat file "::" search))))
10622 (dlink (downcase link))
10623 (old-buffer (current-buffer))
10624 (old-pos (point))
10625 (old-mode major-mode)
10626 ext cmd link-match-data)
10627 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10628 (setq ext (match-string 1 dfile))
10629 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10630 (setq ext (match-string 1 dfile))))
10631 (cond
10632 ((member in-emacs '((16) system))
10633 (setq cmd (cdr (assoc 'system apps))))
10634 (in-emacs (setq cmd 'emacs))
10636 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10637 (and dirp (cdr (assoc 'directory apps)))
10638 ; first, try matching against apps-dlink
10639 ; if we get a match here, store the match data for later
10640 (let ((match (assoc-default dlink apps-dlink
10641 'string-match)))
10642 (if match
10643 (progn (setq link-match-data (match-data))
10644 match)
10645 (progn (setq in-emacs (or in-emacs line search))
10646 nil))) ; if we have no match in apps-dlink,
10647 ; always open the file in emacs if line or search
10648 ; is given (for backwards compatibility)
10649 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10650 'string-match)
10651 (cdr (assoc ext apps))
10652 (cdr (assoc t apps))))))
10653 (when (eq cmd 'system)
10654 (setq cmd (cdr (assoc 'system apps))))
10655 (when (eq cmd 'default)
10656 (setq cmd (cdr (assoc t apps))))
10657 (when (eq cmd 'mailcap)
10658 (require 'mailcap)
10659 (mailcap-parse-mailcaps)
10660 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10661 (command (mailcap-mime-info mime-type)))
10662 (if (stringp command)
10663 (setq cmd command)
10664 (setq cmd 'emacs))))
10665 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10666 (not (file-exists-p file))
10667 (not org-open-non-existing-files))
10668 (error "No such file: %s" file))
10669 (cond
10670 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10671 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10672 (while (string-match "['\"]%s['\"]" cmd)
10673 (setq cmd (replace-match "%s" t t cmd)))
10674 (while (string-match "%s" cmd)
10675 (setq cmd (replace-match
10676 (save-match-data
10677 (shell-quote-argument
10678 (convert-standard-filename file)))
10679 t t cmd)))
10681 ;; Replace "%1", "%2" etc. in command with group matches from regex
10682 (save-match-data
10683 (let ((match-index 1)
10684 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10685 (set-match-data link-match-data)
10686 (while (<= match-index number-of-groups)
10687 (let ((regex (concat "%" (number-to-string match-index)))
10688 (replace-with (match-string match-index dlink)))
10689 (while (string-match regex cmd)
10690 (setq cmd (replace-match replace-with t t cmd))))
10691 (setq match-index (+ match-index 1)))))
10693 (save-window-excursion
10694 (message "Running %s...done" cmd)
10695 (start-process-shell-command cmd nil cmd)
10696 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10697 ((or (stringp cmd)
10698 (eq cmd 'emacs))
10699 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10700 (widen)
10701 (if line (org-goto-line line)
10702 (if search (org-link-search search))))
10703 ((consp cmd)
10704 (let ((file (convert-standard-filename file)))
10705 (save-match-data
10706 (set-match-data link-match-data)
10707 (eval cmd))))
10708 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10709 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10710 (or (not (equal old-buffer (current-buffer)))
10711 (not (equal old-pos (point))))
10712 (org-mark-ring-push old-pos old-buffer))))
10714 (defun org-file-apps-entry-match-against-dlink-p (entry)
10715 "This function returns non-nil if `entry' uses a regular
10716 expression which should be matched against the whole link by
10717 org-open-file.
10719 It assumes that is the case when the entry uses a regular
10720 expression which has at least one grouping construct and the
10721 action is either a lisp form or a command string containing
10722 '%1', i.e. using at least one subexpression match as a
10723 parameter."
10724 (let ((selector (car entry))
10725 (action (cdr entry)))
10726 (if (stringp selector)
10727 (and (> (regexp-opt-depth selector) 0)
10728 (or (and (stringp action)
10729 (string-match "%[0-9]" action))
10730 (consp action)))
10731 nil)))
10733 (defun org-default-apps ()
10734 "Return the default applications for this operating system."
10735 (cond
10736 ((eq system-type 'darwin)
10737 org-file-apps-defaults-macosx)
10738 ((eq system-type 'windows-nt)
10739 org-file-apps-defaults-windowsnt)
10740 (t org-file-apps-defaults-gnu)))
10742 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10743 "Convert extensions to regular expressions in the cars of LIST.
10744 Also, weed out any non-string entries, because the return value is used
10745 only for regexp matching.
10746 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10747 point to the symbol `emacs', indicating that the file should
10748 be opened in Emacs."
10749 (append
10750 (delq nil
10751 (mapcar (lambda (x)
10752 (if (not (stringp (car x)))
10754 (if (string-match "\\W" (car x))
10756 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10757 list))
10758 (if add-auto-mode
10759 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10761 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10762 (defun org-file-remote-p (file)
10763 "Test whether FILE specifies a location on a remote system.
10764 Return non-nil if the location is indeed remote.
10766 For example, the filename \"/user@host:/foo\" specifies a location
10767 on the system \"/user@host:\"."
10768 (cond ((fboundp 'file-remote-p)
10769 (file-remote-p file))
10770 ((fboundp 'tramp-handle-file-remote-p)
10771 (tramp-handle-file-remote-p file))
10772 ((and (boundp 'ange-ftp-name-format)
10773 (string-match (car ange-ftp-name-format) file))
10774 t)))
10777 ;;;; Refiling
10779 (defun org-get-org-file ()
10780 "Read a filename, with default directory `org-directory'."
10781 (let ((default (or org-default-notes-file remember-data-file)))
10782 (read-file-name (format "File name [%s]: " default)
10783 (file-name-as-directory org-directory)
10784 default)))
10786 (defun org-notes-order-reversed-p ()
10787 "Check if the current file should receive notes in reversed order."
10788 (cond
10789 ((not org-reverse-note-order) nil)
10790 ((eq t org-reverse-note-order) t)
10791 ((not (listp org-reverse-note-order)) nil)
10792 (t (catch 'exit
10793 (let ((all org-reverse-note-order)
10794 entry)
10795 (while (setq entry (pop all))
10796 (if (string-match (car entry) buffer-file-name)
10797 (throw 'exit (cdr entry))))
10798 nil)))))
10800 (defvar org-refile-target-table nil
10801 "The list of refile targets, created by `org-refile'.")
10803 (defvar org-agenda-new-buffers nil
10804 "Buffers created to visit agenda files.")
10806 (defvar org-refile-cache nil
10807 "Cache for refile targets.")
10809 (defvar org-refile-markers nil
10810 "All the markers used for caching refile locations.")
10812 (defun org-refile-marker (pos)
10813 "Get a new refile marker, but only if caching is in use."
10814 (if (not org-refile-use-cache)
10816 (let ((m (make-marker)))
10817 (move-marker m pos)
10818 (push m org-refile-markers)
10819 m)))
10821 (defun org-refile-cache-clear ()
10822 "Clear the refile cache and disable all the markers."
10823 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10824 (setq org-refile-markers nil)
10825 (setq org-refile-cache nil)
10826 (message "Refile cache has been cleared"))
10828 (defun org-refile-cache-check-set (set)
10829 "Check if all the markers in the cache still have live buffers."
10830 (let (marker)
10831 (catch 'exit
10832 (while (and set (setq marker (nth 3 (pop set))))
10833 ;; if org-refile-use-outline-path is 'file, marker may be nil
10834 (when (and marker (null (marker-buffer marker)))
10835 (message "not found") (sit-for 3)
10836 (throw 'exit nil)))
10837 t)))
10839 (defun org-refile-cache-put (set &rest identifiers)
10840 "Push the refile targets SET into the cache, under IDENTIFIERS."
10841 (let* ((key (sha1 (prin1-to-string identifiers)))
10842 (entry (assoc key org-refile-cache)))
10843 (if entry
10844 (setcdr entry set)
10845 (push (cons key set) org-refile-cache))))
10847 (defun org-refile-cache-get (&rest identifiers)
10848 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10849 (cond
10850 ((not org-refile-cache) nil)
10851 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10853 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10854 org-refile-cache))))
10855 (and set (org-refile-cache-check-set set) set)))))
10857 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10858 "Produce a table with refile targets."
10859 (let ((case-fold-search nil)
10860 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10861 (entries (or org-refile-targets '((nil . (:level . 1)))))
10862 targets tgs txt re files f desc descre fast-path-p level pos0)
10863 (message "Getting targets...")
10864 (with-current-buffer (or default-buffer (current-buffer))
10865 (while (setq entry (pop entries))
10866 (setq files (car entry) desc (cdr entry))
10867 (setq fast-path-p nil)
10868 (cond
10869 ((null files) (setq files (list (current-buffer))))
10870 ((eq files 'org-agenda-files)
10871 (setq files (org-agenda-files 'unrestricted)))
10872 ((and (symbolp files) (fboundp files))
10873 (setq files (funcall files)))
10874 ((and (symbolp files) (boundp files))
10875 (setq files (symbol-value files))))
10876 (if (stringp files) (setq files (list files)))
10877 (cond
10878 ((eq (car desc) :tag)
10879 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10880 ((eq (car desc) :todo)
10881 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10882 ((eq (car desc) :regexp)
10883 (setq descre (cdr desc)))
10884 ((eq (car desc) :level)
10885 (setq descre (concat "^\\*\\{" (number-to-string
10886 (if org-odd-levels-only
10887 (1- (* 2 (cdr desc)))
10888 (cdr desc)))
10889 "\\}[ \t]")))
10890 ((eq (car desc) :maxlevel)
10891 (setq fast-path-p t)
10892 (setq descre (concat "^\\*\\{1," (number-to-string
10893 (if org-odd-levels-only
10894 (1- (* 2 (cdr desc)))
10895 (cdr desc)))
10896 "\\}[ \t]")))
10897 (t (error "Bad refiling target description %s" desc)))
10898 (while (setq f (pop files))
10899 (with-current-buffer
10900 (if (bufferp f) f (org-get-agenda-file-buffer f))
10902 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10903 (progn
10904 (if (bufferp f) (setq f (buffer-file-name
10905 (buffer-base-buffer f))))
10906 (setq f (and f (expand-file-name f)))
10907 (if (eq org-refile-use-outline-path 'file)
10908 (push (list (file-name-nondirectory f) f nil nil) tgs))
10909 (save-excursion
10910 (save-restriction
10911 (widen)
10912 (goto-char (point-min))
10913 (while (re-search-forward descre nil t)
10914 (goto-char (setq pos0 (point-at-bol)))
10915 (catch 'next
10916 (when org-refile-target-verify-function
10917 (save-match-data
10918 (or (funcall org-refile-target-verify-function)
10919 (throw 'next t))))
10920 (when (and (looking-at org-complex-heading-regexp)
10921 (not (member (match-string 4) excluded-entries))
10922 (match-string 4))
10923 (setq level (org-reduced-level
10924 (- (match-end 1) (match-beginning 1)))
10925 txt (org-link-display-format (match-string 4))
10926 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10927 re (format org-complex-heading-regexp-format
10928 (regexp-quote (match-string 4))))
10929 (when org-refile-use-outline-path
10930 (setq txt (mapconcat
10931 'org-protect-slash
10932 (append
10933 (if (eq org-refile-use-outline-path
10934 'file)
10935 (list (file-name-nondirectory
10936 (buffer-file-name
10937 (buffer-base-buffer))))
10938 (if (eq org-refile-use-outline-path
10939 'full-file-path)
10940 (list (buffer-file-name
10941 (buffer-base-buffer)))))
10942 (org-get-outline-path fast-path-p
10943 level txt)
10944 (list txt))
10945 "/")))
10946 (push (list txt f re (org-refile-marker (point)))
10947 tgs)))
10948 (when (= (point) pos0)
10949 ;; verification function has not moved point
10950 (goto-char (point-at-eol))))))))
10951 (when org-refile-use-cache
10952 (org-refile-cache-put tgs (buffer-file-name) descre))
10953 (setq targets (append tgs targets))
10954 ))))
10955 (message "Getting targets...done")
10956 (nreverse targets)))
10958 (defun org-protect-slash (s)
10959 (while (string-match "/" s)
10960 (setq s (replace-match "\\" t t s)))
10963 (defvar org-olpa (make-vector 20 nil))
10965 (defun org-get-outline-path (&optional fastp level heading)
10966 "Return the outline path to the current entry, as a list.
10968 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10969 routine which makes outline path derivations for an entire file,
10970 avoiding backtracing. Refile target collection makes use of that."
10971 (if fastp
10972 (progn
10973 (if (> level 19)
10974 (error "Outline path failure, more than 19 levels"))
10975 (loop for i from level upto 19 do
10976 (aset org-olpa i nil))
10977 (prog1
10978 (delq nil (append org-olpa nil))
10979 (aset org-olpa level heading)))
10980 (let (rtn case-fold-search)
10981 (save-excursion
10982 (save-restriction
10983 (widen)
10984 (while (org-up-heading-safe)
10985 (when (looking-at org-complex-heading-regexp)
10986 (push (org-match-string-no-properties 4) rtn)))
10987 rtn)))))
10989 (defun org-format-outline-path (path &optional width prefix separator)
10990 "Format the outline path PATH for display.
10991 WIDTH is the maximum number of characters that is available.
10992 PREFIX is a prefix to be included in the returned string,
10993 such as the file name.
10994 SEPARATOR is inserted between the different parts of the path,
10995 the default is \"/\"."
10996 (setq width (or width 79))
10997 (if prefix (setq width (- width (length prefix))))
10998 (if (not path)
10999 (or prefix "")
11000 (let* ((nsteps (length path))
11001 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11002 (maxwidth (if (<= total-width width)
11003 10000 ;; everything fits
11004 ;; we need to shorten the level headings
11005 (/ (- width nsteps) nsteps)))
11006 (org-odd-levels-only nil)
11007 (n 0)
11008 (total (1+ (length prefix))))
11009 (setq maxwidth (max maxwidth 10))
11010 (concat prefix
11011 (if prefix (or separator "/"))
11012 (mapconcat
11013 (lambda (h)
11014 (setq n (1+ n))
11015 (if (and (= n nsteps) (< maxwidth 10000))
11016 (setq maxwidth (- total-width total)))
11017 (if (< (length h) maxwidth)
11018 (progn (setq total (+ total (length h) 1)) h)
11019 (setq h (substring h 0 (- maxwidth 2))
11020 total (+ total maxwidth 1))
11021 (if (string-match "[ \t]+\\'" h)
11022 (setq h (substring h 0 (match-beginning 0))))
11023 (setq h (concat h "..")))
11024 (org-add-props h nil 'face
11025 (nth (% (1- n) org-n-level-faces)
11026 org-level-faces))
11028 path (or separator "/"))))))
11030 (defun org-display-outline-path (&optional file current separator just-return-string)
11031 "Display the current outline path in the echo area.
11033 If FILE is non-nil, prepend the output with the file name.
11034 If CURRENT is non-nil, append the current heading to the output.
11035 SEPARATOR is passed through to `org-format-outline-path'. It separates
11036 the different parts of the path and defaults to \"/\".
11037 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11038 (interactive "P")
11039 (let* (case-fold-search
11040 message-log-max ; Don't populate the *Messages* buffer
11041 (bfn (buffer-file-name (buffer-base-buffer)))
11042 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11043 res)
11044 (if current (setq path (append path
11045 (save-excursion
11046 (org-back-to-heading t)
11047 (if (looking-at org-complex-heading-regexp)
11048 (list (match-string 4)))))))
11049 (setq res
11050 (org-format-outline-path
11051 path
11052 (1- (frame-width))
11053 (and file bfn (concat (file-name-nondirectory bfn) separator))
11054 separator))
11055 (if just-return-string
11056 (org-no-properties res)
11057 (message "%s" res))))
11059 (defvar org-refile-history nil
11060 "History for refiling operations.")
11062 (defvar org-after-refile-insert-hook nil
11063 "Hook run after `org-refile' has inserted its stuff at the new location.
11064 Note that this is still *before* the stuff will be removed from
11065 the *old* location.")
11067 (defvar org-capture-last-stored-marker)
11068 (defvar org-refile-keep nil
11069 "Non-nil means `org-refile' will copy instead of refile.")
11071 (defun org-copy ()
11072 "Like `org-refile', but copy."
11073 (interactive)
11074 (let ((org-refile-keep t))
11075 (funcall 'org-refile nil nil nil "Copy")))
11077 (defun org-refile (&optional goto default-buffer rfloc msg)
11078 "Move the entry or entries at point to another heading.
11079 The list of target headings is compiled using the information in
11080 `org-refile-targets', which see.
11082 At the target location, the entry is filed as a subitem of the target
11083 heading. Depending on `org-reverse-note-order', the new subitem will
11084 either be the first or the last subitem.
11086 If there is an active region, all entries in that region will be moved.
11087 However, the region must fulfill the requirement that the first heading
11088 is the first one sets the top-level of the moved text - at most siblings
11089 below it are allowed.
11091 With prefix arg GOTO, the command will only visit the target location
11092 and not actually move anything.
11094 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11095 go to the location where the last refiling operation has put the subtree.
11096 With a prefix argument of `2', refile to the running clock.
11098 RFLOC can be a refile location obtained in a different way.
11100 MSG is a string to replace \"Refile\" in the default prompt with
11101 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11103 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11105 If you are using target caching (see `org-refile-use-cache'),
11106 you have to clear the target cache in order to find new targets.
11107 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11108 prefix argument (`C-u C-u C-u C-c C-w')."
11110 (interactive "P")
11111 (if (member goto '(0 (64)))
11112 (org-refile-cache-clear)
11113 (let* ((actionmsg (or msg "Refile"))
11114 (cbuf (current-buffer))
11115 (regionp (org-region-active-p))
11116 (region-start (and regionp (region-beginning)))
11117 (region-end (and regionp (region-end)))
11118 (region-length (and regionp (- region-end region-start)))
11119 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11120 pos it nbuf file re level reversed)
11121 (setq last-command nil)
11122 (when regionp
11123 (goto-char region-start)
11124 (or (bolp) (goto-char (point-at-bol)))
11125 (setq region-start (point))
11126 (unless (or (org-kill-is-subtree-p
11127 (buffer-substring region-start region-end))
11128 (prog1 org-refile-active-region-within-subtree
11129 (org-toggle-heading)))
11130 (error "The region is not a (sequence of) subtree(s)")))
11131 (if (equal goto '(16))
11132 (org-refile-goto-last-stored)
11133 (when (or
11134 (and (equal goto 2)
11135 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11136 (prog1
11137 (setq it (list (or org-clock-heading "running clock")
11138 (buffer-file-name
11139 (marker-buffer org-clock-hd-marker))
11141 (marker-position org-clock-hd-marker)))
11142 (setq goto nil)))
11143 (setq it (or rfloc
11144 (let (heading-text)
11145 (save-excursion
11146 (unless goto
11147 (org-back-to-heading t)
11148 (setq heading-text
11149 (nth 4 (org-heading-components))))
11151 (org-refile-get-location
11152 (cond (goto "Goto")
11153 (regionp (concat actionmsg " region to"))
11154 (t (concat actionmsg " subtree \""
11155 heading-text "\" to")))
11156 default-buffer
11157 (and (not (equal '(4) goto))
11158 org-refile-allow-creating-parent-nodes)
11159 goto))))))
11160 (setq file (nth 1 it)
11161 re (nth 2 it)
11162 pos (nth 3 it))
11163 (if (and (not goto)
11165 (equal (buffer-file-name) file)
11166 (if regionp
11167 (and (>= pos region-start)
11168 (<= pos region-end))
11169 (and (>= pos (point))
11170 (< pos (save-excursion
11171 (org-end-of-subtree t t))))))
11172 (error "Cannot refile to position inside the tree or region"))
11174 (setq nbuf (or (find-buffer-visiting file)
11175 (find-file-noselect file)))
11176 (if goto
11177 (progn
11178 (org-pop-to-buffer-same-window nbuf)
11179 (goto-char pos)
11180 (org-show-context 'org-goto))
11181 (if regionp
11182 (progn
11183 (org-kill-new (buffer-substring region-start region-end))
11184 (org-save-markers-in-region region-start region-end))
11185 (org-copy-subtree 1 nil t))
11186 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11187 (find-file-noselect file)))
11188 (setq reversed (org-notes-order-reversed-p))
11189 (save-excursion
11190 (save-restriction
11191 (widen)
11192 (if pos
11193 (progn
11194 (goto-char pos)
11195 (looking-at org-outline-regexp)
11196 (setq level (org-get-valid-level (funcall outline-level) 1))
11197 (goto-char
11198 (if reversed
11199 (or (outline-next-heading) (point-max))
11200 (or (save-excursion (org-get-next-sibling))
11201 (org-end-of-subtree t t)
11202 (point-max)))))
11203 (setq level 1)
11204 (if (not reversed)
11205 (goto-char (point-max))
11206 (goto-char (point-min))
11207 (or (outline-next-heading) (goto-char (point-max)))))
11208 (if (not (bolp)) (newline))
11209 (org-paste-subtree level)
11210 (when org-log-refile
11211 (org-add-log-setup 'refile nil nil 'findpos
11212 org-log-refile)
11213 (unless (eq org-log-refile 'note)
11214 (save-excursion (org-add-log-note))))
11215 (and org-auto-align-tags
11216 (let ((org-loop-over-headlines-in-active-region nil))
11217 (org-set-tags nil t)))
11218 (with-demoted-errors
11219 (bookmark-set "org-refile-last-stored"))
11220 ;; If we are refiling for capture, make sure that the
11221 ;; last-capture pointers point here
11222 (when (org-bound-and-true-p org-refile-for-capture)
11223 (with-demoted-errors
11224 (bookmark-set "org-capture-last-stored-marker"))
11225 (move-marker org-capture-last-stored-marker (point)))
11226 (if (fboundp 'deactivate-mark) (deactivate-mark))
11227 (run-hooks 'org-after-refile-insert-hook))))
11228 (unless org-refile-keep
11229 (if regionp
11230 (delete-region (point) (+ (point) region-length))
11231 (org-cut-subtree)))
11232 (when (featurep 'org-inlinetask)
11233 (org-inlinetask-remove-END-maybe))
11234 (setq org-markers-to-move nil)
11235 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11237 (defun org-refile-goto-last-stored ()
11238 "Go to the location where the last refile was stored."
11239 (interactive)
11240 (bookmark-jump "org-refile-last-stored")
11241 (message "This is the location of the last refile"))
11243 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11244 no-exclude)
11245 "Prompt the user for a refile location, using PROMPT.
11246 PROMPT should not be suffixed with a colon and a space, because
11247 this function appends the default value from
11248 `org-refile-history' automatically, if that is not empty.
11249 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11250 this is used for the GOTO interface."
11251 (let ((org-refile-targets org-refile-targets)
11252 (org-refile-use-outline-path org-refile-use-outline-path)
11253 excluded-entries)
11254 (when (and (derived-mode-p 'org-mode)
11255 (not org-refile-use-cache)
11256 (not no-exclude))
11257 (org-map-tree
11258 (lambda()
11259 (setq excluded-entries
11260 (append excluded-entries (list (org-get-heading t t)))))))
11261 (setq org-refile-target-table
11262 (org-refile-get-targets default-buffer excluded-entries)))
11263 (unless org-refile-target-table
11264 (error "No refile targets"))
11265 (let* ((cbuf (current-buffer))
11266 (partial-completion-mode nil)
11267 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11268 (cfunc (if (and org-refile-use-outline-path
11269 org-outline-path-complete-in-steps)
11270 'org-olpath-completing-read
11271 'org-icompleting-read))
11272 (extra (if org-refile-use-outline-path "/" ""))
11273 (cbnex (concat (buffer-name) extra))
11274 (filename (and cfn (expand-file-name cfn)))
11275 (tbl (mapcar
11276 (lambda (x)
11277 (if (and (not (member org-refile-use-outline-path
11278 '(file full-file-path)))
11279 (not (equal filename (nth 1 x))))
11280 (cons (concat (car x) extra " ("
11281 (file-name-nondirectory (nth 1 x)) ")")
11282 (cdr x))
11283 (cons (concat (car x) extra) (cdr x))))
11284 org-refile-target-table))
11285 (completion-ignore-case t)
11286 cdef
11287 (prompt (concat prompt
11288 (or (and (car org-refile-history)
11289 (concat " (default " (car org-refile-history) ")"))
11290 (and (assoc cbnex tbl) (setq cdef cbnex)
11291 (concat " (default " cbnex ")"))) ": "))
11292 pa answ parent-target child parent old-hist)
11293 (setq old-hist org-refile-history)
11294 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11295 nil 'org-refile-history (or cdef (car org-refile-history))))
11296 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11297 (org-refile-check-position pa)
11298 (if pa
11299 (progn
11300 (when (or (not org-refile-history)
11301 (not (eq old-hist org-refile-history))
11302 (not (equal (car pa) (car org-refile-history))))
11303 (setq org-refile-history
11304 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11305 org-refile-history
11306 (cdr org-refile-history))))
11307 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11308 (pop org-refile-history)))
11310 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11311 (progn
11312 (setq parent (match-string 1 answ)
11313 child (match-string 2 answ))
11314 (setq parent-target (or (assoc parent tbl)
11315 (assoc (concat parent "/") tbl)))
11316 (when (and parent-target
11317 (or (eq new-nodes t)
11318 (and (eq new-nodes 'confirm)
11319 (y-or-n-p (format "Create new node \"%s\"? "
11320 child)))))
11321 (org-refile-new-child parent-target child)))
11322 (error "Invalid target location")))))
11324 (declare-function org-string-nw-p "org-macs" (s))
11325 (defun org-refile-check-position (refile-pointer)
11326 "Check if the refile pointer matches the headline to which it points."
11327 (let* ((file (nth 1 refile-pointer))
11328 (re (nth 2 refile-pointer))
11329 (pos (nth 3 refile-pointer))
11330 buffer)
11331 (if (and (not (markerp pos)) (not file))
11332 (error "Please save the buffer to a file before refiling")
11333 (when (org-string-nw-p re)
11334 (setq buffer (if (markerp pos)
11335 (marker-buffer pos)
11336 (or (find-buffer-visiting file)
11337 (find-file-noselect file))))
11338 (with-current-buffer buffer
11339 (save-excursion
11340 (save-restriction
11341 (widen)
11342 (goto-char pos)
11343 (beginning-of-line 1)
11344 (unless (org-looking-at-p re)
11345 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11347 (defun org-refile-new-child (parent-target child)
11348 "Use refile target PARENT-TARGET to add new CHILD below it."
11349 (unless parent-target
11350 (error "Cannot find parent for new node"))
11351 (let ((file (nth 1 parent-target))
11352 (pos (nth 3 parent-target))
11353 level)
11354 (with-current-buffer (or (find-buffer-visiting file)
11355 (find-file-noselect file))
11356 (save-excursion
11357 (save-restriction
11358 (widen)
11359 (if pos
11360 (goto-char pos)
11361 (goto-char (point-max))
11362 (if (not (bolp)) (newline)))
11363 (when (looking-at org-outline-regexp)
11364 (setq level (funcall outline-level))
11365 (org-end-of-subtree t t))
11366 (org-back-over-empty-lines)
11367 (insert "\n" (make-string
11368 (if pos (org-get-valid-level level 1) 1) ?*)
11369 " " child "\n")
11370 (beginning-of-line 0)
11371 (list (concat (car parent-target) "/" child) file "" (point)))))))
11373 (defun org-olpath-completing-read (prompt collection &rest args)
11374 "Read an outline path like a file name."
11375 (let ((thetable collection)
11376 (org-completion-use-ido nil) ; does not work with ido.
11377 (org-completion-use-iswitchb nil)) ; or iswitchb
11378 (apply
11379 'org-icompleting-read prompt
11380 (lambda (string predicate &optional flag)
11381 (let (rtn r f (l (length string)))
11382 (cond
11383 ((eq flag nil)
11384 ;; try completion
11385 (try-completion string thetable))
11386 ((eq flag t)
11387 ;; all-completions
11388 (setq rtn (all-completions string thetable predicate))
11389 (mapcar
11390 (lambda (x)
11391 (setq r (substring x l))
11392 (if (string-match " ([^)]*)$" x)
11393 (setq f (match-string 0 x))
11394 (setq f ""))
11395 (if (string-match "/" r)
11396 (concat string (substring r 0 (match-end 0)) f)
11398 rtn))
11399 ((eq flag 'lambda)
11400 ;; exact match?
11401 (assoc string thetable)))))
11402 args)))
11404 ;;;; Dynamic blocks
11406 (defun org-find-dblock (name)
11407 "Find the first dynamic block with name NAME in the buffer.
11408 If not found, stay at current position and return nil."
11409 (let ((case-fold-search t) pos)
11410 (save-excursion
11411 (goto-char (point-min))
11412 (setq pos (and (re-search-forward
11413 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11414 (match-beginning 0))))
11415 (if pos (goto-char pos))
11416 pos))
11418 (defconst org-dblock-start-re
11419 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11420 "Matches the start line of a dynamic block, with parameters.")
11422 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11423 "Matches the end of a dynamic block.")
11425 (defun org-create-dblock (plist)
11426 "Create a dynamic block section, with parameters taken from PLIST.
11427 PLIST must contain a :name entry which is used as name of the block."
11428 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11429 (end-of-line 1)
11430 (newline))
11431 (let ((col (current-column))
11432 (name (plist-get plist :name)))
11433 (insert "#+BEGIN: " name)
11434 (while plist
11435 (if (eq (car plist) :name)
11436 (setq plist (cddr plist))
11437 (insert " " (prin1-to-string (pop plist)))))
11438 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11439 (beginning-of-line -2)))
11441 (defun org-prepare-dblock ()
11442 "Prepare dynamic block for refresh.
11443 This empties the block, puts the cursor at the insert position and returns
11444 the property list including an extra property :name with the block name."
11445 (unless (looking-at org-dblock-start-re)
11446 (error "Not at a dynamic block"))
11447 (let* ((begdel (1+ (match-end 0)))
11448 (name (org-no-properties (match-string 1)))
11449 (params (append (list :name name)
11450 (read (concat "(" (match-string 3) ")")))))
11451 (save-excursion
11452 (beginning-of-line 1)
11453 (skip-chars-forward " \t")
11454 (setq params (plist-put params :indentation-column (current-column))))
11455 (unless (re-search-forward org-dblock-end-re nil t)
11456 (error "Dynamic block not terminated"))
11457 (setq params
11458 (append params
11459 (list :content (buffer-substring
11460 begdel (match-beginning 0)))))
11461 (delete-region begdel (match-beginning 0))
11462 (goto-char begdel)
11463 (open-line 1)
11464 params))
11466 (defun org-map-dblocks (&optional command)
11467 "Apply COMMAND to all dynamic blocks in the current buffer.
11468 If COMMAND is not given, use `org-update-dblock'."
11469 (let ((cmd (or command 'org-update-dblock)))
11470 (save-excursion
11471 (goto-char (point-min))
11472 (while (re-search-forward org-dblock-start-re nil t)
11473 (goto-char (match-beginning 0))
11474 (save-excursion
11475 (condition-case nil
11476 (funcall cmd)
11477 (error (message "Error during update of dynamic block"))))
11478 (unless (re-search-forward org-dblock-end-re nil t)
11479 (error "Dynamic block not terminated"))))))
11481 (defun org-dblock-update (&optional arg)
11482 "User command for updating dynamic blocks.
11483 Update the dynamic block at point. With prefix ARG, update all dynamic
11484 blocks in the buffer."
11485 (interactive "P")
11486 (if arg
11487 (org-update-all-dblocks)
11488 (or (looking-at org-dblock-start-re)
11489 (org-beginning-of-dblock))
11490 (org-update-dblock)))
11492 (defun org-update-dblock ()
11493 "Update the dynamic block at point.
11494 This means to empty the block, parse for parameters and then call
11495 the correct writing function."
11496 (interactive)
11497 (save-window-excursion
11498 (let* ((pos (point))
11499 (line (org-current-line))
11500 (params (org-prepare-dblock))
11501 (name (plist-get params :name))
11502 (indent (plist-get params :indentation-column))
11503 (cmd (intern (concat "org-dblock-write:" name))))
11504 (message "Updating dynamic block `%s' at line %d..." name line)
11505 (funcall cmd params)
11506 (message "Updating dynamic block `%s' at line %d...done" name line)
11507 (goto-char pos)
11508 (when (and indent (> indent 0))
11509 (setq indent (make-string indent ?\ ))
11510 (save-excursion
11511 (org-beginning-of-dblock)
11512 (forward-line 1)
11513 (while (not (looking-at org-dblock-end-re))
11514 (insert indent)
11515 (beginning-of-line 2))
11516 (when (looking-at org-dblock-end-re)
11517 (and (looking-at "[ \t]+")
11518 (replace-match ""))
11519 (insert indent)))))))
11521 (defun org-beginning-of-dblock ()
11522 "Find the beginning of the dynamic block at point.
11523 Error if there is no such block at point."
11524 (let ((pos (point))
11525 beg)
11526 (end-of-line 1)
11527 (if (and (re-search-backward org-dblock-start-re nil t)
11528 (setq beg (match-beginning 0))
11529 (re-search-forward org-dblock-end-re nil t)
11530 (> (match-end 0) pos))
11531 (goto-char beg)
11532 (goto-char pos)
11533 (error "Not in a dynamic block"))))
11535 (defun org-update-all-dblocks ()
11536 "Update all dynamic blocks in the buffer.
11537 This function can be used in a hook."
11538 (interactive)
11539 (when (derived-mode-p 'org-mode)
11540 (org-map-dblocks 'org-update-dblock)))
11543 ;;;; Completion
11545 (defun org-get-export-keywords ()
11546 "Return a list of all currently understood export keywords.
11547 Export keywords include options, block names, attributes and
11548 keywords relative to each registered export back-end."
11549 (delq nil
11550 (let (keywords)
11551 (mapc
11552 (lambda (back-end)
11553 (let ((props (cdr back-end)))
11554 ;; Back-end name (for keywords, like #+LATEX:)
11555 (push (upcase (symbol-name (car back-end))) keywords)
11556 ;; Back-end options.
11557 (mapc (lambda (option) (push (cadr option) keywords))
11558 (plist-get (cdr back-end) :options-alist))))
11559 (org-bound-and-true-p org-export-registered-backends))
11560 keywords)))
11562 (defconst org-options-keywords
11563 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11564 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11565 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11566 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11567 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11569 (defcustom org-structure-template-alist
11570 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11571 "<src lang=\"?\">\n\n</src>")
11572 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11573 "<example>\n?\n</example>")
11574 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11575 "<quote>\n?\n</quote>")
11576 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11577 "<verse>\n?\n</verse>")
11578 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11579 "<verbatim>\n?\n</verbatim>")
11580 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11581 "<center>\n?\n</center>")
11582 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11583 "<literal style=\"latex\">\n?\n</literal>")
11584 ("L" "#+LaTeX: "
11585 "<literal style=\"latex\">?</literal>")
11586 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11587 "<literal style=\"html\">\n?\n</literal>")
11588 ("H" "#+HTML: "
11589 "<literal style=\"html\">?</literal>")
11590 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11591 ("A" "#+ASCII: ")
11592 ("i" "#+INDEX: ?"
11593 "#+INDEX: ?")
11594 ("I" "#+INCLUDE: %file ?"
11595 "<include file=%file markup=\"?\">"))
11596 "Structure completion elements.
11597 This is a list of abbreviation keys and values. The value gets inserted
11598 if you type `<' followed by the key and then press the completion key,
11599 usually `M-TAB'. %file will be replaced by a file name after prompting
11600 for the file using completion. The cursor will be placed at the position
11601 of the `?` in the template.
11602 There are two templates for each key, the first uses the original Org syntax,
11603 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11604 the default when the /org-mtags.el/ module has been loaded. See also the
11605 variable `org-mtags-prefer-muse-templates'."
11606 :group 'org-completion
11607 :type '(repeat
11608 (string :tag "Key")
11609 (string :tag "Template")
11610 (string :tag "Muse Template")))
11612 (defun org-try-structure-completion ()
11613 "Try to complete a structure template before point.
11614 This looks for strings like \"<e\" on an otherwise empty line and
11615 expands them."
11616 (let ((l (buffer-substring (point-at-bol) (point)))
11618 (when (and (looking-at "[ \t]*$")
11619 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11620 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11621 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11622 (match-beginning 1)) a)
11623 t)))
11625 (defun org-complete-expand-structure-template (start cell)
11626 "Expand a structure template."
11627 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11628 (rpl (nth (if musep 2 1) cell))
11629 (ind ""))
11630 (delete-region start (point))
11631 (when (string-match "\\`#\\+" rpl)
11632 (cond
11633 ((bolp))
11634 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11635 (setq ind (buffer-substring (point-at-bol) (point))))
11636 (t (newline))))
11637 (setq start (point))
11638 (if (string-match "%file" rpl)
11639 (setq rpl (replace-match
11640 (concat
11641 "\""
11642 (save-match-data
11643 (abbreviate-file-name (read-file-name "Include file: ")))
11644 "\"")
11645 t t rpl)))
11646 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11647 (concat "\n" ind)))
11648 (insert rpl)
11649 (if (re-search-backward "\\?" start t) (delete-char 1))))
11651 ;;;; TODO, DEADLINE, Comments
11653 (defun org-toggle-comment ()
11654 "Change the COMMENT state of an entry."
11655 (interactive)
11656 (save-excursion
11657 (org-back-to-heading)
11658 (let (case-fold-search)
11659 (cond
11660 ((looking-at (format org-heading-keyword-regexp-format
11661 org-comment-string))
11662 (goto-char (match-end 1))
11663 (looking-at (concat " +" org-comment-string))
11664 (replace-match "" t t)
11665 (when (eolp) (insert " ")))
11666 ((looking-at org-outline-regexp)
11667 (goto-char (match-end 0))
11668 (insert org-comment-string " "))))))
11670 (defvar org-last-todo-state-is-todo nil
11671 "This is non-nil when the last TODO state change led to a TODO state.
11672 If the last change removed the TODO tag or switched to DONE, then
11673 this is nil.")
11675 (defvar org-setting-tags nil) ; dynamically skipped
11677 (defvar org-todo-setup-filter-hook nil
11678 "Hook for functions that pre-filter todo specs.
11679 Each function takes a todo spec and returns either nil or the spec
11680 transformed into canonical form." )
11682 (defvar org-todo-get-default-hook nil
11683 "Hook for functions that get a default item for todo.
11684 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11685 nil or a string to be used for the todo mark." )
11687 (defvar org-agenda-headline-snapshot-before-repeat)
11689 (defun org-current-effective-time ()
11690 "Return current time adjusted for `org-extend-today-until' variable."
11691 (let* ((ct (org-current-time))
11692 (dct (decode-time ct))
11693 (ct1
11694 (cond
11695 (org-use-last-clock-out-time-as-effective-time
11696 (or (org-clock-get-last-clock-out-time) ct))
11697 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11698 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11699 (t ct))))
11700 ct1))
11702 (defun org-todo-yesterday (&optional arg)
11703 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11704 (interactive "P")
11705 (if (eq major-mode 'org-agenda-mode)
11706 (apply 'org-agenda-todo-yesterday arg)
11707 (let* ((hour (third (decode-time
11708 (org-current-time))))
11709 (org-extend-today-until (1+ hour)))
11710 (org-todo arg))))
11712 (defvar org-block-entry-blocking ""
11713 "First entry preventing the TODO state change.")
11715 (defun org-todo (&optional arg)
11716 "Change the TODO state of an item.
11717 The state of an item is given by a keyword at the start of the heading,
11718 like
11719 *** TODO Write paper
11720 *** DONE Call mom
11722 The different keywords are specified in the variable `org-todo-keywords'.
11723 By default the available states are \"TODO\" and \"DONE\".
11724 So for this example: when the item starts with TODO, it is changed to DONE.
11725 When it starts with DONE, the DONE is removed. And when neither TODO nor
11726 DONE are present, add TODO at the beginning of the heading.
11728 With \\[universal-argument] prefix arg, use completion to determine the new \
11729 state.
11730 With numeric prefix arg, switch to that state.
11731 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11732 keywords (nextset).
11733 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11734 With a numeric prefix arg of 0, inhibit note taking for the change.
11736 For calling through lisp, arg is also interpreted in the following way:
11737 'none -> empty state
11738 \"\"(empty string) -> switch to empty state
11739 'done -> switch to DONE
11740 'nextset -> switch to the next set of keywords
11741 'previousset -> switch to the previous set of keywords
11742 \"WAITING\" -> switch to the specified keyword, but only if it
11743 really is a member of `org-todo-keywords'."
11744 (interactive "P")
11745 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11746 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11747 'region-start-level 'region))
11748 org-loop-over-headlines-in-active-region)
11749 (org-map-entries
11750 `(org-todo ,arg)
11751 org-loop-over-headlines-in-active-region
11752 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11753 (if (equal arg '(16)) (setq arg 'nextset))
11754 (let ((org-blocker-hook org-blocker-hook)
11755 commentp
11756 case-fold-search)
11757 (when (equal arg '(64))
11758 (setq arg nil org-blocker-hook nil))
11759 (when (and org-blocker-hook
11760 (or org-inhibit-blocking
11761 (org-entry-get nil "NOBLOCKING")))
11762 (setq org-blocker-hook nil))
11763 (save-excursion
11764 (catch 'exit
11765 (org-back-to-heading t)
11766 (when (looking-at (concat "^\\*+ " org-comment-string))
11767 (org-toggle-comment)
11768 (setq commentp t))
11769 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11770 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11771 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11772 (let* ((match-data (match-data))
11773 (startpos (point-at-bol))
11774 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11775 (org-log-done org-log-done)
11776 (org-log-repeat org-log-repeat)
11777 (org-todo-log-states org-todo-log-states)
11778 (org-inhibit-logging
11779 (if (equal arg 0)
11780 (progn (setq arg nil) 'note) org-inhibit-logging))
11781 (this (match-string 1))
11782 (hl-pos (match-beginning 0))
11783 (head (org-get-todo-sequence-head this))
11784 (ass (assoc head org-todo-kwd-alist))
11785 (interpret (nth 1 ass))
11786 (done-word (nth 3 ass))
11787 (final-done-word (nth 4 ass))
11788 (org-last-state (or this ""))
11789 (completion-ignore-case t)
11790 (member (member this org-todo-keywords-1))
11791 (tail (cdr member))
11792 (org-state (cond
11793 ((and org-todo-key-trigger
11794 (or (and (equal arg '(4))
11795 (eq org-use-fast-todo-selection 'prefix))
11796 (and (not arg) org-use-fast-todo-selection
11797 (not (eq org-use-fast-todo-selection
11798 'prefix)))))
11799 ;; Use fast selection
11800 (org-fast-todo-selection))
11801 ((and (equal arg '(4))
11802 (or (not org-use-fast-todo-selection)
11803 (not org-todo-key-trigger)))
11804 ;; Read a state with completion
11805 (org-icompleting-read
11806 "State: " (mapcar (lambda(x) (list x))
11807 org-todo-keywords-1)
11808 nil t))
11809 ((eq arg 'right)
11810 (if this
11811 (if tail (car tail) nil)
11812 (car org-todo-keywords-1)))
11813 ((eq arg 'left)
11814 (if (equal member org-todo-keywords-1)
11816 (if this
11817 (nth (- (length org-todo-keywords-1)
11818 (length tail) 2)
11819 org-todo-keywords-1)
11820 (org-last org-todo-keywords-1))))
11821 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11822 (setq arg nil))) ; hack to fall back to cycling
11823 (arg
11824 ;; user or caller requests a specific state
11825 (cond
11826 ((equal arg "") nil)
11827 ((eq arg 'none) nil)
11828 ((eq arg 'done) (or done-word (car org-done-keywords)))
11829 ((eq arg 'nextset)
11830 (or (car (cdr (member head org-todo-heads)))
11831 (car org-todo-heads)))
11832 ((eq arg 'previousset)
11833 (let ((org-todo-heads (reverse org-todo-heads)))
11834 (or (car (cdr (member head org-todo-heads)))
11835 (car org-todo-heads))))
11836 ((car (member arg org-todo-keywords-1)))
11837 ((stringp arg)
11838 (error "State `%s' not valid in this file" arg))
11839 ((nth (1- (prefix-numeric-value arg))
11840 org-todo-keywords-1))))
11841 ((null member) (or head (car org-todo-keywords-1)))
11842 ((equal this final-done-word) nil) ;; -> make empty
11843 ((null tail) nil) ;; -> first entry
11844 ((memq interpret '(type priority))
11845 (if (eq this-command last-command)
11846 (car tail)
11847 (if (> (length tail) 0)
11848 (or done-word (car org-done-keywords))
11849 nil)))
11851 (car tail))))
11852 (org-state (or
11853 (run-hook-with-args-until-success
11854 'org-todo-get-default-hook org-state org-last-state)
11855 org-state))
11856 (next (if org-state (concat " " org-state " ") " "))
11857 (change-plist (list :type 'todo-state-change :from this :to org-state
11858 :position startpos))
11859 dolog now-done-p)
11860 (when org-blocker-hook
11861 (setq org-last-todo-state-is-todo
11862 (not (member this org-done-keywords)))
11863 (unless (save-excursion
11864 (save-match-data
11865 (org-with-wide-buffer
11866 (run-hook-with-args-until-failure
11867 'org-blocker-hook change-plist))))
11868 (if (org-called-interactively-p 'interactive)
11869 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11870 this org-state org-block-entry-blocking)
11871 ;; fail silently
11872 (message "TODO state change from %s to %s blocked (by \"%s\")"
11873 this org-state org-block-entry-blocking)
11874 (throw 'exit nil))))
11875 (store-match-data match-data)
11876 (replace-match next t t)
11877 (unless (pos-visible-in-window-p hl-pos)
11878 (message "TODO state changed to %s" (org-trim next)))
11879 (unless head
11880 (setq head (org-get-todo-sequence-head org-state)
11881 ass (assoc head org-todo-kwd-alist)
11882 interpret (nth 1 ass)
11883 done-word (nth 3 ass)
11884 final-done-word (nth 4 ass)))
11885 (when (memq arg '(nextset previousset))
11886 (message "Keyword-Set %d/%d: %s"
11887 (- (length org-todo-sets) -1
11888 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11889 (length org-todo-sets)
11890 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11891 (setq org-last-todo-state-is-todo
11892 (not (member org-state org-done-keywords)))
11893 (setq now-done-p (and (member org-state org-done-keywords)
11894 (not (member this org-done-keywords))))
11895 (and logging (org-local-logging logging))
11896 (when (and (or org-todo-log-states org-log-done)
11897 (not (eq org-inhibit-logging t))
11898 (not (memq arg '(nextset previousset))))
11899 ;; we need to look at recording a time and note
11900 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11901 (nth 2 (assoc this org-todo-log-states))))
11902 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11903 (setq dolog 'time))
11904 (when (and org-state
11905 (member org-state org-not-done-keywords)
11906 (not (member this org-not-done-keywords)))
11907 ;; This is now a todo state and was not one before
11908 ;; If there was a CLOSED time stamp, get rid of it.
11909 (org-add-planning-info nil nil 'closed))
11910 (when (and now-done-p org-log-done)
11911 ;; It is now done, and it was not done before
11912 (org-add-planning-info 'closed (org-current-effective-time))
11913 (if (and (not dolog) (eq 'note org-log-done))
11914 (org-add-log-setup 'done org-state this 'findpos 'note)))
11915 (when (and org-state dolog)
11916 ;; This is a non-nil state, and we need to log it
11917 (org-add-log-setup 'state org-state this 'findpos dolog)))
11918 ;; Fixup tag positioning
11919 (org-todo-trigger-tag-changes org-state)
11920 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11921 (when org-provide-todo-statistics
11922 (org-update-parent-todo-statistics))
11923 (run-hooks 'org-after-todo-state-change-hook)
11924 (if (and arg (not (member org-state org-done-keywords)))
11925 (setq head (org-get-todo-sequence-head org-state)))
11926 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11927 ;; Do we need to trigger a repeat?
11928 (when now-done-p
11929 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11930 ;; This is for the agenda, take a snapshot of the headline.
11931 (save-match-data
11932 (setq org-agenda-headline-snapshot-before-repeat
11933 (org-get-heading))))
11934 (org-auto-repeat-maybe org-state))
11935 ;; Fixup cursor location if close to the keyword
11936 (if (and (outline-on-heading-p)
11937 (not (bolp))
11938 (save-excursion (beginning-of-line 1)
11939 (looking-at org-todo-line-regexp))
11940 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11941 (progn
11942 (goto-char (or (match-end 2) (match-end 1)))
11943 (and (looking-at " ") (just-one-space))))
11944 (when org-trigger-hook
11945 (save-excursion
11946 (run-hook-with-args 'org-trigger-hook change-plist)))
11947 (when commentp (org-toggle-comment))))))))
11949 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11950 "Block turning an entry into a TODO, using the hierarchy.
11951 This checks whether the current task should be blocked from state
11952 changes. Such blocking occurs when:
11954 1. The task has children which are not all in a completed state.
11956 2. A task has a parent with the property :ORDERED:, and there
11957 are siblings prior to the current task with incomplete
11958 status.
11960 3. The parent of the task is blocked because it has siblings that should
11961 be done first, or is child of a block grandparent TODO entry."
11963 (if (not org-enforce-todo-dependencies)
11964 t ; if locally turned off don't block
11965 (catch 'dont-block
11966 ;; If this is not a todo state change, or if this entry is already DONE,
11967 ;; do not block
11968 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11969 (member (plist-get change-plist :from)
11970 (cons 'done org-done-keywords))
11971 (member (plist-get change-plist :to)
11972 (cons 'todo org-not-done-keywords))
11973 (not (plist-get change-plist :to)))
11974 (throw 'dont-block t))
11975 ;; If this task has children, and any are undone, it's blocked
11976 (save-excursion
11977 (org-back-to-heading t)
11978 (let ((this-level (funcall outline-level)))
11979 (outline-next-heading)
11980 (let ((child-level (funcall outline-level)))
11981 (while (and (not (eobp))
11982 (> child-level this-level))
11983 ;; this todo has children, check whether they are all
11984 ;; completed
11985 (if (and (not (org-entry-is-done-p))
11986 (org-entry-is-todo-p))
11987 (progn (setq org-block-entry-blocking (org-get-heading))
11988 (throw 'dont-block nil)))
11989 (outline-next-heading)
11990 (setq child-level (funcall outline-level))))))
11991 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11992 ;; any previous siblings are undone, it's blocked
11993 (save-excursion
11994 (org-back-to-heading t)
11995 (let* ((pos (point))
11996 (parent-pos (and (org-up-heading-safe) (point))))
11997 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11998 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11999 (forward-line 1)
12000 (re-search-forward org-not-done-heading-regexp pos t))
12001 (setq org-block-entry-blocking (match-string 0))
12002 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12003 ;; Search further up the hierarchy, to see if an ancestor is blocked
12004 (while t
12005 (goto-char parent-pos)
12006 (if (not (looking-at org-not-done-heading-regexp))
12007 (throw 'dont-block t)) ; do not block, parent is not a TODO
12008 (setq pos (point))
12009 (setq parent-pos (and (org-up-heading-safe) (point)))
12010 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12011 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12012 (forward-line 1)
12013 (re-search-forward org-not-done-heading-regexp pos t)
12014 (setq org-block-entry-blocking (org-get-heading)))
12015 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12017 (defcustom org-track-ordered-property-with-tag nil
12018 "Should the ORDERED property also be shown as a tag?
12019 The ORDERED property decides if an entry should require subtasks to be
12020 completed in sequence. Since a property is not very visible, setting
12021 this option means that toggling the ORDERED property with the command
12022 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12023 not relevant for the behavior, but it makes things more visible.
12025 Note that toggling the tag with tags commands will not change the property
12026 and therefore not influence behavior!
12028 This can be t, meaning the tag ORDERED should be used, It can also be a
12029 string to select a different tag for this task."
12030 :group 'org-todo
12031 :type '(choice
12032 (const :tag "No tracking" nil)
12033 (const :tag "Track with ORDERED tag" t)
12034 (string :tag "Use other tag")))
12036 (defun org-toggle-ordered-property ()
12037 "Toggle the ORDERED property of the current entry.
12038 For better visibility, you can track the value of this property with a tag.
12039 See variable `org-track-ordered-property-with-tag'."
12040 (interactive)
12041 (let* ((t1 org-track-ordered-property-with-tag)
12042 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12043 (save-excursion
12044 (org-back-to-heading)
12045 (if (org-entry-get nil "ORDERED")
12046 (progn
12047 (org-delete-property "ORDERED")
12048 (and tag (org-toggle-tag tag 'off))
12049 (message "Subtasks can be completed in arbitrary order"))
12050 (org-entry-put nil "ORDERED" "t")
12051 (and tag (org-toggle-tag tag 'on))
12052 (message "Subtasks must be completed in sequence")))))
12054 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12055 (defun org-block-todo-from-checkboxes (change-plist)
12056 "Block turning an entry into a TODO, using checkboxes.
12057 This checks whether the current task should be blocked from state
12058 changes because there are unchecked boxes in this entry."
12059 (if (not org-enforce-todo-checkbox-dependencies)
12060 t ; if locally turned off don't block
12061 (catch 'dont-block
12062 ;; If this is not a todo state change, or if this entry is already DONE,
12063 ;; do not block
12064 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12065 (member (plist-get change-plist :from)
12066 (cons 'done org-done-keywords))
12067 (member (plist-get change-plist :to)
12068 (cons 'todo org-not-done-keywords))
12069 (not (plist-get change-plist :to)))
12070 (throw 'dont-block t))
12071 ;; If this task has checkboxes that are not checked, it's blocked
12072 (save-excursion
12073 (org-back-to-heading t)
12074 (let ((beg (point)) end)
12075 (outline-next-heading)
12076 (setq end (point))
12077 (goto-char beg)
12078 (if (org-list-search-forward
12079 (concat (org-item-beginning-re)
12080 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12081 "\\[[- ]\\]")
12082 end t)
12083 (progn
12084 (if (boundp 'org-blocked-by-checkboxes)
12085 (setq org-blocked-by-checkboxes t))
12086 (throw 'dont-block nil)))))
12087 t))) ; do not block
12089 (defun org-entry-blocked-p ()
12090 "Is the current entry blocked?"
12091 (org-with-buffer-modified-unmodified
12092 (if (org-entry-get nil "NOBLOCKING")
12093 nil ;; Never block this entry
12094 (not
12095 (run-hook-with-args-until-failure
12096 'org-blocker-hook
12097 (list :type 'todo-state-change
12098 :position (point)
12099 :from 'todo
12100 :to 'done))))))
12102 (defun org-update-statistics-cookies (all)
12103 "Update the statistics cookie, either from TODO or from checkboxes.
12104 This should be called with the cursor in a line with a statistics cookie."
12105 (interactive "P")
12106 (if all
12107 (progn
12108 (org-update-checkbox-count 'all)
12109 (org-map-entries 'org-update-parent-todo-statistics))
12110 (if (not (org-at-heading-p))
12111 (org-update-checkbox-count)
12112 (let ((pos (point-marker))
12113 end l1 l2)
12114 (ignore-errors (org-back-to-heading t))
12115 (if (not (org-at-heading-p))
12116 (org-update-checkbox-count)
12117 (setq l1 (org-outline-level))
12118 (setq end (save-excursion
12119 (outline-next-heading)
12120 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12121 (point)))
12122 (if (and (save-excursion
12123 (re-search-forward
12124 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12125 (not (save-excursion (re-search-forward
12126 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12127 (org-update-checkbox-count)
12128 (if (and l2 (> l2 l1))
12129 (progn
12130 (goto-char end)
12131 (org-update-parent-todo-statistics))
12132 (goto-char pos)
12133 (beginning-of-line 1)
12134 (while (re-search-forward
12135 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12136 (point-at-eol) t)
12137 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12138 (goto-char pos)
12139 (move-marker pos nil)))))
12141 (defvar org-entry-property-inherited-from) ;; defined below
12142 (defun org-update-parent-todo-statistics ()
12143 "Update any statistics cookie in the parent of the current headline.
12144 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12145 the entire subtree and this will travel up the hierarchy and update
12146 statistics everywhere."
12147 (let* ((prop (save-excursion (org-up-heading-safe)
12148 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12149 (recursive (or (not org-hierarchical-todo-statistics)
12150 (and prop (string-match "\\<recursive\\>" prop))))
12151 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12153 (first t)
12154 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12155 level ltoggle l1 new ndel
12156 (cnt-all 0) (cnt-done 0) is-percent kwd
12157 checkbox-beg ov ovs ove cookie-present)
12158 (catch 'exit
12159 (save-excursion
12160 (beginning-of-line 1)
12161 (setq ltoggle (funcall outline-level))
12162 ;; Three situations are to consider:
12164 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12165 ;; to the top-level ancestor on the headline;
12167 ;; 2. If parent has "recursive" property, repeat up to the
12168 ;; headline setting that property, taking inheritance into
12169 ;; account;
12171 ;; 3. Else, move up to direct parent and proceed only once.
12172 (while (and (setq level (org-up-heading-safe))
12173 (or recursive first)
12174 (>= (point) lim))
12175 (setq first nil cookie-present nil)
12176 (unless (and level
12177 (not (string-match
12178 "\\<checkbox\\>"
12179 (downcase (or (org-entry-get nil "COOKIE_DATA")
12180 "")))))
12181 (throw 'exit nil))
12182 (while (re-search-forward box-re (point-at-eol) t)
12183 (setq cnt-all 0 cnt-done 0 cookie-present t)
12184 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12185 (save-match-data
12186 (unless (outline-next-heading) (throw 'exit nil))
12187 (while (and (looking-at org-complex-heading-regexp)
12188 (> (setq l1 (length (match-string 1))) level))
12189 (setq kwd (and (or recursive (= l1 ltoggle))
12190 (match-string 2)))
12191 (if (or (eq org-provide-todo-statistics 'all-headlines)
12192 (and (listp org-provide-todo-statistics)
12193 (or (member kwd org-provide-todo-statistics)
12194 (member kwd org-done-keywords))))
12195 (setq cnt-all (1+ cnt-all))
12196 (if (eq org-provide-todo-statistics t)
12197 (and kwd (setq cnt-all (1+ cnt-all)))))
12198 (and (member kwd org-done-keywords)
12199 (setq cnt-done (1+ cnt-done)))
12200 (outline-next-heading)))
12201 (setq new
12202 (if is-percent
12203 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12204 (format "[%d/%d]" cnt-done cnt-all))
12205 ndel (- (match-end 0) checkbox-beg))
12206 ;; handle overlays when updating cookie from column view
12207 (when (setq ov (car (overlays-at checkbox-beg)))
12208 (setq ovs (overlay-start ov) ove (overlay-end ov))
12209 (delete-overlay ov))
12210 (goto-char checkbox-beg)
12211 (insert new)
12212 (delete-region (point) (+ (point) ndel))
12213 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12214 (when ov (move-overlay ov ovs ove)))
12215 (when cookie-present
12216 (run-hook-with-args 'org-after-todo-statistics-hook
12217 cnt-done (- cnt-all cnt-done))))))
12218 (run-hooks 'org-todo-statistics-hook)))
12220 (defvar org-after-todo-statistics-hook nil
12221 "Hook that is called after a TODO statistics cookie has been updated.
12222 Each function is called with two arguments: the number of not-done entries
12223 and the number of done entries.
12225 For example, the following function, when added to this hook, will switch
12226 an entry to DONE when all children are done, and back to TODO when new
12227 entries are set to a TODO status. Note that this hook is only called
12228 when there is a statistics cookie in the headline!
12230 (defun org-summary-todo (n-done n-not-done)
12231 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12232 (let (org-log-done org-log-states) ; turn off logging
12233 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12236 (defvar org-todo-statistics-hook nil
12237 "Hook that is run whenever Org thinks TODO statistics should be updated.
12238 This hook runs even if there is no statistics cookie present, in which case
12239 `org-after-todo-statistics-hook' would not run.")
12241 (defun org-todo-trigger-tag-changes (state)
12242 "Apply the changes defined in `org-todo-state-tags-triggers'."
12243 (let ((l org-todo-state-tags-triggers)
12244 changes)
12245 (when (or (not state) (equal state ""))
12246 (setq changes (append changes (cdr (assoc "" l)))))
12247 (when (and (stringp state) (> (length state) 0))
12248 (setq changes (append changes (cdr (assoc state l)))))
12249 (when (member state org-not-done-keywords)
12250 (setq changes (append changes (cdr (assoc 'todo l)))))
12251 (when (member state org-done-keywords)
12252 (setq changes (append changes (cdr (assoc 'done l)))))
12253 (dolist (c changes)
12254 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12256 (defun org-local-logging (value)
12257 "Get logging settings from a property VALUE."
12258 (let* (words w a)
12259 ;; directly set the variables, they are already local.
12260 (setq org-log-done nil
12261 org-log-repeat nil
12262 org-todo-log-states nil)
12263 (setq words (org-split-string value))
12264 (while (setq w (pop words))
12265 (cond
12266 ((setq a (assoc w org-startup-options))
12267 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12268 (set (nth 1 a) (nth 2 a))))
12269 ((setq a (org-extract-log-state-settings w))
12270 (and (member (car a) org-todo-keywords-1)
12271 (push a org-todo-log-states)))))))
12273 (defun org-get-todo-sequence-head (kwd)
12274 "Return the head of the TODO sequence to which KWD belongs.
12275 If KWD is not set, check if there is a text property remembering the
12276 right sequence."
12277 (let (p)
12278 (cond
12279 ((not kwd)
12280 (or (get-text-property (point-at-bol) 'org-todo-head)
12281 (progn
12282 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12283 nil (point-at-eol)))
12284 (get-text-property p 'org-todo-head))))
12285 ((not (member kwd org-todo-keywords-1))
12286 (car org-todo-keywords-1))
12287 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12289 (defun org-fast-todo-selection ()
12290 "Fast TODO keyword selection with single keys.
12291 Returns the new TODO keyword, or nil if no state change should occur."
12292 (let* ((fulltable org-todo-key-alist)
12293 (done-keywords org-done-keywords) ;; needed for the faces.
12294 (maxlen (apply 'max (mapcar
12295 (lambda (x)
12296 (if (stringp (car x)) (string-width (car x)) 0))
12297 fulltable)))
12298 (expert nil)
12299 (fwidth (+ maxlen 3 1 3))
12300 (ncol (/ (- (window-width) 4) fwidth))
12301 tg cnt e c tbl
12302 groups ingroup)
12303 (save-excursion
12304 (save-window-excursion
12305 (if expert
12306 (set-buffer (get-buffer-create " *Org todo*"))
12307 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12308 (erase-buffer)
12309 (org-set-local 'org-done-keywords done-keywords)
12310 (setq tbl fulltable cnt 0)
12311 (while (setq e (pop tbl))
12312 (cond
12313 ((equal e '(:startgroup))
12314 (push '() groups) (setq ingroup t)
12315 (when (not (= cnt 0))
12316 (setq cnt 0)
12317 (insert "\n"))
12318 (insert "{ "))
12319 ((equal e '(:endgroup))
12320 (setq ingroup nil cnt 0)
12321 (insert "}\n"))
12322 ((equal e '(:newline))
12323 (when (not (= cnt 0))
12324 (setq cnt 0)
12325 (insert "\n")
12326 (setq e (car tbl))
12327 (while (equal (car tbl) '(:newline))
12328 (insert "\n")
12329 (setq tbl (cdr tbl)))))
12331 (setq tg (car e) c (cdr e))
12332 (if ingroup (push tg (car groups)))
12333 (setq tg (org-add-props tg nil 'face
12334 (org-get-todo-face tg)))
12335 (if (and (= cnt 0) (not ingroup)) (insert " "))
12336 (insert "[" c "] " tg (make-string
12337 (- fwidth 4 (length tg)) ?\ ))
12338 (when (= (setq cnt (1+ cnt)) ncol)
12339 (insert "\n")
12340 (if ingroup (insert " "))
12341 (setq cnt 0)))))
12342 (insert "\n")
12343 (goto-char (point-min))
12344 (if (not expert) (org-fit-window-to-buffer))
12345 (message "[a-z..]:Set [SPC]:clear")
12346 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12347 (cond
12348 ((or (= c ?\C-g)
12349 (and (= c ?q) (not (rassoc c fulltable))))
12350 (setq quit-flag t))
12351 ((= c ?\ ) nil)
12352 ((setq e (rassoc c fulltable) tg (car e))
12354 (t (setq quit-flag t)))))))
12356 (defun org-entry-is-todo-p ()
12357 (member (org-get-todo-state) org-not-done-keywords))
12359 (defun org-entry-is-done-p ()
12360 (member (org-get-todo-state) org-done-keywords))
12362 (defun org-get-todo-state ()
12363 (save-excursion
12364 (org-back-to-heading t)
12365 (and (looking-at org-todo-line-regexp)
12366 (match-end 2)
12367 (match-string 2))))
12369 (defun org-at-date-range-p (&optional inactive-ok)
12370 "Is the cursor inside a date range?"
12371 (interactive)
12372 (save-excursion
12373 (catch 'exit
12374 (let ((pos (point)))
12375 (skip-chars-backward "^[<\r\n")
12376 (skip-chars-backward "<[")
12377 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12378 (>= (match-end 0) pos)
12379 (throw 'exit t))
12380 (skip-chars-backward "^<[\r\n")
12381 (skip-chars-backward "<[")
12382 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12383 (>= (match-end 0) pos)
12384 (throw 'exit t)))
12385 nil)))
12387 (defun org-get-repeat (&optional tagline)
12388 "Check if there is a deadline/schedule with repeater in this entry."
12389 (save-match-data
12390 (save-excursion
12391 (org-back-to-heading t)
12392 (and (re-search-forward (if tagline
12393 (concat tagline "\\s-*" org-repeat-re)
12394 org-repeat-re)
12395 (org-entry-end-position) t)
12396 (match-string-no-properties 1)))))
12398 (defvar org-last-changed-timestamp)
12399 (defvar org-last-inserted-timestamp)
12400 (defvar org-log-post-message)
12401 (defvar org-log-note-purpose)
12402 (defvar org-log-note-how)
12403 (defvar org-log-note-extra)
12404 (defun org-auto-repeat-maybe (done-word)
12405 "Check if the current headline contains a repeated deadline/schedule.
12406 If yes, set TODO state back to what it was and change the base date
12407 of repeating deadline/scheduled time stamps to new date.
12408 This function is run automatically after each state change to a DONE state."
12409 ;; last-state is dynamically scoped into this function
12410 (let* ((repeat (org-get-repeat))
12411 (aa (assoc org-last-state org-todo-kwd-alist))
12412 (interpret (nth 1 aa))
12413 (head (nth 2 aa))
12414 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12415 (msg "Entry repeats: ")
12416 (org-log-done nil)
12417 (org-todo-log-states nil)
12418 re type n what ts time to-state)
12419 (when repeat
12420 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12421 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12422 org-todo-repeat-to-state))
12423 (unless (and to-state (member to-state org-todo-keywords-1))
12424 (setq to-state (if (eq interpret 'type) org-last-state head)))
12425 (org-todo to-state)
12426 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12427 (org-entry-put nil "LAST_REPEAT" (format-time-string
12428 (org-time-stamp-format t t))))
12429 (when org-log-repeat
12430 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12431 (memq 'org-add-log-note post-command-hook))
12432 ;; OK, we are already setup for some record
12433 (if (eq org-log-repeat 'note)
12434 ;; make sure we take a note, not only a time stamp
12435 (setq org-log-note-how 'note))
12436 ;; Set up for taking a record
12437 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12438 org-last-state
12439 'findpos org-log-repeat)))
12440 (org-back-to-heading t)
12441 (org-add-planning-info nil nil 'closed)
12442 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12443 org-deadline-time-regexp "\\)\\|\\("
12444 org-ts-regexp "\\)"))
12445 (while (re-search-forward
12446 re (save-excursion (outline-next-heading) (point)) t)
12447 (setq type (if (match-end 1) org-scheduled-string
12448 (if (match-end 3) org-deadline-string "Plain:"))
12449 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12450 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12451 (setq n (string-to-number (match-string 2 ts))
12452 what (match-string 3 ts))
12453 (if (equal what "w") (setq n (* n 7) what "d"))
12454 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12455 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12456 ;; Preparation, see if we need to modify the start date for the change
12457 (when (match-end 1)
12458 (setq time (save-match-data (org-time-string-to-time ts)))
12459 (cond
12460 ((equal (match-string 1 ts) ".")
12461 ;; Shift starting date to today
12462 (org-timestamp-change
12463 (- (org-today) (time-to-days time))
12464 'day))
12465 ((equal (match-string 1 ts) "+")
12466 (let ((nshiftmax 10) (nshift 0))
12467 (while (or (= nshift 0)
12468 (<= (time-to-days time)
12469 (time-to-days (current-time))))
12470 (when (= (incf nshift) nshiftmax)
12471 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12472 (error "Abort")))
12473 (org-timestamp-change n (cdr (assoc what whata)))
12474 (org-at-timestamp-p t)
12475 (setq ts (match-string 1))
12476 (setq time (save-match-data (org-time-string-to-time ts)))))
12477 (org-timestamp-change (- n) (cdr (assoc what whata)))
12478 ;; rematch, so that we have everything in place for the real shift
12479 (org-at-timestamp-p t)
12480 (setq ts (match-string 1))
12481 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12482 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12483 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12484 (setq org-log-post-message msg)
12485 (message "%s" msg))))
12487 (defun org-show-todo-tree (arg)
12488 "Make a compact tree which shows all headlines marked with TODO.
12489 The tree will show the lines where the regexp matches, and all higher
12490 headlines above the match.
12491 With a \\[universal-argument] prefix, prompt for a regexp to match.
12492 With a numeric prefix N, construct a sparse tree for the Nth element
12493 of `org-todo-keywords-1'."
12494 (interactive "P")
12495 (let ((case-fold-search nil)
12496 (kwd-re
12497 (cond ((null arg) org-not-done-regexp)
12498 ((equal arg '(4))
12499 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12500 (mapcar 'list org-todo-keywords-1))))
12501 (concat "\\("
12502 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12503 "\\)\\>")))
12504 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12505 (regexp-quote (nth (1- (prefix-numeric-value arg))
12506 org-todo-keywords-1)))
12507 (t (error "Invalid prefix argument: %s" arg)))))
12508 (message "%d TODO entries found"
12509 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12511 (defun org-deadline (&optional arg time)
12512 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12513 With one universal prefix argument, remove any deadline from the item.
12514 With two universal prefix arguments, prompt for a warning delay.
12515 With argument TIME, set the deadline at the corresponding date. TIME
12516 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12517 (interactive "P")
12518 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12519 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12520 'region-start-level 'region))
12521 org-loop-over-headlines-in-active-region)
12522 (org-map-entries
12523 `(org-deadline ',arg ,time)
12524 org-loop-over-headlines-in-active-region
12525 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12526 (let* ((old-date (org-entry-get nil "DEADLINE"))
12527 (repeater (and old-date
12528 (string-match
12529 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12530 old-date)
12531 (match-string 1 old-date))))
12532 (cond
12533 ((equal arg '(4))
12534 (when (and old-date org-log-redeadline)
12535 (org-add-log-setup 'deldeadline nil old-date 'findpos
12536 org-log-redeadline))
12537 (org-remove-timestamp-with-keyword org-deadline-string)
12538 (message "Item no longer has a deadline."))
12539 ((equal arg '(16))
12540 (save-excursion
12541 (if (re-search-forward
12542 org-deadline-time-regexp
12543 (save-excursion (outline-next-heading) (point)) t)
12544 (let* ((rpl0 (match-string 1))
12545 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12546 (replace-match
12547 (concat org-deadline-string
12548 " <" rpl
12549 (format " -%dd" (abs
12550 (- (time-to-days
12551 (save-match-data
12552 (org-read-date nil t nil "Warn starting from")))
12553 (time-to-days nil))))
12554 ">") t t))
12555 (user-error "No deadline information to update"))))
12557 (org-add-planning-info 'deadline time 'closed)
12558 (when (and old-date org-log-redeadline
12559 (not (equal old-date
12560 (substring org-last-inserted-timestamp 1 -1))))
12561 (org-add-log-setup 'redeadline nil old-date 'findpos
12562 org-log-redeadline))
12563 (when repeater
12564 (save-excursion
12565 (org-back-to-heading t)
12566 (when (re-search-forward (concat org-deadline-string " "
12567 org-last-inserted-timestamp)
12568 (save-excursion
12569 (outline-next-heading) (point)) t)
12570 (goto-char (1- (match-end 0)))
12571 (insert " " repeater)
12572 (setq org-last-inserted-timestamp
12573 (concat (substring org-last-inserted-timestamp 0 -1)
12574 " " repeater
12575 (substring org-last-inserted-timestamp -1))))))
12576 (message "Deadline on %s" org-last-inserted-timestamp))))))
12578 (defun org-schedule (&optional arg time)
12579 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12580 With one universal prefix argument, remove any scheduling date from the item.
12581 With two universal prefix arguments, prompt for a delay cookie.
12582 With argument TIME, scheduled at the corresponding date. TIME can
12583 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12584 (interactive "P")
12585 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12586 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12587 'region-start-level 'region))
12588 org-loop-over-headlines-in-active-region)
12589 (org-map-entries
12590 `(org-schedule ',arg ,time)
12591 org-loop-over-headlines-in-active-region
12592 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12593 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12594 (repeater (and old-date
12595 (string-match
12596 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12597 old-date)
12598 (match-string 1 old-date))))
12599 (cond
12600 ((equal arg '(4))
12601 (progn
12602 (when (and old-date org-log-reschedule)
12603 (org-add-log-setup 'delschedule nil old-date 'findpos
12604 org-log-reschedule))
12605 (org-remove-timestamp-with-keyword org-scheduled-string)
12606 (message "Item is no longer scheduled.")))
12607 ((equal arg '(16))
12608 (save-excursion
12609 (if (re-search-forward
12610 org-scheduled-time-regexp
12611 (save-excursion (outline-next-heading) (point)) t)
12612 (let* ((rpl0 (match-string 1))
12613 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12614 (replace-match
12615 (concat org-scheduled-string
12616 " <" rpl
12617 (format " -%dd" (abs
12618 (- (time-to-days
12619 (save-match-data
12620 (org-read-date nil t nil "Delay until")))
12621 (time-to-days nil))))
12622 ">") t t))
12623 (user-error "No scheduled information to update"))))
12625 (org-add-planning-info 'scheduled time 'closed)
12626 (when (and old-date org-log-reschedule
12627 (not (equal old-date
12628 (substring org-last-inserted-timestamp 1 -1))))
12629 (org-add-log-setup 'reschedule nil old-date 'findpos
12630 org-log-reschedule))
12631 (when repeater
12632 (save-excursion
12633 (org-back-to-heading t)
12634 (when (re-search-forward (concat org-scheduled-string " "
12635 org-last-inserted-timestamp)
12636 (save-excursion
12637 (outline-next-heading) (point)) t)
12638 (goto-char (1- (match-end 0)))
12639 (insert " " repeater)
12640 (setq org-last-inserted-timestamp
12641 (concat (substring org-last-inserted-timestamp 0 -1)
12642 " " repeater
12643 (substring org-last-inserted-timestamp -1))))))
12644 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12646 (defun org-get-scheduled-time (pom &optional inherit)
12647 "Get the scheduled time as a time tuple, of a format suitable
12648 for calling org-schedule with, or if there is no scheduling,
12649 returns nil."
12650 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12651 (when time
12652 (apply 'encode-time (org-parse-time-string time)))))
12654 (defun org-get-deadline-time (pom &optional inherit)
12655 "Get the deadline as a time tuple, of a format suitable for
12656 calling org-deadline with, or if there is no scheduling, returns
12657 nil."
12658 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12659 (when time
12660 (apply 'encode-time (org-parse-time-string time)))))
12662 (defun org-remove-timestamp-with-keyword (keyword)
12663 "Remove all time stamps with KEYWORD in the current entry."
12664 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12665 beg)
12666 (save-excursion
12667 (org-back-to-heading t)
12668 (setq beg (point))
12669 (outline-next-heading)
12670 (while (re-search-backward re beg t)
12671 (replace-match "")
12672 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12673 (equal (char-before) ?\ ))
12674 (backward-delete-char 1)
12675 (if (string-match "^[ \t]*$" (buffer-substring
12676 (point-at-bol) (point-at-eol)))
12677 (delete-region (point-at-bol)
12678 (min (point-max) (1+ (point-at-eol))))))))))
12680 (defun org-add-planning-info (what &optional time &rest remove)
12681 "Insert new timestamp with keyword in the line directly after the headline.
12682 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12683 If non is given, the user is prompted for a date.
12684 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12685 be removed."
12686 (interactive)
12687 (let (org-time-was-given org-end-time-was-given ts
12688 end default-time default-input)
12690 (catch 'exit
12691 (when (and (memq what '(scheduled deadline))
12692 (or (not time)
12693 (and (stringp time)
12694 (string-match "^[-+]+[0-9]" time))))
12695 ;; Try to get a default date/time from existing timestamp
12696 (save-excursion
12697 (org-back-to-heading t)
12698 (setq end (save-excursion (outline-next-heading) (point)))
12699 (when (re-search-forward (if (eq what 'scheduled)
12700 org-scheduled-time-regexp
12701 org-deadline-time-regexp)
12702 end t)
12703 (setq ts (match-string 1)
12704 default-time
12705 (apply 'encode-time (org-parse-time-string ts))
12706 default-input (and ts (org-get-compact-tod ts))))))
12707 (when what
12708 (setq time
12709 (if (stringp time)
12710 ;; This is a string (relative or absolute), set proper date
12711 (apply 'encode-time
12712 (org-read-date-analyze
12713 time default-time (decode-time default-time)))
12714 ;; If necessary, get the time from the user
12715 (or time (org-read-date nil 'to-time nil nil
12716 default-time default-input)))))
12718 (when (and org-insert-labeled-timestamps-at-point
12719 (member what '(scheduled deadline)))
12720 (insert
12721 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12722 (org-insert-time-stamp time org-time-was-given
12723 nil nil nil (list org-end-time-was-given))
12724 (setq what nil))
12725 (save-excursion
12726 (save-restriction
12727 (let (col list elt ts buffer-invisibility-spec)
12728 (org-back-to-heading t)
12729 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12730 (goto-char (match-end 1))
12731 (setq col (current-column))
12732 (goto-char (match-end 0))
12733 (if (eobp) (insert "\n") (forward-char 1))
12734 (when (and (not what)
12735 (not (looking-at
12736 (concat "[ \t]*"
12737 org-keyword-time-not-clock-regexp))))
12738 ;; Nothing to add, nothing to remove...... :-)
12739 (throw 'exit nil))
12740 (if (and (not (looking-at org-outline-regexp))
12741 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12742 "[^\r\n]*"))
12743 (not (equal (match-string 1) org-clock-string)))
12744 (narrow-to-region (match-beginning 0) (match-end 0))
12745 (insert-before-markers "\n")
12746 (backward-char 1)
12747 (narrow-to-region (point) (point))
12748 (and org-adapt-indentation (org-indent-to-column col)))
12749 ;; Check if we have to remove something.
12750 (setq list (cons what remove))
12751 (while list
12752 (setq elt (pop list))
12753 (when (or (and (eq elt 'scheduled)
12754 (re-search-forward org-scheduled-time-regexp nil t))
12755 (and (eq elt 'deadline)
12756 (re-search-forward org-deadline-time-regexp nil t))
12757 (and (eq elt 'closed)
12758 (re-search-forward org-closed-time-regexp nil t)))
12759 (replace-match "")
12760 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12761 (and (looking-at "[ \t]+") (replace-match ""))
12762 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12763 (when what
12764 (insert
12765 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12766 (cond ((eq what 'scheduled) org-scheduled-string)
12767 ((eq what 'deadline) org-deadline-string)
12768 ((eq what 'closed) org-closed-string))
12769 " ")
12770 (setq ts (org-insert-time-stamp
12771 time
12772 (or org-time-was-given
12773 (and (eq what 'closed) org-log-done-with-time))
12774 (eq what 'closed)
12775 nil nil (list org-end-time-was-given)))
12776 (insert
12777 (if (not (or (bolp) (eq (char-before) ?\ )
12778 (memq (char-after) '(32 10))
12779 (eobp))) " " ""))
12780 (end-of-line 1))
12781 (goto-char (point-min))
12782 (widen)
12783 (if (and (looking-at "[ \t]*\n")
12784 (equal (char-before) ?\n))
12785 (delete-region (1- (point)) (point-at-eol)))
12786 ts))))))
12788 (defvar org-log-note-marker (make-marker))
12789 (defvar org-log-note-purpose nil)
12790 (defvar org-log-note-state nil)
12791 (defvar org-log-note-previous-state nil)
12792 (defvar org-log-note-how nil)
12793 (defvar org-log-note-extra nil)
12794 (defvar org-log-note-window-configuration nil)
12795 (defvar org-log-note-return-to (make-marker))
12796 (defvar org-log-note-effective-time nil
12797 "Remembered current time so that dynamically scoped
12798 `org-extend-today-until' affects tha timestamps in state change
12799 log")
12801 (defvar org-log-post-message nil
12802 "Message to be displayed after a log note has been stored.
12803 The auto-repeater uses this.")
12805 (defun org-add-note ()
12806 "Add a note to the current entry.
12807 This is done in the same way as adding a state change note."
12808 (interactive)
12809 (org-add-log-setup 'note nil nil 'findpos nil))
12811 (defvar org-property-end-re)
12812 (defun org-add-log-setup (&optional purpose state prev-state
12813 findpos how extra)
12814 "Set up the post command hook to take a note.
12815 If this is about to TODO state change, the new state is expected in STATE.
12816 When FINDPOS is non-nil, find the correct position for the note in
12817 the current entry. If not, assume that it can be inserted at point.
12818 HOW is an indicator what kind of note should be created.
12819 EXTRA is additional text that will be inserted into the notes buffer."
12820 (let* ((org-log-into-drawer (org-log-into-drawer))
12821 (drawer (cond ((stringp org-log-into-drawer)
12822 org-log-into-drawer)
12823 (org-log-into-drawer "LOGBOOK"))))
12824 (save-restriction
12825 (save-excursion
12826 (when findpos
12827 (org-back-to-heading t)
12828 (narrow-to-region (point) (save-excursion
12829 (outline-next-heading) (point)))
12830 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12831 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12832 "[^\r\n]*\\)?"))
12833 (goto-char (match-end 0))
12834 (cond
12835 (drawer
12836 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12837 nil t)
12838 (progn
12839 (goto-char (match-end 0))
12840 (or org-log-states-order-reversed
12841 (and (re-search-forward org-property-end-re nil t)
12842 (goto-char (1- (match-beginning 0))))))
12843 (insert "\n:" drawer ":\n:END:")
12844 (beginning-of-line 0)
12845 (org-indent-line)
12846 (beginning-of-line 2)
12847 (org-indent-line)
12848 (end-of-line 0)))
12849 ((and org-log-state-notes-insert-after-drawers
12850 (save-excursion
12851 (forward-line) (looking-at org-drawer-regexp)))
12852 (forward-line)
12853 (while (looking-at org-drawer-regexp)
12854 (goto-char (match-end 0))
12855 (re-search-forward org-property-end-re (point-max) t)
12856 (forward-line))
12857 (forward-line -1)))
12858 (unless org-log-states-order-reversed
12859 (and (= (char-after) ?\n) (forward-char 1))
12860 (org-skip-over-state-notes)
12861 (skip-chars-backward " \t\n\r")))
12862 (move-marker org-log-note-marker (point))
12863 (setq org-log-note-purpose purpose
12864 org-log-note-state state
12865 org-log-note-previous-state prev-state
12866 org-log-note-how how
12867 org-log-note-extra extra
12868 org-log-note-effective-time (org-current-effective-time))
12869 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12871 (defun org-skip-over-state-notes ()
12872 "Skip past the list of State notes in an entry."
12873 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12874 (when (ignore-errors (goto-char (org-in-item-p)))
12875 (let* ((struct (org-list-struct))
12876 (prevs (org-list-prevs-alist struct)))
12877 (while (looking-at "[ \t]*- State")
12878 (goto-char (or (org-list-get-next-item (point) struct prevs)
12879 (org-list-get-item-end (point) struct)))))))
12881 (defun org-add-log-note (&optional purpose)
12882 "Pop up a window for taking a note, and add this note later at point."
12883 (remove-hook 'post-command-hook 'org-add-log-note)
12884 (setq org-log-note-window-configuration (current-window-configuration))
12885 (delete-other-windows)
12886 (move-marker org-log-note-return-to (point))
12887 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12888 (goto-char org-log-note-marker)
12889 (org-switch-to-buffer-other-window "*Org Note*")
12890 (erase-buffer)
12891 (if (memq org-log-note-how '(time state))
12892 (let (current-prefix-arg) (org-store-log-note))
12893 (let ((org-inhibit-startup t)) (org-mode))
12894 (insert (format "# Insert note for %s.
12895 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12896 (cond
12897 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12898 ((eq org-log-note-purpose 'done) "closed todo item")
12899 ((eq org-log-note-purpose 'state)
12900 (format "state change from \"%s\" to \"%s\""
12901 (or org-log-note-previous-state "")
12902 (or org-log-note-state "")))
12903 ((eq org-log-note-purpose 'reschedule)
12904 "rescheduling")
12905 ((eq org-log-note-purpose 'delschedule)
12906 "no longer scheduled")
12907 ((eq org-log-note-purpose 'redeadline)
12908 "changing deadline")
12909 ((eq org-log-note-purpose 'deldeadline)
12910 "removing deadline")
12911 ((eq org-log-note-purpose 'refile)
12912 "refiling")
12913 ((eq org-log-note-purpose 'note)
12914 "this entry")
12915 (t (error "This should not happen")))))
12916 (if org-log-note-extra (insert org-log-note-extra))
12917 (org-set-local 'org-finish-function 'org-store-log-note)
12918 (run-hooks 'org-log-buffer-setup-hook)))
12920 (defvar org-note-abort nil) ; dynamically scoped
12921 (defun org-store-log-note ()
12922 "Finish taking a log note, and insert it to where it belongs."
12923 (let ((txt (buffer-string)))
12924 (kill-buffer (current-buffer))
12925 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12926 lines ind bul)
12927 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12928 (setq txt (replace-match "" t t txt)))
12929 (if (string-match "\\s-+\\'" txt)
12930 (setq txt (replace-match "" t t txt)))
12931 (setq lines (org-split-string txt "\n"))
12932 (when (and note (string-match "\\S-" note))
12933 (setq note
12934 (org-replace-escapes
12935 note
12936 (list (cons "%u" (user-login-name))
12937 (cons "%U" user-full-name)
12938 (cons "%t" (format-time-string
12939 (org-time-stamp-format 'long 'inactive)
12940 org-log-note-effective-time))
12941 (cons "%T" (format-time-string
12942 (org-time-stamp-format 'long nil)
12943 org-log-note-effective-time))
12944 (cons "%d" (format-time-string
12945 (org-time-stamp-format nil 'inactive)
12946 org-log-note-effective-time))
12947 (cons "%D" (format-time-string
12948 (org-time-stamp-format nil nil)
12949 org-log-note-effective-time))
12950 (cons "%s" (if org-log-note-state
12951 (concat "\"" org-log-note-state "\"")
12952 ""))
12953 (cons "%S" (if org-log-note-previous-state
12954 (concat "\"" org-log-note-previous-state "\"")
12955 "\"\"")))))
12956 (if lines (setq note (concat note " \\\\")))
12957 (push note lines))
12958 (when (or current-prefix-arg org-note-abort)
12959 (when org-log-into-drawer
12960 (org-remove-empty-drawer-at
12961 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12962 org-log-note-marker))
12963 (setq lines nil))
12964 (when lines
12965 (with-current-buffer (marker-buffer org-log-note-marker)
12966 (save-excursion
12967 (goto-char org-log-note-marker)
12968 (move-marker org-log-note-marker nil)
12969 (end-of-line 1)
12970 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12971 (setq ind (save-excursion
12972 (if (ignore-errors (goto-char (org-in-item-p)))
12973 (let ((struct (org-list-struct)))
12974 (org-list-get-ind
12975 (org-list-get-top-point struct) struct))
12976 (skip-chars-backward " \r\t\n")
12977 (cond
12978 ((and (org-at-heading-p)
12979 org-adapt-indentation)
12980 (1+ (org-current-level)))
12981 ((org-at-heading-p) 0)
12982 (t (org-get-indentation))))))
12983 (setq bul (org-list-bullet-string "-"))
12984 (org-indent-line-to ind)
12985 (insert bul (pop lines))
12986 (let ((ind-body (+ (length bul) ind)))
12987 (while lines
12988 (insert "\n")
12989 (org-indent-line-to ind-body)
12990 (insert (pop lines))))
12991 (message "Note stored")
12992 (org-back-to-heading t)
12993 (org-cycle-hide-drawers 'children))))))
12994 (set-window-configuration org-log-note-window-configuration)
12995 (with-current-buffer (marker-buffer org-log-note-return-to)
12996 (goto-char org-log-note-return-to))
12997 (move-marker org-log-note-return-to nil)
12998 (and org-log-post-message (message "%s" org-log-post-message)))
13000 (defun org-remove-empty-drawer-at (drawer pos)
13001 "Remove an empty drawer DRAWER at position POS.
13002 POS may also be a marker."
13003 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13004 (save-excursion
13005 (save-restriction
13006 (widen)
13007 (goto-char pos)
13008 (if (org-in-regexp
13009 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13010 (replace-match ""))))))
13012 (defvar org-ts-type nil)
13013 (defun org-sparse-tree (&optional arg type)
13014 "Create a sparse tree, prompt for the details.
13015 This command can create sparse trees. You first need to select the type
13016 of match used to create the tree:
13018 t Show all TODO entries.
13019 T Show entries with a specific TODO keyword.
13020 m Show entries selected by a tags/property match.
13021 p Enter a property name and its value (both with completion on existing
13022 names/values) and show entries with that property.
13023 r Show entries matching a regular expression (`/' can be used as well).
13024 b Show deadlines and scheduled items before a date.
13025 a Show deadlines and scheduled items after a date.
13026 d Show deadlines due within `org-deadline-warning-days'.
13027 D Show deadlines and scheduled items between a date range."
13028 (interactive "P")
13029 (let (ans kwd value ts-type)
13030 (setq type (or type org-sparse-tree-default-date-type))
13031 (setq org-ts-type type)
13032 (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"
13033 (cond ((eq type 'all) "all timestamps")
13034 ((eq type 'scheduled) "only scheduled")
13035 ((eq type 'deadline) "only deadline")
13036 ((eq type 'active) "only active timestamps")
13037 ((eq type 'inactive) "only inactive timestamps")
13038 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13039 (t "scheduled/deadline")))
13040 (setq ans (read-char-exclusive))
13041 (cond
13042 ((equal ans ?c)
13043 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13044 ((equal ans ?d)
13045 (call-interactively 'org-check-deadlines))
13046 ((equal ans ?b)
13047 (call-interactively 'org-check-before-date))
13048 ((equal ans ?a)
13049 (call-interactively 'org-check-after-date))
13050 ((equal ans ?D)
13051 (call-interactively 'org-check-dates-range))
13052 ((equal ans ?t)
13053 (call-interactively 'org-show-todo-tree))
13054 ((equal ans ?T)
13055 (org-show-todo-tree '(4)))
13056 ((member ans '(?T ?m))
13057 (call-interactively 'org-match-sparse-tree))
13058 ((member ans '(?p ?P))
13059 (setq kwd (org-icompleting-read "Property: "
13060 (mapcar 'list (org-buffer-property-keys))))
13061 (setq value (org-icompleting-read "Value: "
13062 (mapcar 'list (org-property-values kwd))))
13063 (unless (string-match "\\`{.*}\\'" value)
13064 (setq value (concat "\"" value "\"")))
13065 (org-match-sparse-tree arg (concat kwd "=" value)))
13066 ((member ans '(?r ?R ?/))
13067 (call-interactively 'org-occur))
13068 (t (error "No such sparse tree command \"%c\"" ans)))))
13070 (defvar org-occur-highlights nil
13071 "List of overlays used for occur matches.")
13072 (make-variable-buffer-local 'org-occur-highlights)
13073 (defvar org-occur-parameters nil
13074 "Parameters of the active org-occur calls.
13075 This is a list, each call to org-occur pushes as cons cell,
13076 containing the regular expression and the callback, onto the list.
13077 The list can contain several entries if `org-occur' has been called
13078 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13079 will only contain one set of parameters. When the highlights are
13080 removed (for example with `C-c C-c', or with the next edit (depending
13081 on `org-remove-highlights-with-change'), this variable is emptied
13082 as well.")
13083 (make-variable-buffer-local 'org-occur-parameters)
13085 (defun org-occur (regexp &optional keep-previous callback)
13086 "Make a compact tree which shows all matches of REGEXP.
13087 The tree will show the lines where the regexp matches, and all higher
13088 headlines above the match. It will also show the heading after the match,
13089 to make sure editing the matching entry is easy.
13090 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13091 call to `org-occur' will be kept, to allow stacking of calls to this
13092 command.
13093 If CALLBACK is non-nil, it is a function which is called to confirm
13094 that the match should indeed be shown."
13095 (interactive "sRegexp: \nP")
13096 (when (equal regexp "")
13097 (error "Regexp cannot be empty"))
13098 (unless keep-previous
13099 (org-remove-occur-highlights nil nil t))
13100 (push (cons regexp callback) org-occur-parameters)
13101 (let ((cnt 0))
13102 (save-excursion
13103 (goto-char (point-min))
13104 (if (or (not keep-previous) ; do not want to keep
13105 (not org-occur-highlights)) ; no previous matches
13106 ;; hide everything
13107 (org-overview))
13108 (while (re-search-forward regexp nil t)
13109 (when (or (not callback)
13110 (save-match-data (funcall callback)))
13111 (setq cnt (1+ cnt))
13112 (when org-highlight-sparse-tree-matches
13113 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13114 (org-show-context 'occur-tree))))
13115 (when org-remove-highlights-with-change
13116 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13117 nil 'local))
13118 (unless org-sparse-tree-open-archived-trees
13119 (org-hide-archived-subtrees (point-min) (point-max)))
13120 (run-hooks 'org-occur-hook)
13121 (if (org-called-interactively-p 'interactive)
13122 (message "%d match(es) for regexp %s" cnt regexp))
13123 cnt))
13125 (defun org-occur-next-match (&optional n reset)
13126 "Function for `next-error-function' to find sparse tree matches.
13127 N is the number of matches to move, when negative move backwards.
13128 RESET is entirely ignored - this function always goes back to the
13129 starting point when no match is found."
13130 (let* ((limit (if (< n 0) (point-min) (point-max)))
13131 (search-func (if (< n 0)
13132 'previous-single-char-property-change
13133 'next-single-char-property-change))
13134 (n (abs n))
13135 (pos (point))
13137 (catch 'exit
13138 (while (setq p1 (funcall search-func (point) 'org-type))
13139 (when (equal p1 limit)
13140 (goto-char pos)
13141 (error "No more matches"))
13142 (when (equal (get-char-property p1 'org-type) 'org-occur)
13143 (setq n (1- n))
13144 (when (= n 0)
13145 (goto-char p1)
13146 (throw 'exit (point))))
13147 (goto-char p1))
13148 (goto-char p1)
13149 (error "No more matches"))))
13151 (defun org-show-context (&optional key)
13152 "Make sure point and context are visible.
13153 How much context is shown depends upon the variables
13154 `org-show-hierarchy-above', `org-show-following-heading',
13155 `org-show-entry-below' and `org-show-siblings'."
13156 (let ((heading-p (org-at-heading-p t))
13157 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13158 (following-p (org-get-alist-option org-show-following-heading key))
13159 (entry-p (org-get-alist-option org-show-entry-below key))
13160 (siblings-p (org-get-alist-option org-show-siblings key)))
13161 (catch 'exit
13162 ;; Show heading or entry text
13163 (if (and heading-p (not entry-p))
13164 (org-flag-heading nil) ; only show the heading
13165 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13166 (org-show-hidden-entry))) ; show entire entry
13167 (when following-p
13168 ;; Show next sibling, or heading below text
13169 (save-excursion
13170 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13171 (org-flag-heading nil))))
13172 (when siblings-p (org-show-siblings))
13173 (when hierarchy-p
13174 ;; show all higher headings, possibly with siblings
13175 (save-excursion
13176 (while (and (condition-case nil
13177 (progn (org-up-heading-all 1) t)
13178 (error nil))
13179 (not (bobp)))
13180 (org-flag-heading nil)
13181 (when siblings-p (org-show-siblings))))))))
13183 (defvar org-reveal-start-hook nil
13184 "Hook run before revealing a location.")
13186 (defun org-reveal (&optional siblings)
13187 "Show current entry, hierarchy above it, and the following headline.
13188 This can be used to show a consistent set of context around locations
13189 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13190 not t for the search context.
13192 With optional argument SIBLINGS, on each level of the hierarchy all
13193 siblings are shown. This repairs the tree structure to what it would
13194 look like when opened with hierarchical calls to `org-cycle'.
13195 With double optional argument \\[universal-argument] \\[universal-argument], \
13196 go to the parent and show the
13197 entire tree."
13198 (interactive "P")
13199 (run-hooks 'org-reveal-start-hook)
13200 (let ((org-show-hierarchy-above t)
13201 (org-show-following-heading t)
13202 (org-show-siblings (if siblings t org-show-siblings)))
13203 (org-show-context nil))
13204 (when (equal siblings '(16))
13205 (save-excursion
13206 (when (org-up-heading-safe)
13207 (org-show-subtree)
13208 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13210 (defun org-highlight-new-match (beg end)
13211 "Highlight from BEG to END and mark the highlight is an occur headline."
13212 (let ((ov (make-overlay beg end)))
13213 (overlay-put ov 'face 'secondary-selection)
13214 (overlay-put ov 'org-type 'org-occur)
13215 (push ov org-occur-highlights)))
13217 (defun org-remove-occur-highlights (&optional beg end noremove)
13218 "Remove the occur highlights from the buffer.
13219 BEG and END are ignored. If NOREMOVE is nil, remove this function
13220 from the `before-change-functions' in the current buffer."
13221 (interactive)
13222 (unless org-inhibit-highlight-removal
13223 (mapc 'delete-overlay org-occur-highlights)
13224 (setq org-occur-highlights nil)
13225 (setq org-occur-parameters nil)
13226 (unless noremove
13227 (remove-hook 'before-change-functions
13228 'org-remove-occur-highlights 'local))))
13230 ;;;; Priorities
13232 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13233 "Regular expression matching the priority indicator.")
13235 (defvar org-remove-priority-next-time nil)
13237 (defun org-priority-up ()
13238 "Increase the priority of the current item."
13239 (interactive)
13240 (org-priority 'up))
13242 (defun org-priority-down ()
13243 "Decrease the priority of the current item."
13244 (interactive)
13245 (org-priority 'down))
13247 (defun org-priority (&optional action show)
13248 "Change the priority of an item.
13249 ACTION can be `set', `up', `down', or a character."
13250 (interactive "P")
13251 (if (equal action '(4))
13252 (org-show-priority)
13253 (unless org-enable-priority-commands
13254 (error "Priority commands are disabled"))
13255 (setq action (or action 'set))
13256 (let (current new news have remove)
13257 (save-excursion
13258 (org-back-to-heading t)
13259 (if (looking-at org-priority-regexp)
13260 (setq current (string-to-char (match-string 2))
13261 have t))
13262 (cond
13263 ((eq action 'remove)
13264 (setq remove t new ?\ ))
13265 ((or (eq action 'set)
13266 (if (featurep 'xemacs) (characterp action) (integerp action)))
13267 (if (not (eq action 'set))
13268 (setq new action)
13269 (message "Priority %c-%c, SPC to remove: "
13270 org-highest-priority org-lowest-priority)
13271 (save-match-data
13272 (setq new (read-char-exclusive))))
13273 (if (and (= (upcase org-highest-priority) org-highest-priority)
13274 (= (upcase org-lowest-priority) org-lowest-priority))
13275 (setq new (upcase new)))
13276 (cond ((equal new ?\ ) (setq remove t))
13277 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13278 (error "Priority must be between `%c' and `%c'"
13279 org-highest-priority org-lowest-priority))))
13280 ((eq action 'up)
13281 (setq new (if have
13282 (1- current) ; normal cycling
13283 ;; last priority was empty
13284 (if (eq last-command this-command)
13285 org-lowest-priority ; wrap around empty to lowest
13286 ;; default
13287 (if org-priority-start-cycle-with-default
13288 org-default-priority
13289 (1- org-default-priority))))))
13290 ((eq action 'down)
13291 (setq new (if have
13292 (1+ current) ; normal cycling
13293 ;; last priority was empty
13294 (if (eq last-command this-command)
13295 org-highest-priority ; wrap around empty to highest
13296 ;; default
13297 (if org-priority-start-cycle-with-default
13298 org-default-priority
13299 (1+ org-default-priority))))))
13300 (t (error "Invalid action")))
13301 (if (or (< (upcase new) org-highest-priority)
13302 (> (upcase new) org-lowest-priority))
13303 (if (and (memq action '(up down))
13304 (not have) (not (eq last-command this-command)))
13305 ;; `new' is from default priority
13306 (error
13307 "The default can not be set, see `org-default-priority' why")
13308 ;; normal cycling: `new' is beyond highest/lowest priority
13309 ;; and is wrapped around to the empty priority
13310 (setq remove t)))
13311 (setq news (format "%c" new))
13312 (if have
13313 (if remove
13314 (replace-match "" t t nil 1)
13315 (replace-match news t t nil 2))
13316 (if remove
13317 (error "No priority cookie found in line")
13318 (let ((case-fold-search nil))
13319 (looking-at org-todo-line-regexp))
13320 (if (match-end 2)
13321 (progn
13322 (goto-char (match-end 2))
13323 (insert " [#" news "]"))
13324 (goto-char (match-beginning 3))
13325 (insert "[#" news "] "))))
13326 (org-preserve-lc (org-set-tags nil 'align)))
13327 (if remove
13328 (message "Priority removed")
13329 (message "Priority of current item set to %s" news)))))
13331 (defun org-show-priority ()
13332 "Show the priority of the current item.
13333 This priority is composed of the main priority given with the [#A] cookies,
13334 and by additional input from the age of a schedules or deadline entry."
13335 (interactive)
13336 (let ((pri (if (eq major-mode 'org-agenda-mode)
13337 (org-get-at-bol 'priority)
13338 (save-excursion
13339 (save-match-data
13340 (beginning-of-line)
13341 (and (looking-at org-heading-regexp)
13342 (org-get-priority (match-string 0))))))))
13343 (message "Priority is %d" (if pri pri -1000))))
13345 (defun org-get-priority (s)
13346 "Find priority cookie and return priority."
13347 (save-match-data
13348 (if (functionp org-get-priority-function)
13349 (funcall org-get-priority-function)
13350 (if (not (string-match org-priority-regexp s))
13351 (* 1000 (- org-lowest-priority org-default-priority))
13352 (* 1000 (- org-lowest-priority
13353 (string-to-char (match-string 2 s))))))))
13355 ;;;; Tags
13357 (defvar org-agenda-archives-mode)
13358 (defvar org-map-continue-from nil
13359 "Position from where mapping should continue.
13360 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13362 (defvar org-scanner-tags nil
13363 "The current tag list while the tags scanner is running.")
13364 (defvar org-trust-scanner-tags nil
13365 "Should `org-get-tags-at' use the tags for the scanner.
13366 This is for internal dynamical scoping only.
13367 When this is non-nil, the function `org-get-tags-at' will return the value
13368 of `org-scanner-tags' instead of building the list by itself. This
13369 can lead to large speed-ups when the tags scanner is used in a file with
13370 many entries, and when the list of tags is retrieved, for example to
13371 obtain a list of properties. Building the tags list for each entry in such
13372 a file becomes an N^2 operation - but with this variable set, it scales
13373 as N.")
13375 (defun org-scan-tags (action matcher todo-only &optional start-level)
13376 "Scan headline tags with inheritance and produce output ACTION.
13378 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13379 or `agenda' to produce an entry list for an agenda view. It can also be
13380 a Lisp form or a function that should be called at each matched headline, in
13381 this case the return value is a list of all return values from these calls.
13383 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13384 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13385 only lines with a not-done TODO keyword are included in the output.
13386 This should be the same variable that was scoped into
13387 and set by `org-make-tags-matcher' when it constructed MATCHER.
13389 START-LEVEL can be a string with asterisks, reducing the scope to
13390 headlines matching this string."
13391 (require 'org-agenda)
13392 (let* ((re (concat "^"
13393 (if start-level
13394 ;; Get the correct level to match
13395 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13396 org-outline-regexp)
13397 " *\\(\\<\\("
13398 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13399 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13400 (props (list 'face 'default
13401 'done-face 'org-agenda-done
13402 'undone-face 'default
13403 'mouse-face 'highlight
13404 'org-not-done-regexp org-not-done-regexp
13405 'org-todo-regexp org-todo-regexp
13406 'org-complex-heading-regexp org-complex-heading-regexp
13407 'help-echo
13408 (format "mouse-2 or RET jump to org file %s"
13409 (abbreviate-file-name
13410 (or (buffer-file-name (buffer-base-buffer))
13411 (buffer-name (buffer-base-buffer)))))))
13412 (case-fold-search nil)
13413 (org-map-continue-from nil)
13414 lspos tags tags-list
13415 (tags-alist (list (cons 0 org-file-tags)))
13416 (llast 0) rtn rtn1 level category i txt
13417 todo marker entry priority)
13418 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13419 (setq action (list 'lambda nil action)))
13420 (save-excursion
13421 (goto-char (point-min))
13422 (when (eq action 'sparse-tree)
13423 (org-overview)
13424 (org-remove-occur-highlights))
13425 (while (re-search-forward re nil t)
13426 (setq org-map-continue-from nil)
13427 (catch :skip
13428 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13429 tags (if (match-end 4) (org-match-string-no-properties 4)))
13430 (goto-char (setq lspos (match-beginning 0)))
13431 (setq level (org-reduced-level (org-outline-level))
13432 category (org-get-category))
13433 (setq i llast llast level)
13434 ;; remove tag lists from same and sublevels
13435 (while (>= i level)
13436 (when (setq entry (assoc i tags-alist))
13437 (setq tags-alist (delete entry tags-alist)))
13438 (setq i (1- i)))
13439 ;; add the next tags
13440 (when tags
13441 (setq tags (org-split-string tags ":")
13442 tags-alist
13443 (cons (cons level tags) tags-alist)))
13444 ;; compile tags for current headline
13445 (setq tags-list
13446 (if org-use-tag-inheritance
13447 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13448 tags)
13449 org-scanner-tags tags-list)
13450 (when org-use-tag-inheritance
13451 (setcdr (car tags-alist)
13452 (mapcar (lambda (x)
13453 (setq x (copy-sequence x))
13454 (org-add-prop-inherited x))
13455 (cdar tags-alist))))
13456 (when (and tags org-use-tag-inheritance
13457 (or (not (eq t org-use-tag-inheritance))
13458 org-tags-exclude-from-inheritance))
13459 ;; selective inheritance, remove uninherited ones
13460 (setcdr (car tags-alist)
13461 (org-remove-uninherited-tags (cdar tags-alist))))
13462 (when (and
13464 ;; eval matcher only when the todo condition is OK
13465 (and (or (not todo-only) (member todo org-not-done-keywords))
13466 (let ((case-fold-search t) (org-trust-scanner-tags t))
13467 (eval matcher)))
13469 ;; Call the skipper, but return t if it does not skip,
13470 ;; so that the `and' form continues evaluating
13471 (progn
13472 (unless (eq action 'sparse-tree) (org-agenda-skip))
13475 ;; Check if timestamps are deselecting this entry
13476 (or (not todo-only)
13477 (and (member todo org-not-done-keywords)
13478 (or (not org-agenda-tags-todo-honor-ignore-options)
13479 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13481 ;; select this headline
13482 (cond
13483 ((eq action 'sparse-tree)
13484 (and org-highlight-sparse-tree-matches
13485 (org-get-heading) (match-end 0)
13486 (org-highlight-new-match
13487 (match-beginning 1) (match-end 1)))
13488 (org-show-context 'tags-tree))
13489 ((eq action 'agenda)
13490 (setq txt (org-agenda-format-item
13492 (concat
13493 (if (eq org-tags-match-list-sublevels 'indented)
13494 (make-string (1- level) ?.) "")
13495 (org-get-heading))
13496 level category
13497 tags-list)
13498 priority (org-get-priority txt))
13499 (goto-char lspos)
13500 (setq marker (org-agenda-new-marker))
13501 (org-add-props txt props
13502 'org-marker marker 'org-hd-marker marker 'org-category category
13503 'todo-state todo
13504 'priority priority 'type "tagsmatch")
13505 (push txt rtn))
13506 ((functionp action)
13507 (setq org-map-continue-from nil)
13508 (save-excursion
13509 (setq rtn1 (funcall action))
13510 (push rtn1 rtn)))
13511 (t (error "Invalid action")))
13513 ;; if we are to skip sublevels, jump to end of subtree
13514 (unless org-tags-match-list-sublevels
13515 (org-end-of-subtree t)
13516 (backward-char 1))))
13517 ;; Get the correct position from where to continue
13518 (if org-map-continue-from
13519 (goto-char org-map-continue-from)
13520 (and (= (point) lspos) (end-of-line 1)))))
13521 (when (and (eq action 'sparse-tree)
13522 (not org-sparse-tree-open-archived-trees))
13523 (org-hide-archived-subtrees (point-min) (point-max)))
13524 (nreverse rtn)))
13526 (defun org-remove-uninherited-tags (tags)
13527 "Remove all tags that are not inherited from the list TAGS."
13528 (cond
13529 ((eq org-use-tag-inheritance t)
13530 (if org-tags-exclude-from-inheritance
13531 (org-delete-all org-tags-exclude-from-inheritance tags)
13532 tags))
13533 ((not org-use-tag-inheritance) nil)
13534 ((stringp org-use-tag-inheritance)
13535 (delq nil (mapcar
13536 (lambda (x)
13537 (if (and (string-match org-use-tag-inheritance x)
13538 (not (member x org-tags-exclude-from-inheritance)))
13539 x nil))
13540 tags)))
13541 ((listp org-use-tag-inheritance)
13542 (delq nil (mapcar
13543 (lambda (x)
13544 (if (member x org-use-tag-inheritance) x nil))
13545 tags)))))
13547 (defun org-match-sparse-tree (&optional todo-only match)
13548 "Create a sparse tree according to tags string MATCH.
13549 MATCH can contain positive and negative selection of tags, like
13550 \"+WORK+URGENT-WITHBOSS\".
13551 If optional argument TODO-ONLY is non-nil, only select lines that are
13552 also TODO lines."
13553 (interactive "P")
13554 (org-agenda-prepare-buffers (list (current-buffer)))
13555 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13557 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13559 (defvar org-cached-props nil)
13560 (defun org-cached-entry-get (pom property)
13561 (if (or (eq t org-use-property-inheritance)
13562 (and (stringp org-use-property-inheritance)
13563 (string-match org-use-property-inheritance property))
13564 (and (listp org-use-property-inheritance)
13565 (member property org-use-property-inheritance)))
13566 ;; Caching is not possible, check it directly
13567 (org-entry-get pom property 'inherit)
13568 ;; Get all properties, so that we can do complicated checks easily
13569 (cdr (assoc property (or org-cached-props
13570 (setq org-cached-props
13571 (org-entry-properties pom)))))))
13573 (defun org-global-tags-completion-table (&optional files)
13574 "Return the list of all tags in all agenda buffer/files.
13575 Optional FILES argument is a list of files which can be used
13576 instead of the agenda files."
13577 (save-excursion
13578 (org-uniquify
13579 (delq nil
13580 (apply 'append
13581 (mapcar
13582 (lambda (file)
13583 (set-buffer (find-file-noselect file))
13584 (append (org-get-buffer-tags)
13585 (mapcar (lambda (x) (if (stringp (car-safe x))
13586 (list (car-safe x)) nil))
13587 org-tag-alist)))
13588 (if (and files (car files))
13589 files
13590 (org-agenda-files))))))))
13592 (defun org-make-tags-matcher (match)
13593 "Create the TAGS/TODO matcher form for the selection string MATCH.
13595 The variable `todo-only' is scoped dynamically into this function.
13596 It will be set to t if the matcher restricts matching to TODO entries,
13597 otherwise will not be touched.
13599 Returns a cons of the selection string MATCH and the constructed
13600 lisp form implementing the matcher. The matcher is to be evaluated
13601 at an Org entry, with point on the headline, and returns t if the
13602 entry matches the selection string MATCH. The returned lisp form
13603 references two variables with information about the entry, which
13604 must be bound around the form's evaluation: todo, the TODO keyword
13605 at the entry (or nil of none); and tags-list, the list of all tags
13606 at the entry including inherited ones. Additionally, the category
13607 of the entry (if any) must be specified as the text property
13608 'org-category on the headline.
13610 See also `org-scan-tags'.
13612 (declare (special todo-only))
13613 (unless (boundp 'todo-only)
13614 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13615 (unless match
13616 ;; Get a new match request, with completion
13617 (let ((org-last-tags-completion-table
13618 (org-global-tags-completion-table)))
13619 (setq match (org-completing-read-no-i
13620 "Match: " 'org-tags-completion-function nil nil nil
13621 'org-tags-history))))
13623 ;; Parse the string and create a lisp form
13624 (let ((match0 match)
13625 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13626 minus tag mm
13627 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13628 orterms term orlist re-p str-p level-p level-op time-p
13629 prop-p pn pv po gv rest)
13630 (if (string-match "/+" match)
13631 ;; match contains also a todo-matching request
13632 (progn
13633 (setq tagsmatch (substring match 0 (match-beginning 0))
13634 todomatch (substring match (match-end 0)))
13635 (if (string-match "^!" todomatch)
13636 (setq todo-only t todomatch (substring todomatch 1)))
13637 (if (string-match "^\\s-*$" todomatch)
13638 (setq todomatch nil)))
13639 ;; only matching tags
13640 (setq tagsmatch match todomatch nil))
13642 ;; Make the tags matcher
13643 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13644 (setq tagsmatcher t)
13645 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13646 (while (setq term (pop orterms))
13647 (while (and (equal (substring term -1) "\\") orterms)
13648 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13649 (while (string-match re term)
13650 (setq rest (substring term (match-end 0))
13651 minus (and (match-end 1)
13652 (equal (match-string 1 term) "-"))
13653 tag (save-match-data (replace-regexp-in-string
13654 "\\\\-" "-"
13655 (match-string 2 term)))
13656 re-p (equal (string-to-char tag) ?{)
13657 level-p (match-end 4)
13658 prop-p (match-end 5)
13659 mm (cond
13660 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13661 (level-p
13662 (setq level-op (org-op-to-function (match-string 3 term)))
13663 `(,level-op level ,(string-to-number
13664 (match-string 4 term))))
13665 (prop-p
13666 (setq pn (match-string 5 term)
13667 po (match-string 6 term)
13668 pv (match-string 7 term)
13669 re-p (equal (string-to-char pv) ?{)
13670 str-p (equal (string-to-char pv) ?\")
13671 time-p (save-match-data
13672 (string-match "^\"[[<].*[]>]\"$" pv))
13673 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13674 (if time-p (setq pv (org-matcher-time pv)))
13675 (setq po (org-op-to-function po (if time-p 'time str-p)))
13676 (cond
13677 ((equal pn "CATEGORY")
13678 (setq gv '(get-text-property (point) 'org-category)))
13679 ((equal pn "TODO")
13680 (setq gv 'todo))
13682 (setq gv `(org-cached-entry-get nil ,pn))))
13683 (if re-p
13684 (if (eq po 'org<>)
13685 `(not (string-match ,pv (or ,gv "")))
13686 `(string-match ,pv (or ,gv "")))
13687 (if str-p
13688 `(,po (or ,gv "") ,pv)
13689 `(,po (string-to-number (or ,gv ""))
13690 ,(string-to-number pv) ))))
13691 (t `(member ,tag tags-list)))
13692 mm (if minus (list 'not mm) mm)
13693 term rest)
13694 (push mm tagsmatcher))
13695 (push (if (> (length tagsmatcher) 1)
13696 (cons 'and tagsmatcher)
13697 (car tagsmatcher))
13698 orlist)
13699 (setq tagsmatcher nil))
13700 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13701 (setq tagsmatcher
13702 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13703 ;; Make the todo matcher
13704 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13705 (setq todomatcher t)
13706 (setq orterms (org-split-string todomatch "|") orlist nil)
13707 (while (setq term (pop orterms))
13708 (while (string-match re term)
13709 (setq minus (and (match-end 1)
13710 (equal (match-string 1 term) "-"))
13711 kwd (match-string 2 term)
13712 re-p (equal (string-to-char kwd) ?{)
13713 term (substring term (match-end 0))
13714 mm (if re-p
13715 `(string-match ,(substring kwd 1 -1) todo)
13716 (list 'equal 'todo kwd))
13717 mm (if minus (list 'not mm) mm))
13718 (push mm todomatcher))
13719 (push (if (> (length todomatcher) 1)
13720 (cons 'and todomatcher)
13721 (car todomatcher))
13722 orlist)
13723 (setq todomatcher nil))
13724 (setq todomatcher (if (> (length orlist) 1)
13725 (cons 'or orlist) (car orlist))))
13727 ;; Return the string and lisp forms of the matcher
13728 (setq matcher (if todomatcher
13729 (list 'and tagsmatcher todomatcher)
13730 tagsmatcher))
13731 (when todo-only
13732 (setq matcher (list 'and '(member todo org-not-done-keywords)
13733 matcher)))
13734 (cons match0 matcher)))
13736 (defun org-op-to-function (op &optional stringp)
13737 "Turn an operator into the appropriate function."
13738 (setq op
13739 (cond
13740 ((equal op "<" ) '(< string< org-time<))
13741 ((equal op ">" ) '(> org-string> org-time>))
13742 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13743 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13744 ((member op '("=" "==")) '(= string= org-time=))
13745 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13746 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13748 (defun org<> (a b) (not (= a b)))
13749 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13750 (defun org-string>= (a b) (not (string< a b)))
13751 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13752 (defun org-string<> (a b) (not (string= a b)))
13753 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= 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) (org<> a b)))
13759 (defun org-2ft (s)
13760 "Convert S to a floating point time.
13761 If S is already a number, just return it. If it is a string, parse
13762 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13763 (cond
13764 ((numberp s) s)
13765 ((stringp s)
13766 (condition-case nil
13767 (float-time (apply 'encode-time (org-parse-time-string s)))
13768 (error 0.)))
13769 (t 0.)))
13771 (defun org-time-today ()
13772 "Time in seconds today at 0:00.
13773 Returns the float number of seconds since the beginning of the
13774 epoch to the beginning of today (00:00)."
13775 (float-time (apply 'encode-time
13776 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13778 (defun org-matcher-time (s)
13779 "Interpret a time comparison value."
13780 (save-match-data
13781 (cond
13782 ((string= s "<now>") (float-time))
13783 ((string= s "<today>") (org-time-today))
13784 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13785 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13786 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13787 (+ (org-time-today)
13788 (* (string-to-number (match-string 1 s))
13789 (cdr (assoc (match-string 2 s)
13790 '(("d" . 86400.0) ("w" . 604800.0)
13791 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13792 (t (org-2ft s)))))
13794 (defun org-match-any-p (re list)
13795 "Does re match any element of list?"
13796 (setq list (mapcar (lambda (x) (string-match re x)) list))
13797 (delq nil list))
13799 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13800 (defvar org-tags-overlay (make-overlay 1 1))
13801 (org-detach-overlay org-tags-overlay)
13803 (defun org-get-local-tags-at (&optional pos)
13804 "Get a list of tags defined in the current headline."
13805 (org-get-tags-at pos 'local))
13807 (defun org-get-local-tags ()
13808 "Get a list of tags defined in the current headline."
13809 (org-get-tags-at nil 'local))
13811 (defun org-get-tags-at (&optional pos local)
13812 "Get a list of all headline tags applicable at POS.
13813 POS defaults to point. If tags are inherited, the list contains
13814 the targets in the same sequence as the headlines appear, i.e.
13815 the tags of the current headline come last.
13816 When LOCAL is non-nil, only return tags from the current headline,
13817 ignore inherited ones."
13818 (interactive)
13819 (if (and org-trust-scanner-tags
13820 (or (not pos) (equal pos (point)))
13821 (not local))
13822 org-scanner-tags
13823 (let (tags ltags lastpos parent)
13824 (save-excursion
13825 (save-restriction
13826 (widen)
13827 (goto-char (or pos (point)))
13828 (save-match-data
13829 (catch 'done
13830 (condition-case nil
13831 (progn
13832 (org-back-to-heading t)
13833 (while (not (equal lastpos (point)))
13834 (setq lastpos (point))
13835 (when (looking-at
13836 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13837 (setq ltags (org-split-string
13838 (org-match-string-no-properties 1) ":"))
13839 (when parent
13840 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13841 (setq tags (append
13842 (if parent
13843 (org-remove-uninherited-tags ltags)
13844 ltags)
13845 tags)))
13846 (or org-use-tag-inheritance (throw 'done t))
13847 (if local (throw 'done t))
13848 (or (org-up-heading-safe) (error nil))
13849 (setq parent t)))
13850 (error nil)))))
13851 (if local
13852 tags
13853 (reverse (delete-dups
13854 (reverse (append
13855 (org-remove-uninherited-tags
13856 org-file-tags) tags)))))))))
13858 (defun org-add-prop-inherited (s)
13859 (add-text-properties 0 (length s) '(inherited t) s)
13862 (defun org-toggle-tag (tag &optional onoff)
13863 "Toggle the tag TAG for the current line.
13864 If ONOFF is `on' or `off', don't toggle but set to this state."
13865 (let (res current)
13866 (save-excursion
13867 (org-back-to-heading t)
13868 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13869 (point-at-eol) t)
13870 (progn
13871 (setq current (match-string 1))
13872 (replace-match ""))
13873 (setq current ""))
13874 (setq current (nreverse (org-split-string current ":")))
13875 (cond
13876 ((eq onoff 'on)
13877 (setq res t)
13878 (or (member tag current) (push tag current)))
13879 ((eq onoff 'off)
13880 (or (not (member tag current)) (setq current (delete tag current))))
13881 (t (if (member tag current)
13882 (setq current (delete tag current))
13883 (setq res t)
13884 (push tag current))))
13885 (end-of-line 1)
13886 (if current
13887 (progn
13888 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13889 (org-set-tags nil t))
13890 (delete-horizontal-space))
13891 (run-hooks 'org-after-tags-change-hook))
13892 res))
13894 (defun org-align-tags-here (to-col)
13895 ;; Assumes that this is a headline
13896 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13897 (beginning-of-line 1)
13898 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13899 (< pos (match-beginning 2)))
13900 (progn
13901 (setq tags-l (- (match-end 2) (match-beginning 2)))
13902 (goto-char (match-beginning 1))
13903 (insert " ")
13904 (delete-region (point) (1+ (match-beginning 2)))
13905 (setq ncol (max (current-column)
13906 (1+ col)
13907 (if (> to-col 0)
13908 to-col
13909 (- (abs to-col) tags-l))))
13910 (setq p (point))
13911 (insert (make-string (- ncol (current-column)) ?\ ))
13912 (setq ncol (current-column))
13913 (when indent-tabs-mode (tabify p (point-at-eol)))
13914 (org-move-to-column (min ncol col) t))
13915 (goto-char pos))))
13917 (defun org-set-tags-command (&optional arg just-align)
13918 "Call the set-tags command for the current entry."
13919 (interactive "P")
13920 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13921 (org-set-tags arg just-align)
13922 (save-excursion
13923 (org-back-to-heading t)
13924 (org-set-tags arg just-align))))
13926 (defun org-set-tags-to (data)
13927 "Set the tags of the current entry to DATA, replacing the current tags.
13928 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13929 If DATA is nil or the empty string, any tags will be removed."
13930 (interactive "sTags: ")
13931 (setq data
13932 (cond
13933 ((eq data nil) "")
13934 ((equal data "") "")
13935 ((stringp data)
13936 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13937 ":"))
13938 ((listp data)
13939 (concat ":" (mapconcat 'identity data ":") ":"))))
13940 (when data
13941 (save-excursion
13942 (org-back-to-heading t)
13943 (when (looking-at org-complex-heading-regexp)
13944 (if (match-end 5)
13945 (progn
13946 (goto-char (match-beginning 5))
13947 (insert data)
13948 (delete-region (point) (point-at-eol))
13949 (org-set-tags nil 'align))
13950 (goto-char (point-at-eol))
13951 (insert " " data)
13952 (org-set-tags nil 'align)))
13953 (beginning-of-line 1)
13954 (if (looking-at ".*?\\([ \t]+\\)$")
13955 (delete-region (match-beginning 1) (match-end 1))))))
13957 (defun org-align-all-tags ()
13958 "Align the tags i all headings."
13959 (interactive)
13960 (save-excursion
13961 (or (ignore-errors (org-back-to-heading t))
13962 (outline-next-heading))
13963 (if (org-at-heading-p)
13964 (org-set-tags t)
13965 (message "No headings"))))
13967 (defvar org-indent-indentation-per-level)
13968 (defun org-set-tags (&optional arg just-align)
13969 "Set the tags for the current headline.
13970 With prefix ARG, realign all tags in headings in the current buffer."
13971 (interactive "P")
13972 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13973 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13974 'region-start-level 'region))
13975 org-loop-over-headlines-in-active-region)
13976 (org-map-entries
13977 ;; We don't use ARG and JUST-ALIGN here these args are not
13978 ;; useful when looping over headlines
13979 `(org-set-tags)
13980 org-loop-over-headlines-in-active-region
13981 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13982 (let* ((re org-outline-regexp-bol)
13983 (current (unless arg (org-get-tags-string)))
13984 (col (current-column))
13985 (org-setting-tags t)
13986 table current-tags inherited-tags ; computed below when needed
13987 tags p0 c0 c1 rpl di tc level)
13988 (if arg
13989 (save-excursion
13990 (goto-char (point-min))
13991 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13992 (while (re-search-forward re nil t)
13993 (org-set-tags nil t)
13994 (end-of-line 1)))
13995 (message "All tags realigned to column %d" org-tags-column))
13996 (if just-align
13997 (setq tags current)
13998 ;; Get a new set of tags from the user
13999 (save-excursion
14000 (setq table (append org-tag-persistent-alist
14001 (or org-tag-alist (org-get-buffer-tags))
14002 (and
14003 org-complete-tags-always-offer-all-agenda-tags
14004 (org-global-tags-completion-table
14005 (org-agenda-files))))
14006 org-last-tags-completion-table table
14007 current-tags (org-split-string current ":")
14008 inherited-tags (nreverse
14009 (nthcdr (length current-tags)
14010 (nreverse (org-get-tags-at))))
14011 tags
14012 (if (or (eq t org-use-fast-tag-selection)
14013 (and org-use-fast-tag-selection
14014 (delq nil (mapcar 'cdr table))))
14015 (org-fast-tag-selection
14016 current-tags inherited-tags table
14017 (if org-fast-tag-selection-include-todo
14018 org-todo-key-alist))
14019 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14020 (org-trim
14021 (org-icompleting-read "Tags: "
14022 'org-tags-completion-function
14023 nil nil current 'org-tags-history))))))
14024 (while (string-match "[-+&]+" tags)
14025 ;; No boolean logic, just a list
14026 (setq tags (replace-match ":" t t tags))))
14028 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14030 (if org-tags-sort-function
14031 (setq tags (mapconcat 'identity
14032 (sort (org-split-string
14033 tags (org-re "[^[:alnum:]_@#%]+"))
14034 org-tags-sort-function) ":")))
14036 (if (string-match "\\`[\t ]*\\'" tags)
14037 (setq tags "")
14038 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14039 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14041 ;; Insert new tags at the correct column
14042 (beginning-of-line 1)
14043 (setq level (or (and (looking-at org-outline-regexp)
14044 (- (match-end 0) (point) 1))
14046 (cond
14047 ((and (equal current "") (equal tags "")))
14048 ((re-search-forward
14049 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14050 (point-at-eol) t)
14051 (if (equal tags "")
14052 (setq rpl "")
14053 (goto-char (match-beginning 0))
14054 (setq c0 (current-column)
14055 ;; compute offset for the case of org-indent-mode active
14056 di (if org-indent-mode
14057 (* (1- org-indent-indentation-per-level) (1- level))
14059 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14060 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14061 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14062 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14063 (replace-match rpl t t)
14064 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14065 tags)
14066 (t (error "Tags alignment failed")))
14067 (org-move-to-column col)
14068 (unless just-align
14069 (run-hooks 'org-after-tags-change-hook))))))
14071 (defun org-change-tag-in-region (beg end tag off)
14072 "Add or remove TAG for each entry in the region.
14073 This works in the agenda, and also in an org-mode buffer."
14074 (interactive
14075 (list (region-beginning) (region-end)
14076 (let ((org-last-tags-completion-table
14077 (if (derived-mode-p 'org-mode)
14078 (org-get-buffer-tags)
14079 (org-global-tags-completion-table))))
14080 (org-icompleting-read
14081 "Tag: " 'org-tags-completion-function nil nil nil
14082 'org-tags-history))
14083 (progn
14084 (message "[s]et or [r]emove? ")
14085 (equal (read-char-exclusive) ?r))))
14086 (if (fboundp 'deactivate-mark) (deactivate-mark))
14087 (let ((agendap (equal major-mode 'org-agenda-mode))
14088 l1 l2 m buf pos newhead (cnt 0))
14089 (goto-char end)
14090 (setq l2 (1- (org-current-line)))
14091 (goto-char beg)
14092 (setq l1 (org-current-line))
14093 (loop for l from l1 to l2 do
14094 (org-goto-line l)
14095 (setq m (get-text-property (point) 'org-hd-marker))
14096 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14097 (and agendap m))
14098 (setq buf (if agendap (marker-buffer m) (current-buffer))
14099 pos (if agendap m (point)))
14100 (with-current-buffer buf
14101 (save-excursion
14102 (save-restriction
14103 (goto-char pos)
14104 (setq cnt (1+ cnt))
14105 (org-toggle-tag tag (if off 'off 'on))
14106 (setq newhead (org-get-heading)))))
14107 (and agendap (org-agenda-change-all-lines newhead m))))
14108 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14110 (defun org-tags-completion-function (string predicate &optional flag)
14111 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14112 (confirm (lambda (x) (stringp (car x)))))
14113 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14114 (setq s1 (match-string 1 string)
14115 s2 (match-string 2 string))
14116 (setq s1 "" s2 string))
14117 (cond
14118 ((eq flag nil)
14119 ;; try completion
14120 (setq rtn (try-completion s2 ctable confirm))
14121 (if (stringp rtn)
14122 (setq rtn
14123 (concat s1 s2 (substring rtn (length s2))
14124 (if (and org-add-colon-after-tag-completion
14125 (assoc rtn ctable))
14126 ":" ""))))
14127 rtn)
14128 ((eq flag t)
14129 ;; all-completions
14130 (all-completions s2 ctable confirm)
14132 ((eq flag 'lambda)
14133 ;; exact match?
14134 (assoc s2 ctable)))
14137 (defun org-fast-tag-insert (kwd tags face &optional end)
14138 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14139 (insert (format "%-12s" (concat kwd ":"))
14140 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14141 (or end "")))
14143 (defun org-fast-tag-show-exit (flag)
14144 (save-excursion
14145 (org-goto-line 3)
14146 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14147 (replace-match ""))
14148 (when flag
14149 (end-of-line 1)
14150 (org-move-to-column (- (window-width) 19) t)
14151 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14153 (defun org-set-current-tags-overlay (current prefix)
14154 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14155 (if (featurep 'xemacs)
14156 (org-overlay-display org-tags-overlay (concat prefix s)
14157 'secondary-selection)
14158 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14159 (org-overlay-display org-tags-overlay (concat prefix s)))))
14161 (defvar org-last-tag-selection-key nil)
14162 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14163 "Fast tag selection with single keys.
14164 CURRENT is the current list of tags in the headline, INHERITED is the
14165 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14166 possibly with grouping information. TODO-TABLE is a similar table with
14167 TODO keywords, should these have keys assigned to them.
14168 If the keys are nil, a-z are automatically assigned.
14169 Returns the new tags string, or nil to not change the current settings."
14170 (let* ((fulltable (append table todo-table))
14171 (maxlen (apply 'max (mapcar
14172 (lambda (x)
14173 (if (stringp (car x)) (string-width (car x)) 0))
14174 fulltable)))
14175 (buf (current-buffer))
14176 (expert (eq org-fast-tag-selection-single-key 'expert))
14177 (buffer-tags nil)
14178 (fwidth (+ maxlen 3 1 3))
14179 (ncol (/ (- (window-width) 4) fwidth))
14180 (i-face 'org-done)
14181 (c-face 'org-todo)
14182 tg cnt e c char c1 c2 ntable tbl rtn
14183 ov-start ov-end ov-prefix
14184 (exit-after-next org-fast-tag-selection-single-key)
14185 (done-keywords org-done-keywords)
14186 groups ingroup)
14187 (save-excursion
14188 (beginning-of-line 1)
14189 (if (looking-at
14190 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14191 (setq ov-start (match-beginning 1)
14192 ov-end (match-end 1)
14193 ov-prefix "")
14194 (setq ov-start (1- (point-at-eol))
14195 ov-end (1+ ov-start))
14196 (skip-chars-forward "^\n\r")
14197 (setq ov-prefix
14198 (concat
14199 (buffer-substring (1- (point)) (point))
14200 (if (> (current-column) org-tags-column)
14202 (make-string (- org-tags-column (current-column)) ?\ ))))))
14203 (move-overlay org-tags-overlay ov-start ov-end)
14204 (save-window-excursion
14205 (if expert
14206 (set-buffer (get-buffer-create " *Org tags*"))
14207 (delete-other-windows)
14208 (split-window-vertically)
14209 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14210 (erase-buffer)
14211 (org-set-local 'org-done-keywords done-keywords)
14212 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14213 (org-fast-tag-insert "Current" current c-face "\n\n")
14214 (org-fast-tag-show-exit exit-after-next)
14215 (org-set-current-tags-overlay current ov-prefix)
14216 (setq tbl fulltable char ?a cnt 0)
14217 (while (setq e (pop tbl))
14218 (cond
14219 ((equal (car e) :startgroup)
14220 (push '() groups) (setq ingroup t)
14221 (when (not (= cnt 0))
14222 (setq cnt 0)
14223 (insert "\n"))
14224 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14225 ((equal (car e) :endgroup)
14226 (setq ingroup nil cnt 0)
14227 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14228 ((equal e '(:newline))
14229 (when (not (= cnt 0))
14230 (setq cnt 0)
14231 (insert "\n")
14232 (setq e (car tbl))
14233 (while (equal (car tbl) '(:newline))
14234 (insert "\n")
14235 (setq tbl (cdr tbl)))))
14237 (setq tg (copy-sequence (car e)) c2 nil)
14238 (if (cdr e)
14239 (setq c (cdr e))
14240 ;; automatically assign a character.
14241 (setq c1 (string-to-char
14242 (downcase (substring
14243 tg (if (= (string-to-char tg) ?@) 1 0)))))
14244 (if (or (rassoc c1 ntable) (rassoc c1 table))
14245 (while (or (rassoc char ntable) (rassoc char table))
14246 (setq char (1+ char)))
14247 (setq c2 c1))
14248 (setq c (or c2 char)))
14249 (if ingroup (push tg (car groups)))
14250 (setq tg (org-add-props tg nil 'face
14251 (cond
14252 ((not (assoc tg table))
14253 (org-get-todo-face tg))
14254 ((member tg current) c-face)
14255 ((member tg inherited) i-face))))
14256 (if (and (= cnt 0) (not ingroup)) (insert " "))
14257 (insert "[" c "] " tg (make-string
14258 (- fwidth 4 (length tg)) ?\ ))
14259 (push (cons tg c) ntable)
14260 (when (= (setq cnt (1+ cnt)) ncol)
14261 (insert "\n")
14262 (if ingroup (insert " "))
14263 (setq cnt 0)))))
14264 (setq ntable (nreverse ntable))
14265 (insert "\n")
14266 (goto-char (point-min))
14267 (if (not expert) (org-fit-window-to-buffer))
14268 (setq rtn
14269 (catch 'exit
14270 (while t
14271 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14272 (if (not groups) "no " "")
14273 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14274 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14275 (setq org-last-tag-selection-key c)
14276 (cond
14277 ((= c ?\r) (throw 'exit t))
14278 ((= c ?!)
14279 (setq groups (not groups))
14280 (goto-char (point-min))
14281 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14282 ((= c ?\C-c)
14283 (if (not expert)
14284 (org-fast-tag-show-exit
14285 (setq exit-after-next (not exit-after-next)))
14286 (setq expert nil)
14287 (delete-other-windows)
14288 (set-window-buffer (split-window-vertically) " *Org tags*")
14289 (org-switch-to-buffer-other-window " *Org tags*")
14290 (org-fit-window-to-buffer)))
14291 ((or (= c ?\C-g)
14292 (and (= c ?q) (not (rassoc c ntable))))
14293 (org-detach-overlay org-tags-overlay)
14294 (setq quit-flag t))
14295 ((= c ?\ )
14296 (setq current nil)
14297 (if exit-after-next (setq exit-after-next 'now)))
14298 ((= c ?\t)
14299 (condition-case nil
14300 (setq tg (org-icompleting-read
14301 "Tag: "
14302 (or buffer-tags
14303 (with-current-buffer buf
14304 (org-get-buffer-tags)))))
14305 (quit (setq tg "")))
14306 (when (string-match "\\S-" tg)
14307 (add-to-list 'buffer-tags (list tg))
14308 (if (member tg current)
14309 (setq current (delete tg current))
14310 (push tg current)))
14311 (if exit-after-next (setq exit-after-next 'now)))
14312 ((setq e (rassoc c todo-table) tg (car e))
14313 (with-current-buffer buf
14314 (save-excursion (org-todo tg)))
14315 (if exit-after-next (setq exit-after-next 'now)))
14316 ((setq e (rassoc c ntable) tg (car e))
14317 (if (member tg current)
14318 (setq current (delete tg current))
14319 (loop for g in groups do
14320 (if (member tg g)
14321 (mapc (lambda (x)
14322 (setq current (delete x current)))
14323 g)))
14324 (push tg current))
14325 (if exit-after-next (setq exit-after-next 'now))))
14327 ;; Create a sorted list
14328 (setq current
14329 (sort current
14330 (lambda (a b)
14331 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14332 (if (eq exit-after-next 'now) (throw 'exit t))
14333 (goto-char (point-min))
14334 (beginning-of-line 2)
14335 (delete-region (point) (point-at-eol))
14336 (org-fast-tag-insert "Current" current c-face)
14337 (org-set-current-tags-overlay current ov-prefix)
14338 (while (re-search-forward
14339 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14340 (setq tg (match-string 1))
14341 (add-text-properties
14342 (match-beginning 1) (match-end 1)
14343 (list 'face
14344 (cond
14345 ((member tg current) c-face)
14346 ((member tg inherited) i-face)
14347 (t (get-text-property (match-beginning 1) 'face))))))
14348 (goto-char (point-min)))))
14349 (org-detach-overlay org-tags-overlay)
14350 (if rtn
14351 (mapconcat 'identity current ":")
14352 nil))))
14354 (defun org-get-tags-string ()
14355 "Get the TAGS string in the current headline."
14356 (unless (org-at-heading-p t)
14357 (error "Not on a heading"))
14358 (save-excursion
14359 (beginning-of-line 1)
14360 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14361 (org-match-string-no-properties 1)
14362 "")))
14364 (defun org-get-tags ()
14365 "Get the list of tags specified in the current headline."
14366 (org-split-string (org-get-tags-string) ":"))
14368 (defun org-get-buffer-tags ()
14369 "Get a table of all tags used in the buffer, for completion."
14370 (let (tags)
14371 (save-excursion
14372 (goto-char (point-min))
14373 (while (re-search-forward
14374 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14375 (when (equal (char-after (point-at-bol 0)) ?*)
14376 (mapc (lambda (x) (add-to-list 'tags x))
14377 (org-split-string (org-match-string-no-properties 1) ":")))))
14378 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14379 (mapcar 'list tags)))
14381 ;;;; The mapping API
14383 (defun org-map-entries (func &optional match scope &rest skip)
14384 "Call FUNC at each headline selected by MATCH in SCOPE.
14386 FUNC is a function or a lisp form. The function will be called without
14387 arguments, with the cursor positioned at the beginning of the headline.
14388 The return values of all calls to the function will be collected and
14389 returned as a list.
14391 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14392 does not need to preserve point. After evaluation, the cursor will be
14393 moved to the end of the line (presumably of the headline of the
14394 processed entry) and search continues from there. Under some
14395 circumstances, this may not produce the wanted results. For example,
14396 if you have removed (e.g. archived) the current (sub)tree it could
14397 mean that the next entry will be skipped entirely. In such cases, you
14398 can specify the position from where search should continue by making
14399 FUNC set the variable `org-map-continue-from' to the desired buffer
14400 position.
14402 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14403 Only headlines that are matched by this query will be considered during
14404 the iteration. When MATCH is nil or t, all headlines will be
14405 visited by the iteration.
14407 SCOPE determines the scope of this command. It can be any of:
14409 nil The current buffer, respecting the restriction if any
14410 tree The subtree started with the entry at point
14411 region The entries within the active region, if any
14412 region-start-level
14413 The entries within the active region, but only those at
14414 the same level than the first one.
14415 file The current buffer, without restriction
14416 file-with-archives
14417 The current buffer, and any archives associated with it
14418 agenda All agenda files
14419 agenda-with-archives
14420 All agenda files with any archive files associated with them
14421 \(file1 file2 ...)
14422 If this is a list, all files in the list will be scanned
14424 The remaining args are treated as settings for the skipping facilities of
14425 the scanner. The following items can be given here:
14427 archive skip trees with the archive tag.
14428 comment skip trees with the COMMENT keyword
14429 function or Emacs Lisp form:
14430 will be used as value for `org-agenda-skip-function', so whenever
14431 the function returns t, FUNC will not be called for that
14432 entry and search will continue from the point where the
14433 function leaves it.
14435 If your function needs to retrieve the tags including inherited tags
14436 at the *current* entry, you can use the value of the variable
14437 `org-scanner-tags' which will be much faster than getting the value
14438 with `org-get-tags-at'. If your function gets properties with
14439 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14440 to t around the call to `org-entry-properties' to get the same speedup.
14441 Note that if your function moves around to retrieve tags and properties at
14442 a *different* entry, you cannot use these techniques."
14443 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14444 (not (org-region-active-p)))
14445 (let* ((org-agenda-archives-mode nil) ; just to make sure
14446 (org-agenda-skip-archived-trees (memq 'archive skip))
14447 (org-agenda-skip-comment-trees (memq 'comment skip))
14448 (org-agenda-skip-function
14449 (car (org-delete-all '(comment archive) skip)))
14450 (org-tags-match-list-sublevels t)
14451 (start-level (eq scope 'region-start-level))
14452 matcher file res
14453 org-todo-keywords-for-agenda
14454 org-done-keywords-for-agenda
14455 org-todo-keyword-alist-for-agenda
14456 org-drawers-for-agenda
14457 org-tag-alist-for-agenda
14458 todo-only)
14460 (cond
14461 ((eq match t) (setq matcher t))
14462 ((eq match nil) (setq matcher t))
14463 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14465 (save-excursion
14466 (save-restriction
14467 (cond ((eq scope 'tree)
14468 (org-back-to-heading t)
14469 (org-narrow-to-subtree)
14470 (setq scope nil))
14471 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14472 (org-region-active-p))
14473 ;; If needed, set start-level to a string like "2"
14474 (when start-level
14475 (save-excursion
14476 (goto-char (region-beginning))
14477 (unless (org-at-heading-p) (outline-next-heading))
14478 (setq start-level (org-current-level))))
14479 (narrow-to-region (region-beginning)
14480 (save-excursion
14481 (goto-char (region-end))
14482 (unless (and (bolp) (org-at-heading-p))
14483 (outline-next-heading))
14484 (point)))
14485 (setq scope nil)))
14487 (if (not scope)
14488 (progn
14489 (org-agenda-prepare-buffers
14490 (list (buffer-file-name (current-buffer))))
14491 (setq res (org-scan-tags func matcher todo-only start-level)))
14492 ;; Get the right scope
14493 (cond
14494 ((and scope (listp scope) (symbolp (car scope)))
14495 (setq scope (eval scope)))
14496 ((eq scope 'agenda)
14497 (setq scope (org-agenda-files t)))
14498 ((eq scope 'agenda-with-archives)
14499 (setq scope (org-agenda-files t))
14500 (setq scope (org-add-archive-files scope)))
14501 ((eq scope 'file)
14502 (setq scope (list (buffer-file-name))))
14503 ((eq scope 'file-with-archives)
14504 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14505 (org-agenda-prepare-buffers scope)
14506 (while (setq file (pop scope))
14507 (with-current-buffer (org-find-base-buffer-visiting file)
14508 (save-excursion
14509 (save-restriction
14510 (widen)
14511 (goto-char (point-min))
14512 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14513 res)))
14515 ;;;; Properties
14517 ;;; Setting and retrieving properties
14519 (defconst org-special-properties
14520 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14521 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14522 "The special properties valid in Org-mode.
14524 These are properties that are not defined in the property drawer,
14525 but in some other way.")
14527 (defconst org-default-properties
14528 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14529 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14530 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14531 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14532 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14533 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14534 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14535 "Some properties that are used by Org-mode for various purposes.
14536 Being in this list makes sure that they are offered for completion.")
14538 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14539 "Regular expression matching the first line of a property drawer.")
14541 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14542 "Regular expression matching the last line of a property drawer.")
14544 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14545 "Regular expression matching the first line of a property drawer.")
14547 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14548 "Regular expression matching the first line of a property drawer.")
14550 (defconst org-property-drawer-re
14551 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14552 org-property-end-re "\\)\n?")
14553 "Matches an entire property drawer.")
14555 (defconst org-clock-drawer-re
14556 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14557 org-property-end-re "\\)\n?")
14558 "Matches an entire clock drawer.")
14560 (defsubst org-re-property (property)
14561 "Return a regexp matching a PROPERTY line.
14562 Match group 1 will be set to the value."
14563 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14565 (defsubst org-re-property-keyword (property)
14566 "Return a regexp matching a PROPERTY line, possibly with no
14567 value for the property."
14568 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14570 (defun org-property-action ()
14571 "Do an action on properties."
14572 (interactive)
14573 (let (c)
14574 (org-at-property-p)
14575 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14576 (setq c (read-char-exclusive))
14577 (cond
14578 ((equal c ?s)
14579 (call-interactively 'org-set-property))
14580 ((equal c ?d)
14581 (call-interactively 'org-delete-property))
14582 ((equal c ?D)
14583 (call-interactively 'org-delete-property-globally))
14584 ((equal c ?c)
14585 (call-interactively 'org-compute-property-at-point))
14586 (t (error "No such property action %c" c)))))
14588 (defun org-inc-effort ()
14589 "Increment the value of the effort property in the current entry."
14590 (interactive)
14591 (org-set-effort nil t))
14593 (defun org-set-effort (&optional value increment)
14594 "Set the effort property of the current entry.
14595 With numerical prefix arg, use the nth allowed value, 0 stands for the
14596 10th allowed value.
14598 When INCREMENT is non-nil, set the property to the next allowed value."
14599 (interactive "P")
14600 (if (equal value 0) (setq value 10))
14601 (let* ((completion-ignore-case t)
14602 (prop org-effort-property)
14603 (cur (org-entry-get nil prop))
14604 (allowed (org-property-get-allowed-values nil prop 'table))
14605 (existing (mapcar 'list (org-property-values prop)))
14607 (val (cond
14608 ((stringp value) value)
14609 ((and allowed (integerp value))
14610 (or (car (nth (1- value) allowed))
14611 (car (org-last allowed))))
14612 ((and allowed increment)
14613 (or (caadr (member (list cur) allowed))
14614 (error "Allowed effort values are not set")))
14615 (allowed
14616 (message "Select 1-9,0, [RET%s]: %s"
14617 (if cur (concat "=" cur) "")
14618 (mapconcat 'car allowed " "))
14619 (setq rpl (read-char-exclusive))
14620 (if (equal rpl ?\r)
14622 (setq rpl (- rpl ?0))
14623 (if (equal rpl 0) (setq rpl 10))
14624 (if (and (> rpl 0) (<= rpl (length allowed)))
14625 (car (nth (1- rpl) allowed))
14626 (org-completing-read "Effort: " allowed nil))))
14628 (let (org-completion-use-ido org-completion-use-iswitchb)
14629 (org-completing-read
14630 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14631 (concat "[" cur "]") "")
14632 ": ")
14633 existing nil nil "" nil cur))))))
14634 (unless (equal (org-entry-get nil prop) val)
14635 (org-entry-put nil prop val))
14636 (save-excursion
14637 (org-back-to-heading t)
14638 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14639 (message "%s is now %s" prop val)))
14641 (defun org-at-property-p ()
14642 "Is cursor inside a property drawer?"
14643 (save-excursion
14644 (beginning-of-line 1)
14645 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14646 (save-match-data ;; Used by calling procedures
14647 (let ((p (point))
14648 (range (unless (org-before-first-heading-p)
14649 (org-get-property-block))))
14650 (and range (<= (car range) p) (< p (cdr range))))))))
14652 (defun org-get-property-block (&optional beg end force)
14653 "Return the (beg . end) range of the body of the property drawer.
14654 BEG and END are the beginning and end of the current subtree, or of
14655 the part before the first headline. If they are not given, they will
14656 be found. If the drawer does not exist and FORCE is non-nil, create
14657 the drawer."
14658 (catch 'exit
14659 (save-excursion
14660 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14661 (progn (org-back-to-heading t) (point))))
14662 (end (or end (and (not (outline-next-heading)) (point-max))
14663 (point))))
14664 (goto-char beg)
14665 (if (re-search-forward org-property-start-re end t)
14666 (setq beg (1+ (match-end 0)))
14667 (if force
14668 (save-excursion
14669 (org-insert-property-drawer)
14670 (setq end (progn (outline-next-heading) (point))))
14671 (throw 'exit nil))
14672 (goto-char beg)
14673 (if (re-search-forward org-property-start-re end t)
14674 (setq beg (1+ (match-end 0)))))
14675 (if (re-search-forward org-property-end-re end t)
14676 (setq end (match-beginning 0))
14677 (or force (throw 'exit nil))
14678 (goto-char beg)
14679 (setq end beg)
14680 (org-indent-line)
14681 (insert ":END:\n"))
14682 (cons beg end)))))
14684 (defun org-entry-properties (&optional pom which specific)
14685 "Get all properties of the entry at point-or-marker POM.
14686 This includes the TODO keyword, the tags, time strings for deadline,
14687 scheduled, and clocking, and any additional properties defined in the
14688 entry. The return value is an alist, keys may occur multiple times
14689 if the property key was used several times.
14690 POM may also be nil, in which case the current entry is used.
14691 If WHICH is nil or `all', get all properties. If WHICH is
14692 `special' or `standard', only get that subclass. If WHICH
14693 is a string only get exactly this property. SPECIFIC can be a string, the
14694 specific property we are interested in. Specifying it can speed
14695 things up because then unnecessary parsing is avoided."
14696 (setq which (or which 'all))
14697 (org-with-point-at pom
14698 (let ((clockstr (substring org-clock-string 0 -1))
14699 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14700 (case-fold-search nil)
14701 beg end range props sum-props key key1 value string clocksum clocksumt)
14702 (save-excursion
14703 (when (condition-case nil
14704 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14705 (error nil))
14706 (setq beg (point))
14707 (setq sum-props (get-text-property (point) 'org-summaries))
14708 (setq clocksum (get-text-property (point) :org-clock-minutes)
14709 clocksumt (get-text-property (point) :org-clock-minutes-today))
14710 (outline-next-heading)
14711 (setq end (point))
14712 (when (memq which '(all special))
14713 ;; Get the special properties, like TODO and tags
14714 (goto-char beg)
14715 (when (and (or (not specific) (string= specific "TODO"))
14716 (looking-at org-todo-line-regexp) (match-end 2))
14717 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14718 (when (and (or (not specific) (string= specific "PRIORITY"))
14719 (looking-at org-priority-regexp))
14720 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14721 (when (or (not specific) (string= specific "FILE"))
14722 (push (cons "FILE" buffer-file-name) props))
14723 (when (and (or (not specific) (string= specific "TAGS"))
14724 (setq value (org-get-tags-string))
14725 (string-match "\\S-" value))
14726 (push (cons "TAGS" value) props))
14727 (when (and (or (not specific) (string= specific "ALLTAGS"))
14728 (setq value (org-get-tags-at)))
14729 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14730 ":"))
14731 props))
14732 (when (or (not specific) (string= specific "BLOCKED"))
14733 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14734 (when (or (not specific)
14735 (member specific
14736 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14737 "TIMESTAMP" "TIMESTAMP_IA")))
14738 (catch 'match
14739 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14740 (setq key (if (match-end 1)
14741 (substring (org-match-string-no-properties 1)
14742 0 -1))
14743 string (if (equal key clockstr)
14744 (org-trim
14745 (buffer-substring-no-properties
14746 (match-beginning 3) (goto-char
14747 (point-at-eol))))
14748 (substring (org-match-string-no-properties 3)
14749 1 -1)))
14750 ;; Get the correct property name from the key. This is
14751 ;; necessary if the user has configured time keywords.
14752 (setq key1 (concat key ":"))
14753 (cond
14754 ((not key)
14755 (setq key
14756 (if (= (char-after (match-beginning 3)) ?\[)
14757 "TIMESTAMP_IA" "TIMESTAMP")))
14758 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14759 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14760 ((equal key1 org-closed-string) (setq key "CLOSED"))
14761 ((equal key1 org-clock-string) (setq key "CLOCK")))
14762 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14763 (progn
14764 (push (cons key string) props)
14765 ;; no need to search further if match is found
14766 (throw 'match t))
14767 (when (or (equal key "CLOCK") (not (assoc key props)))
14768 (push (cons key string) props)))))))
14770 (when (memq which '(all standard))
14771 ;; Get the standard properties, like :PROP: ...
14772 (setq range (org-get-property-block beg end))
14773 (when range
14774 (goto-char (car range))
14775 (while (re-search-forward
14776 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14777 (cdr range) t)
14778 (setq key (org-match-string-no-properties 1)
14779 value (org-trim (or (org-match-string-no-properties 2) "")))
14780 (unless (member key excluded)
14781 (push (cons key (or value "")) props)))))
14782 (if clocksum
14783 (push (cons "CLOCKSUM"
14784 (org-columns-number-to-string (/ (float clocksum) 60.)
14785 'add_times))
14786 props))
14787 (if clocksumt
14788 (push (cons "CLOCKSUM_T"
14789 (org-columns-number-to-string (/ (float clocksumt) 60.)
14790 'add_times))
14791 props))
14792 (unless (assoc "CATEGORY" props)
14793 (push (cons "CATEGORY" (org-get-category)) props))
14794 (append sum-props (nreverse props)))))))
14796 (defun org-entry-get (pom property &optional inherit literal-nil)
14797 "Get value of PROPERTY for entry or content at point-or-marker POM.
14798 If INHERIT is non-nil and the entry does not have the property,
14799 then also check higher levels of the hierarchy.
14800 If INHERIT is the symbol `selective', use inheritance only if the setting
14801 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14802 If the property is present but empty, the return value is the empty string.
14803 If the property is not present at all, nil is returned.
14805 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14806 do not interpret it as the list atom nil. This is used for inheritance
14807 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14808 (org-with-point-at pom
14809 (if (and inherit (if (eq inherit 'selective)
14810 (org-property-inherit-p property)
14812 (org-entry-get-with-inheritance property literal-nil)
14813 (if (member property org-special-properties)
14814 ;; We need a special property. Use `org-entry-properties' to
14815 ;; retrieve it, but specify the wanted property
14816 (cdr (assoc property (org-entry-properties nil 'special property)))
14817 (let ((range (org-get-property-block)))
14818 (when (and range (not (eq (car range) (cdr range))))
14819 (let* ((props (list (or (assoc property org-file-properties)
14820 (assoc property org-global-properties)
14821 (assoc property org-global-properties-fixed))))
14822 (ap (lambda (key)
14823 (when (re-search-forward
14824 (org-re-property key) (cdr range) t)
14825 (setq props
14826 (org-update-property-plist
14828 (if (match-end 1)
14829 (org-match-string-no-properties 1) "")
14830 props)))))
14831 val)
14832 (goto-char (car range))
14833 (funcall ap property)
14834 (goto-char (car range))
14835 (while (funcall ap (concat property "+")))
14836 (setq val (cdr (assoc property props)))
14837 (when val (if literal-nil val (org-not-nil val))))))))))
14839 (defun org-property-or-variable-value (var &optional inherit)
14840 "Check if there is a property fixing the value of VAR.
14841 If yes, return this value. If not, return the current value of the variable."
14842 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14843 (if (and prop (stringp prop) (string-match "\\S-" prop))
14844 (read prop)
14845 (symbol-value var))))
14847 (defun org-entry-delete (pom property)
14848 "Delete the property PROPERTY from entry at point-or-marker POM."
14849 (org-with-point-at pom
14850 (if (member property org-special-properties)
14851 nil ; cannot delete these properties.
14852 (let ((range (org-get-property-block)))
14853 (if (and range
14854 (goto-char (car range))
14855 (re-search-forward
14856 (org-re-property property)
14857 (cdr range) t))
14858 (progn
14859 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14861 nil)))))
14863 ;; Multi-values properties are properties that contain multiple values
14864 ;; These values are assumed to be single words, separated by whitespace.
14865 (defun org-entry-add-to-multivalued-property (pom property value)
14866 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14867 (let* ((old (org-entry-get pom property))
14868 (values (and old (org-split-string old "[ \t]"))))
14869 (setq value (org-entry-protect-space value))
14870 (unless (member value values)
14871 (setq values (cons value values))
14872 (org-entry-put pom property
14873 (mapconcat 'identity values " ")))))
14875 (defun org-entry-remove-from-multivalued-property (pom property value)
14876 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14877 (let* ((old (org-entry-get pom property))
14878 (values (and old (org-split-string old "[ \t]"))))
14879 (setq value (org-entry-protect-space value))
14880 (when (member value values)
14881 (setq values (delete value values))
14882 (org-entry-put pom property
14883 (mapconcat 'identity values " ")))))
14885 (defun org-entry-member-in-multivalued-property (pom property value)
14886 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14887 (let* ((old (org-entry-get pom property))
14888 (values (and old (org-split-string old "[ \t]"))))
14889 (setq value (org-entry-protect-space value))
14890 (member value values)))
14892 (defun org-entry-get-multivalued-property (pom property)
14893 "Return a list of values in a multivalued property."
14894 (let* ((value (org-entry-get pom property))
14895 (values (and value (org-split-string value "[ \t]"))))
14896 (mapcar 'org-entry-restore-space values)))
14898 (defun org-entry-put-multivalued-property (pom property &rest values)
14899 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14900 VALUES should be a list of strings. Spaces will be protected."
14901 (org-entry-put pom property
14902 (mapconcat 'org-entry-protect-space values " "))
14903 (let* ((value (org-entry-get pom property))
14904 (values (and value (org-split-string value "[ \t]"))))
14905 (mapcar 'org-entry-restore-space values)))
14907 (defun org-entry-protect-space (s)
14908 "Protect spaces and newline in string S."
14909 (while (string-match " " s)
14910 (setq s (replace-match "%20" t t s)))
14911 (while (string-match "\n" s)
14912 (setq s (replace-match "%0A" t t s)))
14915 (defun org-entry-restore-space (s)
14916 "Restore spaces and newline in string S."
14917 (while (string-match "%20" s)
14918 (setq s (replace-match " " t t s)))
14919 (while (string-match "%0A" s)
14920 (setq s (replace-match "\n" t t s)))
14923 (defvar org-entry-property-inherited-from (make-marker)
14924 "Marker pointing to the entry from where a property was inherited.
14925 Each call to `org-entry-get-with-inheritance' will set this marker to the
14926 location of the entry where the inheritance search matched. If there was
14927 no match, the marker will point nowhere.
14928 Note that also `org-entry-get' calls this function, if the INHERIT flag
14929 is set.")
14931 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14932 "Get PROPERTY of entry or content at point, search higher levels if needed.
14933 The search will stop at the first ancestor which has the property defined.
14934 If the value found is \"nil\", return nil to show that the property
14935 should be considered as undefined (this is the meaning of nil here).
14936 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14937 (move-marker org-entry-property-inherited-from nil)
14938 (let (tmp)
14939 (save-excursion
14940 (save-restriction
14941 (widen)
14942 (catch 'ex
14943 (while t
14944 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14945 (or (ignore-errors (org-back-to-heading t))
14946 (goto-char (point-min)))
14947 (move-marker org-entry-property-inherited-from (point))
14948 (throw 'ex tmp))
14949 (or (ignore-errors (org-up-heading-safe))
14950 (throw 'ex nil))))))
14951 (setq tmp (or tmp
14952 (cdr (assoc property org-file-properties))
14953 (cdr (assoc property org-global-properties))
14954 (cdr (assoc property org-global-properties-fixed))))
14955 (if literal-nil tmp (org-not-nil tmp))))
14957 (defvar org-property-changed-functions nil
14958 "Hook called when the value of a property has changed.
14959 Each hook function should accept two arguments, the name of the property
14960 and the new value.")
14962 (defun org-entry-put (pom property value)
14963 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14964 (org-with-point-at pom
14965 (org-back-to-heading t)
14966 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14967 range)
14968 (cond
14969 ((equal property "TODO")
14970 (when (and (stringp value) (string-match "\\S-" value)
14971 (not (member value org-todo-keywords-1)))
14972 (error "\"%s\" is not a valid TODO state" value))
14973 (if (or (not value)
14974 (not (string-match "\\S-" value)))
14975 (setq value 'none))
14976 (org-todo value)
14977 (org-set-tags nil 'align))
14978 ((equal property "PRIORITY")
14979 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14980 (string-to-char value) ?\ ))
14981 (org-set-tags nil 'align))
14982 ((equal property "CLOCKSUM")
14983 (if (not (re-search-forward
14984 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14985 (error "Cannot find a clock log")
14986 (goto-char (- (match-end 1) 2))
14987 (cond
14988 ((eq value 'earlier) (org-timestamp-down))
14989 ((eq value 'later) (org-timestamp-up)))
14990 (org-clock-sum-current-item)))
14991 ((equal property "SCHEDULED")
14992 (if (re-search-forward org-scheduled-time-regexp end t)
14993 (cond
14994 ((eq value 'earlier) (org-timestamp-change -1 'day))
14995 ((eq value 'later) (org-timestamp-change 1 'day))
14996 (t (call-interactively 'org-schedule)))
14997 (call-interactively 'org-schedule)))
14998 ((equal property "DEADLINE")
14999 (if (re-search-forward org-deadline-time-regexp end t)
15000 (cond
15001 ((eq value 'earlier) (org-timestamp-change -1 'day))
15002 ((eq value 'later) (org-timestamp-change 1 'day))
15003 (t (call-interactively 'org-deadline)))
15004 (call-interactively 'org-deadline)))
15005 ((member property org-special-properties)
15006 (error "The %s property can not yet be set with `org-entry-put'"
15007 property))
15008 (t ; a non-special property
15009 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15010 (setq range (org-get-property-block beg end 'force))
15011 (goto-char (car range))
15012 (if (re-search-forward
15013 (org-re-property-keyword property) (cdr range) t)
15014 (progn
15015 (delete-region (match-beginning 0) (match-end 0))
15016 (goto-char (match-beginning 0)))
15017 (goto-char (cdr range))
15018 (insert "\n")
15019 (backward-char 1)
15020 (org-indent-line))
15021 (insert ":" property ":")
15022 (and value (insert " " value))
15023 (org-indent-line)))))
15024 (run-hook-with-args 'org-property-changed-functions property value)))
15026 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15027 "Get all property keys in the current buffer.
15028 With INCLUDE-SPECIALS, also list the special properties that reflect things
15029 like tags and TODO state.
15030 With INCLUDE-DEFAULTS, also include properties that has special meaning
15031 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15032 and others.
15033 With INCLUDE-COLUMNS, also include property names given in COLUMN
15034 formats in the current buffer."
15035 (let (rtn range cfmt s p)
15036 (save-excursion
15037 (save-restriction
15038 (widen)
15039 (goto-char (point-min))
15040 (while (re-search-forward org-property-start-re nil t)
15041 (setq range (org-get-property-block))
15042 (goto-char (car range))
15043 (while (re-search-forward
15044 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15045 (cdr range) t)
15046 (add-to-list 'rtn (org-match-string-no-properties 1)))
15047 (outline-next-heading))))
15049 (when include-specials
15050 (setq rtn (append org-special-properties rtn)))
15052 (when include-defaults
15053 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15054 (add-to-list 'rtn org-effort-property))
15056 (when include-columns
15057 (save-excursion
15058 (save-restriction
15059 (widen)
15060 (goto-char (point-min))
15061 (while (re-search-forward
15062 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15063 nil t)
15064 (setq cfmt (match-string 2) s 0)
15065 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15066 cfmt s)
15067 (setq s (match-end 0)
15068 p (match-string 1 cfmt))
15069 (unless (or (equal p "ITEM")
15070 (member p org-special-properties))
15071 (add-to-list 'rtn (match-string 1 cfmt))))))))
15073 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15075 (defun org-property-values (key)
15076 "Return a list of all values of property KEY in the current buffer."
15077 (save-excursion
15078 (save-restriction
15079 (widen)
15080 (goto-char (point-min))
15081 (let ((re (org-re-property key))
15082 values)
15083 (while (re-search-forward re nil t)
15084 (add-to-list 'values (org-trim (match-string 1))))
15085 (delete "" values)))))
15087 (defun org-insert-property-drawer ()
15088 "Insert a property drawer into the current entry."
15089 (org-back-to-heading t)
15090 (looking-at org-outline-regexp)
15091 (let ((indent (if org-adapt-indentation
15092 (- (match-end 0) (match-beginning 0))
15094 (beg (point))
15095 (re (concat "^[ \t]*" org-keyword-time-regexp))
15096 end hiddenp)
15097 (outline-next-heading)
15098 (setq end (point))
15099 (goto-char beg)
15100 (while (re-search-forward re end t))
15101 (setq hiddenp (outline-invisible-p))
15102 (end-of-line 1)
15103 (and (equal (char-after) ?\n) (forward-char 1))
15104 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15105 (if (member (match-string 1) '("CLOCK:" ":END:"))
15106 ;; just skip this line
15107 (beginning-of-line 2)
15108 ;; Drawer start, find the end
15109 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15110 (beginning-of-line 1)))
15111 (org-skip-over-state-notes)
15112 (skip-chars-backward " \t\n\r")
15113 (if (eq (char-before) ?*) (forward-char 1))
15114 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15115 (beginning-of-line 0)
15116 (org-indent-to-column indent)
15117 (beginning-of-line 2)
15118 (org-indent-to-column indent)
15119 (beginning-of-line 0)
15120 (if hiddenp
15121 (save-excursion
15122 (org-back-to-heading t)
15123 (hide-entry))
15124 (org-flag-drawer t))))
15126 (defun org-insert-drawer (&optional arg drawer)
15127 "Insert a drawer at point.
15129 Optional argument DRAWER, when non-nil, is a string representing
15130 drawer's name. Otherwise, the user is prompted for a name.
15132 If a region is active, insert the drawer around that region
15133 instead.
15135 Point is left between drawer's boundaries."
15136 (interactive "P")
15137 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15138 "LOGBOOK"))
15139 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15140 ;; internally by Org. They are meant to be inserted
15141 ;; automatically.
15142 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15143 ;; Remove system drawers from list. Note: For some reason,
15144 ;; `org-completing-read' ignores the predicate while
15145 ;; `completing-read' handles it fine.
15146 (drawer (if arg "PROPERTIES"
15147 (or drawer
15148 (completing-read
15149 "Drawer: " org-drawers
15150 (lambda (d) (not (member d system-drawers))))))))
15151 (cond
15152 ;; With C-u, fall back on `org-insert-property-drawer'
15153 (arg (org-insert-property-drawer))
15154 ;; With an active region, insert a drawer at point.
15155 ((not (org-region-active-p))
15156 (progn
15157 (unless (bolp) (insert "\n"))
15158 (insert (format ":%s:\n\n:END:\n" drawer))
15159 (forward-line -2)))
15160 ;; Otherwise, insert the drawer at point
15162 (let ((rbeg (region-beginning))
15163 (rend (copy-marker (region-end))))
15164 (unwind-protect
15165 (progn
15166 (goto-char rbeg)
15167 (beginning-of-line)
15168 (when (save-excursion
15169 (re-search-forward org-outline-regexp-bol rend t))
15170 (error "Drawers cannot contain headlines"))
15171 ;; Position point at the beginning of the first
15172 ;; non-blank line in region. Insert drawer's opening
15173 ;; there, then indent it.
15174 (org-skip-whitespace)
15175 (beginning-of-line)
15176 (insert ":" drawer ":\n")
15177 (forward-line -1)
15178 (indent-for-tab-command)
15179 ;; Move point to the beginning of the first blank line
15180 ;; after the last non-blank line in region. Insert
15181 ;; drawer's closing, then indent it.
15182 (goto-char rend)
15183 (skip-chars-backward " \r\t\n")
15184 (insert "\n:END:")
15185 (deactivate-mark t)
15186 (indent-for-tab-command)
15187 (unless (eolp) (insert "\n")))
15188 ;; Clear marker, whatever the outcome of insertion is.
15189 (set-marker rend nil)))))))
15191 (defvar org-property-set-functions-alist nil
15192 "Property set function alist.
15193 Each entry should have the following format:
15195 (PROPERTY . READ-FUNCTION)
15197 The read function will be called with the same argument as
15198 `org-completing-read'.")
15200 (defun org-set-property-function (property)
15201 "Get the function that should be used to set PROPERTY.
15202 This is computed according to `org-property-set-functions-alist'."
15203 (or (cdr (assoc property org-property-set-functions-alist))
15204 'org-completing-read))
15206 (defun org-read-property-value (property)
15207 "Read PROPERTY value from user."
15208 (let* ((completion-ignore-case t)
15209 (allowed (org-property-get-allowed-values nil property 'table))
15210 (cur (org-entry-get nil property))
15211 (prompt (concat property " value"
15212 (if (and cur (string-match "\\S-" cur))
15213 (concat " [" cur "]") "") ": "))
15214 (set-function (org-set-property-function property))
15215 (val (if allowed
15216 (funcall set-function prompt allowed nil
15217 (not (get-text-property 0 'org-unrestricted
15218 (caar allowed))))
15219 (let (org-completion-use-ido org-completion-use-iswitchb)
15220 (funcall set-function prompt
15221 (mapcar 'list (org-property-values property))
15222 nil nil "" nil cur)))))
15223 (if (equal val "")
15225 val)))
15227 (defvar org-last-set-property nil)
15228 (defvar org-last-set-property-value nil)
15229 (defun org-read-property-name ()
15230 "Read a property name."
15231 (let* ((completion-ignore-case t)
15232 (keys (org-buffer-property-keys nil t t))
15233 (default-prop (or (save-excursion
15234 (save-match-data
15235 (beginning-of-line)
15236 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15237 (null (string= (match-string 1) "END"))
15238 (match-string 1))))
15239 org-last-set-property))
15240 (property (org-icompleting-read
15241 (concat "Property"
15242 (if default-prop (concat " [" default-prop "]") "")
15243 ": ")
15244 (mapcar 'list keys)
15245 nil nil nil nil
15246 default-prop)))
15247 (if (member property keys)
15248 property
15249 (or (cdr (assoc (downcase property)
15250 (mapcar (lambda (x) (cons (downcase x) x))
15251 keys)))
15252 property))))
15254 (defun org-set-property-and-value (use-last)
15255 "Allow to set [PROPERTY]: [value] direction from prompt.
15256 When use-default, don't even ask, just use the last
15257 \"[PROPERTY]: [value]\" string from the history."
15258 (interactive "P")
15259 (let* ((completion-ignore-case t)
15260 (pv (or (and use-last org-last-set-property-value)
15261 (org-completing-read
15262 "Enter a \"[Property]: [value]\" pair: "
15263 nil nil nil nil nil
15264 org-last-set-property-value)))
15265 prop val)
15266 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15267 (setq prop (match-string 1 pv)
15268 val (match-string 2 pv))
15269 (org-set-property prop val))))
15271 (defun org-set-property (property value)
15272 "In the current entry, set PROPERTY to VALUE.
15273 When called interactively, this will prompt for a property name, offering
15274 completion on existing and default properties. And then it will prompt
15275 for a value, offering completion either on allowed values (via an inherited
15276 xxx_ALL property) or on existing values in other instances of this property
15277 in the current file."
15278 (interactive (list nil nil))
15279 (let* ((property (or property (org-read-property-name)))
15280 (value (or value (org-read-property-value property)))
15281 (fn (cdr (assoc property org-properties-postprocess-alist))))
15282 (setq org-last-set-property property)
15283 (setq org-last-set-property-value (concat property ": " value))
15284 ;; Possibly postprocess the inserted value:
15285 (when fn (setq value (funcall fn value)))
15286 (unless (equal (org-entry-get nil property) value)
15287 (org-entry-put nil property value))))
15289 (defun org-delete-property (property)
15290 "In the current entry, delete PROPERTY."
15291 (interactive
15292 (let* ((completion-ignore-case t)
15293 (prop (org-icompleting-read "Property: "
15294 (org-entry-properties nil 'standard))))
15295 (list prop)))
15296 (message "Property %s %s" property
15297 (if (org-entry-delete nil property)
15298 "deleted"
15299 "was not present in the entry")))
15301 (defun org-delete-property-globally (property)
15302 "Remove PROPERTY globally, from all entries."
15303 (interactive
15304 (let* ((completion-ignore-case t)
15305 (prop (org-icompleting-read
15306 "Globally remove property: "
15307 (mapcar 'list (org-buffer-property-keys)))))
15308 (list prop)))
15309 (save-excursion
15310 (save-restriction
15311 (widen)
15312 (goto-char (point-min))
15313 (let ((cnt 0))
15314 (while (re-search-forward
15315 (org-re-property property)
15316 nil t)
15317 (setq cnt (1+ cnt))
15318 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15319 (message "Property \"%s\" removed from %d entries" property cnt)))))
15321 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15323 (defun org-compute-property-at-point ()
15324 "Compute the property at point.
15325 This looks for an enclosing column format, extracts the operator and
15326 then applies it to the property in the column format's scope."
15327 (interactive)
15328 (unless (org-at-property-p)
15329 (error "Not at a property"))
15330 (let ((prop (org-match-string-no-properties 2)))
15331 (org-columns-get-format-and-top-level)
15332 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15333 (error "No operator defined for property %s" prop))
15334 (org-columns-compute prop)))
15336 (defvar org-property-allowed-value-functions nil
15337 "Hook for functions supplying allowed values for a specific property.
15338 The functions must take a single argument, the name of the property, and
15339 return a flat list of allowed values. If \":ETC\" is one of
15340 the values, this means that these values are intended as defaults for
15341 completion, but that other values should be allowed too.
15342 The functions must return nil if they are not responsible for this
15343 property.")
15345 (defun org-property-get-allowed-values (pom property &optional table)
15346 "Get allowed values for the property PROPERTY.
15347 When TABLE is non-nil, return an alist that can directly be used for
15348 completion."
15349 (let (vals)
15350 (cond
15351 ((equal property "TODO")
15352 (setq vals (org-with-point-at pom
15353 (append org-todo-keywords-1 '("")))))
15354 ((equal property "PRIORITY")
15355 (let ((n org-lowest-priority))
15356 (while (>= n org-highest-priority)
15357 (push (char-to-string n) vals)
15358 (setq n (1- n)))))
15359 ((member property org-special-properties))
15360 ((setq vals (run-hook-with-args-until-success
15361 'org-property-allowed-value-functions property)))
15363 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15364 (when (and vals (string-match "\\S-" vals))
15365 (setq vals (car (read-from-string (concat "(" vals ")"))))
15366 (setq vals (mapcar (lambda (x)
15367 (cond ((stringp x) x)
15368 ((numberp x) (number-to-string x))
15369 ((symbolp x) (symbol-name x))
15370 (t "???")))
15371 vals)))))
15372 (when (member ":ETC" vals)
15373 (setq vals (remove ":ETC" vals))
15374 (org-add-props (car vals) '(org-unrestricted t)))
15375 (if table (mapcar 'list vals) vals)))
15377 (defun org-property-previous-allowed-value (&optional previous)
15378 "Switch to the next allowed value for this property."
15379 (interactive)
15380 (org-property-next-allowed-value t))
15382 (defun org-property-next-allowed-value (&optional previous)
15383 "Switch to the next allowed value for this property."
15384 (interactive)
15385 (unless (org-at-property-p)
15386 (error "Not at a property"))
15387 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15388 (key (match-string 2))
15389 (value (match-string 3))
15390 (allowed (or (org-property-get-allowed-values (point) key)
15391 (and (member value '("[ ]" "[-]" "[X]"))
15392 '("[ ]" "[X]"))))
15393 nval)
15394 (unless allowed
15395 (error "Allowed values for this property have not been defined"))
15396 (if previous (setq allowed (reverse allowed)))
15397 (if (member value allowed)
15398 (setq nval (car (cdr (member value allowed)))))
15399 (setq nval (or nval (car allowed)))
15400 (if (equal nval value)
15401 (error "Only one allowed value for this property"))
15402 (org-at-property-p)
15403 (replace-match (concat " :" key ": " nval) t t)
15404 (org-indent-line)
15405 (beginning-of-line 1)
15406 (skip-chars-forward " \t")
15407 (when (equal prop org-effort-property)
15408 (save-excursion
15409 (org-back-to-heading t)
15410 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15411 (run-hook-with-args 'org-property-changed-functions key nval)))
15413 (defun org-find-olp (path &optional this-buffer)
15414 "Return a marker pointing to the entry at outline path OLP.
15415 If anything goes wrong, throw an error.
15416 You can wrap this call to catch the error like this:
15418 (condition-case msg
15419 (org-mobile-locate-entry (match-string 4))
15420 (error (nth 1 msg)))
15422 The return value will then be either a string with the error message,
15423 or a marker if everything is OK.
15425 If THIS-BUFFER is set, the outline path does not contain a file,
15426 only headings."
15427 (let* ((file (if this-buffer buffer-file-name (pop path)))
15428 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15429 (level 1)
15430 (lmin 1)
15431 (lmax 1)
15432 limit re end found pos heading cnt flevel)
15433 (unless buffer (error "File not found :%s" file))
15434 (with-current-buffer buffer
15435 (save-excursion
15436 (save-restriction
15437 (widen)
15438 (setq limit (point-max))
15439 (goto-char (point-min))
15440 (while (setq heading (pop path))
15441 (setq re (format org-complex-heading-regexp-format
15442 (regexp-quote heading)))
15443 (setq cnt 0 pos (point))
15444 (while (re-search-forward re end t)
15445 (setq level (- (match-end 1) (match-beginning 1)))
15446 (if (and (>= level lmin) (<= level lmax))
15447 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15448 (when (= cnt 0) (error "Heading not found on level %d: %s"
15449 lmax heading))
15450 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15451 lmax heading))
15452 (goto-char found)
15453 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15454 (setq end (save-excursion (org-end-of-subtree t t))))
15455 (when (org-at-heading-p)
15456 (point-marker)))))))
15458 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15459 "Find node HEADING in BUFFER.
15460 Return a marker to the heading if it was found, or nil if not.
15461 If POS-ONLY is set, return just the position instead of a marker.
15463 The heading text must match exact, but it may have a TODO keyword,
15464 a priority cookie and tags in the standard locations."
15465 (with-current-buffer (or buffer (current-buffer))
15466 (save-excursion
15467 (save-restriction
15468 (widen)
15469 (goto-char (point-min))
15470 (let (case-fold-search)
15471 (if (re-search-forward
15472 (format org-complex-heading-regexp-format
15473 (regexp-quote heading)) nil t)
15474 (if pos-only
15475 (match-beginning 0)
15476 (move-marker (make-marker) (match-beginning 0)))))))))
15478 (defun org-find-exact-heading-in-directory (heading &optional dir)
15479 "Find Org node headline HEADING in all .org files in directory DIR.
15480 When the target headline is found, return a marker to this location."
15481 (let ((files (directory-files (or dir default-directory)
15482 nil "\\`[^.#].*\\.org\\'"))
15483 file visiting m buffer)
15484 (catch 'found
15485 (while (setq file (pop files))
15486 (message "trying %s" file)
15487 (setq visiting (org-find-base-buffer-visiting file))
15488 (setq buffer (or visiting (find-file-noselect file)))
15489 (setq m (org-find-exact-headline-in-buffer
15490 heading buffer))
15491 (when (and (not m) (not visiting)) (kill-buffer buffer))
15492 (and m (throw 'found m))))))
15494 (defun org-find-entry-with-id (ident)
15495 "Locate the entry that contains the ID property with exact value IDENT.
15496 IDENT can be a string, a symbol or a number, this function will search for
15497 the string representation of it.
15498 Return the position where this entry starts, or nil if there is no such entry."
15499 (interactive "sID: ")
15500 (let ((id (cond
15501 ((stringp ident) ident)
15502 ((symbol-name ident) (symbol-name ident))
15503 ((numberp ident) (number-to-string ident))
15504 (t (error "IDENT %s must be a string, symbol or number" ident))))
15505 (case-fold-search nil))
15506 (save-excursion
15507 (save-restriction
15508 (widen)
15509 (goto-char (point-min))
15510 (when (re-search-forward
15511 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15512 nil t)
15513 (org-back-to-heading t)
15514 (point))))))
15516 ;;;; Timestamps
15518 (defvar org-last-changed-timestamp nil)
15519 (defvar org-last-inserted-timestamp nil
15520 "The last time stamp inserted with `org-insert-time-stamp'.")
15521 (defvar org-time-was-given) ; dynamically scoped parameter
15522 (defvar org-end-time-was-given) ; dynamically scoped parameter
15523 (defvar org-ts-what) ; dynamically scoped parameter
15525 (defun org-time-stamp (arg &optional inactive)
15526 "Prompt for a date/time and insert a time stamp.
15527 If the user specifies a time like HH:MM or if this command is
15528 called with at least one prefix argument, the time stamp contains
15529 the date and the time. Otherwise, only the date is be included.
15531 All parts of a date not specified by the user is filled in from
15532 the current date/time. So if you just press return without
15533 typing anything, the time stamp will represent the current
15534 date/time.
15536 If there is already a timestamp at the cursor, it will be
15537 modified.
15539 With two universal prefix arguments, insert an active timestamp
15540 with the current time without prompting the user."
15541 (interactive "P")
15542 (let* ((ts nil)
15543 (default-time
15544 ;; Default time is either today, or, when entering a range,
15545 ;; the range start.
15546 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15547 (save-excursion
15548 (re-search-backward
15549 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15550 (- (point) 20) t)))
15551 (apply 'encode-time (org-parse-time-string (match-string 1)))
15552 (current-time)))
15553 (default-input (and ts (org-get-compact-tod ts)))
15554 (repeater (save-excursion
15555 (save-match-data
15556 (beginning-of-line)
15557 (when (re-search-forward
15558 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15559 (save-excursion (progn (end-of-line) (point))) t)
15560 (match-string 0)))))
15561 org-time-was-given org-end-time-was-given time)
15562 (cond
15563 ((and (org-at-timestamp-p t)
15564 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15565 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15566 (insert "--")
15567 (setq time (let ((this-command this-command))
15568 (org-read-date arg 'totime nil nil
15569 default-time default-input inactive)))
15570 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15571 ((org-at-timestamp-p t)
15572 (setq time (let ((this-command this-command))
15573 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15574 (when (org-at-timestamp-p t) ; just to get the match data
15575 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15576 (replace-match "")
15577 (setq org-last-changed-timestamp
15578 (org-insert-time-stamp
15579 time (or org-time-was-given arg)
15580 inactive nil nil (list org-end-time-was-given)))
15581 (when repeater (goto-char (1- (point))) (insert " " repeater)
15582 (setq org-last-changed-timestamp
15583 (concat (substring org-last-inserted-timestamp 0 -1)
15584 " " repeater ">"))))
15585 (message "Timestamp updated"))
15586 ((equal arg '(16))
15587 (org-insert-time-stamp (current-time) t))
15589 (setq time (let ((this-command this-command))
15590 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15591 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15592 nil nil (list org-end-time-was-given))))))
15594 ;; FIXME: can we use this for something else, like computing time differences?
15595 (defun org-get-compact-tod (s)
15596 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15597 (let* ((t1 (match-string 1 s))
15598 (h1 (string-to-number (match-string 2 s)))
15599 (m1 (string-to-number (match-string 3 s)))
15600 (t2 (and (match-end 4) (match-string 5 s)))
15601 (h2 (and t2 (string-to-number (match-string 6 s))))
15602 (m2 (and t2 (string-to-number (match-string 7 s))))
15603 dh dm)
15604 (if (not t2)
15606 (setq dh (- h2 h1) dm (- m2 m1))
15607 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15608 (concat t1 "+" (number-to-string dh)
15609 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15611 (defun org-time-stamp-inactive (&optional arg)
15612 "Insert an inactive time stamp.
15613 An inactive time stamp is enclosed in square brackets instead of angle
15614 brackets. It is inactive in the sense that it does not trigger agenda entries,
15615 does not link to the calendar and cannot be changed with the S-cursor keys.
15616 So these are more for recording a certain time/date."
15617 (interactive "P")
15618 (org-time-stamp arg 'inactive))
15620 (defvar org-date-ovl (make-overlay 1 1))
15621 (overlay-put org-date-ovl 'face 'org-date-selected)
15622 (org-detach-overlay org-date-ovl)
15624 (defvar org-ans1) ; dynamically scoped parameter
15625 (defvar org-ans2) ; dynamically scoped parameter
15627 (defvar org-plain-time-of-day-regexp) ; defined below
15629 (defvar org-overriding-default-time nil) ; dynamically scoped
15630 (defvar org-read-date-overlay nil)
15631 (defvar org-dcst nil) ; dynamically scoped
15632 (defvar org-read-date-history nil)
15633 (defvar org-read-date-final-answer nil)
15634 (defvar org-read-date-analyze-futurep nil)
15635 (defvar org-read-date-analyze-forced-year nil)
15636 (defvar org-read-date-inactive)
15638 (defvar org-read-date-minibuffer-local-map
15639 (let ((map (make-sparse-keymap)))
15640 (set-keymap-parent map minibuffer-local-map)
15641 (org-defkey map (kbd ".")
15642 (lambda () (interactive)
15643 (org-eval-in-calendar '(calendar-goto-today))))
15644 (org-defkey map [(meta shift left)]
15645 (lambda () (interactive)
15646 (org-eval-in-calendar '(calendar-backward-month 1))))
15647 (org-defkey map [(meta shift right)]
15648 (lambda () (interactive)
15649 (org-eval-in-calendar '(calendar-forward-month 1))))
15650 (org-defkey map [(meta shift up)]
15651 (lambda () (interactive)
15652 (org-eval-in-calendar '(calendar-backward-year 1))))
15653 (org-defkey map [(meta shift down)]
15654 (lambda () (interactive)
15655 (org-eval-in-calendar '(calendar-forward-year 1))))
15656 (org-defkey map [?\e (shift left)]
15657 (lambda () (interactive)
15658 (org-eval-in-calendar '(calendar-backward-month 1))))
15659 (org-defkey map [?\e (shift right)]
15660 (lambda () (interactive)
15661 (org-eval-in-calendar '(calendar-forward-month 1))))
15662 (org-defkey map [?\e (shift up)]
15663 (lambda () (interactive)
15664 (org-eval-in-calendar '(calendar-backward-year 1))))
15665 (org-defkey map [?\e (shift down)]
15666 (lambda () (interactive)
15667 (org-eval-in-calendar '(calendar-forward-year 1))))
15668 (org-defkey map [(shift up)]
15669 (lambda () (interactive)
15670 (org-eval-in-calendar '(calendar-backward-week 1))))
15671 (org-defkey map [(shift down)]
15672 (lambda () (interactive)
15673 (org-eval-in-calendar '(calendar-forward-week 1))))
15674 (org-defkey map [(shift left)]
15675 (lambda () (interactive)
15676 (org-eval-in-calendar '(calendar-backward-day 1))))
15677 (org-defkey map [(shift right)]
15678 (lambda () (interactive)
15679 (org-eval-in-calendar '(calendar-forward-day 1))))
15680 (org-defkey map "!"
15681 (lambda () (interactive)
15682 (org-eval-in-calendar '(diary-view-entries))
15683 (message "")))
15684 (org-defkey map ">"
15685 (lambda () (interactive)
15686 (org-eval-in-calendar '(scroll-calendar-left 1))))
15687 (org-defkey map "<"
15688 (lambda () (interactive)
15689 (org-eval-in-calendar '(scroll-calendar-right 1))))
15690 (org-defkey map "\C-v"
15691 (lambda () (interactive)
15692 (org-eval-in-calendar
15693 '(calendar-scroll-left-three-months 1))))
15694 (org-defkey map "\M-v"
15695 (lambda () (interactive)
15696 (org-eval-in-calendar
15697 '(calendar-scroll-right-three-months 1))))
15698 map)
15699 "Keymap for minibuffer commands when using `org-read-date'.")
15701 (defun org-read-date (&optional org-with-time to-time from-string prompt
15702 default-time default-input inactive)
15703 "Read a date, possibly a time, and make things smooth for the user.
15704 The prompt will suggest to enter an ISO date, but you can also enter anything
15705 which will at least partially be understood by `parse-time-string'.
15706 Unrecognized parts of the date will default to the current day, month, year,
15707 hour and minute. If this command is called to replace a timestamp at point,
15708 or to enter the second timestamp of a range, the default time is taken
15709 from the existing stamp. Furthermore, the command prefers the future,
15710 so if you are giving a date where the year is not given, and the day-month
15711 combination is already past in the current year, it will assume you
15712 mean next year. For details, see the manual. A few examples:
15714 3-2-5 --> 2003-02-05
15715 feb 15 --> currentyear-02-15
15716 2/15 --> currentyear-02-15
15717 sep 12 9 --> 2009-09-12
15718 12:45 --> today 12:45
15719 22 sept 0:34 --> currentyear-09-22 0:34
15720 12 --> currentyear-currentmonth-12
15721 Fri --> nearest Friday (today or later)
15722 etc.
15724 Furthermore you can specify a relative date by giving, as the *first* thing
15725 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15726 change in days weeks, months, years.
15727 With a single plus or minus, the date is relative to today. With a double
15728 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15729 +4d --> four days from today
15730 +4 --> same as above
15731 +2w --> two weeks from today
15732 ++5 --> five days from default date
15734 The function understands only English month and weekday abbreviations.
15736 While prompting, a calendar is popped up - you can also select the
15737 date with the mouse (button 1). The calendar shows a period of three
15738 months. To scroll it to other months, use the keys `>' and `<'.
15739 If you don't like the calendar, turn it off with
15740 \(setq org-read-date-popup-calendar nil)
15742 With optional argument TO-TIME, the date will immediately be converted
15743 to an internal time.
15744 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15745 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15746 still enter a time, and this function will inform the calling routine
15747 about this change. The calling routine may then choose to change the
15748 format used to insert the time stamp into the buffer to include the time.
15749 With optional argument FROM-STRING, read from this string instead from
15750 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15751 the time/date that is used for everything that is not specified by the
15752 user."
15753 (require 'parse-time)
15754 (let* ((org-time-stamp-rounding-minutes
15755 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15756 (org-dcst org-display-custom-times)
15757 (ct (org-current-time))
15758 (org-def (or org-overriding-default-time default-time ct))
15759 (org-defdecode (decode-time org-def))
15760 (dummy (progn
15761 (when (< (nth 2 org-defdecode) org-extend-today-until)
15762 (setcar (nthcdr 2 org-defdecode) -1)
15763 (setcar (nthcdr 1 org-defdecode) 59)
15764 (setq org-def (apply 'encode-time org-defdecode)
15765 org-defdecode (decode-time org-def)))))
15766 (mouse-autoselect-window nil) ; Don't let the mouse jump
15767 (calendar-frame-setup nil)
15768 (calendar-setup nil)
15769 (calendar-move-hook nil)
15770 (calendar-view-diary-initially-flag nil)
15771 (calendar-view-holidays-initially-flag nil)
15772 (timestr (format-time-string
15773 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15774 (prompt (concat (if prompt (concat prompt " ") "")
15775 (format "Date+time [%s]: " timestr)))
15776 ans (org-ans0 "") org-ans1 org-ans2 final)
15778 (cond
15779 (from-string (setq ans from-string))
15780 (org-read-date-popup-calendar
15781 (save-excursion
15782 (save-window-excursion
15783 (calendar)
15784 (org-eval-in-calendar '(setq cursor-type nil) t)
15785 (unwind-protect
15786 (progn
15787 (calendar-forward-day (- (time-to-days org-def)
15788 (calendar-absolute-from-gregorian
15789 (calendar-current-date))))
15790 (org-eval-in-calendar nil t)
15791 (let* ((old-map (current-local-map))
15792 (map (copy-keymap calendar-mode-map))
15793 (minibuffer-local-map
15794 (copy-keymap org-read-date-minibuffer-local-map)))
15795 (org-defkey map (kbd "RET") 'org-calendar-select)
15796 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15797 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15798 (unwind-protect
15799 (progn
15800 (use-local-map map)
15801 (setq org-read-date-inactive inactive)
15802 (add-hook 'post-command-hook 'org-read-date-display)
15803 (setq org-ans0 (read-string prompt default-input
15804 'org-read-date-history nil))
15805 ;; org-ans0: from prompt
15806 ;; org-ans1: from mouse click
15807 ;; org-ans2: from calendar motion
15808 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15809 (remove-hook 'post-command-hook 'org-read-date-display)
15810 (use-local-map old-map)
15811 (when org-read-date-overlay
15812 (delete-overlay org-read-date-overlay)
15813 (setq org-read-date-overlay nil)))))
15814 (bury-buffer "*Calendar*")))))
15816 (t ; Naked prompt only
15817 (unwind-protect
15818 (setq ans (read-string prompt default-input
15819 'org-read-date-history timestr))
15820 (when org-read-date-overlay
15821 (delete-overlay org-read-date-overlay)
15822 (setq org-read-date-overlay nil)))))
15824 (setq final (org-read-date-analyze ans org-def org-defdecode))
15826 (when org-read-date-analyze-forced-year
15827 (message "Year was forced into %s"
15828 (if org-read-date-force-compatible-dates
15829 "compatible range (1970-2037)"
15830 "range representable on this machine"))
15831 (ding))
15833 ;; One round trip to get rid of 34th of August and stuff like that....
15834 (setq final (decode-time (apply 'encode-time final)))
15836 (setq org-read-date-final-answer ans)
15838 (if to-time
15839 (apply 'encode-time final)
15840 (if (and (boundp 'org-time-was-given) org-time-was-given)
15841 (format "%04d-%02d-%02d %02d:%02d"
15842 (nth 5 final) (nth 4 final) (nth 3 final)
15843 (nth 2 final) (nth 1 final))
15844 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15846 (defvar org-def)
15847 (defvar org-defdecode)
15848 (defvar org-with-time)
15849 (defun org-read-date-display ()
15850 "Display the current date prompt interpretation in the minibuffer."
15851 (when org-read-date-display-live
15852 (when org-read-date-overlay
15853 (delete-overlay org-read-date-overlay))
15854 (when (minibufferp (current-buffer))
15855 (save-excursion
15856 (end-of-line 1)
15857 (while (not (equal (buffer-substring
15858 (max (point-min) (- (point) 4)) (point))
15859 " "))
15860 (insert " ")))
15861 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15862 " " (or org-ans1 org-ans2)))
15863 (org-end-time-was-given nil)
15864 (f (org-read-date-analyze ans org-def org-defdecode))
15865 (fmts (if org-dcst
15866 org-time-stamp-custom-formats
15867 org-time-stamp-formats))
15868 (fmt (if (or org-with-time
15869 (and (boundp 'org-time-was-given) org-time-was-given))
15870 (cdr fmts)
15871 (car fmts)))
15872 (txt (format-time-string fmt (apply 'encode-time f)))
15873 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15874 (txt (concat "=> " txt)))
15875 (when (and org-end-time-was-given
15876 (string-match org-plain-time-of-day-regexp txt))
15877 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15878 org-end-time-was-given
15879 (substring txt (match-end 0)))))
15880 (when org-read-date-analyze-futurep
15881 (setq txt (concat txt " (=>F)")))
15882 (setq org-read-date-overlay
15883 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15884 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15886 (defun org-read-date-analyze (ans org-def org-defdecode)
15887 "Analyze the combined answer of the date prompt."
15888 ;; FIXME: cleanup and comment
15889 (let ((nowdecode (decode-time (current-time)))
15890 delta deltan deltaw deltadef year month day
15891 hour minute second wday pm h2 m2 tl wday1
15892 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15893 (setq org-read-date-analyze-futurep nil
15894 org-read-date-analyze-forced-year nil)
15895 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15896 (setq ans "+0"))
15898 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15899 (setq ans (replace-match "" t t ans)
15900 deltan (car delta)
15901 deltaw (nth 1 delta)
15902 deltadef (nth 2 delta)))
15904 ;; Check if there is an iso week date in there. If yes, store the
15905 ;; info and postpone interpreting it until the rest of the parsing
15906 ;; is done.
15907 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15908 (setq iso-year (if (match-end 1)
15909 (org-small-year-to-year
15910 (string-to-number (match-string 1 ans))))
15911 iso-weekday (if (match-end 3)
15912 (string-to-number (match-string 3 ans)))
15913 iso-week (string-to-number (match-string 2 ans)))
15914 (setq ans (replace-match "" t t ans)))
15916 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15917 (when (string-match
15918 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15919 (setq year (if (match-end 2)
15920 (string-to-number (match-string 2 ans))
15921 (progn (setq kill-year t)
15922 (string-to-number (format-time-string "%Y"))))
15923 month (string-to-number (match-string 3 ans))
15924 day (string-to-number (match-string 4 ans)))
15925 (if (< year 100) (setq year (+ 2000 year)))
15926 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15927 t nil ans)))
15929 ;; Help matching dotted european dates
15930 (when (string-match
15931 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15932 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15933 (setq kill-year t)
15934 (string-to-number (format-time-string "%Y")))
15935 day (string-to-number (match-string 1 ans))
15936 month (string-to-number (match-string 2 ans))
15937 ans (replace-match (format "%04d-%02d-%02d" year month day)
15938 t nil ans)))
15940 ;; Help matching american dates, like 5/30 or 5/30/7
15941 (when (string-match
15942 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15943 (setq year (if (match-end 4)
15944 (string-to-number (match-string 4 ans))
15945 (progn (setq kill-year t)
15946 (string-to-number (format-time-string "%Y"))))
15947 month (string-to-number (match-string 1 ans))
15948 day (string-to-number (match-string 2 ans)))
15949 (if (< year 100) (setq year (+ 2000 year)))
15950 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15951 t nil ans)))
15952 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15953 ;; If there is a time with am/pm, and *no* time without it, we convert
15954 ;; so that matching will be successful.
15955 (loop for i from 1 to 2 do ; twice, for end time as well
15956 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15957 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15958 (setq hour (string-to-number (match-string 1 ans))
15959 minute (if (match-end 3)
15960 (string-to-number (match-string 3 ans))
15962 pm (equal ?p
15963 (string-to-char (downcase (match-string 4 ans)))))
15964 (if (and (= hour 12) (not pm))
15965 (setq hour 0)
15966 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15967 (setq ans (replace-match (format "%02d:%02d" hour minute)
15968 t t ans))))
15970 ;; Check if a time range is given as a duration
15971 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15972 (setq hour (string-to-number (match-string 1 ans))
15973 h2 (+ hour (string-to-number (match-string 3 ans)))
15974 minute (string-to-number (match-string 2 ans))
15975 m2 (+ minute (if (match-end 5) (string-to-number
15976 (match-string 5 ans))0)))
15977 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15978 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15979 t t ans)))
15981 ;; Check if there is a time range
15982 (when (boundp 'org-end-time-was-given)
15983 (setq org-time-was-given nil)
15984 (when (and (string-match org-plain-time-of-day-regexp ans)
15985 (match-end 8))
15986 (setq org-end-time-was-given (match-string 8 ans))
15987 (setq ans (concat (substring ans 0 (match-beginning 7))
15988 (substring ans (match-end 7))))))
15990 (setq tl (parse-time-string ans)
15991 day (or (nth 3 tl) (nth 3 org-defdecode))
15992 month (or (nth 4 tl)
15993 (if (and org-read-date-prefer-future
15994 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15995 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15996 (nth 4 org-defdecode)))
15997 year (or (and (not kill-year) (nth 5 tl))
15998 (if (and org-read-date-prefer-future
15999 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16000 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16001 (nth 5 org-defdecode)))
16002 hour (or (nth 2 tl) (nth 2 org-defdecode))
16003 minute (or (nth 1 tl) (nth 1 org-defdecode))
16004 second (or (nth 0 tl) 0)
16005 wday (nth 6 tl))
16007 (when (and (eq org-read-date-prefer-future 'time)
16008 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16009 (equal day (nth 3 nowdecode))
16010 (equal month (nth 4 nowdecode))
16011 (equal year (nth 5 nowdecode))
16012 (nth 2 tl)
16013 (or (< (nth 2 tl) (nth 2 nowdecode))
16014 (and (= (nth 2 tl) (nth 2 nowdecode))
16015 (nth 1 tl)
16016 (< (nth 1 tl) (nth 1 nowdecode)))))
16017 (setq day (1+ day)
16018 futurep t))
16020 ;; Special date definitions below
16021 (cond
16022 (iso-week
16023 ;; There was an iso week
16024 (require 'cal-iso)
16025 (setq futurep nil)
16026 (setq year (or iso-year year)
16027 day (or iso-weekday wday 1)
16028 wday nil ; to make sure that the trigger below does not match
16029 iso-date (calendar-gregorian-from-absolute
16030 (calendar-absolute-from-iso
16031 (list iso-week day year))))
16032 ; FIXME: Should we also push ISO weeks into the future?
16033 ; (when (and org-read-date-prefer-future
16034 ; (not iso-year)
16035 ; (< (calendar-absolute-from-gregorian iso-date)
16036 ; (time-to-days (current-time))))
16037 ; (setq year (1+ year)
16038 ; iso-date (calendar-gregorian-from-absolute
16039 ; (calendar-absolute-from-iso
16040 ; (list iso-week day year)))))
16041 (setq month (car iso-date)
16042 year (nth 2 iso-date)
16043 day (nth 1 iso-date)))
16044 (deltan
16045 (setq futurep nil)
16046 (unless deltadef
16047 (let ((now (decode-time (current-time))))
16048 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16049 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16050 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16051 ((equal deltaw "m") (setq month (+ month deltan)))
16052 ((equal deltaw "y") (setq year (+ year deltan)))))
16053 ((and wday (not (nth 3 tl)))
16054 ;; Weekday was given, but no day, so pick that day in the week
16055 ;; on or after the derived date.
16056 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16057 (unless (equal wday wday1)
16058 (setq day (+ day (% (- wday wday1 -7) 7))))))
16059 (if (and (boundp 'org-time-was-given)
16060 (nth 2 tl))
16061 (setq org-time-was-given t))
16062 (if (< year 100) (setq year (+ 2000 year)))
16063 ;; Check of the date is representable
16064 (if org-read-date-force-compatible-dates
16065 (progn
16066 (if (< year 1970)
16067 (setq year 1970 org-read-date-analyze-forced-year t))
16068 (if (> year 2037)
16069 (setq year 2037 org-read-date-analyze-forced-year t)))
16070 (condition-case nil
16071 (ignore (encode-time second minute hour day month year))
16072 (error
16073 (setq year (nth 5 org-defdecode))
16074 (setq org-read-date-analyze-forced-year t))))
16075 (setq org-read-date-analyze-futurep futurep)
16076 (list second minute hour day month year)))
16078 (defvar parse-time-weekdays)
16079 (defun org-read-date-get-relative (s today default)
16080 "Check string S for special relative date string.
16081 TODAY and DEFAULT are internal times, for today and for a default.
16082 Return shift list (N what def-flag)
16083 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16084 N is the number of WHATs to shift.
16085 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16086 the DEFAULT date rather than TODAY."
16087 (require 'parse-time)
16088 (when (and
16089 (string-match
16090 (concat
16091 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16092 "\\([0-9]+\\)?"
16093 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16094 "\\([ \t]\\|$\\)") s)
16095 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16096 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16097 (string-to-char (substring (match-string 1 s) -1))
16098 ?+))
16099 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16100 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16101 (what (if (match-end 3) (match-string 3 s) "d"))
16102 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16103 (date (if rel default today))
16104 (wday (nth 6 (decode-time date)))
16105 delta)
16106 (if wday1
16107 (progn
16108 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16109 (if (= dir ?-) (setq delta (- delta 7)))
16110 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16111 (list delta "d" rel))
16112 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16114 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16115 "Turn a user-specified date into the internal representation.
16116 The internal representation needed by the calendar is (month day year).
16117 This is a wrapper to handle the brain-dead convention in calendar that
16118 user function argument order change dependent on argument order."
16119 (if (boundp 'calendar-date-style)
16120 (cond
16121 ((eq calendar-date-style 'american)
16122 (list arg1 arg2 arg3))
16123 ((eq calendar-date-style 'european)
16124 (list arg2 arg1 arg3))
16125 ((eq calendar-date-style 'iso)
16126 (list arg2 arg3 arg1)))
16127 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16128 (if (org-bound-and-true-p european-calendar-style)
16129 (list arg2 arg1 arg3)
16130 (list arg1 arg2 arg3)))))
16132 (defun org-eval-in-calendar (form &optional keepdate)
16133 "Eval FORM in the calendar window and return to current window.
16134 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16135 otherwise stick to the current value of `org-ans2'."
16136 (let ((sf (selected-frame))
16137 (sw (selected-window)))
16138 (select-window (get-buffer-window "*Calendar*" t))
16139 (eval form)
16140 (when (and (not keepdate) (calendar-cursor-to-date))
16141 (let* ((date (calendar-cursor-to-date))
16142 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16143 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16144 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16145 (select-window sw)
16146 (org-select-frame-set-input-focus sf)))
16148 (defun org-calendar-select ()
16149 "Return to `org-read-date' with the date currently selected.
16150 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16151 (interactive)
16152 (when (calendar-cursor-to-date)
16153 (let* ((date (calendar-cursor-to-date))
16154 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16155 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16156 (if (active-minibuffer-window) (exit-minibuffer))))
16158 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16159 "Insert a date stamp for the date given by the internal TIME.
16160 WITH-HM means use the stamp format that includes the time of the day.
16161 INACTIVE means use square brackets instead of angular ones, so that the
16162 stamp will not contribute to the agenda.
16163 PRE and POST are optional strings to be inserted before and after the
16164 stamp.
16165 The command returns the inserted time stamp."
16166 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16167 stamp)
16168 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16169 (insert-before-markers (or pre ""))
16170 (when (listp extra)
16171 (setq extra (car extra))
16172 (if (and (stringp extra)
16173 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16174 (setq extra (format "-%02d:%02d"
16175 (string-to-number (match-string 1 extra))
16176 (string-to-number (match-string 2 extra))))
16177 (setq extra nil)))
16178 (when extra
16179 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16180 (insert-before-markers (setq stamp (format-time-string fmt time)))
16181 (insert-before-markers (or post ""))
16182 (setq org-last-inserted-timestamp stamp)))
16184 (defun org-toggle-time-stamp-overlays ()
16185 "Toggle the use of custom time stamp formats."
16186 (interactive)
16187 (setq org-display-custom-times (not org-display-custom-times))
16188 (unless org-display-custom-times
16189 (let ((p (point-min)) (bmp (buffer-modified-p)))
16190 (while (setq p (next-single-property-change p 'display))
16191 (if (and (get-text-property p 'display)
16192 (eq (get-text-property p 'face) 'org-date))
16193 (remove-text-properties
16194 p (setq p (next-single-property-change p 'display))
16195 '(display t))))
16196 (set-buffer-modified-p bmp)))
16197 (if (featurep 'xemacs)
16198 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16199 (org-restart-font-lock)
16200 (setq org-table-may-need-update t)
16201 (if org-display-custom-times
16202 (message "Time stamps are overlaid with custom format")
16203 (message "Time stamp overlays removed")))
16205 (defun org-display-custom-time (beg end)
16206 "Overlay modified time stamp format over timestamp between BEG and END."
16207 (let* ((ts (buffer-substring beg end))
16208 t1 w1 with-hm tf time str w2 (off 0))
16209 (save-match-data
16210 (setq t1 (org-parse-time-string ts t))
16211 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16212 (setq off (- (match-end 0) (match-beginning 0)))))
16213 (setq end (- end off))
16214 (setq w1 (- end beg)
16215 with-hm (and (nth 1 t1) (nth 2 t1))
16216 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16217 time (org-fix-decoded-time t1)
16218 str (org-add-props
16219 (format-time-string
16220 (substring tf 1 -1) (apply 'encode-time time))
16221 nil 'mouse-face 'highlight)
16222 w2 (length str))
16223 (if (not (= w2 w1))
16224 (add-text-properties (1+ beg) (+ 2 beg)
16225 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16226 (if (featurep 'xemacs)
16227 (progn
16228 (put-text-property beg end 'invisible t)
16229 (put-text-property beg end 'end-glyph (make-glyph str)))
16230 (put-text-property beg end 'display str))))
16232 (defun org-translate-time (string)
16233 "Translate all timestamps in STRING to custom format.
16234 But do this only if the variable `org-display-custom-times' is set."
16235 (when org-display-custom-times
16236 (save-match-data
16237 (let* ((start 0)
16238 (re org-ts-regexp-both)
16239 t1 with-hm inactive tf time str beg end)
16240 (while (setq start (string-match re string start))
16241 (setq beg (match-beginning 0)
16242 end (match-end 0)
16243 t1 (save-match-data
16244 (org-parse-time-string (substring string beg end) t))
16245 with-hm (and (nth 1 t1) (nth 2 t1))
16246 inactive (equal (substring string beg (1+ beg)) "[")
16247 tf (funcall (if with-hm 'cdr 'car)
16248 org-time-stamp-custom-formats)
16249 time (org-fix-decoded-time t1)
16250 str (format-time-string
16251 (concat
16252 (if inactive "[" "<") (substring tf 1 -1)
16253 (if inactive "]" ">"))
16254 (apply 'encode-time time))
16255 string (replace-match str t t string)
16256 start (+ start (length str)))))))
16257 string)
16259 (defun org-fix-decoded-time (time)
16260 "Set 0 instead of nil for the first 6 elements of time.
16261 Don't touch the rest."
16262 (let ((n 0))
16263 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16265 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16267 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16268 "Difference between TIMESTAMP-STRING and now in days.
16269 If SECONDS is non-nil, return the difference in seconds."
16270 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16271 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16272 (funcall fdiff (current-time)))))
16274 (defun org-deadline-close (timestamp-string &optional ndays)
16275 "Is the time in TIMESTAMP-STRING close to the current date?"
16276 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16277 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16278 (not (org-entry-is-done-p))))
16280 (defun org-get-wdays (ts &optional delay zero-delay)
16281 "Get the deadline lead time appropriate for timestring TS.
16282 When DELAY is non-nil, get the delay time for scheduled items
16283 instead of the deadline lead time. When ZERO-DELAY is non-nil
16284 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16285 don't try to find the delay cookie in the scheduled timestamp."
16286 (let ((tv (if delay org-scheduled-delay-days
16287 org-deadline-warning-days)))
16288 (cond
16289 ((or (and delay (< tv 0))
16290 (and delay zero-delay (<= tv 0))
16291 (and (not delay) (<= tv 0)))
16292 ;; Enforce this value no matter what
16293 (- tv))
16294 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16295 ;; lead time is specified.
16296 (floor (* (string-to-number (match-string 1 ts))
16297 (cdr (assoc (match-string 2 ts)
16298 '(("d" . 1) ("w" . 7)
16299 ("m" . 30.4) ("y" . 365.25)
16300 ("h" . 0.041667)))))))
16301 ;; go for the default.
16302 (t tv))))
16304 (defun org-calendar-select-mouse (ev)
16305 "Return to `org-read-date' with the date currently selected.
16306 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16307 (interactive "e")
16308 (mouse-set-point ev)
16309 (when (calendar-cursor-to-date)
16310 (let* ((date (calendar-cursor-to-date))
16311 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16312 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16313 (if (active-minibuffer-window) (exit-minibuffer))))
16315 (defun org-check-deadlines (ndays)
16316 "Check if there are any deadlines due or past due.
16317 A deadline is considered due if it happens within `org-deadline-warning-days'
16318 days from today's date. If the deadline appears in an entry marked DONE,
16319 it is not shown. The prefix arg NDAYS can be used to test that many
16320 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16321 (interactive "P")
16322 (let* ((org-warn-days
16323 (cond
16324 ((equal ndays '(4)) 100000)
16325 (ndays (prefix-numeric-value ndays))
16326 (t (abs org-deadline-warning-days))))
16327 (case-fold-search nil)
16328 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16329 (callback
16330 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16332 (message "%d deadlines past-due or due within %d days"
16333 (org-occur regexp nil callback)
16334 org-warn-days)))
16336 (defsubst org-re-timestamp (type)
16337 "Return a regexp for timestamp TYPE.
16338 Allowed values for TYPE are:
16340 all: all timestamps
16341 active: only active timestamps (<...>)
16342 inactive: only inactive timestamps ([...])
16343 scheduled: only scheduled timestamps
16344 deadline: only deadline timestamps
16346 When TYPE is nil, fall back on returning a regexp that matches
16347 both scheduled and deadline timestamps."
16348 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16349 ((eq type 'active) org-ts-regexp)
16350 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16351 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16352 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16353 ((eq type 'scheduled-or-deadline)
16354 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16356 (defun org-check-before-date (date)
16357 "Check if there are deadlines or scheduled entries before DATE."
16358 (interactive (list (org-read-date)))
16359 (let ((case-fold-search nil)
16360 (regexp (org-re-timestamp org-ts-type))
16361 (callback
16362 (lambda () (time-less-p
16363 (org-time-string-to-time (match-string 1))
16364 (org-time-string-to-time date)))))
16365 (message "%d entries before %s"
16366 (org-occur regexp nil callback) date)))
16368 (defun org-check-after-date (date)
16369 "Check if there are deadlines or scheduled entries after DATE."
16370 (interactive (list (org-read-date)))
16371 (let ((case-fold-search nil)
16372 (regexp (org-re-timestamp org-ts-type))
16373 (callback
16374 (lambda () (not
16375 (time-less-p
16376 (org-time-string-to-time (match-string 1))
16377 (org-time-string-to-time date))))))
16378 (message "%d entries after %s"
16379 (org-occur regexp nil callback) date)))
16381 (defun org-check-dates-range (start-date end-date)
16382 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16383 (interactive (list (org-read-date nil nil nil "Range starts")
16384 (org-read-date nil nil nil "Range end")))
16385 (let ((case-fold-search nil)
16386 (regexp (org-re-timestamp org-ts-type))
16387 (callback
16388 (lambda ()
16389 (let ((match (match-string 1)))
16390 (and
16391 (not (time-less-p
16392 (org-time-string-to-time match)
16393 (org-time-string-to-time start-date)))
16394 (time-less-p
16395 (org-time-string-to-time match)
16396 (org-time-string-to-time end-date)))))))
16397 (message "%d entries between %s and %s"
16398 (org-occur regexp nil callback) start-date end-date)))
16400 (defun org-evaluate-time-range (&optional to-buffer)
16401 "Evaluate a time range by computing the difference between start and end.
16402 Normally the result is just printed in the echo area, but with prefix arg
16403 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16404 If the time range is actually in a table, the result is inserted into the
16405 next column.
16406 For time difference computation, a year is assumed to be exactly 365
16407 days in order to avoid rounding problems."
16408 (interactive "P")
16410 (org-clock-update-time-maybe)
16411 (save-excursion
16412 (unless (org-at-date-range-p t)
16413 (goto-char (point-at-bol))
16414 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16415 (if (not (org-at-date-range-p t))
16416 (error "Not at a time-stamp range, and none found in current line")))
16417 (let* ((ts1 (match-string 1))
16418 (ts2 (match-string 2))
16419 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16420 (match-end (match-end 0))
16421 (time1 (org-time-string-to-time ts1))
16422 (time2 (org-time-string-to-time ts2))
16423 (t1 (org-float-time time1))
16424 (t2 (org-float-time time2))
16425 (diff (abs (- t2 t1)))
16426 (negative (< (- t2 t1) 0))
16427 ;; (ys (floor (* 365 24 60 60)))
16428 (ds (* 24 60 60))
16429 (hs (* 60 60))
16430 (fy "%dy %dd %02d:%02d")
16431 (fy1 "%dy %dd")
16432 (fd "%dd %02d:%02d")
16433 (fd1 "%dd")
16434 (fh "%02d:%02d")
16435 y d h m align)
16436 (if havetime
16437 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16439 d (floor (/ diff ds)) diff (mod diff ds)
16440 h (floor (/ diff hs)) diff (mod diff hs)
16441 m (floor (/ diff 60)))
16442 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16444 d (floor (+ (/ diff ds) 0.5))
16445 h 0 m 0))
16446 (if (not to-buffer)
16447 (message "%s" (org-make-tdiff-string y d h m))
16448 (if (org-at-table-p)
16449 (progn
16450 (goto-char match-end)
16451 (setq align t)
16452 (and (looking-at " *|") (goto-char (match-end 0))))
16453 (goto-char match-end))
16454 (if (looking-at
16455 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16456 (replace-match ""))
16457 (if negative (insert " -"))
16458 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16459 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16460 (insert " " (format fh h m))))
16461 (if align (org-table-align))
16462 (message "Time difference inserted")))))
16464 (defun org-make-tdiff-string (y d h m)
16465 (let ((fmt "")
16466 (l nil))
16467 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16468 l (push y l)))
16469 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16470 l (push d l)))
16471 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16472 l (push h l)))
16473 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16474 l (push m l)))
16475 (apply 'format fmt (nreverse l))))
16477 (defun org-time-string-to-time (s &optional buffer pos)
16478 "Convert a timestamp string into internal time."
16479 (condition-case errdata
16480 (apply 'encode-time (org-parse-time-string s))
16481 (error (error "Bad timestamp `%s'%s\nError was: %s"
16482 s (if (not (and buffer pos))
16484 (format " at %d in buffer `%s'" pos buffer))
16485 (cdr errdata)))))
16487 (defun org-time-string-to-seconds (s)
16488 "Convert a timestamp string to a number of seconds."
16489 (org-float-time (org-time-string-to-time s)))
16491 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16492 "Convert a time stamp to an absolute day number.
16493 If there is a specifier for a cyclic time stamp, get the closest
16494 date to DAYNR.
16495 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16496 The variable date is bound by the calendar when this is called."
16497 (cond
16498 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16499 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16500 daynr
16501 (+ daynr 1000)))
16502 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16503 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16504 (time-to-days (current-time))) (match-string 0 s)
16505 prefer show-all))
16506 (t (time-to-days
16507 (condition-case errdata
16508 (apply 'encode-time (org-parse-time-string s))
16509 (error (error "Bad timestamp `%s'%s\nError was: %s"
16510 s (if (not (and buffer pos))
16512 (format " at %d in buffer `%s'" pos buffer))
16513 (cdr errdata))))))))
16515 (defun org-days-to-iso-week (days)
16516 "Return the iso week number."
16517 (require 'cal-iso)
16518 (car (calendar-iso-from-absolute days)))
16520 (defun org-small-year-to-year (year)
16521 "Convert 2-digit years into 4-digit years.
16522 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16523 The year 2000 cannot be abbreviated. Any year larger than 99
16524 is returned unchanged."
16525 (if (< year 38)
16526 (setq year (+ 2000 year))
16527 (if (< year 100)
16528 (setq year (+ 1900 year))))
16529 year)
16531 (defun org-time-from-absolute (d)
16532 "Return the time corresponding to date D.
16533 D may be an absolute day number, or a calendar-type list (month day year)."
16534 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16535 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16537 (defun org-calendar-holiday ()
16538 "List of holidays, for Diary display in Org-mode."
16539 (require 'holidays)
16540 (let ((hl (funcall
16541 (if (fboundp 'calendar-check-holidays)
16542 'calendar-check-holidays 'check-calendar-holidays) date)))
16543 (if hl (mapconcat 'identity hl "; "))))
16545 (defun org-diary-sexp-entry (sexp entry date)
16546 "Process a SEXP diary ENTRY for DATE."
16547 (require 'diary-lib)
16548 (let ((result (if calendar-debug-sexp
16549 (let ((stack-trace-on-error t))
16550 (eval (car (read-from-string sexp))))
16551 (condition-case nil
16552 (eval (car (read-from-string sexp)))
16553 (error
16554 (beep)
16555 (message "Bad sexp at line %d in %s: %s"
16556 (org-current-line)
16557 (buffer-file-name) sexp)
16558 (sleep-for 2))))))
16559 (cond ((stringp result) (split-string result "; "))
16560 ((and (consp result)
16561 (not (consp (cdr result)))
16562 (stringp (cdr result))) (cdr result))
16563 ((and (consp result)
16564 (stringp (car result))) result)
16565 (result entry))))
16567 (defun org-diary-to-ical-string (frombuf)
16568 "Get iCalendar entries from diary entries in buffer FROMBUF.
16569 This uses the icalendar.el library."
16570 (let* ((tmpdir (if (featurep 'xemacs)
16571 (temp-directory)
16572 temporary-file-directory))
16573 (tmpfile (make-temp-name
16574 (expand-file-name "orgics" tmpdir)))
16575 buf rtn b e)
16576 (with-current-buffer frombuf
16577 (icalendar-export-region (point-min) (point-max) tmpfile)
16578 (setq buf (find-buffer-visiting tmpfile))
16579 (set-buffer buf)
16580 (goto-char (point-min))
16581 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16582 (setq b (match-beginning 0)))
16583 (goto-char (point-max))
16584 (if (re-search-backward "^END:VEVENT" nil t)
16585 (setq e (match-end 0)))
16586 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16587 (kill-buffer buf)
16588 (delete-file tmpfile)
16589 rtn))
16591 (defun org-closest-date (start current change prefer show-all)
16592 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16593 When PREFER is `past', return a date that is either CURRENT or past.
16594 When PREFER is `future', return a date that is either CURRENT or future.
16595 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16596 ;; Make the proper lists from the dates
16597 (catch 'exit
16598 (let ((a1 '(("h" . hour)
16599 ("d" . day)
16600 ("w" . week)
16601 ("m" . month)
16602 ("y" . year)))
16603 (shour (nth 2 (org-parse-time-string start)))
16604 dn dw sday cday n1 n2 n0
16605 d m y y1 y2 date1 date2 nmonths nm ny m2)
16607 (setq start (org-date-to-gregorian start)
16608 current (org-date-to-gregorian
16609 (if show-all
16610 current
16611 (time-to-days (current-time))))
16612 sday (calendar-absolute-from-gregorian start)
16613 cday (calendar-absolute-from-gregorian current))
16615 (if (<= cday sday) (throw 'exit sday))
16617 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16618 (setq dn (string-to-number (match-string 1 change))
16619 dw (cdr (assoc (match-string 2 change) a1)))
16620 (error "Invalid change specifier: %s" change))
16621 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16622 (cond
16623 ((eq dw 'hour)
16624 (let ((missing-hours
16625 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16626 dn)))
16627 (setq n1 (if (zerop missing-hours) cday
16628 (- cday (1+ (floor (/ missing-hours 24)))))
16629 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16630 ((eq dw 'day)
16631 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16632 n2 (+ n1 dn)))
16633 ((eq dw 'year)
16634 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16635 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16636 (setq date1 (list m d y1)
16637 n1 (calendar-absolute-from-gregorian date1)
16638 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16639 n2 (calendar-absolute-from-gregorian date2)))
16640 ((eq dw 'month)
16641 ;; approx number of month between the two dates
16642 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16643 ;; How often does dn fit in there?
16644 (setq d (nth 1 start) m (car start) y (nth 2 start)
16645 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16646 m (+ m nm)
16647 ny (floor (/ m 12))
16648 y (+ y ny)
16649 m (- m (* ny 12)))
16650 (while (> m 12) (setq m (- m 12) y (1+ y)))
16651 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16652 (setq m2 (+ m dn) y2 y)
16653 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16654 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16655 (while (<= n2 cday)
16656 (setq n1 n2 m m2 y y2)
16657 (setq m2 (+ m dn) y2 y)
16658 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16659 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16660 ;; Make sure n1 is the earlier date
16661 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16662 (if show-all
16663 (cond
16664 ((eq prefer 'past) (if (= cday n2) n2 n1))
16665 ((eq prefer 'future) (if (= cday n1) n1 n2))
16666 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16667 (cond
16668 ((eq prefer 'past) (if (= cday n2) n2 n1))
16669 ((eq prefer 'future) (if (= cday n1) n1 n2))
16670 (t (if (= cday n1) n1 n2)))))))
16672 (defun org-date-to-gregorian (date)
16673 "Turn any specification of DATE into a Gregorian date for the calendar."
16674 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16675 ((and (listp date) (= (length date) 3)) date)
16676 ((stringp date)
16677 (setq date (org-parse-time-string date))
16678 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16679 ((listp date)
16680 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16682 (defun org-parse-time-string (s &optional nodefault)
16683 "Parse the standard Org-mode time string.
16684 This should be a lot faster than the normal `parse-time-string'.
16685 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16686 hour and minute fields will be nil if not given."
16687 (cond ((string-match org-ts-regexp0 s)
16688 (list 0
16689 (if (or (match-beginning 8) (not nodefault))
16690 (string-to-number (or (match-string 8 s) "0")))
16691 (if (or (match-beginning 7) (not nodefault))
16692 (string-to-number (or (match-string 7 s) "0")))
16693 (string-to-number (match-string 4 s))
16694 (string-to-number (match-string 3 s))
16695 (string-to-number (match-string 2 s))
16696 nil nil nil))
16697 ((string-match "^<[^>]+>$" s)
16698 (decode-time (seconds-to-time (org-matcher-time s))))
16699 (t (error "Not a standard Org-mode time string: %s" s))))
16701 (defun org-timestamp-up (&optional arg)
16702 "Increase the date item at the cursor by one.
16703 If the cursor is on the year, change the year. If it is on the month,
16704 the day or the time, change that.
16705 With prefix ARG, change by that many units."
16706 (interactive "p")
16707 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16709 (defun org-timestamp-down (&optional arg)
16710 "Decrease the date item at the cursor by one.
16711 If the cursor is on the year, change the year. If it is on the month,
16712 the day or the time, change that.
16713 With prefix ARG, change by that many units."
16714 (interactive "p")
16715 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16717 (defun org-timestamp-up-day (&optional arg)
16718 "Increase the date in the time stamp by one day.
16719 With prefix ARG, change that many days."
16720 (interactive "p")
16721 (if (and (not (org-at-timestamp-p t))
16722 (org-at-heading-p))
16723 (org-todo 'up)
16724 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16726 (defun org-timestamp-down-day (&optional arg)
16727 "Decrease the date in the time stamp by one day.
16728 With prefix ARG, change that many days."
16729 (interactive "p")
16730 (if (and (not (org-at-timestamp-p t))
16731 (org-at-heading-p))
16732 (org-todo 'down)
16733 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16735 (defun org-at-timestamp-p (&optional inactive-ok)
16736 "Determine if the cursor is in or at a timestamp."
16737 (interactive)
16738 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16739 (pos (point))
16740 (ans (or (looking-at tsr)
16741 (save-excursion
16742 (skip-chars-backward "^[<\n\r\t")
16743 (if (> (point) (point-min)) (backward-char 1))
16744 (and (looking-at tsr)
16745 (> (- (match-end 0) pos) -1))))))
16746 (and ans
16747 (boundp 'org-ts-what)
16748 (setq org-ts-what
16749 (cond
16750 ((= pos (match-beginning 0)) 'bracket)
16751 ;; Point is considered to be "on the bracket" whether
16752 ;; it's really on it or right after it.
16753 ((= pos (1- (match-end 0))) 'bracket)
16754 ((= pos (match-end 0)) 'after)
16755 ((org-pos-in-match-range pos 2) 'year)
16756 ((org-pos-in-match-range pos 3) 'month)
16757 ((org-pos-in-match-range pos 7) 'hour)
16758 ((org-pos-in-match-range pos 8) 'minute)
16759 ((or (org-pos-in-match-range pos 4)
16760 (org-pos-in-match-range pos 5)) 'day)
16761 ((and (> pos (or (match-end 8) (match-end 5)))
16762 (< pos (match-end 0)))
16763 (- pos (or (match-end 8) (match-end 5))))
16764 (t 'day))))
16765 ans))
16767 (defun org-toggle-timestamp-type ()
16768 "Toggle the type (<active> or [inactive]) of a time stamp."
16769 (interactive)
16770 (when (org-at-timestamp-p t)
16771 (let ((beg (match-beginning 0)) (end (match-end 0))
16772 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16773 (save-excursion
16774 (goto-char beg)
16775 (while (re-search-forward "[][<>]" end t)
16776 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16777 t t)))
16778 (message "Timestamp is now %sactive"
16779 (if (equal (char-after beg) ?<) "" "in")))))
16781 (defvar org-clock-history) ; defined in org-clock.el
16782 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16783 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16784 "Change the date in the time stamp at point.
16785 The date will be changed by N times WHAT. WHAT can be `day', `month',
16786 `year', `minute', `second'. If WHAT is not given, the cursor position
16787 in the timestamp determines what will be changed.
16788 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16789 (let ((origin (point)) origin-cat
16790 with-hm inactive
16791 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16792 org-ts-what
16793 extra rem
16794 ts time time0 fixnext clrgx)
16795 (if (not (org-at-timestamp-p t))
16796 (error "Not at a timestamp"))
16797 (if (and (not what) (eq org-ts-what 'bracket))
16798 (org-toggle-timestamp-type)
16799 ;; Point isn't on brackets. Remember the part of the time-stamp
16800 ;; the point was in. Indeed, size of time-stamps may change,
16801 ;; but point must be kept in the same category nonetheless.
16802 (setq origin-cat org-ts-what)
16803 (if (and (not what) (not (eq org-ts-what 'day))
16804 org-display-custom-times
16805 (get-text-property (point) 'display)
16806 (not (get-text-property (1- (point)) 'display)))
16807 (setq org-ts-what 'day))
16808 (setq org-ts-what (or what org-ts-what)
16809 inactive (= (char-after (match-beginning 0)) ?\[)
16810 ts (match-string 0))
16811 (replace-match "")
16812 (when (string-match
16813 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16815 (setq extra (match-string 1 ts))
16816 (if suppress-tmp-delay
16817 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16818 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16819 (setq with-hm t))
16820 (setq time0 (org-parse-time-string ts))
16821 (when (and updown
16822 (eq org-ts-what 'minute)
16823 (not current-prefix-arg))
16824 ;; This looks like s-up and s-down. Change by one rounding step.
16825 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16826 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16827 (setcar (cdr time0) (+ (nth 1 time0)
16828 (if (> n 0) (- rem) (- dm rem))))))
16829 (setq time
16830 (encode-time (or (car time0) 0)
16831 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16832 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16833 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16834 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16835 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16836 (nthcdr 6 time0)))
16837 (when (and (member org-ts-what '(hour minute))
16838 extra
16839 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16840 (setq extra (org-modify-ts-extra
16841 extra
16842 (if (eq org-ts-what 'hour) 2 5)
16843 n dm)))
16844 (when (integerp org-ts-what)
16845 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16846 (if (eq what 'calendar)
16847 (let ((cal-date (org-get-date-from-calendar)))
16848 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16849 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16850 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16851 (setcar time0 (or (car time0) 0))
16852 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16853 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16854 (setq time (apply 'encode-time time0))))
16855 ;; Insert the new time-stamp, and ensure point stays in the same
16856 ;; category as before (i.e. not after the last position in that
16857 ;; category).
16858 (let ((pos (point)))
16859 ;; Stay before inserted string. `save-excursion' is of no use.
16860 (setq org-last-changed-timestamp
16861 (org-insert-time-stamp time with-hm inactive nil nil extra))
16862 (goto-char pos))
16863 (save-match-data
16864 (looking-at org-ts-regexp3)
16865 (goto-char (cond
16866 ;; `day' category ends before `hour' if any, or at
16867 ;; the end of the day name.
16868 ((eq origin-cat 'day)
16869 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16870 ((eq origin-cat 'hour) (min (match-end 7) origin))
16871 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16872 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16873 ;; `year' and `month' have both fixed size: point
16874 ;; couldn't have moved into another part.
16875 (t origin))))
16876 ;; Update clock if on a CLOCK line.
16877 (org-clock-update-time-maybe)
16878 ;; Maybe adjust the closest clock in `org-clock-history'
16879 (when org-clock-adjust-closest
16880 (if (not (and (org-at-clock-log-p)
16881 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16882 org-clock-history))))))
16883 (message "No clock to adjust")
16884 (cond ((save-excursion ; fix previous clock?
16885 (re-search-backward org-ts-regexp0 nil t)
16886 (org-looking-back (concat org-clock-string " \\[")))
16887 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16888 ((save-excursion ; fix next clock?
16889 (re-search-backward org-ts-regexp0 nil t)
16890 (looking-at (concat org-ts-regexp0 "\\] =>")))
16891 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16892 (save-window-excursion
16893 ;; Find closest clock to point, adjust the previous/next one in history
16894 (let* ((p (save-excursion (org-back-to-heading t)))
16895 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16896 (clfixnth
16897 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16898 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16899 (if (not clfixpos)
16900 (message "No clock to adjust")
16901 (save-excursion
16902 (org-goto-marker-or-bmk clfixpos)
16903 (org-show-subtree)
16904 (when (re-search-forward clrgx nil t)
16905 (goto-char (match-beginning 1))
16906 (let (org-clock-adjust-closest)
16907 (org-timestamp-change n org-ts-what updown))
16908 (message "Clock adjusted in %s for heading: %s"
16909 (file-name-nondirectory (buffer-file-name))
16910 (org-get-heading t t)))))))))
16911 ;; Try to recenter the calendar window, if any.
16912 (if (and org-calendar-follow-timestamp-change
16913 (get-buffer-window "*Calendar*" t)
16914 (memq org-ts-what '(day month year)))
16915 (org-recenter-calendar (time-to-days time))))))
16917 (defun org-modify-ts-extra (s pos n dm)
16918 "Change the different parts of the lead-time and repeat fields in timestamp."
16919 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16920 ng h m new rem)
16921 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16922 (cond
16923 ((or (org-pos-in-match-range pos 2)
16924 (org-pos-in-match-range pos 3))
16925 (setq m (string-to-number (match-string 3 s))
16926 h (string-to-number (match-string 2 s)))
16927 (if (org-pos-in-match-range pos 2)
16928 (setq h (+ h n))
16929 (setq n (* dm (org-no-warnings (signum n))))
16930 (when (not (= 0 (setq rem (% m dm))))
16931 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16932 (setq m (+ m n)))
16933 (if (< m 0) (setq m (+ m 60) h (1- h)))
16934 (if (> m 59) (setq m (- m 60) h (1+ h)))
16935 (setq h (min 24 (max 0 h)))
16936 (setq ng 1 new (format "-%02d:%02d" h m)))
16937 ((org-pos-in-match-range pos 6)
16938 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16939 ((org-pos-in-match-range pos 5)
16940 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16942 ((org-pos-in-match-range pos 9)
16943 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16944 ((org-pos-in-match-range pos 8)
16945 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16947 (when ng
16948 (setq s (concat
16949 (substring s 0 (match-beginning ng))
16951 (substring s (match-end ng))))))
16954 (defun org-recenter-calendar (date)
16955 "If the calendar is visible, recenter it to DATE."
16956 (let ((cwin (get-buffer-window "*Calendar*" t)))
16957 (when cwin
16958 (let ((calendar-move-hook nil))
16959 (with-selected-window cwin
16960 (calendar-goto-date (if (listp date) date
16961 (calendar-gregorian-from-absolute date))))))))
16963 (defun org-goto-calendar (&optional arg)
16964 "Go to the Emacs calendar at the current date.
16965 If there is a time stamp in the current line, go to that date.
16966 A prefix ARG can be used to force the current date."
16967 (interactive "P")
16968 (let ((tsr org-ts-regexp) diff
16969 (calendar-move-hook nil)
16970 (calendar-view-holidays-initially-flag nil)
16971 (calendar-view-diary-initially-flag nil))
16972 (if (or (org-at-timestamp-p)
16973 (save-excursion
16974 (beginning-of-line 1)
16975 (looking-at (concat ".*" tsr))))
16976 (let ((d1 (time-to-days (current-time)))
16977 (d2 (time-to-days
16978 (org-time-string-to-time (match-string 1)))))
16979 (setq diff (- d2 d1))))
16980 (calendar)
16981 (calendar-goto-today)
16982 (if (and diff (not arg)) (calendar-forward-day diff))))
16984 (defun org-get-date-from-calendar ()
16985 "Return a list (month day year) of date at point in calendar."
16986 (with-current-buffer "*Calendar*"
16987 (save-match-data
16988 (calendar-cursor-to-date))))
16990 (defun org-date-from-calendar ()
16991 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16992 If there is already a time stamp at the cursor position, update it."
16993 (interactive)
16994 (if (org-at-timestamp-p t)
16995 (org-timestamp-change 0 'calendar)
16996 (let ((cal-date (org-get-date-from-calendar)))
16997 (org-insert-time-stamp
16998 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17000 (defcustom org-effort-durations
17001 `(("h" . 60)
17002 ("d" . ,(* 60 8))
17003 ("w" . ,(* 60 8 5))
17004 ("m" . ,(* 60 8 5 4))
17005 ("y" . ,(* 60 8 5 40)))
17006 "Conversion factor to minutes for an effort modifier.
17008 Each entry has the form (MODIFIER . MINUTES).
17010 In an effort string, a number followed by MODIFIER is multiplied
17011 by the specified number of MINUTES to obtain an effort in
17012 minutes.
17014 For example, if the value of this variable is ((\"hours\" . 60)), then an
17015 effort string \"2hours\" is equivalent to 120 minutes."
17016 :group 'org-agenda
17017 :version "24.1"
17018 :type '(alist :key-type (string :tag "Modifier")
17019 :value-type (number :tag "Minutes")))
17021 (defun org-minutes-to-clocksum-string (m)
17022 "Format number of minutes as a clocksum string.
17023 The format is determined by `org-time-clocksum-format',
17024 `org-time-clocksum-use-fractional' and
17025 `org-time-clocksum-fractional-format' and
17026 `org-time-clocksum-use-effort-durations'."
17027 (let ((clocksum "") h d w mo y fmt n)
17028 (setq h (if org-time-clocksum-use-effort-durations
17029 (cdr (assoc "h" org-effort-durations)) 60)
17030 d (if org-time-clocksum-use-effort-durations
17031 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17032 w (if org-time-clocksum-use-effort-durations
17033 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17034 mo (if org-time-clocksum-use-effort-durations
17035 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17036 y (if org-time-clocksum-use-effort-durations
17037 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17038 ;; fractional format
17039 (if org-time-clocksum-use-fractional
17040 (cond
17041 ;; single format string
17042 ((stringp org-time-clocksum-fractional-format)
17043 (format org-time-clocksum-fractional-format (/ m (float h))))
17044 ;; choice of fractional formats for different time units
17045 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17046 (> (/ (truncate m) (* y d h)) 0))
17047 (format fmt (/ m (* y d (float h)))))
17048 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17049 (> (/ (truncate m) (* mo d h)) 0))
17050 (format fmt (/ m (* mo d (float h)))))
17051 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17052 (> (/ (truncate m) (* w d h)) 0))
17053 (format fmt (/ m (* w d (float h)))))
17054 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17055 (> (/ (truncate m) (* d h)) 0))
17056 (format fmt (/ m (* d (float h)))))
17057 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17058 (> (/ (truncate m) h) 0))
17059 (format fmt (/ m (float h))))
17060 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17061 (format fmt m))
17062 ;; fall back to smallest time unit with a format
17063 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17064 (format fmt (/ m (float h))))
17065 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17066 (format fmt (/ m (* d (float h)))))
17067 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17068 (format fmt (/ m (* w d (float h)))))
17069 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17070 (format fmt (/ m (* mo d (float h)))))
17071 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17072 (format fmt (/ m (* y d (float h))))))
17073 ;; standard (non-fractional) format, with single format string
17074 (if (stringp org-time-clocksum-format)
17075 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17076 ;; separate formats components
17077 (and (setq fmt (plist-get org-time-clocksum-format :years))
17078 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17079 (plist-get org-time-clocksum-format :require-years))
17080 (setq clocksum (concat clocksum (format fmt n))
17081 m (- m (* n y d h))))
17082 (and (setq fmt (plist-get org-time-clocksum-format :months))
17083 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17084 (plist-get org-time-clocksum-format :require-months))
17085 (setq clocksum (concat clocksum (format fmt n))
17086 m (- m (* n mo d h))))
17087 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17088 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17089 (plist-get org-time-clocksum-format :require-weeks))
17090 (setq clocksum (concat clocksum (format fmt n))
17091 m (- m (* n w d h))))
17092 (and (setq fmt (plist-get org-time-clocksum-format :days))
17093 (or (> (setq n (/ (truncate m) (* d h))) 0)
17094 (plist-get org-time-clocksum-format :require-days))
17095 (setq clocksum (concat clocksum (format fmt n))
17096 m (- m (* n d h))))
17097 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17098 (or (> (setq n (/ (truncate m) h)) 0)
17099 (plist-get org-time-clocksum-format :require-hours))
17100 (setq clocksum (concat clocksum (format fmt n))
17101 m (- m (* n h))))
17102 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17103 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17104 (setq clocksum (concat clocksum (format fmt m))))
17105 ;; return formatted time duration
17106 clocksum))))
17108 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17109 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17110 "Org mode version 8.0")
17112 (defun org-hours-to-clocksum-string (n)
17113 (org-minutes-to-clocksum-string (* n 60)))
17115 (defun org-hh:mm-string-to-minutes (s)
17116 "Convert a string H:MM to a number of minutes.
17117 If the string is just a number, interpret it as minutes.
17118 In fact, the first hh:mm or number in the string will be taken,
17119 there can be extra stuff in the string.
17120 If no number is found, the return value is 0."
17121 (cond
17122 ((integerp s) s)
17123 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17124 (+ (* (string-to-number (match-string 1 s)) 60)
17125 (string-to-number (match-string 2 s))))
17126 ((string-match "\\([0-9]+\\)" s)
17127 (string-to-number (match-string 1 s)))
17128 (t 0)))
17130 (defcustom org-image-actual-width t
17131 "Should we use the actual width of images when inlining them?
17133 When set to `t', always use the image width.
17135 When set to a number, use imagemagick (when available) to set
17136 the image's width to this value.
17138 When set to a number in a list, try to get the width from the
17139 #+ATTR.* keyword if it matches a width specification like
17140 width=\"[0-9]+\", and fall back on that number if none is found.
17142 When set to nil, try to get the width from an #+ATTR.* keyword
17143 and fall back on the original width if none is found.
17145 This requires Emacs >= 24.1, build with imagemagick support."
17146 :group 'org-appearance
17147 :version "24.3"
17148 :type '(choice
17149 (const :tag "Use the image width" t)
17150 (integer :tag "Use a number of pixels")
17151 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17152 (const :tag "Use #+ATTR* or don't resize" nil)))
17154 (defcustom org-agenda-inhibit-startup t
17155 "Inhibit startup when preparing agenda buffers.
17156 When this variable is `t' (the default), the initialization of
17157 the Org agenda buffers is inhibited: e.g. the visibility state
17158 is not set, the tables are not re-aligned, etc."
17159 :type 'boolean
17160 :version "24.3"
17161 :group 'org-agenda)
17163 (defun org-duration-string-to-minutes (s &optional output-to-string)
17164 "Convert a duration string S to minutes.
17166 A bare number is interpreted as minutes, modifiers can be set by
17167 customizing `org-effort-durations' (which see).
17169 Entries containing a colon are interpreted as H:MM by
17170 `org-hh:mm-string-to-minutes'."
17171 (let ((result 0)
17172 (re (concat "\\([0-9.]+\\) *\\("
17173 (regexp-opt (mapcar 'car org-effort-durations))
17174 "\\)")))
17175 (while (string-match re s)
17176 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17177 (string-to-number (match-string 1 s))))
17178 (setq s (replace-match "" nil t s)))
17179 (setq result (floor result))
17180 (incf result (org-hh:mm-string-to-minutes s))
17181 (if output-to-string (number-to-string result) result)))
17183 ;;;; Files
17185 (defun org-save-all-org-buffers ()
17186 "Save all Org-mode buffers without user confirmation."
17187 (interactive)
17188 (message "Saving all Org-mode buffers...")
17189 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17190 (when (featurep 'org-id) (org-id-locations-save))
17191 (message "Saving all Org-mode buffers... done"))
17193 (defun org-revert-all-org-buffers ()
17194 "Revert all Org-mode buffers.
17195 Prompt for confirmation when there are unsaved changes.
17196 Be sure you know what you are doing before letting this function
17197 overwrite your changes.
17199 This function is useful in a setup where one tracks org files
17200 with a version control system, to revert on one machine after pulling
17201 changes from another. I believe the procedure must be like this:
17203 1. M-x org-save-all-org-buffers
17204 2. Pull changes from the other machine, resolve conflicts
17205 3. M-x org-revert-all-org-buffers"
17206 (interactive)
17207 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17208 (error "Abort"))
17209 (save-excursion
17210 (save-window-excursion
17211 (mapc
17212 (lambda (b)
17213 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17214 (with-current-buffer b buffer-file-name))
17215 (org-pop-to-buffer-same-window b)
17216 (revert-buffer t 'no-confirm)))
17217 (buffer-list))
17218 (when (and (featurep 'org-id) org-id-track-globally)
17219 (org-id-locations-load)))))
17221 ;;;; Agenda files
17223 ;;;###autoload
17224 (defun org-switchb (&optional arg)
17225 "Switch between Org buffers.
17226 With one prefix argument, restrict available buffers to files.
17227 With two prefix arguments, restrict available buffers to agenda files.
17229 Defaults to `iswitchb' for buffer name completion.
17230 Set `org-completion-use-ido' to make it use ido instead."
17231 (interactive "P")
17232 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17233 ((equal arg '(16)) (org-buffer-list 'agenda))
17234 (t (org-buffer-list))))
17235 (org-completion-use-iswitchb org-completion-use-iswitchb)
17236 (org-completion-use-ido org-completion-use-ido))
17237 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17238 (setq org-completion-use-iswitchb t))
17239 (org-pop-to-buffer-same-window
17240 (org-icompleting-read "Org buffer: "
17241 (mapcar 'list (mapcar 'buffer-name blist))
17242 nil t))))
17244 ;;; Define some older names previously used for this functionality
17245 ;;;###autoload
17246 (defalias 'org-ido-switchb 'org-switchb)
17247 ;;;###autoload
17248 (defalias 'org-iswitchb 'org-switchb)
17250 (defun org-buffer-list (&optional predicate exclude-tmp)
17251 "Return a list of Org buffers.
17252 PREDICATE can be `export', `files' or `agenda'.
17254 export restrict the list to Export buffers.
17255 files restrict the list to buffers visiting Org files.
17256 agenda restrict the list to buffers visiting agenda files.
17258 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17259 (let* ((bfn nil)
17260 (agenda-files (and (eq predicate 'agenda)
17261 (mapcar 'file-truename (org-agenda-files t))))
17262 (filter
17263 (cond
17264 ((eq predicate 'files)
17265 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17266 ((eq predicate 'export)
17267 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17268 ((eq predicate 'agenda)
17269 (lambda (b)
17270 (with-current-buffer b
17271 (and (derived-mode-p 'org-mode)
17272 (setq bfn (buffer-file-name b))
17273 (member (file-truename bfn) agenda-files)))))
17274 (t (lambda (b) (with-current-buffer b
17275 (or (derived-mode-p 'org-mode)
17276 (string-match "\*Org .*Export"
17277 (buffer-name b)))))))))
17278 (delq nil
17279 (mapcar
17280 (lambda(b)
17281 (if (and (funcall filter b)
17282 (or (not exclude-tmp)
17283 (not (string-match "tmp" (buffer-name b)))))
17285 nil))
17286 (buffer-list)))))
17288 (defun org-agenda-files (&optional unrestricted archives)
17289 "Get the list of agenda files.
17290 Optional UNRESTRICTED means return the full list even if a restriction
17291 is currently in place.
17292 When ARCHIVES is t, include all archive files that are really being
17293 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17294 `org-agenda-archives-mode' is t."
17295 (let ((files
17296 (cond
17297 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17298 ((stringp org-agenda-files) (org-read-agenda-file-list))
17299 ((listp org-agenda-files) org-agenda-files)
17300 (t (error "Invalid value of `org-agenda-files'")))))
17301 (setq files (apply 'append
17302 (mapcar (lambda (f)
17303 (if (file-directory-p f)
17304 (directory-files
17305 f t org-agenda-file-regexp)
17306 (list f)))
17307 files)))
17308 (when org-agenda-skip-unavailable-files
17309 (setq files (delq nil
17310 (mapcar (function
17311 (lambda (file)
17312 (and (file-readable-p file) file)))
17313 files))))
17314 (when (or (eq archives t)
17315 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17316 (setq files (org-add-archive-files files)))
17317 files))
17319 (defun org-agenda-file-p (&optional file)
17320 "Return non-nil, if FILE is an agenda file.
17321 If FILE is omitted, use the file associated with the current
17322 buffer."
17323 (member (or file (buffer-file-name))
17324 (org-agenda-files t)))
17326 (defun org-edit-agenda-file-list ()
17327 "Edit the list of agenda files.
17328 Depending on setup, this either uses customize to edit the variable
17329 `org-agenda-files', or it visits the file that is holding the list. In the
17330 latter case, the buffer is set up in a way that saving it automatically kills
17331 the buffer and restores the previous window configuration."
17332 (interactive)
17333 (if (stringp org-agenda-files)
17334 (let ((cw (current-window-configuration)))
17335 (find-file org-agenda-files)
17336 (org-set-local 'org-window-configuration cw)
17337 (org-add-hook 'after-save-hook
17338 (lambda ()
17339 (set-window-configuration
17340 (prog1 org-window-configuration
17341 (kill-buffer (current-buffer))))
17342 (org-install-agenda-files-menu)
17343 (message "New agenda file list installed"))
17344 nil 'local)
17345 (message "%s" (substitute-command-keys
17346 "Edit list and finish with \\[save-buffer]")))
17347 (customize-variable 'org-agenda-files)))
17349 (defun org-store-new-agenda-file-list (list)
17350 "Set new value for the agenda file list and save it correctly."
17351 (if (stringp org-agenda-files)
17352 (let ((fe (org-read-agenda-file-list t)) b u)
17353 (while (setq b (find-buffer-visiting org-agenda-files))
17354 (kill-buffer b))
17355 (with-temp-file org-agenda-files
17356 (insert
17357 (mapconcat
17358 (lambda (f) ;; Keep un-expanded entries.
17359 (if (setq u (assoc f fe))
17360 (cdr u)
17362 list "\n")
17363 "\n")))
17364 (let ((org-mode-hook nil) (org-inhibit-startup t)
17365 (org-insert-mode-line-in-empty-file nil))
17366 (setq org-agenda-files list)
17367 (customize-save-variable 'org-agenda-files org-agenda-files))))
17369 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17370 "Read the list of agenda files from a file.
17371 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17372 filenames, used by `org-store-new-agenda-file-list' to write back
17373 un-expanded file names."
17374 (when (file-directory-p org-agenda-files)
17375 (error "`org-agenda-files' cannot be a single directory"))
17376 (when (stringp org-agenda-files)
17377 (with-temp-buffer
17378 (insert-file-contents org-agenda-files)
17379 (mapcar
17380 (lambda (f)
17381 (let ((e (expand-file-name (substitute-in-file-name f)
17382 org-directory)))
17383 (if pair-with-expansion
17384 (cons e f)
17385 e)))
17386 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17388 ;;;###autoload
17389 (defun org-cycle-agenda-files ()
17390 "Cycle through the files in `org-agenda-files'.
17391 If the current buffer visits an agenda file, find the next one in the list.
17392 If the current buffer does not, find the first agenda file."
17393 (interactive)
17394 (let* ((fs (org-agenda-files t))
17395 (files (append fs (list (car fs))))
17396 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17397 file)
17398 (unless files (error "No agenda files"))
17399 (catch 'exit
17400 (while (setq file (pop files))
17401 (if (equal (file-truename file) tcf)
17402 (when (car files)
17403 (find-file (car files))
17404 (throw 'exit t))))
17405 (find-file (car fs)))
17406 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17408 (defun org-agenda-file-to-front (&optional to-end)
17409 "Move/add the current file to the top of the agenda file list.
17410 If the file is not present in the list, it is added to the front. If it is
17411 present, it is moved there. With optional argument TO-END, add/move to the
17412 end of the list."
17413 (interactive "P")
17414 (let ((org-agenda-skip-unavailable-files nil)
17415 (file-alist (mapcar (lambda (x)
17416 (cons (file-truename x) x))
17417 (org-agenda-files t)))
17418 (ctf (file-truename
17419 (or buffer-file-name
17420 (error "Please save the current buffer to a file"))))
17421 x had)
17422 (setq x (assoc ctf file-alist) had x)
17424 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17425 (if to-end
17426 (setq file-alist (append (delq x file-alist) (list x)))
17427 (setq file-alist (cons x (delq x file-alist))))
17428 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17429 (org-install-agenda-files-menu)
17430 (message "File %s to %s of agenda file list"
17431 (if had "moved" "added") (if to-end "end" "front"))))
17433 (defun org-remove-file (&optional file)
17434 "Remove current file from the list of files in variable `org-agenda-files'.
17435 These are the files which are being checked for agenda entries.
17436 Optional argument FILE means use this file instead of the current."
17437 (interactive)
17438 (let* ((org-agenda-skip-unavailable-files nil)
17439 (file (or file buffer-file-name
17440 (error "Current buffer does not visit a file")))
17441 (true-file (file-truename file))
17442 (afile (abbreviate-file-name file))
17443 (files (delq nil (mapcar
17444 (lambda (x)
17445 (if (equal true-file
17446 (file-truename x))
17447 nil x))
17448 (org-agenda-files t)))))
17449 (if (not (= (length files) (length (org-agenda-files t))))
17450 (progn
17451 (org-store-new-agenda-file-list files)
17452 (org-install-agenda-files-menu)
17453 (message "Removed file: %s" afile))
17454 (message "File was not in list: %s (not removed)" afile))))
17456 (defun org-file-menu-entry (file)
17457 (vector file (list 'find-file file) t))
17459 (defun org-check-agenda-file (file)
17460 "Make sure FILE exists. If not, ask user what to do."
17461 (when (not (file-exists-p file))
17462 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17463 (abbreviate-file-name file))
17464 (let ((r (downcase (read-char-exclusive))))
17465 (cond
17466 ((equal r ?r)
17467 (org-remove-file file)
17468 (throw 'nextfile t))
17469 (t (error "Abort"))))))
17471 (defun org-get-agenda-file-buffer (file)
17472 "Get a buffer visiting FILE. If the buffer needs to be created, add
17473 it to the list of buffers which might be released later."
17474 (let ((buf (org-find-base-buffer-visiting file)))
17475 (if buf
17476 buf ; just return it
17477 ;; Make a new buffer and remember it
17478 (setq buf (find-file-noselect file))
17479 (if buf (push buf org-agenda-new-buffers))
17480 buf)))
17482 (defun org-release-buffers (blist)
17483 "Release all buffers in list, asking the user for confirmation when needed.
17484 When a buffer is unmodified, it is just killed. When modified, it is saved
17485 \(if the user agrees) and then killed."
17486 (let (buf file)
17487 (while (setq buf (pop blist))
17488 (setq file (buffer-file-name buf))
17489 (when (and (buffer-modified-p buf)
17490 file
17491 (y-or-n-p (format "Save file %s? " file)))
17492 (with-current-buffer buf (save-buffer)))
17493 (kill-buffer buf))))
17495 (defun org-agenda-prepare-buffers (files)
17496 "Create buffers for all agenda files, protect archived trees and comments."
17497 (interactive)
17498 (let ((pa '(:org-archived t))
17499 (pc '(:org-comment t))
17500 (pall '(:org-archived t :org-comment t))
17501 (inhibit-read-only t)
17502 (org-inhibit-startup org-agenda-inhibit-startup)
17503 (rea (concat ":" org-archive-tag ":"))
17504 file re)
17505 (save-excursion
17506 (save-restriction
17507 (while (setq file (pop files))
17508 (catch 'nextfile
17509 (if (bufferp file)
17510 (set-buffer file)
17511 (org-check-agenda-file file)
17512 (set-buffer (org-get-agenda-file-buffer file)))
17513 (widen)
17514 (org-unmodified
17515 (org-refresh-category-properties)
17516 (org-refresh-properties org-effort-property 'org-effort)
17517 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17518 (setq org-todo-keywords-for-agenda
17519 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17520 (setq org-done-keywords-for-agenda
17521 (append org-done-keywords-for-agenda org-done-keywords))
17522 (setq org-todo-keyword-alist-for-agenda
17523 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17524 (setq org-drawers-for-agenda
17525 (append org-drawers-for-agenda org-drawers))
17526 (setq org-tag-alist-for-agenda
17527 (append org-tag-alist-for-agenda org-tag-alist))
17529 (save-excursion
17530 (remove-text-properties (point-min) (point-max) pall)
17531 (when org-agenda-skip-archived-trees
17532 (goto-char (point-min))
17533 (while (re-search-forward rea nil t)
17534 (if (org-at-heading-p t)
17535 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17536 (goto-char (point-min))
17537 (setq re (format org-heading-keyword-regexp-format
17538 org-comment-string))
17539 (while (re-search-forward re nil t)
17540 (add-text-properties
17541 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17542 (setq org-todo-keywords-for-agenda
17543 (org-uniquify org-todo-keywords-for-agenda))
17544 (setq org-todo-keyword-alist-for-agenda
17545 (org-uniquify org-todo-keyword-alist-for-agenda)
17546 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17550 ;;;; CDLaTeX minor mode
17552 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17553 "Keymap for the minor `org-cdlatex-mode'.")
17555 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17556 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17557 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17558 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17559 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17561 (defvar org-cdlatex-texmathp-advice-is-done nil
17562 "Flag remembering if we have applied the advice to texmathp already.")
17564 (define-minor-mode org-cdlatex-mode
17565 "Toggle the minor `org-cdlatex-mode'.
17566 This mode supports entering LaTeX environment and math in LaTeX fragments
17567 in Org-mode.
17568 \\{org-cdlatex-mode-map}"
17569 nil " OCDL" nil
17570 (when org-cdlatex-mode
17571 (require 'cdlatex)
17572 (run-hooks 'cdlatex-mode-hook)
17573 (cdlatex-compute-tables))
17574 (unless org-cdlatex-texmathp-advice-is-done
17575 (setq org-cdlatex-texmathp-advice-is-done t)
17576 (defadvice texmathp (around org-math-always-on activate)
17577 "Always return t in org-mode buffers.
17578 This is because we want to insert math symbols without dollars even outside
17579 the LaTeX math segments. If Orgmode thinks that point is actually inside
17580 an embedded LaTeX fragment, let texmathp do its job.
17581 \\[org-cdlatex-mode-map]"
17582 (interactive)
17583 (let (p)
17584 (cond
17585 ((not (derived-mode-p 'org-mode)) ad-do-it)
17586 ((eq this-command 'cdlatex-math-symbol)
17587 (setq ad-return-value t
17588 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17590 (let ((p (org-inside-LaTeX-fragment-p)))
17591 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17592 (setq ad-return-value t
17593 texmathp-why '("Org-mode embedded math" . 0))
17594 (if p ad-do-it)))))))))
17596 (defun turn-on-org-cdlatex ()
17597 "Unconditionally turn on `org-cdlatex-mode'."
17598 (org-cdlatex-mode 1))
17600 (defun org-try-cdlatex-tab ()
17601 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17602 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17603 - inside a LaTeX fragment, or
17604 - after the first word in a line, where an abbreviation expansion could
17605 insert a LaTeX environment."
17606 (when org-cdlatex-mode
17607 (cond
17608 ;; Before any word on the line: No expansion possible.
17609 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17610 ;; Just after first word on the line: Expand it. Make sure it
17611 ;; cannot happen on headlines, though.
17612 ((save-excursion
17613 (skip-chars-backward "a-zA-Z0-9*")
17614 (skip-chars-backward " \t")
17615 (and (bolp) (not (org-at-heading-p))))
17616 (cdlatex-tab) t)
17617 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17619 (defun org-cdlatex-underscore-caret (&optional arg)
17620 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17621 Revert to the normal definition outside of these fragments."
17622 (interactive "P")
17623 (if (org-inside-LaTeX-fragment-p)
17624 (call-interactively 'cdlatex-sub-superscript)
17625 (let (org-cdlatex-mode)
17626 (call-interactively (key-binding (vector last-input-event))))))
17628 (defun org-cdlatex-math-modify (&optional arg)
17629 "Execute `cdlatex-math-modify' in LaTeX fragments.
17630 Revert to the normal definition outside of these fragments."
17631 (interactive "P")
17632 (if (org-inside-LaTeX-fragment-p)
17633 (call-interactively 'cdlatex-math-modify)
17634 (let (org-cdlatex-mode)
17635 (call-interactively (key-binding (vector last-input-event))))))
17639 ;;;; LaTeX fragments
17641 (defvar org-latex-regexps
17642 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17643 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17644 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17645 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17646 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17647 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17648 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17649 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17650 "Regular expressions for matching embedded LaTeX.")
17652 (defun org-inside-LaTeX-fragment-p ()
17653 "Test if point is inside a LaTeX fragment.
17654 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17655 sequence appearing also before point.
17656 Even though the matchers for math are configurable, this function assumes
17657 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17658 delimiters are skipped when they have been removed by customization.
17659 The return value is nil, or a cons cell with the delimiter and the
17660 position of this delimiter.
17662 This function does a reasonably good job, but can locally be fooled by
17663 for example currency specifications. For example it will assume being in
17664 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17665 fragments that are properly closed, but during editing, we have to live
17666 with the uncertainty caused by missing closing delimiters. This function
17667 looks only before point, not after."
17668 (catch 'exit
17669 (let ((pos (point))
17670 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17671 (lim (progn
17672 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17673 (point)))
17674 dd-on str (start 0) m re)
17675 (goto-char pos)
17676 (when dodollar
17677 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17678 re (nth 1 (assoc "$" org-latex-regexps)))
17679 (while (string-match re str start)
17680 (cond
17681 ((= (match-end 0) (length str))
17682 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17683 ((= (match-end 0) (- (length str) 5))
17684 (throw 'exit nil))
17685 (t (setq start (match-end 0))))))
17686 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17687 (goto-char pos)
17688 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17689 (and (match-beginning 2) (throw 'exit nil))
17690 ;; count $$
17691 (while (re-search-backward "\\$\\$" lim t)
17692 (setq dd-on (not dd-on)))
17693 (goto-char pos)
17694 (if dd-on (cons "$$" m))))))
17696 (defun org-inside-latex-macro-p ()
17697 "Is point inside a LaTeX macro or its arguments?"
17698 (save-match-data
17699 (org-in-regexp
17700 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17702 (defvar org-latex-fragment-image-overlays nil
17703 "List of overlays carrying the images of latex fragments.")
17704 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17706 (defun org-remove-latex-fragment-image-overlays ()
17707 "Remove all overlays with LaTeX fragment images in current buffer."
17708 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17709 (setq org-latex-fragment-image-overlays nil))
17711 (defun org-preview-latex-fragment (&optional subtree)
17712 "Preview the LaTeX fragment at point, or all locally or globally.
17713 If the cursor is in a LaTeX fragment, create the image and overlay
17714 it over the source code. If there is no fragment at point, display
17715 all fragments in the current text, from one headline to the next. With
17716 prefix SUBTREE, display all fragments in the current subtree. With a
17717 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17718 the cursor is before the first headline,
17719 display all fragments in the buffer.
17720 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17721 (interactive "P")
17722 (unless buffer-file-name
17723 (error "Can't preview LaTeX fragment in a non-file buffer"))
17724 (org-remove-latex-fragment-image-overlays)
17725 (save-excursion
17726 (save-restriction
17727 (let (beg end at msg)
17728 (cond
17729 ((or (equal subtree '(16))
17730 (not (save-excursion
17731 (re-search-backward org-outline-regexp-bol nil t))))
17732 (setq beg (point-min) end (point-max)
17733 msg "Creating images for buffer...%s"))
17734 ((equal subtree '(4))
17735 (org-back-to-heading)
17736 (setq beg (point) end (org-end-of-subtree t)
17737 msg "Creating images for subtree...%s"))
17739 (if (setq at (org-inside-LaTeX-fragment-p))
17740 (goto-char (max (point-min) (- (cdr at) 2)))
17741 (org-back-to-heading))
17742 (setq beg (point) end (progn (outline-next-heading) (point))
17743 msg (if at "Creating image...%s"
17744 "Creating images for entry...%s"))))
17745 (message msg "")
17746 (narrow-to-region beg end)
17747 (goto-char beg)
17748 (org-format-latex
17749 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17750 (file-name-nondirectory
17751 buffer-file-name)))
17752 default-directory 'overlays msg at 'forbuffer
17753 org-latex-create-formula-image-program)
17754 (message msg "done. Use `C-c C-c' to remove images.")))))
17756 (defun org-format-latex (prefix &optional dir overlays msg at
17757 forbuffer processing-type)
17758 "Replace LaTeX fragments with links to an image, and produce images.
17759 Some of the options can be changed using the variable
17760 `org-format-latex-options'."
17761 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17762 (let* ((prefixnodir (file-name-nondirectory prefix))
17763 (absprefix (expand-file-name prefix dir))
17764 (todir (file-name-directory absprefix))
17765 (opt org-format-latex-options)
17766 (optnew org-format-latex-options)
17767 (matchers (plist-get opt :matchers))
17768 (re-list org-latex-regexps)
17769 (cnt 0) txt hash link beg end re e checkdir
17770 string
17771 m n block-type block linkfile movefile ov)
17772 ;; Check the different regular expressions
17773 (while (setq e (pop re-list))
17774 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17775 block (if block-type "\n\n" ""))
17776 (when (member m matchers)
17777 (goto-char (point-min))
17778 (while (re-search-forward re nil t)
17779 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17780 (or (not overlays)
17781 (not (eq (get-char-property (match-beginning n)
17782 'org-overlay-type)
17783 'org-latex-overlay))))
17784 (cond
17785 ((eq processing-type 'verbatim))
17786 ((eq processing-type 'mathjax)
17787 ;; Prepare for MathJax processing.
17788 (setq string (match-string n))
17789 (when (member m '("$" "$1"))
17790 (save-excursion
17791 (delete-region (match-beginning n) (match-end n))
17792 (goto-char (match-beginning n))
17793 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17794 ((or (eq processing-type 'dvipng)
17795 (eq processing-type 'imagemagick))
17796 ;; Process to an image.
17797 (setq txt (match-string n)
17798 beg (match-beginning n) end (match-end n)
17799 cnt (1+ cnt))
17800 (let ((face (face-at-point))
17801 (fg (plist-get opt :foreground))
17802 (bg (plist-get opt :background))
17803 ;; Ensure full list is printed.
17804 print-length print-level)
17805 (when forbuffer
17806 ;; Get the colors from the face at point.
17807 (goto-char beg)
17808 (when (eq fg 'auto)
17809 (setq fg (face-attribute face :foreground nil 'default)))
17810 (when (eq bg 'auto)
17811 (setq bg (face-attribute face :background nil 'default)))
17812 (setq optnew (copy-sequence opt))
17813 (plist-put optnew :foreground fg)
17814 (plist-put optnew :background bg))
17815 (setq hash (sha1 (prin1-to-string
17816 (list org-format-latex-header
17817 org-latex-default-packages-alist
17818 org-latex-packages-alist
17819 org-format-latex-options
17820 forbuffer txt fg bg)))
17821 linkfile (format "%s_%s.png" prefix hash)
17822 movefile (format "%s_%s.png" absprefix hash)))
17823 (setq link (concat block "[[file:" linkfile "]]" block))
17824 (if msg (message msg cnt))
17825 (goto-char beg)
17826 (unless checkdir ; Ensure the directory exists.
17827 (setq checkdir t)
17828 (or (file-directory-p todir) (make-directory todir t)))
17829 (unless (file-exists-p movefile)
17830 (org-create-formula-image
17831 txt movefile optnew forbuffer processing-type))
17832 (if overlays
17833 (progn
17834 (mapc (lambda (o)
17835 (if (eq (overlay-get o 'org-overlay-type)
17836 'org-latex-overlay)
17837 (delete-overlay o)))
17838 (overlays-in beg end))
17839 (setq ov (make-overlay beg end))
17840 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17841 (if (featurep 'xemacs)
17842 (progn
17843 (overlay-put ov 'invisible t)
17844 (overlay-put
17845 ov 'end-glyph
17846 (make-glyph (vector 'png :file movefile))))
17847 (overlay-put
17848 ov 'display
17849 (list 'image :type 'png :file movefile :ascent 'center)))
17850 (push ov org-latex-fragment-image-overlays)
17851 (goto-char end))
17852 (delete-region beg end)
17853 (insert (org-add-props link
17854 (list 'org-latex-src
17855 (replace-regexp-in-string
17856 "\"" "" txt)
17857 'org-latex-src-embed-type
17858 (if block-type 'paragraph 'character))))))
17859 ((eq processing-type 'mathml)
17860 ;; Process to MathML
17861 (unless (save-match-data (org-format-latex-mathml-available-p))
17862 (error "LaTeX to MathML converter not configured"))
17863 (setq txt (match-string n)
17864 beg (match-beginning n) end (match-end n)
17865 cnt (1+ cnt))
17866 (if msg (message msg cnt))
17867 (goto-char beg)
17868 (delete-region beg end)
17869 (insert (org-format-latex-as-mathml
17870 txt block-type prefix dir)))
17872 (error "Unknown conversion type %s for latex fragments"
17873 processing-type)))))))))
17875 (defun org-create-math-formula (latex-frag &optional mathml-file)
17876 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17877 Use `org-latex-to-mathml-convert-command'. If the conversion is
17878 sucessful, return the portion between \"<math...> </math>\"
17879 elements otherwise return nil. When MATHML-FILE is specified,
17880 write the results in to that file. When invoked as an
17881 interactive command, prompt for LATEX-FRAG, with initial value
17882 set to the current active region and echo the results for user
17883 inspection."
17884 (interactive (list (let ((frag (when (org-region-active-p)
17885 (buffer-substring-no-properties
17886 (region-beginning) (region-end)))))
17887 (read-string "LaTeX Fragment: " frag nil frag))))
17888 (unless latex-frag (error "Invalid latex-frag"))
17889 (let* ((tmp-in-file (file-relative-name
17890 (make-temp-name (expand-file-name "ltxmathml-in"))))
17891 (ignore (write-region latex-frag nil tmp-in-file))
17892 (tmp-out-file (file-relative-name
17893 (make-temp-name (expand-file-name "ltxmathml-out"))))
17894 (cmd (format-spec
17895 org-latex-to-mathml-convert-command
17896 `((?j . ,(shell-quote-argument
17897 (expand-file-name org-latex-to-mathml-jar-file)))
17898 (?I . ,(shell-quote-argument tmp-in-file))
17899 (?o . ,(shell-quote-argument tmp-out-file)))))
17900 mathml shell-command-output)
17901 (when (org-called-interactively-p 'any)
17902 (unless (org-format-latex-mathml-available-p)
17903 (error "LaTeX to MathML converter not configured")))
17904 (message "Running %s" cmd)
17905 (setq shell-command-output (shell-command-to-string cmd))
17906 (setq mathml
17907 (when (file-readable-p tmp-out-file)
17908 (with-current-buffer (find-file-noselect tmp-out-file t)
17909 (goto-char (point-min))
17910 (when (re-search-forward
17911 (concat
17912 (regexp-quote
17913 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17914 "\\(.\\|\n\\)*"
17915 (regexp-quote "</math>")) nil t)
17916 (prog1 (match-string 0) (kill-buffer))))))
17917 (cond
17918 (mathml
17919 (setq mathml
17920 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17921 (when mathml-file
17922 (write-region mathml nil mathml-file))
17923 (when (org-called-interactively-p 'any)
17924 (message mathml)))
17925 ((message "LaTeX to MathML conversion failed")
17926 (message shell-command-output)))
17927 (delete-file tmp-in-file)
17928 (when (file-exists-p tmp-out-file)
17929 (delete-file tmp-out-file))
17930 mathml))
17932 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17933 prefix &optional dir)
17934 "Use `org-create-math-formula' but check local cache first."
17935 (let* ((absprefix (expand-file-name prefix dir))
17936 (print-length nil) (print-level nil)
17937 (formula-id (concat
17938 "formula-"
17939 (sha1
17940 (prin1-to-string
17941 (list latex-frag
17942 org-latex-to-mathml-convert-command)))))
17943 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17944 (formula-cache-dir (file-name-directory formula-cache)))
17946 (unless (file-directory-p formula-cache-dir)
17947 (make-directory formula-cache-dir t))
17949 (unless (file-exists-p formula-cache)
17950 (org-create-math-formula latex-frag formula-cache))
17952 (if (file-exists-p formula-cache)
17953 ;; Successful conversion. Return the link to MathML file.
17954 (org-add-props
17955 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17956 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17957 'org-latex-src-embed-type (if latex-frag-type
17958 'paragraph 'character)))
17959 ;; Failed conversion. Return the LaTeX fragment verbatim
17960 latex-frag)))
17962 (defun org-create-formula-image (string tofile options buffer &optional type)
17963 "Create an image from LaTeX source using dvipng or convert.
17964 This function calls either `org-create-formula-image-with-dvipng'
17965 or `org-create-formula-image-with-imagemagick' depending on the
17966 value of `org-latex-create-formula-image-program' or on the value
17967 of the optional TYPE variable.
17969 Note: ultimately these two function should be combined as they
17970 share a good deal of logic."
17971 (org-check-external-command
17972 "latex" "needed to convert LaTeX fragments to images")
17973 (funcall
17974 (case (or type org-latex-create-formula-image-program)
17975 ('dvipng
17976 (org-check-external-command
17977 "dvipng" "needed to convert LaTeX fragments to images")
17978 #'org-create-formula-image-with-dvipng)
17979 ('imagemagick
17980 (org-check-external-command
17981 "convert" "you need to install imagemagick")
17982 #'org-create-formula-image-with-imagemagick)
17983 (t (error
17984 "invalid value of `org-latex-create-formula-image-program'")))
17985 string tofile options buffer))
17987 ;; This function borrows from Ganesh Swami's latex2png.el
17988 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17989 "This calls dvipng."
17990 (let* ((tmpdir (if (featurep 'xemacs)
17991 (temp-directory)
17992 temporary-file-directory))
17993 (texfilebase (make-temp-name
17994 (expand-file-name "orgtex" tmpdir)))
17995 (texfile (concat texfilebase ".tex"))
17996 (dvifile (concat texfilebase ".dvi"))
17997 (pngfile (concat texfilebase ".png"))
17998 (fnh (if (featurep 'xemacs)
17999 (font-height (face-font 'default))
18000 (face-attribute 'default :height nil)))
18001 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18002 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18003 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18004 "Black"))
18005 (bg (or (plist-get options (if buffer :background :html-background))
18006 "Transparent")))
18007 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18008 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18009 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18010 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18011 (with-temp-file texfile
18012 (require 'ox-latex)
18013 (insert (org-latex-guess-inputenc
18014 (org-splice-latex-header
18015 org-format-latex-header
18016 org-latex-default-packages-alist
18017 org-latex-packages-alist t)))
18018 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18019 (let ((dir default-directory))
18020 (condition-case nil
18021 (progn
18022 (cd tmpdir)
18023 (call-process "latex" nil nil nil texfile))
18024 (error nil))
18025 (cd dir))
18026 (if (not (file-exists-p dvifile))
18027 (progn (message "Failed to create dvi file from %s" texfile) nil)
18028 (condition-case nil
18029 (if (featurep 'xemacs)
18030 (call-process "dvipng" nil nil nil
18031 "-fg" fg "-bg" bg
18032 "-T" "tight"
18033 "-o" pngfile
18034 dvifile)
18035 (call-process "dvipng" nil nil nil
18036 "-fg" fg "-bg" bg
18037 "-D" dpi
18038 ;;"-x" scale "-y" scale
18039 "-T" "tight"
18040 "-o" pngfile
18041 dvifile))
18042 (error nil))
18043 (if (not (file-exists-p pngfile))
18044 (if org-format-latex-signal-error
18045 (error "Failed to create png file from %s" texfile)
18046 (message "Failed to create png file from %s" texfile)
18047 nil)
18048 ;; Use the requested file name and clean up
18049 (copy-file pngfile tofile 'replace)
18050 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18051 (if (file-exists-p (concat texfilebase e))
18052 (delete-file (concat texfilebase e))))
18053 pngfile))))
18055 (defvar org-latex-pdf-process) ; From ox-latex.el
18056 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18057 "This calls convert, which is included into imagemagick."
18058 (let* ((tmpdir (if (featurep 'xemacs)
18059 (temp-directory)
18060 temporary-file-directory))
18061 (texfilebase (make-temp-name
18062 (expand-file-name "orgtex" tmpdir)))
18063 (texfile (concat texfilebase ".tex"))
18064 (pdffile (concat texfilebase ".pdf"))
18065 (pngfile (concat texfilebase ".png"))
18066 (fnh (if (featurep 'xemacs)
18067 (font-height (face-font 'default))
18068 (face-attribute 'default :height nil)))
18069 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18070 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18071 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18072 "black"))
18073 (bg (or (plist-get options (if buffer :background :html-background))
18074 "white")))
18075 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18076 (setq fg (org-latex-color-format fg)))
18077 (if (eq bg 'default) (setq bg (org-latex-color :background))
18078 (setq bg (org-latex-color-format
18079 (if (string= bg "Transparent") "white" bg))))
18080 (with-temp-file texfile
18081 (require 'ox-latex)
18082 (insert (org-latex-guess-inputenc
18083 (org-splice-latex-header
18084 org-format-latex-header
18085 org-latex-default-packages-alist
18086 org-latex-packages-alist t)))
18087 (insert "\n\\begin{document}\n"
18088 "\\definecolor{fg}{rgb}{" fg "}\n"
18089 "\\definecolor{bg}{rgb}{" bg "}\n"
18090 "\n\\pagecolor{bg}\n"
18091 "\n{\\color{fg}\n"
18092 string
18093 "\n}\n"
18094 "\n\\end{document}\n"))
18095 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18096 (condition-case nil
18097 (progn
18098 (cd tmpdir)
18099 (setq cmds org-latex-pdf-process)
18100 (while cmds
18101 (setq latex-frags-cmds (pop cmds))
18102 (if (listp latex-frags-cmds)
18103 (setq cmds nil)
18104 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18105 (while latex-frags-cmds
18106 (setq cmd (pop latex-frags-cmds))
18107 (while (string-match "%b" cmd)
18108 (setq cmd (replace-match
18109 (save-match-data
18110 (shell-quote-argument texfile))
18111 t t cmd)))
18112 (while (string-match "%f" cmd)
18113 (setq cmd (replace-match
18114 (save-match-data
18115 (shell-quote-argument
18116 (file-name-nondirectory texfile)))
18117 t t cmd)))
18118 (while (string-match "%o" cmd)
18119 (setq cmd (replace-match
18120 (save-match-data
18121 (shell-quote-argument
18122 (file-name-directory texfile)))
18123 t t cmd)))
18124 (setq cmd (split-string cmd))
18125 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18126 (error nil))
18127 (cd dir))
18128 (if (not (file-exists-p pdffile))
18129 (progn (message "Failed to create pdf file from %s" texfile) nil)
18130 (condition-case nil
18131 (if (featurep 'xemacs)
18132 (call-process "convert" nil nil nil
18133 "-density" "96"
18134 "-trim"
18135 "-antialias"
18136 pdffile
18137 "-quality" "100"
18138 ;; "-sharpen" "0x1.0"
18139 pngfile)
18140 (call-process "convert" nil nil nil
18141 "-density" dpi
18142 "-trim"
18143 "-antialias"
18144 pdffile
18145 "-quality" "100"
18146 ;; "-sharpen" "0x1.0"
18147 pngfile))
18148 (error nil))
18149 (if (not (file-exists-p pngfile))
18150 (if org-format-latex-signal-error
18151 (error "Failed to create png file from %s" texfile)
18152 (message "Failed to create png file from %s" texfile)
18153 nil)
18154 ;; Use the requested file name and clean up
18155 (copy-file pngfile tofile 'replace)
18156 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18157 (if (file-exists-p (concat texfilebase e))
18158 (delete-file (concat texfilebase e))))
18159 pngfile))))
18161 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18162 "Fill a LaTeX header template TPL.
18163 In the template, the following place holders will be recognized:
18165 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18166 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18167 [PACKAGES] \\usepackage statements for PKG
18168 [NO-PACKAGES] do not include PKG
18169 [EXTRA] the string EXTRA
18170 [NO-EXTRA] do not include EXTRA
18172 For backward compatibility, if both the positive and the negative place
18173 holder is missing, the positive one (without the \"NO-\") will be
18174 assumed to be present at the end of the template.
18175 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18176 EXTRA is a string.
18177 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18178 (let (rpl (end ""))
18179 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18180 (setq rpl (if (or (match-end 1) (not def-pkg))
18181 "" (org-latex-packages-to-string def-pkg snippets-p t))
18182 tpl (replace-match rpl t t tpl))
18183 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18185 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18186 (setq rpl (if (or (match-end 1) (not pkg))
18187 "" (org-latex-packages-to-string pkg snippets-p t))
18188 tpl (replace-match rpl t t tpl))
18189 (if pkg (setq end
18190 (concat end "\n"
18191 (org-latex-packages-to-string pkg snippets-p)))))
18193 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18194 (setq rpl (if (or (match-end 1) (not extra))
18195 "" (concat extra "\n"))
18196 tpl (replace-match rpl t t tpl))
18197 (if (and extra (string-match "\\S-" extra))
18198 (setq end (concat end "\n" extra))))
18200 (if (string-match "\\S-" end)
18201 (concat tpl "\n" end)
18202 tpl)))
18204 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18205 "Turn an alist of packages into a string with the \\usepackage macros."
18206 (setq pkg (mapconcat (lambda(p)
18207 (cond
18208 ((stringp p) p)
18209 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18210 (format "%% Package %s omitted" (cadr p)))
18211 ((equal "" (car p))
18212 (format "\\usepackage{%s}" (cadr p)))
18214 (format "\\usepackage[%s]{%s}"
18215 (car p) (cadr p)))))
18217 "\n"))
18218 (if newline (concat pkg "\n") pkg))
18220 (defun org-dvipng-color (attr)
18221 "Return a RGB color specification for dvipng."
18222 (apply 'format "rgb %s %s %s"
18223 (mapcar 'org-normalize-color
18224 (if (featurep 'xemacs)
18225 (color-rgb-components
18226 (face-property 'default
18227 (cond ((eq attr :foreground) 'foreground)
18228 ((eq attr :background) 'background))))
18229 (color-values (face-attribute 'default attr nil))))))
18231 (defun org-dvipng-color-format (color-name)
18232 "Convert COLOR-NAME to a RGB color value for dvipng."
18233 (apply 'format "rgb %s %s %s"
18234 (mapcar 'org-normalize-color
18235 (color-values color-name))))
18237 (defun org-latex-color (attr)
18238 "Return a RGB color for the LaTeX color package."
18239 (apply 'format "%s,%s,%s"
18240 (mapcar 'org-normalize-color
18241 (if (featurep 'xemacs)
18242 (color-rgb-components
18243 (face-property 'default
18244 (cond ((eq attr :foreground) 'foreground)
18245 ((eq attr :background) 'background))))
18246 (color-values (face-attribute 'default attr nil))))))
18248 (defun org-latex-color-format (color-name)
18249 "Convert COLOR-NAME to a RGB color value."
18250 (apply 'format "%s,%s,%s"
18251 (mapcar 'org-normalize-color
18252 (color-values color-name))))
18254 (defun org-normalize-color (value)
18255 "Return string to be used as color value for an RGB component."
18256 (format "%g" (/ value 65535.0)))
18260 ;; Image display
18262 (defvar org-inline-image-overlays nil)
18263 (make-variable-buffer-local 'org-inline-image-overlays)
18265 (defun org-toggle-inline-images (&optional include-linked)
18266 "Toggle the display of inline images.
18267 INCLUDE-LINKED is passed to `org-display-inline-images'."
18268 (interactive "P")
18269 (if org-inline-image-overlays
18270 (progn
18271 (org-remove-inline-images)
18272 (message "Inline image display turned off"))
18273 (org-display-inline-images include-linked)
18274 (if (and (org-called-interactively-p)
18275 org-inline-image-overlays)
18276 (message "%d images displayed inline"
18277 (length org-inline-image-overlays))
18278 (message "No images to display inline"))))
18280 (defun org-redisplay-inline-images ()
18281 "Refresh the display of inline images."
18282 (interactive)
18283 (if (not org-inline-image-overlays)
18284 (org-toggle-inline-images)
18285 (org-toggle-inline-images)
18286 (org-toggle-inline-images)))
18288 (defun org-display-inline-images (&optional include-linked refresh beg end)
18289 "Display inline images.
18290 Normally only links without a description part are inlined, because this
18291 is how it will work for export. When INCLUDE-LINKED is set, also links
18292 with a description part will be inlined. This can be nice for a quick
18293 look at those images, but it does not reflect what exported files will look
18294 like.
18295 When REFRESH is set, refresh existing images between BEG and END.
18296 This will create new image displays only if necessary.
18297 BEG and END default to the buffer boundaries."
18298 (interactive "P")
18299 (unless refresh
18300 (org-remove-inline-images)
18301 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18302 (save-excursion
18303 (save-restriction
18304 (widen)
18305 (setq beg (or beg (point-min)) end (or end (point-max)))
18306 (goto-char beg)
18307 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18308 (substring (org-image-file-name-regexp) 0 -2)
18309 "\\)\\]" (if include-linked "" "\\]")))
18310 old file ov img type attrwidth width)
18311 (while (re-search-forward re end t)
18312 (setq old (get-char-property-and-overlay (match-beginning 1)
18313 'org-image-overlay)
18314 file (expand-file-name
18315 (concat (or (match-string 3) "") (match-string 4))))
18316 (when (image-type-available-p 'imagemagick)
18317 (setq attrwidth (if (or (listp org-image-actual-width)
18318 (null org-image-actual-width))
18319 (save-excursion
18320 (save-match-data
18321 (when (re-search-backward
18322 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18323 (save-excursion
18324 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18325 (string-to-number (match-string 1))))))
18326 width (cond ((eq org-image-actual-width t) nil)
18327 ((null org-image-actual-width) attrwidth)
18328 ((numberp org-image-actual-width)
18329 org-image-actual-width)
18330 ((listp org-image-actual-width)
18331 (or attrwidth (car org-image-actual-width))))
18332 type (if width 'imagemagick)))
18333 (when (file-exists-p file)
18334 (if (and (car-safe old) refresh)
18335 (image-refresh (overlay-get (cdr old) 'display))
18336 (setq img (save-match-data (create-image file type nil :width width)))
18337 (when img
18338 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18339 (overlay-put ov 'display img)
18340 (overlay-put ov 'face 'default)
18341 (overlay-put ov 'org-image-overlay t)
18342 (overlay-put ov 'modification-hooks
18343 (list 'org-display-inline-remove-overlay))
18344 (push ov org-inline-image-overlays)))))))))
18346 (define-obsolete-function-alias
18347 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18349 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18350 "Remove inline-display overlay if a corresponding region is modified."
18351 (let ((inhibit-modification-hooks t))
18352 (when (and ov after)
18353 (delete ov org-inline-image-overlays)
18354 (delete-overlay ov))))
18356 (defun org-remove-inline-images ()
18357 "Remove inline display of images."
18358 (interactive)
18359 (mapc 'delete-overlay org-inline-image-overlays)
18360 (setq org-inline-image-overlays nil))
18362 ;;;; Key bindings
18364 ;; Outline functions from `outline-mode-prefix-map'
18365 ;; that can be remapped in Org:
18366 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18367 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18368 (define-key org-mode-map [remap outline-forward-same-level]
18369 'org-forward-heading-same-level)
18370 (define-key org-mode-map [remap outline-backward-same-level]
18371 'org-backward-heading-same-level)
18372 (define-key org-mode-map [remap show-branches]
18373 'org-kill-note-or-show-branches)
18374 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18375 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18376 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18378 ;; Outline functions from `outline-mode-prefix-map' that can not
18379 ;; be remapped in Org:
18381 ;; - the column "key binding" shows whether the Outline function is still
18382 ;; available in Org mode on the same key that it has been bound to in
18383 ;; Outline mode:
18384 ;; - "overridden": key used for a different functionality in Org mode
18385 ;; - else: key still bound to the same Outline function in Org mode
18387 ;; | Outline function | key binding | Org replacement |
18388 ;; |------------------------------------+-------------+-----------------------|
18389 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18390 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18391 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18392 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18393 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18394 ;; | `show-entry' | overridden | no replacement |
18395 ;; | `show-children' | `C-c C-i' | visibility cycling |
18396 ;; | `show-branches' | `C-c C-k' | still same function |
18397 ;; | `show-subtree' | overridden | visibility cycling |
18398 ;; | `show-all' | overridden | no replacement |
18399 ;; | `hide-subtree' | overridden | visibility cycling |
18400 ;; | `hide-body' | overridden | no replacement |
18401 ;; | `hide-entry' | overridden | visibility cycling |
18402 ;; | `hide-leaves' | overridden | no replacement |
18403 ;; | `hide-sublevels' | overridden | no replacement |
18404 ;; | `hide-other' | overridden | no replacement |
18406 ;; Make `C-c C-x' a prefix key
18407 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18409 ;; TAB key with modifiers
18410 (org-defkey org-mode-map "\C-i" 'org-cycle)
18411 (org-defkey org-mode-map [(tab)] 'org-cycle)
18412 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18413 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18414 ;; The following line is necessary under Suse GNU/Linux
18415 (unless (featurep 'xemacs)
18416 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18417 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18418 (define-key org-mode-map [backtab] 'org-shifttab)
18420 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18421 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18422 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18424 ;; Cursor keys with modifiers
18425 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18426 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18427 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18428 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18430 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18431 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18432 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18433 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18435 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18436 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18437 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18438 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18440 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18441 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18442 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18443 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18445 ;; Babel keys
18446 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18447 (mapc (lambda (pair)
18448 (define-key org-babel-map (car pair) (cdr pair)))
18449 org-babel-key-bindings)
18451 ;;; Extra keys for tty access.
18452 ;; We only set them when really needed because otherwise the
18453 ;; menus don't show the simple keys
18455 (when (or org-use-extra-keys
18456 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18457 (not window-system))
18458 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18459 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18460 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18461 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18462 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18463 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18464 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18465 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18466 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18467 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18468 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18469 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18470 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18471 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18472 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18473 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18474 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18475 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18476 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18477 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18478 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18479 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18480 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18481 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18482 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18483 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18484 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18485 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18487 ;; All the other keys
18489 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18490 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18491 (if (boundp 'narrow-map)
18492 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18493 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18494 (if (boundp 'narrow-map)
18495 (org-defkey narrow-map "b" 'org-narrow-to-block)
18496 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18497 (if (boundp 'narrow-map)
18498 (org-defkey narrow-map "e" 'org-narrow-to-element)
18499 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18500 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18501 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18502 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18503 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18504 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18505 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18506 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18507 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18508 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18509 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18510 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18511 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18512 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18513 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18514 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18515 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18516 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18517 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18518 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18519 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18520 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18521 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18522 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18523 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18524 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18525 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18526 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18527 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18528 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18529 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18530 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18531 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18532 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18533 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18534 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18535 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18536 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18537 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18538 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18539 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18540 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18541 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18542 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18543 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18544 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18545 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18546 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18547 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18548 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18549 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18550 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18551 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18552 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18553 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18554 (org-defkey org-mode-map "\C-c^" 'org-sort)
18555 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18556 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18557 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18558 (org-defkey org-mode-map "\C-m" 'org-return)
18559 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18560 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18561 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18562 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18563 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18564 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18565 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18566 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18567 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18568 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18569 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18570 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18571 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18572 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18573 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18574 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18575 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18576 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18577 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18578 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18579 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18580 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18581 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18583 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18584 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18585 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18587 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18588 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18589 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18590 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18591 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18592 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18593 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18594 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18595 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18596 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18597 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18598 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18599 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18600 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18601 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18602 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18603 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18604 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18605 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18606 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18607 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18608 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18609 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18611 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18612 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18613 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18614 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18615 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18617 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18619 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18621 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18622 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18624 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18627 (when (featurep 'xemacs)
18628 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18631 (defconst org-speed-commands-default
18633 ("Outline Navigation")
18634 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18635 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18636 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18637 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18638 ("F" . org-next-block)
18639 ("B" . org-previous-block)
18640 ("u" . (org-speed-move-safe 'outline-up-heading))
18641 ("j" . org-goto)
18642 ("g" . (org-refile t))
18643 ("Outline Visibility")
18644 ("c" . org-cycle)
18645 ("C" . org-shifttab)
18646 (" " . org-display-outline-path)
18647 ("=" . org-columns)
18648 ("Outline Structure Editing")
18649 ("U" . org-shiftmetaup)
18650 ("D" . org-shiftmetadown)
18651 ("r" . org-metaright)
18652 ("l" . org-metaleft)
18653 ("R" . org-shiftmetaright)
18654 ("L" . org-shiftmetaleft)
18655 ("i" . (progn (forward-char 1) (call-interactively
18656 'org-insert-heading-respect-content)))
18657 ("^" . org-sort)
18658 ("w" . org-refile)
18659 ("a" . org-archive-subtree-default-with-confirmation)
18660 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18661 ("#" . org-toggle-comment)
18662 ("Clock Commands")
18663 ("I" . org-clock-in)
18664 ("O" . org-clock-out)
18665 ("Meta Data Editing")
18666 ("t" . org-todo)
18667 ("," . (org-priority))
18668 ("0" . (org-priority ?\ ))
18669 ("1" . (org-priority ?A))
18670 ("2" . (org-priority ?B))
18671 ("3" . (org-priority ?C))
18672 (":" . org-set-tags-command)
18673 ("e" . org-set-effort)
18674 ("E" . org-inc-effort)
18675 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18676 (org-entry-put (point) "APPT_WARNTIME" m)))
18677 ("Agenda Views etc")
18678 ("v" . org-agenda)
18679 ("/" . org-sparse-tree)
18680 ("Misc")
18681 ("o" . org-open-at-point)
18682 ("?" . org-speed-command-help)
18683 ("<" . (org-agenda-set-restriction-lock 'subtree))
18684 (">" . (org-agenda-remove-restriction-lock))
18686 "The default speed commands.")
18688 (defun org-print-speed-command (e)
18689 (if (> (length (car e)) 1)
18690 (progn
18691 (princ "\n")
18692 (princ (car e))
18693 (princ "\n")
18694 (princ (make-string (length (car e)) ?-))
18695 (princ "\n"))
18696 (princ (car e))
18697 (princ " ")
18698 (if (symbolp (cdr e))
18699 (princ (symbol-name (cdr e)))
18700 (prin1 (cdr e)))
18701 (princ "\n")))
18703 (defun org-speed-command-help ()
18704 "Show the available speed commands."
18705 (interactive)
18706 (if (not org-use-speed-commands)
18707 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18708 (with-output-to-temp-buffer "*Help*"
18709 (princ "User-defined Speed commands\n===========================\n")
18710 (mapc 'org-print-speed-command org-speed-commands-user)
18711 (princ "\n")
18712 (princ "Built-in Speed commands\n=======================\n")
18713 (mapc 'org-print-speed-command org-speed-commands-default))
18714 (with-current-buffer "*Help*"
18715 (setq truncate-lines t))))
18717 (defun org-speed-move-safe (cmd)
18718 "Execute CMD, but make sure that the cursor always ends up in a headline.
18719 If not, return to the original position and throw an error."
18720 (interactive)
18721 (let ((pos (point)))
18722 (call-interactively cmd)
18723 (unless (and (bolp) (org-at-heading-p))
18724 (goto-char pos)
18725 (error "Boundary reached while executing %s" cmd))))
18727 (defvar org-self-insert-command-undo-counter 0)
18729 (defvar org-table-auto-blank-field) ; defined in org-table.el
18730 (defvar org-speed-command nil)
18732 (define-obsolete-function-alias
18733 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18735 (defun org-speed-command-activate (keys)
18736 "Hook for activating single-letter speed commands.
18737 `org-speed-commands-default' specifies a minimal command set.
18738 Use `org-speed-commands-user' for further customization."
18739 (when (or (and (bolp) (looking-at org-outline-regexp))
18740 (and (functionp org-use-speed-commands)
18741 (funcall org-use-speed-commands)))
18742 (cdr (assoc keys (append org-speed-commands-user
18743 org-speed-commands-default)))))
18745 (define-obsolete-function-alias
18746 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18748 (defun org-babel-speed-command-activate (keys)
18749 "Hook for activating single-letter code block commands."
18750 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18751 (cdr (assoc keys org-babel-key-bindings))))
18753 (defcustom org-speed-command-hook
18754 '(org-speed-command-default-hook org-babel-speed-command-hook)
18755 "Hook for activating speed commands at strategic locations.
18756 Hook functions are called in sequence until a valid handler is
18757 found.
18759 Each hook takes a single argument, a user-pressed command key
18760 which is also a `self-insert-command' from the global map.
18762 Within the hook, examine the cursor position and the command key
18763 and return nil or a valid handler as appropriate. Handler could
18764 be one of an interactive command, a function, or a form.
18766 Set `org-use-speed-commands' to non-nil value to enable this
18767 hook. The default setting is `org-speed-command-activate'."
18768 :group 'org-structure
18769 :version "24.1"
18770 :type 'hook)
18772 (defun org-self-insert-command (N)
18773 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18774 If the cursor is in a table looking at whitespace, the whitespace is
18775 overwritten, and the table is not marked as requiring realignment."
18776 (interactive "p")
18777 (org-check-before-invisible-edit 'insert)
18778 (cond
18779 ((and org-use-speed-commands
18780 (setq org-speed-command
18781 (run-hook-with-args-until-success
18782 'org-speed-command-hook (this-command-keys))))
18783 (cond
18784 ((commandp org-speed-command)
18785 (setq this-command org-speed-command)
18786 (call-interactively org-speed-command))
18787 ((functionp org-speed-command)
18788 (funcall org-speed-command))
18789 ((and org-speed-command (listp org-speed-command))
18790 (eval org-speed-command))
18791 (t (let (org-use-speed-commands)
18792 (call-interactively 'org-self-insert-command)))))
18793 ((and
18794 (org-table-p)
18795 (progn
18796 ;; check if we blank the field, and if that triggers align
18797 (and (featurep 'org-table) org-table-auto-blank-field
18798 (member last-command
18799 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18800 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18801 ;; got extra space, this field does not determine column width
18802 (let (org-table-may-need-update) (org-table-blank-field))
18803 ;; no extra space, this field may determine column width
18804 (org-table-blank-field)))
18806 (eq N 1)
18807 (looking-at "[^|\n]* |"))
18808 (let (org-table-may-need-update)
18809 (goto-char (1- (match-end 0)))
18810 (backward-delete-char 1)
18811 (goto-char (match-beginning 0))
18812 (self-insert-command N)))
18814 (setq org-table-may-need-update t)
18815 (self-insert-command N)
18816 (org-fix-tags-on-the-fly)
18817 (if org-self-insert-cluster-for-undo
18818 (if (not (eq last-command 'org-self-insert-command))
18819 (setq org-self-insert-command-undo-counter 1)
18820 (if (>= org-self-insert-command-undo-counter 20)
18821 (setq org-self-insert-command-undo-counter 1)
18822 (and (> org-self-insert-command-undo-counter 0)
18823 buffer-undo-list (listp buffer-undo-list)
18824 (not (cadr buffer-undo-list)) ; remove nil entry
18825 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18826 (setq org-self-insert-command-undo-counter
18827 (1+ org-self-insert-command-undo-counter))))))))
18829 (defun org-check-before-invisible-edit (kind)
18830 "Check is editing if kind KIND would be dangerous with invisible text around.
18831 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18832 ;; First, try to get out of here as quickly as possible, to reduce overhead
18833 (if (and org-catch-invisible-edits
18834 (or (not (boundp 'visible-mode)) (not visible-mode))
18835 (or (get-char-property (point) 'invisible)
18836 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18837 ;; OK, we need to take a closer look
18838 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18839 (invisible-before-point (if (bobp) nil (get-char-property
18840 (1- (point)) 'invisible)))
18841 (border-and-ok-direction
18843 ;; Check if we are acting predictably before invisible text
18844 (and invisible-at-point (not invisible-before-point)
18845 (memq kind '(insert delete-backward)))
18846 ;; Check if we are acting predictably after invisible text
18847 ;; This works not well, and I have turned it off. It seems
18848 ;; better to always show and stop after invisible text.
18849 ;; (and (not invisible-at-point) invisible-before-point
18850 ;; (memq kind '(insert delete)))
18852 (when (or (memq invisible-at-point '(outline org-hide-block t))
18853 (memq invisible-before-point '(outline org-hide-block t)))
18854 (if (eq org-catch-invisible-edits 'error)
18855 (error "Editing in invisible areas is prohibited - make visible first"))
18856 (if (and org-custom-properties-overlays
18857 (y-or-n-p "Display invisible properties in this buffer? "))
18858 (org-toggle-custom-properties-visibility)
18859 ;; Make the area visible
18860 (save-excursion
18861 (if invisible-before-point
18862 (goto-char (previous-single-char-property-change
18863 (point) 'invisible)))
18864 (org-cycle))
18865 (cond
18866 ((eq org-catch-invisible-edits 'show)
18867 ;; That's it, we do the edit after showing
18868 (message
18869 "Unfolding invisible region around point before editing")
18870 (sit-for 1))
18871 ((and (eq org-catch-invisible-edits 'smart)
18872 border-and-ok-direction)
18873 (message "Unfolding invisible region around point before editing"))
18875 ;; Don't do the edit, make the user repeat it in full visibility
18876 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18878 (defun org-fix-tags-on-the-fly ()
18879 (when (and (equal (char-after (point-at-bol)) ?*)
18880 (org-at-heading-p))
18881 (org-align-tags-here org-tags-column)))
18883 (defun org-delete-backward-char (N)
18884 "Like `delete-backward-char', insert whitespace at field end in tables.
18885 When deleting backwards, in tables this function will insert whitespace in
18886 front of the next \"|\" separator, to keep the table aligned. The table will
18887 still be marked for re-alignment if the field did fill the entire column,
18888 because, in this case the deletion might narrow the column."
18889 (interactive "p")
18890 (save-match-data
18891 (org-check-before-invisible-edit 'delete-backward)
18892 (if (and (org-table-p)
18893 (eq N 1)
18894 (string-match "|" (buffer-substring (point-at-bol) (point)))
18895 (looking-at ".*?|"))
18896 (let ((pos (point))
18897 (noalign (looking-at "[^|\n\r]* |"))
18898 (c org-table-may-need-update))
18899 (backward-delete-char N)
18900 (if (not overwrite-mode)
18901 (progn
18902 (skip-chars-forward "^|")
18903 (insert " ")
18904 (goto-char (1- pos))))
18905 ;; noalign: if there were two spaces at the end, this field
18906 ;; does not determine the width of the column.
18907 (if noalign (setq org-table-may-need-update c)))
18908 (backward-delete-char N)
18909 (org-fix-tags-on-the-fly))))
18911 (defun org-delete-char (N)
18912 "Like `delete-char', but insert whitespace at field end in tables.
18913 When deleting characters, in tables this function will insert whitespace in
18914 front of the next \"|\" separator, to keep the table aligned. The table will
18915 still be marked for re-alignment if the field did fill the entire column,
18916 because, in this case the deletion might narrow the column."
18917 (interactive "p")
18918 (save-match-data
18919 (org-check-before-invisible-edit 'delete)
18920 (if (and (org-table-p)
18921 (not (bolp))
18922 (not (= (char-after) ?|))
18923 (eq N 1))
18924 (if (looking-at ".*?|")
18925 (let ((pos (point))
18926 (noalign (looking-at "[^|\n\r]* |"))
18927 (c org-table-may-need-update))
18928 (replace-match (concat
18929 (substring (match-string 0) 1 -1)
18930 " |"))
18931 (goto-char pos)
18932 ;; noalign: if there were two spaces at the end, this field
18933 ;; does not determine the width of the column.
18934 (if noalign (setq org-table-may-need-update c)))
18935 (delete-char N))
18936 (delete-char N)
18937 (org-fix-tags-on-the-fly))))
18939 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18940 (put 'org-self-insert-command 'delete-selection t)
18941 (put 'orgtbl-self-insert-command 'delete-selection t)
18942 (put 'org-delete-char 'delete-selection 'supersede)
18943 (put 'org-delete-backward-char 'delete-selection 'supersede)
18944 (put 'org-yank 'delete-selection 'yank)
18946 ;; Make `flyspell-mode' delay after some commands
18947 (put 'org-self-insert-command 'flyspell-delayed t)
18948 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18949 (put 'org-delete-char 'flyspell-delayed t)
18950 (put 'org-delete-backward-char 'flyspell-delayed t)
18952 ;; Make pabbrev-mode expand after org-mode commands
18953 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18954 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18956 ;; How to do this: Measure non-white length of current string
18957 ;; If equal to column width, we should realign.
18959 (defun org-remap (map &rest commands)
18960 "In MAP, remap the functions given in COMMANDS.
18961 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18962 (let (new old)
18963 (while commands
18964 (setq old (pop commands) new (pop commands))
18965 (if (fboundp 'command-remapping)
18966 (org-defkey map (vector 'remap old) new)
18967 (substitute-key-definition old new map global-map)))))
18969 (when (eq org-enable-table-editor 'optimized)
18970 ;; If the user wants maximum table support, we need to hijack
18971 ;; some standard editing functions
18972 (org-remap org-mode-map
18973 'self-insert-command 'org-self-insert-command
18974 'delete-char 'org-delete-char
18975 'delete-backward-char 'org-delete-backward-char)
18976 (org-defkey org-mode-map "|" 'org-force-self-insert))
18978 (defvar org-ctrl-c-ctrl-c-hook nil
18979 "Hook for functions attaching themselves to `C-c C-c'.
18981 This can be used to add additional functionality to the C-c C-c
18982 key which executes context-dependent commands. This hook is run
18983 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18984 run after the last test.
18986 Each function will be called with no arguments. The function
18987 must check if the context is appropriate for it to act. If yes,
18988 it should do its thing and then return a non-nil value. If the
18989 context is wrong, just do nothing and return nil.")
18991 (defvar org-ctrl-c-ctrl-c-final-hook nil
18992 "Hook for functions attaching themselves to `C-c C-c'.
18994 This can be used to add additional functionality to the C-c C-c
18995 key which executes context-dependent commands. This hook is run
18996 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18997 before the first test.
18999 Each function will be called with no arguments. The function
19000 must check if the context is appropriate for it to act. If yes,
19001 it should do its thing and then return a non-nil value. If the
19002 context is wrong, just do nothing and return nil.")
19004 (defvar org-tab-first-hook nil
19005 "Hook for functions to attach themselves to TAB.
19006 See `org-ctrl-c-ctrl-c-hook' for more information.
19007 This hook runs as the first action when TAB is pressed, even before
19008 `org-cycle' messes around with the `outline-regexp' to cater for
19009 inline tasks and plain list item folding.
19010 If any function in this hook returns t, any other actions that
19011 would have been caused by TAB (such as table field motion or visibility
19012 cycling) will not occur.")
19014 (defvar org-tab-after-check-for-table-hook nil
19015 "Hook for functions to attach themselves to TAB.
19016 See `org-ctrl-c-ctrl-c-hook' for more information.
19017 This hook runs after it has been established that the cursor is not in a
19018 table, but before checking if the cursor is in a headline or if global cycling
19019 should be done.
19020 If any function in this hook returns t, not other actions like visibility
19021 cycling will be done.")
19023 (defvar org-tab-after-check-for-cycling-hook nil
19024 "Hook for functions to attach themselves to TAB.
19025 See `org-ctrl-c-ctrl-c-hook' for more information.
19026 This hook runs after it has been established that not table field motion and
19027 not visibility should be done because of current context. This is probably
19028 the place where a package like yasnippets can hook in.")
19030 (defvar org-tab-before-tab-emulation-hook nil
19031 "Hook for functions to attach themselves to TAB.
19032 See `org-ctrl-c-ctrl-c-hook' for more information.
19033 This hook runs after every other options for TAB have been exhausted, but
19034 before indentation and \t insertion takes place.")
19036 (defvar org-metaleft-hook nil
19037 "Hook for functions attaching themselves to `M-left'.
19038 See `org-ctrl-c-ctrl-c-hook' for more information.")
19039 (defvar org-metaright-hook nil
19040 "Hook for functions attaching themselves to `M-right'.
19041 See `org-ctrl-c-ctrl-c-hook' for more information.")
19042 (defvar org-metaup-hook nil
19043 "Hook for functions attaching themselves to `M-up'.
19044 See `org-ctrl-c-ctrl-c-hook' for more information.")
19045 (defvar org-metadown-hook nil
19046 "Hook for functions attaching themselves to `M-down'.
19047 See `org-ctrl-c-ctrl-c-hook' for more information.")
19048 (defvar org-shiftmetaleft-hook nil
19049 "Hook for functions attaching themselves to `M-S-left'.
19050 See `org-ctrl-c-ctrl-c-hook' for more information.")
19051 (defvar org-shiftmetaright-hook nil
19052 "Hook for functions attaching themselves to `M-S-right'.
19053 See `org-ctrl-c-ctrl-c-hook' for more information.")
19054 (defvar org-shiftmetaup-hook nil
19055 "Hook for functions attaching themselves to `M-S-up'.
19056 See `org-ctrl-c-ctrl-c-hook' for more information.")
19057 (defvar org-shiftmetadown-hook nil
19058 "Hook for functions attaching themselves to `M-S-down'.
19059 See `org-ctrl-c-ctrl-c-hook' for more information.")
19060 (defvar org-metareturn-hook nil
19061 "Hook for functions attaching themselves to `M-RET'.
19062 See `org-ctrl-c-ctrl-c-hook' for more information.")
19063 (defvar org-shiftup-hook nil
19064 "Hook for functions attaching themselves to `S-up'.
19065 See `org-ctrl-c-ctrl-c-hook' for more information.")
19066 (defvar org-shiftup-final-hook nil
19067 "Hook for functions attaching themselves to `S-up'.
19068 This one runs after all other options except shift-select have been excluded.
19069 See `org-ctrl-c-ctrl-c-hook' for more information.")
19070 (defvar org-shiftdown-hook nil
19071 "Hook for functions attaching themselves to `S-down'.
19072 See `org-ctrl-c-ctrl-c-hook' for more information.")
19073 (defvar org-shiftdown-final-hook nil
19074 "Hook for functions attaching themselves to `S-down'.
19075 This one runs after all other options except shift-select have been excluded.
19076 See `org-ctrl-c-ctrl-c-hook' for more information.")
19077 (defvar org-shiftleft-hook nil
19078 "Hook for functions attaching themselves to `S-left'.
19079 See `org-ctrl-c-ctrl-c-hook' for more information.")
19080 (defvar org-shiftleft-final-hook nil
19081 "Hook for functions attaching themselves to `S-left'.
19082 This one runs after all other options except shift-select have been excluded.
19083 See `org-ctrl-c-ctrl-c-hook' for more information.")
19084 (defvar org-shiftright-hook nil
19085 "Hook for functions attaching themselves to `S-right'.
19086 See `org-ctrl-c-ctrl-c-hook' for more information.")
19087 (defvar org-shiftright-final-hook nil
19088 "Hook for functions attaching themselves to `S-right'.
19089 This one runs after all other options except shift-select have been excluded.
19090 See `org-ctrl-c-ctrl-c-hook' for more information.")
19092 (defun org-modifier-cursor-error ()
19093 "Throw an error, a modified cursor command was applied in wrong context."
19094 (error "This command is active in special context like tables, headlines or items"))
19096 (defun org-shiftselect-error ()
19097 "Throw an error because Shift-Cursor command was applied in wrong context."
19098 (if (and (boundp 'shift-select-mode) shift-select-mode)
19099 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19100 (error "This command works only in special context like headlines or timestamps")))
19102 (defun org-call-for-shift-select (cmd)
19103 (let ((this-command-keys-shift-translated t))
19104 (call-interactively cmd)))
19106 (defun org-shifttab (&optional arg)
19107 "Global visibility cycling or move to previous table field.
19108 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19109 on context.
19110 See the individual commands for more information."
19111 (interactive "P")
19112 (cond
19113 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19114 ((integerp arg)
19115 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19116 (message "Content view to level: %d" arg)
19117 (org-content (prefix-numeric-value arg2))
19118 (setq org-cycle-global-status 'overview)))
19119 (t (call-interactively 'org-global-cycle))))
19121 (defun org-shiftmetaleft ()
19122 "Promote subtree or delete table column.
19123 Calls `org-promote-subtree', `org-outdent-item-tree', or
19124 `org-table-delete-column', depending on context. See the
19125 individual commands for more information."
19126 (interactive)
19127 (cond
19128 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19129 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19130 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19131 ((if (not (org-region-active-p)) (org-at-item-p)
19132 (save-excursion (goto-char (region-beginning))
19133 (org-at-item-p)))
19134 (call-interactively 'org-outdent-item-tree))
19135 (t (org-modifier-cursor-error))))
19137 (defun org-shiftmetaright ()
19138 "Demote subtree or insert table column.
19139 Calls `org-demote-subtree', `org-indent-item-tree', or
19140 `org-table-insert-column', depending on context. See the
19141 individual commands for more information."
19142 (interactive)
19143 (cond
19144 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19145 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19146 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19147 ((if (not (org-region-active-p)) (org-at-item-p)
19148 (save-excursion (goto-char (region-beginning))
19149 (org-at-item-p)))
19150 (call-interactively 'org-indent-item-tree))
19151 (t (org-modifier-cursor-error))))
19153 (defun org-shiftmetaup (&optional arg)
19154 "Move subtree up or kill table row.
19155 Calls `org-move-subtree-up' or `org-table-kill-row' or
19156 `org-move-item-up' or `org-timestamp-up', depending on context.
19157 See the individual commands for more information."
19158 (interactive "P")
19159 (cond
19160 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19161 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19162 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19163 ((org-at-item-p) (call-interactively 'org-move-item-up))
19164 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19165 (call-interactively 'org-timestamp-up)))
19166 (t (org-modifier-cursor-error))))
19168 (defun org-shiftmetadown (&optional arg)
19169 "Move subtree down or insert table row.
19170 Calls `org-move-subtree-down' or `org-table-insert-row' or
19171 `org-move-item-down' or `org-timestamp-up', depending on context.
19172 See the individual commands for more information."
19173 (interactive "P")
19174 (cond
19175 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19176 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19177 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19178 ((org-at-item-p) (call-interactively 'org-move-item-down))
19179 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19180 (call-interactively 'org-timestamp-down)))
19181 (t (org-modifier-cursor-error))))
19183 (defsubst org-hidden-tree-error ()
19184 (error
19185 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19187 (defun org-metaleft (&optional arg)
19188 "Promote heading or move table column to left.
19189 Calls `org-do-promote' or `org-table-move-column', depending on context.
19190 With no specific context, calls the Emacs default `backward-word'.
19191 See the individual commands for more information."
19192 (interactive "P")
19193 (cond
19194 ((run-hook-with-args-until-success 'org-metaleft-hook))
19195 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19196 ((org-with-limited-levels
19197 (or (org-at-heading-p)
19198 (and (org-region-active-p)
19199 (save-excursion
19200 (goto-char (region-beginning))
19201 (org-at-heading-p)))))
19202 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19203 (call-interactively 'org-do-promote))
19204 ;; At an inline task.
19205 ((org-at-heading-p)
19206 (call-interactively 'org-inlinetask-promote))
19207 ((or (org-at-item-p)
19208 (and (org-region-active-p)
19209 (save-excursion
19210 (goto-char (region-beginning))
19211 (org-at-item-p))))
19212 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19213 (call-interactively 'org-outdent-item))
19214 (t (call-interactively 'backward-word))))
19216 (defun org-metaright (&optional arg)
19217 "Demote a subtree, a list item or move table column to right.
19218 In front of a drawer or a block keyword, indent it correctly.
19219 With no specific context, calls the Emacs default `forward-word'.
19220 See the individual commands for more information."
19221 (interactive "P")
19222 (cond
19223 ((run-hook-with-args-until-success 'org-metaright-hook))
19224 ((org-at-table-p) (call-interactively 'org-table-move-column))
19225 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19226 ((org-at-block-p) (call-interactively 'org-indent-block))
19227 ((org-with-limited-levels
19228 (or (org-at-heading-p)
19229 (and (org-region-active-p)
19230 (save-excursion
19231 (goto-char (region-beginning))
19232 (org-at-heading-p)))))
19233 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19234 (call-interactively 'org-do-demote))
19235 ;; At an inline task.
19236 ((org-at-heading-p)
19237 (call-interactively 'org-inlinetask-demote))
19238 ((or (org-at-item-p)
19239 (and (org-region-active-p)
19240 (save-excursion
19241 (goto-char (region-beginning))
19242 (org-at-item-p))))
19243 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19244 (call-interactively 'org-indent-item))
19245 (t (call-interactively 'forward-word))))
19247 (defun org-check-for-hidden (what)
19248 "Check if there are hidden headlines/items in the current visual line.
19249 WHAT can be either `headlines' or `items'. If the current line is
19250 an outline or item heading and it has a folded subtree below it,
19251 this function returns t, nil otherwise."
19252 (let ((re (cond
19253 ((eq what 'headlines) org-outline-regexp-bol)
19254 ((eq what 'items) (org-item-beginning-re))
19255 (t (error "This should not happen"))))
19256 beg end)
19257 (save-excursion
19258 (catch 'exit
19259 (unless (org-region-active-p)
19260 (setq beg (point-at-bol))
19261 (beginning-of-line 2)
19262 (while (and (not (eobp)) ;; this is like `next-line'
19263 (get-char-property (1- (point)) 'invisible))
19264 (beginning-of-line 2))
19265 (setq end (point))
19266 (goto-char beg)
19267 (goto-char (point-at-eol))
19268 (setq end (max end (point)))
19269 (while (re-search-forward re end t)
19270 (if (get-char-property (match-beginning 0) 'invisible)
19271 (throw 'exit t))))
19272 nil))))
19274 (defun org-metaup (&optional arg)
19275 "Move subtree up or move table row up.
19276 Calls `org-move-subtree-up' or `org-table-move-row' or
19277 `org-move-item-up', depending on context. See the individual commands
19278 for more information."
19279 (interactive "P")
19280 (cond
19281 ((run-hook-with-args-until-success 'org-metaup-hook))
19282 ((org-region-active-p)
19283 (let* ((a (min (region-beginning) (region-end)))
19284 (b (1- (max (region-beginning) (region-end))))
19285 (c (save-excursion (goto-char a)
19286 (move-beginning-of-line 0)))
19287 (d (save-excursion (goto-char a)
19288 (move-end-of-line 0) (point))))
19289 (transpose-regions a b c d)
19290 (goto-char c)))
19291 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19292 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19293 ((org-at-item-p) (call-interactively 'org-move-item-up))
19294 (t (org-drag-element-backward))))
19296 (defun org-metadown (&optional arg)
19297 "Move subtree down or move table row down.
19298 Calls `org-move-subtree-down' or `org-table-move-row' or
19299 `org-move-item-down', depending on context. See the individual
19300 commands for more information."
19301 (interactive "P")
19302 (cond
19303 ((run-hook-with-args-until-success 'org-metadown-hook))
19304 ((org-region-active-p)
19305 (let* ((a (min (region-beginning) (region-end)))
19306 (b (max (region-beginning) (region-end)))
19307 (c (save-excursion (goto-char b)
19308 (move-beginning-of-line 1)))
19309 (d (save-excursion (goto-char b)
19310 (move-end-of-line 1) (1+ (point)))))
19311 (transpose-regions a b c d)
19312 (goto-char d)))
19313 ((org-at-table-p) (call-interactively 'org-table-move-row))
19314 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19315 ((org-at-item-p) (call-interactively 'org-move-item-down))
19316 (t (org-drag-element-forward))))
19318 (defun org-shiftup (&optional arg)
19319 "Increase item in timestamp or increase priority of current headline.
19320 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19321 depending on context. See the individual commands for more information."
19322 (interactive "P")
19323 (cond
19324 ((run-hook-with-args-until-success 'org-shiftup-hook))
19325 ((and org-support-shift-select (org-region-active-p))
19326 (org-call-for-shift-select 'previous-line))
19327 ((org-at-timestamp-p t)
19328 (call-interactively (if org-edit-timestamp-down-means-later
19329 'org-timestamp-down 'org-timestamp-up)))
19330 ((and (not (eq org-support-shift-select 'always))
19331 org-enable-priority-commands
19332 (org-at-heading-p))
19333 (call-interactively 'org-priority-up))
19334 ((and (not org-support-shift-select) (org-at-item-p))
19335 (call-interactively 'org-previous-item))
19336 ((org-clocktable-try-shift 'up arg))
19337 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19338 (org-support-shift-select
19339 (org-call-for-shift-select 'previous-line))
19340 (t (org-shiftselect-error))))
19342 (defun org-shiftdown (&optional arg)
19343 "Decrease item in timestamp or decrease priority of current headline.
19344 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19345 depending on context. See the individual commands for more information."
19346 (interactive "P")
19347 (cond
19348 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19349 ((and org-support-shift-select (org-region-active-p))
19350 (org-call-for-shift-select 'next-line))
19351 ((org-at-timestamp-p t)
19352 (call-interactively (if org-edit-timestamp-down-means-later
19353 'org-timestamp-up 'org-timestamp-down)))
19354 ((and (not (eq org-support-shift-select 'always))
19355 org-enable-priority-commands
19356 (org-at-heading-p))
19357 (call-interactively 'org-priority-down))
19358 ((and (not org-support-shift-select) (org-at-item-p))
19359 (call-interactively 'org-next-item))
19360 ((org-clocktable-try-shift 'down arg))
19361 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19362 (org-support-shift-select
19363 (org-call-for-shift-select 'next-line))
19364 (t (org-shiftselect-error))))
19366 (defun org-shiftright (&optional arg)
19367 "Cycle the thing at point or in the current line, depending on context.
19368 Depending on context, this does one of the following:
19370 - switch a timestamp at point one day into the future
19371 - on a headline, switch to the next TODO keyword.
19372 - on an item, switch entire list to the next bullet type
19373 - on a property line, switch to the next allowed value
19374 - on a clocktable definition line, move time block into the future"
19375 (interactive "P")
19376 (cond
19377 ((run-hook-with-args-until-success 'org-shiftright-hook))
19378 ((and org-support-shift-select (org-region-active-p))
19379 (org-call-for-shift-select 'forward-char))
19380 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19381 ((and (not (eq org-support-shift-select 'always))
19382 (org-at-heading-p))
19383 (let ((org-inhibit-logging
19384 (not org-treat-S-cursor-todo-selection-as-state-change))
19385 (org-inhibit-blocking
19386 (not org-treat-S-cursor-todo-selection-as-state-change)))
19387 (org-call-with-arg 'org-todo 'right)))
19388 ((or (and org-support-shift-select
19389 (not (eq org-support-shift-select 'always))
19390 (org-at-item-bullet-p))
19391 (and (not org-support-shift-select) (org-at-item-p)))
19392 (org-call-with-arg 'org-cycle-list-bullet nil))
19393 ((and (not (eq org-support-shift-select 'always))
19394 (org-at-property-p))
19395 (call-interactively 'org-property-next-allowed-value))
19396 ((org-clocktable-try-shift 'right arg))
19397 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19398 (org-support-shift-select
19399 (org-call-for-shift-select 'forward-char))
19400 (t (org-shiftselect-error))))
19402 (defun org-shiftleft (&optional arg)
19403 "Cycle the thing at point or in the current line, depending on context.
19404 Depending on context, this does one of the following:
19406 - switch a timestamp at point one day into the past
19407 - on a headline, switch to the previous TODO keyword.
19408 - on an item, switch entire list to the previous bullet type
19409 - on a property line, switch to the previous allowed value
19410 - on a clocktable definition line, move time block into the past"
19411 (interactive "P")
19412 (cond
19413 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19414 ((and org-support-shift-select (org-region-active-p))
19415 (org-call-for-shift-select 'backward-char))
19416 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19417 ((and (not (eq org-support-shift-select 'always))
19418 (org-at-heading-p))
19419 (let ((org-inhibit-logging
19420 (not org-treat-S-cursor-todo-selection-as-state-change))
19421 (org-inhibit-blocking
19422 (not org-treat-S-cursor-todo-selection-as-state-change)))
19423 (org-call-with-arg 'org-todo 'left)))
19424 ((or (and org-support-shift-select
19425 (not (eq org-support-shift-select 'always))
19426 (org-at-item-bullet-p))
19427 (and (not org-support-shift-select) (org-at-item-p)))
19428 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19429 ((and (not (eq org-support-shift-select 'always))
19430 (org-at-property-p))
19431 (call-interactively 'org-property-previous-allowed-value))
19432 ((org-clocktable-try-shift 'left arg))
19433 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19434 (org-support-shift-select
19435 (org-call-for-shift-select 'backward-char))
19436 (t (org-shiftselect-error))))
19438 (defun org-shiftcontrolright ()
19439 "Switch to next TODO set."
19440 (interactive)
19441 (cond
19442 ((and org-support-shift-select (org-region-active-p))
19443 (org-call-for-shift-select 'forward-word))
19444 ((and (not (eq org-support-shift-select 'always))
19445 (org-at-heading-p))
19446 (org-call-with-arg 'org-todo 'nextset))
19447 (org-support-shift-select
19448 (org-call-for-shift-select 'forward-word))
19449 (t (org-shiftselect-error))))
19451 (defun org-shiftcontrolleft ()
19452 "Switch to previous TODO set."
19453 (interactive)
19454 (cond
19455 ((and org-support-shift-select (org-region-active-p))
19456 (org-call-for-shift-select 'backward-word))
19457 ((and (not (eq org-support-shift-select 'always))
19458 (org-at-heading-p))
19459 (org-call-with-arg 'org-todo 'previousset))
19460 (org-support-shift-select
19461 (org-call-for-shift-select 'backward-word))
19462 (t (org-shiftselect-error))))
19464 (defun org-shiftcontrolup (&optional n)
19465 "Change timestamps synchronously up in CLOCK log lines.
19466 Optional argument N tells to change by that many units."
19467 (interactive "P")
19468 (cond ((and (not org-support-shift-select)
19469 (org-at-clock-log-p)
19470 (org-at-timestamp-p t))
19471 (org-clock-timestamps-up n))
19472 (t (org-shiftselect-error))))
19474 (defun org-shiftcontroldown (&optional n)
19475 "Change timestamps synchronously down in CLOCK log lines.
19476 Optional argument N tells to change by that many units."
19477 (interactive "P")
19478 (cond ((and (not org-support-shift-select)
19479 (org-at-clock-log-p)
19480 (org-at-timestamp-p t))
19481 (org-clock-timestamps-down n))
19482 (t (org-shiftselect-error))))
19484 (defun org-ctrl-c-ret ()
19485 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19486 (interactive)
19487 (cond
19488 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19489 (t (call-interactively 'org-insert-heading))))
19491 (defun org-find-visible ()
19492 (let ((s (point)))
19493 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19494 (get-char-property s 'invisible)))
19496 (defun org-find-invisible ()
19497 (let ((s (point)))
19498 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19499 (not (get-char-property s 'invisible))))
19502 (defun org-copy-visible (beg end)
19503 "Copy the visible parts of the region."
19504 (interactive "r")
19505 (let (snippets s)
19506 (save-excursion
19507 (save-restriction
19508 (narrow-to-region beg end)
19509 (setq s (goto-char (point-min)))
19510 (while (not (= (point) (point-max)))
19511 (goto-char (org-find-invisible))
19512 (push (buffer-substring s (point)) snippets)
19513 (setq s (goto-char (org-find-visible))))))
19514 (kill-new (apply 'concat (nreverse snippets)))))
19516 (defun org-copy-special ()
19517 "Copy region in table or copy current subtree.
19518 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19519 See the individual commands for more information."
19520 (interactive)
19521 (call-interactively
19522 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19524 (defun org-cut-special ()
19525 "Cut region in table or cut current subtree.
19526 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19527 See the individual commands for more information."
19528 (interactive)
19529 (call-interactively
19530 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19532 (defun org-paste-special (arg)
19533 "Paste rectangular region into table, or past subtree relative to level.
19534 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19535 See the individual commands for more information."
19536 (interactive "P")
19537 (if (org-at-table-p)
19538 (org-table-paste-rectangle)
19539 (org-paste-subtree arg)))
19541 (defsubst org-in-fixed-width-region-p ()
19542 "Is point in a fixed-width region?"
19543 (save-match-data
19544 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19546 (defun org-edit-special (&optional arg)
19547 "Call a special editor for the element at point.
19548 When at a table, call the formula editor with `org-table-edit-formulas'.
19549 When in a source code block, call `org-edit-src-code'.
19550 When in a fixed-width region, call `org-edit-fixed-width-region'.
19551 When at an #+INCLUDE keyword, visit the included file.
19552 On a link, call `ffap' to visit the link at point.
19553 Otherwise, return a user error."
19554 (interactive)
19555 (let ((element (org-element-at-point)))
19556 (assert (not buffer-read-only) nil
19557 "Buffer is read-only: %s" (buffer-name))
19558 (case (org-element-type element)
19559 (src-block
19560 (if (not arg) (org-edit-src-code)
19561 (let* ((info (org-babel-get-src-block-info))
19562 (lang (nth 0 info))
19563 (params (nth 2 info))
19564 (session (cdr (assq :session params))))
19565 (if (not session) (org-edit-src-code)
19566 ;; At a src-block with a session and function called with
19567 ;; an ARG: switch to the buffer related to the inferior
19568 ;; process.
19569 (funcall (intern (concat "org-babel-prep-session:" lang))
19570 session params)))))
19571 (keyword
19572 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19573 (find-file
19574 (org-remove-double-quotes
19575 (car (org-split-string (org-element-property :value element)))))
19576 (user-error "No special environment to edit here")))
19577 (table
19578 (if (eq (org-element-property :type element) 'table.el)
19579 (org-edit-src-code)
19580 (call-interactively 'org-table-edit-formulas)))
19581 ;; Only Org tables contain `table-row' type elements.
19582 (table-row (call-interactively 'org-table-edit-formulas))
19583 ((example-block export-block) (org-edit-src-code))
19584 (fixed-width (org-edit-fixed-width-region))
19585 (otherwise
19586 ;; No notable element at point. Though, we may be at a link,
19587 ;; which is an object. Thus, scan deeper.
19588 (if (eq (org-element-type (org-element-context element)) 'link)
19589 (call-interactively 'ffap)
19590 (user-error "No special environment to edit here"))))))
19592 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19593 (defun org-ctrl-c-ctrl-c (&optional arg)
19594 "Set tags in headline, or update according to changed information at point.
19596 This command does many different things, depending on context:
19598 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19599 this is what we do.
19601 - If the cursor is on a statistics cookie, update it.
19603 - If the cursor is in a headline, prompt for tags and insert them
19604 into the current line, aligned to `org-tags-column'. When called
19605 with prefix arg, realign all tags in the current buffer.
19607 - If the cursor is in one of the special #+KEYWORD lines, this
19608 triggers scanning the buffer for these lines and updating the
19609 information.
19611 - If the cursor is inside a table, realign the table. This command
19612 works even if the automatic table editor has been turned off.
19614 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19615 the entire table.
19617 - If the cursor is at a footnote reference or definition, jump to
19618 the corresponding definition or references, respectively.
19620 - If the cursor is a the beginning of a dynamic block, update it.
19622 - If the current buffer is a capture buffer, close note and file it.
19624 - If the cursor is on a <<<target>>>, update radio targets and
19625 corresponding links in this buffer.
19627 - If the cursor is on a numbered item in a plain list, renumber the
19628 ordered list.
19630 - If the cursor is on a checkbox, toggle it.
19632 - If the cursor is on a code block, evaluate it. The variable
19633 `org-confirm-babel-evaluate' can be used to control prompting
19634 before code block evaluation, by default every code block
19635 evaluation requires confirmation. Code block evaluation can be
19636 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19637 (interactive "P")
19638 (cond
19639 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19640 org-occur-highlights
19641 org-latex-fragment-image-overlays)
19642 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19643 (org-remove-occur-highlights)
19644 (org-remove-latex-fragment-image-overlays)
19645 (message "Temporary highlights/overlays removed from current buffer"))
19646 ((and (local-variable-p 'org-finish-function (current-buffer))
19647 (fboundp org-finish-function))
19648 (funcall org-finish-function))
19649 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19651 (let* ((context (org-element-context)) (type (org-element-type context)))
19652 ;; Test if point is within blanks at the end of an element.
19653 (if (save-excursion
19654 (or (not context)
19655 (beginning-of-line)
19656 (and (looking-at "[ \t]*$")
19657 (skip-chars-forward " \r\t\n")
19658 (>= (point) (org-element-property :end context)))))
19659 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19660 (user-error "C-c C-c can do nothing useful at this location"))
19661 ;; For convenience: at the first line of a paragraph on the
19662 ;; same line as an item, apply function on that item instead.
19663 (when (eq type 'paragraph)
19664 (let ((parent (org-element-property :parent context)))
19665 (when (and (eq (org-element-type parent) 'item)
19666 (= (point-at-bol) (org-element-property :begin parent)))
19667 (setq context parent type 'item))))
19668 ;; Act according to type of element or object at point.
19669 (case type
19670 (clock (org-clock-update-time-maybe))
19671 (dynamic-block
19672 (save-excursion
19673 (goto-char (org-element-property :post-affiliated context))
19674 (org-update-dblock)))
19675 (footnote-definition
19676 (goto-char (org-element-property :post-affiliated context))
19677 (call-interactively 'org-footnote-action))
19678 (footnote-reference (call-interactively 'org-footnote-action))
19679 ((headline inlinetask)
19680 (save-excursion (goto-char (org-element-property :begin context))
19681 (call-interactively 'org-set-tags)))
19682 (item
19683 ;; At an item: a double C-u set checkbox to "[-]"
19684 ;; unconditionally, whereas a single one will toggle its
19685 ;; presence. Without an universal argument, if the item
19686 ;; has a checkbox, toggle it. Otherwise repair the list.
19687 (let* ((box (org-element-property :checkbox context))
19688 (struct (org-element-property :structure context))
19689 (old-struct (copy-tree struct))
19690 (parents (org-list-parents-alist struct))
19691 (prevs (org-list-prevs-alist struct))
19692 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19693 (org-list-set-checkbox
19694 (org-element-property :begin context) struct
19695 (cond ((equal arg '(16)) "[-]")
19696 ((and (not box) (equal arg '(4))) "[ ]")
19697 ((or (not box) (equal arg '(4))) nil)
19698 ((eq box 'on) "[ ]")
19699 (t "[X]")))
19700 ;; Mimic `org-list-write-struct' but with grabbing
19701 ;; a return value from `org-list-struct-fix-box'.
19702 (org-list-struct-fix-ind struct parents 2)
19703 (org-list-struct-fix-item-end struct)
19704 (org-list-struct-fix-bul struct prevs)
19705 (org-list-struct-fix-ind struct parents)
19706 (let ((block-item
19707 (org-list-struct-fix-box struct parents prevs orderedp)))
19708 (if (and box (equal struct old-struct))
19709 (if (equal arg '(16))
19710 (message "Checkboxes already reset")
19711 (user-error "Cannot toggle this checkbox: %s"
19712 (if (eq box 'on)
19713 "all subitems checked"
19714 "unchecked subitems")))
19715 (org-list-struct-apply-struct struct old-struct)
19716 (org-update-checkbox-count-maybe))
19717 (when block-item
19718 (message "Checkboxes were removed due to empty box at line %d"
19719 (org-current-line block-item))))))
19720 (keyword
19721 (let ((org-inhibit-startup-visibility-stuff t)
19722 (org-startup-align-all-tables nil))
19723 (when (boundp 'org-table-coordinate-overlays)
19724 (mapc 'delete-overlay org-table-coordinate-overlays)
19725 (setq org-table-coordinate-overlays nil))
19726 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19727 (message "Local setup has been refreshed"))
19728 (plain-list
19729 ;; At a plain list, with a double C-u argument, set
19730 ;; checkboxes of each item to "[-]", whereas a single one
19731 ;; will toggle their presence according to the state of the
19732 ;; first item in the list. Without an argument, repair the
19733 ;; list.
19734 (let* ((begin (org-element-property :contents-begin context))
19735 (struct (org-element-property :structure context))
19736 (old-struct (copy-tree struct))
19737 (first-box (save-excursion
19738 (goto-char begin)
19739 (looking-at org-list-full-item-re)
19740 (match-string-no-properties 3)))
19741 (new-box (cond ((equal arg '(16)) "[-]")
19742 ((equal arg '(4)) (unless first-box "[ ]"))
19743 ((equal first-box "[X]") "[ ]")
19744 (t "[X]"))))
19745 (cond
19746 (arg
19747 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19748 (org-list-get-all-items
19749 begin struct (org-list-prevs-alist struct))))
19750 ((and first-box (eq (point) begin))
19751 ;; For convenience, when point is at bol on the first
19752 ;; item of the list and no argument is provided, simply
19753 ;; toggle checkbox of that item, if any.
19754 (org-list-set-checkbox begin struct new-box)))
19755 (org-list-write-struct
19756 struct (org-list-parents-alist struct) old-struct)
19757 (org-update-checkbox-count-maybe)
19758 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19759 ((property-drawer node-property)
19760 (call-interactively 'org-property-action))
19761 ((radio-target target)
19762 (call-interactively 'org-update-radio-target-regexp))
19763 (statistics-cookie
19764 (call-interactively 'org-update-statistics-cookies))
19765 ((table table-cell table-row)
19766 ;; At a table, recalculate every field and align it. Also
19767 ;; send the table if necessary. If the table has
19768 ;; a `table.el' type, just give up. At a table row or
19769 ;; cell, maybe recalculate line but always align table.
19770 (if (eq (org-element-property :type context) 'table.el)
19771 (message "Use C-c ' to edit table.el tables")
19772 (let ((org-enable-table-editor t))
19773 (if (or (eq type 'table)
19774 ;; Check if point is at a TBLFM line.
19775 (and (eq type 'table-row)
19776 (= (point) (org-element-property :end context))))
19777 (save-excursion
19778 (goto-char (org-element-property :contents-begin context))
19779 (org-call-with-arg 'org-table-recalculate (or arg t))
19780 (orgtbl-send-table 'maybe))
19781 (org-table-maybe-eval-formula)
19782 (cond (arg (call-interactively 'org-table-recalculate))
19783 ((org-table-maybe-recalculate-line))
19784 (t (org-table-align)))))))
19785 (timestamp (org-timestamp-change 0 'day))
19786 (otherwise
19787 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19788 (user-error
19789 "C-c C-c can do nothing useful at this location")))))))))
19791 (defun org-mode-restart ()
19792 "Restart Org-mode, to scan again for special lines.
19793 Also updates the keyword regular expressions."
19794 (interactive)
19795 (org-mode)
19796 (message "Org-mode restarted"))
19798 (defun org-kill-note-or-show-branches ()
19799 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19800 (interactive)
19801 (if (not org-finish-function)
19802 (progn
19803 (hide-subtree)
19804 (call-interactively 'show-branches))
19805 (let ((org-note-abort t))
19806 (funcall org-finish-function))))
19808 (defun org-return (&optional indent)
19809 "Goto next table row or insert a newline.
19810 Calls `org-table-next-row' or `newline', depending on context.
19811 See the individual commands for more information."
19812 (interactive)
19813 (let (org-ts-what)
19814 (cond
19815 ((or (bobp) (org-in-src-block-p))
19816 (if indent (newline-and-indent) (newline)))
19817 ((org-at-table-p)
19818 (org-table-justify-field-maybe)
19819 (call-interactively 'org-table-next-row))
19820 ;; when `newline-and-indent' is called within a list, make sure
19821 ;; text moved stays inside the item.
19822 ((and (org-in-item-p) indent)
19823 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19824 (progn
19825 (save-match-data (newline))
19826 (org-indent-line-to (length (match-string 0))))
19827 (let ((ind (org-get-indentation)))
19828 (newline)
19829 (if (org-looking-back org-list-end-re)
19830 (org-indent-line)
19831 (org-indent-line-to ind)))))
19832 ((and org-return-follows-link
19833 (org-at-timestamp-p t)
19834 (not (eq org-ts-what 'after)))
19835 (org-follow-timestamp-link))
19836 ((and org-return-follows-link
19837 (let ((tprop (get-text-property (point) 'face)))
19838 (or (eq tprop 'org-link)
19839 (and (listp tprop) (memq 'org-link tprop)))))
19840 (call-interactively 'org-open-at-point))
19841 ((and (org-at-heading-p)
19842 (looking-at
19843 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19844 (org-show-entry)
19845 (end-of-line 1)
19846 (newline))
19847 (t (if indent (newline-and-indent) (newline))))))
19849 (defun org-return-indent ()
19850 "Goto next table row or insert a newline and indent.
19851 Calls `org-table-next-row' or `newline-and-indent', depending on
19852 context. See the individual commands for more information."
19853 (interactive)
19854 (org-return t))
19856 (defun org-ctrl-c-star ()
19857 "Compute table, or change heading status of lines.
19858 Calls `org-table-recalculate' or `org-toggle-heading',
19859 depending on context."
19860 (interactive)
19861 (cond
19862 ((org-at-table-p)
19863 (call-interactively 'org-table-recalculate))
19865 ;; Convert all lines in region to list items
19866 (call-interactively 'org-toggle-heading))))
19868 (defun org-ctrl-c-minus ()
19869 "Insert separator line in table or modify bullet status of line.
19870 Also turns a plain line or a region of lines into list items.
19871 Calls `org-table-insert-hline', `org-toggle-item', or
19872 `org-cycle-list-bullet', depending on context."
19873 (interactive)
19874 (cond
19875 ((org-at-table-p)
19876 (call-interactively 'org-table-insert-hline))
19877 ((org-region-active-p)
19878 (call-interactively 'org-toggle-item))
19879 ((org-in-item-p)
19880 (call-interactively 'org-cycle-list-bullet))
19882 (call-interactively 'org-toggle-item))))
19884 (defun org-toggle-item (arg)
19885 "Convert headings or normal lines to items, items to normal lines.
19886 If there is no active region, only the current line is considered.
19888 If the first non blank line in the region is an headline, convert
19889 all headlines to items, shifting text accordingly.
19891 If it is an item, convert all items to normal lines.
19893 If it is normal text, change region into an item. With a prefix
19894 argument ARG, change each line in region into an item."
19895 (interactive "P")
19896 (let ((shift-text
19897 (function
19898 ;; Shift text in current section to IND, from point to END.
19899 ;; The function leaves point to END line.
19900 (lambda (ind end)
19901 (let ((min-i 1000) (end (copy-marker end)))
19902 ;; First determine the minimum indentation (MIN-I) of
19903 ;; the text.
19904 (save-excursion
19905 (catch 'exit
19906 (while (< (point) end)
19907 (let ((i (org-get-indentation)))
19908 (cond
19909 ;; Skip blank lines and inline tasks.
19910 ((looking-at "^[ \t]*$"))
19911 ((looking-at org-outline-regexp-bol))
19912 ;; We can't find less than 0 indentation.
19913 ((zerop i) (throw 'exit (setq min-i 0)))
19914 ((< i min-i) (setq min-i i))))
19915 (forward-line))))
19916 ;; Then indent each line so that a line indented to
19917 ;; MIN-I becomes indented to IND. Ignore blank lines
19918 ;; and inline tasks in the process.
19919 (let ((delta (- ind min-i)))
19920 (while (< (point) end)
19921 (unless (or (looking-at "^[ \t]*$")
19922 (looking-at org-outline-regexp-bol))
19923 (org-indent-line-to (+ (org-get-indentation) delta)))
19924 (forward-line)))))))
19925 (skip-blanks
19926 (function
19927 ;; Return beginning of first non-blank line, starting from
19928 ;; line at POS.
19929 (lambda (pos)
19930 (save-excursion
19931 (goto-char pos)
19932 (skip-chars-forward " \r\t\n")
19933 (point-at-bol)))))
19934 beg end)
19935 ;; Determine boundaries of changes.
19936 (if (org-region-active-p)
19937 (setq beg (funcall skip-blanks (region-beginning))
19938 end (copy-marker (region-end)))
19939 (setq beg (funcall skip-blanks (point-at-bol))
19940 end (copy-marker (point-at-eol))))
19941 ;; Depending on the starting line, choose an action on the text
19942 ;; between BEG and END.
19943 (org-with-limited-levels
19944 (save-excursion
19945 (goto-char beg)
19946 (cond
19947 ;; Case 1. Start at an item: de-itemize. Note that it only
19948 ;; happens when a region is active: `org-ctrl-c-minus'
19949 ;; would call `org-cycle-list-bullet' otherwise.
19950 ((org-at-item-p)
19951 (while (< (point) end)
19952 (when (org-at-item-p)
19953 (skip-chars-forward " \t")
19954 (delete-region (point) (match-end 0)))
19955 (forward-line)))
19956 ;; Case 2. Start at an heading: convert to items.
19957 ((org-at-heading-p)
19958 (let* ((bul (org-list-bullet-string "-"))
19959 (bul-len (length bul))
19960 ;; Indentation of the first heading. It should be
19961 ;; relative to the indentation of its parent, if any.
19962 (start-ind (save-excursion
19963 (cond
19964 ((not org-adapt-indentation) 0)
19965 ((not (outline-previous-heading)) 0)
19966 (t (length (match-string 0))))))
19967 ;; Level of first heading. Further headings will be
19968 ;; compared to it to determine hierarchy in the list.
19969 (ref-level (org-reduced-level (org-outline-level))))
19970 (while (< (point) end)
19971 (let* ((level (org-reduced-level (org-outline-level)))
19972 (delta (max 0 (- level ref-level))))
19973 ;; If current headline is less indented than the first
19974 ;; one, set it as reference, in order to preserve
19975 ;; subtrees.
19976 (when (< level ref-level) (setq ref-level level))
19977 (replace-match bul t t)
19978 (org-indent-line-to (+ start-ind (* delta bul-len)))
19979 ;; Ensure all text down to END (or SECTION-END) belongs
19980 ;; to the newly created item.
19981 (let ((section-end (save-excursion
19982 (or (outline-next-heading) (point)))))
19983 (forward-line)
19984 (funcall shift-text
19985 (+ start-ind (* (1+ delta) bul-len))
19986 (min end section-end)))))))
19987 ;; Case 3. Normal line with ARG: turn each non-item line into
19988 ;; an item.
19989 (arg
19990 (while (< (point) end)
19991 (unless (or (org-at-heading-p) (org-at-item-p))
19992 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19993 (replace-match
19994 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19995 (forward-line)))
19996 ;; Case 4. Normal line without ARG: make the first line of
19997 ;; region an item, and shift indentation of others
19998 ;; lines to set them as item's body.
19999 (t (let* ((bul (org-list-bullet-string "-"))
20000 (bul-len (length bul))
20001 (ref-ind (org-get-indentation)))
20002 (skip-chars-forward " \t")
20003 (insert bul)
20004 (forward-line)
20005 (while (< (point) end)
20006 ;; Ensure that lines less indented than first one
20007 ;; still get included in item body.
20008 (funcall shift-text
20009 (+ ref-ind bul-len)
20010 (min end (save-excursion (or (outline-next-heading)
20011 (point)))))
20012 (forward-line)))))))))
20014 (defun org-toggle-heading (&optional nstars)
20015 "Convert headings to normal text, or items or text to headings.
20016 If there is no active region, only the current line is considered.
20018 With a \\[universal-argument] prefix, convert the whole list at
20019 point into heading.
20021 In a region:
20023 - If the first non blank line is an headline, remove the stars
20024 from all headlines in the region.
20026 - If it is a normal line turn each and every normal line (i.e. not an
20027 heading or an item) in the region into a heading.
20029 - If it is a plain list item, turn all plain list items into headings.
20031 When converting a line into a heading, the number of stars is chosen
20032 such that the lines become children of the current entry. However,
20033 when a prefix argument is given, its value determines the number of
20034 stars to add."
20035 (interactive "P")
20036 (let ((skip-blanks
20037 (function
20038 ;; Return beginning of first non-blank line, starting from
20039 ;; line at POS.
20040 (lambda (pos)
20041 (save-excursion
20042 (goto-char pos)
20043 (while (org-at-comment-p) (forward-line))
20044 (skip-chars-forward " \r\t\n")
20045 (point-at-bol)))))
20046 beg end toggled)
20047 ;; Determine boundaries of changes. If a universal prefix has
20048 ;; been given, put the list in a region. If region ends at a bol,
20049 ;; do not consider the last line to be in the region.
20051 (when (and current-prefix-arg (org-at-item-p))
20052 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20053 (org-mark-element))
20055 (if (org-region-active-p)
20056 (setq beg (funcall skip-blanks (region-beginning))
20057 end (copy-marker (save-excursion
20058 (goto-char (region-end))
20059 (if (bolp) (point) (point-at-eol)))))
20060 (setq beg (funcall skip-blanks (point-at-bol))
20061 end (copy-marker (point-at-eol))))
20062 ;; Ensure inline tasks don't count as headings.
20063 (org-with-limited-levels
20064 (save-excursion
20065 (goto-char beg)
20066 (cond
20067 ;; Case 1. Started at an heading: de-star headings.
20068 ((org-at-heading-p)
20069 (while (< (point) end)
20070 (when (org-at-heading-p t)
20071 (looking-at org-outline-regexp) (replace-match "")
20072 (setq toggled t))
20073 (forward-line)))
20074 ;; Case 2. Started at an item: change items into headlines.
20075 ;; One star will be added by `org-list-to-subtree'.
20076 ((org-at-item-p)
20077 (let* ((stars (make-string
20078 (if nstars
20079 ;; subtract the star that will be added again by
20080 ;; `org-list-to-subtree'
20081 (1- (prefix-numeric-value current-prefix-arg))
20082 (or (org-current-level) 0))
20083 ?*))
20084 (add-stars
20085 (cond (nstars "") ; stars from prefix only
20086 ((equal stars "") "") ; before first heading
20087 (org-odd-levels-only "*") ; inside heading, odd
20088 (t "")))) ; inside heading, oddeven
20089 (while (< (point) end)
20090 (when (org-at-item-p)
20091 ;; Pay attention to cases when region ends before list.
20092 (let* ((struct (org-list-struct))
20093 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20094 (save-restriction
20095 (narrow-to-region (point) list-end)
20096 (insert
20097 (org-list-to-subtree
20098 (org-list-parse-list t)
20099 '(:istart (concat stars add-stars (funcall get-stars depth))
20100 :icount (concat stars add-stars (funcall get-stars depth)))))))
20101 (setq toggled t))
20102 (forward-line))))
20103 ;; Case 3. Started at normal text: make every line an heading,
20104 ;; skipping headlines and items.
20105 (t (let* ((stars (make-string
20106 (if nstars
20107 (prefix-numeric-value current-prefix-arg)
20108 (or (org-current-level) 0))
20109 ?*))
20110 (add-stars
20111 (cond (nstars "") ; stars from prefix only
20112 ((equal stars "") "*") ; before first heading
20113 (org-odd-levels-only "**") ; inside heading, odd
20114 (t "*"))) ; inside heading, oddeven
20115 (rpl (concat stars add-stars " ")))
20116 (while (< (point) end)
20117 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20118 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20119 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20120 (forward-line)))))))
20121 (unless toggled (message "Cannot toggle heading from here"))))
20123 (defun org-meta-return (&optional arg)
20124 "Insert a new heading or wrap a region in a table.
20125 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20126 See the individual commands for more information."
20127 (interactive "P")
20128 (cond
20129 ((run-hook-with-args-until-success 'org-metareturn-hook))
20130 ((or (org-at-drawer-p) (org-at-property-p))
20131 (newline-and-indent))
20132 ((org-at-table-p)
20133 (call-interactively 'org-table-wrap-region))
20134 (t (call-interactively 'org-insert-heading))))
20136 ;;; Menu entries
20138 (defsubst org-in-subtree-not-table-p ()
20139 "Are we in a subtree and not in a table?"
20140 (and (not (org-before-first-heading-p))
20141 (not (org-at-table-p))))
20143 ;; Define the Org-mode menus
20144 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20145 '("Tbl"
20146 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20147 ["Next Field" org-cycle (org-at-table-p)]
20148 ["Previous Field" org-shifttab (org-at-table-p)]
20149 ["Next Row" org-return (org-at-table-p)]
20150 "--"
20151 ["Blank Field" org-table-blank-field (org-at-table-p)]
20152 ["Edit Field" org-table-edit-field (org-at-table-p)]
20153 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20154 "--"
20155 ("Column"
20156 ["Move Column Left" org-metaleft (org-at-table-p)]
20157 ["Move Column Right" org-metaright (org-at-table-p)]
20158 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20159 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20160 ("Row"
20161 ["Move Row Up" org-metaup (org-at-table-p)]
20162 ["Move Row Down" org-metadown (org-at-table-p)]
20163 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20164 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20165 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20166 "--"
20167 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20168 ("Rectangle"
20169 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20170 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20171 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20172 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20173 "--"
20174 ("Calculate"
20175 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20176 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20177 ["Edit Formulas" org-edit-special (org-at-table-p)]
20178 "--"
20179 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20180 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20181 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20182 "--"
20183 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20184 "--"
20185 ["Sum Column/Rectangle" org-table-sum
20186 (or (org-at-table-p) (org-region-active-p))]
20187 ["Which Column?" org-table-current-column (org-at-table-p)])
20188 ["Debug Formulas"
20189 org-table-toggle-formula-debugger
20190 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20191 ["Show Col/Row Numbers"
20192 org-table-toggle-coordinate-overlays
20193 :style toggle
20194 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20195 "--"
20196 ["Create" org-table-create (and (not (org-at-table-p))
20197 org-enable-table-editor)]
20198 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20199 ["Import from File" org-table-import (not (org-at-table-p))]
20200 ["Export to File" org-table-export (org-at-table-p)]
20201 "--"
20202 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20204 (easy-menu-define org-org-menu org-mode-map "Org menu"
20205 '("Org"
20206 ("Show/Hide"
20207 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20208 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20209 ["Sparse Tree..." org-sparse-tree t]
20210 ["Reveal Context" org-reveal t]
20211 ["Show All" show-all t]
20212 "--"
20213 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20214 "--"
20215 ["New Heading" org-insert-heading t]
20216 ("Navigate Headings"
20217 ["Up" outline-up-heading t]
20218 ["Next" outline-next-visible-heading t]
20219 ["Previous" outline-previous-visible-heading t]
20220 ["Next Same Level" outline-forward-same-level t]
20221 ["Previous Same Level" outline-backward-same-level t]
20222 "--"
20223 ["Jump" org-goto t])
20224 ("Edit Structure"
20225 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20226 "--"
20227 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20228 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20229 "--"
20230 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20231 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20232 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20233 "--"
20234 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20235 "--"
20236 ["Copy visible text" org-copy-visible t]
20237 "--"
20238 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20239 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20240 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20241 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20242 "--"
20243 ["Sort Region/Children" org-sort t]
20244 "--"
20245 ["Convert to odd levels" org-convert-to-odd-levels t]
20246 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20247 ("Editing"
20248 ["Emphasis..." org-emphasize t]
20249 ["Edit Source Example" org-edit-special t]
20250 "--"
20251 ["Footnote new/jump" org-footnote-action t]
20252 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20253 ("Archive"
20254 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20255 "--"
20256 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20257 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20258 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20260 "--"
20261 ("Hyperlinks"
20262 ["Store Link (Global)" org-store-link t]
20263 ["Find existing link to here" org-occur-link-in-agenda-files t]
20264 ["Insert Link" org-insert-link t]
20265 ["Follow Link" org-open-at-point t]
20266 "--"
20267 ["Next link" org-next-link t]
20268 ["Previous link" org-previous-link t]
20269 "--"
20270 ["Descriptive Links"
20271 org-toggle-link-display
20272 :style radio
20273 :selected org-descriptive-links
20275 ["Literal Links"
20276 org-toggle-link-display
20277 :style radio
20278 :selected (not org-descriptive-links)])
20279 "--"
20280 ("TODO Lists"
20281 ["TODO/DONE/-" org-todo t]
20282 ("Select keyword"
20283 ["Next keyword" org-shiftright (org-at-heading-p)]
20284 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20285 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20286 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20287 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20288 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20289 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20290 "--"
20291 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20292 :selected org-enforce-todo-dependencies :style toggle :active t]
20293 "Settings for tree at point"
20294 ["Do Children sequentially" org-toggle-ordered-property :style radio
20295 :selected (org-entry-get nil "ORDERED")
20296 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20297 ["Do Children parallel" org-toggle-ordered-property :style radio
20298 :selected (not (org-entry-get nil "ORDERED"))
20299 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20300 "--"
20301 ["Set Priority" org-priority t]
20302 ["Priority Up" org-shiftup t]
20303 ["Priority Down" org-shiftdown t]
20304 "--"
20305 ["Get news from all feeds" org-feed-update-all t]
20306 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20307 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20308 ("TAGS and Properties"
20309 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20310 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20311 "--"
20312 ["Set property" org-set-property (not (org-before-first-heading-p))]
20313 ["Column view of properties" org-columns t]
20314 ["Insert Column View DBlock" org-insert-columns-dblock t])
20315 ("Dates and Scheduling"
20316 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20317 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20318 ("Change Date"
20319 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20320 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20321 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20322 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20323 ["Compute Time Range" org-evaluate-time-range t]
20324 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20325 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20326 "--"
20327 ["Custom time format" org-toggle-time-stamp-overlays
20328 :style radio :selected org-display-custom-times]
20329 "--"
20330 ["Goto Calendar" org-goto-calendar t]
20331 ["Date from Calendar" org-date-from-calendar t]
20332 "--"
20333 ["Start/Restart Timer" org-timer-start t]
20334 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20335 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20336 ["Insert Timer String" org-timer t]
20337 ["Insert Timer Item" org-timer-item t])
20338 ("Logging work"
20339 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20340 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20341 ["Clock out" org-clock-out t]
20342 ["Clock cancel" org-clock-cancel t]
20343 "--"
20344 ["Mark as default task" org-clock-mark-default-task t]
20345 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20346 ["Goto running clock" org-clock-goto t]
20347 "--"
20348 ["Display times" org-clock-display t]
20349 ["Create clock table" org-clock-report t]
20350 "--"
20351 ["Record DONE time"
20352 (progn (setq org-log-done (not org-log-done))
20353 (message "Switching to %s will %s record a timestamp"
20354 (car org-done-keywords)
20355 (if org-log-done "automatically" "not")))
20356 :style toggle :selected org-log-done])
20357 "--"
20358 ["Agenda Command..." org-agenda t]
20359 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20360 ("File List for Agenda")
20361 ("Special views current file"
20362 ["TODO Tree" org-show-todo-tree t]
20363 ["Check Deadlines" org-check-deadlines t]
20364 ["Timeline" org-timeline t]
20365 ["Tags/Property tree" org-match-sparse-tree t])
20366 "--"
20367 ["Export/Publish..." org-export-dispatch t]
20368 ("LaTeX"
20369 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20370 :selected org-cdlatex-mode]
20371 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20372 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20373 ["Modify math symbol" org-cdlatex-math-modify
20374 (org-inside-LaTeX-fragment-p)]
20375 ["Insert citation" org-reftex-citation t]
20376 "--"
20377 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20378 "--"
20379 ("MobileOrg"
20380 ["Push Files and Views" org-mobile-push t]
20381 ["Get Captured and Flagged" org-mobile-pull t]
20382 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20383 "--"
20384 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20385 "--"
20386 ("Documentation"
20387 ["Show Version" org-version t]
20388 ["Info Documentation" org-info t])
20389 ("Customize"
20390 ["Browse Org Group" org-customize t]
20391 "--"
20392 ["Expand This Menu" org-create-customize-menu
20393 (fboundp 'customize-menu-create)])
20394 ["Send bug report" org-submit-bug-report t]
20395 "--"
20396 ("Refresh/Reload"
20397 ["Refresh setup current buffer" org-mode-restart t]
20398 ["Reload Org (after update)" org-reload t]
20399 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20402 (defun org-info (&optional node)
20403 "Read documentation for Org-mode in the info system.
20404 With optional NODE, go directly to that node."
20405 (interactive)
20406 (info (format "(org)%s" (or node ""))))
20408 ;;;###autoload
20409 (defun org-submit-bug-report ()
20410 "Submit a bug report on Org-mode via mail.
20412 Don't hesitate to report any problems or inaccurate documentation.
20414 If you don't have setup sending mail from (X)Emacs, please copy the
20415 output buffer into your mail program, as it gives us important
20416 information about your Org-mode version and configuration."
20417 (interactive)
20418 (require 'reporter)
20419 (org-load-modules-maybe)
20420 (org-require-autoloaded-modules)
20421 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20422 (reporter-submit-bug-report
20423 "emacs-orgmode@gnu.org"
20424 (org-version nil 'full)
20425 (let (list)
20426 (save-window-excursion
20427 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20428 (delete-other-windows)
20429 (erase-buffer)
20430 (insert "You are about to submit a bug report to the Org-mode mailing list.
20432 We would like to add your full Org-mode and Outline configuration to the
20433 bug report. This greatly simplifies the work of the maintainer and
20434 other experts on the mailing list.
20436 HOWEVER, some variables you have customized may contain private
20437 information. The names of customers, colleagues, or friends, might
20438 appear in the form of file names, tags, todo states, or search strings.
20439 If you answer yes to the prompt, you might want to check and remove
20440 such private information before sending the email.")
20441 (add-text-properties (point-min) (point-max) '(face org-warning))
20442 (when (yes-or-no-p "Include your Org-mode configuration ")
20443 (mapatoms
20444 (lambda (v)
20445 (and (boundp v)
20446 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20447 (or (and (symbol-value v)
20448 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20449 (and
20450 (get v 'custom-type) (get v 'standard-value)
20451 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20452 (push v list)))))
20453 (kill-buffer (get-buffer "*Warn about privacy*"))
20454 list))
20455 nil nil
20456 "Remember to cover the basics, that is, what you expected to happen and
20457 what in fact did happen. You don't know how to make a good report? See
20459 http://orgmode.org/manual/Feedback.html#Feedback
20461 Your bug report will be posted to the Org-mode mailing list.
20462 ------------------------------------------------------------------------")
20463 (save-excursion
20464 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20465 (replace-match "\\1Bug: \\3 [\\2]")))))
20468 (defun org-install-agenda-files-menu ()
20469 (let ((bl (buffer-list)))
20470 (save-excursion
20471 (while bl
20472 (set-buffer (pop bl))
20473 (if (derived-mode-p 'org-mode) (setq bl nil)))
20474 (when (derived-mode-p 'org-mode)
20475 (easy-menu-change
20476 '("Org") "File List for Agenda"
20477 (append
20478 (list
20479 ["Edit File List" (org-edit-agenda-file-list) t]
20480 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20481 ["Remove Current File from List" org-remove-file t]
20482 ["Cycle through agenda files" org-cycle-agenda-files t]
20483 ["Occur in all agenda files" org-occur-in-agenda-files t]
20484 "--")
20485 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20487 ;;;; Documentation
20489 (defun org-require-autoloaded-modules ()
20490 (interactive)
20491 (mapc 'require
20492 '(org-agenda org-archive org-attach org-clock org-colview org-id
20493 org-remember org-table org-timer)))
20495 ;;;###autoload
20496 (defun org-reload (&optional uncompiled)
20497 "Reload all org lisp files.
20498 With prefix arg UNCOMPILED, load the uncompiled versions."
20499 (interactive "P")
20500 (require 'loadhist)
20501 (let* ((org-dir (org-find-library-dir "org"))
20502 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20503 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20504 (remove-re (mapconcat 'identity
20505 (mapcar (lambda (f) (concat "^" f "$"))
20506 (list (if (featurep 'xemacs)
20507 "org-colview"
20508 "org-colview-xemacs")
20509 "org" "org-loaddefs" "org-version"))
20510 "\\|"))
20511 (feats (delete-dups
20512 (mapcar 'file-name-sans-extension
20513 (mapcar 'file-name-nondirectory
20514 (delq nil
20515 (mapcar 'feature-file
20516 features))))))
20517 (lfeat (append
20518 (sort
20519 (setq feats
20520 (delq nil (mapcar
20521 (lambda (f)
20522 (if (and (string-match feature-re f)
20523 (not (string-match remove-re f)))
20524 f nil))
20525 feats)))
20526 'string-lessp)
20527 (list "org-version" "org")))
20528 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20529 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20530 load-uncore load-misses)
20531 (setq load-misses
20532 (delq 't
20533 (mapcar (lambda (f)
20534 (or (org-load-noerror-mustsuffix (concat org-dir f))
20535 (and (string= org-dir contrib-dir)
20536 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20537 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20538 (add-to-list 'load-uncore f 'append)
20541 lfeat)))
20542 (if load-uncore
20543 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20544 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20545 (if load-misses
20546 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20547 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20548 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20550 ;;;###autoload
20551 (defun org-customize ()
20552 "Call the customize function with org as argument."
20553 (interactive)
20554 (org-load-modules-maybe)
20555 (org-require-autoloaded-modules)
20556 (customize-browse 'org))
20558 (defun org-create-customize-menu ()
20559 "Create a full customization menu for Org-mode, insert it into the menu."
20560 (interactive)
20561 (org-load-modules-maybe)
20562 (org-require-autoloaded-modules)
20563 (if (fboundp 'customize-menu-create)
20564 (progn
20565 (easy-menu-change
20566 '("Org") "Customize"
20567 `(["Browse Org group" org-customize t]
20568 "--"
20569 ,(customize-menu-create 'org)
20570 ["Set" Custom-set t]
20571 ["Save" Custom-save t]
20572 ["Reset to Current" Custom-reset-current t]
20573 ["Reset to Saved" Custom-reset-saved t]
20574 ["Reset to Standard Settings" Custom-reset-standard t]))
20575 (message "\"Org\"-menu now contains full customization menu"))
20576 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20578 ;;;; Miscellaneous stuff
20580 ;;; Generally useful functions
20582 (defun org-get-at-bol (property)
20583 "Get text property PROPERTY at beginning of line."
20584 (get-text-property (point-at-bol) property))
20586 (defun org-find-text-property-in-string (prop s)
20587 "Return the first non-nil value of property PROP in string S."
20588 (or (get-text-property 0 prop s)
20589 (get-text-property (or (next-single-property-change 0 prop s) 0)
20590 prop s)))
20592 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20593 "Display the given MESSAGE as a warning."
20594 (if (fboundp 'display-warning)
20595 (display-warning 'org message
20596 (if (featurep 'xemacs) 'warning :warning))
20597 (let ((buf (get-buffer-create "*Org warnings*")))
20598 (with-current-buffer buf
20599 (goto-char (point-max))
20600 (insert "Warning (Org): " message)
20601 (unless (bolp)
20602 (newline)))
20603 (display-buffer buf)
20604 (sit-for 0))))
20606 (defun org-eval (form)
20607 "Eval FORM and return result."
20608 (condition-case error
20609 (eval form)
20610 (error (format "%%![Error: %s]" error))))
20612 (defun org-in-clocktable-p ()
20613 "Check if the cursor is in a clocktable."
20614 (let ((pos (point)) start)
20615 (save-excursion
20616 (end-of-line 1)
20617 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20618 (setq start (match-beginning 0))
20619 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20620 (>= (match-end 0) pos)
20621 start))))
20623 (defun org-in-commented-line ()
20624 "Is point in a line starting with `#'?"
20625 (equal (char-after (point-at-bol)) ?#))
20627 (defun org-in-indented-comment-line ()
20628 "Is point in a line starting with `#' after some white space?"
20629 (save-excursion
20630 (save-match-data
20631 (goto-char (point-at-bol))
20632 (looking-at "[ \t]*#"))))
20634 (defun org-in-verbatim-emphasis ()
20635 (save-match-data
20636 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20638 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20639 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20640 (if (and marker (marker-buffer marker)
20641 (buffer-live-p (marker-buffer marker)))
20642 (progn
20643 (org-pop-to-buffer-same-window (marker-buffer marker))
20644 (if (or (> marker (point-max)) (< marker (point-min)))
20645 (widen))
20646 (goto-char marker)
20647 (org-show-context 'org-goto))
20648 (if bookmark
20649 (bookmark-jump bookmark)
20650 (error "Cannot find location"))))
20652 (defun org-quote-csv-field (s)
20653 "Quote field for inclusion in CSV material."
20654 (if (string-match "[\",]" s)
20655 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20658 (defun org-force-self-insert (N)
20659 "Needed to enforce self-insert under remapping."
20660 (interactive "p")
20661 (self-insert-command N))
20663 (defun org-string-width (s)
20664 "Compute width of string, ignoring invisible characters.
20665 This ignores character with invisibility property `org-link', and also
20666 characters with property `org-cwidth', because these will become invisible
20667 upon the next fontification round."
20668 (let (b l)
20669 (when (or (eq t buffer-invisibility-spec)
20670 (assq 'org-link buffer-invisibility-spec))
20671 (while (setq b (text-property-any 0 (length s)
20672 'invisible 'org-link s))
20673 (setq s (concat (substring s 0 b)
20674 (substring s (or (next-single-property-change
20675 b 'invisible s) (length s)))))))
20676 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20677 (setq s (concat (substring s 0 b)
20678 (substring s (or (next-single-property-change
20679 b 'org-cwidth s) (length s))))))
20680 (setq l (string-width s) b -1)
20681 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20682 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20685 (defun org-shorten-string (s maxlength)
20686 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20687 If the string is shorter or has length MAXLENGTH, just return the
20688 original string. If it is longer, the functions finds a space in the
20689 string, breaks this string off at that locations and adds three dots
20690 as ellipsis. Including the ellipsis, the string will not be longer
20691 than MAXLENGTH. If finding a good breaking point in the string does
20692 not work, the string is just chopped off in the middle of a word
20693 if necessary."
20694 (if (<= (length s) maxlength)
20696 (let* ((n (max (- maxlength 4) 1))
20697 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20698 (if (string-match re s)
20699 (concat (match-string 1 s) "...")
20700 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20702 (defun org-get-indentation (&optional line)
20703 "Get the indentation of the current line, interpreting tabs.
20704 When LINE is given, assume it represents a line and compute its indentation."
20705 (if line
20706 (if (string-match "^ *" (org-remove-tabs line))
20707 (match-end 0))
20708 (save-excursion
20709 (beginning-of-line 1)
20710 (skip-chars-forward " \t")
20711 (current-column))))
20713 (defun org-get-string-indentation (s)
20714 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20715 (let ((n -1) (i 0) (w tab-width) c)
20716 (catch 'exit
20717 (while (< (setq n (1+ n)) (length s))
20718 (setq c (aref s n))
20719 (cond ((= c ?\ ) (setq i (1+ i)))
20720 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20721 (t (throw 'exit t)))))
20724 (defun org-remove-tabs (s &optional width)
20725 "Replace tabulators in S with spaces.
20726 Assumes that s is a single line, starting in column 0."
20727 (setq width (or width tab-width))
20728 (while (string-match "\t" s)
20729 (setq s (replace-match
20730 (make-string
20731 (- (* width (/ (+ (match-beginning 0) width) width))
20732 (match-beginning 0)) ?\ )
20733 t t s)))
20736 (defun org-fix-indentation (line ind)
20737 "Fix indentation in LINE.
20738 IND is a cons cell with target and minimum indentation.
20739 If the current indentation in LINE is smaller than the minimum,
20740 leave it alone. If it is larger than ind, set it to the target."
20741 (let* ((l (org-remove-tabs line))
20742 (i (org-get-indentation l))
20743 (i1 (car ind)) (i2 (cdr ind)))
20744 (if (>= i i2) (setq l (substring line i2)))
20745 (if (> i1 0)
20746 (concat (make-string i1 ?\ ) l)
20747 l)))
20749 (defun org-remove-indentation (code &optional n)
20750 "Remove the maximum common indentation from the lines in CODE.
20751 N may optionally be the number of spaces to remove."
20752 (with-temp-buffer
20753 (insert code)
20754 (org-do-remove-indentation n)
20755 (buffer-string)))
20757 (defun org-do-remove-indentation (&optional n)
20758 "Remove the maximum common indentation from the buffer."
20759 (untabify (point-min) (point-max))
20760 (let ((min 10000) re)
20761 (if n
20762 (setq min n)
20763 (goto-char (point-min))
20764 (while (re-search-forward "^ *[^ \n]" nil t)
20765 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20766 (unless (or (= min 0) (= min 10000))
20767 (setq re (format "^ \\{%d\\}" min))
20768 (goto-char (point-min))
20769 (while (re-search-forward re nil t)
20770 (replace-match "")
20771 (end-of-line 1))
20772 min)))
20774 (defun org-fill-template (template alist)
20775 "Find each %key of ALIST in TEMPLATE and replace it."
20776 (let ((case-fold-search nil)
20777 entry key value)
20778 (setq alist (sort (copy-sequence alist)
20779 (lambda (a b) (< (length (car a)) (length (car b))))))
20780 (while (setq entry (pop alist))
20781 (setq template
20782 (replace-regexp-in-string
20783 (concat "%" (regexp-quote (car entry)))
20784 (or (cdr entry) "") template t t)))
20785 template))
20787 (defun org-base-buffer (buffer)
20788 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20789 (if (not buffer)
20790 buffer
20791 (or (buffer-base-buffer buffer)
20792 buffer)))
20794 (defun org-trim (s)
20795 "Remove whitespace at beginning and end of string."
20796 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20797 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20800 (defun org-wrap (string &optional width lines)
20801 "Wrap string to either a number of lines, or a width in characters.
20802 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20803 that costs. If there is a word longer than WIDTH, the text is actually
20804 wrapped to the length of that word.
20805 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20806 many lines, whatever width that takes.
20807 The return value is a list of lines, without newlines at the end."
20808 (let* ((words (org-split-string string "[ \t\n]+"))
20809 (maxword (apply 'max (mapcar 'org-string-width words)))
20810 w ll)
20811 (cond (width
20812 (org-do-wrap words (max maxword width)))
20813 (lines
20814 (setq w maxword)
20815 (setq ll (org-do-wrap words maxword))
20816 (if (<= (length ll) lines)
20818 (setq ll words)
20819 (while (> (length ll) lines)
20820 (setq w (1+ w))
20821 (setq ll (org-do-wrap words w)))
20822 ll))
20823 (t (error "Cannot wrap this")))))
20825 (defun org-do-wrap (words width)
20826 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20827 (let (lines line)
20828 (while words
20829 (setq line (pop words))
20830 (while (and words (< (+ (length line) (length (car words))) width))
20831 (setq line (concat line " " (pop words))))
20832 (setq lines (push line lines)))
20833 (nreverse lines)))
20835 (defun org-split-string (string &optional separators)
20836 "Splits STRING into substrings at SEPARATORS.
20837 No empty strings are returned if there are matches at the beginning
20838 and end of string."
20839 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20840 (start 0)
20841 notfirst
20842 (list nil))
20843 (while (and (string-match rexp string
20844 (if (and notfirst
20845 (= start (match-beginning 0))
20846 (< start (length string)))
20847 (1+ start) start))
20848 (< (match-beginning 0) (length string)))
20849 (setq notfirst t)
20850 (or (eq (match-beginning 0) 0)
20851 (and (eq (match-beginning 0) (match-end 0))
20852 (eq (match-beginning 0) start))
20853 (setq list
20854 (cons (substring string start (match-beginning 0))
20855 list)))
20856 (setq start (match-end 0)))
20857 (or (eq start (length string))
20858 (setq list
20859 (cons (substring string start)
20860 list)))
20861 (nreverse list)))
20863 (defun org-quote-vert (s)
20864 "Replace \"|\" with \"\\vert\"."
20865 (while (string-match "|" s)
20866 (setq s (replace-match "\\vert" t t s)))
20869 (defun org-uuidgen-p (s)
20870 "Is S an ID created by UUIDGEN?"
20871 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20873 (defun org-in-src-block-p (&optional inside)
20874 "Whether point is in a code source block.
20875 When INSIDE is non-nil, don't consider we are within a src block
20876 when point is at #+BEGIN_SRC or #+END_SRC."
20877 (let ((case-fold-search t) ov)
20878 (or (and (setq ov (overlays-at (point)))
20879 (memq 'org-block-background
20880 (overlay-properties (car ov))))
20881 (and (not inside)
20882 (save-match-data
20883 (save-excursion
20884 (beginning-of-line)
20885 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20887 (defun org-context ()
20888 "Return a list of contexts of the current cursor position.
20889 If several contexts apply, all are returned.
20890 Each context entry is a list with a symbol naming the context, and
20891 two positions indicating start and end of the context. Possible
20892 contexts are:
20894 :headline anywhere in a headline
20895 :headline-stars on the leading stars in a headline
20896 :todo-keyword on a TODO keyword (including DONE) in a headline
20897 :tags on the TAGS in a headline
20898 :priority on the priority cookie in a headline
20899 :item on the first line of a plain list item
20900 :item-bullet on the bullet/number of a plain list item
20901 :checkbox on the checkbox in a plain list item
20902 :table in an org-mode table
20903 :table-special on a special filed in a table
20904 :table-table in a table.el table
20905 :clocktable in a clocktable
20906 :src-block in a source block
20907 :link on a hyperlink
20908 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20909 :target on a <<target>>
20910 :radio-target on a <<<radio-target>>>
20911 :latex-fragment on a LaTeX fragment
20912 :latex-preview on a LaTeX fragment with overlaid preview image
20914 This function expects the position to be visible because it uses font-lock
20915 faces as a help to recognize the following contexts: :table-special, :link,
20916 and :keyword."
20917 (let* ((f (get-text-property (point) 'face))
20918 (faces (if (listp f) f (list f)))
20919 (case-fold-search t)
20920 (p (point)) clist o)
20921 ;; First the large context
20922 (cond
20923 ((org-at-heading-p t)
20924 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20925 (when (progn
20926 (beginning-of-line 1)
20927 (looking-at org-todo-line-tags-regexp))
20928 (push (org-point-in-group p 1 :headline-stars) clist)
20929 (push (org-point-in-group p 2 :todo-keyword) clist)
20930 (push (org-point-in-group p 4 :tags) clist))
20931 (goto-char p)
20932 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20933 (if (looking-at "\\[#[A-Z0-9]\\]")
20934 (push (org-point-in-group p 0 :priority) clist)))
20936 ((org-at-item-p)
20937 (push (org-point-in-group p 2 :item-bullet) clist)
20938 (push (list :item (point-at-bol)
20939 (save-excursion (org-end-of-item) (point)))
20940 clist)
20941 (and (org-at-item-checkbox-p)
20942 (push (org-point-in-group p 0 :checkbox) clist)))
20944 ((org-at-table-p)
20945 (push (list :table (org-table-begin) (org-table-end)) clist)
20946 (if (memq 'org-formula faces)
20947 (push (list :table-special
20948 (previous-single-property-change p 'face)
20949 (next-single-property-change p 'face)) clist)))
20950 ((org-at-table-p 'any)
20951 (push (list :table-table) clist)))
20952 (goto-char p)
20954 (let ((case-fold-search t))
20955 ;; New the "medium" contexts: clocktables, source blocks
20956 (cond ((org-in-clocktable-p)
20957 (push (list :clocktable
20958 (and (or (looking-at "#\\+BEGIN: clocktable")
20959 (search-backward "#+BEGIN: clocktable" nil t))
20960 (match-beginning 0))
20961 (and (re-search-forward "#\\+END:?" nil t)
20962 (match-end 0))) clist))
20963 ((org-in-src-block-p)
20964 (push (list :src-block
20965 (and (or (looking-at "#\\+BEGIN_SRC")
20966 (search-backward "#+BEGIN_SRC" nil t))
20967 (match-beginning 0))
20968 (and (search-forward "#+END_SRC" nil t)
20969 (match-beginning 0))) clist))))
20970 (goto-char p)
20972 ;; Now the small context
20973 (cond
20974 ((org-at-timestamp-p)
20975 (push (org-point-in-group p 0 :timestamp) clist))
20976 ((memq 'org-link faces)
20977 (push (list :link
20978 (previous-single-property-change p 'face)
20979 (next-single-property-change p 'face)) clist))
20980 ((memq 'org-special-keyword faces)
20981 (push (list :keyword
20982 (previous-single-property-change p 'face)
20983 (next-single-property-change p 'face)) clist))
20984 ((org-at-target-p)
20985 (push (org-point-in-group p 0 :target) clist)
20986 (goto-char (1- (match-beginning 0)))
20987 (if (looking-at org-radio-target-regexp)
20988 (push (org-point-in-group p 0 :radio-target) clist))
20989 (goto-char p))
20990 ((setq o (car (delq nil
20991 (mapcar
20992 (lambda (x)
20993 (if (memq x org-latex-fragment-image-overlays) x))
20994 (overlays-at (point))))))
20995 (push (list :latex-fragment
20996 (overlay-start o) (overlay-end o)) clist)
20997 (push (list :latex-preview
20998 (overlay-start o) (overlay-end o)) clist))
20999 ((org-inside-LaTeX-fragment-p)
21000 ;; FIXME: positions wrong.
21001 (push (list :latex-fragment (point) (point)) clist)))
21003 (setq clist (nreverse (delq nil clist)))
21004 clist))
21006 ;; FIXME: Compare with at-regexp-p Do we need both?
21007 (defun org-in-regexp (re &optional nlines visually)
21008 "Check if point is inside a match of regexp.
21009 Normally only the current line is checked, but you can include NLINES extra
21010 lines both before and after point into the search.
21011 If VISUALLY is set, require that the cursor is not after the match but
21012 really on, so that the block visually is on the match."
21013 (catch 'exit
21014 (let ((pos (point))
21015 (eol (point-at-eol (+ 1 (or nlines 0))))
21016 (inc (if visually 1 0)))
21017 (save-excursion
21018 (beginning-of-line (- 1 (or nlines 0)))
21019 (while (re-search-forward re eol t)
21020 (if (and (<= (match-beginning 0) pos)
21021 (>= (+ inc (match-end 0)) pos))
21022 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21024 (defun org-at-regexp-p (regexp)
21025 "Is point inside a match of REGEXP in the current line?"
21026 (catch 'exit
21027 (save-excursion
21028 (let ((pos (point)) (end (point-at-eol)))
21029 (beginning-of-line 1)
21030 (while (re-search-forward regexp end t)
21031 (if (and (<= (match-beginning 0) pos)
21032 (>= (match-end 0) pos))
21033 (throw 'exit t)))
21034 nil))))
21036 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21037 "Non-nil when point is between matches of START-RE and END-RE.
21039 Also return a non-nil value when point is on one of the matches.
21041 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21042 buffer positions. Default values are the positions of headlines
21043 surrounding the point.
21045 The functions returns a cons cell whose car (resp. cdr) is the
21046 position before START-RE (resp. after END-RE)."
21047 (save-match-data
21048 (let ((pos (point))
21049 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21050 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21051 beg end)
21052 (save-excursion
21053 ;; Point is on a block when on START-RE or if START-RE can be
21054 ;; found before it...
21055 (and (or (org-at-regexp-p start-re)
21056 (re-search-backward start-re limit-up t))
21057 (setq beg (match-beginning 0))
21058 ;; ... and END-RE after it...
21059 (goto-char (match-end 0))
21060 (re-search-forward end-re limit-down t)
21061 (> (setq end (match-end 0)) pos)
21062 ;; ... without another START-RE in-between.
21063 (goto-char (match-beginning 0))
21064 (not (re-search-backward start-re (1+ beg) t))
21065 ;; Return value.
21066 (cons beg end))))))
21068 (defun org-in-block-p (names)
21069 "Non-nil when point belongs to a block whose name belongs to NAMES.
21071 NAMES is a list of strings containing names of blocks.
21073 Return first block name matched, or nil. Beware that in case of
21074 nested blocks, the returned name may not belong to the closest
21075 block from point."
21076 (save-match-data
21077 (catch 'exit
21078 (let ((case-fold-search t)
21079 (lim-up (save-excursion (outline-previous-heading)))
21080 (lim-down (save-excursion (outline-next-heading))))
21081 (mapc (lambda (name)
21082 (let ((n (regexp-quote name)))
21083 (when (org-between-regexps-p
21084 (concat "^[ \t]*#\\+begin_" n)
21085 (concat "^[ \t]*#\\+end_" n)
21086 lim-up lim-down)
21087 (throw 'exit n))))
21088 names))
21089 nil)))
21091 (defun org-occur-in-agenda-files (regexp &optional nlines)
21092 "Call `multi-occur' with buffers for all agenda files."
21093 (interactive "sOrg-files matching: \np")
21094 (let* ((files (org-agenda-files))
21095 (tnames (mapcar 'file-truename files))
21096 (extra org-agenda-text-search-extra-files)
21098 (when (eq (car extra) 'agenda-archives)
21099 (setq extra (cdr extra))
21100 (setq files (org-add-archive-files files)))
21101 (while (setq f (pop extra))
21102 (unless (member (file-truename f) tnames)
21103 (add-to-list 'files f 'append)
21104 (add-to-list 'tnames (file-truename f) 'append)))
21105 (multi-occur
21106 (mapcar (lambda (x)
21107 (with-current-buffer
21108 (or (get-file-buffer x) (find-file-noselect x))
21109 (widen)
21110 (current-buffer)))
21111 files)
21112 regexp)))
21114 (if (boundp 'occur-mode-find-occurrence-hook)
21115 ;; Emacs 23
21116 (add-hook 'occur-mode-find-occurrence-hook
21117 (lambda ()
21118 (when (derived-mode-p 'org-mode)
21119 (org-reveal))))
21120 ;; Emacs 22
21121 (defadvice occur-mode-goto-occurrence
21122 (after org-occur-reveal activate)
21123 (and (derived-mode-p 'org-mode) (org-reveal)))
21124 (defadvice occur-mode-goto-occurrence-other-window
21125 (after org-occur-reveal activate)
21126 (and (derived-mode-p 'org-mode) (org-reveal)))
21127 (defadvice occur-mode-display-occurrence
21128 (after org-occur-reveal activate)
21129 (when (derived-mode-p 'org-mode)
21130 (let ((pos (occur-mode-find-occurrence)))
21131 (with-current-buffer (marker-buffer pos)
21132 (save-excursion
21133 (goto-char pos)
21134 (org-reveal)))))))
21136 (defun org-occur-link-in-agenda-files ()
21137 "Create a link and search for it in the agendas.
21138 The link is not stored in `org-stored-links', it is just created
21139 for the search purpose."
21140 (interactive)
21141 (let ((link (condition-case nil
21142 (org-store-link nil)
21143 (error "Unable to create a link to here"))))
21144 (org-occur-in-agenda-files (regexp-quote link))))
21146 (defun org-reverse-string (string)
21147 "Return the reverse of STRING."
21148 (apply 'string (reverse (string-to-list string))))
21150 (defun org-uniquify (list)
21151 "Remove duplicate elements from LIST."
21152 (let (res)
21153 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21154 res))
21156 (defun org-delete-all (elts list)
21157 "Remove all elements in ELTS from LIST."
21158 (while elts
21159 (setq list (delete (pop elts) list)))
21160 list)
21162 (defun org-count (cl-item cl-seq)
21163 "Count the number of occurrences of ITEM in SEQ.
21164 Taken from `count' in cl-seq.el with all keyword arguments removed."
21165 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21166 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21167 (while (< cl-start cl-end)
21168 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21169 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21170 (setq cl-start (1+ cl-start)))
21171 cl-count))
21173 (defun org-remove-if (predicate seq)
21174 "Remove everything from SEQ that fulfills PREDICATE."
21175 (let (res e)
21176 (while seq
21177 (setq e (pop seq))
21178 (if (not (funcall predicate e)) (push e res)))
21179 (nreverse res)))
21181 (defun org-remove-if-not (predicate seq)
21182 "Remove everything from SEQ that does not fulfill PREDICATE."
21183 (let (res e)
21184 (while seq
21185 (setq e (pop seq))
21186 (if (funcall predicate e) (push e res)))
21187 (nreverse res)))
21189 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21190 "Reduce two-argument FUNCTION across SEQ.
21191 Taken from `reduce' in cl-seq.el with all keyword arguments but
21192 \":initial-value\" removed."
21193 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21194 (cadr (memq :initial-value cl-keys)))
21195 (cl-seq (pop cl-seq))
21196 (t (funcall cl-func)))))
21197 (while cl-seq
21198 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21199 cl-accum))
21201 (defun org-back-over-empty-lines ()
21202 "Move backwards over whitespace, to the beginning of the first empty line.
21203 Returns the number of empty lines passed."
21204 (let ((pos (point)))
21205 (if (cdr (assoc 'heading org-blank-before-new-entry))
21206 (skip-chars-backward " \t\n\r")
21207 (unless (eobp)
21208 (forward-line -1)))
21209 (beginning-of-line 2)
21210 (goto-char (min (point) pos))
21211 (count-lines (point) pos)))
21213 (defun org-skip-whitespace ()
21214 (skip-chars-forward " \t\n\r"))
21216 (defun org-point-in-group (point group &optional context)
21217 "Check if POINT is in match-group GROUP.
21218 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21219 match. If the match group does not exist or point is not inside it,
21220 return nil."
21221 (and (match-beginning group)
21222 (>= point (match-beginning group))
21223 (<= point (match-end group))
21224 (if context
21225 (list context (match-beginning group) (match-end group))
21226 t)))
21228 (defun org-switch-to-buffer-other-window (&rest args)
21229 "Switch to buffer in a second window on the current frame.
21230 In particular, do not allow pop-up frames.
21231 Returns the newly created buffer."
21232 (org-no-popups
21233 (apply 'switch-to-buffer-other-window args)))
21235 (defun org-combine-plists (&rest plists)
21236 "Create a single property list from all plists in PLISTS.
21237 The process starts by copying the first list, and then setting properties
21238 from the other lists. Settings in the last list are the most significant
21239 ones and overrule settings in the other lists."
21240 (let ((rtn (copy-sequence (pop plists)))
21241 p v ls)
21242 (while plists
21243 (setq ls (pop plists))
21244 (while ls
21245 (setq p (pop ls) v (pop ls))
21246 (setq rtn (plist-put rtn p v))))
21247 rtn))
21249 (defun org-replace-escapes (string table)
21250 "Replace %-escapes in STRING with values in TABLE.
21251 TABLE is an association list with keys like \"%a\" and string values.
21252 The sequences in STRING may contain normal field width and padding information,
21253 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21254 so values can contain further %-escapes if they are define later in TABLE."
21255 (let ((tbl (copy-alist table))
21256 (case-fold-search nil)
21257 (pchg 0)
21258 e re rpl)
21259 (while (setq e (pop tbl))
21260 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21261 (when (and (cdr e) (string-match re (cdr e)))
21262 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21263 (safe "SREF"))
21264 (add-text-properties 0 3 (list 'sref sref) safe)
21265 (setcdr e (replace-match safe t t (cdr e)))))
21266 (while (string-match re string)
21267 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21268 (cdr e)))
21269 (setq string (replace-match rpl t t string))))
21270 (while (setq pchg (next-property-change pchg string))
21271 (let ((sref (get-text-property pchg 'sref string)))
21272 (when (and sref (string-match "SREF" string pchg))
21273 (setq string (replace-match sref t t string)))))
21274 string))
21276 (defun org-sublist (list start end)
21277 "Return a section of LIST, from START to END.
21278 Counting starts at 1."
21279 (let (rtn (c start))
21280 (setq list (nthcdr (1- start) list))
21281 (while (and list (<= c end))
21282 (push (pop list) rtn)
21283 (setq c (1+ c)))
21284 (nreverse rtn)))
21286 (defun org-find-base-buffer-visiting (file)
21287 "Like `find-buffer-visiting' but always return the base buffer and
21288 not an indirect buffer."
21289 (let ((buf (or (get-file-buffer file)
21290 (find-buffer-visiting file))))
21291 (if buf
21292 (or (buffer-base-buffer buf) buf)
21293 nil)))
21295 (defun org-image-file-name-regexp (&optional extensions)
21296 "Return regexp matching the file names of images.
21297 If EXTENSIONS is given, only match these."
21298 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21299 (image-file-name-regexp)
21300 (let ((image-file-name-extensions
21301 (or extensions
21302 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21303 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21304 (concat "\\."
21305 (regexp-opt (nconc (mapcar 'upcase
21306 image-file-name-extensions)
21307 image-file-name-extensions)
21309 "\\'"))))
21311 (defun org-file-image-p (file &optional extensions)
21312 "Return non-nil if FILE is an image."
21313 (save-match-data
21314 (string-match (org-image-file-name-regexp extensions) file)))
21316 (defun org-get-cursor-date (&optional with-time)
21317 "Return the date at cursor in as a time.
21318 This works in the calendar and in the agenda, anywhere else it just
21319 returns the current time.
21320 If WITH-TIME is non-nil, returns the time of the event at point (in
21321 the agenda) or the current time of the day."
21322 (let (date day defd tp tm hod mod)
21323 (when with-time
21324 (setq tp (get-text-property (point) 'time))
21325 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21326 (setq hod (string-to-number (match-string 1 tp))
21327 mod (string-to-number (match-string 2 tp))))
21328 (or tp (setq hod (nth 2 (decode-time (current-time)))
21329 mod (nth 1 (decode-time (current-time))))))
21330 (cond
21331 ((eq major-mode 'calendar-mode)
21332 (setq date (calendar-cursor-to-date)
21333 defd (encode-time 0 (or mod 0) (or hod 0)
21334 (nth 1 date) (nth 0 date) (nth 2 date))))
21335 ((eq major-mode 'org-agenda-mode)
21336 (setq day (get-text-property (point) 'day))
21337 (if day
21338 (setq date (calendar-gregorian-from-absolute day)
21339 defd (encode-time 0 (or mod 0) (or hod 0)
21340 (nth 1 date) (nth 0 date) (nth 2 date))))))
21341 (or defd (current-time))))
21343 (defun org-mark-subtree (&optional up)
21344 "Mark the current subtree.
21345 This puts point at the start of the current subtree, and mark at
21346 the end. If a numeric prefix UP is given, move up into the
21347 hierarchy of headlines by UP levels before marking the subtree."
21348 (interactive "P")
21349 (org-with-limited-levels
21350 (cond ((org-at-heading-p) (beginning-of-line))
21351 ((org-before-first-heading-p) (error "Not in a subtree"))
21352 (t (outline-previous-visible-heading 1))))
21353 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21354 (if (org-called-interactively-p 'any)
21355 (call-interactively 'org-mark-element)
21356 (org-mark-element)))
21359 ;;; Macros
21361 ;; Macros are expanded with `org-macro-replace-all', which relies
21362 ;; internally on `org-macro-expand'.
21364 ;; Default templates for expansion are stored in the buffer-local
21365 ;; variable `org-macro-templates'. This variable is updated by
21366 ;; `org-macro-initialize-templates'.
21368 ;; Along with macros defined through #+MACRO: keyword, default
21369 ;; templates include the following hard-coded macros:
21370 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21371 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21373 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21374 ;; {{{title}}} will also be provided.
21377 (defvar org-macro-templates nil
21378 "Alist containing all macro templates in current buffer.
21379 Associations are in the shape of (NAME . TEMPLATE) where NAME
21380 stands for macro's name and template for its replacement value,
21381 both as strings. This is an internal variable. Do not set it
21382 directly, use instead:
21384 #+MACRO: name template")
21385 (make-variable-buffer-local 'org-macro-templates)
21387 (defun org-macro-expand (macro templates)
21388 "Return expanded MACRO, as a string.
21389 MACRO is an object, obtained, for example, with
21390 `org-element-context'. TEMPLATES is an alist of templates used
21391 for expansion. See `org-macro-templates' for a buffer-local
21392 default value. Return nil if no template was found."
21393 (let ((template
21394 ;; Macro names are case-insensitive.
21395 (cdr (assoc-string (org-element-property :key macro) templates t))))
21396 (when template
21397 (let ((value (replace-regexp-in-string
21398 "\\$[0-9]+"
21399 (lambda (arg)
21400 (or (nth (1- (string-to-number (substring arg 1)))
21401 (org-element-property :args macro))
21402 ;; No argument provided: remove
21403 ;; place-holder.
21404 ""))
21405 template)))
21406 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21407 (when (string-match "\\`(eval\\>" value)
21408 (setq value (eval (read value))))
21409 ;; Return string.
21410 (format "%s" (or value ""))))))
21412 (defun org-macro-replace-all (templates)
21413 "Replace all macros in current buffer by their expansion.
21414 TEMPLATES is an alist of templates used for expansion. See
21415 `org-macro-templates' for a buffer-local default value."
21416 (save-excursion
21417 (goto-char (point-min))
21418 (let (record)
21419 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21420 (let ((object (org-element-context)))
21421 (when (eq (org-element-type object) 'macro)
21422 (let* ((value (org-macro-expand object templates))
21423 (begin (org-element-property :begin object))
21424 (signature (list begin
21425 object
21426 (org-element-property :args object))))
21427 ;; Avoid circular dependencies by checking if the same
21428 ;; macro with the same arguments is expanded at the same
21429 ;; position twice.
21430 (if (member signature record)
21431 (error "Circular macro expansion: %s"
21432 (org-element-property :key object))
21433 (when value
21434 (push signature record)
21435 (delete-region
21436 begin
21437 ;; Preserve white spaces after the macro.
21438 (progn (goto-char (org-element-property :end object))
21439 (skip-chars-backward " \t")
21440 (point)))
21441 ;; Leave point before replacement in case of recursive
21442 ;; expansions.
21443 (save-excursion (insert value)))))))))))
21445 (defun org-macro-initialize-templates ()
21446 "Collect macro templates defined in current buffer.
21447 Templates are stored in buffer-local variable
21448 `org-macro-templates'. In addition to buffer-defined macros, the
21449 function installs the following ones: \"property\",
21450 \"time\". and, if the buffer is associated to a file,
21451 \"input-file\" and \"modification-time\"."
21452 (let ((case-fold-search t)
21453 (set-template
21454 (lambda (cell)
21455 ;; Add CELL to `org-macro-templates' if there's no
21456 ;; association matching its name already. Otherwise,
21457 ;; replace old association with the new one in that
21458 ;; variable.
21459 (let ((old-template (assoc (car cell) org-macro-templates)))
21460 (if old-template (setcdr old-template (cdr cell))
21461 (push cell org-macro-templates))))))
21462 ;; Install buffer-local macros.
21463 (org-with-wide-buffer
21464 (goto-char (point-min))
21465 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21466 (let ((element (org-element-at-point)))
21467 (when (eq (org-element-type element) 'keyword)
21468 (let ((value (org-element-property :value element)))
21469 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21470 (funcall set-template
21471 (cons (match-string 1 value)
21472 (or (match-string 2 value) "")))))))))
21473 ;; Install hard-coded macros.
21474 (mapc (lambda (cell) (funcall set-template cell))
21475 (list
21476 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21477 (cons "time" "(eval (format-time-string \"$1\"))")))
21478 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21479 (when (and visited-file (file-exists-p visited-file))
21480 (mapc (lambda (cell) (funcall set-template cell))
21481 (list
21482 (cons "input-file" (file-name-nondirectory visited-file))
21483 (cons "modification-time"
21484 (format "(eval (format-time-string \"$1\" '%s))"
21485 (prin1-to-string
21486 (nth 5 (file-attributes visited-file)))))))))))
21489 ;;; Indentation
21491 (defun org-indent-line ()
21492 "Indent line depending on context."
21493 (interactive)
21494 (let* ((pos (point))
21495 (itemp (org-at-item-p))
21496 (case-fold-search t)
21497 (org-drawer-regexp (or org-drawer-regexp "\000"))
21498 (inline-task-p (and (featurep 'org-inlinetask)
21499 (org-inlinetask-in-task-p)))
21500 (inline-re (and inline-task-p
21501 (org-inlinetask-outline-regexp)))
21502 column)
21503 (if (and orgstruct-is-++ (eq pos (point)))
21504 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21505 (indent-according-to-mode))
21506 (beginning-of-line 1)
21507 (cond
21508 ;; Headings
21509 ((looking-at org-outline-regexp) (setq column 0))
21510 ;; Footnote definition
21511 ((looking-at org-footnote-definition-re) (setq column 0))
21512 ;; Literal examples
21513 ((looking-at "[ \t]*:\\( \\|$\\)")
21514 (setq column (org-get-indentation))) ; do nothing
21515 ;; Lists
21516 ((ignore-errors (goto-char (org-in-item-p)))
21517 (setq column (if itemp
21518 (org-get-indentation)
21519 (org-list-item-body-column (point))))
21520 (goto-char pos))
21521 ;; Drawers
21522 ((and (looking-at "[ \t]*:END:")
21523 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21524 (save-excursion
21525 (goto-char (1- (match-beginning 1)))
21526 (setq column (current-column))))
21527 ;; Special blocks
21528 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21529 (save-excursion
21530 (re-search-backward
21531 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21532 (setq column (org-get-indentation (match-string 0))))
21533 ((and (not (looking-at "[ \t]*#\\+begin_"))
21534 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21535 (save-excursion
21536 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21537 (setq column
21538 (cond ((equal (downcase (match-string 1)) "src")
21539 ;; src blocks: let `org-edit-src-exit' handle them
21540 (org-get-indentation))
21541 ((equal (downcase (match-string 1)) "example")
21542 (max (org-get-indentation)
21543 (org-get-indentation (match-string 0))))
21545 (org-get-indentation (match-string 0))))))
21546 ;; This line has nothing special, look at the previous relevant
21547 ;; line to compute indentation
21549 (beginning-of-line 0)
21550 (while (and (not (bobp))
21551 (not (looking-at org-table-line-regexp))
21552 (not (looking-at org-drawer-regexp))
21553 ;; When point started in an inline task, do not move
21554 ;; above task starting line.
21555 (not (and inline-task-p (looking-at inline-re)))
21556 ;; Skip drawers, blocks, empty lines, verbatim,
21557 ;; comments, tables, footnotes definitions, lists,
21558 ;; inline tasks.
21559 (or (and (looking-at "[ \t]*:END:")
21560 (re-search-backward org-drawer-regexp nil t))
21561 (and (looking-at "[ \t]*#\\+end_")
21562 (re-search-backward "[ \t]*#\\+begin_"nil t))
21563 (looking-at "[ \t]*[\n:#|]")
21564 (looking-at org-footnote-definition-re)
21565 (and (ignore-errors (goto-char (org-in-item-p)))
21566 (goto-char
21567 (org-list-get-top-point (org-list-struct))))
21568 (and (not inline-task-p)
21569 (featurep 'org-inlinetask)
21570 (org-inlinetask-in-task-p)
21571 (or (org-inlinetask-goto-beginning) t))))
21572 (beginning-of-line 0))
21573 (cond
21574 ;; There was an heading above.
21575 ((looking-at "\\*+[ \t]+")
21576 (if (not org-adapt-indentation)
21577 (setq column 0)
21578 (goto-char (match-end 0))
21579 (setq column (current-column))))
21580 ;; A drawer had started and is unfinished
21581 ((looking-at org-drawer-regexp)
21582 (goto-char (1- (match-beginning 1)))
21583 (setq column (current-column)))
21584 ;; Else, nothing noticeable found: get indentation and go on.
21585 (t (setq column (org-get-indentation))))))
21586 ;; Now apply indentation and move cursor accordingly
21587 (goto-char pos)
21588 (if (<= (current-column) (current-indentation))
21589 (org-indent-line-to column)
21590 (save-excursion (org-indent-line-to column)))
21591 ;; Special polishing for properties, see `org-property-format'
21592 (setq column (current-column))
21593 (beginning-of-line 1)
21594 (if (looking-at
21595 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21596 (replace-match (concat (match-string 1)
21597 (format org-property-format
21598 (match-string 2) (match-string 3)))
21599 t t))
21600 (org-move-to-column column))))
21602 (defun org-indent-drawer ()
21603 "Indent the drawer at point."
21604 (interactive)
21605 (let ((p (point))
21606 (e (and (save-excursion (re-search-forward ":END:" nil t))
21607 (match-end 0)))
21608 (folded
21609 (save-excursion
21610 (end-of-line)
21611 (when (overlays-at (point))
21612 (member 'invisible (overlay-properties
21613 (car (overlays-at (point)))))))))
21614 (when folded (org-cycle))
21615 (indent-for-tab-command)
21616 (while (and (move-beginning-of-line 2) (< (point) e))
21617 (indent-for-tab-command))
21618 (goto-char p)
21619 (when folded (org-cycle)))
21620 (message "Drawer at point indented"))
21622 (defun org-indent-block ()
21623 "Indent the block at point."
21624 (interactive)
21625 (let ((p (point))
21626 (case-fold-search t)
21627 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21628 (match-end 0)))
21629 (folded
21630 (save-excursion
21631 (end-of-line)
21632 (when (overlays-at (point))
21633 (member 'invisible (overlay-properties
21634 (car (overlays-at (point)))))))))
21635 (when folded (org-cycle))
21636 (indent-for-tab-command)
21637 (while (and (move-beginning-of-line 2) (< (point) e))
21638 (indent-for-tab-command))
21639 (goto-char p)
21640 (when folded (org-cycle)))
21641 (message "Block at point indented"))
21643 (defun org-indent-region (start end)
21644 "Indent region."
21645 (interactive "r")
21646 (save-excursion
21647 (let ((line-end (org-current-line end)))
21648 (goto-char start)
21649 (while (< (org-current-line) line-end)
21650 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21651 (t (call-interactively 'org-indent-line)))
21652 (move-beginning-of-line 2)))))
21655 ;;; Filling
21657 ;; We use our own fill-paragraph and auto-fill functions.
21659 ;; `org-fill-paragraph' relies on adaptive filling and context
21660 ;; checking. Appropriate `fill-prefix' is computed with
21661 ;; `org-adaptive-fill-function'.
21663 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21664 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21665 ;; `org-adaptive-fill-function' value. Internally,
21666 ;; `org-comment-line-break-function' breaks the line.
21668 ;; `org-setup-filling' installs filling and auto-filling related
21669 ;; variables during `org-mode' initialization.
21671 (defun org-setup-filling ()
21672 (interactive)
21673 ;; Prevent auto-fill from inserting unwanted new items.
21674 (when (boundp 'fill-nobreak-predicate)
21675 (org-set-local
21676 'fill-nobreak-predicate
21677 (org-uniquify
21678 (append fill-nobreak-predicate
21679 '(org-fill-paragraph-separate-nobreak-p
21680 org-fill-line-break-nobreak-p
21681 org-fill-paragraph-with-timestamp-nobreak-p)))))
21682 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21683 (org-set-local 'auto-fill-inhibit-regexp nil)
21684 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21685 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21686 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21688 (defvar org-element-paragraph-separate) ; org-element.el
21689 (defun org-fill-paragraph-separate-nobreak-p ()
21690 "Non-nil when a line break at point would insert a new item."
21691 (looking-at (substring org-element-paragraph-separate 1)))
21693 (defun org-fill-line-break-nobreak-p ()
21694 "Non-nil when a line break at point would create an Org line break."
21695 (save-excursion
21696 (skip-chars-backward "[ \t]")
21697 (skip-chars-backward "\\\\")
21698 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21700 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21701 "Non-nil when a line break at point would insert a new item."
21702 (and (org-at-timestamp-p t)
21703 (not (looking-at org-ts-regexp-both))))
21705 (declare-function message-in-body-p "message" ())
21706 (defvar orgtbl-line-start-regexp) ; From org-table.el
21707 (defun org-adaptive-fill-function ()
21708 "Compute a fill prefix for the current line.
21709 Return fill prefix, as a string, or nil if current line isn't
21710 meant to be filled."
21711 (let (prefix)
21712 (catch 'exit
21713 (when (derived-mode-p 'message-mode)
21714 (save-excursion
21715 (beginning-of-line)
21716 (cond ((or (not (message-in-body-p))
21717 (looking-at orgtbl-line-start-regexp))
21718 (throw 'exit nil))
21719 ((looking-at message-cite-prefix-regexp)
21720 (throw 'exit (match-string-no-properties 0)))
21721 ((looking-at org-outline-regexp)
21722 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21723 (org-with-wide-buffer
21724 (let* ((p (line-beginning-position))
21725 (element (save-excursion (beginning-of-line)
21726 (org-element-at-point)))
21727 (type (org-element-type element))
21728 (post-affiliated (org-element-property :post-affiliated element)))
21729 (unless (and post-affiliated (< p post-affiliated))
21730 (case type
21731 (comment (looking-at "[ \t]*# ?") (match-string 0))
21732 (footnote-definition "")
21733 ((item plain-list)
21734 (make-string (org-list-item-body-column
21735 (or post-affiliated
21736 (org-element-property :begin element)))
21737 ? ))
21738 (paragraph
21739 ;; Fill prefix is usually the same as the current line,
21740 ;; except if the paragraph is at the beginning of an item.
21741 (let ((parent (org-element-property :parent element)))
21742 (cond ((eq (org-element-type parent) 'item)
21743 (make-string (org-list-item-body-column
21744 (org-element-property :begin parent))
21745 ? ))
21746 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21747 (match-string 0))
21748 (t ""))))
21749 (comment-block
21750 ;; Only fill contents if P is within block boundaries.
21751 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21752 (forward-line)
21753 (point)))
21754 (cend (save-excursion
21755 (goto-char (org-element-property :end element))
21756 (skip-chars-backward " \r\t\n")
21757 (line-beginning-position))))
21758 (when (and (>= p cbeg) (< p cend))
21759 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21760 (match-string 0)
21761 "")))))))))))
21763 (declare-function message-goto-body "message" ())
21764 (defvar message-cite-prefix-regexp) ; From message.el
21765 (defvar org-element-all-objects) ; From org-element.el
21766 (defun org-fill-paragraph (&optional justify)
21767 "Fill element at point, when applicable.
21769 This function only applies to comment blocks, comments, example
21770 blocks and paragraphs. Also, as a special case, re-align table
21771 when point is at one.
21773 If JUSTIFY is non-nil (interactively, with prefix argument),
21774 justify as well. If `sentence-end-double-space' is non-nil, then
21775 period followed by one space does not end a sentence, so don't
21776 break a line there. The variable `fill-column' controls the
21777 width for filling.
21779 For convenience, when point is at a plain list, an item or
21780 a footnote definition, try to fill the first paragraph within."
21781 (interactive)
21782 (if (and (derived-mode-p 'message-mode)
21783 (or (not (message-in-body-p))
21784 (save-excursion (move-beginning-of-line 1)
21785 (looking-at message-cite-prefix-regexp))))
21786 ;; First ensure filling is correct in message-mode.
21787 (let ((fill-paragraph-function
21788 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21789 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21790 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21791 (paragraph-separate
21792 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21793 (fill-paragraph nil))
21794 (save-excursion
21795 ;; Move to end of line in order to get the first paragraph
21796 ;; within a plain list or a footnote definition.
21797 (end-of-line)
21798 (let ((element (org-element-at-point)))
21799 ;; First check if point is in a blank line at the beginning of
21800 ;; the buffer. In that case, ignore filling.
21801 (if (< (point) (org-element-property :begin element)) t
21802 (case (org-element-type element)
21803 ;; Use major mode filling function is src blocks.
21804 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21805 ;; Align Org tables, leave table.el tables as-is.
21806 (table-row (org-table-align) t)
21807 (table
21808 (when (eq (org-element-property :type element) 'org)
21809 (org-table-align))
21811 (paragraph
21812 ;; Paragraphs may contain `line-break' type objects.
21813 (let ((beg (max (point-min)
21814 (org-element-property :contents-begin element)))
21815 (end (min (point-max)
21816 (org-element-property :contents-end element))))
21817 ;; Do nothing if point is at an affiliated keyword.
21818 (if (< (point) beg) t
21819 (when (derived-mode-p 'message-mode)
21820 ;; In `message-mode', do not fill following
21821 ;; citation in current paragraph nor text before
21822 ;; message body.
21823 (let ((body-start (save-excursion (message-goto-body))))
21824 (when body-start (setq beg (max body-start beg))))
21825 (when (save-excursion
21826 (re-search-forward
21827 (concat "^" message-cite-prefix-regexp) end t))
21828 (setq end (match-beginning 0))))
21829 ;; Fill paragraph, taking line breaks into
21830 ;; consideration. For that, slice the paragraph
21831 ;; using line breaks as separators, and fill the
21832 ;; parts in reverse order to avoid messing with
21833 ;; markers.
21834 (save-excursion
21835 (goto-char end)
21836 (mapc
21837 (lambda (pos)
21838 (fill-region-as-paragraph pos (point) justify)
21839 (goto-char pos))
21840 ;; Find the list of ending positions for line
21841 ;; breaks in the current paragraph. Add paragraph
21842 ;; beginning to include first slice.
21843 (nreverse
21844 (cons
21846 (org-element-map
21847 (org-element--parse-objects
21848 beg end nil org-element-all-objects)
21849 'line-break
21850 (lambda (lb) (org-element-property :end lb)))))))
21851 t)))
21852 ;; Contents of `comment-block' type elements should be
21853 ;; filled as plain text, but only if point is within block
21854 ;; markers.
21855 (comment-block
21856 (let* ((case-fold-search t)
21857 (beg (save-excursion
21858 (goto-char (org-element-property :begin element))
21859 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21860 (forward-line)
21861 (point)))
21862 (end (save-excursion
21863 (goto-char (org-element-property :end element))
21864 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21865 (line-beginning-position))))
21866 (when (and (>= (point) beg) (< (point) end))
21867 (fill-region-as-paragraph
21868 (save-excursion
21869 (end-of-line)
21870 (re-search-backward "^[ \t]*$" beg 'move)
21871 (line-beginning-position))
21872 (save-excursion
21873 (beginning-of-line)
21874 (re-search-forward "^[ \t]*$" end 'move)
21875 (line-beginning-position))
21876 justify)))
21878 ;; Fill comments.
21879 (comment (fill-comment-paragraph justify))
21880 ;; Ignore every other element.
21881 (otherwise t)))))))
21883 (defun org-auto-fill-function ()
21884 "Auto-fill function."
21885 ;; Check if auto-filling is meaningful.
21886 (let ((fc (current-fill-column)))
21887 (when (and fc (> (current-column) fc))
21888 (let* ((fill-prefix (org-adaptive-fill-function))
21889 ;; Enforce empty fill prefix, if required. Otherwise, it
21890 ;; will be computed again.
21891 (adaptive-fill-mode (not (equal fill-prefix ""))))
21892 (when fill-prefix (do-auto-fill))))))
21894 (defun org-comment-line-break-function (&optional soft)
21895 "Break line at point and indent, continuing comment if within one.
21896 The inserted newline is marked hard if variable
21897 `use-hard-newlines' is true, unless optional argument SOFT is
21898 non-nil."
21899 (if soft (insert-and-inherit ?\n) (newline 1))
21900 (save-excursion (forward-char -1) (delete-horizontal-space))
21901 (delete-horizontal-space)
21902 (indent-to-left-margin)
21903 (insert-before-markers-and-inherit fill-prefix))
21906 ;;; Comments
21908 ;; Org comments syntax is quite complex. It requires the entire line
21909 ;; to be just a comment. Also, even with the right syntax at the
21910 ;; beginning of line, some some elements (i.e. verse-block or
21911 ;; example-block) don't accept comments. Usual Emacs comment commands
21912 ;; cannot cope with those requirements. Therefore, Org replaces them.
21914 ;; Org still relies on `comment-dwim', but cannot trust
21915 ;; `comment-only-p'. So, `comment-region-function' and
21916 ;; `uncomment-region-function' both point
21917 ;; to`org-comment-or-uncomment-region'. Eventually,
21918 ;; `org-insert-comment' takes care of insertion of comments at the
21919 ;; beginning of line.
21921 ;; `org-setup-comments-handling' install comments related variables
21922 ;; during `org-mode' initialization.
21924 (defun org-setup-comments-handling ()
21925 (interactive)
21926 (org-set-local 'comment-use-syntax nil)
21927 (org-set-local 'comment-start "# ")
21928 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21929 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21930 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21931 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21933 (defun org-insert-comment ()
21934 "Insert an empty comment above current line.
21935 If the line is empty, insert comment at its beginning."
21936 (beginning-of-line)
21937 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21938 (org-indent-line)
21939 (insert "# "))
21941 (defvar comment-empty-lines) ; From newcomment.el.
21942 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21943 "Comment or uncomment each non-blank line in the region.
21944 Uncomment each non-blank line between BEG and END if it only
21945 contains commented lines. Otherwise, comment them."
21946 (save-restriction
21947 ;; Restrict region
21948 (narrow-to-region (save-excursion (goto-char beg)
21949 (skip-chars-forward " \r\t\n" end)
21950 (line-beginning-position))
21951 (save-excursion (goto-char end)
21952 (skip-chars-backward " \r\t\n" beg)
21953 (line-end-position)))
21954 (let ((uncommentp
21955 ;; UNCOMMENTP is non-nil when every non blank line between
21956 ;; BEG and END is a comment.
21957 (save-excursion
21958 (goto-char (point-min))
21959 (while (and (not (eobp))
21960 (let ((element (org-element-at-point)))
21961 (and (eq (org-element-type element) 'comment)
21962 (goto-char (min (point-max)
21963 (org-element-property
21964 :end element)))))))
21965 (eobp))))
21966 (if uncommentp
21967 ;; Only blank lines and comments in region: uncomment it.
21968 (save-excursion
21969 (goto-char (point-min))
21970 (while (not (eobp))
21971 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21972 (replace-match "" nil nil nil 1))
21973 (forward-line)))
21974 ;; Comment each line in region.
21975 (let ((min-indent (point-max)))
21976 ;; First find the minimum indentation across all lines.
21977 (save-excursion
21978 (goto-char (point-min))
21979 (while (and (not (eobp)) (not (zerop min-indent)))
21980 (unless (looking-at "[ \t]*$")
21981 (setq min-indent (min min-indent (current-indentation))))
21982 (forward-line)))
21983 ;; Then loop over all lines.
21984 (save-excursion
21985 (goto-char (point-min))
21986 (while (not (eobp))
21987 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21988 (org-move-to-column min-indent t)
21989 (insert comment-start))
21990 (forward-line))))))))
21993 ;;; Planning
21995 ;; This section contains tools to operate on timestamp objects, as
21996 ;; returned by, e.g. `org-element-context'.
21998 (defun org-timestamp-has-time-p (timestamp)
21999 "Non-nil when TIMESTAMP has a time specified."
22000 (org-element-property :hour-start timestamp))
22002 (defun org-timestamp-format (timestamp format &optional end utc)
22003 "Format a TIMESTAMP element into a string.
22005 FORMAT is a format specifier to be passed to
22006 `format-time-string'.
22008 When optional argument END is non-nil, use end of date-range or
22009 time-range, if possible.
22011 When optional argument UTC is non-nil, time will be expressed as
22012 Universal Time."
22013 (format-time-string
22014 format
22015 (apply 'encode-time
22016 (cons 0
22017 (mapcar
22018 (lambda (prop) (or (org-element-property prop timestamp) 0))
22019 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22020 '(:minute-start :hour-start :day-start :month-start
22021 :year-start)))))
22022 utc))
22024 (defun org-timestamp-split-range (timestamp &optional end)
22025 "Extract a timestamp object from a date or time range.
22027 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22028 the end of the range. Otherwise, extract its start.
22030 Return a new timestamp object sharing the same parent as
22031 TIMESTAMP."
22032 (let ((type (org-element-property :type timestamp)))
22033 (if (memq type '(active inactive diary)) timestamp
22034 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22035 ;; Set new type.
22036 (org-element-put-property
22037 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22038 ;; Copy start properties over end properties if END is
22039 ;; non-nil. Otherwise, copy end properties over `start' ones.
22040 (let ((p-alist '((:minute-start . :minute-end)
22041 (:hour-start . :hour-end)
22042 (:day-start . :day-end)
22043 (:month-start . :month-end)
22044 (:year-start . :year-end))))
22045 (dolist (p-cell p-alist)
22046 (org-element-put-property
22047 split-ts
22048 (funcall (if end 'car 'cdr) p-cell)
22049 (org-element-property
22050 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22051 ;; Eventually refresh `:raw-value'.
22052 (org-element-put-property split-ts :raw-value nil)
22053 (org-element-put-property
22054 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22056 (defun org-timestamp-translate (timestamp &optional boundary)
22057 "Apply `org-translate-time' on a TIMESTAMP object.
22058 When optional argument BOUNDARY is non-nil, it is either the
22059 symbol `start' or `end'. In this case, only translate the
22060 starting or ending part of TIMESTAMP if it is a date or time
22061 range. Otherwise, translate both parts."
22062 (if (and (not boundary)
22063 (memq (org-element-property :type timestamp)
22064 '(active-range inactive-range)))
22065 (concat
22066 (org-translate-time
22067 (org-element-property :raw-value
22068 (org-timestamp-split-range timestamp)))
22069 "--"
22070 (org-translate-time
22071 (org-element-property :raw-value
22072 (org-timestamp-split-range timestamp t))))
22073 (org-translate-time
22074 (org-element-property
22075 :raw-value
22076 (if (not boundary) timestamp
22077 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22081 ;;; Other stuff.
22083 (defun org-toggle-fixed-width-section (arg)
22084 "Toggle the fixed-width export.
22085 If there is no active region, the QUOTE keyword at the current headline is
22086 inserted or removed. When present, it causes the text between this headline
22087 and the next to be exported as fixed-width text, and unmodified.
22088 If there is an active region, this command adds or removes a colon as the
22089 first character of this line. If the first character of a line is a colon,
22090 this line is also exported in fixed-width font."
22091 (interactive "P")
22092 (let* ((cc 0)
22093 (regionp (org-region-active-p))
22094 (beg (if regionp (region-beginning) (point)))
22095 (end (if regionp (region-end)))
22096 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22097 (case-fold-search nil)
22098 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22099 off)
22100 (if regionp
22101 (save-excursion
22102 (goto-char beg)
22103 (setq cc (current-column))
22104 (beginning-of-line 1)
22105 (setq off (looking-at re))
22106 (while (> nlines 0)
22107 (setq nlines (1- nlines))
22108 (beginning-of-line 1)
22109 (cond
22110 (arg
22111 (org-move-to-column cc t)
22112 (insert ": \n")
22113 (forward-line -1))
22114 ((and off (looking-at re))
22115 (replace-match "" t t nil 1))
22116 ((not off) (org-move-to-column cc t) (insert ": ")))
22117 (forward-line 1)))
22118 (save-excursion
22119 (org-back-to-heading)
22120 (cond
22121 ((looking-at (format org-heading-keyword-regexp-format
22122 org-quote-string))
22123 (goto-char (match-end 1))
22124 (looking-at (concat " +" org-quote-string))
22125 (replace-match "" t t)
22126 (when (eolp) (insert " ")))
22127 ((looking-at org-outline-regexp)
22128 (goto-char (match-end 0))
22129 (insert org-quote-string " ")))))))
22131 (defun org-reftex-citation ()
22132 "Use reftex-citation to insert a citation into the buffer.
22133 This looks for a line like
22135 #+BIBLIOGRAPHY: foo plain option:-d
22137 and derives from it that foo.bib is the bibliography file relevant
22138 for this document. It then installs the necessary environment for RefTeX
22139 to work in this buffer and calls `reftex-citation' to insert a citation
22140 into the buffer.
22142 Export of such citations to both LaTeX and HTML is handled by the contributed
22143 package org-exp-bibtex by Taru Karttunen."
22144 (interactive)
22145 (let ((reftex-docstruct-symbol 'rds)
22146 (reftex-cite-format "\\cite{%l}")
22147 rds bib)
22148 (save-excursion
22149 (save-restriction
22150 (widen)
22151 (let ((case-fold-search t)
22152 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22153 (if (not (save-excursion
22154 (or (re-search-forward re nil t)
22155 (re-search-backward re nil t))))
22156 (error "No bibliography defined in file")
22157 (setq bib (concat (match-string 1) ".bib")
22158 rds (list (list 'bib bib)))))))
22159 (call-interactively 'reftex-citation)))
22161 ;;;; Functions extending outline functionality
22163 (defun org-beginning-of-line (&optional arg)
22164 "Go to the beginning of the current line. If that is invisible, continue
22165 to a visible line beginning. This makes the function of C-a more intuitive.
22166 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22167 first attempt, and only move to after the tags when the cursor is already
22168 beyond the end of the headline."
22169 (interactive "P")
22170 (let ((pos (point))
22171 (special (if (consp org-special-ctrl-a/e)
22172 (car org-special-ctrl-a/e)
22173 org-special-ctrl-a/e))
22174 refpos)
22175 (if (org-bound-and-true-p visual-line-mode)
22176 (beginning-of-visual-line 1)
22177 (beginning-of-line 1))
22178 (if (and arg (fboundp 'move-beginning-of-line))
22179 (call-interactively 'move-beginning-of-line)
22180 (if (bobp)
22182 (backward-char 1)
22183 (if (org-truely-invisible-p)
22184 (while (and (not (bobp)) (org-truely-invisible-p))
22185 (backward-char 1)
22186 (beginning-of-line 1))
22187 (forward-char 1))))
22188 (when special
22189 (cond
22190 ((and (looking-at org-complex-heading-regexp)
22191 (= (char-after (match-end 1)) ?\ ))
22192 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22193 (point-at-eol)))
22194 (goto-char
22195 (if (eq special t)
22196 (cond ((> pos refpos) refpos)
22197 ((= pos (point)) refpos)
22198 (t (point)))
22199 (cond ((> pos (point)) (point))
22200 ((not (eq last-command this-command)) (point))
22201 (t refpos)))))
22202 ((org-at-item-p)
22203 ;; Being at an item and not looking at an the item means point
22204 ;; was previously moved to beginning of a visual line, which
22205 ;; doesn't contain the item. Therefore, do nothing special,
22206 ;; just stay here.
22207 (when (looking-at org-list-full-item-re)
22208 ;; Set special position at first white space character after
22209 ;; bullet, and check-box, if any.
22210 (let ((after-bullet
22211 (let ((box (match-end 3)))
22212 (if (not box) (match-end 1)
22213 (let ((after (char-after box)))
22214 (if (and after (= after ? )) (1+ box) box))))))
22215 ;; Special case: Move point to special position when
22216 ;; currently after it or at beginning of line.
22217 (if (eq special t)
22218 (when (or (> pos after-bullet) (= (point) pos))
22219 (goto-char after-bullet))
22220 ;; Reversed case: Move point to special position when
22221 ;; point was already at beginning of line and command is
22222 ;; repeated.
22223 (when (and (= (point) pos) (eq last-command this-command))
22224 (goto-char after-bullet))))))))
22225 (org-no-warnings
22226 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22228 (defun org-end-of-line (&optional arg)
22229 "Go to the end of the line.
22230 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22231 tags on the first attempt, and only move to after the tags when
22232 the cursor is already beyond the end of the headline."
22233 (interactive "P")
22234 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22235 org-special-ctrl-a/e))
22236 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22237 'end-of-visual-line)
22238 ((fboundp 'move-end-of-line) 'move-end-of-line)
22239 (t 'end-of-line))))
22240 (if (or (not special) arg) (call-interactively move-fun)
22241 (let* ((element (ignore-errors
22242 ;; Don't throw an error outside elements
22243 (save-excursion (beginning-of-line)
22244 (org-element-at-point))))
22245 (type (org-element-type element)))
22246 (cond
22247 ((memq type '(headline inlinetask))
22248 (let ((pos (point)))
22249 (beginning-of-line 1)
22250 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22251 (if (eq special t)
22252 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22253 (goto-char (match-beginning 1))
22254 (goto-char (match-end 0)))
22255 (if (or (< pos (match-end 0))
22256 (not (eq this-command last-command)))
22257 (goto-char (match-end 0))
22258 (goto-char (match-beginning 1))))
22259 (call-interactively move-fun))))
22260 ((org-element-property :hiddenp element)
22261 ;; If element is hidden, `move-end-of-line' would put point
22262 ;; after it. Use `end-of-line' to stay on current line.
22263 (call-interactively 'end-of-line))
22264 (t (call-interactively move-fun)))))
22265 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22267 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22268 (define-key org-mode-map "\C-e" 'org-end-of-line)
22270 (defun org-backward-sentence (&optional arg)
22271 "Go to beginning of sentence, or beginning of table field.
22272 This will call `backward-sentence' or `org-table-beginning-of-field',
22273 depending on context."
22274 (interactive "P")
22275 (cond
22276 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22277 (t (call-interactively 'backward-sentence))))
22279 (defun org-forward-sentence (&optional arg)
22280 "Go to end of sentence, or end of table field.
22281 This will call `forward-sentence' or `org-table-end-of-field',
22282 depending on context."
22283 (interactive "P")
22284 (cond
22285 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22286 (t (call-interactively 'forward-sentence))))
22288 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22289 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22291 (defun org-kill-line (&optional arg)
22292 "Kill line, to tags or end of line."
22293 (interactive "P")
22294 (cond
22295 ((or (not org-special-ctrl-k)
22296 (bolp)
22297 (not (org-at-heading-p)))
22298 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22299 org-ctrl-k-protect-subtree)
22300 (if (or (eq org-ctrl-k-protect-subtree 'error)
22301 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22302 (error "C-k aborted - would kill hidden subtree")))
22303 (call-interactively
22304 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22305 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22306 (kill-region (point) (match-beginning 1))
22307 (org-set-tags nil t))
22308 (t (kill-region (point) (point-at-eol)))))
22310 (define-key org-mode-map "\C-k" 'org-kill-line)
22312 (defun org-yank (&optional arg)
22313 "Yank. If the kill is a subtree, treat it specially.
22314 This command will look at the current kill and check if is a single
22315 subtree, or a series of subtrees[1]. If it passes the test, and if the
22316 cursor is at the beginning of a line or after the stars of a currently
22317 empty headline, then the yank is handled specially. How exactly depends
22318 on the value of the following variables, both set by default.
22320 org-yank-folded-subtrees
22321 When set, the subtree(s) will be folded after insertion, but only
22322 if doing so would now swallow text after the yanked text.
22324 org-yank-adjusted-subtrees
22325 When set, the subtree will be promoted or demoted in order to
22326 fit into the local outline tree structure, which means that the level
22327 will be adjusted so that it becomes the smaller one of the two
22328 *visible* surrounding headings.
22330 Any prefix to this command will cause `yank' to be called directly with
22331 no special treatment. In particular, a simple \\[universal-argument] prefix \
22332 will just
22333 plainly yank the text as it is.
22335 \[1] The test checks if the first non-white line is a heading
22336 and if there are no other headings with fewer stars."
22337 (interactive "P")
22338 (org-yank-generic 'yank arg))
22340 (defun org-yank-generic (command arg)
22341 "Perform some yank-like command.
22343 This function implements the behavior described in the `org-yank'
22344 documentation. However, it has been generalized to work for any
22345 interactive command with similar behavior."
22347 ;; pretend to be command COMMAND
22348 (setq this-command command)
22350 (if arg
22351 (call-interactively command)
22353 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22354 (and (org-kill-is-subtree-p)
22355 (or (bolp)
22356 (and (looking-at "[ \t]*$")
22357 (string-match
22358 "\\`\\*+\\'"
22359 (buffer-substring (point-at-bol) (point)))))))
22360 swallowp)
22361 (cond
22362 ((and subtreep org-yank-folded-subtrees)
22363 (let ((beg (point))
22364 end)
22365 (if (and subtreep org-yank-adjusted-subtrees)
22366 (org-paste-subtree nil nil 'for-yank)
22367 (call-interactively command))
22369 (setq end (point))
22370 (goto-char beg)
22371 (when (and (bolp) subtreep
22372 (not (setq swallowp
22373 (org-yank-folding-would-swallow-text beg end))))
22374 (org-with-limited-levels
22375 (or (looking-at org-outline-regexp)
22376 (re-search-forward org-outline-regexp-bol end t))
22377 (while (and (< (point) end) (looking-at org-outline-regexp))
22378 (hide-subtree)
22379 (org-cycle-show-empty-lines 'folded)
22380 (condition-case nil
22381 (outline-forward-same-level 1)
22382 (error (goto-char end))))))
22383 (when swallowp
22384 (message
22385 "Inserted text not folded because that would swallow text"))
22387 (goto-char end)
22388 (skip-chars-forward " \t\n\r")
22389 (beginning-of-line 1)
22390 (push-mark beg 'nomsg)))
22391 ((and subtreep org-yank-adjusted-subtrees)
22392 (let ((beg (point-at-bol)))
22393 (org-paste-subtree nil nil 'for-yank)
22394 (push-mark beg 'nomsg)))
22396 (call-interactively command))))))
22398 (defun org-yank-folding-would-swallow-text (beg end)
22399 "Would hide-subtree at BEG swallow any text after END?"
22400 (let (level)
22401 (org-with-limited-levels
22402 (save-excursion
22403 (goto-char beg)
22404 (when (or (looking-at org-outline-regexp)
22405 (re-search-forward org-outline-regexp-bol end t))
22406 (setq level (org-outline-level)))
22407 (goto-char end)
22408 (skip-chars-forward " \t\r\n\v\f")
22409 (if (or (eobp)
22410 (and (bolp) (looking-at org-outline-regexp)
22411 (<= (org-outline-level) level)))
22412 nil ; Nothing would be swallowed
22413 t))))) ; something would swallow
22415 (define-key org-mode-map "\C-y" 'org-yank)
22417 (defun org-truely-invisible-p ()
22418 "Check if point is at a character currently not visible.
22419 This version does not only check the character property, but also
22420 `visible-mode'."
22421 ;; Early versions of noutline don't have `outline-invisible-p'.
22422 (if (org-bound-and-true-p visible-mode)
22424 (outline-invisible-p)))
22426 (defun org-invisible-p2 ()
22427 "Check if point is at a character currently not visible."
22428 (save-excursion
22429 (if (and (eolp) (not (bobp))) (backward-char 1))
22430 ;; Early versions of noutline don't have `outline-invisible-p'.
22431 (outline-invisible-p)))
22433 (defun org-back-to-heading (&optional invisible-ok)
22434 "Call `outline-back-to-heading', but provide a better error message."
22435 (condition-case nil
22436 (outline-back-to-heading invisible-ok)
22437 (error (error "Before first headline at position %d in buffer %s"
22438 (point) (current-buffer)))))
22440 (defun org-before-first-heading-p ()
22441 "Before first heading?"
22442 (save-excursion
22443 (end-of-line)
22444 (null (re-search-backward org-outline-regexp-bol nil t))))
22446 (defun org-at-heading-p (&optional ignored)
22447 (outline-on-heading-p t))
22448 ;; Compatibility alias with Org versions < 7.8.03
22449 (defalias 'org-on-heading-p 'org-at-heading-p)
22451 (defun org-at-comment-p nil
22452 "Is cursor in a line starting with a # character?"
22453 (save-excursion
22454 (beginning-of-line)
22455 (looking-at "^#")))
22457 (defun org-at-drawer-p nil
22458 "Is cursor at a drawer keyword?"
22459 (save-excursion
22460 (move-beginning-of-line 1)
22461 (looking-at org-drawer-regexp)))
22463 (defun org-at-block-p nil
22464 "Is cursor at a block keyword?"
22465 (save-excursion
22466 (move-beginning-of-line 1)
22467 (looking-at org-block-regexp)))
22469 (defun org-point-at-end-of-empty-headline ()
22470 "If point is at the end of an empty headline, return t, else nil.
22471 If the heading only contains a TODO keyword, it is still still considered
22472 empty."
22473 (and (looking-at "[ \t]*$")
22474 (when org-todo-line-regexp
22475 (save-excursion
22476 (beginning-of-line 1)
22477 (let ((case-fold-search nil))
22478 (looking-at org-todo-line-regexp)
22479 (string= (match-string 3) ""))))))
22481 (defun org-at-heading-or-item-p ()
22482 (or (org-at-heading-p) (org-at-item-p)))
22484 (defun org-at-target-p ()
22485 (or (org-in-regexp org-radio-target-regexp)
22486 (org-in-regexp org-target-regexp)))
22487 ;; Compatibility alias with Org versions < 7.8.03
22488 (defalias 'org-on-target-p 'org-at-target-p)
22490 (defun org-up-heading-all (arg)
22491 "Move to the heading line of which the present line is a subheading.
22492 This function considers both visible and invisible heading lines.
22493 With argument, move up ARG levels."
22494 (if (fboundp 'outline-up-heading-all)
22495 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22496 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22498 (defun org-up-heading-safe ()
22499 "Move to the heading line of which the present line is a subheading.
22500 This version will not throw an error. It will return the level of the
22501 headline found, or nil if no higher level is found.
22503 Also, this function will be a lot faster than `outline-up-heading',
22504 because it relies on stars being the outline starters. This can really
22505 make a significant difference in outlines with very many siblings."
22506 (let (start-level re)
22507 (org-back-to-heading t)
22508 (setq start-level (funcall outline-level))
22509 (if (equal start-level 1)
22511 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22512 (if (re-search-backward re nil t)
22513 (funcall outline-level)))))
22515 (defun org-first-sibling-p ()
22516 "Is this heading the first child of its parents?"
22517 (interactive)
22518 (let ((re org-outline-regexp-bol)
22519 level l)
22520 (unless (org-at-heading-p t)
22521 (error "Not at a heading"))
22522 (setq level (funcall outline-level))
22523 (save-excursion
22524 (if (not (re-search-backward re nil t))
22526 (setq l (funcall outline-level))
22527 (< l level)))))
22529 (defun org-goto-sibling (&optional previous)
22530 "Goto the next sibling, even if it is invisible.
22531 When PREVIOUS is set, go to the previous sibling instead. Returns t
22532 when a sibling was found. When none is found, return nil and don't
22533 move point."
22534 (let ((fun (if previous 're-search-backward 're-search-forward))
22535 (pos (point))
22536 (re org-outline-regexp-bol)
22537 level l)
22538 (when (condition-case nil (org-back-to-heading t) (error nil))
22539 (setq level (funcall outline-level))
22540 (catch 'exit
22541 (or previous (forward-char 1))
22542 (while (funcall fun re nil t)
22543 (setq l (funcall outline-level))
22544 (when (< l level) (goto-char pos) (throw 'exit nil))
22545 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22546 (goto-char pos)
22547 nil))))
22549 (defun org-show-siblings ()
22550 "Show all siblings of the current headline."
22551 (save-excursion
22552 (while (org-goto-sibling) (org-flag-heading nil)))
22553 (save-excursion
22554 (while (org-goto-sibling 'previous)
22555 (org-flag-heading nil))))
22557 (defun org-goto-first-child ()
22558 "Goto the first child, even if it is invisible.
22559 Return t when a child was found. Otherwise don't move point and
22560 return nil."
22561 (let (level (pos (point)) (re org-outline-regexp-bol))
22562 (when (condition-case nil (org-back-to-heading t) (error nil))
22563 (setq level (outline-level))
22564 (forward-char 1)
22565 (if (and (re-search-forward re nil t) (> (outline-level) level))
22566 (progn (goto-char (match-beginning 0)) t)
22567 (goto-char pos) nil))))
22569 (defun org-show-hidden-entry ()
22570 "Show an entry where even the heading is hidden."
22571 (save-excursion
22572 (org-show-entry)))
22574 (defun org-flag-heading (flag &optional entry)
22575 "Flag the current heading. FLAG non-nil means make invisible.
22576 When ENTRY is non-nil, show the entire entry."
22577 (save-excursion
22578 (org-back-to-heading t)
22579 ;; Check if we should show the entire entry
22580 (if entry
22581 (progn
22582 (org-show-entry)
22583 (save-excursion
22584 (and (outline-next-heading)
22585 (org-flag-heading nil))))
22586 (outline-flag-region (max (point-min) (1- (point)))
22587 (save-excursion (outline-end-of-heading) (point))
22588 flag))))
22590 (defun org-get-next-sibling ()
22591 "Move to next heading of the same level, and return point.
22592 If there is no such heading, return nil.
22593 This is like outline-next-sibling, but invisible headings are ok."
22594 (let ((level (funcall outline-level)))
22595 (outline-next-heading)
22596 (while (and (not (eobp)) (> (funcall outline-level) level))
22597 (outline-next-heading))
22598 (if (or (eobp) (< (funcall outline-level) level))
22600 (point))))
22602 (defun org-get-last-sibling ()
22603 "Move to previous heading of the same level, and return point.
22604 If there is no such heading, return nil."
22605 (let ((opoint (point))
22606 (level (funcall outline-level)))
22607 (outline-previous-heading)
22608 (when (and (/= (point) opoint) (outline-on-heading-p t))
22609 (while (and (> (funcall outline-level) level)
22610 (not (bobp)))
22611 (outline-previous-heading))
22612 (if (< (funcall outline-level) level)
22614 (point)))))
22616 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22617 "Goto to the end of a subtree."
22618 ;; This contains an exact copy of the original function, but it uses
22619 ;; `org-back-to-heading', to make it work also in invisible
22620 ;; trees. And is uses an invisible-ok argument.
22621 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22622 ;; Furthermore, when used inside Org, finding the end of a large subtree
22623 ;; with many children and grandchildren etc, this can be much faster
22624 ;; than the outline version.
22625 (org-back-to-heading invisible-ok)
22626 (let ((first t)
22627 (level (funcall outline-level)))
22628 (if (and (derived-mode-p 'org-mode) (< level 1000))
22629 ;; A true heading (not a plain list item), in Org-mode
22630 ;; This means we can easily find the end by looking
22631 ;; only for the right number of stars. Using a regexp to do
22632 ;; this is so much faster than using a Lisp loop.
22633 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22634 (forward-char 1)
22635 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22636 ;; something else, do it the slow way
22637 (while (and (not (eobp))
22638 (or first (> (funcall outline-level) level)))
22639 (setq first nil)
22640 (outline-next-heading)))
22641 (unless to-heading
22642 (if (memq (preceding-char) '(?\n ?\^M))
22643 (progn
22644 ;; Go to end of line before heading
22645 (forward-char -1)
22646 (if (memq (preceding-char) '(?\n ?\^M))
22647 ;; leave blank line before heading
22648 (forward-char -1))))))
22649 (point))
22651 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22652 "Use Org version in org-mode, for dramatic speed-up."
22653 (if (derived-mode-p 'org-mode)
22654 (progn
22655 (org-end-of-subtree nil t)
22656 (unless (eobp) (backward-char 1)))
22657 ad-do-it))
22659 (defun org-end-of-meta-data-and-drawers ()
22660 "Jump to the first text after meta data and drawers in the current entry.
22661 This will move over empty lines, lines with planning time stamps,
22662 clocking lines, and drawers."
22663 (org-back-to-heading t)
22664 (let ((end (save-excursion (outline-next-heading) (point)))
22665 (re (concat "\\(" org-drawer-regexp "\\)"
22666 "\\|" "[ \t]*" org-keyword-time-regexp)))
22667 (forward-line 1)
22668 (while (re-search-forward re end t)
22669 (if (not (match-end 1))
22670 ;; empty or planning line
22671 (forward-line 1)
22672 ;; a drawer, find the end
22673 (re-search-forward "^[ \t]*:END:" end 'move)
22674 (forward-line 1)))
22675 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22676 (point)))
22678 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22679 "Move forward to the ARG'th subheading at same level as this one.
22680 Stop at the first and last subheadings of a superior heading.
22681 Normally this only looks at visible headings, but when INVISIBLE-OK is
22682 non-nil it will also look at invisible ones."
22683 (interactive "p")
22684 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22685 (if (and arg (< arg 0))
22686 (goto-char (point-min))
22687 (outline-next-heading))
22688 (org-at-heading-p)
22689 (let ((level (- (match-end 0) (match-beginning 0) 1))
22690 (f (if (and arg (< arg 0))
22691 're-search-backward
22692 're-search-forward))
22693 (count (if arg (abs arg) 1))
22694 (result (point)))
22695 (forward-char (if (and arg (< arg 0)) -1 1))
22696 (while (and (> count 0)
22697 (funcall f org-outline-regexp-bol nil 'move))
22698 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22699 (cond ((< l level) (setq count 0))
22700 ((and (= l level)
22701 (or invisible-ok
22702 (progn
22703 (goto-char (line-beginning-position))
22704 (not (outline-invisible-p)))))
22705 (setq count (1- count))
22706 (when (eq l level)
22707 (setq result (point)))))))
22708 (goto-char result))
22709 (beginning-of-line 1)))
22711 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22712 "Move backward to the ARG'th subheading at same level as this one.
22713 Stop at the first and last subheadings of a superior heading."
22714 (interactive "p")
22715 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22717 (defun org-next-block (arg &optional backward block-regexp)
22718 "Jump to the next block.
22719 With a prefix argument ARG, jump forward ARG many source blocks.
22720 When BACKWARD is non-nil, jump to the previous block.
22721 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22722 (interactive "p")
22723 (let ((re (or block-regexp org-block-regexp))
22724 (re-search-fn (or (and backward 're-search-backward)
22725 're-search-forward)))
22726 (if (looking-at re) (forward-char 1))
22727 (condition-case nil
22728 (funcall re-search-fn re nil nil arg)
22729 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22730 (goto-char (match-beginning 0)) (org-show-context)))
22732 (defun org-previous-block (arg &optional block-regexp)
22733 "Jump to the previous block.
22734 With a prefix argument ARG, jump backward ARG many source blocks.
22735 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22736 (interactive "p")
22737 (org-next-block arg t block-regexp))
22739 (defun org-forward-element ()
22740 "Move forward by one element.
22741 Move to the next element at the same level, when possible."
22742 (interactive)
22743 (cond ((eobp) (error "Cannot move further down"))
22744 ((org-with-limited-levels (org-at-heading-p))
22745 (let ((origin (point)))
22746 (goto-char (org-end-of-subtree nil t))
22747 (unless (org-with-limited-levels (org-at-heading-p))
22748 (goto-char origin)
22749 (error "Cannot move further down"))))
22751 (let* ((elem (org-element-at-point))
22752 (end (org-element-property :end elem))
22753 (parent (org-element-property :parent elem)))
22754 (if (and parent (= (org-element-property :contents-end parent) end))
22755 (goto-char (org-element-property :end parent))
22756 (goto-char end))))))
22758 (defun org-backward-element ()
22759 "Move backward by one element.
22760 Move to the previous element at the same level, when possible."
22761 (interactive)
22762 (cond ((bobp) (error "Cannot move further up"))
22763 ((org-with-limited-levels (org-at-heading-p))
22764 ;; At an headline, move to the previous one, if any, or stay
22765 ;; here.
22766 (let ((origin (point)))
22767 (org-with-limited-levels (org-backward-heading-same-level 1))
22768 ;; When current headline has no sibling above, move to its
22769 ;; parent.
22770 (when (= (point) origin)
22771 (or (org-with-limited-levels (org-up-heading-safe))
22772 (progn (goto-char origin)
22773 (error "Cannot move further up"))))))
22775 (let* ((trail (org-element-at-point 'keep-trail))
22776 (elem (car trail))
22777 (prev-elem (nth 1 trail))
22778 (beg (org-element-property :begin elem)))
22779 (cond
22780 ;; Move to beginning of current element if point isn't
22781 ;; there already.
22782 ((/= (point) beg) (goto-char beg))
22783 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22784 ((org-before-first-heading-p) (goto-char (point-min)))
22785 (t (org-back-to-heading)))))))
22787 (defun org-up-element ()
22788 "Move to upper element."
22789 (interactive)
22790 (if (org-with-limited-levels (org-at-heading-p))
22791 (unless (org-up-heading-safe) (error "No surrounding element"))
22792 (let* ((elem (org-element-at-point))
22793 (parent (org-element-property :parent elem)))
22794 (if parent (goto-char (org-element-property :begin parent))
22795 (if (org-with-limited-levels (org-before-first-heading-p))
22796 (error "No surrounding element")
22797 (org-with-limited-levels (org-back-to-heading)))))))
22799 (defvar org-element-greater-elements)
22800 (defun org-down-element ()
22801 "Move to inner element."
22802 (interactive)
22803 (let ((element (org-element-at-point)))
22804 (cond
22805 ((memq (org-element-type element) '(plain-list table))
22806 (goto-char (org-element-property :contents-begin element))
22807 (forward-char))
22808 ((memq (org-element-type element) org-element-greater-elements)
22809 ;; If contents are hidden, first disclose them.
22810 (when (org-element-property :hiddenp element) (org-cycle))
22811 (goto-char (or (org-element-property :contents-begin element)
22812 (error "No content for this element"))))
22813 (t (error "No inner element")))))
22815 (defun org-drag-element-backward ()
22816 "Move backward element at point."
22817 (interactive)
22818 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22819 (let* ((trail (org-element-at-point 'keep-trail))
22820 (elem (car trail))
22821 (prev-elem (nth 1 trail)))
22822 ;; Error out if no previous element or previous element is
22823 ;; a parent of the current one.
22824 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22825 (error "Cannot drag element backward")
22826 (let ((pos (point)))
22827 (org-element-swap-A-B prev-elem elem)
22828 (goto-char (+ (org-element-property :begin prev-elem)
22829 (- pos (org-element-property :begin elem)))))))))
22831 (defun org-drag-element-forward ()
22832 "Move forward element at point."
22833 (interactive)
22834 (let* ((pos (point))
22835 (elem (org-element-at-point)))
22836 (when (= (point-max) (org-element-property :end elem))
22837 (error "Cannot drag element forward"))
22838 (goto-char (org-element-property :end elem))
22839 (let ((next-elem (org-element-at-point)))
22840 (when (or (org-element-nested-p elem next-elem)
22841 (and (eq (org-element-type next-elem) 'headline)
22842 (not (eq (org-element-type elem) 'headline))))
22843 (goto-char pos)
22844 (error "Cannot drag element forward"))
22845 ;; Compute new position of point: it's shifted by NEXT-ELEM
22846 ;; body's length (without final blanks) and by the length of
22847 ;; blanks between ELEM and NEXT-ELEM.
22848 (let ((size-next (- (save-excursion
22849 (goto-char (org-element-property :end next-elem))
22850 (skip-chars-backward " \r\t\n")
22851 (forward-line)
22852 ;; Small correction if buffer doesn't end
22853 ;; with a newline character.
22854 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22855 (org-element-property :begin next-elem)))
22856 (size-blank (- (org-element-property :end elem)
22857 (save-excursion
22858 (goto-char (org-element-property :end elem))
22859 (skip-chars-backward " \r\t\n")
22860 (forward-line)
22861 (point)))))
22862 (org-element-swap-A-B elem next-elem)
22863 (goto-char (+ pos size-next size-blank))))))
22865 (defun org-mark-element ()
22866 "Put point at beginning of this element, mark at end.
22868 Interactively, if this command is repeated or (in Transient Mark
22869 mode) if the mark is active, it marks the next element after the
22870 ones already marked."
22871 (interactive)
22872 (let (deactivate-mark)
22873 (if (and (org-called-interactively-p 'any)
22874 (or (and (eq last-command this-command) (mark t))
22875 (and transient-mark-mode mark-active)))
22876 (set-mark
22877 (save-excursion
22878 (goto-char (mark))
22879 (goto-char (org-element-property :end (org-element-at-point)))))
22880 (let ((element (org-element-at-point)))
22881 (end-of-line)
22882 (push-mark (org-element-property :end element) t t)
22883 (goto-char (org-element-property :begin element))))))
22885 (defun org-narrow-to-element ()
22886 "Narrow buffer to current element."
22887 (interactive)
22888 (let ((elem (org-element-at-point)))
22889 (cond
22890 ((eq (car elem) 'headline)
22891 (narrow-to-region
22892 (org-element-property :begin elem)
22893 (org-element-property :end elem)))
22894 ((memq (car elem) org-element-greater-elements)
22895 (narrow-to-region
22896 (org-element-property :contents-begin elem)
22897 (org-element-property :contents-end elem)))
22899 (narrow-to-region
22900 (org-element-property :begin elem)
22901 (org-element-property :end elem))))))
22903 (defun org-transpose-words ()
22904 "Transpose words, using `org-mode' syntax table."
22905 (interactive)
22906 (with-syntax-table org-syntax-table
22907 (call-interactively 'transpose-words)))
22908 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22910 (defun org-transpose-element ()
22911 "Transpose current and previous elements, keeping blank lines between.
22912 Point is moved after both elements."
22913 (interactive)
22914 (org-skip-whitespace)
22915 (let ((end (org-element-property :end (org-element-at-point))))
22916 (org-drag-element-backward)
22917 (goto-char end)))
22919 (defun org-unindent-buffer ()
22920 "Un-indent the visible part of the buffer.
22921 Relative indentation (between items, inside blocks, etc.) isn't
22922 modified."
22923 (interactive)
22924 (unless (eq major-mode 'org-mode)
22925 (error "Cannot un-indent a buffer not in Org mode"))
22926 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22927 unindent-tree ; For byte-compiler.
22928 (unindent-tree
22929 (function
22930 (lambda (contents)
22931 (mapc
22932 (lambda (element)
22933 (if (memq (org-element-type element) '(headline section))
22934 (funcall unindent-tree (org-element-contents element))
22935 (save-excursion
22936 (save-restriction
22937 (narrow-to-region
22938 (org-element-property :begin element)
22939 (org-element-property :end element))
22940 (org-do-remove-indentation)))))
22941 (reverse contents))))))
22942 (funcall unindent-tree (org-element-contents parse-tree))))
22944 (defun org-show-subtree ()
22945 "Show everything after this heading at deeper levels."
22946 (interactive)
22947 (outline-flag-region
22948 (point)
22949 (save-excursion
22950 (org-end-of-subtree t t))
22951 nil))
22953 (defun org-show-entry ()
22954 "Show the body directly following this heading.
22955 Show the heading too, if it is currently invisible."
22956 (interactive)
22957 (save-excursion
22958 (condition-case nil
22959 (progn
22960 (org-back-to-heading t)
22961 (outline-flag-region
22962 (max (point-min) (1- (point)))
22963 (save-excursion
22964 (if (re-search-forward
22965 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22966 (match-beginning 1)
22967 (point-max)))
22968 nil)
22969 (org-cycle-hide-drawers 'children))
22970 (error nil))))
22972 (defun org-make-options-regexp (kwds &optional extra)
22973 "Make a regular expression for keyword lines."
22974 (concat
22975 "^#\\+\\("
22976 (mapconcat 'regexp-quote kwds "\\|")
22977 (if extra (concat "\\|" extra))
22978 "\\):[ \t]*\\(.*\\)"))
22980 ;; Make isearch reveal the necessary context
22981 (defun org-isearch-end ()
22982 "Reveal context after isearch exits."
22983 (when isearch-success ; only if search was successful
22984 (if (featurep 'xemacs)
22985 ;; Under XEmacs, the hook is run in the correct place,
22986 ;; we directly show the context.
22987 (org-show-context 'isearch)
22988 ;; In Emacs the hook runs *before* restoring the overlays.
22989 ;; So we have to use a one-time post-command-hook to do this.
22990 ;; (Emacs 22 has a special variable, see function `org-mode')
22991 (unless (and (boundp 'isearch-mode-end-hook-quit)
22992 isearch-mode-end-hook-quit)
22993 ;; Only when the isearch was not quitted.
22994 (org-add-hook 'post-command-hook 'org-isearch-post-command
22995 'append 'local)))))
22997 (defun org-isearch-post-command ()
22998 "Remove self from hook, and show context."
22999 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23000 (org-show-context 'isearch))
23003 ;;;; Integration with and fixes for other packages
23005 ;;; Imenu support
23007 (defvar org-imenu-markers nil
23008 "All markers currently used by Imenu.")
23009 (make-variable-buffer-local 'org-imenu-markers)
23011 (defun org-imenu-new-marker (&optional pos)
23012 "Return a new marker for use by Imenu, and remember the marker."
23013 (let ((m (make-marker)))
23014 (move-marker m (or pos (point)))
23015 (push m org-imenu-markers)
23018 (defun org-imenu-get-tree ()
23019 "Produce the index for Imenu."
23020 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23021 (setq org-imenu-markers nil)
23022 (let* ((n org-imenu-depth)
23023 (re (concat "^" (org-get-limited-outline-regexp)))
23024 (subs (make-vector (1+ n) nil))
23025 (last-level 0)
23026 m level head)
23027 (save-excursion
23028 (save-restriction
23029 (widen)
23030 (goto-char (point-max))
23031 (while (re-search-backward re nil t)
23032 (setq level (org-reduced-level (funcall outline-level)))
23033 (when (and (<= level n)
23034 (looking-at org-complex-heading-regexp))
23035 (setq head (org-link-display-format
23036 (org-match-string-no-properties 4))
23037 m (org-imenu-new-marker))
23038 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23039 (if (>= level last-level)
23040 (push (cons head m) (aref subs level))
23041 (push (cons head (aref subs (1+ level))) (aref subs level))
23042 (loop for i from (1+ level) to n do (aset subs i nil)))
23043 (setq last-level level)))))
23044 (aref subs 1)))
23046 (eval-after-load "imenu"
23047 '(progn
23048 (add-hook 'imenu-after-jump-hook
23049 (lambda ()
23050 (if (derived-mode-p 'org-mode)
23051 (org-show-context 'org-goto))))))
23053 (defun org-link-display-format (link)
23054 "Replace a link with either the description, or the link target
23055 if no description is present"
23056 (save-match-data
23057 (if (string-match org-bracket-link-analytic-regexp link)
23058 (replace-match (if (match-end 5)
23059 (match-string 5 link)
23060 (concat (match-string 1 link)
23061 (match-string 3 link)))
23062 nil t link)
23063 link)))
23065 (defun org-toggle-link-display ()
23066 "Toggle the literal or descriptive display of links."
23067 (interactive)
23068 (if org-descriptive-links
23069 (progn (org-remove-from-invisibility-spec '(org-link))
23070 (org-restart-font-lock)
23071 (setq org-descriptive-links nil))
23072 (progn (add-to-invisibility-spec '(org-link))
23073 (org-restart-font-lock)
23074 (setq org-descriptive-links t))))
23076 ;; Speedbar support
23078 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23079 "Overlay marking the agenda restriction line in speedbar.")
23080 (overlay-put org-speedbar-restriction-lock-overlay
23081 'face 'org-agenda-restriction-lock)
23082 (overlay-put org-speedbar-restriction-lock-overlay
23083 'help-echo "Agendas are currently limited to this item.")
23084 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23086 (defun org-speedbar-set-agenda-restriction ()
23087 "Restrict future agenda commands to the location at point in speedbar.
23088 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23089 (interactive)
23090 (require 'org-agenda)
23091 (let (p m tp np dir txt)
23092 (cond
23093 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23094 'org-imenu t))
23095 (setq m (get-text-property p 'org-imenu-marker))
23096 (with-current-buffer (marker-buffer m)
23097 (goto-char m)
23098 (org-agenda-set-restriction-lock 'subtree)))
23099 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23100 'speedbar-function 'speedbar-find-file))
23101 (setq tp (previous-single-property-change
23102 (1+ p) 'speedbar-function)
23103 np (next-single-property-change
23104 tp 'speedbar-function)
23105 dir (speedbar-line-directory)
23106 txt (buffer-substring-no-properties (or tp (point-min))
23107 (or np (point-max))))
23108 (with-current-buffer (find-file-noselect
23109 (let ((default-directory dir))
23110 (expand-file-name txt)))
23111 (unless (derived-mode-p 'org-mode)
23112 (error "Cannot restrict to non-Org-mode file"))
23113 (org-agenda-set-restriction-lock 'file)))
23114 (t (error "Don't know how to restrict Org-mode's agenda")))
23115 (move-overlay org-speedbar-restriction-lock-overlay
23116 (point-at-bol) (point-at-eol))
23117 (setq current-prefix-arg nil)
23118 (org-agenda-maybe-redo)))
23120 (eval-after-load "speedbar"
23121 '(progn
23122 (speedbar-add-supported-extension ".org")
23123 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23124 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23125 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23126 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23127 (add-hook 'speedbar-visiting-tag-hook
23128 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23130 ;;; Fixes and Hacks for problems with other packages
23132 ;; Make flyspell not check words in links, to not mess up our keymap
23133 (defvar org-element-affiliated-keywords) ; From org-element.el
23134 (defvar org-element-block-name-alist) ; From org-element.el
23135 (defun org-mode-flyspell-verify ()
23136 "Don't let flyspell put overlays at active buttons, or on
23137 {todo,all-time,additional-option-like}-keywords."
23138 (let ((pos (max (1- (point)) (point-min)))
23139 (word (thing-at-point 'word)))
23140 (and (not (get-text-property pos 'keymap))
23141 (not (get-text-property pos 'org-no-flyspell))
23142 (not (member word org-todo-keywords-1))
23143 (not (member word org-all-time-keywords))
23144 (not (member word org-options-keywords))
23145 (not (member word (mapcar 'car org-startup-options)))
23146 (not (member-ignore-case word org-element-affiliated-keywords))
23147 (not (member-ignore-case word (org-get-export-keywords)))
23148 (not (member-ignore-case
23149 word (mapcar 'car org-element-block-name-alist)))
23150 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23152 (defun org-remove-flyspell-overlays-in (beg end)
23153 "Remove flyspell overlays in region."
23154 (and (org-bound-and-true-p flyspell-mode)
23155 (fboundp 'flyspell-delete-region-overlays)
23156 (flyspell-delete-region-overlays beg end))
23157 (add-text-properties beg end '(org-no-flyspell t)))
23159 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23160 (eval-after-load "bookmark"
23161 '(if (boundp 'bookmark-after-jump-hook)
23162 ;; We can use the hook
23163 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23164 ;; Hook not available, use advice
23165 (defadvice bookmark-jump (after org-make-visible activate)
23166 "Make the position visible."
23167 (org-bookmark-jump-unhide))))
23169 ;; Make sure saveplace shows the location if it was hidden
23170 (eval-after-load "saveplace"
23171 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23172 "Make the position visible."
23173 (org-bookmark-jump-unhide)))
23175 ;; Make sure ecb shows the location if it was hidden
23176 (eval-after-load "ecb"
23177 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23178 "Make hierarchy visible when jumping into location from ECB tree buffer."
23179 (if (derived-mode-p 'org-mode)
23180 (org-show-context))))
23182 (defun org-bookmark-jump-unhide ()
23183 "Unhide the current position, to show the bookmark location."
23184 (and (derived-mode-p 'org-mode)
23185 (or (outline-invisible-p)
23186 (save-excursion (goto-char (max (point-min) (1- (point))))
23187 (outline-invisible-p)))
23188 (org-show-context 'bookmark-jump)))
23190 ;; Make session.el ignore our circular variable
23191 (eval-after-load "session"
23192 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23194 ;;;; Experimental code
23196 (defun org-closed-in-range ()
23197 "Sparse tree of items closed in a certain time range.
23198 Still experimental, may disappear in the future."
23199 (interactive)
23200 ;; Get the time interval from the user.
23201 (let* ((time1 (org-float-time
23202 (org-read-date nil 'to-time nil "Starting date: ")))
23203 (time2 (org-float-time
23204 (org-read-date nil 'to-time nil "End date:")))
23205 ;; callback function
23206 (callback (lambda ()
23207 (let ((time
23208 (org-float-time
23209 (apply 'encode-time
23210 (org-parse-time-string
23211 (match-string 1))))))
23212 ;; check if time in interval
23213 (and (>= time time1) (<= time time2))))))
23214 ;; make tree, check each match with the callback
23215 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23217 ;;;; Finish up
23219 (provide 'org)
23221 (run-hooks 'org-load-hook)
23223 ;;; org.el ends here